First Committ

This commit is contained in:
Paolo Arena
2021-08-31 18:09:59 +02:00
commit 1d6c55807c
299 changed files with 55382 additions and 0 deletions

16
src/store/Api/ApiRoutes.ts Executable file
View File

@@ -0,0 +1,16 @@
const ServerRoutes = {
LOGIN: 'login_check',
TOKEN_REFRESH: 'token/refresh',
SIGNUP: 'register/',
MOVING_LIST: 'announcements',
MOVING_DETAIL: 'announcement/',
MOVING_CREATE: 'announcement',
MOVING_USER_INFOS: 'user/verify',
PARTICIPATION_CREATE: 'participations',
CREATE_NOTE: 'note_user',
MOVERS_LIST: 'movers',
NEW_MOVER: 'mover',
USERS: 'users',
}
export default ServerRoutes

142
src/store/Api/ApiTypes.ts Executable file
View File

@@ -0,0 +1,142 @@
// import { NotificationsStore, LoginStore } from '@store'
export class AxiosSuccess {
public success: any = true
public status: number
public data: any
constructor(data: any, status: number) {
this.data = data
this.status = status
}
}
export class AxiosError {
public success: boolean = false
public status: number = 0
public data: any
public code: any = 0
public msgerr: string = ''
constructor(status: number, data?: any, code?: any, msgerr: string = '') {
this.status = status
this.data = data
this.code = code
this.msgerr = msgerr
if (status !== 401) {
// if (status == 0) message = 'Vérifiez votre connexion Internet';
// NotificationsStore.actions.addNotification({ type: 'warning', message: message })
} else if (data.error && data.error.message !== 'Bad credentials') {
// LoginStore.actions.disconnectRequest()
}
}
public getMsgError() {
if (this.data && this.data.error) return this.data.error.message
return this.msgerr
}
public getMsg() {
try {
if (this.code === 0) {
if (this.data.code) {
return this.data.msg
}
}
} catch (e) {
return ''
}
return ''
}
public getCode() {
if (this.code === 0) {
if (this.data.code) {
return this.data.code
}
}
return this.code
}
}
// export class ApiResponse {
// public success: boolean = true;
// public message?: string;
// public data?: any;
// public type: string;
// constructor(fields: {message?: string, data?: any, type: any, success: boolean}) {
// this.message = fields.message;
// this.type = fields.type;
// this.data = fields.data ? fields.data : {};
// this.success = fields.success;
// }
// yes() {
// return Promise.resolve(this);
// }
// }
export interface IApiResponse {
success: boolean
message?: string
data?: any
type: string
}
export class ApiResponse {
public data?: any
public message?: any
constructor(fields: { message?: string, data?: any, type: any, success: boolean }) {
const returnData: any = {}
returnData.message = fields.message
returnData.type = fields.type
returnData.data = fields.data != null ? fields.data : {}
returnData.success = fields.success
if (fields.success) return <any>Promise.resolve(returnData)
return <any>Promise.reject(returnData)
}
}
export class ApiSuccess extends ApiResponse {
constructor(fields: { message?: string, data?: any } = {}) {
super({
success: true,
type: 'success',
message: fields.message,
data: fields.data,
})
}
}
export class ApiError extends ApiResponse {
constructor(fields: { message?: string, data?: any } = {}) {
super({
success: false,
type: 'error',
message: fields.message,
data: fields.data,
})
}
}
export class ApiWarning extends ApiResponse {
constructor(fields: { message?: string, data?: any } = {}) {
super({
success: false,
type: 'warning',
message: fields.message,
data: fields.data,
})
}
}

22
src/store/Api/Inst-Pao.ts Executable file
View File

@@ -0,0 +1,22 @@
import axios, {
AxiosInstance, AxiosPromise, AxiosResponse, AxiosInterceptorManager,
} from 'axios'
import Api from '@api'
import * as Types from '@src/store/Api/ApiTypes'
async function sendRequest(url: string, method: string, mydata: any) {
if (!process.env.DEBUG) console.log('sendRequest', method, url)
let request
if (method === 'GET') request = Api.get(url, mydata)
else if (method === 'POST') request = Api.post(url, mydata)
else if (method === 'DELETE') request = Api.Delete(url, mydata)
else if (method === 'PUT') request = Api.put(url, mydata)
else if (method === 'PATCH') request = Api.patch(url, mydata)
// @ts-ignore
const req: Promise<Types.AxiosSuccess | Types.AxiosError> = request
return req
}
export default sendRequest

157
src/store/Api/Instance.ts Executable file
View File

@@ -0,0 +1,157 @@
import axios, { AxiosInstance, AxiosResponse } from 'axios'
// import LoginModule from '../Modules/Auth/LoginStore'
import router from '@router'
import { tools } from '@src/store/Modules/tools'
import { toolsext } from '@src/store/Modules/toolsext'
import { serv_constants } from '@src/store/Modules/serv_constants'
import { useGlobalStore } from '@store/globalStore'
import { useUserStore } from '@store/UserStore'
import * as Types from './ApiTypes'
export const API_URL = process.env.MONGODB_HOST
export const axiosInstance: AxiosInstance = axios.create({
baseURL: API_URL,
headers: {
Accept: 'application/json',
},
})
axiosInstance.interceptors.response.use(
(response) => {
if (process.env.DEBUG === '1') console.log(response)
return response
},
(error) => {
const globalStore = useGlobalStore()
// console.log('error', error)
if (error.response) {
if (process.env.DEBUG === '1') console.log('Status = ', error.response.status)
console.log('Request Error: ', error.response)
if (error.response.status !== 0) {
globalStore.setStateConnection('online')
} else {
globalStore.setStateConnection('offline')
}
} else {
globalStore.setStateConnection('offline')
}
return Promise.reject(error)
},
)
export const addAuthHeaders = () => {
// axiosInstance.defaults.headers.Authorization = `Bearer ${LoginModule.userInfos.userToken}`
}
export const removeAuthHeaders = () => {
delete axiosInstance.defaults.headers.Authorization
}
async function Request(type: string, path: string, payload: any): Promise<Types.AxiosSuccess | Types.AxiosError | undefined> {
let ricevuto = false
const userStore = useUserStore()
const globalStore = useGlobalStore()
try {
if (tools.isDebug()) console.log('Axios Request', path, type, tools.notshowPwd(payload))
let response: AxiosResponse
if (type === 'post' || type === 'put' || type === 'patch') {
response = await axiosInstance[type](path, payload, {
headers: {
'Content-Type': 'application/json',
'x-auth': userStore.x_auth_token,
},
})
ricevuto = true
// console.log('Request Response: ', response)
// console.log(new Types.AxiosSuccess(response.data, response.status))
const setAuthToken = (path === '/updatepwd')
// console.log('--------- 0 ')
if (response && (response.status === 200)) {
let x_auth_token = ''
try {
if (setAuthToken || (path === '/users/login')) {
x_auth_token = String(response.headers['x-auth'])
if (x_auth_token === '') {
userStore.setServerCode(toolsext.ERR_AUTHENTICATION)
}
if (setAuthToken) {
userStore.UpdatePwd(x_auth_token)
localStorage.setItem(toolsext.localStorage.token, x_auth_token)
}
userStore.setAuth(x_auth_token)
localStorage.setItem(toolsext.localStorage.token, x_auth_token)
}
globalStore.setStateConnection(ricevuto ? 'online' : 'offline')
userStore.setServerCode(tools.OK)
} catch (e) {
if (setAuthToken) {
userStore.setServerCode(toolsext.ERR_AUTHENTICATION)
userStore.setAuth('')
}
globalStore.setStateConnection(ricevuto ? 'online' : 'offline')
return Promise.reject(new Types.AxiosError(serv_constants.RIS_CODE__HTTP_FORBIDDEN_INVALID_TOKEN, null, toolsext.ERR_AUTHENTICATION))
}
}
return new Types.AxiosSuccess(response.data, response.status)
} if (type === 'get' || type === 'delete') {
// @ts-ignore
response = await axiosInstance[type](path, {
params: payload,
headers: {
'Content-Type': 'application/json',
'x-auth': userStore.x_auth_token,
},
})
ricevuto = true
return new Types.AxiosSuccess(response.data, response.status)
} if (type === 'postFormData') {
response = await axiosInstance.post(path, payload, {
headers: {
'Content-Type': 'multipart/form-data',
'x-auth': userStore.x_auth_token,
},
})
ricevuto = true
return new Types.AxiosSuccess(response.data, response.status)
}
} catch (error) {
setTimeout(() => {
globalStore.connData.uploading_server = (globalStore.connData.uploading_server === 1) ? -1 : globalStore.connData.uploading_server
globalStore.connData.downloading_server = (globalStore.connData.downloading_server === 1) ? -1 : globalStore.connData.downloading_server
}, 1000)
if (process.env.DEV) {
console.log('ERROR using', path)
// console.log('Error received: ', error)
// console.log('ricevuto=', ricevuto)
console.log('error.response=', error.response)
}
let mycode = 0
if (!ricevuto) {
mycode = toolsext.ERR_SERVERFETCH
userStore.setServerCode(toolsext.ERR_SERVERFETCH)
} else {
mycode = toolsext.ERR_GENERICO
userStore.setServerCode(toolsext.ERR_GENERICO)
}
if (error.response) {
if (error.response.data && error.response.data.code) {
mycode = error.response.data.code
userStore.setServerCode(mycode)
}
return Promise.reject(new Types.AxiosError(error.response.status, error.response.data, error.response.data.code))
}
return Promise.reject(new Types.AxiosError(0, null, mycode, error))
}
}
export default Request

221
src/store/Api/index.ts Executable file
View File

@@ -0,0 +1,221 @@
import { useRouter } from 'vue-router'
import { useGlobalStore } from '@store/globalStore'
import { useUserStore } from '@store/UserStore'
export * from './ApiTypes'
import axios from 'axios'
export { addAuthHeaders, removeAuthHeaders, API_URL } from './Instance'
// import {AlgoliaSearch} from './AlgoliaController'
import Paths from '@paths'
import { tools } from '@src/store/Modules/tools'
import { toolsext } from '@src/store/Modules/toolsext'
import { serv_constants } from '@src/store/Modules/serv_constants'
import router from '@router'
import * as Types from '@src/store/Api/ApiTypes'
import { costanti } from '@src/store/Modules/costanti'
import * as ApiTables from '@src/store/Modules/ApiTables'
import sendRequest from './Inst-Pao'
import Request from './Instance'
import globalroutines from '../../globalroutines/index'
function ReceiveResponsefromServer(tablesync: string, nametab: string, method: string, risdata: any) {
// console.log('ReceiveResponsefromServer', nametab, method, risdata)
if (risdata) {
// Updated somw data after Server arrived data.
if (method === 'PATCH') {
if (nametab === 'projects') {
if (risdata.projectris) {
const copyrec = tools.jsonCopy(risdata.projectris)
// +*Todo conv: Projects.updateProject({ objproj: copyrec })
}
}
}
}
}
// const algoliaApi = new AlgoliaSearch()
export namespace ApiTool {
export async function post(path: string, payload?: any) {
const globalStore = useGlobalStore()
globalStore.connData.downloading_server = 1
globalStore.connData.uploading_server = 1
return Request('post', path, payload)
}
export async function postFormData(path: string, payload?: any) {
const globalStore = useGlobalStore()
globalStore.connData.uploading_server = 1
globalStore.connData.downloading_server = 1
return Request('postFormData', path, payload)
}
export async function get(path: string, payload?: any) {
const globalStore = useGlobalStore()
globalStore.connData.downloading_server = 1
globalStore.connData.uploading_server = 0
return Request('get', path, payload)
}
export async function put(path: string, payload?: any) {
const globalStore = useGlobalStore()
globalStore.connData.uploading_server = 1
return Request('put', path, payload)
}
export async function patch(path: string, payload?: any) {
const globalStore = useGlobalStore()
globalStore.connData.uploading_server = 1
return Request('patch', path, payload)
}
export async function Delete(path: string, payload: any) {
const globalStore = useGlobalStore()
globalStore.connData.uploading_server = 1
return Request('delete', path, payload)
}
export async function checkSession({ token, refresh_token }: any) {
return axios.post(process.env.API_URL + Paths.TOKEN_REFRESH, {
refresh_token,
}, {
headers: {
Authorization: `Bearer ${token}`,
},
})
}
export async function SendReq(url: string, method: string, mydata: any, setAuthToken: boolean = false): Promise<Types.AxiosSuccess | Types.AxiosError> {
const mydataout = {
...mydata,
keyappid: process.env.PAO_APP_ID,
idapp: process.env.APP_ID,
}
// console.log('mydata', mydata)
const userStore = useUserStore()
const globalStore = useGlobalStore()
const $router = useRouter()
userStore.setServerCode(tools.EMPTY)
userStore.setResStatus(0)
return new Promise((resolve, reject) => sendRequest(url, method, mydataout)
.then((res) => {
// console.log('res', res)
setTimeout(() => {
if (method === 'get') {
globalStore.connData.downloading_server = 0
} else {
globalStore.connData.uploading_server = 0
globalStore.connData.downloading_server = 0
}
}, 1000)
if (res.status) {
userStore.setResStatus(res.status)
if (res.status === serv_constants.RIS_CODE__HTTP_FORBIDDEN_INVALID_TOKEN) {
// Forbidden
// You probably is connectiong with other page...
userStore.setServerCode(toolsext.ERR_AUTHENTICATION)
userStore.setAuth('')
$router.push('/signin')
return reject({ code: toolsext.ERR_AUTHENTICATION })
}
}
return resolve(res)
})
.catch((error) => {
setTimeout(() => {
if (method === 'get') {
globalStore.connData.downloading_server = -1
} else {
globalStore.connData.uploading_server = -1
globalStore.connData.downloading_server = -1
}
}, 1000)
console.log('error', error)
return reject(error)
}))
}
export async function syncAlternative(mystrparam: string) {
// console.log('[ALTERNATIVE Background syncing', mystrparam)
const multiparams = mystrparam.split('|')
if (multiparams) {
if (multiparams.length > 3) {
const cmd = multiparams[0]
const tablesync = multiparams[1]
const nametab = multiparams[2]
const method = multiparams[3]
// const token = multiparams[3]
if (cmd === ApiTables.DB.CMD_SYNC) {
let errorfromserver = false
let lettoqualcosa = false
// console.log('A1) INIZIO.............................................................')
return globalroutines(null, 'readall', tablesync, null)
.then((alldata) => {
if (alldata === undefined) {
console.log('alldata NON DEFINITA')
return true
}
const myrecs = [...alldata]
const promises = myrecs.map((rec) => {
let link = `/${ApiTables.getLinkByTableName(nametab)}`
if (method !== 'POST') {
link += `/${rec._id}`
}
console.log('----------------------- LEGGO QUALCOSA ', link)
// Insert/Delete/Update table to the server
return SendReq(link, method, rec)
.then((ris) => {
ReceiveResponsefromServer(tablesync, nametab, method, ris.data)
lettoqualcosa = true
return globalroutines(null, 'delete', tablesync, null, rec._id)
})
.then(() => {
return globalroutines(null, 'delete', 'swmsg', null, mystrparam)
}).catch((err) => {
if (err.msgerr) {
if (err.msgerr.message.includes('Failed to fetch') || err.msgerr.message.includes('Network Error')) {
errorfromserver = true
}
}
console.log(' [Alternative] !!!!!!!!!!!!!!! Error while sending data', err, errorfromserver, 'lettoqualcosa', lettoqualcosa)
if (!errorfromserver) {
return globalroutines(null, 'delete', 'swmsg', null, mystrparam)
}
})
})
// CALL ALL THE PROMISES
return Promise.all(promises).then(() => (errorfromserver && !lettoqualcosa)).catch((err) => (errorfromserver && !lettoqualcosa))
}).catch((error) => {
console.log('¨¨¨¨¨¨¨¨¨¨¨¨¨¨ errorfromserver:', errorfromserver, error)
return (errorfromserver && !lettoqualcosa)
})
.then((error) => {
const mystate = (error || errorfromserver) ? 'offline' : 'online'
const globalStore = useGlobalStore()
globalStore.setStateConnection(mystate)
globalStore.saveConfig({ _id: costanti.CONFIG_ID_STATE_CONN, value: mystate })
})
}
}
}
return null
}
}
export default ApiTool

492
src/store/Modules/ApiTables.ts Executable file
View File

@@ -0,0 +1,492 @@
import Api from '@api'
import { ITodo } from '@src/model'
import { tools } from '@src/store/Modules/tools'
import { toolsext } from '@src/store/Modules/toolsext'
import { useUserStore } from '@store/UserStore'
import { serv_constants } from '@store/Modules/serv_constants'
import { costanti } from '@store/Modules/costanti'
import { useGlobalStore } from '@store/globalStore'
import globalroutines from '../../globalroutines/index'
export function getLinkByTableName(nametable: string) {
if (nametable === 'todos') {
return 'todos'
}
if (nametable === 'projects') {
return 'projects'
}
return ''
}
export const DB = {
CMD_SYNC: 'sync',
CMD_SYNC_NEW: 'sync-new',
CMD_DELETE: 'sync-delete',
CMD_HIDE: 'sync-hide',
TABLE_SYNC_POST: 'sync_post_',
TABLE_SYNC_PATCH: 'sync_patch_',
TABLE_DELETE: 'delete_',
TABLE_HIDE: 'hide_',
}
export function allTables() {
/* const myarr = OtherTables
for (const tab of costanti.MainTables) {
for (const method of costanti.allMethod) {
myarr.push(method + tab)
}
} */
return costanti.OtherTables
}
async function updatefromIndexedDbToState(nametab: string) {
await globalroutines(null, 'updatefromIndexedDbToState', nametab, null)
.then(() => {
console.log('updatefromIndexedDbToState! ')
return true
})
}
async function checkPendingMsg() {
// console.log('checkPendingMsg')
const globalStore = useGlobalStore()
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.stateConnection) {
globalStore.setStateConnection(config[1].stateconn)
}
}
}
} catch (e) {
// ...
}
return new Promise((resolve, reject) => globalroutines(null, 'count', 'swmsg')
.then((count) => {
if (count > 0) {
return resolve(true)
}
return resolve(false)
}).catch(() => reject()))
}
function useServiceWorker() {
return false // return 'serviceWorker' in navigator
}
// If something in the call of Service Worker went wrong (Network or Server Down), then retry !
async function sendSwMsgIfAvailable() {
let something = false
if (useServiceWorker()) {
console.log(' -------- sendSwMsgIfAvailable')
const count = await checkPendingMsg()
if (count) {
return navigator.serviceWorker.ready
.then(() => 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) {
// #Alternative to SyncManager
promiseChain = promiseChain.then(() => Api.syncAlternative(rec._id)
.then(() => {
//++Todo conv: something = true
}))
}
return promiseChain
}
return null
}))
}
}
return new Promise((resolve, reject) => {
resolve(something)
})
}
export async function waitAndRefreshData() {
// ++Todo: conv
/* await Projects.actions.dbLoad({ checkPending: false, onlyiffirsttime: false })
return await Todos.actions.dbLoad({ checkPending: false })
*/
return null
}
export async function waitAndcheckPendingMsg() {
// await aspettansec(1000)
const globalStore = useGlobalStore()
return checkPendingMsg()
.then((ris) => {
if (ris) {
if (!globalStore.isOnline()) { // If is Offline, then check
}
return sendSwMsgIfAvailable()
.then((something) => {
if (something) {
if (process.env.DEBUG === '1') {
console.log('something')
}
// Refresh data
return waitAndRefreshData()
}
return null
})
}
return null
})
}
async function dbInsertSave(call: string, item: any, method: string) {
let ret = true
const userStore = useUserStore()
if (!useServiceWorker()) {
console.log('dbInsertSave', item, method)
if (userStore.isUserInvalid) {
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: any) => {
console.log('dbInsertSave ', call, 'to the Server', res.data)
return (res.status === 200)
})
.catch((error: any) => {
userStore.setErrorCatch(error)
return false
})
}
return ret
}
async function dbDeleteItem(call: string, item: any) {
let res = true
const userStore = useUserStore()
if (!useServiceWorker()) {
// console.log('dbdeleteItem', item)
if (userStore.isUserInvalid) {
return false
} // Login not made
call = `/${call}`
res = await Api.SendReq(`${call}/${item._id}`, 'DELETE', null)
.then((myres: any) => {
console.log('dbdeleteItem to the Server')
// tools.showPositiveNotif(this.$q, 'Riga cancellata')
return myres
})
.catch((error: any) => {
userStore.setErrorCatch(error)
return userStore.getServerCode
})
return res
}
return res
}
async function dbHideItem(call: string, item: any) {
const userStore = useUserStore()
if (!useServiceWorker()) {
// console.log('dbdeleteItem', item)
if (userStore.isUserInvalid) {
return false
} // Login not made
item = {
...item,
hide: true,
}
console.log('dbHideItem', item)
call = `/${call}`
return Api.SendReq(`${call + item._id}/true`, 'DELETE', null)
.then((myres: any) => {
console.log('dbHideItem to the Server')
return myres
})
.catch((error: any) => {
userStore.setErrorCatch(error)
return userStore.getServerCode
})
}
return null
}
async function Sync_Execute(cmd: string, tablesync: string, nametab: string, method: string, item: ITodo, id: string, msg: string) {
// Send to Server to Sync
const userStore = useUserStore()
console.log('Sync_Execute', cmd, tablesync, nametab, method, id, msg)
if (nametab === 'todos') {
console.log(' TODO: ', item.descr)
}
let cmdSw = cmd
if ((cmd === DB.CMD_SYNC_NEW) || (cmd === DB.CMD_DELETE) || (cmd === DB.CMD_HIDE)) {
cmdSw = DB.CMD_SYNC
}
// console.log('cmdSw', cmdSw)
// if ('serviceWorker' in navigator) {
// console.log('serviceWorker PRESENTE')
// } else {
// console.log('serviceWorker NON PRESENTE !')
// }
// console.log('---------------------- navigator.serviceWorker.ready')
if (useServiceWorker()) {
return navigator.serviceWorker.ready
.then((sw) => {
globalroutines(null, 'write', tablesync, item, id)
.then((ris) => {
console.log('ris write:', ris)
const sep = '|'
const multiparams = cmdSw + sep + tablesync + sep + nametab + sep + method + sep + userStore.x_auth_token + sep + toolsext.getLocale()
const mymsgkey = {
_id: multiparams,
value: multiparams,
}
/* console.log('*** swmsg')
// if ('SyncManager' in window) {
// console.log(' SENDING... sw.sync.register', multiparams)
// return sw.sync.register(multiparams)
// } else {
*/
return globalroutines(null, 'write', 'swmsg', mymsgkey, multiparams)
.then((ris2) => Api.syncAlternative(multiparams))
.then(() => {
let data = null
if (msg !== '') {
data = { message: msg, position: 'bottom', timeout: 3000 }
}
return data
})
.catch((err) => {
console.error('Errore in globalroutines', tablesync, nametab, err)
})
})
.catch((err) => {
console.error('Errore catch in globalroutines write', tablesync, nametab, err)
})
})
}
}
async function Sync_ExecuteCmd(cmd: string, nametab: string, method: string, item: ITodo, id: string, msg: string) {
// Send to Server to Sync
let tablesync = ''
if (method === 'POST') {
tablesync = DB.TABLE_SYNC_POST + nametab
} else if (method === 'PATCH') {
tablesync = DB.TABLE_SYNC_PATCH + nametab
} else if (method === 'DELETE') {
tablesync = DB.TABLE_DELETE + nametab
} else if (method === 'HIDE') {
tablesync = DB.TABLE_HIDE + nametab
}
const risdata = await Sync_Execute(cmd, tablesync, nametab, method, item, id, msg)
let ris = false
if (cmd === DB.CMD_SYNC_NEW) {
if ((method === 'POST') || (method === 'PATCH')) {
ris = await dbInsertSave(nametab, item, method)
}
} else if (cmd === DB.CMD_DELETE) {
ris = await dbDeleteItem(nametab, item)
} else if (cmd === DB.CMD_HIDE) {
ris = await dbHideItem(nametab, item)
}
return ris
}
export async function Sync_SaveItem(nametab: string, method: string, item: any) {
return Sync_ExecuteCmd(DB.CMD_SYNC_NEW, nametab, method, item, '0', '')
}
export function Sync_DeleteItem(nametab: string, item: any, id: string) {
Sync_ExecuteCmd(DB.CMD_DELETE, nametab, 'DELETE', item, id, '')
}
export function Sync_HideItem(nametab: string, item: any, id: string) {
Sync_ExecuteCmd(DB.CMD_HIDE, nametab, 'HIDE', item, id, '')
}
export async function aftercalling(ris: any, checkPending: boolean, nametabindex: string) {
const userStore = useUserStore()
if (ris.status !== 200) {
if (process.env.DEBUG === '1') {
console.log('ris.status', ris.status)
}
if (ris.status === serv_constants.RIS_CODE__HTTP_FORBIDDEN_INVALID_TOKEN) {
tools.consolelogpao('UNAUTHORIZING... TOKEN EXPIRED... !! ')
} else {
tools.consolelogpao('NETWORK UNREACHABLE ! (Error in fetch)', userStore.getServerCode, ris.status)
}
if (useServiceWorker()) {
// Read all data from IndexedDB Store into Memory
await updatefromIndexedDbToState(nametabindex)
}
} else if (ris.status === tools.OK && checkPending) {
waitAndcheckPendingMsg()
}
}
export function removeitemfromarray(myarray: any, ind: any) {
// console.log('PRIMA todos', todos)
// Delete Item in to Array
if (ind >= 0) {
myarray.splice(ind, 1)
}
// console.log('DOPO todos', todos, 'ind', ind)
}
/*
export async functionfunction testfunc() {
while (true) {
tools.consolelogpao('testfunc')
// console.log('Todos.todos_changed:', Todos.todos_changed)
await tools.aspettansec(5000)
}
}
*/
/*
sendMessageToSW(recdata, method) {
navigator.serviceWorker.controller.postMessage({
type: 'sync',
recdata,
method,
cmd: 'sync-new-todos',
token: userStore.idToken,
lang: userStore.lang
})
}
*/
function setmodifiedIfchanged(recOut: any, recIn: any, field: string) {
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
}
export async function table_ModifyRecord(nametable: string, myitem: any, listFieldsToChange: any, field: string) {
// console.log('table_ModifyRecord ... ', nametable)
if (myitem === null) {
return new Promise<void>((resolve, reject) => {
resolve()
})
}
console.log('--> table_ModifyRecord', nametable, myitem)
if ((field === 'status') && (nametable === 'todos') && (myitem.status === tools.Status.COMPLETED)) {
myitem.completed_at = tools.getDateNow()
}
const myobjsaved = tools.jsonCopy(myitem)
let miorec: any = null
if (useServiceWorker()) {
// get record from IndexedDb
miorec = await globalroutines(null, 'read', nametable, null, myobjsaved._id)
if (miorec === undefined) {
console.log('~~~~~~~~~~~~~~~~~~~~ !!!!!!!!!!!!!!!!!! Record not Found !!!!!! id=', myobjsaved._id)
// Prova cmq a salvarlo sul server
return Sync_SaveItem(nametable, 'PATCH', miorec)
}
listFieldsToChange.forEach((myfield: any) => {
setmodifiedIfchanged(miorec, myobjsaved, myfield)
})
} else {
miorec = myitem
miorec.modified = true
}
console.log(' ... 4 ')
if (miorec.modified) {
console.log(` ${nametable} MODIFICATO! `, miorec.descr, miorec.pos, 'SALVALO SULLA IndexedDB')
miorec.modify_at = tools.getDateNow()
miorec.modified = false
// 1) Permit to Update the Views
tools.notifyarraychanged(miorec)
if (useServiceWorker()) {
// 2) Modify on IndexedDb
console.log('// 2) Modify on IndexedDb', miorec)
return globalroutines(null, 'write', nametable, miorec)
.then((ris) => Sync_SaveItem(nametable, 'PATCH', miorec)) // 3) Modify on the Server (call)
}
return Sync_SaveItem(nametable, 'PATCH', miorec)
}
return null
}
export function table_DeleteRecord(nametable: string, myobjtrov: any, id: any) {
const mymodule: any = tools.getModulesByTable(nametable)
// 1) Delete from the Todos Array
mymodule.deletemyitem(myobjtrov)
// 2) Delete from the IndexedDb
globalroutines(null, 'delete', nametable, null, id)
// 3) Delete from the Server (call)
Sync_DeleteItem(nametable, myobjtrov, id)
}
export function table_HideRecord(nametable: string, myobjtrov: any, id: any) {
const mymodule: any = tools.getModulesByTable(nametable)
// 1) Delete from the Todos Array
mymodule.deletemyitem(myobjtrov)
// 2) Delete from the IndexedDb
globalroutines(null, 'delete', nametable, null, id)
// 3) Hide from the Server (call)
Sync_DeleteItem(nametable, myobjtrov, id)
}

View File

@@ -0,0 +1,79 @@
import { defineStore } from 'pinia'
import { nextTick } from 'vue'
const css = require('@css')
let TIMER: any = null
let TIMEOUT: any = null
let CUT: any = null
export const useProgressBar = defineStore('ProgressBar', {
state: () => ({
percent: 0,
show: false,
canSuccess: true,
duration: 3000,
height: '2px',
color: css.mainStyle,
failedColor: css.red1,
}),
getters: {},
actions: {
start(): void {
if (!this.show) {
clearTimeout(TIMEOUT)
this.show = true
this.canSuccess = true
if (TIMER) {
clearInterval(TIMER)
this.percent = 0
}
CUT = 20000 / Math.floor(this.duration)
TIMER = setInterval(() => {
this.increase(CUT * Math.random())
if (this.percent > 80) {
this.pause()
}
}, 200)
}
},
set(num: number): void {
this.show = true
this.canSuccess = true
this.percent = Math.floor(num)
},
increase(num: number) {
this.percent += Math.floor(num)
},
decrease(num: number) {
this.percent -= Math.floor(num)
},
finish(): void {
this.percent = 100
this.hide()
},
pause() {
clearInterval(TIMER)
},
hide() {
clearInterval(TIMER)
TIMER = null
TIMEOUT = setTimeout(() => {
this.show = false
this.percent = 0
nextTick(() => {
setTimeout(() => {
this.percent = 0
}, 200)
})
}, 500)
},
fail() {
this.canSuccess = false
this.finish()
},
},
})

59
src/store/Modules/costanti.ts Executable file
View File

@@ -0,0 +1,59 @@
export const costanti = {
ShowTypeTask: {
SHOW_LAST_N_COMPLETED: 200,
SHOW_ONLY_TOCOMPLETE: 201,
SHOW_ALL: 202,
},
CONFIG_ID_CFG: '1',
CONFIG_ID_STATE_CONN: '2',
CONFIG_ID_SHOW_TYPE_TODOS: '3',
FuncDialog: {
CANCEL_BOOKING: 1,
},
DRAGULA: false,
TABEVENTS: 'myevents',
NOFIELD: 'nofield',
MAX_PHASES: 5,
OtherTables: ['config', 'swmsg'],
// export const MainTables = ['todos', 'projects']
MainTables: [],
allMethod: ['sync_post_', 'sync_patch_', 'delete_', 'hide_'],
FieldType: {
boolean: 1,
date: 2,
string: 4,
binary: 8,
html: 16,
select: 32,
number: 64,
typeinrec: 128,
multiselect: 256,
password: 512,
listimages: 1024,
exact: 2048,
image: 3000,
nationality: 4096,
intcode: 5000,
multioption: 6000,
onlydate: 7000,
hours: 8000,
},
FieldTypeArr: [
{ label: 'Boolean', value: 1 },
{ label: 'Date', value: 2 },
{ label: 'String', value: 4 },
{ label: 'Binary', value: 8 },
{ label: 'Html', value: 16 },
{ label: 'Select', value: 32 },
{ label: 'Number', value: 64 },
],
}

1310
src/store/Modules/fieldsTable.ts Executable file

File diff suppressed because it is too large Load Diff

180
src/store/Modules/lists.ts Executable file
View File

@@ -0,0 +1,180 @@
export const lists = {
MenuAction: {
CUT: 71,
PASTE: 72,
DELETE: 100,
TOGGLE_EXPIRING: 101,
COMPLETED: 110,
PROGRESS_BAR: 120,
PRIORITY: 130,
SHOW_TASK: 150,
SHOW_POSIZ: 155,
EDIT: 160,
ADD_PROJECT: 200,
THEME: 210,
THEMEBG: 211,
DELETE_RECTABLE: 300,
DUPLICATE_RECTABLE: 310,
DELETE_EVENT: 320,
DELETE_EXTRALIST: 330,
DELETE_USERLIST: 335,
REGALA_INVITATO: 340,
REGALA_INVITANTE: 342,
SOSTITUISCI: 345,
INVIA_MSG_A_DONATORI: 350,
INVIA_MSG_A_FLOTTA: 352,
INVIA_MSG_A_SINGOLO: 355,
DONO_INVIATO: 360,
DONO_RICEVUTO: 370,
AGGIUNGI_NUOVO_IMBARCO: 380,
CANCELLA_IMBARCO: 385,
DAMMI_PRIMO_UTENTE_LIBERO: 390,
CAN_EDIT_TABLE: 400,
SHOW_PREV_REC: 401,
ZOOM_GIA_PARTECIPATO: 510,
},
selectTheme: [
{
id: 1,
label: 'Theme 1',
value: 'red',
},
{
id: 2,
label: 'Theme 2',
value: 'pink',
},
{
id: 3,
label: 'Theme 3',
value: 'purple',
},
{
id: 4,
label: 'Theme 4',
value: 'deep-purple',
},
{
id: 5,
label: 'Theme 5',
value: 'indigo',
},
{
id: 6,
label: 'Theme 6',
value: 'blue',
},
{
id: 7,
label: 'Theme 7',
value: 'green',
},
{
id: 8,
label: 'Theme 8',
value: 'orange',
},
{
id: 9,
label: 'Theme 9',
value: 'brown',
},
{
id: 10,
label: 'Theme 10',
value: 'black',
},
{
id: 11,
label: 'Theme 11',
value: 'white',
},
],
selectPriority: {
it: [
{
id: 1,
label: 'Alta',
value: 2,
icon: 'expand_less',
},
{
id: 2,
label: 'Normale',
value: 1,
icon: 'remove',
},
{
id: 3,
label: 'Bassa',
value: 0,
icon: 'expand_more',
}],
es:
[
{
id: 1,
label: 'Alta',
value: 2,
icon: 'expand_less',
},
{
id: 2,
label: 'Normal',
value: 1,
icon: 'remove',
},
{
id: 3,
label: 'Baja',
value: 0,
icon: 'expand_more',
}],
enUs:
[
{
id: 1,
label: 'High',
value: 2,
icon: 'expand_less',
},
{
id: 2,
label: 'Normal',
value: 1,
icon: 'remove',
},
{
id: 3,
label: 'Low',
value: 0,
icon: 'expand_more',
}],
de:
[
{
id: 1,
label: 'High',
value: 2,
icon: 'expand_less',
},
{
id: 2,
label: 'Normal',
value: 1,
icon: 'remove',
},
{
id: 3,
label: 'Low',
value: 0,
icon: 'expand_more',
}],
},
}

View File

@@ -0,0 +1,39 @@
export const serv_constants = {
RIS_CODE_TODO_CREATING_NOTMYUSER: -1001,
RIS_CODE_NOT_MY_USERNAME: -1010,
RIS_CODE_ERR: -99,
RIS_CODE_EMAIL_ALREADY_VERIFIED: -5,
RIS_CODE_EMAIL_VERIFIED: 1,
RIS_CODE_USER_NOT_THIS_APORTADOR: -75,
RIS_CODE_USER_EXTRALIST_NOTFOUND: -70,
RIS_CODE_USERNAME_ALREADY_EXIST: -60,
RIS_CODE_USERNAME_NOT_VALID: -65,
RIS_CODE_EMAIL_ALREADY_EXIST: -50,
RIS_CODE_USER_ALREADY_EXIST: -48,
RIS_CODE_EMAIL_NOT_EXIST: -45,
RIS_CODE_EMAIL_NOT_SENT: -40,
RIS_CODE_ERR_UNAUTHORIZED: -30,
RIS_CODE_LOGIN_ERR_GENERIC: -20,
RIS_CODE_LOGIN_ERR: -10,
RIS_CODE_LOGIN_ERR_SUBACCOUNT: -8,
RIS_CODE_OK: 1,
RIS_CODE_LOGIN_OK: 1,
RIS_ISCRIZIONE_OK: 5,
RIS_CODE__HTTP_FORBIDDEN_INVALID_TOKEN: 403,
RIS_CODE_TOKEN_RESETPASSWORD_NOT_FOUND: -23,
RIS_SUBSCRIBED_OK: 1,
RIS_SUBSCRIBED_ALREADYEXIST: 2,
RIS_SUBSCRIBED_ERR: -1,
RIS_SUBSCRIBED_STR: 'subscribed',
RIS_UNSUBSCRIBED_OK: 5,
RIS_UNSUBSCRIBED_STR: 'unsubscribed',
RIS_UNSUBSCRIBED_NOT_EXIST: -5,
}

1734
src/store/Modules/tools.ts Normal file

File diff suppressed because it is too large Load Diff

256
src/store/Modules/toolsext.ts Executable file
View File

@@ -0,0 +1,256 @@
import { date, useQuasar } from 'quasar'
import { useUserStore } from '@store/UserStore'
// import { useGlobalStore } from '@store/globalStore'
import { static_data } from '../../db/static_data'
export const func_tools = {
getLocale(vero ?: boolean): string {
const userStore = useUserStore()
if (userStore) {
return userStore.lang
}
if (!vero) return process.env.LANG_DEFAULT ? process.env.LANG_DEFAULT : 'it'
return ''
},
getDateStr(mydate: any) {
const DateFormatter = new Intl.DateTimeFormat(func_tools.getLocale() || void 0, {
weekday: 'short',
day: 'numeric',
month: 'long',
year: 'numeric',
// timeZone: 'UTC'
})
try {
// console.log('mydate', mydate, DateFormatter)
if (DateFormatter) {
const date1 = new Date(mydate)
return DateFormatter.format(date1)
}
return mydate
} catch (e) {
return ''
}
},
getMinutesDuration(mydatestart: any, mydateend: any) {
return date.getDateDiff(mydateend, mydatestart, 'minutes')
},
getDateTimeShortStr(mydate: any) {
const DateFormatter = new Intl.DateTimeFormat(func_tools.getLocale() || void 0, {
hour: 'numeric',
minute: 'numeric',
day: 'numeric',
month: 'short',
// timeZone: 'UTC'
})
if (DateFormatter) {
const date1 = new Date(mydate)
return DateFormatter.format(date1)
}
return mydate
},
}
export const toolsext = {
TABUSER: 'users',
TABNAVI: 'navi',
TABLISTAINGRESSO: 'listaingressos',
TABGRADUATORIA: 'graduatorias',
TABEXTRALIST: 'extralist',
TABNEWSLETTER: 'newstosent',
TABGALLERY: 'gallery',
TABMAILINGLIST: 'mailinglist',
TABMYPAGE: 'mypage',
TABCALZOOM: 'calzoom',
TABGROUPS: 'groups',
TABTEMPLEMAIL: 'templemail',
TABOPZEMAIL: 'opzemail',
TABSHAREWITHUS: 'sharewithus',
SERVKEY_VERS: 'vers',
ERR_GENERICO: -1,
ERR_SERVERFETCH: -2,
ERR_AUTHENTICATION: -5,
localStorage: {
teleg_id: 'ti',
verified_email: 'vf',
made_gift: 'mg',
wasAlreadySubOnDb: 'sb',
categorySel: 'cs',
isLogged: 'ilog',
expirationDate: 'expdate',
leftDrawerOpen: 'ldo',
userId: 'uid',
token: 'tk',
username: 'uname',
name: 'nm',
surname: 'sn',
perm: 'pm',
lang: 'lg',
img: 'img',
},
getLocale(vero?: boolean): string {
const userStore = useUserStore()
if (userStore) {
return userStore.lang
}
return process.env.LANG_DEFAULT ? process.env.LANG_DEFAULT : 'it'
},
isLang(whichlang: string): boolean {
const loc = func_tools.getLocale()
return (loc === whichlang)
},
getlangforQuasar(mylang: string) {
if (mylang === 'enUs') return 'en-us'
return mylang
},
setLangAtt(mylang: string) {
/** ++Todo: SISTEMARE
const globalStore = useGlobalStore()
const $q = useQuasar()
console.log('setLangAtt =', mylang)
// console.log('PRIMA this.$q.lang.isoName', this.$q.lang.isoName)
// dynamic import, so loading on demand only
import(`quasar/lang/${this.getlangforQuasar(mylang)}`).then((lang) => {
console.log(' Import dinamically lang =', lang)
$q.lang.set(this.getlangforQuasar(lang.default))
import('../../public/i18n').then(() => {
console.log(' *** MY LANG DOPO=', $q.lang.isoName)
})
})
globalStore.addDynamicPages()
*/
// this.$q.lang.set(mylang)
},
getValDb(keystr: string, serv: boolean, def?: any, table?: string, subkey?: string, id?: any, idmain?: any): any | undefined {
/** ++Todo: SISTEMARE
const userStore = useUserStore()
const globalStore = useGlobalStore()
if (table === 'users') {
if (keystr === 'profile') {
if (subkey) { // @ts-ignore
return userStore.my.profile[subkey]
}
} else if (keystr) { // @ts-ignore
return userStore.my[keystr]
}
/* } else if (table === 'todos') {
// console.log('id', id, 'idmain', idmain)
const indcat = Todos.categories.indexOf(idmain)
console.log('indcat', indcat)
if (indcat >= 0) {
const myrec = Todos.todos[indcat].find((rec) => rec._id === id)
console.log('myrec', myrec)
let ris = null
if (myrec) {
ris = myrec[keystr]
}
console.log('ris', ris)
return ris
}
return ''
} else {
const ris = globalStore.getValueSettingsByKey(keystr, serv)
if (ris === '') {
if (def !== undefined) return def
return ''
}
return ris
}
*/
return ''
},
sito_online(pertutti: boolean): boolean {
const userStore = useUserStore()
let ris = true
const online = this.getValDb('SITO_ONLINE', false, true)
ris = userStore.isAdmin && !pertutti ? true : online
// console.log('isadmin', userStore.isAdmin)
return ris
},
checkLangPassed(mylangprop: string) {
// console.log('checkLangPassed ', mylang)
let mylang = mylangprop
const $q = useQuasar()
const userStore = useUserStore()
const mybrowserLang = $q.lang.isoName
if (mylang !== '') {
if ((mylang.toLowerCase() === 'enus') || (mylang.toLowerCase() === 'en-us') || (mylang.toLowerCase() === 'uk')
|| (mylang.toLowerCase() === 'uk-uk') || (mylang.toLowerCase() === 'en-uk') || (mylang.toLowerCase() === 'en-gb')
|| (mylang.toLowerCase() === 'gb-gb')) {
mylang = 'enUs'
}
if ((mylang.toLowerCase() === 'es') || (mylang.toLowerCase() === 'es-es') || (mylang.toLowerCase() === 'eses')) {
mylang = 'es'
}
if ((mylang.toLowerCase() === 'pt') || (mylang.toLowerCase() === 'pt-pt') || (mylang.toLowerCase() === 'ptpt')) {
mylang = 'pt'
}
if ((mylang.toLowerCase() === 'fr') || (mylang.toLowerCase() === 'fr-fr') || (mylang.toLowerCase() === 'frfr')) {
mylang = 'fr'
}
if ((mylang.toLowerCase() === 'it') || (mylang.toLowerCase() === 'it-it') || (mylang.toLowerCase() === 'itit')) {
mylang = 'it'
}
if ((mylang.toLowerCase() === 'si') || (mylang.toLowerCase() === 'si-si') || (mylang.toLowerCase() === 'sisi')) {
mylang = 'si'
}
if (!(static_data.arrLangUsed.includes(mylang))) {
// console.log('non incluso ', mylang)
// mylang = static_data.arrLangUsed[0]
mylang = 'it'
// Metti come default
userStore.setlang(mylang)
}
}
if (!mylang) {
if (process.env.LANG_DEFAULT) mylang = process.env.LANG_DEFAULT
console.log('LANG DEFAULT: ', mylang)
}
if (this.getLocale(true) === '') {
userStore.setlang(mylang)
}
// console.log('mylang calc : ', mylang)
return mylang
},
}
// export const costanti_tools = {
// DateFormatter: new Intl.DateTimeFormat(func_this.getLocale() || void 0, {
// weekday: 'long',
// day: 'numeric',
// month: 'long',
// year: 'numeric'
// // timeZone: 'UTC'
// })
// }

View File

@@ -0,0 +1,77 @@
export const translation = {
it: {
fase: 'Fase',
privacy: {
all: 'Tutti',
friends: 'Amici',
mygroup: 'Gruppo',
onlyme: 'Solo io',
inherited: 'Ereditato',
},
tipovisu: {
simplelist: 'Lista Semplice',
taskProgress: 'Statistiche',
responsabili: 'Responsabili',
},
proj: {
newproj: 'Nuovo Progetto',
newsubproj: 'Nuovo Sotto-Progetto',
themecolor: 'Tema Colore',
themebgcolor: 'Tema Colore Sfondo',
},
task: {
showtask: 'Mostra Task',
showposiz: 'Mostra Ordine',
},
action: {
paste: 'Incolla',
},
end: '',
},
es: {
fase: 'Fase',
privacy: {
all: 'Todos',
friends: 'Amigos',
mygroup: 'Grupos',
onlyme: 'Solo yo',
inherited: 'Ereditato',
},
proj: {
newproj: 'Nuevo Projecto',
newsubproj: 'Nuevo Sub-Projecto',
themecolor: 'Tema Colores',
themebgcolor: 'Tema Colores Fondo',
},
task: {
showtask: 'Mostrar Tarea',
},
action: {
paste: 'Pegar',
},
end: '',
},
enUs: {
fase: 'Phase',
privacy: {
all: 'All',
friends: 'Friends',
mygroup: 'Group',
onlyme: 'Only me',
inherited: 'Inherited',
},
proj: {
newproj: 'New Project',
newsubproj: 'New Sub-Project',
themecolor: 'Theme Color',
themebgcolor: 'Theme Background Color',
},
task: {
showtask: 'Show Task',
},
action: {
paste: 'Paste',
},
end: '',
},
}

510
src/store/UserStore.ts Executable file
View File

@@ -0,0 +1,510 @@
import { defineStore } from 'pinia'
import {
ISignupOptions, IUserFields, IUserProfile, IUserState,
} from '@src/model'
import { tools } from '@store/Modules/tools'
import translate from '@src/globalroutines/util'
import { ILinkReg, IToken } from '@model/other'
import * as Types from '@src/store/Api/ApiTypes'
import { useGlobalStore } from '@store/globalStore'
import { useRouter } from 'vue-router'
import { serv_constants } from '@store/Modules/serv_constants'
import Api from './Api'
import { toolsext } from '@store/Modules/toolsext'
export const DefaultUser: IUserFields = {
_id: '',
email: '',
username: '',
name: '',
surname: '',
password: '',
tokens: [],
verified_email: false,
aportador_solidario: '',
made_gift: false,
profile: {
img: '',
teleg_id: 0,
saw_zoom_presentation: false,
ask_zoom_partecipato: false,
saw_and_accepted: false,
qualified: false,
qualified_2invitati: false,
socio: false,
socioresidente: false,
myshares: [],
},
cart: {
userId: '',
items: [],
totalPrice: 0,
department: '',
totalQty: 0,
note: '',
},
}
export const DefaultProfile: IUserProfile = {
img: '',
nationality: '',
intcode_cell: '',
cell: process.env.TEST_CELL || '',
dateofbirth: new Date(),
sex: 0,
country_pay: '',
email_paypal: '',
payeer_id: '',
advcash_id: '',
revolut: '',
link_payment: '',
note_payment: '',
username_telegram: '',
teleg_id: 0,
teleg_checkcode: 0,
my_dream: '',
manage_telegram: false,
saw_zoom_presentation: false,
ask_zoom_partecipato: false,
saw_and_accepted: false,
socio: false,
socioresidente: false,
myshares: [],
paymenttypes: [],
qualified: false,
qualified_2invitati: false,
}
export const useUserStore = defineStore('UserStore', {
state: () => ({
my: { ...DefaultUser },
lang: process.env.LANG_DEFAULT ? process.env.LANG_DEFAULT : 'it',
repeatPassword: '',
categorySel: 'personal',
servercode: 0,
resStatus: 0,
x_auth_token: '',
isLogged: false,
isAdmin: false,
isManager: false,
isDepartment: false,
isTutor: false,
isZoomeri: false,
isTratuttrici: false,
isEditor: false,
usersList: [],
countusers: 0,
lastparamquery: {},
}),
getters: {
getUserByUsername: (state: IUserState) => (username: string): IUserFields | null => {
// Check if is this User!
if (state.my.username === username) return state.my
let trovato = null
if (state.usersList) trovato = state.usersList.find((item) => item.username === username)
return (trovato) || null
},
getImgByUsername: (state: IUserState) => (username: string): string => {
if (username === '') return ''
// Check if is this User!
// @ts-ignore
const myrec = this.getUserByUsername(username)
// console.log('myrec', myrec)
if (myrec && myrec.profile && !!myrec.profile.img && myrec.profile.img !== '' && myrec.profile.img !== 'undefined') {
return myrec.profile.img
}
return ''
},
isServerError(): boolean {
return (this.servercode === toolsext.ERR_SERVERFETCH)
},
getServerCode: (state: IUserState): number => (state.servercode ? state.servercode : 0),
getNameSurnameByUserId: (state: IUserState) => (userId: string): string => {
// @ts-ignore
const user = this.getUserByUserId(state, userId)
if (user) return `${user.name} ${user.surname}`
return `(${userId})`
},
getNameSurnameByUsername: (state: IUserState) => (username: string): string => {
// @ts-ignore
const user = this.getUserByUsername(state, username)
if (user) return `${user.name} ${user.surname}`
return `(${username})`
},
getUserByUserId: (state: IUserState) => (userId: string): IUserFields | null => {
// Check if is this User!
if (state.my._id === userId) return state.my
let trovato = null
if (state.usersList) trovato = state.usersList.find((item) => item._id === userId)
return (trovato) || null
},
isUserInvalid: (state: IUserState): boolean => {
try {
return (state.my._id === undefined) || (state.my._id.trim() === '')
} catch (e) {
return true
}
},
getMsgError: (state: IUserState) => (err: number): string => {
let msgerrore = ''
if (err !== tools.OK) {
msgerrore = `Error [${state.servercode}]: `
if (state.servercode === toolsext.ERR_SERVERFETCH) {
msgerrore = translate('fetch.errore_server')
} else {
msgerrore = translate('fetch.errore_generico')
}
if (process.env.DEV) {
console.log('ERROREEEEEEEEE: ', msgerrore, ' (', err, ')')
}
}
// return { code: this.servercode, msg: msgerrore }
return msgerrore
},
},
actions: {
clearAuthData() {
this.my = DefaultUser
// resetArrToken(mystate.my.tokens)
this.categorySel = 'personal'
this.servercode = 0
this.resStatus = 0
this.isLogged = false
this.x_auth_token = ''
return true
},
setErrorCatch(axerr: Types.AxiosError) {
try {
if (this.servercode !== toolsext.ERR_SERVERFETCH) {
this.servercode = axerr.getCode()
}
// this.msg = axerr.getMsg()
console.log('Err catch: (servercode:', axerr.getCode(), axerr.getMsgError(), ')')
} catch (e) {
console.log('Err catch:', axerr)
}
},
async setLangServer() {
const mydata = {
username: this.my.username,
lang: this.lang,
}
return Api.SendReq('/setlang', 'PATCH', { data: mydata })
.then((res) => {
if (res) {
return (res.data.code === serv_constants.RIS_CODE_OK)
} return false
})
.catch((error: any) => false)
},
async requestpwd(paramquery: any) {
const usertosend = {
email: paramquery.email,
}
console.log(usertosend)
this.setServerCode(tools.CALLING)
return Api.SendReq('/requestnewpwd', 'POST', usertosend)
.then((res) => ({ code: res.data.code, msg: res.data.msg })).catch((error) => {
this.setErrorCatch(error)
return this.getServerCode
})
},
async vreg(paramquery: ILinkReg) {
const usertosend = {
idlink: paramquery.idlink,
}
console.log(usertosend)
this.setServerCode(tools.CALLING)
return Api.SendReq('/vreg', 'POST', usertosend)
.then((res) => {
// console.log("RITORNO 2 ");
// mutations.setServerCode(myres);
if (res.data.code === serv_constants.RIS_CODE_EMAIL_VERIFIED) {
console.log('VERIFICATO !!')
localStorage.setItem(toolsext.localStorage.verified_email, String(true))
} else {
console.log('Risultato di vreg: ', res.data.code)
}
return { code: res.data.code, msg: res.data.msg }
}).catch((error) => {
this.setErrorCatch(error)
return this.getServerCode
})
},
async unsubscribe(paramquery: any) {
return Api.SendReq('/news/unsubscribe', 'POST', paramquery)
.then((res) => {
// console.log("RITORNO 2 ");
// mutations.setServerCode(myres);
if (res.data.code === serv_constants.RIS_UNSUBSCRIBED_OK) {
console.log('DESOTTOSCRITTO ALLA NEWSLETTER !!')
} else {
console.log('Risultato di unsubscribe: ', res.data.code)
}
return { code: res.data.code, msg: res.data.msg }
}).catch((error) => this.getServerCode)
},
async importemail(paramquery: any) {
return Api.SendReq('/news/import', 'POST', paramquery)
.then((res) => res).catch((error) => ({ numtot: 0, numadded: 0, numalreadyexisted: 0 }))
},
authUser(data: IUserFields) {
this.my = { ...data }
if (!this.my.profile) {
this.my.profile = DefaultProfile
}
},
updateLocalStorage(myuser: IUserFields) {
const globalStore = useGlobalStore()
const now = tools.getDateNow()
// const expirationDate = new Date(now.getTime() + myres.data.expiresIn * 1000);
const expirationDate = new Date(now.getTime() * 1000)
localStorage.setItem(toolsext.localStorage.lang, this.lang)
localStorage.setItem(toolsext.localStorage.userId, myuser._id)
localStorage.setItem(toolsext.localStorage.username, myuser.username)
localStorage.setItem(toolsext.localStorage.name, myuser.name)
localStorage.setItem(toolsext.localStorage.surname, myuser.surname)
localStorage.setItem(toolsext.localStorage.perm, String(myuser.perm) || '')
if (myuser.profile !== undefined) localStorage.setItem(toolsext.localStorage.img, (myuser.profile.img) ? String(myuser.profile.img) || '' : '')
else localStorage.setItem(toolsext.localStorage.img, '')
localStorage.setItem(toolsext.localStorage.token, this.x_auth_token)
localStorage.setItem(toolsext.localStorage.expirationDate, expirationDate.toString())
localStorage.setItem(toolsext.localStorage.isLogged, String(true))
localStorage.setItem(toolsext.localStorage.verified_email, String(myuser.verified_email))
localStorage.setItem(toolsext.localStorage.teleg_id, String(myuser.profile.teleg_id))
localStorage.setItem(toolsext.localStorage.made_gift, String(myuser.made_gift))
localStorage.setItem(toolsext.localStorage.wasAlreadySubOnDb, String(globalStore.wasAlreadySubOnDb))
},
setusersList(usersList: IUserFields[]) {
// console.log('setusersList', usersList)
// @ts-ignore
this.usersList = [...usersList]
},
setlang(newstr: string) {
console.log('SETLANG', newstr)
this.lang = newstr
toolsext.setLangAtt(newstr)
localStorage.setItem(toolsext.localStorage.lang, this.lang)
},
async signup(authData: ISignupOptions) {
console.log('SIGNUP')
},
UpdatePwd(x_auth_token: string) {
this.x_auth_token = x_auth_token
if (!this.my.tokens) {
this.my.tokens = []
}
this.my.tokens.push({ access: 'auth', token: x_auth_token, data_login: tools.getDateNow() })
},
setServerCode(num: number) {
this.servercode = num
},
setResStatus(status: number) {
this.resStatus = status
},
setAuth(x_auth_token: string) {
this.x_auth_token = x_auth_token
},
resetArrToken(arrtokens: IToken[]) {
if (!arrtokens) {
arrtokens = []
}
// Take only the others access (from others Browser)
return arrtokens.filter((token: IToken) => token.access !== 'auth')
},
async logout() {
const globalStore = useGlobalStore()
const $router = useRouter()
console.log('logout')
localStorage.removeItem(toolsext.localStorage.expirationDate)
localStorage.removeItem(toolsext.localStorage.token)
localStorage.removeItem(toolsext.localStorage.userId)
localStorage.removeItem(toolsext.localStorage.username)
localStorage.removeItem(toolsext.localStorage.name)
localStorage.removeItem(toolsext.localStorage.surname)
localStorage.removeItem(toolsext.localStorage.img)
localStorage.removeItem(toolsext.localStorage.perm)
localStorage.removeItem(toolsext.localStorage.isLogged)
// localStorage.removeItem(rescodes.localStorage.leftDrawerOpen)
localStorage.removeItem(toolsext.localStorage.verified_email)
localStorage.removeItem(toolsext.localStorage.teleg_id)
localStorage.removeItem(toolsext.localStorage.made_gift)
localStorage.removeItem(toolsext.localStorage.categorySel)
localStorage.removeItem(toolsext.localStorage.wasAlreadySubOnDb)
this.isLogged = false
this.my = { ...DefaultUser }
await globalStore.clearDataAfterLogout()
const riscall = await Api.SendReq('/users/me/token', 'DELETE', null)
.then((res) => {
console.log(res)
}).then(() => this.clearAuthData()).catch((error) => {
this.setErrorCatch(error)
return this.getServerCode
})
return riscall
// $router.push('/signin')
},
async setGlobal(isLogged: boolean) {
// console.log('setGlobal', isLogged)
const globalStore = useGlobalStore()
try {
// this.isLogged = true
if (isLogged) {
// console.log('this.isLogged', this.isLogged)
globalStore.setleftDrawerOpen(localStorage.getItem(toolsext.localStorage.leftDrawerOpen) === 'true')
globalStore.setCategorySel(localStorage.getItem(toolsext.localStorage.categorySel))
globalStore.checkUpdates()
}
const isok = await globalStore.loadAfterLogin()
this.isLogged = isok && isLogged
// ++Todo conv if (static_data.functionality.ENABLE_TODOS_LOADING)
// await Todos.dbLoad({ checkPending: true })
// if (static_data.functionality.ENABLE_PROJECTS_LOADING)
// await Projects.dbLoad({ checkPending: true, onlyiffirsttime: true })
// console.log('add routes')
globalStore.addDynamicPages()
globalStore.finishLoading = true
if (tools.isDebug()) console.log('finishLoading', globalStore.finishLoading)
// document.dispatchEvent(new Event('custom-post-render-event'))
} catch (e) {
console.error('Error', e)
globalStore.finishLoading = true
}
return true
// console.log('setGlobal: END')
},
async autologin_FromLocalStorage() {
try {
const globalStore = useGlobalStore()
// console.log('*** autologin_FromLocalStorage ***')
// INIT
let isLogged = false
this.lang = tools.getItemLS(toolsext.localStorage.lang)
const token = localStorage.getItem(toolsext.localStorage.token)
if (token) {
const expirationDateStr = localStorage.getItem(toolsext.localStorage.expirationDate)
const expirationDate = new Date(String(expirationDateStr))
const now = tools.getDateNow()
if (now < expirationDate) {
const _id = String(localStorage.getItem(toolsext.localStorage.userId))
const username = String(localStorage.getItem(toolsext.localStorage.username))
const name = String(localStorage.getItem(toolsext.localStorage.name))
const surname = String(localStorage.getItem(toolsext.localStorage.surname))
const verified_email = localStorage.getItem(toolsext.localStorage.verified_email) === 'true'
const made_gift = localStorage.getItem(toolsext.localStorage.made_gift) === 'true'
const myperm = localStorage.getItem(toolsext.localStorage.perm)
let perm = 0
if (myperm) perm = parseInt(myperm, 10)
const img = String(localStorage.getItem(toolsext.localStorage.img))
let teleg_id = 0
const telegid = localStorage.getItem(toolsext.localStorage.teleg_id)
if (telegid) teleg_id = parseInt(telegid, 10)
globalStore.wasAlreadySubOnDb = localStorage.getItem(toolsext.localStorage.wasAlreadySubOnDb) === 'true'
console.log('************* autologin _id', _id)
this.setAuth(token)
this.authUser({
_id,
username,
name,
surname,
verified_email,
made_gift,
perm,
profile: { img, teleg_id },
})
isLogged = true
}
}
return await this.setGlobal(isLogged)
// console.log('autologin _id STATE ', this._id)
// return true
} catch (e) {
console.error('ERR autologin ', e.message)
return false
}
},
},
})

681
src/store/globalStore.ts Normal file
View File

@@ -0,0 +1,681 @@
import { defineStore } from 'pinia'
import {
ICfgServer, IColGridTable, IConfig, IDataPass, IGlobalState, IListRoutes, ISettings, StateConnection,
} from '@model'
import { static_data } from '@src/db/static_data'
import * as Types from '@src/store/Api/ApiTypes'
import { useUserStore } from '@store/UserStore'
import { serv_constants } from '@store/Modules/serv_constants'
import * as ApiTables from '@src/store/Modules/ApiTables'
import globalroutines from '@src/boot/globalroutines'
import { useRouter } from 'vue-router'
import { cfgrouter } from '@src/router/route-config'
import Api from './Api'
import { toolsext } from '@store/Modules/toolsext'
import { costanti } from '@costanti'
import { fieldsTable } from '@store/Modules/fieldsTable'
import { tools } from '@store/Modules/tools'
import { shared_consts } from '@src/common/shared_vuejs'
const stateConnDefault = 'online'
export const useGlobalStore = defineStore('GlobalStore', {
// @ts-ignore
state: (): IGlobalState => ({
finishLoading: false,
conta: 0,
wasAlreadySubscribed: false,
wasAlreadySubOnDb: false,
isLoginPage: false,
layoutNeeded: true,
mobileMode: false,
menuCollapse: true,
leftDrawerOpen: true,
rightDrawerOpen: false,
rightCartOpen: false,
stateConnection: stateConnDefault,
networkDataReceived: false,
clickcmd: '',
cfgServer: [],
testp1: { contatore: 0, mioarray: [] },
category: 'personal',
posts: [],
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,
},
arrConfig: [],
lastaction: {
table: '',
type: 0,
_id: 0,
},
serv_settings: [],
templemail: [],
opzemail: [],
settings: [],
disciplines: [],
paymenttypes: [],
autoplaydisc: 8000,
newstosent: [],
gallery: [],
mailinglist: [],
mypage: [],
calzoom: [],
producers: [],
groups: [],
resps: [],
workers: [],
storehouses: [],
departments: [],
sharewithus: [],
TIMER: null,
TIMEOUT: null,
CUT: null,
TIMER_STATE: 0,
URL_RITORNA: '',
URL_RESTORE: '',
}),
getters: {
isNewVersionAvailable(state: IGlobalState) {
// console.log('cfgServer', cfgServer)
const serversrec = state.cfgServer.find((x) => (x.chiave === toolsext.SERVKEY_VERS) && (x.idapp === process.env.APP_ID))
// 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
}
return false
},
isMyLang: (state: IGlobalState) => (rec: any) => {
if (!rec.lang) return true
return (rec.lang === toolsext.getLocale(false) || toolsext.getLocale() === '')
},
getPage: (state: IGlobalState) => (path: string) => state.mypage.find((page) => (`/${page.path}`) === path),
getmenu: (state: IGlobalState): any => {
// console.log('getmenu', cfgrouter.getmenu())
/*
const mystate = state
mystate.menulinks = {
Dashboard: {
routes: cfgrouter.getmenu(),
show: true,
},
}
*/
// return mystate.menulinks
cfgrouter.getmenu()
},
getListByTable: (state: IGlobalState) => (table: string): any => {
/* if (table === costanti.TABEVENTS)
return CalendarStore.eventlist
else if (table === 'operators')
return CalendarStore.operators
else if (table === 'internalpages')
return CalendarStore.internalpages
else if (table === 'wheres')
return CalendarStore.wheres
else if (table === 'contribtype')
return CalendarStore.contribtype */
let ris = null
if (table === 'disciplines') ris = state.disciplines
else if (table === toolsext.TABNEWSLETTER) ris = state.newstosent
else if (table === toolsext.TABGALLERY) ris = state.gallery
else if (table === toolsext.TABTEMPLEMAIL) ris = state.templemail
else if (table === toolsext.TABOPZEMAIL) ris = state.opzemail
else if (table === toolsext.TABMAILINGLIST) ris = state.mailinglist
else if (table === toolsext.TABMYPAGE) ris = state.mypage
else if (table === toolsext.TABCALZOOM) ris = state.calzoom
else if (table === 'producers') ris = state.producers
else if (table === 'storehouses') ris = state.storehouses
else if (table === 'groups') ris = state.groups
else if (table === 'resps') ris = state.resps
else if (table === 'workers') ris = state.workers
else if (table === 'departments') ris = state.departments
else if (table === 'sharewithus') ris = state.sharewithus
else if (table === 'paymenttypes') ris = state.paymenttypes
/* else if (table === 'bookings')
return CalendarStore.bookedevent
else if (table === 'users')
return userStore.usersList
else if (table === 'sendmsgs')
return MessageStore.last_msgs
else if (table === 'settings')
return userStore.settings */
else return ris
return ris || null
},
getrecSettingsByKey: (state: IGlobalState) => (key: any, serv: any): ISettings | undefined => {
if (serv) return state.serv_settings.find((rec) => rec.key === key)
return state.settings.find((rec) => rec.key === key)
},
getCmdClick: (state: IGlobalState): string => (state.clickcmd ? state.clickcmd : ''),
getValueSettingsByKey: (state: IGlobalState) => (key: any, serv: any): any | undefined => {
// @ts-ignore
const myrec = getrecSettingsByKey(key, serv)
if (myrec) {
if ((myrec.type === costanti.FieldType.date) || (myrec.type === costanti.FieldType.onlydate)) return myrec.value_date
if ((myrec.type === costanti.FieldType.number) || (myrec.type === costanti.FieldType.hours)) return myrec.value_num
if (myrec.type === costanti.FieldType.boolean) return myrec.value_bool
return myrec.value_str
}
return ''
},
// @ts-ignore
setValueSettingsByKey: (state: IGlobalState) => ({ key, value, serv }): any => {
// Update the Server
// Update in Memory
let myrec = null
if (serv) myrec = state.serv_settings.find((rec: any) => rec.key === key)
else myrec = state.settings.find((rec: any) => rec.key === key)
if (myrec) {
if ((myrec.type === costanti.FieldType.date) || (myrec.type === costanti.FieldType.onlydate)) myrec.value_date = value
else if ((myrec.type === costanti.FieldType.number) || (myrec.type === costanti.FieldType.hours)) myrec.value_num = value
else if (myrec.type === costanti.FieldType.boolean) myrec.value_bool = value
else myrec.value_str = value
console.log('setValueSettingsByKey value', value, 'myrec', myrec)
}
},
},
actions: {
changeCmdClick(value: string) {
console.log('changeCmdClick', value)
this.clickcmd = value
},
isOnline(): boolean {
return this.stateConnection === 'online'
},
async addDynamicPages() {
const arrpagesroute: IListRoutes[] = []
for (const page of this.mypage) {
if (page.active) {
// console.log('page', page.lang)
if (this.isMyLang(page)) {
// console.log('page', page.lang, 'OK')
arrpagesroute.push({
active: true,
order: page.order ? page.order : 1000,
lang: page.lang,
path: `/${page.path}`,
name: '',
text: page.title,
materialIcon: page.icon,
component: () => import('@src/root/mypage/mypage.vue'),
inmenu: page.inmenu,
onlySocioResidente: page.only_residenti,
onlyConsiglio: page.only_consiglio,
color: page.color,
infooter: page.infooter,
onlyif_logged: page.onlyif_logged,
level_child: page.l_child,
level_parent: page.l_par,
submenu: page.submenu,
})
}
}
}
const last = {
active: true,
order: 10000,
path: '*',
materialIcon: 'fas fa-calendar-plus',
name: 'otherpages.error404def',
component: () => import('@src/root/My404page/My404page.vue'),
inmenu: false,
infooter: false,
}
const sito_offline = {
active: true,
order: 20,
path: '/sito_offline',
materialIcon: 'home',
name: 'otherpages.sito_offline',
component: () => import('@src/rootgen/sito_offline/sito_offline.vue'),
inmenu: true,
infooter: true,
}
if (!toolsext.sito_online(false)) {
static_data.routes = [sito_offline, last]
} else {
static_data.routes = [...static_data.baseroutes, ...arrpagesroute, last]
}
// Sort array
static_data.routes = static_data.routes.sort((a, myb) => a.order - myb.order)
/*
if (tools.sito_online(false)) {
router.addRoutes([...arrpagesroute, last])
} else {
router.addRoutes([sito_offline, last])
router.replace('/sito_offline')
}
*/
},
async loadPage(path: string) {
const userStore = useUserStore()
path = path.substring(1)
const mypage = this.getPage(`/${path}`)
// Controlla se l'ho già caricato
if (!!mypage && !!mypage.content) {
return mypage
}
console.log('loadPage', path)
return Api.SendReq('/getpage', 'POST', { path })
.then((res) => {
// console.table(res)
if (res) {
const index = this.mypage.findIndex((rec) => rec.path === path)
if (index >= 0) {
this.mypage[index] = res.data.mypage
}
return res.data.mypage
}
return null
})
.catch((error) => {
console.log('error loadTable', error)
userStore.setErrorCatch(error)
return null
})
},
async saveTable(mydata: object) {
// console.log('saveTable', mydata)
const userStore = useUserStore()
return Api.SendReq('/settable', 'POST', mydata)
.then((res) => res.data)
.catch((error) => {
console.log('error saveTable', error)
userStore.setErrorCatch(error)
return null
})
},
async saveFieldValue(mydata: IDataPass) {
// const userStore = useUserStore()
return Api.SendReq('/chval', 'PATCH', { data: mydata })
.then((res) => {
if (res) {
this.UpdateValuesInMemory(mydata)
return (res.data.code === serv_constants.RIS_CODE_OK)
}
return false
})
.catch((error) => false)
},
setPaoArray_Delete(state: IGlobalState) {
state.testp1.mioarray.pop()
},
setConta(num: number) {
this.conta = num
},
setleftDrawerOpen(bool: boolean) {
this.leftDrawerOpen = bool
localStorage.setItem(toolsext.localStorage.leftDrawerOpen, bool.toString())
},
setCategorySel(cat: string | null) {
this.category = cat || ''
},
setStateConnection(stateconn: StateConnection) {
if (this.stateConnection !== stateconn) {
console.log('INTERNET ', stateconn)
this.stateConnection = stateconn
}
},
saveConfig(data: IConfig) {
let dataout
// this.$set(dataout, data.value, {'value': 'default value'})
// @ts-ignore
return globalroutines(null, 'write', 'config', { _id: data._id, value: data.value })
},
UpdateValuesInMemory(mydata: IDataPass): void {
const { id } = mydata
const { table } = mydata
try {
const mylist = this.getListByTable(table)
const mykey = fieldsTable.getKeyByTable(table)
if (mylist) {
const myrec = mylist.find((event: any) => event[mykey] === id)
// console.log('myrec', myrec)
if (myrec) {
// console.log('key', value, myrec[key])
for (const [key, value] of Object.entries(mydata.fieldsvalue)) {
myrec[key] = value
}
}
}
} catch (e) {
console.error(e)
}
},
async deleteSubscriptionToServer() {
console.log('DeleteSubscriptionToServer: ')
return Api.SendReq('/subscribe/del', 'DELETE', null)
.then((res) => {
})
},
async clearDataAfterLogout() {
console.log('clearDataAfterLogout')
// Clear all data from the IndexedDB
// for (const table of ApiTables.allTables()) {
// ++Todo conv: 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 this.deleteSubscriptionToServer()
},
async clearDataAfterLoginOnlyIfActiveConnection() {
const prova = 1
return prova
},
async loadAfterLogin() {
// console.log('loadAfterLogin')
this.clearDataAfterLoginOnlyIfActiveConnection()
let isok = false
const $router = useRouter()
if (!await this.loadSite()) {
$router.push('/signin')
} else {
isok = true
}
// ++Todo conv: this.arrConfig = await globalroutines(null, 'readall', 'config', null)
return isok
},
async saveCfgServerKey(dataval: ICfgServer) {
console.log('saveCfgServerKey dataval', dataval)
const ris = await Api.SendReq('/admin/updateval', 'POST', { pairval: dataval })
.then((res) => {
})
},
async checkUpdates() {
console.log('checkUpdates')
const userStore = useUserStore()
// if (userStore.my._id === '')
// return false // Login not made
this.networkDataReceived = false
const ris = await Api.SendReq('/checkupdates', 'GET', null)
.then((res) => {
this.networkDataReceived = true
// console.log('******* checkUpdates RES :', res.data.cfgServer)
if (res.data.cfgServer) {
this.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.setusersList(res.data.usersList)
}
if (res.data.last_msgs) {
// ++Todo conv: MessageStore.last_msgs = [...res.data.last_msgs]
}
// console.log('MessageStore.last_msgs', MessageStore.last_msgs)
// console.log('********** res', 'todos', todos, 'checkPending', checkPending)
// After Login will store into the indexedDb...
return res
})
.catch((error) => {
console.log('error checkUpdates', error)
userStore.setErrorCatch(error)
return error
})
},
async loadSite() {
const userStore = useUserStore()
// console.log('CalendarStore: loadAfterLogin')
// Load local data
const showall = userStore.isAdmin || userStore.isManager ? '1' : '0'
const myuserid = (userStore.my._id) ? userStore.my._id : '0'
// CalendarStore.editable = false
return Api.SendReq(`/loadsite/${myuserid}/${process.env.APP_ID}/${process.env.APP_VERSION}`, 'GET', null)
.then((res) => {
// console.log('____________________________ res', res)
if (res.status === 200) {
/* CalendarStore.bookedevent = (res.data.bookedevent) ? res.data.bookedevent : []
CalendarStore.eventlist = (res.data.eventlist) ? res.data.eventlist : []
CalendarStore.operators = (res.data.operators) ? res.data.operators : []
CalendarStore.internalpages = (res.data.internalpages) ? res.data.internalpages : []
CalendarStore.wheres = (res.data.wheres) ? res.data.wheres : []
CalendarStore.contribtype = (res.data.contribtype) ? res.data.contribtype : []
*/
this.settings = (res.data.settings) ? [...res.data.settings] : []
this.disciplines = (res.data.disciplines) ? [...res.data.disciplines] : []
this.paymenttypes = (res.data.paymenttypes) ? [...res.data.paymenttypes] : []
this.gallery = (res.data.gallery) ? [...res.data.gallery] : []
this.calzoom = (res.data.calzoom) ? [...res.data.calzoom] : []
this.producers = (res.data.producers) ? [...res.data.producers] : []
this.storehouses = (res.data.storehouses) ? [...res.data.storehouses] : []
this.groups = (res.data.groups) ? [...res.data.groups] : []
this.resps = (res.data.resps) ? [...res.data.resps] : []
this.workers = (res.data.workers) ? [...res.data.workers] : []
// @ts-ignore
this.departments = (res.data.departments) ? [...res.data.departments] : []
// console.log('res.data.cart', res.data.cart)
/* if (res.data.cart)
Products.cart = (res.data.cart) ? { ...res.data.cart } : {}
else
Products.cart = { items: [], totalPrice: 0, totalQty: 0, userId: '' }
Products.orders = (res.data.orders) ? [...res.data.orders] : []
*/
if (showall) {
this.newstosent = (res.data.newstosent) ? [...res.data.newstosent] : []
this.mailinglist = (res.data.mailinglist) ? [...res.data.mailinglist] : []
this.mypage = (res.data.mypage) ? [...res.data.mypage] : []
}
// console.log('res.data.myuser', res.data.myuser)
if (res.data.myuser) {
userStore.authUser(res.data.myuser)
userStore.updateLocalStorage(res.data.myuser)
} else {
// User not exist !!
}
const islogged = localStorage.getItem(toolsext.localStorage.username)
console.log('islogged', islogged)
// CalendarStore.editable = userStore.isAdmin || userStore.isManager || userStore.isTutor
if (res.data.myuser === null) {
if (islogged) {
// Fai Logout
console.log('Fai Logout', 'islogged', islogged)
userStore.logout()
this.rightDrawerOpen = true
return false
}
}
}
return true
}).then((res) => res).catch((error) => {
console.log('error dbLoad', error)
// userStore.setErrorCatch(error)
return new Types.AxiosError(serv_constants.RIS_CODE_ERR, null, toolsext.ERR_GENERICO, error)
})
},
getArrStrByValueBinary(mythis: any, col: IColGridTable, val: any) {
const arr = this.getArrByValueBinary(mythis, col, val)
if (arr.length > 0) return arr.join(' - ')
return '[---]'
},
getArrByValueBinary(mythis: any, col: IColGridTable, val: any) {
if (col.jointable) {
const mylist = this.getTableJoinByName(col.jointable)
const key = fieldsTable.getKeyByTable(col.jointable)
const myres: any = []
mylist.forEach((myrec: any) => {
if (tools.isBitActive(val, myrec[key])) myres.push(mythis.t(myrec.label))
})
return myres
}
return []
},
getValueByTable(col: IColGridTable, val: any) {
if (col.jointable) {
const mylist = this.getTableJoinByName(col.jointable)
const key = fieldsTable.getKeyByTable(col.jointable)
const collab = fieldsTable.getLabelByTable(col.jointable)
// console.table(mylist)
let risultato = ''
if (tools.isObject(collab)) {
risultato = mylist.filter((myrec: any) => myrec.username === val).map(collab)
} else {
const myris = mylist.find((myrec: any) => myrec[key] === val)
risultato = myris[collab]
}
if (key === 'username') {
console.log('key=', key, 'collab', collab, 'val', val)
console.log('myris', risultato)
}
return risultato
}
return ''
},
getMultiValueByTable(col: IColGridTable, arrval: any) {
// console.log('getMultiValueByTable')
if (col.jointable) {
const mylist = this.getTableJoinByName(col.jointable)
const key = fieldsTable.getKeyByTable(col.jointable)
const collab = fieldsTable.getLabelByTable(col.jointable)
// console.table(mylist)
// console.log('key=', key, 'collab', collab, 'val', collab)
const myris = mylist.filter((myrec: any) => arrval.includes(myrec[key]))
// console.log('myris', myris)
if (myris) {
console.log('collab', collab)
if (tools.isObject(collab)) return myris.map(collab)
return myris.map((rec: any) => rec[collab])
}
return ''
}
return ''
},
getTableJoinByName(table: string) {
if (table === 'permissions') return [shared_consts.Permissions.Admin, shared_consts.Permissions.Manager, shared_consts.Permissions.Teacher, shared_consts.Permissions.Tutor, shared_consts.Permissions.Editor, shared_consts.Permissions.Zoomeri, shared_consts.Permissions.Department]
if (table === 'accepted') return [shared_consts.Accepted.CHECK_READ_GUIDELINES, shared_consts.Accepted.CHECK_SEE_VIDEO_PRINCIPI]
if (table === 'fieldstype') return costanti.FieldTypeArr
if (table === 'metodo_pagamento') return tools.SelectMetodiPagamento
return this.getListByTable(table)
},
},
})

3
src/store/index.ts Executable file
View File

@@ -0,0 +1,3 @@
import { createPinia } from 'pinia';
export default createPinia();

9
src/store/store-flag.d.ts vendored Executable file
View File

@@ -0,0 +1,9 @@
// THIS FEATURE-FLAG FILE IS AUTOGENERATED,
// REMOVAL OR CHANGES WILL CAUSE RELATED TYPES TO STOP WORKING
import 'quasar/dist/types/feature-flag';
declare module 'quasar/dist/types/feature-flag' {
interface QuasarFeatureFlags {
store: true;
}
}

36
src/store/testStore.ts Normal file
View File

@@ -0,0 +1,36 @@
import { defineStore } from 'pinia'
import { tools } from '@store/Modules/tools'
import { toolsext } from '@store/Modules/toolsext'
export interface ITest {
finishLoading: boolean
}
export const useTestStore = defineStore({
id: 'TestStore',
state: (): ITest => ({
finishLoading: false,
}),
getters: {
isMyLang: (state: ITest) => (rec: { lang: string }): boolean => {
if (!rec.lang) return true
return (rec.lang === toolsext.getLocale(false) || toolsext.getLocale() === '')
},
prova2(): boolean {
return this.finishLoading
},
},
actions: {
async testProva() {
let arrpagesroute = null
arrpagesroute = this.isMyLang({ lang: 'test' })
},
},
})