- starting project list...

- ordering some functions
- fix error TS2339

quasar.extensions.json was the problem !
inside had:
{
  "@quasar/typescript": {
    "webpack": "plugin",
    "rename": true
  }
}
This commit is contained in:
Paolo Arena
2019-03-21 20:43:15 +01:00
parent 1fd56419a4
commit eda9a8514f
53 changed files with 28076 additions and 726 deletions

View File

@@ -1,7 +1,7 @@
// import { NotificationsStore, LoginStore } from '@store'
export class AxiosSuccess {
public success: boolean = true
public success: any = true
public status: number
public data: any
@@ -11,6 +11,7 @@ export class AxiosSuccess {
}
}
export class AxiosError {
public success: boolean = false
public status: number = 0
@@ -18,7 +19,7 @@ export class AxiosError {
public code: any = 0
public msgerr: string = ''
constructor(status: number, data?: any, code?: any, msgerr?: string) {
constructor(status: number, data?: any, code?: any, msgerr: string = '') {
this.status = status
this.data = data
this.code = code
@@ -89,10 +90,6 @@ export class ApiResponse {
}
}
export class ApiSuccess extends ApiResponse {
constructor(fields: {message?: string, data?: any} = {}) {
super({

View File

@@ -48,7 +48,7 @@ export const removeAuthHeaders = () => {
async function Request(type: string, path: string, payload: any): Promise<Types.AxiosSuccess | Types.AxiosError> {
let ricevuto = false
try {
console.log(`Axios Request [${type}]:`, axiosInstance.defaults, 'path:', path)
console.log('Axios Request', path, type, axiosInstance.defaults)
let response: AxiosResponse
if (type === 'post' || type === 'put' || type === 'patch') {
response = await axiosInstance[type](path, payload, {
@@ -63,6 +63,8 @@ async function Request(type: string, path: string, payload: any): Promise<Types.
const setAuthToken = (path === '/updatepwd')
// console.log('--------- 0 ')
if (response && (response.status === 200)) {
let x_auth_token = ''
try {

View File

@@ -62,6 +62,15 @@ export namespace ApiTool {
}
export async function SendReq(url: string, method: string, mydata: any, setAuthToken: boolean = false): Promise<Types.AxiosSuccess | Types.AxiosError> {
mydata = {
...mydata,
keyappid: process.env.PAO_APP_ID,
idapp: process.env.APP_ID
}
// console.log('mydata', mydata)
UserStore.mutations.setServerCode(tools.EMPTY)
UserStore.mutations.setResStatus(0)
return await new Promise((resolve, reject) => {
@@ -122,7 +131,7 @@ export namespace ApiTool {
const token = multiparams[3]
// let lang = multiparams[3]
if (cmd === 'sync-todos') {
if (cmd === tools.DB.CMD_SYNC) {
// console.log('[Alternative] Syncing', cmd, table, method)
// const headers = new Headers()

View File

@@ -15,9 +15,6 @@ import { GlobalStore, Todos, UserStore } from '@store'
import messages from '../../statics/i18n'
import globalroutines from './../../globalroutines/index'
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']
let stateConnDefault = 'online'
getstateConnSaved()
@@ -134,6 +131,8 @@ namespace Getters {
route: '/todo', faIcon: 'fa fa-list-alt', materialIcon: 'format_list_numbered', name: 'pages.Todo',
routes2: listatodo
},
{ route: '/projects', faIcon: 'fa fa-list-alt', materialIcon: 'next_week', name: 'pages.Projects' },
{ route: '/category', faIcon: 'fa fa-list-alt', materialIcon: 'category', name: 'pages.Category' },
{ route: '/admin/cfgserv', faIcon: 'fa fa-database', materialIcon: 'event_seat', name: 'pages.Admin' },
{ route: '/admin/testp1/par1', faIcon: 'fa fa-database', materialIcon: 'restore', name: 'pages.Test1' },
@@ -444,22 +443,22 @@ namespace Actions {
console.log('clearDataAfterLogout')
// Clear all data from the IndexedDB
for (const table of allTables) {
for (const table of tools.allTables) {
await globalroutines(null, 'clearalldata', table, null)
}
if ('serviceWorker' in navigator) {
// REMOVE ALL SUBSCRIPTION
console.log('REMOVE ALL SUBSCRIPTION...')
await navigator.serviceWorker.ready.then(function (reg) {
await navigator.serviceWorker.ready.then((reg) => {
console.log('... Ready')
reg.pushManager.getSubscription().then((subscription) => {
console.log(' Found Subscription...')
if (subscription) {
subscription.unsubscribe().then(function (successful) {
subscription.unsubscribe().then((successful) => {
// You've successfully unsubscribed
console.log('You\'ve successfully unsubscribed')
}).catch(function (e) {
}).catch( (e) => {
// Unsubscription failed
})
}

View File

@@ -0,0 +1,111 @@
import Vue from 'vue'
import { IProgressState } from '@types'
import { storeBuilder } from '../Store/Store'
const css = require('@css')
let TIMER = null
let TIMEOUT = null
let CUT = null
// State
const state: IProgressState = {
percent: 0,
show: false,
canSuccess: true,
duration: 3000,
height: '2px',
color: css.mainStyle,
failedColor: css.red1
}
const b = storeBuilder.module<IProgressState>('ProgressModule', state)
const stateGetter = b.state()
// Getters
namespace Getters {
export const getters = {}
}
// Mutations
namespace Mutations {
function start(state: IProgressState) {
if (!state.show) {
clearTimeout(TIMEOUT)
state.show = true
state.canSuccess = true
if (TIMER) {
clearInterval(TIMER)
state.percent = 0
}
CUT = 20000 / Math.floor(state.duration)
TIMER = setInterval(() => {
Mutations.mutations.increase(CUT * Math.random())
if (state.percent > 80) {
Mutations.mutations.pause()
}
}, 200)
}
}
function set(state: IProgressState, num: number) {
state.show = true
state.canSuccess = true
state.percent = Math.floor(num)
}
function increase(state: IProgressState, num: number) {
state.percent = state.percent + Math.floor(num)
}
function decrease(state: IProgressState, num: number) {
state.percent = state.percent - Math.floor(num)
}
function finish(state: IProgressState) {
state.percent = 100
Mutations.mutations.hide()
}
function pause(state: IProgressState) {
clearInterval(TIMER)
}
function hide(state: IProgressState) {
clearInterval(TIMER)
TIMER = null
TIMEOUT = setTimeout(() => {
state.show = false
state.percent = 0
Vue.nextTick(() => {
setTimeout(() => {
state.percent = 0
}, 200)
})
}, 500)
}
function fail(state: IProgressState) {
state.canSuccess = false
mutations.finish()
}
export const mutations = {
start: b.commit(start),
set: b.commit(set),
finish: b.commit(finish),
increase: b.commit(increase),
decrease: b.commit(decrease),
pause: b.commit(pause),
hide: b.commit(hide),
fail: b.commit(fail)
}
}
// Actions
namespace Actions {
export const actions = {
}
}
// Module
const ProgressModule = {
get state() { return stateGetter()},
getters: Getters.getters,
mutations: Mutations.mutations,
actions: Actions.actions
}
export default ProgressModule

View File

@@ -0,0 +1,4 @@
// export {default as NotificationsStore} from './NotificationsStore';
export {default as ProgressBar} from './ProgressBar'
// export {default as AlertsStore} from './AlertsStore';
// export {default as GoogleMaps, getMapInstance, geoLocate} from './GoogleMaps/GoogleMaps';

View File

@@ -11,6 +11,8 @@ import { GetterTree } from 'vuex'
import objectId from '@src/js/objectId'
import { costanti } from '@src/store/Modules/costanti'
const nametable = 'todos'
// import _ from 'lodash'
const state: ITodosState = {
@@ -24,7 +26,7 @@ const state: ITodosState = {
visuLastCompleted: 10
}
const fieldtochange: String [] = ['descr', 'completed', 'category', 'expiring_at', 'priority', 'id_prev', 'pos', 'enableExpiring', 'progress']
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()
@@ -35,8 +37,9 @@ function getindexbycategory(category: string) {
function gettodosByCategory(category: string) {
const indcat = state.categories.indexOf(category)
if (!state.todos[indcat])
if (!state.todos[indcat]) {
return []
}
return state.todos[indcat]
}
@@ -48,49 +51,34 @@ function isValidIndex(cat, index) {
function getElemByIndex(cat, index) {
const myarr = gettodosByCategory(cat)
if (index >= 0 && index < myarr.length)
if (index >= 0 && index < myarr.length) {
return myarr[index]
else
}
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
return myarr.find((elem) => elem._id === id)
}
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
return myarr.findIndex((elem) => elem._id === id)
}
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
return myarr.find((elem) => elem._id === id_prev)
}
function getLastFirstElemPriority(cat: string, priority: number, atfirst: boolean, escludiId: string) {
const myarr = gettodosByCategory(cat)
if (myarr === null)
if (myarr === null) {
return -1
}
let trovato: boolean = false
@@ -114,30 +102,29 @@ function getLastFirstElemPriority(cat: string, priority: number, atfirst: boolea
if (trovato) {
return myarr.length - 1
} else {
if (priority === tools.Todos.PRIORITY_LOW)
if (priority === tools.Todos.PRIORITY_LOW) {
return myarr.length - 1
else if (priority === tools.Todos.PRIORITY_HIGH)
}
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
return myarr.find((elem) => elem.id_prev === tools.LIST_START)
}
function getLastListNotCompleted(cat) {
const arr = Todos.getters.todos_dacompletare(cat)
// console.log('cat', cat, 'arr', arr)
if (arr.length > 0)
if (arr.length > 0) {
return arr[arr.length - 1]
else
}
else {
return null
}
}
function getstrelem(elem) {
@@ -158,10 +145,9 @@ function update_idprev(indcat, indelemchange, indelemId) {
return null
}
function initcat() {
let tomorrow = new Date()
const tomorrow = new Date()
tomorrow.setDate(tomorrow.getDate() + 1)
const objtodo: ITodo = {
@@ -187,55 +173,31 @@ function initcat() {
}
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 []
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]) {
if (state.showtype === costanti.ShowTypeTask.SHOW_LAST_N_COMPLETED)
return state.todos[indcat].filter(todo => todo.completed).slice(0, state.visuLastCompleted) // Show only the first N completed
else if (state.showtype === costanti.ShowTypeTask.SHOW_ALL)
return state.todos[indcat].filter(todo => todo.completed)
else
if (state.showtype === costanti.ShowTypeTask.SHOW_LAST_N_COMPLETED) {
return state.todos[indcat].filter((todo) => todo.completed).slice(0, state.visuLastCompleted)
} // Show only the first N completed
else if (state.showtype === costanti.ShowTypeTask.SHOW_ALL) {
return state.todos[indcat].filter((todo) => todo.completed)
}
else {
return []
} else return []
}
} else {
return []
}
}, 'todos_completati')
const doneTodosCount = b.read((state: ITodosState) => (cat: string): number => {
@@ -250,9 +212,7 @@ namespace Getters {
}
}, 'TodosCount')
export const getters = {
// get fullName() { return fullName();},
get todos_dacompletare() {
return todos_dacompletare()
},
@@ -268,28 +228,17 @@ namespace Getters {
}
}
namespace Mutations {
function setTestpao(state: ITodosState, testpao: String) {
state.testpao = testpao
}
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 state.todos[indcat].find((elem) => elem._id === data.id)
}
return -1
}
function createNewItem(state: ITodosState, { objtodo, atfirst, categorySel }) {
let indcat = state.categories.indexOf(categorySel)
if (indcat == -1) {
@@ -303,10 +252,12 @@ namespace Mutations {
console.log('push state.todos[indcat]', state.todos)
return
}
if (atfirst)
if (atfirst) {
state.todos[indcat].unshift(objtodo)
else
}
else {
state.todos[indcat].push(objtodo)
}
console.log('state.todos[indcat]', state.todos[indcat])
@@ -319,162 +270,35 @@ namespace Mutations {
console.log('PRIMA state.todos', state.todos)
// Delete Item in to Array
if (ind >= 0)
if (ind >= 0) {
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),
// setTestpao: b.commit(setTestpao),
deletemyitem: b.commit(deletemyitem),
createNewItem: b.commit(createNewItem)
}
}
function consolelogpao(strlog, strlog2 = '', strlog3 = '') {
globalroutines(null, 'log', strlog + ' ' + strlog2 + ' ' + strlog3, null)
}
namespace Actions {
// If something in the call of Service Worker went wrong (Network or Server Down), then retry !
async function sendSwMsgIfAvailable() {
let something = false
if ('serviceWorker' in navigator) {
console.log(' -------- sendSwMsgIfAvailable')
let count = await checkPendingMsg(null)
if (count > 0) {
return await navigator.serviceWorker.ready
.then(function (sw) {
return globalroutines(null, 'readall', 'swmsg')
.then(function (arr_recmsg) {
// let recclone = [...arr_recmsg]
if (arr_recmsg.length > 0) {
// console.log('---------------------- 2) navigator (2) .serviceWorker.ready')
let promiseChain = Promise.resolve()
for (let indrec in arr_recmsg) {
// console.log(' .... sw.sync.register ( ', rec._id)
// if ('SyncManager' in window) {
// sw.sync.register(rec._id)
// } else {
// #Alternative to SyncManager
promiseChain = promiseChain.then(() => {
return Api.syncAlternative(arr_recmsg[indrec]._id)
.then(() => {
something = true
})
})
// }
}
return promiseChain
}
})
})
}
}
return new Promise(function (resolve, reject) {
resolve(something)
})
}
async function waitAndcheckPendingMsg(context) {
// await aspettansec(1000)
return await checkPendingMsg(context)
.then(ris => {
if (ris) {
// console.log('risPending = ', ris)
return sendSwMsgIfAvailable()
.then(something => {
if (something) {
if (process.env.DEBUG === '1')
console.log('something')
// Refresh data
return waitAndRefreshData(context)
}
})
}
})
}
async function waitAndRefreshData(context) {
// await aspettansec(3000)
return await dbLoadTodo(context, { checkPending: false })
}
async function readConfig(id) {
return await globalroutines(null, 'read', 'config', null, String(id))
}
async function checkPendingMsg(context) {
// console.log('checkPendingMsg')
const config = await globalroutines(null, 'read', 'config', null, '1')
// console.log('config', config)
try {
if (config) {
if (config[1].stateconn !== undefined) {
// console.log('config.stateconn', config[1].stateconn)
if (config[1].stateconn !== GlobalStore.state.stateConnection) {
GlobalStore.mutations.setStateConnection(config[1].stateconn)
}
}
}
} catch (e) {
}
return new Promise(function (resolve, reject) {
// Check if there is something
return globalroutines(null, 'count', 'swmsg')
.then(function (count) {
if (count > 0) {
// console.log('count = ', count)
return resolve(true)
} else {
return resolve(false)
}
})
.catch(e => {
return reject()
})
})
}
async function dbLoadTodo(context, { checkPending }) {
console.log('dbLoadTodo', checkPending, 'userid=', UserStore.state.userId)
if (UserStore.state.userId === '')
return false // Login not made
if (UserStore.state.userId === '') {
return false
} // Login not made
let ris = await Api.SendReq('/todos/' + UserStore.state.userId, 'GET', null)
.then(res => {
const ris = await Api.SendReq('/todos/' + UserStore.state.userId, 'GET', null)
.then((res) => {
if (res.data.todos) {
// 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 {
@@ -483,53 +307,47 @@ namespace Actions {
// console.log('PRIMA showtype = ', state.showtype)
state.showtype = parseInt(GlobalStore.getters.getConfigStringbyId({id: costanti.CONFIG_ID_SHOW_TYPE_TODOS, default: costanti.ShowTypeTask.SHOW_LAST_N_COMPLETED }))
// console.log('showtype = ', state.showtype)
state.showtype = parseInt(GlobalStore.getters.getConfigStringbyId({
id: costanti.CONFIG_ID_SHOW_TYPE_TODOS,
default: costanti.ShowTypeTask.SHOW_LAST_N_COMPLETED
}), 10)
// console.log('ARRAY TODOS = ', state.todos)
if (process.env.DEBUG === '1')
if (process.env.DEBUG === '1') {
console.log('dbLoadTodo', 'state.todos', state.todos, 'state.categories', state.categories)
}
return res
})
.catch(error => {
.catch((error) => {
console.log('error dbLoadTodo', error)
UserStore.mutations.setErrorCatch(error)
return error
})
if (ris.status !== 200) {
if (process.env.DEBUG === '1')
if (process.env.DEBUG === '1') {
console.log('ris.status', ris.status)
}
if (ris.status === serv_constants.RIS_CODE__HTTP_FORBIDDEN_INVALID_TOKEN) {
consolelogpao('UNAUTHORIZING... TOKEN EXPIRED... !! ')
tools.consolelogpao('UNAUTHORIZING... TOKEN EXPIRED... !! ')
} else {
consolelogpao('NETWORK UNREACHABLE ! (Error in fetch)', UserStore.getters.getServerCode, ris.status)
tools.consolelogpao('NETWORK UNREACHABLE ! (Error in fetch)', UserStore.getters.getServerCode, ris.status)
}
if ('serviceWorker' in navigator) {
// Read all data from IndexedDB Store into Memory
await updatefromIndexedDbToStateTodo(context)
await tools.updatefromIndexedDbToStateTodo('categories')
}
} else {
if (ris.status === tools.OK && checkPending) {
waitAndcheckPendingMsg(context)
tools.waitAndcheckPendingMsg()
}
}
}
async function updatefromIndexedDbToStateTodo(context) {
// console.log('Update the array in memory, from todos table from IndexedDb')
await globalroutines(null, 'updatefromIndexedDbToStateTodo', 'categories', null)
.then(() => {
console.log('updatefromIndexedDbToStateTodo! ')
return true
})
}
function aspettansec(numsec) {
return new Promise(function (resolve, reject) {
setTimeout(function () {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('anything')
}, numsec)
})
@@ -537,71 +355,12 @@ namespace Actions {
async function testfunc() {
while (true) {
consolelogpao('testfunc')
tools.consolelogpao('testfunc')
// console.log('Todos.state.todos_changed:', Todos.state.todos_changed)
await aspettansec(5000)
}
}
async function dbSaveTodo(context, itemtodo: ITodo) {
return await dbInsertSaveTodo(context, itemtodo, 'PATCH')
}
async function dbInsertTodo(context, itemtodo: ITodo) {
return await dbInsertSaveTodo(context, itemtodo, 'POST')
}
async function dbInsertSaveTodo(context, itemtodo: ITodo, method) {
if (!('serviceWorker' in navigator)) {
console.log('dbInsertSaveTodo', itemtodo, method)
let call = '/todos'
if (UserStore.state.userId === '')
return false // Login not made
if (method !== 'POST')
call += '/' + itemtodo._id
console.log('TODO TO SAVE: ', itemtodo)
let res = await Api.SendReq(call, method, itemtodo)
.then(res => {
console.log('dbInsertSaveTodo to the Server', res.data)
return (res.status === 200)
})
.catch((error) => {
UserStore.mutations.setErrorCatch(error)
// return UserStore.getters.getServerCode
return false
})
}
return true
}
async function dbdeleteItem(context, item: ITodo) {
if (!('serviceWorker' in navigator)) {
// 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('dbdeleteItem to the Server')
})
.catch((error) => {
UserStore.mutations.setErrorCatch(error)
return UserStore.getters.getServerCode
})
return res
}
}
function setmodifiedIfchanged(recOut, recIn, field) {
if (String(recOut[field]) !== String(recIn[field])) {
// console.log('*************** CAMPO ', field, 'MODIFICATO!', recOut[field], recIn[field])
@@ -615,12 +374,12 @@ namespace Actions {
async function deleteItem(context, { cat, idobj }) {
console.log('deleteItem: KEY = ', idobj)
let myobjtrov = getElemById(cat, idobj)
const myobjtrov = getElemById(cat, idobj)
if (myobjtrov !== null) {
let myobjnext = getElemPrevById(cat, myobjtrov._id)
if (!!myobjtrov) {
const myobjnext = getElemPrevById(cat, myobjtrov._id)
if (myobjnext !== null) {
if (!!myobjnext) {
myobjnext.id_prev = myobjtrov.id_prev
myobjnext.modified = true
console.log('calling MODIFY 1')
@@ -631,15 +390,13 @@ namespace Actions {
Todos.mutations.deletemyitem(myobjtrov)
// 2) Delete from the IndexedDb
globalroutines(context, 'delete', 'todos', null, idobj)
.then((ris) => {
}).catch((error) => {
console.log('err: ', error)
})
globalroutines(context, 'delete', nametable, null, idobj)
.catch((error) => {
console.log('err: ', error)
})
// 3) Delete from the Server (call)
deleteItemToSyncAndDb(tools.DB.TABLE_DELETE_TODOS, myobjtrov, idobj)
tools.deleteItemToSyncAndDb(nametable, myobjtrov, idobj)
}
@@ -679,7 +436,7 @@ namespace Actions {
Todos.mutations.createNewItem({ objtodo, atfirst, categorySel: objtodo.category })
// 2) Insert into the IndexedDb
const id = await globalroutines(context, 'write', 'todos', objtodo)
const id = await globalroutines(context, 'write', nametable, objtodo)
let field = ''
// update also the last elem
@@ -695,11 +452,11 @@ namespace Actions {
}
// 3) send to the Server
return await saveItemToSyncAndDb(tools.DB.TABLE_SYNC_TODOS, 'POST', objtodo)
return await tools.saveItemToSyncAndDb(nametable, 'POST', objtodo)
.then((ris) => {
// Check if need to be moved...
const indelem = getIndexById(objtodo.category, objtodo._id)
let itemdragend = undefined
let itemdragend
if (atfirst) {
// Check the second item, if it's different priority, then move to the first position of the priority
const secondindelem = indelem + 1
@@ -733,8 +490,9 @@ namespace Actions {
}
}
if (itemdragend)
if (itemdragend) {
swapElems(context, itemdragend)
}
return ris
@@ -742,24 +500,25 @@ namespace Actions {
}
async function modify(context, { myitem, field }) {
if (myitem === null)
return new Promise(function (resolve, reject) {
if (myitem === null) {
return new Promise((resolve, reject) => {
resolve()
})
}
const myobjsaved = tools.jsonCopy(myitem)
// get record from IndexedDb
const miorec = await globalroutines(context, 'read', 'todos', null, myobjsaved._id)
const miorec = await globalroutines(context, 'read', nametable, null, myobjsaved._id)
if (miorec === undefined) {
console.log('~~~~~~~~~~~~~~~~~~~~ !!!!!!!!!!!!!!!!!! Record not Found !!!!!! id=', myobjsaved._id)
return
}
if (setmodifiedIfchanged(miorec, myobjsaved, 'completed'))
if (setmodifiedIfchanged(miorec, myobjsaved, 'completed')) {
miorec.completed_at = new Date().getDate()
}
fieldtochange.forEach(field => {
fieldtochange.forEach((field) => {
setmodifiedIfchanged(miorec, myobjsaved, field)
})
@@ -775,32 +534,16 @@ namespace Actions {
// this.logelem('modify', miorec)
// 2) Modify on IndexedDb
return globalroutines(context, 'write', 'todos', miorec)
.then(ris => {
return globalroutines(context, 'write', nametable, miorec)
.then((ris) => {
// 3) Modify on the Server (call)
saveItemToSyncAndDb(tools.DB.TABLE_SYNC_TODOS_PATCH, 'PATCH', miorec)
tools.saveItemToSyncAndDb(nametable, '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)
console.log('state.todos', state.todos)
@@ -826,8 +569,8 @@ namespace Actions {
tools.notifyarraychanged(state.todos[indcat][itemdragend.oldIndex])
if (itemdragend.field !== 'priority') {
let precind = itemdragend.newIndex - 1
let nextind = itemdragend.newIndex + 1
const precind = itemdragend.newIndex - 1
const 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)) {
@@ -854,7 +597,6 @@ namespace Actions {
}
}
// 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)
@@ -871,15 +613,8 @@ namespace Actions {
}
export const actions = {
dbInsertTodo: b.dispatch(dbInsertTodo),
dbSaveTodo: b.dispatch(dbSaveTodo),
dbLoadTodo: b.dispatch(dbLoadTodo),
dbdeleteItem: b.dispatch(dbdeleteItem),
updatefromIndexedDbToStateTodo: b.dispatch(updatefromIndexedDbToStateTodo),
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)
@@ -887,7 +622,6 @@ namespace Actions {
}
// Module
const TodosModule = {
get state() {

View File

@@ -19,7 +19,6 @@ const state: IUserState = {
userId: '',
email: '',
username: '',
idapp: process.env.APP_ID,
password: '',
lang: '',
repeatPassword: '',
@@ -28,6 +27,7 @@ const state: IUserState = {
categorySel: 'personal',
servercode: 0,
x_auth_token: '',
isLogged: false,
isAdmin: false
}
@@ -79,14 +79,14 @@ namespace Getters {
},
get getServerCode() {
return getServerCode()
}
},
// get fullName() { return fullName();},
}
}
namespace Mutations {
function authUser(state: IUserState, data: IUserState ) {
function authUser(state: IUserState, data: IUserState) {
state.userId = data.userId
state.username = data.username
if (data.verified_email) {
@@ -221,8 +221,6 @@ namespace Actions {
async function resetpwd(context, paramquery: IUserState) {
const usertosend = {
keyappid: process.env.PAO_APP_ID,
idapp: process.env.APP_ID,
email: paramquery.email,
password: paramquery.password,
tokenforgot: paramquery.tokenforgot
@@ -245,8 +243,6 @@ namespace Actions {
async function requestpwd(context, paramquery: IUserState) {
const usertosend = {
keyappid: process.env.PAO_APP_ID,
idapp: process.env.APP_ID,
email: paramquery.email
}
console.log(usertosend)
@@ -265,8 +261,6 @@ namespace Actions {
async function vreg(context, paramquery: ILinkReg) {
const usertosend = {
keyappid: process.env.PAO_APP_ID,
idapp: process.env.APP_ID,
idlink: paramquery.idlink
}
console.log(usertosend)
@@ -301,12 +295,10 @@ namespace Actions {
return bcrypt.hash(authData.password, bcrypt.genSaltSync(12))
.then((hashedPassword: string) => {
const usertosend = {
keyappid: process.env.PAO_APP_ID,
lang: mylang,
email: authData.email,
password: String(hashedPassword),
username: authData.username,
idapp: process.env.APP_ID
}
console.log(usertosend)
@@ -371,7 +363,7 @@ namespace Actions {
try {
if ('serviceWorker' in navigator) {
sub = await navigator.serviceWorker.ready
.then(function(swreg) {
.then(function (swreg) {
console.log('swreg')
const sub = swreg.pushManager.getSubscription()
return sub
@@ -393,8 +385,6 @@ namespace Actions {
const usertosend = {
username: authData.username,
password: authData.password,
idapp: process.env.APP_ID,
keyappid: process.env.PAO_APP_ID,
lang: state.lang,
subs: sub,
options
@@ -487,13 +477,7 @@ namespace Actions {
await GlobalStore.actions.clearDataAfterLogout()
const usertosend = {
keyappid: process.env.PAO_APP_ID,
idapp: process.env.APP_ID
}
console.log(usertosend)
const riscall = await Api.SendReq('/users/me/token', 'DELETE', usertosend)
const riscall = await Api.SendReq('/users/me/token', 'DELETE', null)
.then((res) => {
console.log(res)
}).then(() => {
@@ -510,6 +494,7 @@ namespace Actions {
async function setGlobal(loggedWithNetwork: boolean) {
state.isLogged = true
console.log('state.isLogged')
GlobalStore.mutations.setleftDrawerOpen(localStorage.getItem(tools.localStorage.leftDrawerOpen) === 'true')
GlobalStore.mutations.setCategorySel(localStorage.getItem(tools.localStorage.categorySel))
@@ -523,7 +508,7 @@ namespace Actions {
async function autologin_FromLocalStorage(context) {
try {
// console.log('*** autologin_FromLocalStorage ***')
console.log('*** autologin_FromLocalStorage ***')
// INIT
UserStore.state.lang = tools.getItemLS(tools.localStorage.lang)
@@ -566,6 +551,22 @@ namespace Actions {
}
}
/*
async function refreshUserInfos(){
let {token, refresh_token} = JWT.fetch();
if (!!token) {
try {
let { data } = await Api.checkSession({token, refresh_token});
JWT.set(data);
let userData = await jwtDecode(data.token);
LoginModule.mutations.updateUserInfos({userData, token: data.token});
} catch(e) {
Mutations.mutations.disconnectUser();
}
}
}
*/
export const actions = {
autologin_FromLocalStorage: b.dispatch(autologin_FromLocalStorage),
logout: b.dispatch(logout),

View File

@@ -1,6 +1,6 @@
import Api from '@api'
import { ITodo } from '@src/model'
import { Todos, UserStore } from '@store'
import { GlobalStore, Todos, UserStore } from '@store'
import globalroutines from './../../globalroutines/index'
import { costanti } from './costanti'
import Quasar from 'quasar'
@@ -12,6 +12,7 @@ export interface INotify {
}
export const tools = {
allTables: ['todos', 'categories', 'sync_post_todos', 'sync_patch_todos', 'delete_todos', 'config', 'swmsg'],
EMPTY: 0,
CALLING: 10,
OK: 20,
@@ -48,12 +49,12 @@ export const tools = {
},
DB: {
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'
CMD_SYNC: 'sync-',
CMD_SYNC_NEW: 'sync-new-',
CMD_DELETE: 'sync-delete-',
TABLE_SYNC_POST: 'sync_post_',
TABLE_SYNC_PATCH: 'sync_patch_',
TABLE_DELETE: 'delete_'
},
MenuAction: {
@@ -386,7 +387,7 @@ export const tools = {
json2array(json) {
const result = []
const keys = Object.keys(json)
keys.forEach(function (key) {
keys.forEach((key) => {
result.push(json[key])
})
return result
@@ -395,20 +396,20 @@ export const tools = {
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)
// 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 ((cmd === tools.DB.CMD_SYNC_NEW) || (cmd === tools.DB.CMD_DELETE)) {
cmdSw = tools.DB.CMD_SYNC
}
if ('serviceWorker' in navigator) {
return await navigator.serviceWorker.ready
.then(function (sw) {
.then((sw) => {
// console.log('---------------------- navigator.serviceWorker.ready')
return globalroutines(null, 'write', table, item, id)
.then(function (id) {
.then((id) => {
// console.log('id', id)
const sep = '|'
@@ -427,14 +428,14 @@ export const tools = {
return Api.syncAlternative(multiparams)
// }
})
.then(function () {
.then(() => {
let data = null
if (msg !== '') {
data = { message: msg, position: 'bottom', timeout: 3000 }
}
return data
})
.catch(function (err) {
.catch((err) => {
console.error('Errore in globalroutines', table, err)
})
})
@@ -442,13 +443,104 @@ export const tools = {
}
},
async dbInsertSave(call, item, method) {
let ret = true
if (!('serviceWorker' in navigator)) {
console.log('dbInsertSave', item, method)
if (UserStore.state.userId === '') {
return false
} // Login not made
call = '/' + call
if (method !== 'POST') {
call += '/' + item._id
}
console.log('SAVE: ', item)
ret = await Api.SendReq(call, method, item)
.then((res) => {
console.log('dbInsertSave ', call, 'to the Server', res.data)
return (res.status === 200)
})
.catch((error) => {
UserStore.mutations.setErrorCatch(error)
return false
})
}
return ret
},
async dbdeleteItem(call, item) {
if (!('serviceWorker' in navigator)) {
// console.log('dbdeleteItem', item)
if (UserStore.state.userId === '') {
return false
} // Login not made
call = '/' + call
const res = await Api.SendReq(call + item._id, 'DELETE', item)
.then((res) => {
console.log('dbdeleteItem to the Server')
return res
})
.catch((error) => {
UserStore.mutations.setErrorCatch(error)
return UserStore.getters.getServerCode
})
return res
}
},
async cmdToSyncAndDbTable(cmd, nametab: string, table, method, item: ITodo, id, msg: String) {
// Send to Server to Sync
console.log('cmdToSyncAndDb', 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) {
if ((method === 'POST') || (method === 'PATCH')) {
await tools.dbInsertSave(nametab, item, method)
}
} else if (cmd === tools.DB.CMD_DELETE) {
await tools.dbdeleteItem(nametab, item)
}
return risdata
},
deleteItemToSyncAndDb(nametab: string, item, id) {
tools.cmdToSyncAndDbTable(tools.DB.CMD_DELETE, nametab, tools.DB.TABLE_DELETE + nametab, 'DELETE', item, id, '')
},
async saveItemToSyncAndDb(nametab: string, method, item) {
let table = ''
if (method === 'POST')
table = tools.DB.TABLE_SYNC_POST
else if (method === 'PATCH')
table = tools.DB.TABLE_SYNC_PATCH
return await tools.cmdToSyncAndDbTable(tools.DB.CMD_SYNC_NEW, nametab, table + nametab, method, item, 0, '')
},
showNotif(q: any, msg, data?: INotify | null) {
let myicon = data ? data.icon : 'ion-add'
if (!myicon)
if (!myicon) {
myicon = 'ion-add'
}
let mycolor = data ? data.color : 'primary'
if (!mycolor)
if (!mycolor) {
mycolor = 'primary'
}
q.notify({
message: msg,
icon: myicon,
@@ -489,6 +581,136 @@ export const tools = {
getimglogo() {
return 'statics/images/' + process.env.LOGO_REG
},
consolelogpao(strlog, strlog2 = '', strlog3 = '') {
globalroutines(null, 'log', strlog + ' ' + strlog2 + ' ' + strlog3, null)
},
async checkPendingMsg() {
// console.log('checkPendingMsg')
const config = await globalroutines(null, 'read', 'config', null, '1')
// console.log('config', config)
try {
if (config) {
if (!!config[1].stateconn) {
// console.log('config.stateconn', config[1].stateconn)
if (config[1].stateconn !== GlobalStore.state.stateConnection) {
GlobalStore.mutations.setStateConnection(config[1].stateconn)
}
}
}
} catch (e) {
}
return new Promise((resolve, reject) => {
// Check if there is something
return globalroutines(null, 'count', 'swmsg')
.then((count) => {
if (count > 0) {
// console.log('count = ', count)
return resolve(true)
} else {
return resolve(false)
}
})
.catch((e) => {
return reject()
})
})
},
// If something in the call of Service Worker went wrong (Network or Server Down), then retry !
async sendSwMsgIfAvailable() {
let something = false
if ('serviceWorker' in navigator) {
console.log(' -------- sendSwMsgIfAvailable')
const count = await tools.checkPendingMsg()
if (count > 0) {
return await navigator.serviceWorker.ready
.then((sw) => {
return globalroutines(null, 'readall', 'swmsg')
.then((arr_recmsg) => {
if (arr_recmsg.length > 0) {
// console.log('---------------------- 2) navigator (2) .serviceWorker.ready')
let promiseChain = Promise.resolve()
for (const rec of arr_recmsg) {
// console.log(' .... sw.sync.register ( ', rec._id)
// if ('SyncManager' in window) {
// sw.sync.register(rec._id)
// } else {
// #Alternative to SyncManager
promiseChain = promiseChain.then(() => {
return Api.syncAlternative(rec._id)
.then(() => {
something = true
})
})
// }
}
return promiseChain
}
})
})
}
}
return new Promise((resolve, reject) => {
resolve(something)
})
},
async waitAndRefreshData() {
return await Todos.actions.dbLoadTodo({ checkPending: false })
},
async waitAndcheckPendingMsg() {
// await aspettansec(1000)
return await tools.checkPendingMsg()
.then((ris) => {
if (ris) {
// console.log('risPending = ', ris)
return tools.sendSwMsgIfAvailable()
.then((something) => {
if (something) {
if (process.env.DEBUG === '1') {
console.log('something')
}
// Refresh data
return tools.waitAndRefreshData()
}
})
}
})
},
async updatefromIndexedDbToStateTodo(nametab) {
await globalroutines(null, 'updatefromIndexedDbToStateTodo', nametab, null)
.then(() => {
console.log('updatefromIndexedDbToStateTodo! ')
return true
})
},
isLoggedToSystem() {
const tok = tools.getItemLS(tools.localStorage.token)
return !!tok
}
}

View File

@@ -5,6 +5,7 @@ import { IGlobalState } from 'model'
import { Route } from 'vue-router'
import { getStoreBuilder } from 'vuex-typex'
import { IProgressState } from '@types'
export interface RootState {
GlobalModule: IGlobalState