- Update the way to use the data records on Vuex with Getters!

- Fix: mongodb call passing array todos and categiroes already splitted
This commit is contained in:
Paolo Arena
2019-02-27 02:58:41 +01:00
parent 0e98ac1eaa
commit fa17de24f0
60 changed files with 3133 additions and 1839 deletions

View File

@@ -59,18 +59,18 @@ export default class App extends Vue {
})
if (chiamaautologin) {
console.log('CHIAMA autologin_FromLocalStorage')
// console.log('CHIAMA autologin_FromLocalStorage')
UserStore.actions.autologin_FromLocalStorage()
.then((loadstorage) => {
if (loadstorage) {
if (UserStore.state.lang !== '') {
console.log('SETLOCALE :', this.$i18n.locale)
// console.log('SETLOCALE :', this.$i18n.locale)
this.$i18n.locale = UserStore.state.lang // Set Lang
} else {
UserStore.mutations.setlang(this.$i18n.locale)
}
console.log('lang CARICATO:', this.$i18n.locale)
// console.log('lang CARICATO:', this.$i18n.locale)
globalroutines(this, 'loadapp', '')
// this.$router.replace('/')

View File

@@ -1,6 +1,6 @@
<template>
<div id="q-app">
<q-layout :style="{ backgroundColor: backgroundColor}">
<q-layout :style="">
<app-header></app-header>
<div class="layout-view">
<q-ajax-bar></q-ajax-bar>

View File

@@ -17,7 +17,11 @@ const messages = {
msg: {
hello: 'Buongiorno',
myAppName: 'FreePlanet',
myDescriz: ''
underconstruction: 'App in costruzione...',
myDescriz: '',
sottoTitoloApp: 'Il primo Vero Social',
sottoTitoloApp2: 'Libero, Equo e Solidale',
sottoTitoloApp3: 'dove Vive Consapevolezza e Aiuto Comunitario'
},
pages: {
home: 'Principale',
@@ -31,6 +35,8 @@ const messages = {
work: 'Lavoro',
shopping: 'Spesa',
Admin: 'Admin',
Test1: 'Test1',
Test2: 'Test2',
},
components: {
authentication:{
@@ -112,10 +118,11 @@ const messages = {
inserttop: 'Inserisci il Task in alto',
insertbottom: 'Inserisci il Task in basso',
edit: 'Descrizione Task:',
completed: 'Completati',
completed: 'Ultimi Completati',
usernotdefined: 'Attenzione, occorre essere Loggati per poter aggiungere un Todo'
},
notification : {
status: 'Stato',
ask: 'Attiva le Notifiche',
waitingconfirm: 'Conferma la richiesta di Notifica',
confirmed: 'Notifiche Attivate!',
@@ -146,7 +153,11 @@ const messages = {
msg: {
hello: 'Buenos Días',
myAppName: 'FreePlanet',
myDescriz: ''
underconstruction: 'App en construcción...',
myDescriz: '',
sottoTitoloApp: 'El primer Verdadero Social',
sottoTitoloApp2: 'Libre, justo y Solidario',
sottoTitoloApp3: 'Donde vive Conciencia y Ayuda comunitaria'
},
pages: {
home: 'Principal',
@@ -160,6 +171,8 @@ const messages = {
work: 'Trabajo',
shopping: 'Compras',
Admin: 'Administración',
Test1: 'Test1',
Test2: 'Test2',
},
components: {
authentication:{
@@ -241,10 +254,11 @@ const messages = {
inserttop: 'Ingrese una nueva Tarea arriba',
insertbottom: 'Ingrese una nueva Tarea abajo',
edit: 'Descripción Tarea:',
completed: 'Completados',
completed: 'Ultimos Completados',
usernotdefined: 'Atención, debes iniciar sesión para agregar una Tarea'
},
notification : {
status: 'Estado',
ask: 'Activar notificaciones',
waitingconfirm: 'Confirmar la solicitud de notificación.',
confirmed: 'Notificaciones activadas!',
@@ -275,7 +289,11 @@ const messages = {
msg: {
hello: 'Hello!',
myAppName: 'FreePlanet',
myDescriz: ''
underconstruction: 'App in constuction...',
myDescriz: '',
sottoTitoloApp: 'The first Real Social',
sottoTitoloApp2: 'Free, Fair and solidarity',
sottoTitoloApp3: 'Where the conscience and community help live'
},
pages: {
home: 'Dashboard',
@@ -289,6 +307,8 @@ const messages = {
work: 'Work',
shopping: 'Shopping',
Admin: 'Admin',
Test1: 'Test1',
Test2: 'Test2',
},
components: {
authentication:{
@@ -370,10 +390,11 @@ const messages = {
inserttop: 'Insert Task at the top',
insertbottom: 'Insert Task at the bottom',
edit: 'Task Description:',
completed: 'Completed',
completed: 'Lasts Completed',
usernotdefined: 'Attention, you need to be Signed In to add a new Task'
},
notification : {
status: 'Status',
ask: 'Enable Notification',
waitingconfirm: 'Confirm the Request Notification',
confirmed: 'Notifications Enabled!',

File diff suppressed because it is too large Load Diff

After

Width:  |  Height:  |  Size: 90 KiB

View File

Before

Width:  |  Height:  |  Size: 40 KiB

After

Width:  |  Height:  |  Size: 40 KiB

View File

@@ -15,6 +15,7 @@ let idbKeyval = (() => {
openreq.onupgradeneeded = () => {
// First time setup: create an empty object store
openreq.result.createObjectStore('todos', { keyPath: '_id' });
openreq.result.createObjectStore('categories', { keyPath: '_id' });
openreq.result.createObjectStore('sync_todos', { keyPath: '_id' });
openreq.result.createObjectStore('sync_todos_patch', { keyPath: '_id' });
openreq.result.createObjectStore('delete_todos', { keyPath: '_id' });

View File

@@ -121,7 +121,7 @@
import messagePopover from '../layouts/toolbar/messagePopover/messagePopover.vue'
import { GlobalStore, UserStore } from '@modules'
import { rescodes } from '../store/Modules/rescodes'
import { tools } from '../store/Modules/tools'
import QIcon from "quasar-framework/src/components/icon/QIcon"
import { StateConnection } from "../model"
import { Watch } from "vue-property-decorator"
@@ -213,7 +213,6 @@
})
}
// console.log('Todos.state.todos_changed CHANGED!', value, oldValue)
this.changeIconConn()
}
}
@@ -238,10 +237,10 @@
}
public selectOpLang = [
{ label: 'English', icon: 'fa-flag-us', value: 'enUs', image: '../statics/images/gb.png', short: 'EN' },
{ label: 'German', icon: 'fa-flag-de', value: 'de', image: '../statics/images/de.png', short: 'DE' },
{ label: 'Italian', icon: 'fa-facebook', value: 'it', image: '../statics/images/it.png', short: 'IT' },
{ label: 'Spanish', icon: 'fa-flag-es', value: 'esEs', image: '../statics/images/es.png', short: 'ES' }
{ label: 'English', icon: 'fa-flag-us', value: 'enUs', image: '../assets/images/gb.png', short: 'EN' },
// { label: 'German', icon: 'fa-flag-de', value: 'de', image: '../assets/images/de.png', short: 'DE' },
{ label: 'Italiano', icon: 'fa-facebook', value: 'it', image: '../assets/images/it.png', short: 'IT' },
{ label: 'Español', icon: 'fa-flag-es', value: 'esEs', image: '../assets/images/es.png', short: 'ES' }
]
@@ -279,7 +278,7 @@
set leftDrawerOpen(value) {
GlobalStore.state.leftDrawerOpen = value
localStorage.setItem(rescodes.localStorage.leftDrawerOpen, value.toString())
localStorage.setItem(tools.localStorage.leftDrawerOpen, value.toString())
}
getAppVersion() {
@@ -330,7 +329,7 @@
// dynamic import, so loading on demand only
import(`quasar-framework/i18n/${mylangtopass}`).then(lang => {
this.$q.i18n.set(lang.default)
import(`src/statics/i18n`).then(function () {
import(`src/assets/i18n`).then(function () {
})
})
}
@@ -350,7 +349,7 @@
let my = this.getLangAtt()
// this.$q.notify('prima: ' + String(my))
let mylang = rescodes.getItemLS(rescodes.localStorage.lang)
let mylang = tools.getItemLS(tools.localStorage.lang)
if (mylang === '') {
if (navigator) {
mylang = navigator.language

View File

@@ -0,0 +1 @@
export {default as testp1} from './testp1.vue'

View File

View File

@@ -0,0 +1,95 @@
import Vue from 'vue'
import { Component, Watch } from 'vue-property-decorator'
import { GlobalStore, UserStore } from '@store'
import { Getter } from "vuex-class"
import { ICfgServer, IGlobalState, ITodo, ITodosState } from '@src/model'
const namespace: string = 'GlobalModule'
@Component({})
export default class Testp1 extends Vue {
public myvar:number = 5
public paramcategory: string = ''
public mioobj: any
// @Getter('todos_dacompletare', { namespace })
// public todos_dacompletare: (state: ITodosState, category: string) => ITodo[]
@Getter('testpao1_getter_contatore', { namespace })
public testpao1: (state: IGlobalState, param1: number) => number
@Getter('testpao1_getter_array', { namespace })
public testpao1_array: (state: IGlobalState, miorec: ICfgServer) => ICfgServer[]
@Watch('GlobalStore.state.testp1.mioarray', { immediate: true, deep: true })
array_changed() {
console.log('*** array_changed *** ', GlobalStore.state.testp1.mioarray[GlobalStore.state.testp1.mioarray.length - 1])
}
@Watch('$route.params.category') changecat() {
// this.mytypetransgroup = ''
console.log('PRIMA this.paramcategory', this.paramcategory)
this.paramcategory = this.$route.params.category
console.log('DOPO this.paramcategory', this.paramcategory)
}
created() {
this.mioobj = {
arr1: [{chiave: 'key1', valore: 'val1'}],
arr2: [{chiave: 'key2', valore: 'val2'}]
}
}
get getarr1 () {
// return this.mioobj.arr1
return this.mioobj['arr1']
}
get prova2() {
return GlobalStore.state.testp1.contatore
}
get provagetter() {
return GlobalStore.getters.testpao1_getter_contatore(130)
}
get provagetterarray() {
return GlobalStore.getters.testpao1_getter_array(GlobalStore.state.testp1.contatore)
}
TestBtnCambioaParamPassing () {
this.paramcategory += 's'
}
TestBtn() {
GlobalStore.state.testp1.contatore++
}
TestBtn2() {
GlobalStore.state.testp1.mioarray.push({chiave: 'pippo2', valore: GlobalStore.state.testp1.contatore.toString() })
}
TestBtnModify() {
// GlobalStore.state.testp1.mioarray[GlobalStore.state.testp1.mioarray.length - 1] = GlobalStore.state.testp1.mioarray[GlobalStore.state.testp1.mioarray.length - 1] + 1
GlobalStore.mutations.setPaoArray({chiave: 'pippo', valore: '20' } )
}
TestBtnCambiaTutto() {
// GlobalStore.state.testp1.mioarray[GlobalStore.state.testp1.mioarray.length - 1] = GlobalStore.state.testp1.mioarray[GlobalStore.state.testp1.mioarray.length - 1] + 1
GlobalStore.mutations.NewArray([{chiave: 'nuovorec1', valore: '1' }, {chiave: 'nuovorec2', valore: '2' }] )
}
TestBtnAction() {
GlobalStore.actions.prova()
}
TestBtnDelete() {
// GlobalStore.state.testp1.mioarray[GlobalStore.state.testp1.mioarray.length - 1] = GlobalStore.state.testp1.mioarray[GlobalStore.state.testp1.mioarray.length - 1] + 1
GlobalStore.mutations.setPaoArray_Delete()
}
}

View File

@@ -0,0 +1,43 @@
<template>
<div>
CATEGORY: <strong>{{ paramcategory }}</strong> <br>
<label>TEST Prova Paolo</label><br>
GETTER CONTATORE:
{{ testpao1(300) }} <br>
ARRAY:
{{ testpao1_array(300) }} <br>
TEST OBJECT {{ mioobj }} <br>
ARR1 {{ getarr1 }} <br>
<!--ARR2 {{ mioobj.arr2 }} <br>-->
<!--<q-input v-model="testpao1(myvar)"></q-input>-->
<q-input v-model="prova2" float-label="PROVA2:"></q-input>
<q-input v-model="provagetter" float-label="PROVA GETTER:"></q-input>
<q-input v-model="provagetterarray" float-label="GETTER ARRAY:"></q-input>
<br>
<q-btn color="secondary" rounded icon="refresh"
@click="TestBtn" label="Test 1"/>
<q-btn color="secondary" rounded icon="refresh" @click="TestBtn2" label="ADD TO ARRAY"/>
<q-btn color="secondary" rounded icon="refresh" @click="TestBtnModify" label="MODIFY"/>
<q-btn color="secondary" rounded icon="refresh" @click="TestBtnAction" label="MODIF_BYACTION"/>
<q-btn color="secondary" rounded icon="refresh" @click="TestBtnDelete" label="DEL LAST"/>
<!--<q-btn color="secondary" rounded icon="refresh" @click="TestBtnCambiaTutto" label="NEW ARR"/>-->
<q-btn color="secondary" rounded icon="refresh" @click="TestBtnCambioaParamPassing" label="CAMBIA PARAM"/>
</div>
</template>
<script lang="ts" src="./testp1.ts">
</script>
<style lang="scss" scoped>
@import './testp1.scss';
</style>

View File

@@ -1,9 +1,11 @@
.svgclass{
.svgclass {
color: white;
transform: translateY(0px);
}
.svgclass_animate {
transform: translateY(-70px);
color: red;
@@ -14,16 +16,24 @@
}
@keyframes gravity{
0%{
#logoimg {
height: 150px;
width: auto;
@media screen and (max-width: 600px) {
}
}
@keyframes gravity {
0% {
transform: rotateY(0deg);
}
100%{
100% {
transform: rotateY(360deg);
}
}
#smile{
#smile {
opacity: 0.1 !important;
fill: red;
}

View File

@@ -13,7 +13,7 @@ export default class Logo extends Vue {
logoimg: string = ''
created() {
this.logoimg = 'statics/images/' + process.env.LOGO_REG
this.logoimg = 'assets/images/' + process.env.LOGO_REG
this.animate()
}

View File

@@ -13,7 +13,7 @@ export default class Offline extends Vue {
logoimg: string = ''
created() {
this.logoimg = 'statics/images/' + process.env.LOGO_REG
this.logoimg = '/assets/images/' + process.env.LOGO_REG
this.animate()
}

View File

@@ -1,7 +1,7 @@
import Vue from 'vue'
import { Component, Prop, Watch } from 'vue-property-decorator'
import { rescodes } from '../../../store/Modules/rescodes'
import { tools } from '../../../store/Modules/tools'
import { UserStore } from '@modules'
import { ITodo } from '../../../model/index'
@@ -48,21 +48,21 @@ export default class SingleTodo extends Vue {
@Prop({ required: true }) itemtodo: ITodo
@Watch('itemtodo.completed') valueChanged() {
this.watchupdate()
}
// @Watch('itemtodo.completed') valueChanged() {
// this.watchupdate('completed')
// }
@Watch('itemtodo.enableExpiring') valueChanged4() {
this.watchupdate()
this.watchupdate('enableExpiring')
}
@Watch('itemtodo.expiring_at') valueChanged2() {
this.watchupdate()
this.watchupdate('expiring_at')
}
@Watch('itemtodo.priority') valueChanged3() {
this.watchupdate()
}
// @Watch('itemtodo.priority') valueChanged3() {
// this.watchupdate('priority')
// }
@Watch('itemtodo.descr') valueChanged5() {
@@ -91,8 +91,8 @@ export default class SingleTodo extends Vue {
return elem.descr.slice(-1) !== ':'
}
watchupdate() {
this.$emit('eventupdate', this.itemtodo)
watchupdate(field = '') {
this.$emit('eventupdate', {myitem: this.itemtodo, field } )
this.updateicon()
}
@@ -158,10 +158,10 @@ export default class SingleTodo extends Vue {
// console.log('UserStore.state.lang', UserStore.state.lang)
if (this.isTodo())
this.menuPopupTodo = rescodes.menuPopupTodo[UserStore.state.lang]
this.menuPopupTodo = tools.menuPopupTodo[UserStore.state.lang]
else {
this.menuPopupTodo = []
this.menuPopupTodo.push(rescodes.menuPopupTodo[UserStore.state.lang][rescodes.INDEX_MENU_DELETE])
this.menuPopupTodo.push(tools.menuPopupTodo[UserStore.state.lang][tools.INDEX_MENU_DELETE])
}
}
@@ -172,7 +172,7 @@ export default class SingleTodo extends Vue {
this.updateClasses()
this.selectPriority = rescodes.selectPriority[UserStore.state.lang]
this.selectPriority = tools.selectPriority[UserStore.state.lang]
}
@@ -283,7 +283,7 @@ export default class SingleTodo extends Vue {
if (((e.keyCode === 8) || (e.keyCode === 46)) && (this.precDescr === '') && !e.shiftKey) {
e.preventDefault()
this.deselectRiga()
this.clickMenu(rescodes.MenuAction.DELETE)
this.clickMenu(tools.MenuAction.DELETE)
.then(() => {
this.faiFocus('insertTask', true)
return
@@ -311,7 +311,7 @@ export default class SingleTodo extends Vue {
if (((e.keyCode === 8) || (e.keyCode === 46)) && (this.precDescr === '') && !e.shiftKey) {
e.preventDefault()
this.deselectRiga()
this.clickMenu(rescodes.MenuAction.DELETE)
this.clickMenu(tools.MenuAction.DELETE)
.then(() => {
this.faiFocus('insertTask', true)
return
@@ -349,7 +349,7 @@ export default class SingleTodo extends Vue {
console.log('itemtodo', this.itemtodo)
console.log('Prec:', this.itemtodoPrec)
this.watchupdate()
this.watchupdate('descr')
this.inEdit = false
// this.precDescr = this.itemtodo.descr
this.updateClasses()
@@ -361,15 +361,15 @@ export default class SingleTodo extends Vue {
this.updateicon()
this.updatedata()
this.updatedata('completed')
this.deselectAndExitEdit()
}
updatedata() {
const myitem = rescodes.jsonCopy(this.itemtodo)
console.log('calling this.$emit(eventupdate)', myitem)
this.$emit('eventupdate', myitem)
updatedata(field: string) {
// const myitem = tools.jsonCopy(this.itemtodo)
console.log('calling this.$emit(eventupdate)', this.itemtodo)
this.$emit('eventupdate', { myitem: this.itemtodo, field } )
}
updateicon() {
@@ -380,11 +380,11 @@ export default class SingleTodo extends Vue {
this.iconCompleted = 'check_circle_outline'
if (this.itemtodo.priority === rescodes.Todos.PRIORITY_HIGH)
if (this.itemtodo.priority === tools.Todos.PRIORITY_HIGH)
this.iconPriority = 'expand_less' // expand_less
else if (this.itemtodo.priority === rescodes.Todos.PRIORITY_NORMAL)
else if (this.itemtodo.priority === tools.Todos.PRIORITY_NORMAL)
this.iconPriority = 'remove'
else if (this.itemtodo.priority === rescodes.Todos.PRIORITY_LOW)
else if (this.itemtodo.priority === tools.Todos.PRIORITY_LOW)
this.iconPriority = 'expand_more' // expand_more
this.updateClasses()
@@ -392,7 +392,7 @@ export default class SingleTodo extends Vue {
removeitem(id) {
this.$emit('deleteitem', id)
this.$emit('deleteItem', id)
}
enableExpiring() {
@@ -402,14 +402,14 @@ export default class SingleTodo extends Vue {
async clickMenu(action) {
console.log('click menu: ', action)
if (action === rescodes.MenuAction.DELETE) {
if (action === tools.MenuAction.DELETE) {
return await this.askConfirmDelete()
} else if (action === rescodes.MenuAction.TOGGLE_EXPIRING) {
} else if (action === tools.MenuAction.TOGGLE_EXPIRING) {
return await this.enableExpiring()
} else if (action === rescodes.MenuAction.COMPLETED) {
} else if (action === tools.MenuAction.COMPLETED) {
return await this.setCompleted()
} else if (action === rescodes.MenuAction.PROGRESS_BAR) {
return await this.updatedata()
} else if (action === tools.MenuAction.PROGRESS_BAR) {
return await this.updatedata('progress')
} else if (action === 0) {
this.deselectAndExitEdit()
}
@@ -418,11 +418,13 @@ export default class SingleTodo extends Vue {
setPriority(newpriority) {
this.itemtodo.priority = newpriority
if (this.itemtodo.priority !== newpriority) {
this.itemtodo.priority = newpriority
this.updatedata()
this.updatedata('priority')
this.updateicon()
this.updateicon()
}
// this.$q.notify('setPriority: ' + elem)
}

View File

@@ -83,9 +83,6 @@
<!--<div class="flex-item btn-item">-->
<!--<q-btn class="mybtn" round color="" icon="delete" @click.native="removeitem(itemtodo._id)"></q-btn>-->
<!--</div>-->
<!--<div class="flex-item">-->
<!--[{{ itemtodo.id_prev}} - {{ itemtodo.id_next}}]-->
<!--</div>-->
</div>
</template>

View File

@@ -2,7 +2,7 @@ import Vue from 'vue'
import { Component, Prop } from 'vue-property-decorator'
import { ITodo } from '../../../model/index'
import { rescodes } from '@src/store/Modules/rescodes'
import { tools } from '@src/store/Modules/tools'
import { UserStore } from '@store'
// Doesn't exist in quasar this ? error TS2305
@@ -16,7 +16,7 @@ import { UserStore } from '@store'
})
export default class SubMenus extends Vue {
public selectPriority: [] = rescodes.selectPriority[UserStore.state.lang]
public selectPriority: [] = tools.selectPriority[UserStore.state.lang]
@Prop({ required: false }) menuPopupTodo: any[]
@Prop({ required: false }) itemtodo: ITodo
@@ -47,7 +47,7 @@ export default class SubMenus extends Vue {
}
create () {
this.selectPriority = rescodes.selectPriority[UserStore.state.lang]
this.selectPriority = tools.selectPriority[UserStore.state.lang]
console.log('CREAZIONE')
}

File diff suppressed because it is too large Load Diff

View File

@@ -4,7 +4,7 @@
<p class="caption"></p>
<div class="divtitlecat">
<div class="categorytitle">{{ getCategory() }}</div>
<div class="categorytitle">{{ categoryAtt }}</div>
</div>
<q-input ref="insertTask" v-model="todotop" inverted :float-label="$t('todo.inserttop')"
@@ -19,21 +19,17 @@
<!--<div :id="getmyid(mytodo._id)" v-for="(mytodo, index) in todos_arr" :key="mytodo._id" class="myitemdrag"-->
<!--draggable="true" @dragstart="dragStart(index, $event)" @dragover.prevent @dragenter="dragEnter(index)"-->
<!--@dragleave="dragLeave(index)" @dragend="dragEnd" @drop="dragFinish(index, $event)" >-->
<q-infinite-scroll :handler="loadMoreTodo" :offset="7">
<div class="container" v-dragula="todos_arr" drake="first" :key="compKey3">
<div :id="getmyid(mytodo._id)" :index="index" v-for="(mytodo, index) in showingDataTodo"
<!--<q-infinite-scroll :handler="loadMoreTodo" :offset="7">-->
<div class="container" v-dragula="todos_dacompletare(categoryAtt)" drake="first">
<div :id="getmyid(mytodo._id)" :index="index" v-for="(mytodo, index) in todos_dacompletare(categoryAtt)"
:key="mytodo._id" class="myitemdrag">
<div v-if="(prior !== mytodo.priority) && !mytodo.completed"
:class="getTitlePriority(mytodo.priority)" :key="compKey1">
:class="getTitlePriority(mytodo.priority)">
<label>{{getPriorityByInd(mytodo.priority)}}</label>
</div>
<div v-if="(!priorcomplet && mytodo.completed)" class="titleCompleted" :key="compKey2">
<label>{{$t('todo.completed')}}</label>
<div style="display: none">{{ priorcomplet = true }}</div>
</div>
<SingleTodo ref="single" @deleteitem="deleteitem" @eventupdate="updateitem"
<SingleTodo ref="single" @deleteItem="mydeleteItem" @eventupdate="updateitem"
@deselectAllRows="deselectAllRows" @onEnd="onEnd"
:itemtodo='mytodo'/>
@@ -43,19 +39,40 @@
</div>
</div>
</div>
</q-infinite-scroll>
<!--</q-infinite-scroll>-->
<div v-if="doneTodosCount > 0" class="titleCompleted">
<label>{{$t('todo.completed')}}</label>
</div>
<!--<q-infinite-scroll :handler="loadMoreTodo" :offset="7">-->
<div class="container" v-dragula="todos_completati(categoryAtt)" drake="second">
<div :id="getmyid(mytodo._id)" :index="index" v-for="(mytodo, index) in todos_completati(categoryAtt)"
:key="mytodo._id" class="myitemdrag">
<SingleTodo ref="single" @deleteItem="deleteItem(mytodo._id)" @eventupdate="updateitem"
@deselectAllRows="deselectAllRows" @onEnd="onEnd"
:itemtodo='mytodo'/>
<!--<div :name="`REF${index}`" class="divdrag non-draggato"></div>-->
<div style="display: none">{{ prior = mytodo.priority, priorcomplet = mytodo.completed }}
</div>
</div>
</div>
<!--</q-infinite-scroll>-->
<!--</transition-group>-->
<!--</draggable>-->
</div>
<q-input v-if="todos_arr.length > 0" ref="insertTaskBottom" v-model="todobottom" inverted :float-label="$t('todo.insertbottom')"
<q-input v-if="TodosCount > 0" ref="insertTaskBottom" v-model="todobottom" inverted :float-label="$t('todo.insertbottom')"
:after="[{icon: 'arrow_forward', content: true, handler () {}}]"
v-on:keyup.enter="insertTodo(false)"/>
<!--{{ tmpstrTodos }}-->
<!--<br>-->
<br>
<!--&lt;!&ndash;-->
<!--&lt;!&ndash;<div class="flex-item btn-item">&ndash;&gt;-->
<!--<q-btn class="mybtn" round color="" icon="lock" @click="getArrTodos">Get Todo</q-btn>-->
<!--<q-btn class="mybtn" round color="" icon="person" @click="setArrTodos">Set Todo</q-btn>-->
@@ -72,7 +89,10 @@
<!--<q-btn class="mybtn" round color="" icon="person" @click="clicktest2()"></q-btn>-->
<!--<q-btn class="mybtn" round color="" icon="list" @click="checkUpdate()"></q-btn>-->
<!--</div>-->
<!--&ndash;&gt;-->
<!--<span style="white-space: pre;">{{ todos_vista }}</span>-->
</div>
</q-page>

View File

@@ -3,7 +3,7 @@ import _ from 'lodash'
import { UserStore, Todos } from '@store'
import { i18n } from '../plugins/i18n'
import {idbKeyval as storage} from '../js/storage.js';
import { idbKeyval as storage } from '../js/storage.js';
function saveConfigIndexDb(context) {
@@ -27,20 +27,43 @@ function writeConfigIndexDb(context, data) {
}
async function readfromIndexDbToStateTodos(context, table) {
// console.log('*** read from IndexDb to state.todos')
console.log('*** readfromIndexDbToStateTodos ***')
return await storage.getalldata(table)
.then(records => {
.then(reccat => {
// console.log('&&&&&&& readfromIndexDbToStateTodos OK: Num RECORD: ', records.length)
if (table === 'todos') {
Todos.state.todos = [...records]
Todos.mutations.setTodos_changed()
// console.log('Todos.state.todos_changed:', Todos.state.todos_changed)
// setTimeout(testfunc2, 3000)
if (table === 'categories') {
console.log('reccat', reccat)
Todos.state.categories = []
for (let indcat in reccat) {
Todos.state.categories.push(reccat[indcat].valore)
}
console.log('ARRAY Categories', Todos.state.categories)
return storage.getalldata('todos')
.then(records => {
console.log('todos records', records)
// console.log('&&&&&&& readfromIndexDbToStateTodos OK: Num RECORD: ', records.length)
for (let myrec in records) {
const cat = myrec.category
let indcat = state.categories.indexOf(cat)
if (Todos.state.todos[indcat] === undefined)
Todos.state.todos[indcat] = {}
// add to the right array
Todos.state.todos[indcat].push(myrec)
}
console.log('************ ARRAYS SALVATI IN MEMORIA Todos.state.todos ', Todos.state.todos)
})
}
}).catch((error) => {
console.log('err: ', error)
})
console.log('err: ', error)
})
}
@@ -49,11 +72,9 @@ function consolelogpao(str, str2 = '', str3 = '') {
// Todos.mutations.setTestpao(str + str2 + str3)
}
function testfunc2 () {
function testfunc2() {
consolelogpao('testfunc2')
Todos.mutations.setTodos_changed()
consolelogpao('testfunc2: Todos.state.todos_changed:', Todos.state.todos_changed)
}
export default async (context, cmd, table, datakey = null, id = '') => {

View File

@@ -1,5 +1,5 @@
import { UserStore } from "../store/Modules";
import messages from "../statics/i18n";
import messages from "../assets/i18n";
function translate(params) {
let msg = params.split('.')

View File

@@ -10,21 +10,20 @@
<meta name="viewport"
content="user-scalable=no, initial-scale=1, minimum-scale=1, width=device-width<% if (htmlWebpackPlugin.options.ctx.mode.cordova) { %>, viewport-fit=cover<% } %>">
<link rel="icon" href="/statics/icons/favicon.ico" type="image/x-icon">
<link rel="icon" type="image/png" sizes="32x32" href="/statics/icons/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/statics/icons/favicon-16x16.png">
<link rel="stylesheet" type="text/css" href="/statics/css/dragula.css">
<script defer src="/statics/js/material.min.js"></script>
<script src="/statics/js/promise.js"></script>
<script src="/statics/js/fetch.js"></script>
<script src="/statics/js/idb.js"></script>
<script src="/statics/js/storage.js"></script>
<!--<link type="text/css" rel="stylesheet" href="statics/firebaseui.css" />-->
<link rel="icon" href="<%= htmlWebpackPlugin.files.publicPath %>statics/icons/favicon.ico" type="image/x-icon">
<link rel="icon" type="image/png" sizes="32x32" href="<%= htmlWebpackPlugin.files.publicPath %>statics/icons/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="<%= htmlWebpackPlugin.files.publicPath %>statics/icons/favicon-16x16.png">
<link rel="stylesheet" type="text/css" href="<%= htmlWebpackPlugin.files.publicPath %>assets/css/dragula.css">
<script defer src="<%= htmlWebpackPlugin.files.publicPath %>assets/js/material.min.js"></script>
<script src="<%= htmlWebpackPlugin.files.publicPath %>assets/js/promise.js"></script>
<script src="<%= htmlWebpackPlugin.files.publicPath %>assets/js/fetch.js"></script>
<script src="<%= htmlWebpackPlugin.files.publicPath %>assets/js/idb.js"></script>
<script src="<%= htmlWebpackPlugin.files.publicPath %>assets/js/storage.js"></script>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body>
<!-- DO NOT touch the following DIV -->
<div id="q-app"></div>
</body>
</html>

View File

@@ -15,6 +15,7 @@ export let idbKeyval = (() => {
openreq.onupgradeneeded = () => {
// First time setup: create an empty object store
openreq.result.createObjectStore('todos', { keyPath: '_id' });
openreq.result.createObjectStore('categories', { keyPath: '_id' });
openreq.result.createObjectStore('sync_todos', { keyPath: '_id' });
openreq.result.createObjectStore('sync_todos_patch', { keyPath: '_id' });
openreq.result.createObjectStore('delete_todos', { keyPath: '_id' });
@@ -56,7 +57,7 @@ export let idbKeyval = (() => {
let req;
await withStore('readonly', table, store => {
console.log('getdata', table, key)
// console.log('getdata', table, key)
req = store.get(key);
});

View File

@@ -0,0 +1,50 @@
.background-red {
background-color: red;
padding: 2px;
}
.fixed-bottom {
margin-bottom: 1%;
}
.fixed-bottom a img {
width: 25px;
height: 25px;
}
#avatar {
padding: 20px;
}
#profile {
height: 130px;
background-color: #009688;
}
#user-name {
left: 90px;
bottom: 77px;
position: relative;
width: 159px;
}
#user-actions {
left: 90px;
bottom: 71px;
position: relative;
width: 171px;
}
#menu-collapse {
margin-top: 5%;
}
.fixed-left:hover {
cursor: ew-resize;
}
footer {
small {
color: red;
}
}

View File

@@ -0,0 +1,119 @@
import menuOne from './menuOne.vue'
import Vue from 'vue'
import { Component, Watch, Prop } from 'vue-property-decorator'
import { Store } from 'vuex'
import { UserStore } from '@modules'
import { GlobalStore } from '@modules'
import { ITodoList } from '../../model'
@Component({
components: {
menuOne
}
})
export default class Drawer extends Vue {
public $q
$t: any
public arrlista = GlobalStore.state.listatodo
photo = ''
user = null
links
created() {
let listatodo = []
this.arrlista.forEach((elem: ITodoList) => {
let item = {
route: '/todo/' + elem.namecat,
faIcon: 'fa fa-list-alt',
materialIcon: 'todo',
name: 'pages.' + elem.description
}
listatodo.push(item)
})
if (UserStore.state.isAdmin) {
this.links = {
Dashboard: {
routes: [
{ route: '/', faIcon: 'fa fa-home', materialIcon: 'home', name: 'pages.home' },
{
route: '/todo', faIcon: 'fa fa-list-alt', materialIcon: 'todo', name: 'pages.Todo',
routes2: listatodo
},
{ route: '/category', faIcon: 'fa fa-list-alt', materialIcon: 'category', name: 'pages.Category' },
{ route: '/signup', faIcon: 'fa fa-registered', materialIcon: 'home', name: 'pages.SignUp' },
{ route: '/admin/cfgserv', faIcon: 'fa fa-database', materialIcon: 'admin', name: 'pages.Admin' },
{ route: '/admin/testp1/par1', faIcon: 'fa fa-database', materialIcon: 'admin', name: 'pages.Test1' },
{ route: '/admin/testp1/par2', faIcon: 'fa fa-database', materialIcon: 'admin', name: 'pages.Test2' },
{ route: '/signin', faIcon: 'fa fa-anchor', materialIcon: 'home', name: 'pages.SignIn' },
/* {route: '/vreg?idlink=aaa', faIcon: 'fa fa-login', materialIcon: 'login', name: 'pages.vreg'},*/
],
show: true,
}
}
} else {
// PRODUCTION USER:
if (process.env.PROD) {
this.links = {
Dashboard: {
routes: [
{ route: '/', faIcon: 'fa fa-home', materialIcon: 'home', name: 'pages.home' },
],
show: true,
}
}
} else {
// SERVER TEST
this.links = {
Dashboard: {
routes: [
{ route: '/', faIcon: 'fa fa-home', materialIcon: 'home', name: 'pages.home' },
{
route: '/todo', faIcon: 'fa fa-list-alt', materialIcon: 'todo', name: 'pages.Todo',
routes2: listatodo
},
{ route: '/category', faIcon: 'fa fa-list-alt', materialIcon: 'category', name: 'pages.Category' },
{ route: '/signup', faIcon: 'fa fa-registered', materialIcon: 'home', name: 'pages.SignUp' },
{ route: '/signin', faIcon: 'fa fa-anchor', materialIcon: 'home', name: 'pages.SignIn' },
/* {route: '/vreg?idlink=aaa', faIcon: 'fa fa-login', materialIcon: 'login', name: 'pages.vreg'},*/
],
show: true,
}
}
}
}
}
get MenuCollapse() {
return GlobalStore.state.menuCollapse
// return true
}
get Username() {
return UserStore.state.username
}
get Verificato() {
return UserStore.state.verified_email
}
get Email() {
return UserStore.state.email
}
logoutHandler() {
UserStore.actions.logout()
this.$router.push('/signin')
this.$q.notify(this.$t('logout.uscito'))
}
}

View File

@@ -31,153 +31,8 @@
</div>
</template>
<script lang="ts">
import menuOne from './menuOne.vue'
import Vue from 'vue'
import { Component, Watch, Prop } from 'vue-property-decorator'
import { Store } from 'vuex'
import { UserStore } from '@modules'
import { GlobalStore } from '@modules'
import { ITodoList } from "../../model";
@Component({
components: {
menuOne,
}
})
export default class Drawer extends Vue {
public $q
$t: any
public arrlista = GlobalStore.state.listatodo
photo = ''
user = null
links
created() {
let listatodo = []
this.arrlista.forEach((elem: ITodoList) => {
let item = { route: '/todo/' + elem.namecat, faIcon: 'fa fa-list-alt', materialIcon: 'todo', name: 'pages.' + elem.description }
listatodo.push(item)
})
if (UserStore.state.isAdmin) {
this.links = {
Dashboard: {
routes: [
{ route: '/', faIcon: 'fa fa-home', materialIcon: 'home', name: 'pages.home' },
{
route: '/todo', faIcon: 'fa fa-list-alt', materialIcon: 'todo', name: 'pages.Todo',
routes2: listatodo
},
{ route: '/category', faIcon: 'fa fa-list-alt', materialIcon: 'category', name: 'pages.Category' },
{ route: '/signup', faIcon: 'fa fa-registered', materialIcon: 'home', name: 'pages.SignUp' },
{ route: '/admin/cfgserv', faIcon: 'fa fa-database', materialIcon: 'admin', name: 'pages.Admin' },
{ route: '/signin', faIcon: 'fa fa-anchor', materialIcon: 'home', name: 'pages.SignIn' },
/* {route: '/vreg?idlink=aaa', faIcon: 'fa fa-login', materialIcon: 'login', name: 'pages.vreg'},*/
],
show: true,
}
}
} else {
// Normal USER:
this.links = {
Dashboard: {
routes: [
{ route: '/', faIcon: 'fa fa-home', materialIcon: 'home', name: 'pages.home' },
{
route: '/todo', faIcon: 'fa fa-list-alt', materialIcon: 'todo', name: 'pages.Todo',
routes2: listatodo
},
{ route: '/signup', faIcon: 'fa fa-registered', materialIcon: 'home', name: 'pages.SignUp' },
{ route: '/signin', faIcon: 'fa fa-anchor', materialIcon: 'home', name: 'pages.SignIn' },
],
show: true,
}
}
}
}
get MenuCollapse() {
return GlobalStore.state.menuCollapse
// return true
}
get Username() {
return UserStore.state.username
}
get Verificato() {
return UserStore.state.verified_email
}
get Email() {
return UserStore.state.email
}
logoutHandler() {
UserStore.actions.logout()
this.$router.push('/signin')
this.$q.notify(this.$t('logout.uscito'))
}
}
<script lang="ts" src="./drawer.ts">
</script>
<style scoped lang="scss">
.background-red {
background-color: red;
padding: 2px;
}
.fixed-bottom {
margin-bottom: 1%;
}
.fixed-bottom a img {
width: 25px;
height: 25px;
}
#avatar {
padding: 20px;
}
#profile {
height: 130px;
background-color: #009688;
}
#user-name {
left: 90px;
bottom: 77px;
position: relative;
width: 159px;
}
#user-actions {
left: 90px;
bottom: 71px;
position: relative;
width: 171px;
}
#menu-collapse {
margin-top: 5%;
}
.fixed-left:hover {
cursor: ew-resize;
}
footer {
small {
color: red;
}
}
<style lang="scss" scoped>
@import './drawer.scss';
</style>

View File

@@ -14,6 +14,11 @@ export interface ICfgServer {
valore: string
}
export interface ITestp1 {
contatore: number
mioarray: ICfgServer[]
}
export type StateConnection = 'online' | 'offline'
export interface IGlobalState {
@@ -29,6 +34,7 @@ export interface IGlobalState {
stateConnection: string
networkDataReceived: boolean
cfgServer: ICfgServer[]
testp1: ITestp1
connData: IConnData
posts: IPost[]
listatodo: ITodoList[]

View File

@@ -1,28 +1,48 @@
export interface ITodo {
_id?: any,
userId: string
userId?: string
category?: string
descr?: string,
priority: number,
completed: boolean,
created_at: Date,
modify_at: Date,
completed_at: Date,
expiring_at: Date,
priority?: number,
completed?: boolean,
created_at?: Date,
modify_at?: Date,
completed_at?: Date,
expiring_at?: Date,
enableExpiring?: boolean,
id_prev?: string,
id_next?: string,
modified?: boolean,
pos?: number,
order?: number,
progress?: number
}
export interface IParamTodo {
categorySel?: string
checkPending?: boolean
id?: string
objtodo?: ITodo
atfirst?: boolean
}
export interface IDrag {
field?: string
idelemtochange?: string
prioritychosen?: number
oldIndex?: number
newIndex?: number
category: string
atfirst?: boolean
}
export interface ITodosState {
visuOnlyUncompleted: boolean
todos: ITodo[]
todos_changed: number
todos: [ ITodo[] ]
categories: string[]
// todos_changed: number
reload_fromServer: number
testpao: String
insidePending: boolean
visuLastCompleted: number
}

View File

@@ -1,13 +1,13 @@
// src/plugins/i18n.js
import VueI18n from 'vue-i18n';
import messages from 'src/statics/i18n';
import { rescodes } from "../store/Modules/rescodes";
import messages from 'src/assets/i18n';
import { tools } from "../store/Modules/tools";
export default ({ app, store, Vue }) => {
Vue.use(VueI18n);
// Vue.config.lang = process.env.LANG_DEFAULT;
let mylang = rescodes.getItemLS(rescodes.localStorage.lang)
let mylang = tools.getItemLS(tools.localStorage.lang)
if ((navigator) && (mylang === '')) {
mylang = navigator.language

View File

@@ -1,3 +1,209 @@
.mycard {
visibility: hidden;
}
.landing {
background: #000 url(../../assets/images/cover.jpg) no-repeat 50% fixed;
background-size: cover
}
.landing > section {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center;
padding: 0 16px
}
.landing > section.padding {
padding: 180px 16px
}
.landing > section > div {
position: relative;
max-width: 1040px;
width: 100%
}
.landing__toolbar {
background: -webkit-gradient(linear, left top, left bottom, from(#000), to(transparent));
background: linear-gradient(180deg, #000, transparent);
padding: 0 !important
}
.landing__toolbar .q-btn {
border-radius: 0 0 5px 5px;
-ms-flex-item-align: stretch;
align-self: stretch
}
.landing__hero {
min-height: 100vh
}
.landing__arrow {
bottom: 8px;
opacity: .4
}
.landing__front {
background: -webkit-gradient(linear, left top, left bottom, from(transparent), color-stop(15%, rgba(0, 0, 0, .6)));
background: linear-gradient(180deg, transparent, rgba(0, 0, 0, .6) 15%)
}
.landing__logo {
width: 150px;
height: 150px;
margin-top: 21px;
-webkit-animation: logo-rotate 240s linear infinite;
animation: logo-rotate 240s linear infinite
}
.landing__features .q-icon {
font-size: 64px
}
.landing__features h4, .landing__features h6 {
margin: 26px 0
}
.landing__features p {
opacity: .6;
font-size: 16px
}
.landing__footer {
background: -webkit-gradient(linear, left top, left bottom, color-stop(65%, rgba(0, 0, 0, .1)), to(#000));
background: linear-gradient(180deg, rgba(0, 0, 0, .1) 65%, #000);
padding-top: 72px !important;
padding-bottom: 72px !important
}
.landing__footer .doc-link {
color: #fff
}
.landing__footer .doc-link:hover {
opacity: .8
}
.landing__swirl-bg {
background-repeat: no-repeat !important;
background-position: top;
background-size: contain !important;
background-image: url(https://cdn.quasar-framework.org/img/landing_first_section.png) !important
}
@media (max-width: 718px) {
.landing__hero {
text-align: center
}
.landing__hero .text-h1 {
font-size: 3rem;
line-height: 3.05rem;
margin-bottom: 24px
}
.landing > section.padding {
padding-top: 90px;
padding-bottom: 90px
}
.landing .feature-item {
text-align: center
}
.landing__hero-content {
padding-bottom: 180px
}
.landing__hero-btns {
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center
}
}
body.mobile .landing {
background: unset
}
body.mobile .landing:before {
content: "";
position: fixed;
top: 0;
height: 100vh;
left: 0;
right: 0;
bottom: 0;
z-index: -1;
background: #000 url(../../assets/images/cover.jpg) 50%;
background-size: cover
}
@-webkit-keyframes logo-rotate {
to {
-webkit-transform: rotate(-1turn);
transform: rotate(-1turn)
}
}
@keyframes logo-rotate {
to {
-webkit-transform: rotate(-1turn);
transform: rotate(-1turn)
}
}
.home {
//background-color: rgb(250, 250, 250);
padding: 5px;
display: flex;
//flex-wrap: nowrap;
flex-direction: column;
align-items: center;
justify-content: space-between;
}
.shadow {
//color: white;
text-shadow: 2px 2px 4px #000000;
}
.shadow-max {
//color: white;
text-shadow: 4px 4px 8px #000000;
}
.text-h1 {
font-size: 6rem;
font-weight: 300;
line-height: 6rem;
letter-spacing: -.01562em;
}
.text-weight-bold {
font-weight: 700;
}
.text-subtitle1 {
font-size: 1.25rem;
font-weight: 400;
line-height: 1.75rem;
letter-spacing: .00937em;
&.big {
font-size: 1.5rem;
}
}
.text-subtitle2 {
font-size: 1rem;
font-weight: 400;
line-height: 1.75rem;
letter-spacing: .00937em;
}

View File

@@ -30,6 +30,7 @@ export default class Home extends Vue {
GlobalStore.actions.prova()
}
meta() {
return {
keywords: { name: 'keywords', content: 'Quasar website' },
@@ -95,7 +96,7 @@ export default class Home extends Vue {
options = {
body: 'You successfully subscribed to our Notification service!',
icon: '/statics/icons/app-icon-96x96.png',
image: '/src/images/sf-boat.jpg',
image: '/assets/images/sf-boat.jpg',
dir: 'ltr',
lang: 'enUs', // BCP 47,
vibrate: [100, 50, 200],
@@ -152,7 +153,7 @@ export default class Home extends Vue {
options = {
body: mythis.$t('notification.subscribed'),
icon: '/statics/icons/android-chrome-192x192.png',
image: '/statics/images/freeplanet.png',
image: '/assets/images/freeplanet.png',
dir: 'ltr',
lang: 'enUs', // BCP 47,
vibrate: [100, 50, 200],

View File

@@ -1,33 +1,95 @@
<template >
<q-page class="flex flex-center">
<logo></logo>
<template>
<q-page class="text-white">
<div class="landing">
<section>
<div class="landing__hero">
<div style="height: 18vh;"></div>
<div class="landing__hero-content row justify-center q-gutter-xl">
<div class="row">
<logo></logo>
</div>
<div class="flex justify-end">
<div class="q-gutter-sm">
<div class="text-h1 shadow-max">FreePlanet</div>
<div class="text-subtitle1 shadow text-italic q-pl-sm">{{$t('msg.sottoTitoloApp')}}
</div>
<div class="text-subtitle1 shadow big text-italic q-pl-sm"><strong>{{$t('msg.sottoTitoloApp2')}}</strong>
</div>
<div class="text-subtitle2 shadow text-italic q-pl-sm ">{{$t('msg.sottoTitoloApp3')}}
</div>
<q-btn v-if="getPermission() !== 'granted'" class="enable-notifications" color="primary" rounded size="lg" icon="notifications" @click="askfornotification" :label="$t('notification.ask')"/>
<!--<q-btn v-if="getPermission() === 'granted'" class="enable-notifications" color="primary" rounded size="lg" icon="notifications" @click="showNotificationExample" label="Send Notification"/>-->
<!--<q-btn v-if="getPermission() === 'granted'" class="enable-notifications" color="secondary" rounded size="lg" icon="notifications" @click="createPushSubscription" label="Create Push Subscription !"/>-->
<div>
<q-btn v-if="getPermission() !== 'granted'" class="enable-notifications shadow"
color="primary" rounded
size="lg"
icon="notifications" @click="askfornotification"
:label="$t('notification.ask')"/>
<!--<q-btn v-if="getPermission() === 'granted'" class="enable-notifications" color="primary" rounded size="lg" icon="notifications" @click="showNotificationExample" label="Send Notification"/>-->
<!--<q-btn v-if="getPermission() === 'granted'" class="enable-notifications" color="secondary" rounded size="lg" icon="notifications" @click="createPushSubscription" label="Create Push Subscription !"/>-->
</div>
<!--
<q-btn>
Canale Telegram: <a href="https://t.me/freeplanet_channel" target="_blank"
style="color: white;">
<q-icon class="fab fa-telegram" size="2rem"/>
</a>
</q-btn>
-->
<br>
<div>
<q-chip square color="secondary">
Status:
</q-chip>
<q-field
v-if="getPermission() === 'granted'"
icon="notifications"
:label="$t('notification.titlegranted')"
helper="Stato Notifiche">
</q-field>
<q-field
v-if="NotServiceWorker()"
icon="notifications"
label="Service Worker not present"
>
</q-field>
<div style="margin: 5px;">
<q-alert
type="info"
class="q-mb-sm">
{{$t('msg.underconstruction')}}
</q-alert>
</div>
<br>
<div>
<q-field
v-if="getPermission() === 'granted'"
icon="notifications"
class="shadow"
:label="$t('notification.titlegranted')"
helper="Stato Notifiche">
</q-field>
<q-field
v-if="NotServiceWorker()"
class="shadow"
icon="notifications"
label="Service Worker not present"
>
</q-field>
</div>
<!--<div class="q-pt-md q-pl-sm">-->
<!--<div class="landing__hero-btns q-gutter-md row items-center"><a tabindex="0"-->
<!--type="button"-->
<!--href="/introduction-to-quasar"-->
<!--class="q-btn inline relative-position q-btn-item non-selectable q-btn&#45;&#45;rectangle bg-white text-primary q-focusable q-hoverable q-btn&#45;&#45;push">-->
<!--<div class="q-focus-helper"></div>-->
<!--<div class="q-btn__content text-center col items-center q-anchor&#45;&#45;skip justify-center row">-->
<!--<div>About</div>-->
<!--</div>-->
<!--</a><a tabindex="0" type="button" href="/start"-->
<!--class="q-btn inline relative-position q-btn-item non-selectable q-btn&#45;&#45;rectangle bg-white text-primary q-focusable q-hoverable q-btn&#45;&#45;push">-->
<!--<div class="q-focus-helper"></div>-->
<!--<div class="q-btn__content text-center col items-center q-anchor&#45;&#45;skip justify-center row">-->
<!--<div>Get started</div>-->
<!--</div>-->
<!--</a>-->
<!--<div class="text-body2">v1.0.0-beta.4</div>-->
<!--</div>-->
<!--</div>-->
</div>
</div>
</div>
</div>
</section>
</div>
</q-page>

View File

@@ -0,0 +1,98 @@
<template>
<q-page class="landing text-white">
<section>
<div class="landing__hero">
<div style="height: 28vh;"></div>
<div class="landing__hero-content row justify-center q-gutter-xl">
<div class="row"><img src="https://cdn.quasar-framework.org/logo/svg/quasar-logo.svg"
class="landing__logo"></div>
<div class="flex justify-end">
<div class="q-gutter-sm">
<div class="text-h1">
<div class="text-weight-bold">Quasar</div>
<div>Framework</div>
</div>
<div class="text-subtitle1 text-italic q-pl-sm">High performance, <strong>Material
Design
2</strong>, full front end stack with <strong>Vuejs</strong></div>
<div class="q-pt-md q-pl-sm">
<div class="landing__hero-btns q-gutter-md row items-center"><a tabindex="0"
type="button"
href="/introduction-to-quasar"
class="q-btn inline relative-position q-btn-item non-selectable q-btn--rectangle bg-white text-primary q-focusable q-hoverable q-btn--push">
<div class="q-focus-helper"></div>
<div class="q-btn__content text-center col items-center q-anchor--skip justify-center row">
<div>About</div>
</div>
</a><a tabindex="0" type="button" href="/start"
class="q-btn inline relative-position q-btn-item non-selectable q-btn--rectangle bg-white text-primary q-focusable q-hoverable q-btn--push">
<div class="q-focus-helper"></div>
<div class="q-btn__content text-center col items-center q-anchor--skip justify-center row">
<div>Get started</div>
</div>
</a>
<div class="text-body2">v1.0.0-beta.4</div>
</div>
</div>
</div>
</div>
</div>
<div class="landing__arrow absolute-bottom text-center"><i aria-hidden="true"
class="q-icon text-h2 text-white material-icons">expand_more</i>
</div>
</div>
<!--<div>-->
<!--<logo></logo>-->
<!--</div>-->
<!--<div>-->
<!--&lt;!&ndash; the row with a type of gutter &ndash;&gt;-->
<!--<q-alert-->
<!--avatar="assets/boy-avatar.png"-->
<!--color="primary"-->
<!--message="Jack"-->
<!--detail="Per un mondo più Consapevole"-->
<!--/>-->
<!--</div>-->
<!--<div>-->
<!--<q-btn v-if="getPermission() !== 'granted'" class="enable-notifications" color="primary" rounded-->
<!--size="lg"-->
<!--icon="notifications" @click="askfornotification" :label="$t('notification.ask')"/>-->
<!--&lt;!&ndash;<q-btn v-if="getPermission() === 'granted'" class="enable-notifications" color="primary" rounded size="lg" icon="notifications" @click="showNotificationExample" label="Send Notification"/>&ndash;&gt;-->
<!--&lt;!&ndash;<q-btn v-if="getPermission() === 'granted'" class="enable-notifications" color="secondary" rounded size="lg" icon="notifications" @click="createPushSubscription" label="Create Push Subscription !"/>&ndash;&gt;-->
<!--</div>-->
<!--<div>-->
<!--<q-chip square color="secondary">-->
<!--{{$t('notification.status')}}-->
<!--</q-chip>-->
<!--</div>-->
<!--<div>-->
<!--<q-field-->
<!--v-if="getPermission() === 'granted'"-->
<!--icon="notifications"-->
<!--:label="$t('notification.titlegranted')"-->
<!--helper="Stato Notifiche">-->
<!--</q-field>-->
<!--<q-field-->
<!--v-if="NotServiceWorker()"-->
<!--icon="notifications"-->
<!--label="Service Worker not present"-->
<!--&gt;-->
<!--</q-field>-->
<!--</div>-->
</section>
</q-page>
</template>
<script lang="ts" src="./home.ts">
</script>
<style lang="scss" scoped>
@import './home.scss';
</style>

View File

@@ -40,6 +40,11 @@ export const RouteConfig: VueRouteConfig[] = [
component: () => import('@/components/admin/cfgServer/cfgServer.vue'),
meta: { name: 'Categories' }
},
{
path: '/admin/testp1/:category',
component: () => import('@/components/admin/testp1/testp1.vue'),
meta: { name: 'Categories' }
},
{
path: '/offline',
component: () => import('@/components/offline/offline.vue'),

Binary file not shown.

Before

Width:  |  Height:  |  Size: 163 KiB

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 190 KiB

File diff suppressed because one or more lines are too long

View File

@@ -4,7 +4,7 @@ import router from '@router'
import { clone } from 'lodash'
import * as Types from './ApiTypes'
import { GlobalStore, UserStore } from '@store'
import { rescodes } from '@src/store/Modules/rescodes'
import { tools } from '@src/store/Modules/tools'
import { serv_constants } from '@src/store/Modules/serv_constants'
export const API_URL = process.env.MONGODB_HOST
@@ -40,7 +40,7 @@ export const removeAuthHeaders = () => {
async function Request(type: string, path: string, payload: any, setAuthToken?: boolean): Promise<Types.AxiosSuccess | Types.AxiosError> {
let ricevuto = false
try {
console.log(`Axios Request [${type}]:`, axiosInstance.defaults)
// console.log(`Axios Request [${type}]:`, axiosInstance.defaults)
let response: AxiosResponse
if (type === 'post' || type === 'put' || type === 'patch') {
response = await axiosInstance[type](path, payload, {
@@ -50,7 +50,7 @@ async function Request(type: string, path: string, payload: any, setAuthToken?:
}
})
ricevuto = true
console.log('response', response)
// console.log('Request Response: ', response)
// console.log(new Types.AxiosSuccess(response.data, response.status))
const setAuthToken = (path === '/updatepwd')
@@ -62,26 +62,26 @@ async function Request(type: string, path: string, payload: any, setAuthToken?:
x_auth_token = String(response.headers['x-auth'])
if (x_auth_token === '') {
UserStore.mutations.setServerCode(rescodes.ERR_AUTHENTICATION)
UserStore.mutations.setServerCode(tools.ERR_AUTHENTICATION)
}
if (setAuthToken) {
UserStore.mutations.UpdatePwd(x_auth_token)
localStorage.setItem(rescodes.localStorage.token, x_auth_token)
localStorage.setItem(tools.localStorage.token, x_auth_token)
}
UserStore.mutations.setAuth(x_auth_token)
localStorage.setItem(rescodes.localStorage.token, x_auth_token)
localStorage.setItem(tools.localStorage.token, x_auth_token)
}
GlobalStore.mutations.setStateConnection(ricevuto ? 'online' : 'offline')
UserStore.mutations.setServerCode(rescodes.OK)
UserStore.mutations.setServerCode(tools.OK)
} catch (e) {
if (setAuthToken) {
UserStore.mutations.setServerCode(rescodes.ERR_AUTHENTICATION)
UserStore.mutations.setServerCode(tools.ERR_AUTHENTICATION)
UserStore.mutations.setAuth('')
}
GlobalStore.mutations.setStateConnection(ricevuto ? 'online' : 'offline')
return Promise.reject(new Types.AxiosError(serv_constants.RIS_CODE__HTTP_FORBIDDEN_INVALID_TOKEN, null, rescodes.ERR_AUTHENTICATION))
return Promise.reject(new Types.AxiosError(serv_constants.RIS_CODE__HTTP_FORBIDDEN_INVALID_TOKEN, null, tools.ERR_AUTHENTICATION))
}
}
@@ -120,11 +120,11 @@ async function Request(type: string, path: string, payload: any, setAuthToken?:
}
let mycode = 0
if (!ricevuto) {
mycode = rescodes.ERR_SERVERFETCH
UserStore.mutations.setServerCode(rescodes.ERR_SERVERFETCH)
mycode = tools.ERR_SERVERFETCH
UserStore.mutations.setServerCode(tools.ERR_SERVERFETCH)
} else {
mycode = rescodes.ERR_GENERICO
UserStore.mutations.setServerCode(rescodes.ERR_GENERICO)
mycode = tools.ERR_GENERICO
UserStore.mutations.setServerCode(tools.ERR_GENERICO)
}
if (error.response) {

View File

@@ -7,7 +7,7 @@ import axios from 'axios'
export { addAuthHeaders, removeAuthHeaders, API_URL } from './Instance'
// import {AlgoliaSearch} from './AlgoliaController'
import Paths from '@paths'
import { rescodes } from '@src/store/Modules/rescodes'
import { tools } from '@src/store/Modules/tools'
import { GlobalStore, UserStore } from '@modules'
import globalroutines from './../../globalroutines/index'
@@ -62,7 +62,7 @@ export namespace ApiTool {
}
export async function SendReq(url: string, method: string, mydata: any, setAuthToken: boolean = false): Promise<Types.AxiosSuccess | Types.AxiosError> {
UserStore.mutations.setServerCode(rescodes.EMPTY)
UserStore.mutations.setServerCode(tools.EMPTY)
UserStore.mutations.setResStatus(0)
return await new Promise(function (resolve, reject) {
@@ -85,10 +85,10 @@ export namespace ApiTool {
if (res.status === serv_constants.RIS_CODE__HTTP_FORBIDDEN_INVALID_TOKEN) {
// Forbidden
// You probably is connectiong with other page...
UserStore.mutations.setServerCode(rescodes.ERR_AUTHENTICATION)
UserStore.mutations.setServerCode(tools.ERR_AUTHENTICATION)
UserStore.mutations.setAuth('')
router.push('/signin')
return reject({ code: rescodes.ERR_AUTHENTICATION })
return reject({ code: tools.ERR_AUTHENTICATION })
}
return resolve(res)
@@ -147,7 +147,7 @@ export namespace ApiTool {
if (method !== 'POST')
link += '/' + rec._id
console.log(' [Alternative] ++++++++++++++++++ SYNCING !!!! ', rec.descr, table, 'FETCH: ', method, link, 'data:')
// console.log(' [Alternative] ++++++++++++++++++ SYNCING !!!! ', rec.descr, table, 'FETCH: ', method, link, 'data:')
// Insert/Delete/Update table to the server
return SendReq(link, method, rec)

View File

@@ -7,14 +7,14 @@ import translate from './../../globalroutines/util'
import urlBase64ToUint8Array from '../../js/utility'
import messages from '../../statics/i18n'
import messages from '../../assets/i18n'
import { GlobalStore, Todos, UserStore } from '@store'
import globalroutines from './../../globalroutines/index'
import Api from '@api'
import { rescodes } from '@src/store/Modules/rescodes'
import { tools } from '@src/store/Modules/tools'
const allTables = ['todos', 'sync_todos', 'sync_todos_patch', 'delete_todos', 'config', 'swmsg']
const allTablesAfterLogin = ['todos', 'sync_todos', 'sync_todos_patch', 'delete_todos', 'config', 'swmsg']
const allTables = ['todos', 'categories', 'sync_todos', 'sync_todos_patch', 'delete_todos', 'config', 'swmsg']
const allTablesAfterLogin = ['todos', 'categories', 'sync_todos', 'sync_todos_patch', 'delete_todos', 'config', 'swmsg']
async function getstateConnSaved() {
const config = await globalroutines(null, 'readall', 'config', null)
@@ -44,6 +44,7 @@ const state: IGlobalState = {
stateConnection: stateConnDefault,
networkDataReceived: false,
cfgServer: [],
testp1: { contatore: 0, mioarray: [] },
category: 'personal',
posts: [],
listatodo: [
@@ -69,7 +70,17 @@ namespace Getters {
const listatodo = b.read(state => state.listatodo, 'listatodo')
const category = b.read(state => state.category, 'category')
const testpao1_getter_contatore = b.read(state => param1 => state.testp1.contatore + 100 + param1, 'testpao1_getter_contatore')
const testpao1_getter_array = b.read(state => param1 => state.testp1.mioarray.filter(item => item).map(item => item.valore) , 'testpao1_getter_array')
export const getters = {
get testpao1_getter_contatore() {
return testpao1_getter_contatore()
},
get testpao1_getter_array() {
return testpao1_getter_array()
},
get conta() {
return conta()
},
@@ -89,7 +100,7 @@ namespace Getters {
get isNewVersionAvailable() {
console.log('state.cfgServer', state.cfgServer)
const serversrec = state.cfgServer.find(x => x.chiave === rescodes.SERVKEY_VERS)
const serversrec = state.cfgServer.find(x => x.chiave === tools.SERVKEY_VERS)
console.log('Record ', serversrec)
if (serversrec) {
console.log('Vers Server ', serversrec.valore, 'Vers locale:', process.env.APP_VERSION)
@@ -101,6 +112,18 @@ namespace Getters {
}
namespace Mutations {
function setPaoArray(state: IGlobalState, miorec: ICfgServer) {
state.testp1.mioarray[state.testp1.mioarray.length - 1] = miorec
tools.notifyarraychanged(state.testp1.mioarray)
console.log('last elem = ', state.testp1.mioarray[state.testp1.mioarray.length - 1])
}
function NewArray(state: IGlobalState, newarr: ICfgServer[]) {
state.testp1.mioarray = newarr
}
function setPaoArray_Delete(state: IGlobalState) {
state.testp1.mioarray.pop()
}
function setConta(state: IGlobalState, num: number) {
state.conta = num
@@ -130,7 +153,10 @@ namespace Mutations {
setleftDrawerOpen: b.commit(setleftDrawerOpen),
setCategorySel: b.commit(setCategorySel),
setStateConnection: b.commit(setStateConnection),
SetwasAlreadySubOnDb: b.commit(SetwasAlreadySubOnDb)
SetwasAlreadySubOnDb: b.commit(SetwasAlreadySubOnDb),
setPaoArray: b.commit(setPaoArray),
setPaoArray_Delete: b.commit(setPaoArray_Delete),
NewArray: b.commit(NewArray)
}
}
@@ -170,7 +196,7 @@ namespace Actions {
mystate.wasAlreadySubscribed = !(subscription === null)
if (mystate.wasAlreadySubscribed) {
console.log('User is already SAVED Subscribe on DB!')
// console.log('User is already SAVED Subscribe on DB!')
// return null
return subscription
} else {
@@ -197,7 +223,7 @@ namespace Actions {
if (!newSub)
return
console.log('saveSubscriptionToServer: ', newSub)
// console.log('saveSubscriptionToServer: ', newSub)
// console.log('context', context)
let options = null
@@ -225,7 +251,7 @@ namespace Actions {
state.wasAlreadySubscribed = true
state.wasAlreadySubOnDb = true
localStorage.setItem(rescodes.localStorage.wasAlreadySubOnDb, String(state.wasAlreadySubOnDb))
localStorage.setItem(tools.localStorage.wasAlreadySubOnDb, String(state.wasAlreadySubOnDb))
})
.catch(e => {
console.log('Error during Subscription!', e)
@@ -262,6 +288,7 @@ namespace Actions {
function prova(context) {
// console.log('prova')
// state.testp1.mioarray[state.testp1.mioarray.length - 1].valore = 'VALMODIF';
// let msg = t('notification.title_subscribed')
@@ -318,7 +345,7 @@ namespace Actions {
async function saveCfgServerKey(context, dataval: ICfgServer) {
console.log('saveCfgServerKey dataval', dataval)
let ris = await Api.SendReq('/admin/updateval', 'POST', {pairval: dataval})
let ris = await Api.SendReq('/admin/updateval', 'POST', { pairval: dataval })
.then(res => {
})
@@ -341,7 +368,6 @@ namespace Actions {
if (res.data.cfgServer) {
state.cfgServer = [...res.data.cfgServer]
console.log('res.data.cfgServer', res.data.cfgServer)
// Todos.mutations.setTodos_changed()
}
// console.log('********** res', 'state.todos', state.todos, 'checkPending', checkPending)

View File

@@ -1,92 +1,325 @@
import { IGlobalState, ITodo, ITodosState } from 'model'
import { IGlobalState, ITodo, ITodosState, IParamTodo, IUserState, IDrag } from 'model'
import { storeBuilder } from './Store/Store'
import Api from '@api'
import { rescodes } from './rescodes'
import { tools } from './tools'
import { GlobalStore, Todos, UserStore } from '@store'
import globalroutines from './../../globalroutines/index'
import { Mutation } from 'vuex-module-decorators'
import { serv_constants } from '@src/store/Modules/serv_constants'
import { GetterTree } from 'vuex'
import objectId from '@src/js/objectId'
// import _ from 'lodash'
const state: ITodosState = {
visuOnlyUncompleted: false,
todos: [],
todos_changed: 1,
todos: [[]],
categories: [],
// todos_changed: 1,
reload_fromServer: 0,
testpao: 'Test',
insidePending: false
insidePending: false,
visuLastCompleted: 10
}
const b = storeBuilder.module<ITodosState>('TodosModule', state)
const fieldtochange: String [] = ['descr', 'completed', 'category', 'expiring_at', 'priority', 'id_prev', 'pos', 'enableExpiring', 'progress']
const b = storeBuilder.module<ITodosState>('Todos', state)
const stateGetter = b.state()
// Getters
namespace Getters {
function getindexbycategory(category: string) {
return state.categories.indexOf(category)
}
function gettodosByCategory(category: string) {
const indcat = state.categories.indexOf(category)
if (!state.todos[indcat])
return []
return state.todos[indcat]
}
function isValidIndex(cat, index) {
const myarr = gettodosByCategory(cat)
return (index >= 0 && index < myarr.length)
}
function getElemByIndex(cat, index) {
const myarr = gettodosByCategory(cat)
if (index >= 0 && index < myarr.length)
return myarr[index]
else
return null
}
function getElemById(cat, id) {
const myarr = gettodosByCategory(cat)
for (let indrec = 0; indrec < myarr.length; indrec++) {
if (myarr[indrec]._id === id) {
return myarr[indrec]
}
}
return null
}
function getIndexById(cat, id) {
const myarr = gettodosByCategory(cat)
for (let indrec = 0; indrec < myarr.length; indrec++) {
if (myarr[indrec]._id === id) {
return indrec
}
}
return -1
}
function getElemPrevById(cat, id_prev) {
const myarr = gettodosByCategory(cat)
for (let indrec = 0; indrec < myarr.length; indrec++) {
if (myarr[indrec].id_prev === id_prev) {
return myarr[indrec]
}
}
return null
}
function getLastFirstElemPriority(cat: string, priority: number, atfirst: boolean, escludiId: string) {
const myarr = gettodosByCategory(cat)
if (myarr === null)
return -1
let trovato: boolean = false
console.log('priority', priority)
for (let indrec = 0; indrec < myarr.length; indrec++) {
if ((myarr[indrec].priority === priority) && (myarr[indrec]._id !== escludiId)) {
trovato = true
if (atfirst) {
return indrec - 1
}
} else {
if (trovato) {
return indrec
}
}
}
console.log('trovato?', trovato, 'indrec')
if (trovato) {
return myarr.length - 1
} else {
if (priority === tools.Todos.PRIORITY_LOW)
return myarr.length - 1
else if (priority === tools.Todos.PRIORITY_HIGH)
return 0
}
}
function getFirstList(cat) {
const myarr = gettodosByCategory(cat)
for (let indrec in myarr) {
if (myarr[indrec].id_prev === tools.LIST_START) {
return myarr[indrec]
}
}
return null
}
function getLastListNotCompleted(cat) {
const arr = Todos.getters.todos_dacompletare(cat)
// console.log('cat', cat, 'arr', arr)
if (arr.length > 0)
return arr[arr.length - 1]
else
return null
}
function getstrelem(elem) {
return 'ID [' + elem._id + '] ' + elem.descr + ' [ID_PREV=' + elem.id_prev + '] modif=' + elem.modified
}
function update_idprev(indcat, indelemchange, indelemId) {
if (indelemchange >= 0 && indelemchange < state.todos[indcat].length) {
const id_prev = (indelemId >= 0) ? state.todos[indcat][indelemId]._id : tools.LIST_START
if (state.todos[indcat][indelemchange].id_prev !== id_prev) {
state.todos[indcat][indelemchange].id_prev = id_prev
tools.notifyarraychanged(state.todos[indcat][indelemchange])
// state.todos[indcat][indelemchange].modified = true
console.log('Index=', indelemchange, 'indtoget', indelemId, getstrelem(state.todos[indcat][indelemchange]))
return state.todos[indcat][indelemchange]
}
}
return null
}
function initcat() {
let tomorrow = new Date()
tomorrow.setDate(tomorrow.getDate() + 1)
const objtodo: ITodo = {
// _id: new Date().toISOString(), // Create NEW
_id: objectId(),
userId: UserStore.state.userId,
descr: '',
priority: tools.Todos.PRIORITY_NORMAL,
completed: false,
created_at: new Date(),
modify_at: new Date(),
completed_at: new Date(),
category: '',
expiring_at: tomorrow,
enableExpiring: false,
id_prev: '',
pos: 0,
modified: false,
progress: 0
}
// return this.copy(objtodo)
return objtodo
}
function deleteItemToSyncAndDb(table: String, item: ITodo, id) {
cmdToSyncAndDbTodo(tools.DB.CMD_DELETE_TODOS, table, 'DELETE', item, id, '')
}
async function saveItemToSyncAndDb(table: String, method, item: ITodo) {
return await cmdToSyncAndDbTodo(tools.DB.CMD_SYNC_NEW_TODOS, table, method, item, 0, '')
}
async function cmdToSyncAndDbTodo(cmd, table, method, item: ITodo, id, msg: String) {
// Send to Server to Sync
console.log('cmdToSyncAndDbTodo', cmd, table, method, item.descr, id, msg)
const risdata = await tools.cmdToSyncAndDb(cmd, table, method, item, id, msg)
if (cmd === tools.DB.CMD_SYNC_NEW_TODOS) {
if (method === 'POST')
await Todos.actions.dbInsertTodo(item)
else if (method === 'PATCH')
await Todos.actions.dbSaveTodo(item)
} else if (cmd === tools.DB.CMD_DELETE_TODOS) {
await Todos.actions.dbdeleteItem(item)
}
return risdata
}
namespace Getters {
// const fullName = b.read(function fullName(state): string {
// return state.userInfos.firstname?capitalize(state.userInfos.firstname) + " " + capitalize(state.userInfos.lastname):null;
// })
const todos_dacompletare = b.read((state: ITodosState) => (cat: string): ITodo[] => {
const indcat = getindexbycategory(cat)
if (state.todos[indcat]) {
return state.todos[indcat].filter(todo => !todo.completed)
} else return []
}, 'todos_dacompletare')
const todos_completati = b.read((state: ITodosState) => (cat: string): ITodo[] => {
const indcat = getindexbycategory(cat)
if (state.todos[indcat]) {
return state.todos[indcat].filter(todo => todo.completed).slice(0, state.visuLastCompleted) // Show only the first N completed
} else return []
}, 'todos_completati')
const doneTodosCount = b.read((state: ITodosState) => (cat: string): number => {
return getters.todos_completati(cat).length
}, 'doneTodosCount')
const TodosCount = b.read((state: ITodosState) => (cat: string): number => {
const indcat = getindexbycategory(cat)
if (state.todos[indcat]) {
return state.todos[indcat].length
} else {
return 0
}
}, 'TodosCount')
const visuOnlyUncompleted = b.read(state => state.visuOnlyUncompleted, 'visuOnlyUncompleted')
export const getters = {
get visuOnlyUncompleted() {
return visuOnlyUncompleted
// get fullName() { return fullName();},
get todos_dacompletare() {
return todos_dacompletare()
},
get todos_completati() {
return todos_completati()
},
get doneTodosCount() {
return doneTodosCount()
},
get TodosCount() {
return TodosCount()
}
}
}
namespace Mutations {
function setTestpao(state: ITodosState, testpao: String) {
state.testpao = testpao
}
function setTodos_changed(state: ITodosState) {
state.todos_changed++
mutations.setTestpao('Cambiato : ' + String(state.todos_changed))
// console.log('******* state.todos_changed', state.todos_changed)
}
function findTodoById(state: ITodosState, id: string) {
for (let i = 0; i < state.todos.length; i++) {
if (state.todos[i]._id === id)
return i
function findTodoById(state: ITodosState, data: IParamTodo) {
const indcat = state.categories.indexOf(data.categorySel)
if (indcat >= 0) {
if (state.todos[indcat]) {
for (let i = 0; i < state.todos[indcat].length; i++) {
if (state.todos[indcat][i]._id === data.id)
return i
}
}
}
return -1
}
function createNewItem(state: ITodosState, { objtodo, atfirst }) {
console.log('atfirst', atfirst)
function createNewItem(state: ITodosState, { objtodo, atfirst, categorySel }) {
const indcat = state.categories.indexOf(categorySel)
console.log('createNewItem', objtodo, 'cat=', categorySel, 'state.todos[indcat]', state.todos[indcat])
if (state.todos[indcat] === undefined) {
state.todos[indcat] = []
}
if (!state.todos[indcat]) {
state.todos[indcat].push(objtodo)
console.log('state.todos[indcat]', state.todos[indcat])
return
}
if (atfirst)
state.todos.unshift(objtodo)
state.todos[indcat].unshift(objtodo)
else
state.todos.push(objtodo)
state.todos[indcat].push(objtodo)
Todos.mutations.setTodos_changed()
}
function modifymyItem(state: ITodosState, myitem: ITodo) {
// Find record
const ind = findTodoById(state, myitem._id)
if (ind >= 0)
state.todos[ind] = rescodes.jsonCopy(myitem)
console.log('state.todos[indcat]', state.todos[indcat])
}
function deletemyitem(state: ITodosState, myitem: ITodo) {
// Find record
const ind = findTodoById(state, myitem._id)
const indcat = state.categories.indexOf(myitem.category)
const ind = findTodoById(state, { id: myitem._id, categorySel: myitem.category })
console.log('PRIMA state.todos', state.todos)
// Delete Item in to Array
if (ind >= 0)
state.todos.splice(ind, 1)
state.todos[indcat].splice(ind, 1)
console.log('DOPO state.todos', state.todos, 'ind', ind)
// tools.notifyarraychanged(state.todos[indcat])
}
export const mutations = {
setTestpao: b.commit(setTestpao),
setTodos_changed: b.commit(setTodos_changed),
modifymyItem: b.commit(modifymyItem),
deletemyitem: b.commit(deletemyitem),
createNewItem: b.commit(createNewItem)
}
@@ -94,21 +327,12 @@ namespace Mutations {
}
function consolelogpao(strlog, strlog2 = '', strlog3 = '') {
globalroutines(null, 'log', strlog + strlog2 + strlog3, null)
globalroutines(null, 'log', strlog + ' ' + strlog2 + ' ' + strlog3, null)
}
namespace Actions {
function json2array(json) {
let result = []
let keys = Object.keys(json)
keys.forEach(function (key) {
result.push(json[key])
})
return result
}
// If something in the call of Service Worker went wrong (Network or Server Down), then retry !
async function sendSwMsgIfAvailable() {
let something = false
@@ -126,13 +350,10 @@ namespace Actions {
// let recclone = [...arr_recmsg]
if (arr_recmsg.length > 0) {
// console.log(' TROVATI MSG PENDENTI ! ORA LI MANDO: ', arr_recmsg)
// console.log('---------------------- 2) navigator (2) .serviceWorker.ready')
let promiseChain = Promise.resolve()
for (let rec of arr_recmsg) {
for (let indrec in arr_recmsg) {
// console.log(' .... sw.sync.register ( ', rec._id)
// if ('SyncManager' in window) {
// sw.sync.register(rec._id)
@@ -140,7 +361,7 @@ namespace Actions {
// #Alternative to SyncManager
promiseChain = promiseChain.then(() => {
return Api.syncAlternative(rec._id)
return Api.syncAlternative(arr_recmsg[indrec]._id)
.then(() => {
something = true
})
@@ -180,13 +401,12 @@ namespace Actions {
})
}
})
}
async function waitAndRefreshData(context) {
// await aspettansec(3000)
return await dbLoadTodo(context, false)
return await dbLoadTodo(context, { checkPending: false })
}
async function checkPendingMsg(context) {
@@ -228,26 +448,27 @@ namespace Actions {
}
async function dbLoadTodo(context, checkPending: boolean = false) {
console.log('dbLoadTodo', checkPending)
async function dbLoadTodo(context, { checkPending }) {
console.log('dbLoadTodo', checkPending, 'userid=', UserStore.state.userId)
if (UserStore.state.userId === '')
return false // Login not made
GlobalStore.state.networkDataReceived = false
let ris = await Api.SendReq('/todos/' + UserStore.state.userId, 'GET', null)
.then(res => {
GlobalStore.state.networkDataReceived = true
// console.log('******* UPDATE TODOS.STATE.TODOS !:', res.todos)
if (res.data.todos) {
state.todos = [...res.data.todos]
Todos.mutations.setTodos_changed()
// console.log('RISULTANTE CATEGORIES DAL SERVER = ', res.data.categories)
// console.log('RISULTANTE TODOS DAL SERVER = ', res.data.todos)
state.todos = res.data.todos
state.categories = res.data.categories
} else {
state.todos = [[]]
}
console.log('********** res', 'state.todos', state.todos, 'checkPending', checkPending)
// After Login will store into the indexedDb...
// console.log('ARRAY TODOS = ', state.todos)
console.log('dbLoadTodo', 'state.todos', state.todos, 'state.categories', state.categories)
return res
})
@@ -257,11 +478,8 @@ namespace Actions {
return error
})
// console.log('ris : ', ris)
// console.log('ris STATUS: ', ris.status)
if (!GlobalStore.state.networkDataReceived) {
if (ris.status !== 200) {
console.log('ris.status', ris.status)
if (ris.status === serv_constants.RIS_CODE__HTTP_FORBIDDEN_INVALID_TOKEN) {
consolelogpao('UNAUTHORIZING... TOKEN EXPIRED... !! ')
} else {
@@ -272,7 +490,7 @@ namespace Actions {
await updatefromIndexedDbToStateTodo(context)
}
} else {
if (ris.status === rescodes.OK && checkPending) {
if (ris.status === tools.OK && checkPending) {
waitAndcheckPendingMsg(context)
}
}
@@ -280,7 +498,7 @@ namespace Actions {
async function updatefromIndexedDbToStateTodo(context) {
// console.log('Update the array in memory, from todos table from IndexedDb')
await globalroutines(null, 'updatefromIndexedDbToStateTodo', 'todos', null)
await globalroutines(null, 'updatefromIndexedDbToStateTodo', 'categories', null)
.then(() => {
console.log('updatefromIndexedDbToStateTodo! ')
return true
@@ -298,7 +516,6 @@ namespace Actions {
async function testfunc() {
while (true) {
consolelogpao('testfunc')
Todos.mutations.setTodos_changed()
// console.log('Todos.state.todos_changed:', Todos.state.todos_changed)
await aspettansec(5000)
}
@@ -343,16 +560,16 @@ namespace Actions {
return true
}
async function dbDeleteTodo(context, item: ITodo) {
async function dbdeleteItem(context, item: ITodo) {
if (!('serviceWorker' in navigator)) {
// console.log('dbDeleteTodo', item)
// console.log('dbdeleteItem', item)
if (UserStore.state.userId === '')
return false // Login not made
let res = await Api.SendReq('/todos/' + item._id, 'DELETE', item)
.then(res => {
console.log('dbDeleteTodo to the Server')
console.log('dbdeleteItem to the Server')
})
.catch((error) => {
UserStore.mutations.setErrorCatch(error)
@@ -363,23 +580,274 @@ namespace Actions {
}
}
async function getTodosByCategory(context, category: string) {
let myarr = state.todos.filter((p) => {
return p.category === category
function setmodifiedIfchanged(recOut, recIn, field) {
if (String(recOut[field]) !== String(recIn[field])) {
// console.log('*************** CAMPO ', field, 'MODIFICATO!', recOut[field], recIn[field])
recOut.modified = true
recOut[field] = recIn[field]
return true
}
return false
}
async function deleteItem(context, { cat, idobj }) {
console.log('deleteItem: KEY = ', idobj)
let myobjtrov = getElemById(cat, idobj)
if (myobjtrov !== null) {
let myobjnext = getElemPrevById(cat, myobjtrov._id)
if (myobjnext !== null) {
myobjnext.id_prev = myobjtrov.id_prev
myobjnext.modified = true
console.log('calling MODIFY 1')
await modify(context, { myitem: myobjnext, field: 'id_prev' })
}
// 1) Delete from the Todos Array
Todos.mutations.deletemyitem(myobjtrov)
// 2) Delete from the IndexedDb
globalroutines(context, 'delete', 'todos', null, idobj)
.then((ris) => {
}).catch((error) => {
console.log('err: ', error)
})
// 3) Delete from the Server (call)
deleteItemToSyncAndDb(tools.DB.TABLE_DELETE_TODOS, myobjtrov, idobj)
}
// console.log('FINE deleteItem')
}
async function insertTodo(context, { myobj, atfirst }) {
const objtodo = initcat()
objtodo.descr = myobj.descr
objtodo.category = myobj.category
let elemtochange: ITodo = null
if (atfirst) {
console.log('INSERT AT THE TOP')
elemtochange = getFirstList(objtodo.category)
objtodo.id_prev = tools.LIST_START
// objtodo.pos = (elemtochange !== null) ? elemtochange.pos - 1 : 1
} else {
console.log('INSERT AT THE BOTTOM')
// INSERT AT THE BOTTOM , so GET LAST ITEM
const lastelem = getLastListNotCompleted(objtodo.category)
console.log('lastelem', lastelem)
objtodo.id_prev = (lastelem !== null) ? lastelem._id : tools.LIST_START
// objtodo.pos = (elemtochange !== null) ? elemtochange.pos + 1 : 1
}
console.log('elemtochange TORNATO:', elemtochange)
objtodo.modified = false
console.log('objtodo', objtodo, 'ID_PREV=', objtodo.id_prev)
// 1) Create record in Memory
Todos.mutations.createNewItem({ objtodo, atfirst, categorySel: objtodo.category })
// 2) Insert into the IndexedDb
const id = await globalroutines(context, 'write', 'todos', objtodo)
let field = ''
// update also the last elem
if (atfirst) {
if (elemtochange !== null) {
elemtochange.id_prev = id
console.log('elemtochange', elemtochange)
field = 'id_prev'
// Modify the other record
await modify(context, { myitem: elemtochange, field })
}
}
// 3) send to the Server
await saveItemToSyncAndDb(tools.DB.TABLE_SYNC_TODOS, 'POST', objtodo)
.then((ris) => {
// Check if need to be moved...
const indelem = getIndexById(objtodo.category, objtodo._id)
let itemdragend = undefined
if (atfirst) {
// Check the second item, if it's different priority, then move to the first position of the priority
const secondindelem = indelem + 1
const secondelem = getElemByIndex(objtodo.category, secondindelem)
if (secondelem.priority !== objtodo.priority) {
itemdragend = {
field: 'priority',
idelemtochange: objtodo._id,
prioritychosen: objtodo.priority,
category: objtodo.category,
atfirst
}
}
} else {
// get previous of the last
const prevlastindelem = indelem - 1
const prevlastelem = getElemByIndex(objtodo.category, prevlastindelem)
if (prevlastelem.priority !== objtodo.priority) {
itemdragend = {
field: 'priority',
idelemtochange: objtodo._id,
prioritychosen: objtodo.priority,
category: objtodo.category,
atfirst
}
}
}
if (itemdragend)
swapElems(context, itemdragend)
return ris
})
}
async function modify(context, { myitem, field }) {
if (myitem === null)
return new Promise(function (resolve, reject) {
resolve()
})
const myobjsaved = tools.jsonCopy(myitem)
// get record from IndexedDb
const miorec = await globalroutines(context, 'read', 'todos', null, myobjsaved._id)
if (miorec === undefined) {
console.log('~~~~~~~~~~~~~~~~~~~~ !!!!!!!!!!!!!!!!!! Record not Found !!!!!! id=', myobjsaved._id)
return
}
if (setmodifiedIfchanged(miorec, myobjsaved, 'completed'))
miorec.completed_at = new Date().getDate()
fieldtochange.forEach(field => {
setmodifiedIfchanged(miorec, myobjsaved, field)
})
return myarr
if (miorec.modified) {
// console.log('Todo MODIFICATO! ', miorec.descr, miorec.pos, 'SALVALO SULLA IndexedDB todos')
miorec.modify_at = new Date().getDate()
miorec.modified = false
// 1) Permit to Update the Views
tools.notifyarraychanged(miorec)
// Todos.mutations.modifymyItem(miorec)
// this.logelem('modify', miorec)
// 2) Modify on IndexedDb
return globalroutines(context, 'write', 'todos', miorec)
.then(ris => {
// 3) Modify on the Server (call)
saveItemToSyncAndDb(tools.DB.TABLE_SYNC_TODOS_PATCH, 'PATCH', miorec)
})
}
}
// async function updateModifyRecords(context, cat: string) {
//
// const indcat = getindexbycategory(cat)
// for (const elem of state.todos[indcat]) {
// if (elem.modified) {
// console.log('calling MODIFY 3')
// await modify(context, { myitem: elem, field })
// .then(() => {
// elem.modified = false
// })
// }
// }
// }
//
async function swapElems(context, itemdragend: IDrag) {
// console.log('swapElems', itemdragend)
const cat = itemdragend.category
const indcat = state.categories.indexOf(cat)
if (itemdragend.field === 'priority') {
// get last elem priority
itemdragend.newIndex = getLastFirstElemPriority(itemdragend.category, itemdragend.prioritychosen, itemdragend.atfirst, itemdragend.idelemtochange)
itemdragend.oldIndex = getIndexById(itemdragend.category, itemdragend.idelemtochange)
console.log('swapElems PRIORITY', itemdragend)
}
if (isValidIndex(cat, indcat) && isValidIndex(cat, itemdragend.newIndex) && isValidIndex(cat, itemdragend.oldIndex)) {
state.todos[indcat].splice(itemdragend.newIndex, 0, state.todos[indcat].splice(itemdragend.oldIndex, 1)[0])
tools.notifyarraychanged(state.todos[indcat][itemdragend.newIndex])
tools.notifyarraychanged(state.todos[indcat][itemdragend.oldIndex])
if (itemdragend.field !== 'priority') {
let precind = itemdragend.newIndex - 1
let nextind = itemdragend.newIndex + 1
if (isValidIndex(cat, precind) && isValidIndex(cat, nextind)) {
if ((state.todos[indcat][precind].priority === state.todos[indcat][nextind].priority) && (state.todos[indcat][precind].priority !== state.todos[indcat][itemdragend.newIndex].priority)) {
state.todos[indcat][itemdragend.newIndex].priority = state.todos[indcat][precind].priority
tools.notifyarraychanged(state.todos[indcat][itemdragend.newIndex])
}
} else {
if (!isValidIndex(cat, precind)) {
if ((state.todos[indcat][nextind].priority !== state.todos[indcat][itemdragend.newIndex].priority)) {
state.todos[indcat][itemdragend.newIndex].priority = state.todos[indcat][nextind].priority
tools.notifyarraychanged(state.todos[indcat][itemdragend.newIndex])
}
} else {
if ((state.todos[indcat][precind].priority !== state.todos[indcat][itemdragend.newIndex].priority)) {
state.todos[indcat][itemdragend.newIndex].priority = state.todos[indcat][precind].priority
tools.notifyarraychanged(state.todos[indcat][itemdragend.newIndex])
}
}
}
}
// Update the id_prev property
const elem1 = update_idprev(indcat, itemdragend.newIndex, itemdragend.newIndex - 1)
const elem2 = update_idprev(indcat, itemdragend.newIndex + 1, itemdragend.newIndex)
const elem3 = update_idprev(indcat, itemdragend.oldIndex, itemdragend.oldIndex - 1)
const elem4 = update_idprev(indcat, itemdragend.oldIndex + 1, itemdragend.oldIndex)
// Update the records:
await modify(context, { myitem: elem1, field: 'id_prev' })
await modify(context, { myitem: elem2, field: 'id_prev' })
await modify(context, { myitem: elem3, field: 'id_prev' })
await modify(context, { myitem: elem4, field: 'id_prev' })
}
}
export const actions = {
dbInsertTodo: b.dispatch(dbInsertTodo),
dbSaveTodo: b.dispatch(dbSaveTodo),
dbLoadTodo: b.dispatch(dbLoadTodo),
dbDeleteTodo: b.dispatch(dbDeleteTodo),
dbdeleteItem: b.dispatch(dbdeleteItem),
updatefromIndexedDbToStateTodo: b.dispatch(updatefromIndexedDbToStateTodo),
getTodosByCategory: b.dispatch(getTodosByCategory),
checkPendingMsg: b.dispatch(checkPendingMsg),
waitAndcheckPendingMsg: b.dispatch(waitAndcheckPendingMsg),
swapElems: b.dispatch(swapElems),
// updateModifyRecords: b.dispatch(updateModifyRecords),
deleteItem: b.dispatch(deleteItem),
insertTodo: b.dispatch(insertTodo),
modify: b.dispatch(modify)
}
}

View File

@@ -5,7 +5,7 @@ import { storeBuilder } from './Store/Store'
import router from '@router'
import { serv_constants } from '../Modules/serv_constants'
import { rescodes } from '../Modules/rescodes'
import { tools } from '../Modules/tools'
import { GlobalStore, UserStore, Todos } from '@store'
import globalroutines from './../../globalroutines/index'
@@ -36,6 +36,9 @@ const b = storeBuilder.module<IUserState>('UserModule', state)
const stateGetter = b.state()
namespace Getters {
// const fullName = b.read(function fullName(state): string {
// return state.userInfos.firstname?capitalize(state.userInfos.firstname) + " " + capitalize(state.userInfos.lastname):null;
// })
const lang = b.read(state => {
if (state.lang !== '') {
@@ -58,7 +61,7 @@ namespace Getters {
// }, 'tok')
const isServerError = b.read(state => {
return (state.servercode === rescodes.ERR_SERVERFETCH)
return (state.servercode === tools.ERR_SERVERFETCH)
}, 'isServerError')
const getServerCode = b.read(state => {
@@ -78,6 +81,7 @@ namespace Getters {
get getServerCode() {
return getServerCode()
}
// get fullName() { return fullName();},
}
@@ -116,7 +120,7 @@ namespace Mutations {
function setlang(state: IUserState, newstr: string) {
console.log('SETLANG', newstr)
state.lang = newstr
localStorage.setItem(rescodes.localStorage.lang, state.lang)
localStorage.setItem(tools.localStorage.lang, state.lang)
}
function UpdatePwd(state: IUserState, x_auth_token: string) {
@@ -163,7 +167,7 @@ namespace Mutations {
function setErrorCatch(state: IUserState, axerr: Types.AxiosError) {
if (state.servercode !== rescodes.ERR_SERVERFETCH) {
if (state.servercode !== tools.ERR_SERVERFETCH) {
state.servercode = axerr.getCode()
}
console.log('Err catch: (servercode:', axerr.getCode(), axerr.getMsgError(), ')')
@@ -171,9 +175,9 @@ namespace Mutations {
function getMsgError(state: IUserState, err: number) {
let msgerrore = ''
if (err !== rescodes.OK) {
if (err !== tools.OK) {
msgerrore = 'Error [' + state.servercode + ']: '
if (state.servercode === rescodes.ERR_SERVERFETCH) {
if (state.servercode === tools.ERR_SERVERFETCH) {
msgerrore = translate('fetch.errore_server')
} else {
msgerrore = translate('fetch.errore_generico')
@@ -230,7 +234,7 @@ namespace Actions {
}
console.log(usertosend)
Mutations.mutations.setServerCode(rescodes.CALLING)
Mutations.mutations.setServerCode(tools.CALLING)
return await Api.SendReq('/updatepwd', 'POST', usertosend, true)
.then(res => {
@@ -252,7 +256,7 @@ namespace Actions {
}
console.log(usertosend)
Mutations.mutations.setServerCode(rescodes.CALLING)
Mutations.mutations.setServerCode(tools.CALLING)
return await Api.SendReq('/requestnewpwd', 'POST', usertosend)
.then(res => {
@@ -272,7 +276,7 @@ namespace Actions {
}
console.log(usertosend)
Mutations.mutations.setServerCode(rescodes.CALLING)
Mutations.mutations.setServerCode(tools.CALLING)
return await Api.SendReq('/vreg', 'POST', usertosend)
.then(res => {
@@ -280,7 +284,7 @@ namespace Actions {
// mutations.setServerCode(myres);
if (res.data.code === serv_constants.RIS_CODE_EMAIL_VERIFIED) {
console.log('VERIFICATO !!')
localStorage.setItem(rescodes.localStorage.verified_email, String(true))
localStorage.setItem(tools.localStorage.verified_email, String(true))
} else {
console.log('Risultato di vreg: ', res.data.code)
}
@@ -312,7 +316,7 @@ namespace Actions {
console.log(usertosend)
Mutations.mutations.setServerCode(rescodes.CALLING)
Mutations.mutations.setServerCode(tools.CALLING)
return Api.SendReq('/users', 'POST', usertosend)
.then(res => {
@@ -340,19 +344,19 @@ namespace Actions {
const now = new Date()
// const expirationDate = new Date(now.getTime() + myres.data.expiresIn * 1000);
const expirationDate = new Date(now.getTime() * 1000)
localStorage.setItem(rescodes.localStorage.lang, state.lang)
localStorage.setItem(rescodes.localStorage.userId, userId)
localStorage.setItem(rescodes.localStorage.username, username)
localStorage.setItem(rescodes.localStorage.token, state.x_auth_token)
localStorage.setItem(rescodes.localStorage.expirationDate, expirationDate.toString())
localStorage.setItem(rescodes.localStorage.verified_email, String(false))
localStorage.setItem(tools.localStorage.lang, state.lang)
localStorage.setItem(tools.localStorage.userId, userId)
localStorage.setItem(tools.localStorage.username, username)
localStorage.setItem(tools.localStorage.token, state.x_auth_token)
localStorage.setItem(tools.localStorage.expirationDate, expirationDate.toString())
localStorage.setItem(tools.localStorage.verified_email, String(false))
state.isLogged = true
// dispatch('storeUser', authData);
// dispatch('setLogoutTimer', myres.data.expiresIn);
return rescodes.OK
return tools.OK
} else {
return rescodes.ERR_GENERICO
return tools.ERR_GENERICO
}
})
.catch((error) => {
@@ -405,7 +409,7 @@ namespace Actions {
console.log(usertosend)
Mutations.mutations.setServerCode(rescodes.CALLING)
Mutations.mutations.setServerCode(tools.CALLING)
let myres: any
@@ -416,7 +420,7 @@ namespace Actions {
myres = res
if (myres.status !== 200) {
return Promise.reject(rescodes.ERR_GENERICO)
return Promise.reject(tools.ERR_GENERICO)
}
return myres
@@ -440,22 +444,22 @@ namespace Actions {
const now = new Date()
// const expirationDate = new Date(now.getTime() + myres.data.expiresIn * 1000);
const expirationDate = new Date(now.getTime() * 1000)
localStorage.setItem(rescodes.localStorage.lang, state.lang)
localStorage.setItem(rescodes.localStorage.userId, userId)
localStorage.setItem(rescodes.localStorage.username, username)
localStorage.setItem(rescodes.localStorage.token, state.x_auth_token)
localStorage.setItem(rescodes.localStorage.expirationDate, expirationDate.toString())
localStorage.setItem(rescodes.localStorage.isLogged, String(true))
localStorage.setItem(rescodes.localStorage.verified_email, String(verified_email))
localStorage.setItem(rescodes.localStorage.wasAlreadySubOnDb, String(GlobalStore.state.wasAlreadySubOnDb))
localStorage.setItem(tools.localStorage.lang, state.lang)
localStorage.setItem(tools.localStorage.userId, userId)
localStorage.setItem(tools.localStorage.username, username)
localStorage.setItem(tools.localStorage.token, state.x_auth_token)
localStorage.setItem(tools.localStorage.expirationDate, expirationDate.toString())
localStorage.setItem(tools.localStorage.isLogged, String(true))
localStorage.setItem(tools.localStorage.verified_email, String(verified_email))
localStorage.setItem(tools.localStorage.wasAlreadySubOnDb, String(GlobalStore.state.wasAlreadySubOnDb))
}
}
return rescodes.OK
return tools.OK
}).then(code => {
if (code === rescodes.OK) {
if (code === tools.OK) {
return setGlobal(true)
.then(() => {
return code
@@ -473,15 +477,15 @@ namespace Actions {
async function logout(context) {
console.log('logout')
localStorage.removeItem(rescodes.localStorage.expirationDate)
localStorage.removeItem(rescodes.localStorage.token)
localStorage.removeItem(rescodes.localStorage.userId)
localStorage.removeItem(rescodes.localStorage.username)
localStorage.removeItem(rescodes.localStorage.isLogged)
localStorage.removeItem(tools.localStorage.expirationDate)
localStorage.removeItem(tools.localStorage.token)
localStorage.removeItem(tools.localStorage.userId)
localStorage.removeItem(tools.localStorage.username)
localStorage.removeItem(tools.localStorage.isLogged)
// localStorage.removeItem(rescodes.localStorage.leftDrawerOpen)
localStorage.removeItem(rescodes.localStorage.verified_email)
localStorage.removeItem(rescodes.localStorage.categorySel)
localStorage.removeItem(rescodes.localStorage.wasAlreadySubOnDb)
localStorage.removeItem(tools.localStorage.verified_email)
localStorage.removeItem(tools.localStorage.categorySel)
localStorage.removeItem(tools.localStorage.wasAlreadySubOnDb)
await GlobalStore.actions.clearDataAfterLogout()
@@ -509,14 +513,14 @@ namespace Actions {
async function setGlobal(loggedWithNetwork: boolean) {
state.isLogged = true
GlobalStore.mutations.setleftDrawerOpen(localStorage.getItem(rescodes.localStorage.leftDrawerOpen) === 'true')
GlobalStore.mutations.setCategorySel(localStorage.getItem(rescodes.localStorage.categorySel))
GlobalStore.mutations.setleftDrawerOpen(localStorage.getItem(tools.localStorage.leftDrawerOpen) === 'true')
GlobalStore.mutations.setCategorySel(localStorage.getItem(tools.localStorage.categorySel))
GlobalStore.actions.checkUpdates()
await GlobalStore.actions.loadAfterLogin()
.then(() => {
Todos.actions.dbLoadTodo(true)
Todos.actions.dbLoadTodo({ checkPending: true })
})
}
@@ -526,24 +530,24 @@ namespace Actions {
// console.log('*** autologin_FromLocalStorage ***')
// INIT
UserStore.state.lang = rescodes.getItemLS(rescodes.localStorage.lang)
UserStore.state.lang = tools.getItemLS(tools.localStorage.lang)
const token = localStorage.getItem(rescodes.localStorage.token)
const token = localStorage.getItem(tools.localStorage.token)
if (!token) {
return false
}
const expirationDateStr = localStorage.getItem(rescodes.localStorage.expirationDate)
const expirationDateStr = localStorage.getItem(tools.localStorage.expirationDate)
let expirationDate = new Date(String(expirationDateStr))
const now = new Date()
if (now >= expirationDate) {
console.log('!!! Login Expired')
return false
}
const userId = String(localStorage.getItem(rescodes.localStorage.userId))
const username = String(localStorage.getItem(rescodes.localStorage.username))
const verified_email = localStorage.getItem(rescodes.localStorage.verified_email) === 'true'
const userId = String(localStorage.getItem(tools.localStorage.userId))
const username = String(localStorage.getItem(tools.localStorage.username))
const verified_email = localStorage.getItem(tools.localStorage.verified_email) === 'true'
GlobalStore.state.wasAlreadySubOnDb = localStorage.getItem(rescodes.localStorage.wasAlreadySubOnDb) === 'true'
GlobalStore.state.wasAlreadySubOnDb = localStorage.getItem(tools.localStorage.wasAlreadySubOnDb) === 'true'
console.log('************* autologin userId', userId)

View File

@@ -1,4 +1,9 @@
export const rescodes = {
import { ITodo } from '@src/model'
import globalroutines from './../../globalroutines/index'
import { Todos, UserStore } from '@store'
import Api from '@api'
export const tools = {
EMPTY: 0,
CALLING: 10,
OK: 20,
@@ -36,9 +41,9 @@ export const rescodes = {
CMD_SYNC_TODOS: 'sync-todos',
CMD_SYNC_NEW_TODOS: 'sync-new-todos',
CMD_DELETE_TODOS: 'sync-delete-todos',
TABLE_SYNC_TODOS : 'sync_todos',
TABLE_SYNC_TODOS_PATCH : 'sync_todos_patch',
TABLE_DELETE_TODOS : 'delete_todos'
TABLE_SYNC_TODOS: 'sync_todos',
TABLE_SYNC_TODOS_PATCH: 'sync_todos_patch',
TABLE_DELETE_TODOS: 'delete_todos'
},
MenuAction: {
@@ -170,7 +175,7 @@ export const rescodes = {
icon: 'delete',
checked: false
}
],
],
'esEs': [
{
id: 10,
@@ -244,7 +249,7 @@ export const rescodes = {
icon: 'trash',
checked: false
}
]
]
},
jsonCopy(src) {
@@ -257,9 +262,77 @@ export const rescodes = {
ris = ''
return ris
},
notifyarraychanged(array) {
if (array.length > 0)
array.splice(array.length - 1, 1, array[array.length - 1])
},
existArr(x) {
return x = (typeof x !== 'undefined' && x instanceof Array) ? x : []
},
json2array(json) {
let result = []
let keys = Object.keys(json)
keys.forEach(function (key) {
result.push(json[key])
})
return result
},
async cmdToSyncAndDb(cmd, table, method, item: ITodo, id, msg: String) {
// Send to Server to Sync
console.log('cmdToSyncAndDb', cmd, table, method, item.descr, id, msg)
let cmdSw = cmd
if ((cmd === tools.DB.CMD_SYNC_NEW_TODOS) || (cmd === tools.DB.CMD_DELETE_TODOS)) {
cmdSw = tools.DB.CMD_SYNC_TODOS
}
if ('serviceWorker' in navigator) {
return await navigator.serviceWorker.ready
.then(function (sw) {
// console.log('---------------------- navigator.serviceWorker.ready')
return globalroutines(null, 'write', table, item, id)
.then(function (id) {
// console.log('id', id)
const sep = '|'
let multiparams = cmdSw + sep + table + sep + method + sep + UserStore.state.x_auth_token + sep + UserStore.state.lang
let mymsgkey = {
_id: multiparams,
value: multiparams
}
return globalroutines(null, 'write', 'swmsg', mymsgkey, multiparams)
.then(ris => {
// if ('SyncManager' in window) {
// console.log(' SENDING... sw.sync.register', multiparams)
// return sw.sync.register(multiparams)
// } else {
// #Todo ++ Alternative 2 to SyncManager
return Api.syncAlternative(multiparams)
// }
})
.then(function () {
let data = null
if (msg !== '') {
data = { message: msg, position: 'bottom', timeout: 3000 }
}
return data
})
.catch(function (err) {
console.error('Errore in globalroutines', table, err)
})
})
})
}
}
}

24
src/typings/index.d.ts vendored Normal file
View File

@@ -0,0 +1,24 @@
export interface ActionTree<S, R> {
[key: string]: Action<S, R>;
}
export interface GetterTree<S, R> {
[key: string]: Getter<S, R>;
}
export interface MutationTree<S> {
[key: string]: Mutation<S>;
}
export interface ModuleTree<S> {
[key: string]: Module<S>;
}
export interface Module<S, R> {
namespaced?: boolean;
state?: S | (() => S);
getters?: GetterTree<S, R>;
actions?: ActionTree<S, R>;
mutations?: MutationTree<S>;
modules?: ModuleTree<R>;
}

View File

@@ -49,7 +49,7 @@
import {mapActions} from 'vuex'
import * as types from '../../store/mutation-types'
import { rescodes } from '../../../store/Modules/rescodes'
import { rescodes } from '../../../store/Modules/tools'
import {serv_constants} from '../../store/Modules/serv_constants'

View File

@@ -1,7 +1,7 @@
import Vue from 'vue'
import { Component, Prop, Watch } from 'vue-property-decorator'
import { GlobalStore, UserStore } from '@store'
import { rescodes } from '../../../store/Modules/rescodes'
import { tools } from '../../../store/Modules/tools'
import { serv_constants } from '../../../store/Modules/serv_constants'
@@ -78,7 +78,7 @@ export default class Signin extends Vue {
checkErrors(riscode) {
// console.log('checkErrors: ', riscode)
try {
if (riscode === rescodes.OK) {
if (riscode === tools.OK) {
this.showNotif({ type: 'positive', message: this.$t('login.completato') })
this.$router.push('/')
} else if (riscode === serv_constants.RIS_CODE_LOGIN_ERR) {
@@ -97,9 +97,9 @@ export default class Signin extends Vue {
this.$router.push('/signin')
})
} else if (riscode === rescodes.ERR_SERVERFETCH) {
} else if (riscode === tools.ERR_SERVERFETCH) {
this.showNotif(this.$t('fetch.errore_server'))
} else if (riscode === rescodes.ERR_GENERICO) {
} else if (riscode === tools.ERR_GENERICO) {
let msg = this.$t('fetch.errore_generico') + UserStore.mutations.getMsgError(riscode)
this.showNotif(msg)
} else {
@@ -155,7 +155,7 @@ export default class Signin extends Vue {
UserStore.actions.signin(this.signin)
.then((riscode) => {
// console.log('signin FINITO CALL: riscode=', riscode)
if (riscode === rescodes.OK) {
if (riscode === tools.OK) {
router.push('/signin')
}
return riscode
@@ -171,7 +171,7 @@ export default class Signin extends Vue {
return riscode
})
.then((riscode) => {
if (riscode === rescodes.OK) {
if (riscode === tools.OK) {
GlobalStore.actions.createPushSubscription()
.then(rissub => {

View File

@@ -1,7 +1,7 @@
import Vue from 'vue'
import { Component, Prop, Watch } from 'vue-property-decorator'
import { UserStore } from '@store'
import { rescodes } from '../../../store/Modules/rescodes'
import { tools } from '../../../store/Modules/tools'
import { ISignupOptions, IUserState } from 'model'
import { validations, TSignup } from './signup-validate'
@@ -125,16 +125,16 @@ export default class Signup extends Vue {
checkErrors(riscode: number) {
console.log('checkErrors', riscode)
if (riscode === rescodes.DUPLICATE_EMAIL_ID) {
if (riscode === tools.DUPLICATE_EMAIL_ID) {
this.showNotif(this.$t('reg.err.duplicate_email'))
} else if (riscode === rescodes.DUPLICATE_USERNAME_ID) {
} else if (riscode === tools.DUPLICATE_USERNAME_ID) {
this.showNotif(this.$t('reg.err.duplicate_username'))
} else if (riscode === rescodes.ERR_SERVERFETCH) {
} else if (riscode === tools.ERR_SERVERFETCH) {
this.showNotif(this.$t('fetch.errore_server'))
} else if (riscode === rescodes.ERR_GENERICO) {
} else if (riscode === tools.ERR_GENERICO) {
let msg = this.$t('fetch.errore_generico') + UserStore.mutations.getMsgError(riscode)
this.showNotif(msg)
} else if (riscode === rescodes.OK) {
} else if (riscode === tools.OK) {
this.$router.push('/signin')
this.showNotif({type: 'warning', textColor: 'black', message: this.$t('components.authentication.email_verification.link_sent')})
} else {

View File

@@ -60,7 +60,7 @@
import {mapActions} from 'vuex'
import * as types from '../../store/mutation-types'
//import {rescodes} from '../../store/Modules/user'
//import {tools} from '../../store/Modules/user'
import {serv_constants} from '../../store/Modules/serv_constants';