This commit is contained in:
Paolo Arena
2021-09-02 21:29:24 +02:00
parent 04a9ce2232
commit 1c3df0fac1
21 changed files with 1291 additions and 673 deletions

View File

@@ -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',
},
};

View File

@@ -9,7 +9,7 @@ export type Options = {
export function debounce<F extends Procedure>(
func: F,
waitMilliseconds: number = 50,
waitMilliseconds = 50,
options: Options = {
isImmediate: false,
},

View File

@@ -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[]

View File

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

View File

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

View File

@@ -137,16 +137,16 @@ v-if="tools.getHttpForTelegram(rec.usertelegram)" fab-mini
<div v-if="myitemmenu.infooter && tools.visumenu(myitemmenu)">
<div v-if="myitemmenu.solotitle">
<span class="footer_link">{{tools.getLabelByItem(myitemmenu, mythisfoot)}}</span><br/>
<span class="footer_link">{{tools.getLabelByItem(myitemmenu)}}</span><br/>
</div>
<div v-else>
<router-link :to="myitemmenu.path" custom v-slot="{ navigate }">
<span class="footer_link" @click="navigate" @keypress.enter="navigate" role="link"><span
v-if="myitemmenu.level_child > 0">&nbsp;&nbsp;&nbsp;</span>
{{tools.getLabelByItem(myitemmenu, mythisfoot)}}</span><br/>
{{tools.getLabelByItem(myitemmenu)}}</span><br/>
</router-link>
</div>
<!--<a :href="myitemmenu.path"><span class="footer_link">{{tools.getLabelByItem(myitemmenu, mythisfoot)}}</span></a><br/>-->
<!--<a :href="myitemmenu.path"><span class="footer_link">{{tools.getLabelByItem(myitemmenu)}}</span></a><br/>-->
</div>
</div>
</div>

View File

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

View File

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

View File

@@ -37,6 +37,8 @@ export interface IUserProfile {
socio?: boolean
socioresidente?: boolean
consiglio?: boolean
resplist?: any
workerslist?: any
}
export interface IPaymentType {

View File

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

View File

@@ -86,7 +86,7 @@ export namespace ApiTool {
})
}
export async function SendReq(url: string, method: string, mydata: any, setAuthToken: boolean = false): Promise<Types.AxiosSuccess | Types.AxiosError> {
export async function SendReq(url: string, method: string, mydata: any, setAuthToken = false): Promise<Types.AxiosSuccess | Types.AxiosError> {
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)
}
})
})

200
src/store/CalendarStore.ts Executable file
View File

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

View File

@@ -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<IMessageState>('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
})

View File

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

File diff suppressed because it is too large Load Diff

View File

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

View File

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

View File

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

View File

@@ -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() === '')

View File

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