From 1c3df0fac1fcbabd1c4ebd54fba2614652693611 Mon Sep 17 00:00:00 2001 From: Paolo Arena Date: Thu, 2 Sep 2021 21:29:24 +0200 Subject: [PATCH] ... --- .eslintrc.js | 18 +- src-pwa/{pwa-flag.d.ts => pwa-flag.d.ts.off} | 0 src/classes/debounce.ts | 2 +- src/common/axios.ts | 2 +- src/common/pattern.ts | 6 +- src/components/CMyAvatar/CMyAvatar.ts | 4 +- src/components/Footer/Footer.vue | 6 +- src/globalroutines/indexdb.ts | 2 +- src/model/GlobalStore.ts | 24 +- src/model/UserStore.ts | 2 + src/store/Api/ApiTypes.ts | 8 +- src/store/Api/index.ts | 10 +- src/store/CalendarStore.ts | 200 ++++++ src/store/MessageStore.ts | 248 +++---- src/store/Modules/ApiTables.ts | 24 +- src/store/Modules/tools.ts | 590 ++++++++-------- src/store/Products.ts | 26 +- src/store/Projects.ts | 42 +- src/store/Todos.ts | 58 +- src/store/UserStore.ts | 8 + src/store/globalStore.ts | 684 ++++++++++++++++--- 21 files changed, 1291 insertions(+), 673 deletions(-) rename src-pwa/{pwa-flag.d.ts => pwa-flag.d.ts.off} (100%) create mode 100755 src/store/CalendarStore.ts diff --git a/.eslintrc.js b/.eslintrc.js index 8d8e506b..b63934e2 100755 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -32,9 +32,9 @@ module.exports = { // https://github.com/typescript-eslint/typescript-eslint/tree/master/packages/eslint-plugin#usage // ESLint typescript rules - 'plugin:@typescript-eslint/recommended', + // 'plugin:@typescript-eslint/recommended', // consider disabling this class of rules if linting takes too long - 'plugin:@typescript-eslint/recommended-requiring-type-checking', + // 'plugin:@typescript-eslint/recommended-requiring-type-checking', // Uncomment any of the lines below to choose desired strictness, // but leave only one uncommented! @@ -75,9 +75,10 @@ module.exports = { 'generator-star-spacing': 'off', // allow paren-less arrow functions 'arrow-parens': 'off', + 'no-loop-func': 'off', 'one-var': 'off', 'no-void': 'off', - "comma-dangle": [2, "always-multiline"], + 'comma-dangle': [2, 'always-multiline'], // 'multiline-ternary': 'off', 'vue/max-attributes-per-line': [ 'error', { @@ -100,7 +101,7 @@ module.exports = { 'import/no-extraneous-dependencies': 'off', 'prefer-promise-reject-errors': 'off', 'no-bitwise': 'off', - "no-console": 'off', + 'no-console': 'off', 'no-restricted-syntax': 'off', 'no-param-reassign': 'off', 'no-plusplus': 'off', @@ -110,6 +111,7 @@ module.exports = { '@typescript-eslint/explicit-function-return-type': 'off', '@typescript-eslint/explicit-module-boundary-types': 'off', '@typescript-eslint/semi': 'off', + '@typescript-eslint/object-curly-spacing': 'off', // allow debugger during development only 'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off', @@ -121,9 +123,9 @@ module.exports = { 'import/prefer-default-export': 'off', 'no-use-before-define': 'off', '@typescript-eslint/no-unused-vars': 'off', - "@typescript-eslint/max-len": 'off', - "max-len": 'off', - "@typescript-eslint/naming-convention": 'off', - "no-underscore-dangle": 'off', + '@typescript-eslint/max-len': 'off', + 'max-len': 'off', + '@typescript-eslint/naming-convention': 'off', + 'no-underscore-dangle': 'off', }, }; diff --git a/src-pwa/pwa-flag.d.ts b/src-pwa/pwa-flag.d.ts.off similarity index 100% rename from src-pwa/pwa-flag.d.ts rename to src-pwa/pwa-flag.d.ts.off diff --git a/src/classes/debounce.ts b/src/classes/debounce.ts index 042f4e7f..96146366 100755 --- a/src/classes/debounce.ts +++ b/src/classes/debounce.ts @@ -9,7 +9,7 @@ export type Options = { export function debounce( func: F, - waitMilliseconds: number = 50, + waitMilliseconds = 50, options: Options = { isImmediate: false, }, diff --git a/src/common/axios.ts b/src/common/axios.ts index 25875cf8..2368d6fb 100755 --- a/src/common/axios.ts +++ b/src/common/axios.ts @@ -8,7 +8,7 @@ import axios, { import { serv_constants } from '@src/store/Modules/serv_constants' // import { TokenHelper } from "./token-helper"; -let initialized: boolean = false +let initialized = false interface IRequestConfig extends AxiosRequestConfig { ignore: number[] diff --git a/src/common/pattern.ts b/src/common/pattern.ts index fb2ca581..1fded4a7 100755 --- a/src/common/pattern.ts +++ b/src/common/pattern.ts @@ -2,12 +2,12 @@ export class Patterns { /** * Alphanumeric, spaces and dashes allowed. Min 2 characters length. */ - public static DisplayName: RegExp = /^[0-9a-zA-Z\s-]{2,}/i + public static DisplayName = /^[0-9a-zA-Z\s-]{2,}/i /** * Same pattern used by JQuery userName validation */ - public static Email: RegExp = /^((“[\w-\s]+”)|([\w-]+(?:\.[\w-]+)*)|(“[\w-\s]+”)([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}[0-9];{1,2})\]?$)/i + public static Email = /^((“[\w-\s]+”)|([\w-]+(?:\.[\w-]+)*)|(“[\w-\s]+”)([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}[0-9];{1,2})\]?$)/i /** * 6 to 20 characters string with at least one digit, one upper case letter, one lower case letter and one special symbol @@ -16,5 +16,5 @@ export class Patterns { * * 8 to 20 characters string with at least one digit, one upper case letter, one lower case letter and one special symbol */ - public static Password: RegExp = /^((?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,30})/i + public static Password = /^((?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,30})/i } diff --git a/src/components/CMyAvatar/CMyAvatar.ts b/src/components/CMyAvatar/CMyAvatar.ts index a1fb6afd..1dab33cb 100755 --- a/src/components/CMyAvatar/CMyAvatar.ts +++ b/src/components/CMyAvatar/CMyAvatar.ts @@ -18,8 +18,8 @@ export default defineComponent({ setup(props) { - let myicon = ref('') - let myimgint = ref('') + const myicon = ref('') + const myimgint = ref('') const userStore = useUserStore() const imgprofile = ref(userStore.my.profile.img) diff --git a/src/components/Footer/Footer.vue b/src/components/Footer/Footer.vue index 31a87ff3..b012677a 100755 --- a/src/components/Footer/Footer.vue +++ b/src/components/Footer/Footer.vue @@ -137,16 +137,16 @@ v-if="tools.getHttpForTelegram(rec.usertelegram)" fab-mini
- {{tools.getLabelByItem(myitemmenu, mythisfoot)}}
+ {{tools.getLabelByItem(myitemmenu)}}
    - {{tools.getLabelByItem(myitemmenu, mythisfoot)}}
+ {{tools.getLabelByItem(myitemmenu)}}
- +
diff --git a/src/globalroutines/indexdb.ts b/src/globalroutines/indexdb.ts index ec69f9c9..fc826a5c 100755 --- a/src/globalroutines/indexdb.ts +++ b/src/globalroutines/indexdb.ts @@ -74,7 +74,7 @@ async function readfromIndexDbToState(context: any, table: string) { }) } -function consolelogpao(str: string, str2: string = '', str3: string = '') { +function consolelogpao(str: string, str2 = '', str3 = '') { console.log(str, str2, str3) // Todos.mutations.setTestpao(str + str2 + str3) } diff --git a/src/model/GlobalStore.ts b/src/model/GlobalStore.ts index 8a4f12e3..80015103 100755 --- a/src/model/GlobalStore.ts +++ b/src/model/GlobalStore.ts @@ -353,7 +353,7 @@ export interface ITimeLineEntry { } export interface ITimeLineMain { - titlemain: IAllLang + titlemain: IAllLang | any body: ITimeLineEntry[] } @@ -374,9 +374,9 @@ export interface IGallery { } export interface IColl { - title: IAllLang + title: IAllLang | any date?: string - subtitle?: IAllLang + subtitle?: IAllLang | any img: string img2?: string linkagg?: string @@ -388,7 +388,7 @@ export interface IColl { } export interface ICollaborations { - withwhom_title: IAllLang + withwhom_title: IAllLang | any list: IColl[] } @@ -483,6 +483,22 @@ export interface IDataPass { fieldsvalue: object } +export interface IDataToSet { + id?: string | null + username?: string + table?: string + fieldsvalue?: any + unset?: any, + notifBot?: any | null + tipomsg?: number + invitante_username?: string + ind_order?: any + num_tess?: number + data?: any + myfunc?: any + inviaemail?: any +} + export interface INewsState { lastnewstosent: INewsToSent | null nextnewstosent: INewsToSent | null diff --git a/src/model/UserStore.ts b/src/model/UserStore.ts index a82326ab..566e6804 100755 --- a/src/model/UserStore.ts +++ b/src/model/UserStore.ts @@ -37,6 +37,8 @@ export interface IUserProfile { socio?: boolean socioresidente?: boolean consiglio?: boolean + resplist?: any + workerslist?: any } export interface IPaymentType { diff --git a/src/store/Api/ApiTypes.ts b/src/store/Api/ApiTypes.ts index 3b1b5d36..31da1b85 100755 --- a/src/store/Api/ApiTypes.ts +++ b/src/store/Api/ApiTypes.ts @@ -14,17 +14,17 @@ export class AxiosSuccess { } export class AxiosError { - public success: boolean = false + public success = false - public status: number = 0 + public status = 0 public data: any public code: any = 0 - public msgerr: string = '' + public msgerr = '' - constructor(status: number, data?: any, code?: any, msgerr: string = '') { + constructor(status: number, data?: any, code?: any, msgerr = '') { this.status = status this.data = data this.code = code diff --git a/src/store/Api/index.ts b/src/store/Api/index.ts index 7430453a..f3a25189 100755 --- a/src/store/Api/index.ts +++ b/src/store/Api/index.ts @@ -86,7 +86,7 @@ export namespace ApiTool { }) } - export async function SendReq(url: string, method: string, mydata: any, setAuthToken: boolean = false): Promise { + export async function SendReq(url: string, method: string, mydata: any, setAuthToken = false): Promise { const mydataout = { ...mydata, keyappid: process.env.PAO_APP_ID, @@ -160,7 +160,7 @@ export namespace ApiTool { let lettoqualcosa = false // console.log('A1) INIZIO.............................................................') - return globalroutines(null, 'readall', tablesync, null) + return globalroutines( 'readall', tablesync, null) .then((alldata) => { if (alldata === undefined) { console.log('alldata NON DEFINITA') @@ -182,10 +182,10 @@ export namespace ApiTool { .then((ris) => { ReceiveResponsefromServer(tablesync, nametab, method, ris.data) lettoqualcosa = true - return globalroutines(null, 'delete', tablesync, null, rec._id) + return globalroutines( 'delete', tablesync, null, rec._id) }) .then(() => { - return globalroutines(null, 'delete', 'swmsg', null, mystrparam) + return globalroutines( 'delete', 'swmsg', null, mystrparam) }).catch((err) => { if (err.msgerr) { if (err.msgerr.message.includes('Failed to fetch') || err.msgerr.message.includes('Network Error')) { @@ -194,7 +194,7 @@ export namespace ApiTool { } console.log(' [Alternative] !!!!!!!!!!!!!!! Error while sending data', err, errorfromserver, 'lettoqualcosa', lettoqualcosa) if (!errorfromserver) { - return globalroutines(null, 'delete', 'swmsg', null, mystrparam) + return globalroutines( 'delete', 'swmsg', null, mystrparam) } }) }) diff --git a/src/store/CalendarStore.ts b/src/store/CalendarStore.ts new file mode 100755 index 00000000..e53d34b4 --- /dev/null +++ b/src/store/CalendarStore.ts @@ -0,0 +1,200 @@ +import Api from '@api' +import { IBookedEvent, ICalendarState, IEvents } from 'model' + +import { serv_constants } from './Modules/serv_constants' +import { tools } from './Modules/tools' +import { defineStore } from 'pinia' +import { useUserStore } from '@store/UserStore' +import { useGlobalStore } from '@store/globalStore' +import { costanti } from '@costanti' + +export const useCalendarStore = defineStore('CalendarStore', { + state: (): ICalendarState => ({ + editable: false, + eventlist: [], + bookedevent: [], + operators: [], + internalpages: [], + wheres: [], + contribtype: [], + // --------------- + titlebarHeight: 0, + locale: 'it-IT', + maxDays: 1, + fiveDayWorkWeek: false, + shortMonthLabel: false, + showDayOfYearLabel: false, + shortWeekdayLabel: true, + shortIntervalLabel: false, + hour24Format: true, + hideHeader: false, + noScroll: false, + showMonthLabel: false, + showWorkWeeks: false, + intervalRange: { min: 9, max: 23 }, + intervalRangeStep: 1, + intervalHeight: 35, // 35 + resourceHeight: 80, // 60 + resourceWidth: 100, + dayHeight: 150, + enableThemes: false, + theme: {}, + }), + getters: { + + findEventBooked: (mystate: ICalendarState) => (myevent: IEvents, isconfirmed: boolean) => { + const userStore = useUserStore() + return mystate.bookedevent.find((bookedevent) => (bookedevent.id_bookedevent === myevent._id) && (bookedevent.userId === userStore.my._id) && ((isconfirmed && bookedevent.booked) || (!isconfirmed))) + }, + + getNumParticipants: (mystate: ICalendarState) => (myevent: IEvents, showall: boolean, tipo = 0): number => { + const userStore = useUserStore() + const myarr = mystate.bookedevent.filter((bookedevent) => (bookedevent.id_bookedevent === myevent._id) && (bookedevent.booked) && (showall || (!showall && bookedevent.userId === userStore.my._id)) && (((tipo === tools.peopleWhere.participants) && bookedevent.numpeople > 0) || ((tipo === tools.peopleWhere.lunch && bookedevent.numpeopleLunch! > 0) || (tipo === tools.peopleWhere.dinner && bookedevent.numpeopleDinner! > 0) || (tipo === tools.peopleWhere.dinnerShared && bookedevent.numpeopleDinnerShared! > 0)))) + if (myarr.length > 0) { + let ris = null + if (tipo === tools.peopleWhere.participants) { + ris = myarr.reduce((sum, bookedevent) => sum + bookedevent.numpeople, 0) + } else if (tipo === tools.peopleWhere.lunch) { + ris = myarr.reduce((sum, bookedevent) => sum + bookedevent.numpeopleLunch!, 0) + } else if (tipo === tools.peopleWhere.dinner) { + ris = myarr.reduce((sum, bookedevent) => sum + bookedevent.numpeopleDinner!, 0) + } else if (tipo === tools.peopleWhere.dinnerShared) { + ris = myarr.reduce((sum, bookedevent) => sum + bookedevent.numpeopleDinnerShared!, 0) + } + + return ris! + } else { + return 0 + } + }, + + getEventsBookedByIdEvent: (mystate: ICalendarState) => (idevent: string, showall: boolean) => { + const userStore = useUserStore() + return mystate.bookedevent.filter((bookedevent) => (bookedevent.id_bookedevent === idevent) && (bookedevent.booked) && (showall || (!showall && bookedevent.userId === userStore.my._id))) + }, + + getWhereRec: (mystate: ICalendarState) => (wherecode: string) => { + return mystate.wheres.find((mywhere) => mywhere.code === wherecode) + + }, + + getContribtypeRec: (mystate: ICalendarState) => (id: string) => { + const ctrec = mystate.contribtype.find((mycontr) => mycontr._id === id) + return (ctrec) + + }, + + getOperatorByUsername: (mystate: ICalendarState) => (username: string) => { + const ctrec = mystate.operators.find((rec) => rec.username === username) + return (ctrec) + + }, + + getImgTeacherByUsername: (mystate: ICalendarState) => (username: string): string => { + if (username === '') + return '' + // Check if is this User! + // @ts-ignore + const myop = this.getOperatorByUsername(username) + if (myop && !!myop.img && myop.img !== '' && myop.img !== 'undefined') { + return myop.img + } else { + return '' + } + }, + + getContribtypeById: (mystate: ICalendarState) => (id: string) => { + const ctrec = mystate.contribtype.find((mycontr) => mycontr._id === id) + return (ctrec) ? ctrec.label : '' + + }, + getContribtypeRecByLabel: (mystate: ICalendarState) => (label: string) => { + const ctrec = mystate.contribtype.find((mycontr) => mycontr.label === label) + return (ctrec) + + }, + + }, + actions: { + + getparambyevent(bookevent: IBookedEvent) { + const userStore = useUserStore() + return { + _id: bookevent._id, + id_bookedevent: bookevent.id_bookedevent, + infoevent: bookevent.infoevent, + numpeople: bookevent.numpeople, + numpeopleLunch: bookevent.numpeopleLunch, + numpeopleDinner: bookevent.numpeopleDinner, + numpeopleDinnerShared: bookevent.numpeopleDinnerShared, + msgbooking: bookevent.msgbooking, + datebooked: bookevent.datebooked, + userId: userStore.my._id, + booked: bookevent.booked, + modified: bookevent.modified, + } + }, + + async BookEvent( bookevent: IBookedEvent) { + console.log('BookEvent', bookevent) + + const param = this.getparambyevent(bookevent) + + return Api.SendReq('/booking', 'POST', param) + .then((res) => { + if (res.status === 200) { + console.log('datares', res.data) + if (res.data.code === serv_constants.RIS_CODE_OK) { + bookevent._id = res.data.id + if (bookevent.modified) { + + const foundIndex = this.bookedevent.findIndex((x) => x.id_bookedevent === bookevent.id_bookedevent) + if (foundIndex >= 0) + this.bookedevent[foundIndex] = bookevent + + } else { + this.bookedevent.push(bookevent) + } + return true + } + } + return false + }) + .catch((error) => { + console.error(error) + return false + }) + + }, + + async CancelEvent( { id }: { id: string }) { + const globalStore = useGlobalStore() + return globalStore.DeleteRec({ table: costanti.TABEVENTS, id }) + }, + + async CancelBookingEvent( { ideventbook, notify }: { ideventbook: string, notify: string }) { + console.log('CALSTORE: CancelBookingEvent', ideventbook, notify) + + return Api.SendReq('/booking/' + ideventbook + '/' + notify + '/' + process.env.APP_ID, 'DELETE', null) + .then((res) => { + if (res.status === 200) { + if (res.data.code === serv_constants.RIS_CODE_OK) { + + // Remove this record from my list + this.bookedevent = this.bookedevent.filter((eventbooked) => (eventbooked._id !== ideventbook)) + + return true + } + } + return false + + }) + .catch((error) => { + console.error(error) + // userStore.mutations.setErrorCatch(error) + return false + }) + }, + + }, +}) diff --git a/src/store/MessageStore.ts b/src/store/MessageStore.ts index 4925ae9c..e8026a1c 100755 --- a/src/store/MessageStore.ts +++ b/src/store/MessageStore.ts @@ -1,173 +1,137 @@ +import { defineStore } from 'pinia' import Api from '@api' -import { storeBuilder } from './Store/Store' -import { serv_constants } from '../Modules/serv_constants' -import { toolsext } from '@src/store/Modules/toolsext' -import { GlobalStore, UserStore, Todos, Projects, CalendarStore } from '@store' +import { serv_constants } from './Modules/serv_constants' -import { IMessage, IMessageState, StatusMessage } from '../../model' +import { IMessage, IMessageState, IMsgUsers, StatusMessage } from '../model' import { tools } from '@src/store/Modules/tools' import { MsgDefault } from '@src/model' import { shared_consts } from '@src/common/shared_vuejs' +import { useUserStore } from '@store/UserStore' -// State -const state: IMessageState = { - last_msgs: [], - users_msg: [] - // last_update: [] -} +export const useMessageStore = defineStore('MessageStore', { + state: (): IMessageState => ({ + last_msgs: [], + users_msg: [], + }), -const b = storeBuilder.module('MessageModule', state) + getters: { -namespace Getters { + getlasts_messages: (mystate: IMessageState) => (): IMessage[] => { + const ctrec = (mystate.last_msgs) ? mystate.last_msgs.slice(0, 5) : [] + // const ctrec = (mystate.msgs) ? mystate.msgs.slice().reverse().slice(0, 5) : [] + return (ctrec) - const getlasts_messages = b.read((mystate: IMessageState) => (): IMessage[] => { - const ctrec = (mystate.last_msgs) ? mystate.last_msgs.slice(0, 5) : [] - // const ctrec = (mystate.msgs) ? mystate.msgs.slice().reverse().slice(0, 5) : [] - return (ctrec) - - }, 'getlasts_messages') - - const getnumMsgUnread = b.read((mystate: IMessageState) => () => { - return mystate.last_msgs.filter((msg) => !msg.read).length - }, 'getnumMsgUnread') - - export const getters = { - get getlasts_messages() { - return getlasts_messages() }, - get getnumMsgUnread() { - return getnumMsgUnread() - } - } -} + getnumMsgUnread: (mystate: IMessageState) => () => { + return mystate.last_msgs.filter((msg) => !msg.read).length + }, -namespace Mutations { - export const mutations = { - } -} + }, + actions: { -function setMsg(arrmsg: IMessage[], username) { - // console.log('arrmsg', arrmsg) - if (arrmsg.length > 0) { - let users_msg = state.users_msg.find((rec) => rec.username === username) - if (!users_msg) { - state.users_msg.push({ username, msgs: [] }) - users_msg = state.users_msg.find((rec) => rec.username === username) - } - users_msg.msgs.push(...arrmsg) - // console.table(users_msg.msgs) + setMsg(arrmsg: IMessage[], username: string) { + // console.log('arrmsg', arrmsg) + const userStore = useUserStore() - // users_msg.msgs = tools.getUnique(users_msg.msgs, '_id') - // console.table(users_msg.msgs) - - if (users_msg.msgs) { - let userother = users_msg.msgs.slice(-1)[0].dest.username - if (userother === UserStore.state.my.username) - userother = users_msg.msgs.slice(-1)[0].origin.username - - let index = state.last_msgs.findIndex((rec) => (rec.dest.username === userother) || (rec.origin.username === userother)) - if (index >= 0) { - // Update last message - state.last_msgs[index] = users_msg.msgs.slice(-1)[0] - } else { - state.last_msgs.push(users_msg.msgs.slice(-1)[0]) - index = state.last_msgs.findIndex((rec) => (rec.dest.username === userother) || (rec.origin.username === userother)) - } - if (state.last_msgs[index]) - users_msg.lastdataread = state.last_msgs[index].datemsg - else - users_msg.lastdataread = tools.getLastDateReadReset() - - } else { - users_msg.lastdataread = tools.getLastDateReadReset() - } - - // console.log('RICeVUTO', arrmsg, 'lastdataread', users_msg.lastdataread) - // console.log('state.users_msg', users_msg) - } -} - -namespace Actions { - - async function updateMsgDataFromServer(context, { username, lastdataread } ) { - // console.log('updateMsgDataFromServer', username, lastdataread) - - return await Api.SendReq(`/sendmsg/${username}/${lastdataread}/${process.env.APP_ID}`, 'GET', null) - .then((res) => { - // console.log('res', res) - if (res.status === 200) { - setMsg(res.data.arrmsg, username) - return true + if (arrmsg.length > 0) { + let users_msg: any = this.users_msg.find((rec: IMsgUsers) => rec.username === username) + if (!users_msg) { + this.users_msg.push({ username, msgs: [] }) + users_msg = this.users_msg.find((rec) => rec.username === username) } - return false - }) - .catch((error) => { - console.error(error) - return false - }) + users_msg.msgs.push(...arrmsg) + // console.table(users_msg.msgs) - } + // users_msg.msgs = tools.getUnique(users_msg.msgs, '_id') + // console.table(users_msg.msgs) - async function SendMsgEvent(context, msg: IMessage) { - console.log('SendMsgEvent', msg) + if (users_msg.msgs) { + let userother = users_msg.msgs.slice(-1)[0].dest.username + if (userother === userStore.my.username) + userother = users_msg.msgs.slice(-1)[0].origin.username - const data: IMessage = { ...MsgDefault, ...msg} + let index = this.last_msgs.findIndex((rec: IMessage) => (rec.dest!.username === userother) || (rec.origin!.username === userother)) + if (index >= 0) { + // Update last message + this.last_msgs[index] = users_msg.msgs.slice(-1)[0] + } else { + this.last_msgs.push(users_msg.msgs.slice(-1)[0]) + index = this.last_msgs.findIndex((rec: IMessage) => (rec.dest!.username === userother) || (rec.origin!.username === userother)) + } + if (this.last_msgs[index]) + users_msg.lastdataread = this.last_msgs[index].datemsg + else + users_msg.lastdataread = tools.getLastDateReadReset() - data.source.page = '' - data.idapp = process.env.APP_ID - data.origin.idapp = process.env.APP_ID - data.origin.username = UserStore.state.my.username - data.datemsg = tools.getDateNow() - data.status = StatusMessage.WaitingToSend - // Options - data.options = tools.SetBit(data.options, shared_consts.MessageOptions.Notify_ByEmail) - data.options = tools.SetBit(data.options, shared_consts.MessageOptions.Notify_ByPushNotification) + } else { + users_msg.lastdataread = tools.getLastDateReadReset() + } - // console.log('DOPO:') - // console.table(data) + // console.log('RICeVUTO', arrmsg, 'lastdataread', users_msg.lastdataread) + // console.log('this.users_msg', users_msg) + } + }, - return await Api.SendReq('/sendmsg', 'POST', data) - .then((res) => { - // console.log('res', res) - if (res.status === 200) { - if (res.data.code === serv_constants.RIS_CODE_OK) { - data._id = res.data.id + async updateMsgDataFromServer({ username, lastdataread }: {username: string, lastdataread: Date}) { + // console.log('updateMsgDataFromServer', username, lastdataread) - const myarr = [] - myarr.push(data) - - setMsg(myarr, data.dest.username) + return Api.SendReq(`/sendmsg/${username}/${lastdataread}/${process.env.APP_ID}`, 'GET', null) + .then((res) => { + // console.log('res', res) + if (res.status === 200) { + this.setMsg(res.data.arrmsg, username) return true } - } - return false - }) - .catch((error) => { - console.error(error) - return false - }) + return false + }) + .catch((error) => { + console.error(error) + return false + }) + }, - } + async SendMsgEvent(msg: IMessage) { + console.log('SendMsgEvent', msg) - export const actions = { - updateMsgDataFromServer: b.dispatch(updateMsgDataFromServer), - SendMsgEvent: b.dispatch(SendMsgEvent) - } + const data: IMessage = { ...MsgDefault, ...msg } -} + const userStore = useUserStore() -const stateGetter = b.state() + data.source!.page = '' + data.idapp = process.env.APP_ID + data.origin!.idapp = process.env.APP_ID + data.origin!.username = userStore.my.username + data.datemsg = tools.getDateNow() + data.status = StatusMessage.WaitingToSend + // Options + data.options = tools.SetBit(data.options, shared_consts.MessageOptions.Notify_ByEmail) + data.options = tools.SetBit(data.options, shared_consts.MessageOptions.Notify_ByPushNotification) -// Module -const MessageModule = { - get state() { - return stateGetter() + // console.log('DOPO:') + // console.table(data) + + return Api.SendReq('/sendmsg', 'POST', data) + .then((res) => { + // console.log('res', res) + if (res.status === 200) { + if (res.data.code === serv_constants.RIS_CODE_OK) { + data._id = res.data.id + + const myarr = [] + myarr.push(data) + + this.setMsg(myarr, data.dest!.username!) + return true + } + } + return false + }) + .catch((error) => { + console.error(error) + return false + }) + }, }, - actions: Actions.actions, - getters: Getters.getters, - mutations: Mutations.mutations -} - -export default MessageModule +}) diff --git a/src/store/Modules/ApiTables.ts b/src/store/Modules/ApiTables.ts index 3a1d99fc..b2b0770a 100755 --- a/src/store/Modules/ApiTables.ts +++ b/src/store/Modules/ApiTables.ts @@ -18,6 +18,8 @@ export function getLinkByTableName(nametable: string) { return '' } +export const LIST_START = null + export const DB = { CMD_SYNC: 'sync', CMD_SYNC_NEW: 'sync-new', @@ -40,7 +42,7 @@ export function allTables() { } async function updatefromIndexedDbToState(nametab: string) { - await globalroutines(null, 'updatefromIndexedDbToState', nametab, null) + await globalroutines( 'updatefromIndexedDbToState', nametab, null) .then(() => { console.log('updatefromIndexedDbToState! ') return true @@ -51,7 +53,7 @@ async function checkPendingMsg() { // console.log('checkPendingMsg') const globalStore = useGlobalStore() - const config = await globalroutines(null, 'read', 'config', null, '1') + const config = await globalroutines( 'read', 'config', null, '1') // console.log('config', config) try { @@ -68,7 +70,7 @@ async function checkPendingMsg() { // ... } - return new Promise((resolve, reject) => globalroutines(null, 'count', 'swmsg') + return new Promise((resolve, reject) => globalroutines( 'count', 'swmsg') .then((count) => { if (count > 0) { return resolve(true) @@ -83,7 +85,7 @@ function useServiceWorker() { // If something in the call of Service Worker went wrong (Network or Server Down), then retry ! async function sendSwMsgIfAvailable() { - let something = false + const something = false if (useServiceWorker()) { console.log(' -------- sendSwMsgIfAvailable') @@ -91,7 +93,7 @@ async function sendSwMsgIfAvailable() { const count = await checkPendingMsg() if (count) { return navigator.serviceWorker.ready - .then(() => globalroutines(null, 'readall', 'swmsg') + .then(() => globalroutines( 'readall', 'swmsg') .then((arr_recmsg) => { if (arr_recmsg.length > 0) { // console.log('---------------------- 2) navigator (2) .serviceWorker.ready') @@ -269,7 +271,7 @@ async function Sync_Execute(cmd: string, tablesync: string, nametab: string, met if (useServiceWorker()) { return navigator.serviceWorker.ready .then((sw) => { - globalroutines(null, 'write', tablesync, item, id) + globalroutines( 'write', tablesync, item, id) .then((ris) => { console.log('ris write:', ris) const sep = '|' @@ -285,7 +287,7 @@ async function Sync_Execute(cmd: string, tablesync: string, nametab: string, met // return sw.sync.register(multiparams) // } else { */ - return globalroutines(null, 'write', 'swmsg', mymsgkey, multiparams) + return globalroutines( 'write', 'swmsg', mymsgkey, multiparams) .then((ris2) => Api.syncAlternative(multiparams)) .then(() => { let data = null @@ -429,7 +431,7 @@ export async function table_ModifyRecord(nametable: string, myitem: any, listFie let miorec: any = null if (useServiceWorker()) { // get record from IndexedDb - miorec = await globalroutines(null, 'read', nametable, null, myobjsaved._id) + miorec = await globalroutines( 'read', nametable, null, myobjsaved._id) if (miorec === undefined) { console.log('~~~~~~~~~~~~~~~~~~~~ !!!!!!!!!!!!!!!!!! Record not Found !!!!!! id=', myobjsaved._id) @@ -457,7 +459,7 @@ export async function table_ModifyRecord(nametable: string, myitem: any, listFie if (useServiceWorker()) { // 2) Modify on IndexedDb console.log('// 2) Modify on IndexedDb', miorec) - return globalroutines(null, 'write', nametable, miorec) + return globalroutines( 'write', nametable, miorec) .then((ris) => Sync_SaveItem(nametable, 'PATCH', miorec)) // 3) Modify on the Server (call) } return Sync_SaveItem(nametable, 'PATCH', miorec) @@ -472,7 +474,7 @@ export function table_DeleteRecord(nametable: string, myobjtrov: any, id: any) { mymodule.deletemyitem(myobjtrov) // 2) Delete from the IndexedDb - globalroutines(null, 'delete', nametable, null, id) + globalroutines( 'delete', nametable, null, id) // 3) Delete from the Server (call) Sync_DeleteItem(nametable, myobjtrov, id) @@ -485,7 +487,7 @@ export function table_HideRecord(nametable: string, myobjtrov: any, id: any) { mymodule.deletemyitem(myobjtrov) // 2) Delete from the IndexedDb - globalroutines(null, 'delete', nametable, null, id) + globalroutines( 'delete', nametable, null, id) // 3) Hide from the Server (call) Sync_DeleteItem(nametable, myobjtrov, id) diff --git a/src/store/Modules/tools.ts b/src/store/Modules/tools.ts index 1956eef7..8fec46d7 100644 --- a/src/store/Modules/tools.ts +++ b/src/store/Modules/tools.ts @@ -1,12 +1,12 @@ import { translation } from '@store/Modules/translation' import { IColl, - ICollaborations, + ICollaborations, IDataToSet, IEvents, IListRoutes, IParamDialog, IPathFile, - IProject, ITimeLineEntry, + IProject, ITimeLineMain, ITodo, IUserFields, @@ -16,22 +16,24 @@ import { import { lists } from '@store/Modules/lists' import { costanti } from '@store/Modules/costanti' -import { date, Screen } from 'quasar' +import { copyToClipboard, date, Screen, useQuasar, colors, Cookies, scroll } from 'quasar' -import { toolsext } from '@store/Modules/toolsext' +const { getScrollTarget, setScrollPosition } = scroll +import { func_tools, toolsext } from '@store/Modules/toolsext' import { preloadedimages, static_data } from '@src/db/static_data' import { useGlobalStore } from '@store/globalStore' -import globalroutines from '@src/boot/globalroutines' +import globalroutines from '../../globalroutines/index' import { useI18n } from '@src/boot/i18n' import { RouteNames } from '@src/router/route-names' import messages from '@src/statics/i18n' import { shared_consts } from '@src/common/shared_vuejs' import * as ApiTables from '@store/Modules/ApiTables' import translate from '@src/globalroutines/util' -import { serv_constants } from "@store/Modules/serv_constants" -import { useProjectstore } from "@store/projects" -import { useTodoStore } from "@store/Todos" -import { useUserStore } from "@store/UserStore" +import { serv_constants } from '@store/Modules/serv_constants' +import { useProjectStore } from '@store/Projects' +import { useTodoStore } from '@store/Todos' +import { useUserStore } from '@store/UserStore' +import { useCalendarStore } from '@store/CalendarStore' export interface INotify { color?: string | 'primary' @@ -1197,6 +1199,7 @@ export const tools = { getStatusListByInd(index: number) { try { + // @ts-ignore const arr: any = this.selectStatus[toolsext.getLocale() || 'it'] for (const rec of arr) { if (rec.value === index) { @@ -1212,6 +1215,7 @@ export const tools = { getPriorityByInd(index: number) { // console.log('LANG in PRIOR', toolsext.getLocale()) try { + // @ts-ignore const arr: any = lists.selectPriority[toolsext.getLocale() || 'it'] for (const rec of arr) { if (rec.value === index) { @@ -1454,10 +1458,6 @@ export const tools = { }) }, - isMobile(): boolean { - return (Screen.width < 450) - }, - getimgbysize(dir: string, file: string): string { const myimage = dir + file // console.log('includes = ', static_data.preLoadImages.map((a) => a.imgname).includes(myimage), myimage) @@ -1539,8 +1539,6 @@ export const tools = { }, - - getIndexById(myarr: any, id: any) { if (myarr === undefined) return -1 @@ -1568,7 +1566,7 @@ export const tools = { return -1 } - let trovato: boolean = false + let trovato = false console.log('priority', priority) @@ -1605,7 +1603,7 @@ export const tools = { , getModulesByTable(nametable: string) { - const projects = useProjectstore() + const projects = useProjectStore() const todos = useTodoStore() if (nametable === 'todos') { return todos @@ -1621,7 +1619,7 @@ export const tools = { todos.todos = this.jsonCopy(myarr) return todos.todos } else if (nametable === 'projects') { - const projects = useProjectstore() + const projects = useProjectStore() projects.projects = this.jsonCopy(myarr) return projects.projects } @@ -1635,12 +1633,13 @@ export const tools = { getLastListNotCompleted(nametable: string, cat: string, tipoproj: string) { // console.log('getLastListNotCompleted') // const module = this.getModulesByTable(nametable) - let arr = [] - const projects = useProjectstore() + let arr: any = [] + const projects = useProjectStore() + const todos = useTodoStore() if (nametable === 'projects') - arr = projects.getters.projs_dacompletare(cat, tipoproj) + arr = projects.projs_dacompletare(cat, tipoproj) else if (nametable === 'todos') - arr = Todos.getters.items_dacompletare(cat) + arr = todos.items_dacompletare(cat) if (!!arr) return (arr.length > 0) ? arr[arr.length - 1] : null @@ -1663,7 +1662,7 @@ export const tools = { , json2array(json: any) { - const result = [] + const result: any = [] const keys = Object.keys(json) keys.forEach((key) => { result.push(json[key]) @@ -1698,12 +1697,13 @@ export const tools = { executefunc(myself: any, table: string, func: number, par: IParamDialog) { const globalStore = useGlobalStore() + const calendarStore = useCalendarStore() if (func === lists.MenuAction.DELETE) { // console.log('param1', par.param1) - CalendarStore.CancelBookingEvent({ + calendarStore.CancelBookingEvent({ ideventbook: par.param1, - notify: par.param2 === true ? '1' : '0' - }).then((ris) => { + notify: par.param2 === true ? '1' : '0', + }).then((ris: any) => { if (ris) { this.showPositiveNotif(myself.$q, myself.$t('cal.canceledbooking') + ' "' + par.param3 + '"') if (myself.bookEventpage) @@ -1713,17 +1713,17 @@ export const tools = { }) } else if (func === lists.MenuAction.DELETE_EVENT) { // console.log('param1', par.param1, 'id', par.param1._id) - CalendarStore.CancelEvent({ id: par.param1._id }).then((ris) => { + calendarStore.CancelEvent({ id: par.param1._id }).then((ris: any) => { if (ris) { // Remove this record from my list - CalendarStore.state.eventlist = CalendarStore.state.eventlist.filter((event) => (event._id !== par.param1._id)) + calendarStore.eventlist = calendarStore.eventlist.filter((event: IEvents) => (event._id !== par.param1._id)) this.showPositiveNotif(myself.$q, myself.$t('cal.canceledevent') + ' "' + par.param1.title + '"') } else this.showNegativeNotif(myself.$q, myself.$t('cal.cancelederrorevent')) }) } else if (func === lists.MenuAction.DELETE_EXTRALIST) { // console.log('param1', par.param1, 'id', par.param1._id) - globalStore.DeleteRec({ table: this.TABEXTRALIST, id: par.param1._id }).then((ris) => { + globalStore.DeleteRec({ table: toolsext.TABEXTRALIST, id: par.param1._id }).then((ris) => { if (ris) { myself.update_username() this.showPositiveNotif(myself.$q, myself.$t('reg.cancella_invitato') + ' "' + par.param1.name + ' ' + par.param1.surname + '"') @@ -1732,7 +1732,7 @@ export const tools = { }) } else if (func === lists.MenuAction.DELETE_USERLIST) { // console.log('param1', par.param1, 'id', par.param1._id) - globalStore.DeleteRec({ table: this.TABUSER, id: par.param1._id }).then((ris) => { + globalStore.DeleteRec({ table: toolsext.TABUSER, id: par.param1._id }).then((ris) => { if (ris) { myself.update_username() this.showPositiveNotif(myself.$q, myself.$t('reg.cancella_invitato') + ' "' + par.param1.name + ' ' + par.param1.surname + '"') @@ -1747,7 +1747,7 @@ export const tools = { myfunc: func, data: par.param2, username: par.param2.username, - notifBot: null + notifBot: null, } // if (par.param2.notifBot) @@ -1764,29 +1764,29 @@ export const tools = { }) } else if (func === lists.MenuAction.REGALA_INVITATO) { // console.log('param1', par.param1, 'id', par.param1._id) - let mydatatosave = { + let mydatatosave: IDataToSet = { id: null, username: '', table: '', fieldsvalue: {}, - notifBot: {} + notifBot: {}, } if (!!par.param1.invitante_username) { mydatatosave = { id: par.param1._id, username: par.param1.username, - table: this.TABLISTAINGRESSO, + table: toolsext.TABLISTAINGRESSO, fieldsvalue: { invitante_username: par.param2.aportador_solidario }, - notifBot: null + notifBot: {}, } } else { mydatatosave = { id: par.param1._id, username: '', - table: this.TABUSER, + table: toolsext.TABUSER, fieldsvalue: { aportador_solidario: par.param2.aportador_solidario }, - notifBot: null + notifBot: {}, } } @@ -1807,11 +1807,11 @@ export const tools = { }) } else if (func === lists.MenuAction.REGALA_INVITANTE) { // console.log('param1', par.param1, 'id', par.param1._id) - const mydatatosave = { + const mydatatosave: IDataToSet = { id: par.param1, - table: this.TABLISTAINGRESSO, + table: toolsext.TABLISTAINGRESSO, fieldsvalue: { invitante_username: par.param2.invitante_username, ind_order_ingr: par.param2.ind_order_ingr }, - notifBot: null + notifBot: null, } if (par.param3) { @@ -1827,14 +1827,14 @@ export const tools = { this.showNegativeNotif(myself.$q, myself.$t('db.recfailed')) }) } else if ((func === lists.MenuAction.AGGIUNGI_NUOVO_IMBARCO) || (func === lists.MenuAction.CANCELLA_IMBARCO)) { - const mydatatosave = { + const mydatatosave: IDataToSet = { username: par.param1.username, invitante_username: '', ind_order: -1, num_tess: 0, myfunc: func, data: par.param2, - notifBot: null + notifBot: null, } if (func === lists.MenuAction.CANCELLA_IMBARCO) { @@ -1863,7 +1863,7 @@ export const tools = { }) } else if (func === lists.MenuAction.SOSTITUISCI) { // console.log('param1', par.param1, 'id', par.param1._id) - const mydatatosave = { + const mydatatosave: IDataToSet = { id: par.param1._id, ind_order: par.param1.ind_order, myfunc: func, @@ -1909,7 +1909,7 @@ export const tools = { globalStore.InviaMsgADonatori({ msgobj: par.param1, navemediatore: par.param2, - tipomsg: par.param1.tipomsg + tipomsg: par.param1.tipomsg, }).then((ris) => { if (ris) { if (par.param1.inviareale) @@ -1925,7 +1925,7 @@ export const tools = { flotta: par.param1, inviareale: par.param2.inviareale, inviaemail: par.param2.inviaemail, - tipomsg: par.param3 + tipomsg: par.param3, }).then((ris) => { myself.loading = false if (ris) { @@ -1941,7 +1941,7 @@ export const tools = { globalStore.InviaMsgADonatori({ msgobj: par.param1, navemediatore: par.param2, - tipomsg: par.param1.tipomsg + tipomsg: par.param1.tipomsg, }) .then((ris) => { if (ris) { @@ -1950,16 +1950,16 @@ export const tools = { this.showNegativeNotif(myself.$q, myself.$t('db.recfailed')) }) } else if (func === lists.MenuAction.DONO_INVIATO) { - const mydatatosave = { + const mydatatosave: IDataToSet = { id: par.param1._id, - table: this.TABNAVI, + table: toolsext.TABNAVI, fieldsvalue: { date_made_gift: par.param1.date_made_gift, riga: par.param1.riga, col: par.param1.col, - commento_al_sognatore: par.param1.commento_al_sognatore + commento_al_sognatore: par.param1.commento_al_sognatore, }, - notifBot: null + notifBot: null, } if (par.param3) { @@ -1974,13 +1974,13 @@ export const tools = { this.showNegativeNotif(myself.$q, myself.$t('db.recfailed')) }) } else if (func === lists.MenuAction.DONO_RICEVUTO) { - let mydatatosave = { + const mydatatosave: IDataToSet = { id: par.param1._id, - table: this.TABNAVI, + table: toolsext.TABNAVI, fieldsvalue: {}, unset: null, notifBot: null, - tipomsg: this.TipoMsg.SEND_MSG_DONO_RICEVUTO_CORRETTAMENTE + tipomsg: this.TipoMsg.SEND_MSG_DONO_RICEVUTO_CORRETTAMENTE, } if (!!par.param1.date_made_gift) { @@ -1988,7 +1988,7 @@ export const tools = { made_gift: par.param1.made_gift, riga: par.param1.riga, col: par.param1.col, - date_made_gift: par.param1.date_made_gift + date_made_gift: par.param1.date_made_gift, } } else { mydatatosave.fieldsvalue = { made_gift: par.param1.made_gift, riga: par.param1.riga, col: par.param1.col } @@ -2025,7 +2025,7 @@ export const tools = { id, table, fieldsvalue: mydata, - notifBot: null + notifBot: null, } const globalStore = useGlobalStore() @@ -2041,17 +2041,17 @@ export const tools = { }, - async askConfirm($q: any, mytitle, mytext, ok, cancel, myself: any, table, funcok: number, funccancel: number, par: IParamDialog) { + async askConfirm($q: any, mytitle: string, mytext: string, ok: string, cancel: string, myself: any, table: string, funcok: number, funccancel: number, par: IParamDialog) { return $q.dialog({ message: mytext, html: true, ok: { label: ok, - push: true + push: true, }, title: mytitle, cancel: true, - persistent: false + persistent: false, }).onOk(() => { // console.log('OK') this.executefunc(myself, table, funcok, par) @@ -2095,13 +2095,14 @@ export const tools = { }, isRegistered() { - return localStorage.getItem(this.localStorage.userId) !== '' + return localStorage.getItem(toolsext.localStorage.userId) !== '' } , - checkIfUserExist(mythis) { + checkIfUserExist(mythis?: any) { + const userStore = useUserStore() - if (userStore.getters.isUserInvalid) { + if (userStore.isUserInvalid) { this.showNotif(mythis.$q, mythis.$t('todo.usernotdefined')) return false } @@ -2113,13 +2114,15 @@ export const tools = { } return true - } - , + }, - checkLangPassed(mylang) { + checkLangPassed(mylangpass: string) { // console.log('checkLangPassed ', mylang) + const userStore = useUserStore() - const mybrowserLang = Quasar.lang.isoName + let mylang: string = mylangpass + + // const mybrowserLang = Quasar.lang.isoName if (mylang !== '') { if ((mylang.toLowerCase() === 'enus') || (mylang.toLowerCase() === 'en-us') || (mylang.toLowerCase() === 'uk') @@ -2149,17 +2152,17 @@ export const tools = { mylang = 'it' // Metti come default - userStore.mutations.setlang(mylang) + userStore.setlang(mylang) } } if (!mylang) { - mylang = process.env.LANG_DEFAULT + mylang = process.env.LANG_DEFAULT! console.log('LANG DEFAULT: ', mylang) } if (toolsext.getLocale(true) === '') { - userStore.mutations.setlang(mylang) + userStore.setlang(mylang) } // console.log('mylang calc : ', mylang) @@ -2177,10 +2180,10 @@ export const tools = { consolelogpao(strlog: string, strlog2: any = '', strlog3: any = '') { // @ts-ignore - globalroutines(null, 'log', `${strlog} ${strlog2} ${strlog3}`, null) + globalroutines('log', `${strlog} ${strlog2} ${strlog3}`, null) }, - aspettansec(numsec) { + aspettansec(numsec: number) { return new Promise((resolve, reject) => { setTimeout(() => { resolve('anything') @@ -2189,8 +2192,9 @@ export const tools = { } , - dragula_option($service, dragname) { - $service.options(dragname, + dragula_option($service: any, dragname: any) { + //++Todo: Dragula + /*$service.options(dragname, { moves(el, source, handle, sibling) { return !el.classList.contains('donotdrag') // elements are always draggable by default @@ -2203,18 +2207,14 @@ export const tools = { }, direction: 'vertical' }) + + */ } , -// _.cloneDeep( Per clonare un oggetto + // _.cloneDeep( Per clonare un oggetto - isLoggedToSystem() { - const tok = this.getItemLS(this.localStorage.token) - return !!tok - } - , - - mapSort(linkedList) { + mapSort(linkedList: any) { console.log('mapSort') let sortedList = [] const map = new Map() @@ -2239,7 +2239,7 @@ export const tools = { // let i2 = 0 while (sortedList.length < linkedList.length) { // get the item with a previous item ID referencing the current item - const nextItem = linkedList[map.get(currentId)] + const nextItem: any = linkedList[map.get(currentId)] if (nextItem === undefined) { break } @@ -2283,7 +2283,7 @@ export const tools = { return sortedList }, - getProgressClassColor(progress) { + getProgressClassColor(progress: number) { if (progress > 66) { return 'highperc' } else if (progress > 33) { @@ -2294,7 +2294,7 @@ export const tools = { } , - getProgressColor(progress) { + getProgressColor(progress: number) { if (progress > 66) { return 'green' } else if (progress > 33) { @@ -2303,7 +2303,7 @@ export const tools = { return 'red' } }, - hasManyDays(mydatestart, mydateend) { + hasManyDays(mydatestart: Date | number | string | undefined, mydateend: Date | number | string | undefined) { if (mydateend) return this.getstrDate(mydatestart) !== this.getstrDate(mydateend) else @@ -2311,46 +2311,57 @@ export const tools = { }, isManager() { + const userStore = useUserStore() return userStore.isManager }, isSocioResidente() { + const userStore = useUserStore() return !!userStore.my.profile ? userStore.my.profile.socioresidente : false }, isConsiglio() { + const userStore = useUserStore() return !!userStore.my.profile ? userStore.my.profile.consiglio : false }, isSocio() { + const userStore = useUserStore() return !!userStore.my.profile ? userStore.my.profile.socio : false }, isResp() { + const userStore = useUserStore() return userStore.my.profile.resplist }, isWorkers() { + const userStore = useUserStore() return userStore.my.profile.workerslist }, isDepartment() { + const userStore = useUserStore() return userStore.isDepartment }, isAdmin() { + const userStore = useUserStore() return userStore.isAdmin }, isTutor() { + const userStore = useUserStore() return userStore.isTutor }, isZoomeri() { + const userStore = useUserStore() return userStore.isZoomeri }, isEditor() { + const userStore = useUserStore() return userStore.isEditor }, @@ -2446,7 +2457,7 @@ export const tools = { } }, - getstrDateTimeEvent(mythis, myevent, withhtml) { + getstrDateTimeEvent(mythis: any, myevent: IEvents, withhtml: boolean) { let mystr = '' // is same day? if (this.getstrDate(myevent.dateTimeStart) === this.getstrDate(myevent.dateTimeEnd)) { @@ -2483,7 +2494,7 @@ export const tools = { mystr = `${this.getstrShortDate(myevent.dateTimeStart)} - ${this.getstrTime(myevent.dateTimeStart)}` } else { - mystr = `${this.getstrVeryVeryShortDate(myevent.dateTimeStart)} - ${this.getstrShortDate(myevent.dateTimeEnd)}` + mystr = `${this.getstrVeryVeryShortDate(myevent.dateTimeStart!)} - ${this.getstrShortDate(myevent.dateTimeEnd)}` } @@ -2611,7 +2622,7 @@ export const tools = { } }, - firstchars_onedot(value, numchars = 200) { + firstchars_onedot(value: any, numchars = 200) { if (!value) { return '' } @@ -2706,7 +2717,7 @@ export const tools = { }, displayConfirmNotification() { - let options = null + let options: any = null if ('serviceWorker' in navigator) { options = { body: 'You successfully subscribed to our Notification service!', @@ -2720,8 +2731,8 @@ export const tools = { renotify: true, // if it's already sent, will Vibrate anyway actions: [ { action: 'confirm', title: 'Okay', icon: '/statics/icons/app-icon-96x96.png' }, - { action: 'cancel', title: 'Cancel', icon: '/statics/icons/app-icon-96x96.png' } - ] + { action: 'cancel', title: 'Cancel', icon: '/statics/icons/app-icon-96x96.png' }, + ], } if ('serviceWorker' in navigator) { @@ -2734,7 +2745,7 @@ export const tools = { } , - dataURItoBlob(dataURI) { + dataURItoBlob(dataURI: any) { const byteString = atob(dataURI.split(',')[1]) const mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0] const ab = new ArrayBuffer(byteString.length) @@ -2748,11 +2759,11 @@ export const tools = { , showNotificationExample() { - let options = null - const mythis = this + let options: any = null + const { t } = useI18n() if ('serviceWorker' in navigator) { options = { - body: mythis.$t('notification.subscribed'), + body: t('notification.subscribed'), icon: '/statics/icons/android-chrome-192x192.png', image: '/statics/images/imglogonotif.png', dir: 'ltr', @@ -2762,9 +2773,9 @@ export const tools = { tag: 'confirm-notification', renotify: true, // if it's already sent, will Vibrate anyway actions: [ - { action: 'confirm', title: mythis.$t('dialog.ok'), icon: '/statics/icons/android-chrome-192x192.png' } + { action: 'confirm', title: t('dialog.ok'), icon: '/statics/icons/android-chrome-192x192.png' }, // { action: 'cancel', title: 'Cancel', icon: '/statics/icons/android-chrome-192x192.png', } - ] + ], } navigator.serviceWorker.ready @@ -2772,33 +2783,13 @@ export const tools = { swreg.showNotification('aaa', options) }) } - } - , + }, - getemailto(text) { + getemailto(text: string) { return 'mailto:' + text - } - , + }, - askfornotification(mythis) { - console.log('askfornotification') - this.showNotif(mythis.$q, mythis.$t('notification.waitingconfirm'), { color: 'positive', icon: 'notifications' }) - - Notification.requestPermission((result) => { - console.log('User Choice', result) - if (result === 'granted') { - this.showNotif(mythis.$q, mythis.$t('notification.confirmed'), { color: 'positive', icon: 'notifications' }) - } else { - this.showNotif(mythis.$q, mythis.$t('notification.denied'), { color: 'negative', icon: 'notifications' }) - - // displayConfirmNotification(); - } - }) - - } - , - - heightgallery(coeff) { + heightgallery(coeff: any) { // console.log('heightgallery') return this.heightGallVal(coeff).toString() + 'px' }, @@ -2806,12 +2797,14 @@ export const tools = { heightGallVal(coeff = 1.33) { let maxh2 = 0 + const globalStore = useGlobalStore() + let myw = Screen.width if (!this.isMobile()) - if (GlobalStore.state.leftDrawerOpen) + if (globalStore.leftDrawerOpen) myw -= 300 if (!this.isMobile()) - if (GlobalStore.state.rightDrawerOpen) + if (globalStore.rightDrawerOpen) myw -= 300 maxh2 = (myw / coeff) + 20 @@ -2822,7 +2815,7 @@ export const tools = { } , - myheight_imgtitle(myheight ?, myheightmobile ?) { + myheight_imgtitle(myheight?: number, myheightmobile?: number) { let maxheight = 0 if (!!myheight) { maxheight = myheight @@ -2830,7 +2823,7 @@ export const tools = { if (myheight > 1000) { maxheight = 1000 } else { - maxheight = parseInt(myheight, 10) + maxheight = myheight } } } else { @@ -2851,7 +2844,7 @@ export const tools = { if (!!myheightmobile) { if (this.isMobile() && maxh2 > myheightmobile) - ris = parseInt(myheightmobile, 10) + ris = myheightmobile } // console.log('ris', ris) @@ -2958,7 +2951,8 @@ export const tools = { } , - padTime(val) { + padTime(valpass: string) { + let val = parseFloat(valpass) val = Math.floor(val) if (val < 10) { return '0' + val @@ -2968,8 +2962,9 @@ export const tools = { , getLocale(vero ?: boolean) { - if (UserStore) { - if (userStore.state) { + const userStore = useUserStore() + if (userStore) { + if (userStore) { return userStore.lang } } @@ -3020,7 +3015,7 @@ export const tools = { } } , - gettextdescr(data: ITimeLineEntry, numdescr = 'description' + gettextdescr(data: { [index: string]: any }, numdescr = 'description', ) { if (!!data[numdescr]) { if (data[numdescr][toolsext.getLocale()]) @@ -3034,7 +3029,7 @@ export const tools = { } , - getlink(data: ITimeLineEntry) { + getlink(data: any) { if (data.link_text[toolsext.getLocale()]) return data.link_text[toolsext.getLocale()] else { @@ -3043,7 +3038,7 @@ export const tools = { }, - getlinkurl(data: ITimeLineEntry) { + getlinkurl(data: any) { if (data.link_url_lang) { if (data.link_url_lang[toolsext.getLocale()]) { return data.link_url_lang[toolsext.getLocale()] @@ -3060,61 +3055,24 @@ export const tools = { return process.env.APP_ID }, - getLabelByItem(item, mythis) { + getLabelByItem(item: any) { if (!!item.name) - return mythis.$t(item.name) + return translate(item.name) else return item.text }, - getimgev(ev) { + getimgev(ev: IEvents) { if (!!ev.img_small) - return `statics/` + ev.img_small + return 'statics/' + ev.img_small else if (!!ev.img) - return `statics/` + ev.img + return 'statics/' + ev.img else return '' }, - getimgbysize(dir: string, file: string) { - const myimage = dir + file - // console.log('includes = ', static_data.preLoadImages.map((a) => a.imgname).includes(myimage), myimage) - let ris = '' - if (this.isMobile() && (preloadedimages().map((a) => a.imgname).includes(myimage))) { - ris = dir + 'mobile/' + file - } else { - ris = myimage - } - - // console.log('getimgbysize', ris) - - return ris - }, - - getaltimg(dir: string, file: string, alt?: string) { - const myimage = dir + file - const myrec = static_data.preLoadImages.find((rec) => rec.imgname === myimage) - if (myrec) - return (myrec) ? myrec.alt : 'my image' - else - return alt - }, - - getimgFullpathbysize(fileimg: string) { - if (!fileimg) - return { path: '', file: fileimg } - const ind = fileimg.lastIndexOf('/') - if (ind > 0) { - return { path: fileimg.substring(0, ind + 1), file: fileimg.substring(ind + 1) } - } else { - return { path: '', file: fileimg } - } - - } - , - - convertHTMLtoText(myhtml) { + convertHTMLtoText(myhtml: string) { let msg = myhtml msg = msg.replace('"', '"') msg = msg.replace('>', '>') @@ -3125,32 +3083,35 @@ export const tools = { return msg } , - gettextevent(mythis, myevent: IEvents) { - // return '"' + myevent.title + '" (' + func_this.getDateStr(myevent.date) + ') - ' + myevent.time - return '"' + myevent.title + '" (' + this.getstrDateEmailTime(mythis, myevent.dateTimeStart) + ')' + gettextevent(myevent: IEvents) { + // return '"' + myevent.title + '" (' + func_tools.getDateStr(myevent.date) + ') - ' + myevent.time + return '"' + myevent.title + '" (' + this.getstrDateEmailTime(myevent.dateTimeStart) + ')' }, - getlangforQuasar(mylang) { + getlangforQuasar(mylang: string) { if (mylang === 'enUs') return 'en-us' else return mylang }, - setLangAtt(mylang) { + setLangAtt(mylang: string) { console.log('setLangAtt =', mylang) // console.log('PRIMA this.$q.lang.isoName', this.$q.lang.isoName) + const $q = useQuasar() + const globalStore = useGlobalStore() + // dynamic import, so loading on demand only import(`quasar/lang/${this.getlangforQuasar(mylang)}`).then((lang) => { console.log(' Import dinamically lang =', lang) - Quasar.lang.set(this.getlangforQuasar(lang.default)) - import(`../../statics/i18n`).then(() => { - console.log(' *** MY LANG DOPO=', Quasar.lang.isoName) + $q.lang.set(this.getlangforQuasar(lang.default)) + import('../../statics/i18n').then(() => { + console.log(' *** MY LANG DOPO=', $q.lang.isoName) }) }) - GlobalStore.actions.addDynamicPages() + globalStore.addDynamicPages() // this.$q.lang.set(mylang) @@ -3167,30 +3128,30 @@ export const tools = { return 'Testo: ' + process.env.LOGO_REG }, - loginOk(mythis, ispageLogin: boolean) { + loginOk(mythis: any, ispageLogin: boolean) { // console.log('loginOk') + const userStore = useUserStore() if (toolsext.getLocale() !== '') { mythis.$i18n.locale = toolsext.getLocale() - } // Set Lang - else { - userStore.mutations.setlang(mythis.$i18n.locale) + } else { + userStore.setlang(mythis.$i18n.locale) } // Set Lang if (process.env.DEBUG) { console.log('LANG ORA=', toolsext.getLocale()) } - globalroutines(mythis, 'loadapp', '') + globalroutines('loadapp', '') this.SignIncheckErrors(mythis, this.OK, ispageLogin) } , - loginInCorso(mythis) { + loginInCorso(mythis: any) { // console.log('loginInCorso') - let msg = mythis.$t('login.incorso') + const msg = mythis.$t('login.incorso') // if (process.env.DEBUG) { // msg += ' ' + process.env.MONGODB_HOST // } @@ -3204,8 +3165,11 @@ export const tools = { return arr[0] + '//' + arr[2] }, - SignIncheckErrors(mythis, riscode, ispageLogin ?: boolean) { + SignIncheckErrors(mythis: any, riscode: any, ispageLogin ?: boolean) { // console.log('SignIncheckErrors: ', riscode) + const $q = useQuasar() + const globalStore = useGlobalStore() + const userStore = useUserStore() try { if (riscode === this.OK) { this.showNotif(mythis.$q, mythis.$t('login.completato'), { color: 'positive', icon: 'check' }) @@ -3229,7 +3193,7 @@ export const tools = { this.showNotif(mythis.$q, mythis.$t('login.errato'), { color: 'negative', icon: 'notifications' }) mythis.iswaitingforRes = false if (ispageLogin) { - GlobalStore.state.rightDrawerOpen = true + globalStore.rightDrawerOpen = true // mythis.$router.push('/signin') } }) @@ -3249,15 +3213,15 @@ export const tools = { this.showNotif(mythis.$q, mythis.$t('login.subaccount'), { color: 'negative', icon: 'notifications' }) mythis.iswaitingforRes = false if (ispageLogin) { - GlobalStore.state.rightDrawerOpen = true + globalStore.rightDrawerOpen = true // mythis.$router.push('/signin') } }) - } else if (riscode === this.ERR_SERVERFETCH) { + } else if (riscode === toolsext.ERR_SERVERFETCH) { this.showNotif(mythis.$q, mythis.$t('fetch.errore_server'), { color: 'negative', icon: 'notifications' }) - } else if (riscode === this.ERR_GENERICO) { - const msg = mythis.$t('fetch.errore_generico') + userStore.mutations.getMsgError(riscode) + } else if (riscode === toolsext.ERR_GENERICO) { + const msg = mythis.$t('fetch.errore_generico') + userStore.getMsgError(riscode) this.showNotif(mythis.$q, msg, { color: 'negative', icon: 'notifications' }) } else { this.showNotif(mythis.$q, 'Errore num ' + riscode, { color: 'negative', icon: 'notifications' }) @@ -3275,9 +3239,11 @@ export const tools = { } }, - SignUpcheckErrors(mythis, riscode: number, msg: string) { + SignUpcheckErrors(mythis: any, riscode: number, msg: string) { console.log('SignUpcheckErrors', riscode) - let endload = true + const endload = true + + const userStore = useUserStore() if (riscode === serv_constants.RIS_CODE_EMAIL_ALREADY_EXIST) { this.showNotif(mythis.$q, mythis.$t('reg.err.duplicate_email')) @@ -3294,22 +3260,22 @@ export const tools = { this.showNotif(mythis.$q, mythis.$t('reg.err.username_not_valid')) } else if (riscode === serv_constants.RIS_CODE_USERNAME_ALREADY_EXIST) { this.showNotif(mythis.$q, mythis.$t('reg.err.duplicate_username')) - } else if (riscode === this.ERR_SERVERFETCH) { + } else if (riscode === toolsext.ERR_SERVERFETCH) { this.showNotif(mythis.$q, mythis.$t('fetch.errore_server')) - } else if (riscode === this.ERR_GENERICO) { - const msg = mythis.$t('fetch.errore_generico') + userStore.mutations.getMsgError(riscode) - this.showNotif(mythis.$q, msg) + } else if (riscode === toolsext.ERR_GENERICO) { + const msg2 = mythis.$t('fetch.errore_generico') + userStore.getMsgError(riscode) + this.showNotif(mythis.$q, msg2) } else if (riscode === this.OK) { mythis.$router.push('/regok') this.showNotif(mythis.$q, mythis.$t('components.authentication.email_verification.link_sent', { botname: mythis.$t('ws.botname') }), { color: 'green', - textColor: 'black' + textColor: 'black', }) } else if (riscode === serv_constants.RIS_ISCRIZIONE_OK) { mythis.$router.push('/') this.showNotif(mythis.$q, mythis.$t('components.authentication.iscrizione_ok', { botname: mythis.$t('ws.botname') }), { color: 'green', - textColor: 'black' + textColor: 'black', }) } else { this.showNotif(mythis.$q, 'Errore num ' + riscode) @@ -3317,16 +3283,16 @@ export const tools = { return endload }, - isCssColor(color) { + isCssColor(color: any) { return !!color && !!color.match(/^(#|(rgb|hsl)a?\()/) }, - displayClasses(eventparam) { + displayClasses(eventparam: any) { return { // [`bg-${eventparam.bgcolor}`]: !this.isCssColor(eventparam.bgcolor), - 'text-white': !this.isCssColor(eventparam.bgcolor) + 'text-white': !this.isCssColor(eventparam.bgcolor), } }, - displayStyles(eventparam) { + displayStyles(eventparam: any) { const s = { color: '' } let mycol = eventparam.bgcolor @@ -3340,77 +3306,62 @@ export const tools = { } return s }, - CancelBookingEvent(mythis, eventparam: IEvents, bookeventid: string, notify: boolean) { + CancelBookingEvent(mythis: any, eventparam: IEvents, bookeventid: string, notify: boolean) { console.log('CancelBookingEvent ', eventparam) - this.askConfirm(mythis.$q, translate('cal.titlebooking'), translate('cal.cancelbooking') + ' ' + this.gettextevent(mythis, eventparam) + '?', translate('dialog.yes'), translate('dialog.no'), mythis, '', lists.MenuAction.DELETE, 0, { + this.askConfirm(mythis.$q, translate('cal.titlebooking'), translate('cal.cancelbooking') + ' ' + this.gettextevent(eventparam) + '?', translate('dialog.yes'), translate('dialog.no'), mythis, '', lists.MenuAction.DELETE, 0, { param1: bookeventid, param2: notify, - param3: eventparam.title + param3: eventparam.title, }) }, - CancelEvent(mythis, eventparam: IEvents) { + CancelEvent(mythis: any, eventparam: IEvents) { console.log('CancelEvent ', eventparam) - this.askConfirm(mythis.$q, translate('cal.event'), translate('cal.cancelevent') + ' ' + this.gettextevent(mythis, eventparam) + '?', translate('dialog.yes'), translate('dialog.no'), mythis, '', lists.MenuAction.DELETE_EVENT, 0, { + const $q = useQuasar() + this.askConfirm($q, translate('cal.event'), translate('cal.cancelevent') + ' ' + this.gettextevent(eventparam) + '?', translate('dialog.yes'), translate('dialog.no'), mythis, '', lists.MenuAction.DELETE_EVENT, 0, { param1: eventparam, - param2: true + param2: true, }) }, - AskGiaPartecipatoZoom(mythis, user) { + AskGiaPartecipatoZoom(mythis: any, user: any) { console.log('AskGiaPartecipatoZoom', user.username) - this.askConfirm(mythis.$q, translate('steps.zoom_gia_partecipato'), translate('steps.zoom_gia_partecipato'), translate('dialog.yes'), translate('dialog.no'), mythis, '', lists.MenuAction.ZOOM_GIA_PARTECIPATO, 0, { + const $q = useQuasar() + this.askConfirm($q, translate('steps.zoom_gia_partecipato'), translate('steps.zoom_gia_partecipato'), translate('dialog.yes'), translate('dialog.no'), mythis, '', lists.MenuAction.ZOOM_GIA_PARTECIPATO, 0, { param1: user, param2: user, param3: 'Confermato', }) }, - ActionRecTable(mythis, action, table, id, item, askaction) { + ActionRecTable(mythis: any, action: number, table: string, id: string, item: any, askaction: any) { // console.log('ActionRecTable', id) - return this.askConfirm(mythis.$q, 'Action', translate(askaction) + '?', translate('dialog.yes'), translate('dialog.no'), mythis, table, action, 0, { + const $q = useQuasar() + return this.askConfirm($q, 'Action', translate(askaction) + '?', translate('dialog.yes'), translate('dialog.no'), mythis, table, action, 0, { param1: id, - param2: item + param2: item, }) }, - async createNewRecord(mythis, table, data, withnotif = true) { - - const mydata = { - table, - data - } - - return await - GlobalStore.actions.saveTable(mydata) - .then((record) => { - if (withnotif) { - if (record) { - this.showPositiveNotif(mythis.$q, mythis.$t('db.recupdated')) - } else { - this.showNegativeNotif(mythis.$q, mythis.$t('db.recfailed')) - } - } - return record - }) - }, getheight(mythis: any) { // return height() return mythis.$q.screen.height }, - getwidth(mythis: any, withright = false, withleft = true) { + getwidth(mythis: any, withright = false, withleft = true): number { + const globalStore = useGlobalStore() // return height() let myw = mythis.$q.screen.width if (withleft) { - if (GlobalStore.state.leftDrawerOpen) + if (globalStore.leftDrawerOpen) myw -= 300 } if (withright) - if (GlobalStore.state.rightDrawerOpen) + if (globalStore.rightDrawerOpen) myw -= 300 return myw }, - getwidthscale(mythis, mywidth, maxwidth) { + getwidthscale(mythis: any, mywidthpass: string, maxwidth: string): number { + let mywidth = parseInt(mywidthpass) if (this.isMobile()) { // if (mywidth > this.getwidth(mythis) - 20) mywidth = this.getwidth(mythis, false, false) - 32 @@ -3419,10 +3370,10 @@ export const tools = { return mywidth } else { // console.log('this.getwidth(mythis) = ', this.getwidth(mythis)) - let myw = mywidth + ((this.getwidth(mythis, true) - mywidth) * 0.6) + let myw: number = mywidth + ((this.getwidth(mythis, true) - mywidth) * 0.6) // console.log('myw1 = ', myw) - if (myw > maxwidth) - myw = maxwidth + if (myw > parseInt(maxwidth)) + myw = parseInt(maxwidth) if (myw > this.getwidth(mythis) - 24) myw = this.getwidth(mythis) - 24 @@ -3431,13 +3382,13 @@ export const tools = { } }, - getheightbywidth(mythis, mywidth, myheight, maxwidth) { + getheightbywidth(mythis: any, mywidth: string, myheight: string, maxwidth: string) { // console.log('getheightbywidth') const myw = this.getwidthscale(mythis, mywidth, maxwidth) - return myw * (myheight / mywidth) + return myw * (parseInt(myheight) / parseInt(mywidth)) }, - isIsoDate(str) { + isIsoDate(str: string) { if (!/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z/.test(str)) return false const d = new Date(str) return d.toISOString() === str @@ -3483,13 +3434,13 @@ export const tools = { .filter(e => arr[e]).map(e => arr[e]) }, - getColorByIndexBest(index) { + getColorByIndexBest(index: any) { if (index < this.listBestColor.length - 1) return this.listBestColor[index] else return 'primary' }, - getCookie(mytok, def?) { + getCookie(mytok: any, def?: any) { const ris = Cookies.get(mytok) // console.log('getCookie', ris) if (!!ris) { @@ -3499,33 +3450,23 @@ export const tools = { } }, - setCookie(mytok, value: string) { + setCookie(mytok: any, value: string) { return Cookies.set(mytok, value) }, - removeCookie(mytok) { + removeCookie(mytok: any) { return Cookies.remove(mytok) }, - notshowPwd(payload) { - const mypay = { ...payload } - try { - if (!!mypay.password) { - mypay.password = '**********' - } - } catch (e) { - console.log('error', e) - } - return mypay - }, + scrollToTop() { const element = document.getElementById('mypage') this.scrollToElement(element) }, - scrollToElementId(myid) { + scrollToElementId(myid: string) { const element = document.getElementById(myid) this.scrollToElement(element) }, - scrollToElement(el) { + scrollToElement(el: any) { const target = getScrollTarget(el) const offset = el.offsetTop const duration = 500 @@ -3563,41 +3504,33 @@ export const tools = { metafunc(mythis: any) { return { title: mythis.t('ws.sitename'), - titleTemplate: (title) => `${this.getsuffisso()} ${mythis.mymeta.title} - ${mythis.t('ws.sitename')}`, + titleTemplate: (title: any) => `${this.getsuffisso()} ${mythis.mymeta.title} - ${mythis.t('ws.sitename')}`, meta: { keywords: { name: 'keywords', - content: mythis.mymeta.keywords + content: mythis.mymeta.keywords, }, description: { name: 'description', - content: mythis.mymeta.description + content: mythis.mymeta.description, }, - equiv: { 'http-equiv': 'Content-Type', 'content': 'text/html; charset=UTF-8' } - } + equiv: { 'http-equiv': 'Content-Type', 'content': 'text/html; charset=UTF-8' }, + }, } }, - isObject(anything: any) { - // Object.create(null) instanceof Object → false - return Object(anything) === anything - }, - isDebug() { - return process.env.DEV - }, - - isTest() { - return process.env.ISTEST === '1' - }, - geturlupload() { return process.env.MONGODB_HOST + '/upload' }, getheaders() { + const userStore = useUserStore() return [{ name: 'x-auth', value: userStore.x_auth_token }] }, getextfile(filename: string) { - return filename.split('.').pop().toLowerCase() + const mystr = filename.split('.') + if (mystr) + return mystr.pop()!.toLowerCase() + return '' }, getelembylang(arr: any) { @@ -3624,20 +3557,24 @@ export const tools = { }, - getValDb(keystr: string, serv: boolean, def?: any, table?: string, subkey?: any, id?: any, idmain?: any) { + getValDb(keystr: string, serv: boolean, def?: any, table?: string, subkey?: any, id?: any, idmain?: any): any { const globalStore = useGlobalStore() + const todos = useTodoStore() + const userStore = useUserStore() if (table === 'users') { if (keystr === 'profile') { + // @ts-ignore return userStore.my.profile[subkey] } else { + // @ts-ignore return userStore.my[keystr] } } else if (table === 'todos') { // console.log('id', id, 'idmain', idmain) - const indcat = Todos.state.categories.indexOf(idmain) + const indcat = todos.categories.indexOf(idmain) console.log('indcat', indcat) if (indcat >= 0) { - const myrec = Todos.state.todos[indcat].find((rec) => rec._id === id) + const myrec = todos.todos[indcat].find((rec: any) => rec._id === id) console.log('myrec', myrec) let ris = null if (myrec) { @@ -3649,7 +3586,7 @@ export const tools = { return '' } else { - const ris = globalStore.getters.getValueSettingsByKey(keystr, serv) + const ris = globalStore.getValueSettingsByKey(keystr, serv) if (ris === '') if (def !== undefined) @@ -3662,7 +3599,7 @@ export const tools = { }, - getkey(youtube: boolean, title: string, isnum: boolean) { + getkey(youtube: boolean, title: boolean, isnum: boolean) { let mykey = 'MP4' if (youtube) mykey = 'YT' @@ -3700,11 +3637,11 @@ export const tools = { }, getvideomp4yt(index: number) { - return [{ src: 'https://www.youtube.com/embed/' + this.getvideourl(index, true), type: 'video/mp4' } + return [{ src: 'https://www.youtube.com/embed/' + this.getvideourl(index, true), type: 'video/mp4' }, ] }, getvideomp4src(index: number) { - return [{ src: this.getvideourl(index, false), type: 'video/mp4' } + return [{ src: this.getvideourl(index, false), type: 'video/mp4' }, ] }, @@ -3717,11 +3654,11 @@ export const tools = { }, getpath(myvideo: string) { - return 'statics/video/' + func_this.getLocale() + '/' + myvideo + return 'statics/video/' + func_tools.getLocale() + '/' + myvideo }, mygetarrValDb(keystr: string, serv: boolean) { const globalStore = useGlobalStore() - const myval = globalStore.getters.getValueSettingsByKey(keystr, serv) + const myval = globalStore.getValueSettingsByKey(keystr, serv) // console.log('AA: myval', myval) try { if (myval) { @@ -3748,7 +3685,7 @@ export const tools = { return this.getelembylang(ris) }, - getvideoposter(index) { + getvideoposter(index: number) { return '' }, clone(obj: any) { @@ -3760,7 +3697,7 @@ export const tools = { return copy }, - geticon(langin) { + geticon(langin: string) { if (langin === '') return '' try { @@ -3923,9 +3860,10 @@ export const tools = { let id = '' const globalStore = useGlobalStore() if (globalStore.calzoom.length > 0) { + // @ts-ignore id = globalStore.calzoom.slice(-1)[0].id_conf_zoom.toString() } else { - id = '6668882000' + id = '0' } return 'https://zoom.us/j/' + id }, @@ -3942,9 +3880,10 @@ export const tools = { const msg = params.split('.') const lang = toolsext.getLocale() - const stringa = messages[lang] + // @ts-ignore + const stringa: string = messages[lang] - let ris = stringa + let ris: any = stringa if (!!ris) { msg.forEach((param) => { ris = ris[param] @@ -3974,7 +3913,7 @@ export const tools = { let req = 0 req += user.verified_email ? 1 : 0 - req += user.profile.teleg_id > 0 ? 1 : 0 + req += user.profile.teleg_id! > 0 ? 1 : 0 req += this.isBitActive(user.profile.saw_and_accepted, shared_consts.Accepted.CHECK_READ_GUIDELINES.value) ? 1 : 0 req += this.isBitActive(user.profile.saw_and_accepted, shared_consts.Accepted.CHECK_SEE_VIDEO_PRINCIPI.value) ? 1 : 0 // req += user.profile.saw_zoom_presentation ? 1 : 0 @@ -4089,6 +4028,8 @@ export const tools = { sito_online(pertutti: boolean) { + const userStore = useUserStore() + let ris = true const online = this.getValDb('SITO_ONLINE', false, true) ris = userStore.isAdmin && !pertutti ? true : online @@ -4132,9 +4073,10 @@ export const tools = { }, isselectPaypal() { + const userStore = useUserStore() if (userStore.my.profile) { if (userStore.my.profile.paymenttypes) { - if (userStore.my.profile.paymenttypes.includes('paypal')) { + if (userStore.my.profile.paymenttypes.includes({ key: 'paypal', label: 'paypal' })) { return true } } @@ -4144,9 +4086,10 @@ export const tools = { }, isselectPayeer() { + const userStore = useUserStore() if (userStore.my.profile) { if (userStore.my.profile.paymenttypes) { - if (userStore.my.profile.paymenttypes.includes('payeer')) { + if (userStore.my.profile.paymenttypes.includes({ key: 'payeer', label: 'payeer' })) { return true } } @@ -4156,9 +4099,10 @@ export const tools = { }, isselectRevolut() { + const userStore = useUserStore() if (userStore.my.profile) { if (userStore.my.profile.paymenttypes) { - if (userStore.my.profile.paymenttypes.includes('revolut')) { + if (userStore.my.profile.paymenttypes.includes({ key: 'revolut', label: 'revolut' })) { return true } } @@ -4168,9 +4112,10 @@ export const tools = { }, isselectAdvCash() { + const userStore = useUserStore() if (userStore.my.profile) { if (userStore.my.profile.paymenttypes) { - if (userStore.my.profile.paymenttypes.includes('advcash')) { + if (userStore.my.profile.paymenttypes.includes({ key: 'advcash', label: 'advcash' })) { return true } } @@ -4183,10 +4128,10 @@ export const tools = { const globalStore = useGlobalStore() // console.log('globalStore.groups', globalStore.groups) - const mylist = { + const mylist: any = { it: [], es: [], - enUs: [] + enUs: [], } let myrec = {} @@ -4195,7 +4140,7 @@ export const tools = { myrec = { id: mygroup._id, label: mygroup.descr, - value: mygroup._id + value: mygroup._id, } mylist.it.push(myrec) @@ -4207,10 +4152,10 @@ export const tools = { getRespList() { // console.log('globalStore.groups', globalStore.groups) - const mylist = { + const mylist: any = { it: [], es: [], - enUs: [] + enUs: [], } let myrec = {} @@ -4221,7 +4166,7 @@ export const tools = { myrec = { id: myresp._id, label: myresp.name + ' ' + myresp.surname, - value: myresp.username + value: myresp.username, } mylist.it.push(myrec) @@ -4233,10 +4178,10 @@ export const tools = { getWorkersList() { // console.log('globalStore.groups', globalStore.groups) - const mylist = { + const mylist: any = { it: [], es: [], - enUs: [] + enUs: [], } let myrec = {} @@ -4247,7 +4192,7 @@ export const tools = { myrec = { id: myresp._id, label: myresp.name + ' ' + myresp.surname, - value: myresp.username + value: myresp.username, } mylist.it.push(myrec) @@ -4257,14 +4202,15 @@ export const tools = { }, IsLogged() { - if (!!UserStore) + const userStore = useUserStore() + if (!!userStore) return userStore.isLogged else return false }, formatDate(mydate: any) { - let d = void 0 + let d: Date if (mydate !== void 0) { d = new Date(mydate) @@ -4279,7 +4225,7 @@ export const tools = { }, firstDayOfDate(mydate: any) { - let d = void 0 + let d: Date if (mydate !== void 0) { d = new Date(mydate) @@ -4294,7 +4240,7 @@ export const tools = { }, LastDayOfDate(mydate: any) { - let d = void 0 + let d: Date if (mydate !== void 0) { d = new Date(mydate) @@ -4319,7 +4265,7 @@ export const tools = { return [this.padTime(hours), this.padTime(minutes)].join(':') }, colourNameToHex(colour: string) { - const colours = { + const colours: any = { 'aliceblue': '#f0f8ff', 'antiquewhite': '#faebd7', 'aqua': '#00ffff', @@ -4460,14 +4406,16 @@ export const tools = { 'white': '#ffffff', 'whitesmoke': '#f5f5f5', 'yellow': '#ffff00', - 'yellowgreen': '#9acd32' + 'yellowgreen': '#9acd32', } - if (typeof colours[colour.toLowerCase()] != 'undefined') - return colours[colour.toLowerCase()] + const index: any = colour.toLowerCase() + + if (typeof colours[index] != 'undefined') + return colours[index] return false - } + }, // getLocale() { // if (navigator.languages && navigator.languages.length > 0) { diff --git a/src/store/Products.ts b/src/store/Products.ts index f1da89c8..599ebfce 100755 --- a/src/store/Products.ts +++ b/src/store/Products.ts @@ -5,16 +5,16 @@ import { serv_constants } from '@src/store/Modules/serv_constants' import * as Types from '@src/store/Api/ApiTypes' import { static_data } from '@src/db/static_data' import { shared_consts } from '@src/common/shared_vuejs' -import { tools } from "@store/Modules/tools" -import { defineStore } from "pinia" +import { tools } from '@store/Modules/tools' +import { defineStore } from 'pinia' import { useUserStore } from '@store/UserStore' -import { toolsext } from "@store/Modules/toolsext" +import { toolsext } from '@store/Modules/toolsext' export const useProducts = defineStore('Products', { state: (): IProductsState => ({ products: [], cart: { items: [], totalPrice: 0, totalQty: 0, userId: '' }, - orders: [] + orders: [], }), getters: { @@ -80,9 +80,9 @@ export const useProducts = defineStore('Products', { stars: 0, date: tools.getDateNow(), icon: '', - img: '' + img: '', } - } + }, }, @@ -106,7 +106,7 @@ export const useProducts = defineStore('Products', { weight: product.weight, quantity: order.quantity, - idStorehouse: order.idStorehouse + idStorehouse: order.idStorehouse, } if (product.storehouses.length === 1) { @@ -166,7 +166,7 @@ export const useProducts = defineStore('Products', { return ris }, - async loadProduct({ code }: {code: any}) { + async loadProduct({ code }: { code: any }) { console.log('loadProduct', code) const userStore = useUserStore() @@ -237,11 +237,11 @@ export const useProducts = defineStore('Products', { return ris }, - async removeFromCart({ order }: {order: IOrder}) { + async removeFromCart({ order }: { order: IOrder }) { const userStore = useUserStore() - return await Api.SendReq('/cart/' + userStore.my._id, 'DELETE', { orderId: order._id }) + return Api.SendReq('/cart/' + userStore.my._id, 'DELETE', { orderId: order._id }) .then((res) => { if (res.data.cart) { // console.log('RISULTANTE CATEGORIES DAL SERVER = ', res.data.categories) this.cart = res.data.cart @@ -253,7 +253,7 @@ export const useProducts = defineStore('Products', { }) }, - async addToCart({ product, order }: {product: IProduct, order: IOrder}) { + async addToCart({ product, order }: { product: IProduct, order: IOrder }) { const userStore = useUserStore() @@ -290,7 +290,7 @@ export const useProducts = defineStore('Products', { return ris }, - async addSubQtyToItem({ addqty, subqty, order } : { addqty: number, subqty: number, order: IOrder}) { + async addSubQtyToItem({ addqty, subqty, order } : { addqty: number, subqty: number, order: IOrder }) { const userStore = useUserStore() if (!static_data.functionality.ENABLE_ECOMMERCE) @@ -376,7 +376,7 @@ export const useProducts = defineStore('Products', { return ris }, - } + }, }) diff --git a/src/store/Projects.ts b/src/store/Projects.ts index 65c7a258..6e7e7e46 100755 --- a/src/store/Projects.ts +++ b/src/store/Projects.ts @@ -13,15 +13,12 @@ import { RouteNames } from '@src/router/route-names' import * as Types from '@src/store/Api/ApiTypes' import { serv_constants } from '@src/store/Modules/serv_constants' import { static_data } from '@src/db/static_data' -import { defineStore } from "pinia" -import { useUserStore } from "@store/UserStore" -import { useGlobalStore } from "@store/globalStore" +import { defineStore } from 'pinia' +import { useUserStore } from '@store/UserStore' +import { useGlobalStore } from '@store/globalStore' const nametable = 'projects' -// import _ from 'lodash' - - const listFieldsToChange: string [] = ['descr', 'respUsername', 'viceRespUsername', 'vice2RespUsername', 'longdescr', 'hoursplanned', 'hoursleft', 'hoursworked', 'id_parent', 'statusproj', 'category', 'expiring_at', 'priority', 'pos', 'groupId', 'enableExpiring', 'progressCalc', 'live_url', 'test_url', 'begin_development', 'begin_test', 'actualphase', 'totalphases', 'hoursweeky_plannedtowork', 'endwork_estimate', @@ -34,7 +31,7 @@ export const useProjectStore = defineStore('Projects', { showtype: costanti.ShowTypeTask.SHOW_LAST_N_COMPLETED, projects: [], insidePending: false, - visuLastCompleted: 10 + visuLastCompleted: 10, }), getters: { @@ -80,7 +77,7 @@ export const useProjectStore = defineStore('Projects', { respUsername: '', viceRespUsername: '', vice2RespUsername: '', - tipovisu: 0 + tipovisu: 0, } return obj @@ -118,11 +115,13 @@ export const useProjectStore = defineStore('Projects', { if (state.projects) { // console.log('listagerarchia', idparent) const myarrgerarchia: IMenuList[] = [] - let myidparent = idparent + let myidparent: string = idparent let precmyparent = '-1' while (state.projects && myidparent) { - const proj = state.projects.find((rec) => rec._id === myidparent) + // @ts-ignore + const proj = this.getRecordById(myidparent) + // const proj = state.projects.find((rec: IProject) => rec._id === myidparent) if (proj) { myarrgerarchia.push({ nametranslate: '', description: proj.descr, idelem: proj._id }) } else { @@ -131,7 +130,7 @@ export const useProjectStore = defineStore('Projects', { if (myidparent === proj.id_parent || (!proj.id_parent && (precmyparent === myidparent))) break precmyparent = myidparent - myidparent = proj.id_parent! + myidparent = proj.id_parent ? proj.id_parent : '' } // console.log(' myarrgerarchia', myarrgerarchia) return myarrgerarchia.reverse() @@ -250,7 +249,7 @@ export const useProjectStore = defineStore('Projects', { getFirstInherited(proj: IProject, idparent: string) { let myprojtocheck = null while (proj.privacyread === Privacy.inherited) { - myprojtocheck = this.projects.find((rec) => rec._id === idparent) + myprojtocheck = this.getRecordById(idparent) if (!myprojtocheck) return null @@ -263,7 +262,7 @@ export const useProjectStore = defineStore('Projects', { getFirstInheritedTipoVisu(proj: IProject, idparent: string) { let tipovisuproj = null while (!proj.tipovisu || proj.tipovisu <= 0) { - tipovisuproj = this.projects.find((rec) => rec._id === idparent) + tipovisuproj = this.getRecordById(idparent) if (!tipovisuproj) return null @@ -309,10 +308,9 @@ export const useProjectStore = defineStore('Projects', { else ris = projects.filter((proj: IProject) => (proj.id_parent === idproj)) - if (ris) - { // @ts-ignore - ris = ris.sort((a: IProject, b: IProject) => a.pos - b.pos) - } + if (ris) { // @ts-ignore + ris = ris.sort((a: IProject, b: IProject) => a.pos - b.pos) + } // console.log('idproj', idproj, 'projects', projects, 'getproj', tipoproj, 'ris=', ris) return ris @@ -396,7 +394,7 @@ export const useProjectStore = defineStore('Projects', { this.showtype = parseInt(globalStore.getConfigStringbyId({ id: costanti.CONFIG_ID_SHOW_TYPE_TODOS, - default: costanti.ShowTypeTask.SHOW_LAST_N_COMPLETED + default: costanti.ShowTypeTask.SHOW_LAST_N_COMPLETED, }), 10) if (process.env.DEBUG === '1') { @@ -432,7 +430,7 @@ export const useProjectStore = defineStore('Projects', { return ris }, - async deleteItem({ idobj }: { idobj: any }) { + async deleteItem({ idobj }: {idobj: any}) { console.log('deleteItem: KEY = ', idobj) const myarr = this.getarrByCategory('') @@ -458,7 +456,7 @@ export const useProjectStore = defineStore('Projects', { } }, - async dbInsert({ myobj, atfirst }: { myobj: IProject, atfirst: boolean}) { + async dbInsert({ myobj, atfirst }: { myobj: IProject, atfirst: boolean }) { const objproj = this.initcat() @@ -472,7 +470,7 @@ export const useProjectStore = defineStore('Projects', { objproj.actualphase = myobj.actualphase objproj.tipovisu = myobj.tipovisu - let elemtochange: IProject = { } + let elemtochange: IProject = {} const myarr = this.getarrByCategory(objproj.category!) @@ -513,7 +511,7 @@ export const useProjectStore = defineStore('Projects', { return id }, - async modify({ myitem, field }: { myitem: any, field: any } ) { + async modify({ myitem, field }: {myitem: any, field: any}) { return ApiTables.table_ModifyRecord(nametable, myitem, listFieldsToChange, field) }, diff --git a/src/store/Todos.ts b/src/store/Todos.ts index e03b4eb9..94009cfc 100755 --- a/src/store/Todos.ts +++ b/src/store/Todos.ts @@ -3,7 +3,7 @@ import { ITodosState, IParamTodo, IDrag, - IAction + IAction, } from 'model' import Api from '@api' @@ -16,29 +16,17 @@ import objectId from '@src/js/objectId' import { costanti } from '@src/store/Modules/costanti' import * as Types from '@src/store/Api/ApiTypes' import { static_data } from '@src/db/static_data' -import { defineStore } from "pinia" +import { defineStore } from 'pinia' import { useUserStore } from '@store/UserStore' -import { useGlobalStore } from "@store/globalStore" -import { toolsext } from "@store/Modules/toolsext" +import { useGlobalStore } from '@store/globalStore' +import { toolsext } from '@store/Modules/toolsext' const nametable = 'todos' // import _ from 'lodash' -const state: ITodosState = { - showtype: costanti.ShowTypeTask.SHOW_LAST_N_COMPLETED, - todos: {}, - categories: [], - // todos_changed: 1, - reload_fromServer: 0, - testpao: 'Test', - insidePending: false, - visuLastCompleted: 10 -} - const listFieldsToChange: string [] = ['descr', 'statustodo', 'category', 'expiring_at', 'priority', 'pos', 'enableExpiring', 'progress', 'phase', 'assigned_to_userId', 'hoursplanned', 'hoursworked', 'start_date', 'completed_at', 'themecolor', 'themebgcolor', 'assignedToUsers'] - export const useTodoStore = defineStore('Todos', { state: (): ITodosState => ( { @@ -53,9 +41,9 @@ export const useTodoStore = defineStore('Todos', { }), getters: { - getindexbycategory: (state: ITodosState) => (category: string): number => { - if (state.categories) { - return state.categories.indexOf(category) + getindexbycategory: (mystate: ITodosState) => (category: string): number => { + if (mystate.categories) { + return mystate.categories.indexOf(category) } return -1 }, @@ -92,7 +80,7 @@ export const useTodoStore = defineStore('Todos', { start_date: tools.getDateNull(), themecolor: 'blue', themebgcolor: 'white', - assignedToUsers: [] + assignedToUsers: [], } // return this.copy(objtodo) return objtodo @@ -112,10 +100,9 @@ export const useTodoStore = defineStore('Todos', { } } - if (arrout) - { // @ts-ignore - arrout = arrout.sort((a: ITodo, b: ITodo) => a.pos - b.pos) - } + if (arrout) { // @ts-ignore + arrout = arrout.sort((a: ITodo, b: ITodo) => a.pos - b.pos) + } // return tools.mapSort(arrout) return arrout @@ -123,7 +110,7 @@ export const useTodoStore = defineStore('Todos', { todos_completati: (state: ITodosState) => (cat: string): ITodo[] => { // @ts-ignore - let indcat = this.getindexbycategory(cat) + const indcat = this.getindexbycategory(cat) // console.log('todos_completati', cat, 'indcat=', indcat, 'this.categories=', this.categories) // @ts-ignore if (state.todos[indcat]) { @@ -140,10 +127,9 @@ export const useTodoStore = defineStore('Todos', { arrout = [] } - if (arrout) - { // @ts-ignore - arrout = arrout.sort((a: ITodo, b: ITodo) => a.pos - b.pos) - } + if (arrout) { // @ts-ignore + arrout = arrout.sort((a: ITodo, b: ITodo) => a.pos - b.pos) + } // console.log('arrout', arrout) @@ -163,7 +149,6 @@ export const useTodoStore = defineStore('Todos', { TodosCount: (state: ITodosState) => (cat: string): number => { // @ts-ignore const indcat = this.getindexbycategory(cat) - // @ts-ignore if (state.todos[indcat]) { // @ts-ignore return state.todos[indcat].length @@ -188,7 +173,6 @@ export const useTodoStore = defineStore('Todos', { actions: { gettodosByCategory(category: string): any[] { const indcat = this.categories.indexOf(category) - // @ts-ignore if (!this.todos[indcat]) { return [] } @@ -216,7 +200,7 @@ export const useTodoStore = defineStore('Todos', { }, createNewItem({ objtodo, atfirst, categorySel }: { objtodo: ITodo, atfirst: boolean, categorySel: string }) { - let indcat = state.categories.indexOf(categorySel) + let indcat = this.categories.indexOf(categorySel) if (indcat === -1) { this.categories.push(categorySel) indcat = this.categories.indexOf(categorySel) @@ -295,7 +279,7 @@ export const useTodoStore = defineStore('Todos', { this.showtype = parseInt(globalStore.getConfigStringbyId({ id: costanti.CONFIG_ID_SHOW_TYPE_TODOS, - default: costanti.ShowTypeTask.SHOW_LAST_N_COMPLETED + default: costanti.ShowTypeTask.SHOW_LAST_N_COMPLETED, }), 10) // console.log('ARRAY TODOS = ', this.todos) @@ -421,7 +405,7 @@ export const useTodoStore = defineStore('Todos', { idelemtochange: objtodo._id, prioritychosen: objtodo.priority, category: objtodo.category, - atfirst + atfirst, } } } @@ -437,7 +421,7 @@ export const useTodoStore = defineStore('Todos', { idelemtochange: objtodo._id, prioritychosen: objtodo.priority, category: objtodo.category, - atfirst + atfirst, } } } @@ -491,11 +475,11 @@ export const useTodoStore = defineStore('Todos', { globalStore.lastaction.type = 0 - return await this.movemyitem({ myitemorig: orig_obj, myitemdest: dest_obj }) + return this.movemyitem({ myitemorig: orig_obj, myitemdest: dest_obj }) } } } }, - } + }, }) diff --git a/src/store/UserStore.ts b/src/store/UserStore.ts index 99932189..9bb2d992 100755 --- a/src/store/UserStore.ts +++ b/src/store/UserStore.ts @@ -174,6 +174,14 @@ export const useUserStore = defineStore('UserStore', { return (trovato) || null }, + isTokenInvalid: (state: IUserState) => { + try { + return (state.my.tokens!.length <= 0) + } catch (e) { + return true + } + }, + isUserInvalid: (state: IUserState): boolean => { try { return (state.my._id === undefined) || (state.my._id.trim() === '') diff --git a/src/store/globalStore.ts b/src/store/globalStore.ts index 56d2b22f..f4e38477 100644 --- a/src/store/globalStore.ts +++ b/src/store/globalStore.ts @@ -1,13 +1,12 @@ import { defineStore } from 'pinia' import { - ICfgServer, IColGridTable, IConfig, IDataPass, IGlobalState, IListRoutes, ISettings, StateConnection, + ICfgServer, IColGridTable, IConfig, IDataToSet, IGlobalState, IListRoutes, IParamsQuery, 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' @@ -16,9 +15,33 @@ import { costanti } from '@costanti' import { fieldsTable } from '@store/Modules/fieldsTable' import { tools } from '@store/Modules/tools' import { shared_consts } from '@src/common/shared_vuejs' +import globalroutines from '../globalroutines/index' +import { useCalendarStore } from '@store/CalendarStore' +import urlBase64ToUint8Array from '@src/js/utility' +import translate from '@src/globalroutines/util' + const stateConnDefault = 'online' +async function getConfig(id: any) { + return globalroutines('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' + } + } else { + return 'offline' + } +} + export const useGlobalStore = defineStore('GlobalStore', { state: (): IGlobalState => ({ finishLoading: false, @@ -137,21 +160,27 @@ export const useGlobalStore = defineStore('GlobalStore', { 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 */ + getRespByUsername: (state: IGlobalState) => (username: string) => { + const rec = state.resps.find((recin: any) => recin.username === username) + return !!rec ? rec.name + ' ' + rec.surname : '' + }, + getListByTable: (state: IGlobalState) => (table: string): any => { let ris = null - if (table === 'disciplines') ris = state.disciplines + const calendarStore = useCalendarStore() + + 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 + else 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 @@ -168,7 +197,7 @@ export const useGlobalStore = defineStore('GlobalStore', { else if (table === 'sharewithus') ris = state.sharewithus else if (table === 'paymenttypes') ris = state.paymenttypes /* else if (table === 'bookings') - return CalendarStore.bookedevent + return calendarStore.bookedevent else if (table === 'users') return userStore.usersList else if (table === 'sendmsgs') @@ -187,9 +216,14 @@ export const useGlobalStore = defineStore('GlobalStore', { getCmdClick: (state: IGlobalState): string => (state.clickcmd ? state.clickcmd : ''), + gettemplemailbyId: (mystate: IGlobalState) => (templid: string): string => { + const myrec = mystate.templemail.find((rec) => rec._id === templid) + return (!!myrec) ? myrec.subject! : '' + }, + getValueSettingsByKey: (state: IGlobalState) => (key: any, serv: any): any | undefined => { // @ts-ignore - const myrec = getrecSettingsByKey(key, serv) + const myrec = this.getrecSettingsByKey(key, serv) if (myrec) { if ((myrec.type === costanti.FieldType.date) || (myrec.type === costanti.FieldType.onlydate)) return myrec.value_date @@ -200,8 +234,7 @@ export const useGlobalStore = defineStore('GlobalStore', { return '' }, - // @ts-ignore - setValueSettingsByKey: (state: IGlobalState) => ({ key, value, serv }): any => { + setValueSettingsByKey: (state: IGlobalState) => ({ key, value, serv }: { key: string, value: any, serv: boolean }): any => { // Update the Server // Update in Memory @@ -218,6 +251,7 @@ export const useGlobalStore = defineStore('GlobalStore', { console.log('setValueSettingsByKey value', value, 'myrec', myrec) } }, + }, actions: { @@ -303,63 +337,6 @@ export const useGlobalStore = defineStore('GlobalStore', { */ }, - 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() }, @@ -387,17 +364,31 @@ export const useGlobalStore = defineStore('GlobalStore', { 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 }) + return globalroutines('write', 'config', { _id: data._id, value: data.value }) }, - UpdateValuesInMemory(mydata: IDataPass): void { + /*setShowType(state: IGlobalState, showtype: number) { + console.log('setShowType', showtype) + const config = Getters.getConfigbyId(costanti.CONFIG_ID_SHOW_TYPE_TODOS) + console.log('config', config) + if (config) { + config.value = String(showtype) + Todos.showtype = parseInt(config.value, 10) + } else { + Todos.showtype = showtype + } + console.log('Todos.showtype', Todos.showtype) + GlobalStore.saveConfig({ _id: costanti.CONFIG_ID_SHOW_TYPE_TODOS, value: String(showtype) }) + + },*/ + + UpdateValuesInMemory(mydata: IDataToSet): void { const { id } = mydata const { table } = mydata try { - const mylist = this.getListByTable(table) - const mykey = fieldsTable.getKeyByTable(table) + const mylist = this.getListByTable(table!) + const mykey = fieldsTable.getKeyByTable(table!) if (mylist) { const myrec = mylist.find((event: any) => event[mykey] === id) @@ -414,6 +405,121 @@ export const useGlobalStore = defineStore('GlobalStore', { } }, + createPushSubscription() { + + // If Already subscribed, don't send to the Server DB + // if (state.wasAlreadySubOnDb) { + // // console.log('wasAlreadySubOnDb!') + // return + // } + + if (!static_data.functionality.PWA) + return + + if (!('serviceWorker' in navigator)) { + return + } + + if (!('PushManager' in window)) { + return + } + + console.log('createPushSubscription') + + let reg: any + const mykey = process.env.PUBLICKEY_PUSH + return navigator.serviceWorker.ready + .then((swreg) => { + reg = swreg + return swreg.pushManager.getSubscription() + }) + .then((subscription) => { + console.log('subscription = ', subscription) + + this.wasAlreadySubscribed = !(subscription === null) + + if (this.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') + const convertedVapidPublicKey = urlBase64ToUint8Array(mykey) + return reg.pushManager.subscribe({ + userVisibleOnly: true, + applicationServerKey: convertedVapidPublicKey, + }) + } + }) + .then((newSub) => { + this.saveNewSubscriptionToServer(newSub) + }) + .catch((err) => { + console.log('ERR createPushSubscription:', err) + }) + }, + + // Calling the Server to Save in the MongoDB the Subscriber + saveNewSubscriptionToServer(newSub: any) { + + const userStore = useUserStore() + + + if (!newSub) { + return + } + + if (userStore.isUserInvalid) { + return + } + + // console.log('saveSubscriptionToServer: ', newSub) + // console.log('context', context) + + let options = null + let notreg = false + + if (userStore.isTokenInvalid) { + notreg = true + } + + // If is not already stored in DB, then show the message to the user. + if (!this.wasAlreadySubscribed || notreg) { + options = { + title: tools.translate('notification.title_subscribed', [{ + strin: 'sitename', + strout: translate('ws.sitename'), + }]), + content: translate('notification.subscribed'), + openUrl: '/', + } + } + + const myres = { + options, + subs: newSub, + others: { + userId: userStore.my._id, + access: userStore.my.tokens![0].access, + }, + } + + return Api.SendReq('/subscribe', 'POST', myres) + .then((res) => { + this.wasAlreadySubscribed = true + this.wasAlreadySubOnDb = true + + if (res) + console.log('saveNewSubscriptionToServer: OK') + + localStorage.setItem(toolsext.localStorage.wasAlreadySubOnDb, String(this.wasAlreadySubOnDb)) + }) + .catch((e) => { + console.log('Error during Subscription!', e) + }) + }, + async deleteSubscriptionToServer() { console.log('DeleteSubscriptionToServer: ') @@ -426,10 +532,9 @@ export const useGlobalStore = defineStore('GlobalStore', { 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) - // } + for (const table of ApiTables.allTables()) { + await globalroutines('clearalldata', table, null) + } if (static_data.functionality.PWA) { if ('serviceWorker' in navigator) { @@ -474,7 +579,7 @@ export const useGlobalStore = defineStore('GlobalStore', { isok = true } - // ++Todo conv: this.arrConfig = await globalroutines(null, 'readall', 'config', null) + // ++Todo conv: this.arrConfig = await globalroutines( 'readall', 'config', null) return isok }, @@ -531,26 +636,416 @@ export const useGlobalStore = defineStore('GlobalStore', { }) }, + async sendPushNotif({ params }: { params: any }) { + + return Api.SendReq('/push/send', 'POST', { params }) + .then((res) => { + // console.table(res) + return res.data + }) + .catch((error) => { + console.log('error sendPushNotif', error) + return null + }) + }, + + async loadTable(params: IParamsQuery) { + // console.log('loadTable', params) + const userStore = useUserStore() + + return Api.SendReq('/gettable', 'POST', params) + .then((res) => { + // console.table(res) + return res.data + }) + .catch((error) => { + console.log('error loadTable', error) + userStore.setErrorCatch(error) + return null + }) + }, + + 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: IDataToSet) { + // 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) + }, + + async callFunz({ mydata }: { mydata: any }) { + // console.log('saveFieldValue', mydata) + + return Api.SendReq('/callfunz', 'PATCH', { data: mydata }) + .then((res) => { + if (res) { + return (res.data.code === serv_constants.RIS_CODE_OK) + } else + return false + }) + .catch((error) => { + return false + }) + }, + + async askFunz({ mydata }: { mydata: any }) { + // console.log('saveFieldValue', mydata) + + return Api.SendReq('/askfunz', 'PATCH', { data: mydata }) + .then((ris) => { + return ris.data.out + }) + .catch((error) => { + return null + }) + }, + + async DeleteRec({ table, id }: { table: string, id: string }) { + console.log('DeleteRec', table, id) + + return 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 DeleteFile({ filename }: { filename: string }) { + console.log('DeleteFile', filename) + + return Api.SendReq('/delfile', 'DELETE', { filename }) + .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 DuplicateRec({ table, id }: { table: string, id: string }) { + console.log('DuplicateRec', id) + + return 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 + }) + }, + + async InviaMsgADonatori({ msgobj, navemediatore, tipomsg }: { msgobj: any, navemediatore: any, tipomsg: any }) { + console.log('InviaMsgADonatori', msgobj) + + const mydata = { + idapp: process.env.APP_ID, + msgextra: msgobj.msgextra, + msgpar1: msgobj.msgpar1, + username: msgobj.username, + username_mitt: msgobj.username_mitt, + tipomsg, + inviareale: msgobj.inviareale, + navemediatore, + } + + return Api.SendReq('/dashboard/msgnave', 'POST', mydata) + .then((res) => { + if (res.status === 200) { + if (res.data.code === serv_constants.RIS_CODE_OK) { + return res.data.ris + } + } + return null + }) + .catch((error) => { + console.error(error) + return null + }) + }, + + async InviaMsgAFlotta({ flotta, inviareale, inviaemail, tipomsg }: { flotta: any, inviareale: boolean, inviaemail: boolean, tipomsg: any }) { + console.log('InviaMsgAFlotta') + + const mydata = { + idapp: process.env.APP_ID, + tipomsg, + flotta, + inviareale, + inviaemail, + } + + return Api.SendReq('/dashboard/msgflotta', 'POST', mydata) + .then((res) => { + if (res.status === 200) { + if (res.data.code === serv_constants.RIS_CODE_OK) { + return res.data.ris + } + } + return null + }) + .catch((error) => { + console.error(error) + return null + }) + }, + + async GetArrNavi() { + console.log('GetArrNavi') + + const mydata = { + idapp: process.env.APP_ID, + } + + return Api.SendReq('/dashboard/getnavi', 'POST', mydata) + .then((res) => { + if (res.status === 200) { + if (res.data.code === serv_constants.RIS_CODE_OK) { + return res.data.ris + } + } + return null + }) + .catch((error) => { + console.error(error) + return null + }) + }, + + async GetMsgTemplates() { + console.log('GetMsgTemplates') + + const mydata = { + idapp: process.env.APP_ID, + } + + return Api.SendReq('/dashboard/getmsg_templates', 'POST', mydata) + .then((res) => { + if (res.status === 200) { + if (res.data.code === serv_constants.RIS_CODE_OK) { + return res.data.ris + } + } + return null + }) + .catch((error) => { + console.error(error) + return null + }) + }, + + async GetNave({ riga, col, riga1don, col1don, ind_order }: { riga: any, col: any, riga1don: any, col1don: any, ind_order: number }) { + // console.log('GetNave') + + const mydata = { + idapp: process.env.APP_ID, + riga, + col, + riga1don, + col1don, + ind_order, + } + + return Api.SendReq('/dashboard/getnave', 'POST', mydata) + .then((res) => { + if (res.status === 200) { + if (res.data.code === serv_constants.RIS_CODE_OK) { + return res.data.ris + } + } + return null + }) + .catch((error) => { + console.error(error) + return null + }) + }, + + async GetData({ data }: { data: any }) { + console.log('GetData') + + const mydata = { + idapp: process.env.APP_ID, + data, + } + + return Api.SendReq('/dashboard/getdata', 'POST', mydata) + .then((res) => { + if (res.status === 200) { + if (res.data.code === serv_constants.RIS_CODE_OK) { + return res.data.ris + } + } + return null + }) + .catch((error) => { + console.error(error) + return null + }) + }, + + async GetArrDoniNavi({ ricalcola, showall }: { ricalcola: boolean, showall: boolean }) { + console.log('GetArrDoniNavi') + + const mydata = { + idapp: process.env.APP_ID, + ricalcola, + showall, + } + + return Api.SendReq('/dashboard/getdoninavi', 'POST', mydata) + .then((res) => { + if (res.status === 200) { + if (res.data.code === serv_constants.RIS_CODE_OK) { + return res.data.ris + } + } + return null + }) + .catch((error) => { + console.error(error) + return null + }) + }, + + async GetFlotte({ ricalcola, showall }: { ricalcola: boolean, showall: boolean }) { + console.log('GetFlotte') + + const mydata = { + idapp: process.env.APP_ID, + ricalcola, + showall, + } + + return Api.SendReq('/dashboard/getflotte', 'POST', mydata) + .then((res) => { + if (res.status === 200) { + if (res.data.code === serv_constants.RIS_CODE_OK) { + return res.data.arrflotte + } + } + return null + }) + .catch((error) => { + console.error(error) + return null + }) + }, + + async GetFlotta({ riga, col_prima, col_ultima }: { riga: any, col_prima: any, col_ultima: any }) { + console.log('GetFlotta') + + const mydata = { + idapp: process.env.APP_ID, + riga, + col_prima, + col_ultima, + } + + return Api.SendReq('/dashboard/getflotta', 'POST', mydata) + .then((res) => { + if (res.status === 200) { + if (res.data.code === serv_constants.RIS_CODE_OK) { + return res.data + } + } + return null + }) + .catch((error) => { + console.error(error) + return null + }) + }, + async loadSite() { const userStore = useUserStore() - // console.log('CalendarStore: loadAfterLogin') + // 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 + // 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 : [] + /* 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] : [] @@ -563,7 +1058,6 @@ export const useGlobalStore = defineStore('GlobalStore', { 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) @@ -595,7 +1089,7 @@ export const useGlobalStore = defineStore('GlobalStore', { const islogged = localStorage.getItem(toolsext.localStorage.username) console.log('islogged', islogged) - // CalendarStore.editable = userStore.isAdmin || userStore.isManager || userStore.isTutor + // calendarStore.editable = userStore.isAdmin || userStore.isManager || userStore.isTutor if (res.data.myuser === null) { if (islogged) { // Fai Logout