Files
freeplanet/src/store/Modules/GlobalStore.ts

658 lines
18 KiB
TypeScript
Raw Normal View History

import { ICfgServer, IConfig, IGlobalState, IListRoutes, IMenuList, StateConnection } from 'model'
2018-11-17 21:07:07 +01:00
import { storeBuilder } from './Store/Store'
import Vue from 'vue'
import translate from './../../globalroutines/util'
import urlBase64ToUint8Array from '../../js/utility'
import Api from '@api'
2019-03-04 17:28:29 +01:00
import * as Types from '@src/store/Api/ApiTypes'
2019-03-13 01:53:53 +01:00
import { costanti } from '@src/store/Modules/costanti'
import { tools } from '@src/store/Modules/tools'
2019-07-12 14:09:44 +02:00
import { toolsext } from '@src/store/Modules/toolsext'
2019-03-22 15:32:32 +01:00
import * as ApiTables from '@src/store/Modules/ApiTables'
import { CalendarStore, GlobalStore, Projects, Todos, UserStore } from '@store'
2019-03-13 01:53:53 +01:00
import messages from '../../statics/i18n'
import globalroutines from './../../globalroutines/index'
2019-05-02 16:58:36 +02:00
import { cfgrouter } from '../../router/route-config'
import { static_data } from '@src/db/static_data'
import { IDataPass, IParamsQuery } from '@src/model/GlobalStore'
import { serv_constants } from '@src/store/Modules/serv_constants'
import { IUserState } from '@src/model'
import { Calendar } from 'element-ui'
2019-10-10 16:53:33 +02:00
// import { static_data } from '@src/db/static_data'
let stateConnDefault = 'online'
getstateConnSaved()
2019-03-13 01:53:53 +01:00
.then((conn) => {
stateConnDefault = conn
})
2018-11-15 19:48:37 +01:00
const state: IGlobalState = {
conta: 0,
2019-02-13 18:48:30 +01:00
wasAlreadySubscribed: false,
wasAlreadySubOnDb: false,
2018-11-15 19:48:37 +01:00
isLoginPage: false,
layoutNeeded: true,
mobileMode: false,
menuCollapse: true,
leftDrawerOpen: true,
RightDrawerOpen: false,
stateConnection: stateConnDefault,
networkDataReceived: false,
cfgServer: [],
testp1: { contatore: 0, mioarray: [] },
category: 'personal',
posts: [],
2019-03-13 01:53:53 +01:00
menulinks: {},
listatodo: [
{ nametranslate: 'personal', description: 'personal' },
{ nametranslate: 'work', description: 'work' },
{ nametranslate: 'shopping', description: 'shopping' }
],
connData: {
uploading_server: 0,
uploading_indexeddb: 0,
downloading_server: 0,
downloading_indexeddb: 0
2019-03-04 17:28:29 +01:00
},
2019-04-29 01:01:31 +02:00
arrConfig: [],
lastaction: {
table: '',
type: 0,
_id: 0
}
2019-03-04 17:28:29 +01:00
}
async function getConfig(id) {
return await globalroutines(null, 'read', 'config', null, id)
}
async function getstateConnSaved() {
const config = await getConfig(costanti.CONFIG_ID_CFG)
// console.log('config', config)
if (config) {
if (config.length > 1) {
const cfgstateconn = config[1]
return cfgstateconn.stateconn
} else {
return 'online'
}
2019-03-04 17:28:29 +01:00
} else {
return 'offline'
}
2018-11-15 19:48:37 +01:00
}
const b = storeBuilder.module<IGlobalState>('GlobalModule', state)
// Getters
namespace Getters {
2019-03-13 01:53:53 +01:00
const conta = b.read((state) => state.conta, 'conta')
const listatodo = b.read((state) => state.listatodo, 'listatodo')
const category = b.read((state) => state.category, 'category')
2019-03-13 01:53:53 +01:00
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')
2019-03-04 17:28:29 +01:00
2019-03-13 01:53:53 +01:00
const getConfigbyId = b.read((state) => (id) => state.arrConfig.find((item) => item._id === id), 'getConfigbyId')
const getConfigStringbyId = b.read((state) => (params) => {
const config = state.arrConfig.find((item) => item._id === params.id)
2019-03-04 17:28:29 +01:00
if (config) {
return config.value
} else {
return params.default
2019-03-04 17:28:29 +01:00
}
}, 'getConfigStringbyId')
2019-03-13 01:53:53 +01:00
const showtype = b.read((state) => {
2019-03-04 17:28:29 +01:00
// const config = state.arrConfig.find(item => item._id === cat + costanti.CONFIG_ID_SHOW_TYPE_TODOS)
2019-03-13 01:53:53 +01:00
const config = state.arrConfig.find((item) => item._id === costanti.CONFIG_ID_SHOW_TYPE_TODOS)
if (config) {
2019-03-04 17:28:29 +01:00
return config.value
2019-03-13 01:53:53 +01:00
}
else {
2019-03-04 17:28:29 +01:00
return ''
2019-03-13 01:53:53 +01:00
}
2019-03-04 17:28:29 +01:00
}, 'showtype')
2019-03-13 01:53:53 +01:00
const getmenu = b.read((state) => {
// console.log('getmenu', cfgrouter.getmenu())
state.menulinks = {
Dashboard: {
2019-05-02 16:58:36 +02:00
routes: cfgrouter.getmenu(),
show: true
}
}
2019-03-22 18:49:38 +01:00
2019-03-13 01:53:53 +01:00
return state.menulinks
2019-04-25 00:30:13 +02:00
// console.log('state.menulinks', state.menulinks)
2019-03-13 01:53:53 +01:00
}, 'getmenu')
2019-04-11 17:40:41 +02:00
const t = b.read((state) => (params) => {
const msg = params.split('.')
2019-07-12 14:09:44 +02:00
const lang = toolsext.getLocale()
2019-04-11 17:40:41 +02:00
const stringa = messages[lang]
let ris = stringa
msg.forEach((param) => {
ris = ris[param]
})
return ris
}, 't')
2018-11-15 19:48:37 +01:00
export const getters = {
get testpao1_getter_contatore() {
return testpao1_getter_contatore()
},
get testpao1_getter_array() {
return testpao1_getter_array()
},
get conta() {
return conta()
},
get listaTodo() {
return listatodo()
},
get category() {
return category()
},
2019-03-04 17:28:29 +01:00
get getConfigbyId() {
return getConfigbyId()
},
get getConfigStringbyId() {
return getConfigStringbyId()
},
get showtype() {
return showtype()
},
2019-03-13 01:53:53 +01:00
get getmenu() {
return getmenu()
},
2019-04-11 17:40:41 +02:00
get t() {
return t()
},
get isOnline() {
// console.log('*********************** isOnline')
return state.stateConnection === 'online'
},
get isNewVersionAvailable() {
// console.log('state.cfgServer', state.cfgServer)
2019-03-13 01:53:53 +01:00
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)
return serversrec.valore !== process.env.APP_VERSION
2019-03-13 01:53:53 +01:00
} else {
return false
2019-03-13 01:53:53 +01:00
}
}
2018-11-15 19:48:37 +01:00
}
}
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])
}
2019-03-04 17:28:29 +01:00
function NewArray(state: IGlobalState, newarr: ICfgServer[]) {
state.testp1.mioarray = newarr
}
2019-03-04 17:28:29 +01:00
function setPaoArray_Delete(state: IGlobalState) {
state.testp1.mioarray.pop()
}
2018-11-15 19:48:37 +01:00
function setConta(state: IGlobalState, num: number) {
state.conta = num
}
function setleftDrawerOpen(state: IGlobalState, bool: boolean) {
state.leftDrawerOpen = bool
}
function setCategorySel(state: IGlobalState, cat: string) {
state.category = cat
}
function setStateConnection(state: IGlobalState, stateconn: StateConnection) {
if (state.stateConnection !== stateconn) {
console.log('INTERNET ', stateconn)
state.stateConnection = stateconn
}
}
2019-03-04 17:28:29 +01:00
function saveConfig(state: IGlobalState, data: IConfig) {
let dataout
// this.$set(dataout, data.value, {'value': 'default value'})
return globalroutines(null, 'write', 'config', { _id: data._id, value: data.value })
}
2019-02-13 18:48:30 +01:00
function SetwasAlreadySubOnDb(state: IGlobalState, subscrib: boolean) {
state.wasAlreadySubOnDb = subscrib
}
2019-03-04 17:28:29 +01:00
function setShowType(state: IGlobalState, showtype: number) {
console.log('setShowType', showtype)
2019-03-04 17:28:29 +01:00
const config = Getters.getters.getConfigbyId(costanti.CONFIG_ID_SHOW_TYPE_TODOS)
console.log('config', config)
2019-03-04 17:28:29 +01:00
if (config) {
config.value = String(showtype)
2019-03-22 18:49:38 +01:00
Todos.state.showtype = parseInt(config.value, 10)
} else {
Todos.state.showtype = showtype
2019-03-04 17:28:29 +01:00
}
console.log('Todos.state.showtype', Todos.state.showtype)
GlobalStore.mutations.saveConfig({ _id: costanti.CONFIG_ID_SHOW_TYPE_TODOS, value: String(showtype) })
2019-03-04 17:28:29 +01:00
}
function getListByTable(table): any[] {
if (table === 'myevents')
return CalendarStore.state.eventlist
else if (table === 'operators')
return CalendarStore.state.operators
else if (table === 'wheres')
return CalendarStore.state.wheres
else if (table === 'bookings')
return CalendarStore.state.bookedevent
else if (table === 'users')
return UserStore.state.usersList
else
return null
}
function UpdateValuesInMemory(mystate: IGlobalState, mydata: IDataPass) {
const id = mydata.id
const table = mydata.table
try {
const mylist = getListByTable(table)
const myrec = mylist.find((event) => event._id === id)
// console.log('myrec', myrec)
if (myrec) {
for (const [key, value] of Object.entries(mydata.fieldsvalue)) {
console.log('key', value, myrec[key])
myrec[key] = value
}
}
} catch (e) {
console.error(e)
}
}
2018-11-15 19:48:37 +01:00
export const mutations = {
setConta: b.commit(setConta),
setleftDrawerOpen: b.commit(setleftDrawerOpen),
setCategorySel: b.commit(setCategorySel),
2019-02-13 18:48:30 +01:00
setStateConnection: b.commit(setStateConnection),
SetwasAlreadySubOnDb: b.commit(SetwasAlreadySubOnDb),
2019-03-04 17:28:29 +01:00
saveConfig: b.commit(saveConfig),
setPaoArray: b.commit(setPaoArray),
setPaoArray_Delete: b.commit(setPaoArray_Delete),
2019-03-04 17:28:29 +01:00
NewArray: b.commit(NewArray),
setShowType: b.commit(setShowType),
UpdateValuesInMemory: b.commit(UpdateValuesInMemory)
2018-11-15 19:48:37 +01:00
}
}
namespace Actions {
async function setConta(context, num: number) {
2018-11-15 19:48:37 +01:00
Mutations.mutations.setConta(num)
}
function createPushSubscription(context) {
console.log('createPushSubscription')
2019-02-13 18:48:30 +01:00
// If Already subscribed, don't send to the Server DB
// if (state.wasAlreadySubOnDb) {
// // console.log('wasAlreadySubOnDb!')
// return
// }
2019-02-13 18:48:30 +01:00
if (!static_data.functionality.PWA)
return
if (!('serviceWorker' in navigator)) {
return
}
if (!('PushManager' in window)) {
return
}
2019-03-04 18:48:07 +01:00
// console.log('createPushSubscription')
let reg
const mykey = process.env.PUBLICKEY_PUSH
const mystate = state
return navigator.serviceWorker.ready
.then((swreg) => {
reg = swreg
return swreg.pushManager.getSubscription()
})
.then((subscription) => {
2019-02-13 18:48:30 +01:00
mystate.wasAlreadySubscribed = !(subscription === null)
if (mystate.wasAlreadySubscribed) {
// console.log('User is already SAVED Subscribe on DB!')
// return null
return subscription
} else {
// Create a new subscription
console.log('Create a new subscription')
2019-03-13 01:53:53 +01:00
const convertedVapidPublicKey = urlBase64ToUint8Array(mykey)
return reg.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: convertedVapidPublicKey
})
}
})
.then((newSub) => {
2019-02-13 18:48:30 +01:00
saveNewSubscriptionToServer(context, newSub)
})
.catch((err) => {
console.log('ERR createPushSubscription:', err)
})
}
// Calling the Server to Save in the MongoDB the Subscriber
function saveNewSubscriptionToServer(context, newSub) {
2019-02-13 18:48:30 +01:00
// If already subscribed, exit
2019-10-10 16:53:33 +02:00
if (true) {
return
}
2019-03-13 01:53:53 +01:00
if (!newSub) {
2019-02-13 18:48:30 +01:00
return
2019-03-13 01:53:53 +01:00
}
2019-02-13 18:48:30 +01:00
2019-10-10 16:53:33 +02:00
if (UserStore.getters.isUserInvalid) {
return
}
// console.log('saveSubscriptionToServer: ', newSub)
2019-02-13 18:48:30 +01:00
// console.log('context', context)
let options = null
// If is not already stored in DB, then show the message to the user.
if (!state.wasAlreadySubscribed) {
options = {
title: translate('notification.title_subscribed'),
content: translate('notification.subscribed'),
openUrl: '/'
}
}
2019-03-13 01:53:53 +01:00
const myres = {
options,
subs: newSub,
others: {
userId: UserStore.state.userId,
access: UserStore.state.tokens[0].access
}
}
return Api.SendReq('/subscribe', 'POST', myres)
2019-03-13 01:53:53 +01:00
.then((res) => {
2019-02-13 18:48:30 +01:00
state.wasAlreadySubscribed = true
state.wasAlreadySubOnDb = true
localStorage.setItem(tools.localStorage.wasAlreadySubOnDb, String(state.wasAlreadySubOnDb))
2019-02-13 18:48:30 +01:00
})
2019-03-13 01:53:53 +01:00
.catch((e) => {
2019-02-13 18:48:30 +01:00
console.log('Error during Subscription!', e)
})
}
async function deleteSubscriptionToServer(context) {
console.log('DeleteSubscriptionToServer: ')
2019-03-15 02:01:03 +01:00
return Api.SendReq('/subscribe/del', 'DELETE', null)
.then((res) => {
})
}
function prova(context) {
// console.log('prova')
// state.testp1.mioarray[state.testp1.mioarray.length - 1].valore = 'VALMODIF';
// let msg = t('notification.title_subscribed')
// console.log('msg', msg)
}
async function clearDataAfterLogout(context) {
console.log('clearDataAfterLogout')
// Clear all data from the IndexedDB
2019-03-28 12:58:34 +01:00
for (const table of ApiTables.allTables()) {
await globalroutines(null, 'clearalldata', table, null)
}
if (static_data.functionality.PWA) {
if ('serviceWorker' in navigator) {
// REMOVE ALL SUBSCRIPTION
console.log('REMOVE ALL SUBSCRIPTION...')
await navigator.serviceWorker.ready.then((reg) => {
console.log('... Ready')
reg.pushManager.getSubscription().then((subscription) => {
console.log(' Found Subscription...')
if (subscription) {
subscription.unsubscribe().then((successful) => {
// You've successfully unsubscribed
console.log('You\'ve successfully unsubscribed')
}).catch((e) => {
// Unsubscription failed
})
}
})
})
}
}
await deleteSubscriptionToServer(context)
}
async function clearDataAfterLoginOnlyIfActiveConnection(context) {
}
async function loadAfterLogin(context) {
// console.log('loadAfterLogin')
actions.clearDataAfterLoginOnlyIfActiveConnection()
2019-03-04 17:28:29 +01:00
state.arrConfig = await globalroutines(null, 'readall', 'config', null)
}
async function saveCfgServerKey(context, dataval: ICfgServer) {
console.log('saveCfgServerKey dataval', dataval)
2019-03-13 01:53:53 +01:00
const ris = await Api.SendReq('/admin/updateval', 'POST', { pairval: dataval })
.then((res) => {
})
}
async function checkUpdates(context) {
console.log('checkUpdates')
// if (UserStore.state.userId === '')
// return false // Login not made
state.networkDataReceived = false
2019-03-13 01:53:53 +01:00
const ris = await Api.SendReq('/checkupdates', 'GET', null)
.then((res) => {
state.networkDataReceived = true
// console.log('******* checkUpdates RES :', res.data.cfgServer)
if (res.data.cfgServer) {
state.cfgServer = [...res.data.cfgServer]
// console.log('res.data.cfgServer', res.data.cfgServer)
}
// console.log('res.data.userslist', res.data.usersList)
if (res.data.usersList) {
UserStore.mutations.setusersList(res.data.usersList)
}
// console.log('********** res', 'state.todos', state.todos, 'checkPending', checkPending)
// After Login will store into the indexedDb...
return res
})
2019-03-13 01:53:53 +01:00
.catch((error) => {
console.log('error checkUpdates', error)
UserStore.mutations.setErrorCatch(error)
return error
})
}
async function loadTable(context, params: IParamsQuery) {
// console.log('loadTable', params)
return await Api.SendReq('/gettable', 'POST', params)
.then((res) => {
// console.table(res)
return res.data
})
.catch((error) => {
console.log('error loadTable', error)
UserStore.mutations.setErrorCatch(error)
return null
})
}
async function saveTable(context, mydata: object) {
// console.log('saveTable', mydata)
return await Api.SendReq('/settable', 'POST', mydata)
.then((res) => {
// console.table(res)
return res.data
})
.catch((error) => {
console.log('error saveTable', error)
UserStore.mutations.setErrorCatch(error)
return null
})
}
async function saveFieldValue(context, mydata: IDataPass) {
console.log('saveFieldValue', mydata)
return await Api.SendReq(`/chval`, 'PATCH', { data: mydata })
.then((res) => {
if (res) {
Mutations.mutations.UpdateValuesInMemory(mydata)
return (res.data.code === serv_constants.RIS_CODE_OK)
} else
return false
})
.catch((error) => {
return false
})
}
async function DeleteRec(context, { table, id }) {
console.log('DeleteRec', id)
return await Api.SendReq('/delrec/' + table + '/' + id, 'DELETE', null)
.then((res) => {
if (res.status === 200) {
if (res.data.code === serv_constants.RIS_CODE_OK) {
return true
}
}
return false
})
.catch((error) => {
console.error(error)
return false
})
}
async function DuplicateRec(context, { table, id }) {
console.log('DuplicateRec', id)
return await Api.SendReq('/duprec/' + table + '/' + id, 'POST', null)
.then((res) => {
if (res.status === 200) {
if (res.data.code === serv_constants.RIS_CODE_OK) {
return res.data.record
}
}
return null
})
.catch((error) => {
console.error(error)
return null
})
}
2018-11-15 19:48:37 +01:00
export const actions = {
setConta: b.dispatch(setConta),
createPushSubscription: b.dispatch(createPushSubscription),
loadAfterLogin: b.dispatch(loadAfterLogin),
clearDataAfterLogout: b.dispatch(clearDataAfterLogout),
clearDataAfterLoginOnlyIfActiveConnection: b.dispatch(clearDataAfterLoginOnlyIfActiveConnection),
prova: b.dispatch(prova),
saveCfgServerKey: b.dispatch(saveCfgServerKey),
checkUpdates: b.dispatch(checkUpdates),
saveFieldValue: b.dispatch(saveFieldValue),
loadTable: b.dispatch(loadTable),
saveTable: b.dispatch(saveTable),
DeleteRec: b.dispatch(DeleteRec),
DuplicateRec: b.dispatch(DuplicateRec)
2018-11-15 19:48:37 +01:00
}
}
const stateGetter = b.state()
2018-11-15 19:48:37 +01:00
// Module
const GlobalModule = {
get state() {
return stateGetter()
},
2019-03-13 01:53:53 +01:00
actions: Actions.actions,
2018-11-15 19:48:37 +01:00
getters: Getters.getters,
2019-03-13 01:53:53 +01:00
mutations: Mutations.mutations
2018-11-15 19:48:37 +01:00
}
export default GlobalModule