- 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

@@ -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)
})
})
})
}
}
}