- Update the way to use the data records on Vuex with Getters!

- Fix: mongodb call passing array todos and categiroes already splitted
This commit is contained in:
Paolo Arena
2019-02-27 02:58:41 +01:00
parent 0e98ac1eaa
commit fa17de24f0
60 changed files with 3133 additions and 1839 deletions

View File

@@ -1,4 +1,4 @@
APP_VERSION="0.0.45" APP_VERSION="0.0.47"
SERVICE_WORKER_FILE='service-worker.js' SERVICE_WORKER_FILE='service-worker.js'
APP_ID='1' APP_ID='1'
APP_URL='https://freeplanet.app' APP_URL='https://freeplanet.app'
@@ -7,7 +7,7 @@ LANG_DEFAULT='it'
PAO_APP_ID='KKPPAA5KJK435J3KSS9F9D8S9F8SD98F9SDF' PAO_APP_ID='KKPPAA5KJK435J3KSS9F9D8S9F8SD98F9SDF'
MASTER_KEY='KKPPSS5KJK435J3KSS9F9D8S9F8SD3CR3T' MASTER_KEY='KKPPSS5KJK435J3KSS9F9D8S9F8SD3CR3T'
MONGODB_HOST='http://localhost:3000' MONGODB_HOST='http://localhost:3000'
LOGO_REG='freeplanet-logo-full.svg' LOGO_REG="freeplanet-logo-full.svg"
TEST_EMAIL='paolo.arena77@gmail.com' TEST_EMAIL='paolo.arena77@gmail.com'
TEST_USERNAME='paoloar77' TEST_USERNAME='paoloar77'
TEST_PASSWORD='mypassword@1A' TEST_PASSWORD='mypassword@1A'

10
helpers.js Normal file
View File

@@ -0,0 +1,10 @@
const path = require('path');
const ROOT = path.resolve(__dirname, '.');
function root(args) {
args = Array.prototype.slice.call(arguments, 0);
return path.join.apply(path, [ROOT].concat(args));
}
exports.root = root;

2
package-lock.json generated
View File

@@ -22113,7 +22113,7 @@
}, },
"serve-static": { "serve-static": {
"version": "1.13.2", "version": "1.13.2",
"resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.13.2.tgz", "resolved": "https://registry.npmjs.org/serve-statics/-/serve-static-1.13.2.tgz",
"integrity": "sha512-p/tdJrO4U387R9oMjb1oj7qSMaMfmOyd4j9hOFoxZe2baQszgHcSWjuya/CiT5kgZZKRudHNOA0pYXOl8rQ5nw==", "integrity": "sha512-p/tdJrO4U387R9oMjb1oj7qSMaMfmOyd4j9hOFoxZe2baQszgHcSWjuya/CiT5kgZZKRudHNOA0pYXOl8rQ5nw==",
"dev": true, "dev": true,
"requires": { "requires": {

View File

@@ -1,7 +1,7 @@
// Configuration for your app // Configuration for your app
const path = require('path'); const path = require('path');
const helpers = require('./helpers');
const webpack = require('webpack') const webpack = require('webpack')
const envparser = require('./config/envparser') const envparser = require('./config/envparser')
@@ -12,24 +12,24 @@ const extendTypescriptToWebpack = (config) => {
.add('.ts', '.js', '.vue') .add('.ts', '.js', '.vue')
config.resolve config.resolve
.alias .alias
.set('@components', path.resolve(__dirname, 'src/components/index.ts')) .set('@components', helpers.root('src/components/index.ts'))
// .set('@components', path.resolve(__dirname, 'src/components')) // .set('@components', helpers.root('src/components'))
.set('@views', path.resolve(__dirname, 'src/components/views/index.ts')) .set('@views', helpers.root('src/components/views/index.ts'))
// .set('@views', path.resolve(__dirname, 'src/components/views')) // .set('@views', helpers.root('src/components/views'))
.set('@src', path.resolve(__dirname, 'src')) .set('@src', helpers.root('src'))
.set('@icons', path.resolve(__dirname, 'src/assets/icons')) .set('@css', helpers.root('src/assets/css/*'))
.set('@images', path.resolve(__dirname, 'src/assets/images')) .set('@icons', helpers.root('src/statics/icons/*'))
.set('@classes', path.resolve(__dirname, 'src/classes/index.ts')) .set('@images', helpers.root('src/assets/images/*'))
.set('@utils', path.resolve(__dirname, 'src/utils/index.ts')) .set('@classes', helpers.root('src/classes/index.ts'))
.set('@utils', path.resolve(__dirname, 'src/utils/*')) .set('@utils', helpers.root('src/utils/index.ts'))
.set('@css', path.resolve(__dirname, 'src/styles/variables.scss')) .set('@utils', helpers.root('src/utils/*'))
.set('@router', path.resolve(__dirname, 'src/router/index.ts')) .set('@router', helpers.root('src/router/index.ts'))
.set('@validators', path.resolve(__dirname, 'src/utils/validators.ts')) .set('@validators', helpers.root('src/utils/validators.ts'))
.set('@api', path.resolve(__dirname, 'src/store/Api/index.ts')) .set('@api', helpers.root('src/store/Api/index.ts'))
.set('@paths', path.resolve(__dirname, 'src/store/Api/ApiRoutes.ts')) .set('@paths', helpers.root('src/store/Api/ApiRoutes.ts'))
.set('@types', path.resolve(__dirname, 'src/typings/index.ts')) .set('@types', helpers.root('src/typings/index.ts'))
.set('@store', path.resolve(__dirname, 'src/store/index.ts')) .set('@store', helpers.root('src/store/index.ts'))
.set('@modules', path.resolve(__dirname, 'src/store/Modules/index.ts')) .set('@modules', helpers.root('src/store/Modules/index.ts'))
config.module config.module
.rule('typescript') .rule('typescript')
.test(/\.tsx?$/) .test(/\.tsx?$/)
@@ -87,8 +87,8 @@ module.exports = function (ctx) {
config.resolve config.resolve
.alias .alias
.set('~', __dirname) .set('~', __dirname)
.set('@', path.resolve(__dirname, 'src')) .set('@', helpers.root('src'))
// .set('env', path.resolve(__dirname, 'config/helpers/env.js')) // .set('env', helpers.root('config/helpers/env.js'))
config.module config.module
.rule('template-engine') .rule('template-engine')
.test(/\.pug$/) .test(/\.pug$/)
@@ -180,7 +180,7 @@ module.exports = function (ctx) {
pwa: { pwa: {
runtimeCaching: [ runtimeCaching: [
{ {
urlPattern: '/statics', urlPattern: '/assets',
handler: 'networkFirst' handler: 'networkFirst'
} }
] ]
@@ -189,7 +189,7 @@ module.exports = function (ctx) {
pwa: { pwa: {
// runtimeCaching: [ // runtimeCaching: [
// { // {
// urlPattern: '/statics', // urlPattern: '/assets',
// handler: 'networkFirst' // handler: 'networkFirst'
// } // }
// ], // ],

View File

@@ -8,8 +8,8 @@
console.log(' [ VER-0.0.27 ] _---------________------ PAO: this is my custom service worker'); console.log(' [ VER-0.0.27 ] _---------________------ PAO: this is my custom service worker');
importScripts('../statics/js/idb.js'); importScripts('../assets/js/idb.js');
importScripts('../statics/js/storage.js'); importScripts('../assets/js/storage.js');
importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.0.0/workbox-sw.js'); //++Todo: Replace with local workbox.js importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.0.0/workbox-sw.js'); //++Todo: Replace with local workbox.js
@@ -122,24 +122,50 @@ if (workbox) {
if (res.status === 200) { if (res.status === 200) {
const clonedRes = res.clone(); const clonedRes = res.clone();
// console.log('1) clearAllData(categories)')
return clearAllData('categories')
.then(() => {
// console.log('2) clearAllData(todos)')
return clearAllData('todos') return clearAllData('todos')
.then(() => { .then(() => {
// console.log('3) ....return clonedRes')
return clonedRes return clonedRes
}) })
})
} }
}) })
.then((clonedRes) => { .then((clonedRes) => {
// console.log(' 3) ')
if (clonedRes !== undefined) if (clonedRes !== undefined)
return clonedRes.json(); return clonedRes.json();
return null return null
}) })
.then(async data => { .then(data => {
// console.log(' 4) data = ', data)
if (data) { if (data) {
if (data.todos) { if (data.todos) {
console.log('***********************+++++++++++++++++++++++++++++++++++++++++++++++++++********** Records TODOS Received from Server [', data.todos.length, 'record]', data.todos)
for (let key in data.todos) { let promiseChain = Promise.resolve();
await writeData('todos', data.todos[key])
console.log('*********+++++++++++++++++********** Records TODOS Received from Server [', data.todos.length, 'record]', data.todos)
for (let cat in data.categories) {
promiseChain = promiseChain.then(() => {
return writeData('categories', { _id: cat, valore: data.categories[cat] } )
})
} }
for (let indrecCat in data.todos) {
for (let indrec in data.todos[indrecCat]) {
promiseChain = promiseChain.then(() => {
return writeData('todos', data.todos[indrecCat][indrec])
})
}
}
// console.log('promiseChain', promiseChain)
return promiseChain
} }
} }
}) })
@@ -180,7 +206,7 @@ if (workbox) {
}); });
workbox.routing.registerRoute( workbox.routing.registerRoute(
new RegExp(/.*\/(?:statics\/icons).*$/), new RegExp(/.*\/(?:assets\/icons).*$/),
workbox.strategies.cacheFirst({ workbox.strategies.cacheFirst({
cacheName: 'image-cache', cacheName: 'image-cache',
plugins: [ plugins: [
@@ -232,9 +258,9 @@ if (workbox) {
); );
workbox.routing.registerRoute( workbox.routing.registerRoute(
new RegExp(/.*\/(?:statics).*$/), new RegExp(/.*\/(?:assets).*$/),
workbox.strategies.cacheFirst({ workbox.strategies.cacheFirst({
cacheName: 'statics', cacheName: 'assets',
plugins: [ plugins: [
new workbox.expiration.Plugin({ new workbox.expiration.Plugin({
maxAgeSeconds: 10 * 24 * 60 * 60, maxAgeSeconds: 10 * 24 * 60 * 60,

View File

@@ -59,18 +59,18 @@ export default class App extends Vue {
}) })
if (chiamaautologin) { if (chiamaautologin) {
console.log('CHIAMA autologin_FromLocalStorage') // console.log('CHIAMA autologin_FromLocalStorage')
UserStore.actions.autologin_FromLocalStorage() UserStore.actions.autologin_FromLocalStorage()
.then((loadstorage) => { .then((loadstorage) => {
if (loadstorage) { if (loadstorage) {
if (UserStore.state.lang !== '') { if (UserStore.state.lang !== '') {
console.log('SETLOCALE :', this.$i18n.locale) // console.log('SETLOCALE :', this.$i18n.locale)
this.$i18n.locale = UserStore.state.lang // Set Lang this.$i18n.locale = UserStore.state.lang // Set Lang
} else { } else {
UserStore.mutations.setlang(this.$i18n.locale) UserStore.mutations.setlang(this.$i18n.locale)
} }
console.log('lang CARICATO:', this.$i18n.locale) // console.log('lang CARICATO:', this.$i18n.locale)
globalroutines(this, 'loadapp', '') globalroutines(this, 'loadapp', '')
// this.$router.replace('/') // this.$router.replace('/')

View File

@@ -1,6 +1,6 @@
<template> <template>
<div id="q-app"> <div id="q-app">
<q-layout :style="{ backgroundColor: backgroundColor}"> <q-layout :style="">
<app-header></app-header> <app-header></app-header>
<div class="layout-view"> <div class="layout-view">
<q-ajax-bar></q-ajax-bar> <q-ajax-bar></q-ajax-bar>

View File

@@ -17,7 +17,11 @@ const messages = {
msg: { msg: {
hello: 'Buongiorno', hello: 'Buongiorno',
myAppName: 'FreePlanet', myAppName: 'FreePlanet',
myDescriz: '' underconstruction: 'App in costruzione...',
myDescriz: '',
sottoTitoloApp: 'Il primo Vero Social',
sottoTitoloApp2: 'Libero, Equo e Solidale',
sottoTitoloApp3: 'dove Vive Consapevolezza e Aiuto Comunitario'
}, },
pages: { pages: {
home: 'Principale', home: 'Principale',
@@ -31,6 +35,8 @@ const messages = {
work: 'Lavoro', work: 'Lavoro',
shopping: 'Spesa', shopping: 'Spesa',
Admin: 'Admin', Admin: 'Admin',
Test1: 'Test1',
Test2: 'Test2',
}, },
components: { components: {
authentication:{ authentication:{
@@ -112,10 +118,11 @@ const messages = {
inserttop: 'Inserisci il Task in alto', inserttop: 'Inserisci il Task in alto',
insertbottom: 'Inserisci il Task in basso', insertbottom: 'Inserisci il Task in basso',
edit: 'Descrizione Task:', edit: 'Descrizione Task:',
completed: 'Completati', completed: 'Ultimi Completati',
usernotdefined: 'Attenzione, occorre essere Loggati per poter aggiungere un Todo' usernotdefined: 'Attenzione, occorre essere Loggati per poter aggiungere un Todo'
}, },
notification : { notification : {
status: 'Stato',
ask: 'Attiva le Notifiche', ask: 'Attiva le Notifiche',
waitingconfirm: 'Conferma la richiesta di Notifica', waitingconfirm: 'Conferma la richiesta di Notifica',
confirmed: 'Notifiche Attivate!', confirmed: 'Notifiche Attivate!',
@@ -146,7 +153,11 @@ const messages = {
msg: { msg: {
hello: 'Buenos Días', hello: 'Buenos Días',
myAppName: 'FreePlanet', myAppName: 'FreePlanet',
myDescriz: '' underconstruction: 'App en construcción...',
myDescriz: '',
sottoTitoloApp: 'El primer Verdadero Social',
sottoTitoloApp2: 'Libre, justo y Solidario',
sottoTitoloApp3: 'Donde vive Conciencia y Ayuda comunitaria'
}, },
pages: { pages: {
home: 'Principal', home: 'Principal',
@@ -160,6 +171,8 @@ const messages = {
work: 'Trabajo', work: 'Trabajo',
shopping: 'Compras', shopping: 'Compras',
Admin: 'Administración', Admin: 'Administración',
Test1: 'Test1',
Test2: 'Test2',
}, },
components: { components: {
authentication:{ authentication:{
@@ -241,10 +254,11 @@ const messages = {
inserttop: 'Ingrese una nueva Tarea arriba', inserttop: 'Ingrese una nueva Tarea arriba',
insertbottom: 'Ingrese una nueva Tarea abajo', insertbottom: 'Ingrese una nueva Tarea abajo',
edit: 'Descripción Tarea:', edit: 'Descripción Tarea:',
completed: 'Completados', completed: 'Ultimos Completados',
usernotdefined: 'Atención, debes iniciar sesión para agregar una Tarea' usernotdefined: 'Atención, debes iniciar sesión para agregar una Tarea'
}, },
notification : { notification : {
status: 'Estado',
ask: 'Activar notificaciones', ask: 'Activar notificaciones',
waitingconfirm: 'Confirmar la solicitud de notificación.', waitingconfirm: 'Confirmar la solicitud de notificación.',
confirmed: 'Notificaciones activadas!', confirmed: 'Notificaciones activadas!',
@@ -275,7 +289,11 @@ const messages = {
msg: { msg: {
hello: 'Hello!', hello: 'Hello!',
myAppName: 'FreePlanet', myAppName: 'FreePlanet',
myDescriz: '' underconstruction: 'App in constuction...',
myDescriz: '',
sottoTitoloApp: 'The first Real Social',
sottoTitoloApp2: 'Free, Fair and solidarity',
sottoTitoloApp3: 'Where the conscience and community help live'
}, },
pages: { pages: {
home: 'Dashboard', home: 'Dashboard',
@@ -289,6 +307,8 @@ const messages = {
work: 'Work', work: 'Work',
shopping: 'Shopping', shopping: 'Shopping',
Admin: 'Admin', Admin: 'Admin',
Test1: 'Test1',
Test2: 'Test2',
}, },
components: { components: {
authentication:{ authentication:{
@@ -370,10 +390,11 @@ const messages = {
inserttop: 'Insert Task at the top', inserttop: 'Insert Task at the top',
insertbottom: 'Insert Task at the bottom', insertbottom: 'Insert Task at the bottom',
edit: 'Task Description:', edit: 'Task Description:',
completed: 'Completed', completed: 'Lasts Completed',
usernotdefined: 'Attention, you need to be Signed In to add a new Task' usernotdefined: 'Attention, you need to be Signed In to add a new Task'
}, },
notification : { notification : {
status: 'Status',
ask: 'Enable Notification', ask: 'Enable Notification',
waitingconfirm: 'Confirm the Request Notification', waitingconfirm: 'Confirm the Request Notification',
confirmed: 'Notifications Enabled!', confirmed: 'Notifications Enabled!',

File diff suppressed because it is too large Load Diff

After

Width:  |  Height:  |  Size: 90 KiB

View File

Before

Width:  |  Height:  |  Size: 40 KiB

After

Width:  |  Height:  |  Size: 40 KiB

View File

@@ -15,6 +15,7 @@ let idbKeyval = (() => {
openreq.onupgradeneeded = () => { openreq.onupgradeneeded = () => {
// First time setup: create an empty object store // First time setup: create an empty object store
openreq.result.createObjectStore('todos', { keyPath: '_id' }); openreq.result.createObjectStore('todos', { keyPath: '_id' });
openreq.result.createObjectStore('categories', { keyPath: '_id' });
openreq.result.createObjectStore('sync_todos', { keyPath: '_id' }); openreq.result.createObjectStore('sync_todos', { keyPath: '_id' });
openreq.result.createObjectStore('sync_todos_patch', { keyPath: '_id' }); openreq.result.createObjectStore('sync_todos_patch', { keyPath: '_id' });
openreq.result.createObjectStore('delete_todos', { keyPath: '_id' }); openreq.result.createObjectStore('delete_todos', { keyPath: '_id' });

View File

@@ -121,7 +121,7 @@
import messagePopover from '../layouts/toolbar/messagePopover/messagePopover.vue' import messagePopover from '../layouts/toolbar/messagePopover/messagePopover.vue'
import { GlobalStore, UserStore } from '@modules' import { GlobalStore, UserStore } from '@modules'
import { rescodes } from '../store/Modules/rescodes' import { tools } from '../store/Modules/tools'
import QIcon from "quasar-framework/src/components/icon/QIcon" import QIcon from "quasar-framework/src/components/icon/QIcon"
import { StateConnection } from "../model" import { StateConnection } from "../model"
import { Watch } from "vue-property-decorator" import { Watch } from "vue-property-decorator"
@@ -213,7 +213,6 @@
}) })
} }
// console.log('Todos.state.todos_changed CHANGED!', value, oldValue)
this.changeIconConn() this.changeIconConn()
} }
} }
@@ -238,10 +237,10 @@
} }
public selectOpLang = [ public selectOpLang = [
{ label: 'English', icon: 'fa-flag-us', value: 'enUs', image: '../statics/images/gb.png', short: 'EN' }, { label: 'English', icon: 'fa-flag-us', value: 'enUs', image: '../assets/images/gb.png', short: 'EN' },
{ label: 'German', icon: 'fa-flag-de', value: 'de', image: '../statics/images/de.png', short: 'DE' }, // { label: 'German', icon: 'fa-flag-de', value: 'de', image: '../assets/images/de.png', short: 'DE' },
{ label: 'Italian', icon: 'fa-facebook', value: 'it', image: '../statics/images/it.png', short: 'IT' }, { label: 'Italiano', icon: 'fa-facebook', value: 'it', image: '../assets/images/it.png', short: 'IT' },
{ label: 'Spanish', icon: 'fa-flag-es', value: 'esEs', image: '../statics/images/es.png', short: 'ES' } { label: 'Español', icon: 'fa-flag-es', value: 'esEs', image: '../assets/images/es.png', short: 'ES' }
] ]
@@ -279,7 +278,7 @@
set leftDrawerOpen(value) { set leftDrawerOpen(value) {
GlobalStore.state.leftDrawerOpen = value GlobalStore.state.leftDrawerOpen = value
localStorage.setItem(rescodes.localStorage.leftDrawerOpen, value.toString()) localStorage.setItem(tools.localStorage.leftDrawerOpen, value.toString())
} }
getAppVersion() { getAppVersion() {
@@ -330,7 +329,7 @@
// dynamic import, so loading on demand only // dynamic import, so loading on demand only
import(`quasar-framework/i18n/${mylangtopass}`).then(lang => { import(`quasar-framework/i18n/${mylangtopass}`).then(lang => {
this.$q.i18n.set(lang.default) this.$q.i18n.set(lang.default)
import(`src/statics/i18n`).then(function () { import(`src/assets/i18n`).then(function () {
}) })
}) })
} }
@@ -350,7 +349,7 @@
let my = this.getLangAtt() let my = this.getLangAtt()
// this.$q.notify('prima: ' + String(my)) // this.$q.notify('prima: ' + String(my))
let mylang = rescodes.getItemLS(rescodes.localStorage.lang) let mylang = tools.getItemLS(tools.localStorage.lang)
if (mylang === '') { if (mylang === '') {
if (navigator) { if (navigator) {
mylang = navigator.language mylang = navigator.language

View File

@@ -0,0 +1 @@
export {default as testp1} from './testp1.vue'

View File

View File

@@ -0,0 +1,95 @@
import Vue from 'vue'
import { Component, Watch } from 'vue-property-decorator'
import { GlobalStore, UserStore } from '@store'
import { Getter } from "vuex-class"
import { ICfgServer, IGlobalState, ITodo, ITodosState } from '@src/model'
const namespace: string = 'GlobalModule'
@Component({})
export default class Testp1 extends Vue {
public myvar:number = 5
public paramcategory: string = ''
public mioobj: any
// @Getter('todos_dacompletare', { namespace })
// public todos_dacompletare: (state: ITodosState, category: string) => ITodo[]
@Getter('testpao1_getter_contatore', { namespace })
public testpao1: (state: IGlobalState, param1: number) => number
@Getter('testpao1_getter_array', { namespace })
public testpao1_array: (state: IGlobalState, miorec: ICfgServer) => ICfgServer[]
@Watch('GlobalStore.state.testp1.mioarray', { immediate: true, deep: true })
array_changed() {
console.log('*** array_changed *** ', GlobalStore.state.testp1.mioarray[GlobalStore.state.testp1.mioarray.length - 1])
}
@Watch('$route.params.category') changecat() {
// this.mytypetransgroup = ''
console.log('PRIMA this.paramcategory', this.paramcategory)
this.paramcategory = this.$route.params.category
console.log('DOPO this.paramcategory', this.paramcategory)
}
created() {
this.mioobj = {
arr1: [{chiave: 'key1', valore: 'val1'}],
arr2: [{chiave: 'key2', valore: 'val2'}]
}
}
get getarr1 () {
// return this.mioobj.arr1
return this.mioobj['arr1']
}
get prova2() {
return GlobalStore.state.testp1.contatore
}
get provagetter() {
return GlobalStore.getters.testpao1_getter_contatore(130)
}
get provagetterarray() {
return GlobalStore.getters.testpao1_getter_array(GlobalStore.state.testp1.contatore)
}
TestBtnCambioaParamPassing () {
this.paramcategory += 's'
}
TestBtn() {
GlobalStore.state.testp1.contatore++
}
TestBtn2() {
GlobalStore.state.testp1.mioarray.push({chiave: 'pippo2', valore: GlobalStore.state.testp1.contatore.toString() })
}
TestBtnModify() {
// GlobalStore.state.testp1.mioarray[GlobalStore.state.testp1.mioarray.length - 1] = GlobalStore.state.testp1.mioarray[GlobalStore.state.testp1.mioarray.length - 1] + 1
GlobalStore.mutations.setPaoArray({chiave: 'pippo', valore: '20' } )
}
TestBtnCambiaTutto() {
// GlobalStore.state.testp1.mioarray[GlobalStore.state.testp1.mioarray.length - 1] = GlobalStore.state.testp1.mioarray[GlobalStore.state.testp1.mioarray.length - 1] + 1
GlobalStore.mutations.NewArray([{chiave: 'nuovorec1', valore: '1' }, {chiave: 'nuovorec2', valore: '2' }] )
}
TestBtnAction() {
GlobalStore.actions.prova()
}
TestBtnDelete() {
// GlobalStore.state.testp1.mioarray[GlobalStore.state.testp1.mioarray.length - 1] = GlobalStore.state.testp1.mioarray[GlobalStore.state.testp1.mioarray.length - 1] + 1
GlobalStore.mutations.setPaoArray_Delete()
}
}

View File

@@ -0,0 +1,43 @@
<template>
<div>
CATEGORY: <strong>{{ paramcategory }}</strong> <br>
<label>TEST Prova Paolo</label><br>
GETTER CONTATORE:
{{ testpao1(300) }} <br>
ARRAY:
{{ testpao1_array(300) }} <br>
TEST OBJECT {{ mioobj }} <br>
ARR1 {{ getarr1 }} <br>
<!--ARR2 {{ mioobj.arr2 }} <br>-->
<!--<q-input v-model="testpao1(myvar)"></q-input>-->
<q-input v-model="prova2" float-label="PROVA2:"></q-input>
<q-input v-model="provagetter" float-label="PROVA GETTER:"></q-input>
<q-input v-model="provagetterarray" float-label="GETTER ARRAY:"></q-input>
<br>
<q-btn color="secondary" rounded icon="refresh"
@click="TestBtn" label="Test 1"/>
<q-btn color="secondary" rounded icon="refresh" @click="TestBtn2" label="ADD TO ARRAY"/>
<q-btn color="secondary" rounded icon="refresh" @click="TestBtnModify" label="MODIFY"/>
<q-btn color="secondary" rounded icon="refresh" @click="TestBtnAction" label="MODIF_BYACTION"/>
<q-btn color="secondary" rounded icon="refresh" @click="TestBtnDelete" label="DEL LAST"/>
<!--<q-btn color="secondary" rounded icon="refresh" @click="TestBtnCambiaTutto" label="NEW ARR"/>-->
<q-btn color="secondary" rounded icon="refresh" @click="TestBtnCambioaParamPassing" label="CAMBIA PARAM"/>
</div>
</template>
<script lang="ts" src="./testp1.ts">
</script>
<style lang="scss" scoped>
@import './testp1.scss';
</style>

View File

@@ -1,9 +1,11 @@
.svgclass{
.svgclass {
color: white; color: white;
transform: translateY(0px); transform: translateY(0px);
} }
.svgclass_animate { .svgclass_animate {
transform: translateY(-70px); transform: translateY(-70px);
color: red; color: red;
@@ -14,16 +16,24 @@
} }
@keyframes gravity{ #logoimg {
0%{ height: 150px;
width: auto;
@media screen and (max-width: 600px) {
}
}
@keyframes gravity {
0% {
transform: rotateY(0deg); transform: rotateY(0deg);
} }
100%{ 100% {
transform: rotateY(360deg); transform: rotateY(360deg);
} }
} }
#smile{ #smile {
opacity: 0.1 !important; opacity: 0.1 !important;
fill: red; fill: red;
} }

View File

@@ -13,7 +13,7 @@ export default class Logo extends Vue {
logoimg: string = '' logoimg: string = ''
created() { created() {
this.logoimg = 'statics/images/' + process.env.LOGO_REG this.logoimg = 'assets/images/' + process.env.LOGO_REG
this.animate() this.animate()
} }

View File

@@ -13,7 +13,7 @@ export default class Offline extends Vue {
logoimg: string = '' logoimg: string = ''
created() { created() {
this.logoimg = 'statics/images/' + process.env.LOGO_REG this.logoimg = '/assets/images/' + process.env.LOGO_REG
this.animate() this.animate()
} }

View File

@@ -1,7 +1,7 @@
import Vue from 'vue' import Vue from 'vue'
import { Component, Prop, Watch } from 'vue-property-decorator' import { Component, Prop, Watch } from 'vue-property-decorator'
import { rescodes } from '../../../store/Modules/rescodes' import { tools } from '../../../store/Modules/tools'
import { UserStore } from '@modules' import { UserStore } from '@modules'
import { ITodo } from '../../../model/index' import { ITodo } from '../../../model/index'
@@ -48,21 +48,21 @@ export default class SingleTodo extends Vue {
@Prop({ required: true }) itemtodo: ITodo @Prop({ required: true }) itemtodo: ITodo
@Watch('itemtodo.completed') valueChanged() { // @Watch('itemtodo.completed') valueChanged() {
this.watchupdate() // this.watchupdate('completed')
} // }
@Watch('itemtodo.enableExpiring') valueChanged4() { @Watch('itemtodo.enableExpiring') valueChanged4() {
this.watchupdate() this.watchupdate('enableExpiring')
} }
@Watch('itemtodo.expiring_at') valueChanged2() { @Watch('itemtodo.expiring_at') valueChanged2() {
this.watchupdate() this.watchupdate('expiring_at')
} }
@Watch('itemtodo.priority') valueChanged3() { // @Watch('itemtodo.priority') valueChanged3() {
this.watchupdate() // this.watchupdate('priority')
} // }
@Watch('itemtodo.descr') valueChanged5() { @Watch('itemtodo.descr') valueChanged5() {
@@ -91,8 +91,8 @@ export default class SingleTodo extends Vue {
return elem.descr.slice(-1) !== ':' return elem.descr.slice(-1) !== ':'
} }
watchupdate() { watchupdate(field = '') {
this.$emit('eventupdate', this.itemtodo) this.$emit('eventupdate', {myitem: this.itemtodo, field } )
this.updateicon() this.updateicon()
} }
@@ -158,10 +158,10 @@ export default class SingleTodo extends Vue {
// console.log('UserStore.state.lang', UserStore.state.lang) // console.log('UserStore.state.lang', UserStore.state.lang)
if (this.isTodo()) if (this.isTodo())
this.menuPopupTodo = rescodes.menuPopupTodo[UserStore.state.lang] this.menuPopupTodo = tools.menuPopupTodo[UserStore.state.lang]
else { else {
this.menuPopupTodo = [] this.menuPopupTodo = []
this.menuPopupTodo.push(rescodes.menuPopupTodo[UserStore.state.lang][rescodes.INDEX_MENU_DELETE]) this.menuPopupTodo.push(tools.menuPopupTodo[UserStore.state.lang][tools.INDEX_MENU_DELETE])
} }
} }
@@ -172,7 +172,7 @@ export default class SingleTodo extends Vue {
this.updateClasses() this.updateClasses()
this.selectPriority = rescodes.selectPriority[UserStore.state.lang] this.selectPriority = tools.selectPriority[UserStore.state.lang]
} }
@@ -283,7 +283,7 @@ export default class SingleTodo extends Vue {
if (((e.keyCode === 8) || (e.keyCode === 46)) && (this.precDescr === '') && !e.shiftKey) { if (((e.keyCode === 8) || (e.keyCode === 46)) && (this.precDescr === '') && !e.shiftKey) {
e.preventDefault() e.preventDefault()
this.deselectRiga() this.deselectRiga()
this.clickMenu(rescodes.MenuAction.DELETE) this.clickMenu(tools.MenuAction.DELETE)
.then(() => { .then(() => {
this.faiFocus('insertTask', true) this.faiFocus('insertTask', true)
return return
@@ -311,7 +311,7 @@ export default class SingleTodo extends Vue {
if (((e.keyCode === 8) || (e.keyCode === 46)) && (this.precDescr === '') && !e.shiftKey) { if (((e.keyCode === 8) || (e.keyCode === 46)) && (this.precDescr === '') && !e.shiftKey) {
e.preventDefault() e.preventDefault()
this.deselectRiga() this.deselectRiga()
this.clickMenu(rescodes.MenuAction.DELETE) this.clickMenu(tools.MenuAction.DELETE)
.then(() => { .then(() => {
this.faiFocus('insertTask', true) this.faiFocus('insertTask', true)
return return
@@ -349,7 +349,7 @@ export default class SingleTodo extends Vue {
console.log('itemtodo', this.itemtodo) console.log('itemtodo', this.itemtodo)
console.log('Prec:', this.itemtodoPrec) console.log('Prec:', this.itemtodoPrec)
this.watchupdate() this.watchupdate('descr')
this.inEdit = false this.inEdit = false
// this.precDescr = this.itemtodo.descr // this.precDescr = this.itemtodo.descr
this.updateClasses() this.updateClasses()
@@ -361,15 +361,15 @@ export default class SingleTodo extends Vue {
this.updateicon() this.updateicon()
this.updatedata() this.updatedata('completed')
this.deselectAndExitEdit() this.deselectAndExitEdit()
} }
updatedata() { updatedata(field: string) {
const myitem = rescodes.jsonCopy(this.itemtodo) // const myitem = tools.jsonCopy(this.itemtodo)
console.log('calling this.$emit(eventupdate)', myitem) console.log('calling this.$emit(eventupdate)', this.itemtodo)
this.$emit('eventupdate', myitem) this.$emit('eventupdate', { myitem: this.itemtodo, field } )
} }
updateicon() { updateicon() {
@@ -380,11 +380,11 @@ export default class SingleTodo extends Vue {
this.iconCompleted = 'check_circle_outline' this.iconCompleted = 'check_circle_outline'
if (this.itemtodo.priority === rescodes.Todos.PRIORITY_HIGH) if (this.itemtodo.priority === tools.Todos.PRIORITY_HIGH)
this.iconPriority = 'expand_less' // expand_less this.iconPriority = 'expand_less' // expand_less
else if (this.itemtodo.priority === rescodes.Todos.PRIORITY_NORMAL) else if (this.itemtodo.priority === tools.Todos.PRIORITY_NORMAL)
this.iconPriority = 'remove' this.iconPriority = 'remove'
else if (this.itemtodo.priority === rescodes.Todos.PRIORITY_LOW) else if (this.itemtodo.priority === tools.Todos.PRIORITY_LOW)
this.iconPriority = 'expand_more' // expand_more this.iconPriority = 'expand_more' // expand_more
this.updateClasses() this.updateClasses()
@@ -392,7 +392,7 @@ export default class SingleTodo extends Vue {
removeitem(id) { removeitem(id) {
this.$emit('deleteitem', id) this.$emit('deleteItem', id)
} }
enableExpiring() { enableExpiring() {
@@ -402,14 +402,14 @@ export default class SingleTodo extends Vue {
async clickMenu(action) { async clickMenu(action) {
console.log('click menu: ', action) console.log('click menu: ', action)
if (action === rescodes.MenuAction.DELETE) { if (action === tools.MenuAction.DELETE) {
return await this.askConfirmDelete() return await this.askConfirmDelete()
} else if (action === rescodes.MenuAction.TOGGLE_EXPIRING) { } else if (action === tools.MenuAction.TOGGLE_EXPIRING) {
return await this.enableExpiring() return await this.enableExpiring()
} else if (action === rescodes.MenuAction.COMPLETED) { } else if (action === tools.MenuAction.COMPLETED) {
return await this.setCompleted() return await this.setCompleted()
} else if (action === rescodes.MenuAction.PROGRESS_BAR) { } else if (action === tools.MenuAction.PROGRESS_BAR) {
return await this.updatedata() return await this.updatedata('progress')
} else if (action === 0) { } else if (action === 0) {
this.deselectAndExitEdit() this.deselectAndExitEdit()
} }
@@ -418,11 +418,13 @@ export default class SingleTodo extends Vue {
setPriority(newpriority) { setPriority(newpriority) {
if (this.itemtodo.priority !== newpriority) {
this.itemtodo.priority = newpriority this.itemtodo.priority = newpriority
this.updatedata() this.updatedata('priority')
this.updateicon() this.updateicon()
}
// this.$q.notify('setPriority: ' + elem) // this.$q.notify('setPriority: ' + elem)
} }

View File

@@ -83,9 +83,6 @@
<!--<div class="flex-item btn-item">--> <!--<div class="flex-item btn-item">-->
<!--<q-btn class="mybtn" round color="" icon="delete" @click.native="removeitem(itemtodo._id)"></q-btn>--> <!--<q-btn class="mybtn" round color="" icon="delete" @click.native="removeitem(itemtodo._id)"></q-btn>-->
<!--</div>--> <!--</div>-->
<!--<div class="flex-item">-->
<!--[{{ itemtodo.id_prev}} - {{ itemtodo.id_next}}]-->
<!--</div>-->
</div> </div>
</template> </template>

View File

@@ -2,7 +2,7 @@ import Vue from 'vue'
import { Component, Prop } from 'vue-property-decorator' import { Component, Prop } from 'vue-property-decorator'
import { ITodo } from '../../../model/index' import { ITodo } from '../../../model/index'
import { rescodes } from '@src/store/Modules/rescodes' import { tools } from '@src/store/Modules/tools'
import { UserStore } from '@store' import { UserStore } from '@store'
// Doesn't exist in quasar this ? error TS2305 // Doesn't exist in quasar this ? error TS2305
@@ -16,7 +16,7 @@ import { UserStore } from '@store'
}) })
export default class SubMenus extends Vue { export default class SubMenus extends Vue {
public selectPriority: [] = rescodes.selectPriority[UserStore.state.lang] public selectPriority: [] = tools.selectPriority[UserStore.state.lang]
@Prop({ required: false }) menuPopupTodo: any[] @Prop({ required: false }) menuPopupTodo: any[]
@Prop({ required: false }) itemtodo: ITodo @Prop({ required: false }) itemtodo: ITodo
@@ -47,7 +47,7 @@ export default class SubMenus extends Vue {
} }
create () { create () {
this.selectPriority = rescodes.selectPriority[UserStore.state.lang] this.selectPriority = tools.selectPriority[UserStore.state.lang]
console.log('CREAZIONE') console.log('CREAZIONE')
} }

File diff suppressed because it is too large Load Diff

View File

@@ -4,7 +4,7 @@
<p class="caption"></p> <p class="caption"></p>
<div class="divtitlecat"> <div class="divtitlecat">
<div class="categorytitle">{{ getCategory() }}</div> <div class="categorytitle">{{ categoryAtt }}</div>
</div> </div>
<q-input ref="insertTask" v-model="todotop" inverted :float-label="$t('todo.inserttop')" <q-input ref="insertTask" v-model="todotop" inverted :float-label="$t('todo.inserttop')"
@@ -19,21 +19,17 @@
<!--<div :id="getmyid(mytodo._id)" v-for="(mytodo, index) in todos_arr" :key="mytodo._id" class="myitemdrag"--> <!--<div :id="getmyid(mytodo._id)" v-for="(mytodo, index) in todos_arr" :key="mytodo._id" class="myitemdrag"-->
<!--draggable="true" @dragstart="dragStart(index, $event)" @dragover.prevent @dragenter="dragEnter(index)"--> <!--draggable="true" @dragstart="dragStart(index, $event)" @dragover.prevent @dragenter="dragEnter(index)"-->
<!--@dragleave="dragLeave(index)" @dragend="dragEnd" @drop="dragFinish(index, $event)" >--> <!--@dragleave="dragLeave(index)" @dragend="dragEnd" @drop="dragFinish(index, $event)" >-->
<q-infinite-scroll :handler="loadMoreTodo" :offset="7">
<div class="container" v-dragula="todos_arr" drake="first" :key="compKey3"> <!--<q-infinite-scroll :handler="loadMoreTodo" :offset="7">-->
<div :id="getmyid(mytodo._id)" :index="index" v-for="(mytodo, index) in showingDataTodo" <div class="container" v-dragula="todos_dacompletare(categoryAtt)" drake="first">
<div :id="getmyid(mytodo._id)" :index="index" v-for="(mytodo, index) in todos_dacompletare(categoryAtt)"
:key="mytodo._id" class="myitemdrag"> :key="mytodo._id" class="myitemdrag">
<div v-if="(prior !== mytodo.priority) && !mytodo.completed" <div v-if="(prior !== mytodo.priority) && !mytodo.completed"
:class="getTitlePriority(mytodo.priority)" :key="compKey1"> :class="getTitlePriority(mytodo.priority)">
<label>{{getPriorityByInd(mytodo.priority)}}</label> <label>{{getPriorityByInd(mytodo.priority)}}</label>
</div> </div>
<div v-if="(!priorcomplet && mytodo.completed)" class="titleCompleted" :key="compKey2"> <SingleTodo ref="single" @deleteItem="mydeleteItem" @eventupdate="updateitem"
<label>{{$t('todo.completed')}}</label>
<div style="display: none">{{ priorcomplet = true }}</div>
</div>
<SingleTodo ref="single" @deleteitem="deleteitem" @eventupdate="updateitem"
@deselectAllRows="deselectAllRows" @onEnd="onEnd" @deselectAllRows="deselectAllRows" @onEnd="onEnd"
:itemtodo='mytodo'/> :itemtodo='mytodo'/>
@@ -43,19 +39,40 @@
</div> </div>
</div> </div>
</div> </div>
</q-infinite-scroll> <!--</q-infinite-scroll>-->
<div v-if="doneTodosCount > 0" class="titleCompleted">
<label>{{$t('todo.completed')}}</label>
</div>
<!--<q-infinite-scroll :handler="loadMoreTodo" :offset="7">-->
<div class="container" v-dragula="todos_completati(categoryAtt)" drake="second">
<div :id="getmyid(mytodo._id)" :index="index" v-for="(mytodo, index) in todos_completati(categoryAtt)"
:key="mytodo._id" class="myitemdrag">
<SingleTodo ref="single" @deleteItem="deleteItem(mytodo._id)" @eventupdate="updateitem"
@deselectAllRows="deselectAllRows" @onEnd="onEnd"
:itemtodo='mytodo'/>
<!--<div :name="`REF${index}`" class="divdrag non-draggato"></div>-->
<div style="display: none">{{ prior = mytodo.priority, priorcomplet = mytodo.completed }}
</div>
</div>
</div>
<!--</q-infinite-scroll>-->
<!--</transition-group>--> <!--</transition-group>-->
<!--</draggable>--> <!--</draggable>-->
</div> </div>
<q-input v-if="todos_arr.length > 0" ref="insertTaskBottom" v-model="todobottom" inverted :float-label="$t('todo.insertbottom')" <q-input v-if="TodosCount > 0" ref="insertTaskBottom" v-model="todobottom" inverted :float-label="$t('todo.insertbottom')"
:after="[{icon: 'arrow_forward', content: true, handler () {}}]" :after="[{icon: 'arrow_forward', content: true, handler () {}}]"
v-on:keyup.enter="insertTodo(false)"/> v-on:keyup.enter="insertTodo(false)"/>
<!--{{ tmpstrTodos }}--> <br>
<!--<br>-->
<!--&lt;!&ndash;-->
<!--&lt;!&ndash;<div class="flex-item btn-item">&ndash;&gt;--> <!--&lt;!&ndash;<div class="flex-item btn-item">&ndash;&gt;-->
<!--<q-btn class="mybtn" round color="" icon="lock" @click="getArrTodos">Get Todo</q-btn>--> <!--<q-btn class="mybtn" round color="" icon="lock" @click="getArrTodos">Get Todo</q-btn>-->
<!--<q-btn class="mybtn" round color="" icon="person" @click="setArrTodos">Set Todo</q-btn>--> <!--<q-btn class="mybtn" round color="" icon="person" @click="setArrTodos">Set Todo</q-btn>-->
@@ -72,7 +89,10 @@
<!--<q-btn class="mybtn" round color="" icon="person" @click="clicktest2()"></q-btn>--> <!--<q-btn class="mybtn" round color="" icon="person" @click="clicktest2()"></q-btn>-->
<!--<q-btn class="mybtn" round color="" icon="list" @click="checkUpdate()"></q-btn>--> <!--<q-btn class="mybtn" round color="" icon="list" @click="checkUpdate()"></q-btn>-->
<!--</div>--> <!--</div>-->
<!--&ndash;&gt;-->
<!--<span style="white-space: pre;">{{ todos_vista }}</span>-->
</div> </div>
</q-page> </q-page>

View File

@@ -3,7 +3,7 @@ import _ from 'lodash'
import { UserStore, Todos } from '@store' import { UserStore, Todos } from '@store'
import { i18n } from '../plugins/i18n' import { i18n } from '../plugins/i18n'
import {idbKeyval as storage} from '../js/storage.js'; import { idbKeyval as storage } from '../js/storage.js';
function saveConfigIndexDb(context) { function saveConfigIndexDb(context) {
@@ -27,17 +27,40 @@ function writeConfigIndexDb(context, data) {
} }
async function readfromIndexDbToStateTodos(context, table) { async function readfromIndexDbToStateTodos(context, table) {
// console.log('*** read from IndexDb to state.todos') console.log('*** readfromIndexDbToStateTodos ***')
return await storage.getalldata(table) return await storage.getalldata(table)
.then(records => { .then(reccat => {
// console.log('&&&&&&& readfromIndexDbToStateTodos OK: Num RECORD: ', records.length) // console.log('&&&&&&& readfromIndexDbToStateTodos OK: Num RECORD: ', records.length)
if (table === 'todos') { if (table === 'categories') {
Todos.state.todos = [...records] console.log('reccat', reccat)
Todos.mutations.setTodos_changed() Todos.state.categories = []
// console.log('Todos.state.todos_changed:', Todos.state.todos_changed) for (let indcat in reccat) {
// setTimeout(testfunc2, 3000) Todos.state.categories.push(reccat[indcat].valore)
} }
console.log('ARRAY Categories', Todos.state.categories)
return storage.getalldata('todos')
.then(records => {
console.log('todos records', records)
// console.log('&&&&&&& readfromIndexDbToStateTodos OK: Num RECORD: ', records.length)
for (let myrec in records) {
const cat = myrec.category
let indcat = state.categories.indexOf(cat)
if (Todos.state.todos[indcat] === undefined)
Todos.state.todos[indcat] = {}
// add to the right array
Todos.state.todos[indcat].push(myrec)
}
console.log('************ ARRAYS SALVATI IN MEMORIA Todos.state.todos ', Todos.state.todos)
})
}
}).catch((error) => { }).catch((error) => {
console.log('err: ', error) console.log('err: ', error)
}) })
@@ -49,11 +72,9 @@ function consolelogpao(str, str2 = '', str3 = '') {
// Todos.mutations.setTestpao(str + str2 + str3) // Todos.mutations.setTestpao(str + str2 + str3)
} }
function testfunc2 () { function testfunc2() {
consolelogpao('testfunc2') consolelogpao('testfunc2')
Todos.mutations.setTodos_changed()
consolelogpao('testfunc2: Todos.state.todos_changed:', Todos.state.todos_changed)
} }
export default async (context, cmd, table, datakey = null, id = '') => { export default async (context, cmd, table, datakey = null, id = '') => {

View File

@@ -1,5 +1,5 @@
import { UserStore } from "../store/Modules"; import { UserStore } from "../store/Modules";
import messages from "../statics/i18n"; import messages from "../assets/i18n";
function translate(params) { function translate(params) {
let msg = params.split('.') let msg = params.split('.')

View File

@@ -10,21 +10,20 @@
<meta name="viewport" <meta name="viewport"
content="user-scalable=no, initial-scale=1, minimum-scale=1, width=device-width<% if (htmlWebpackPlugin.options.ctx.mode.cordova) { %>, viewport-fit=cover<% } %>"> content="user-scalable=no, initial-scale=1, minimum-scale=1, width=device-width<% if (htmlWebpackPlugin.options.ctx.mode.cordova) { %>, viewport-fit=cover<% } %>">
<link rel="icon" href="/statics/icons/favicon.ico" type="image/x-icon"> <link rel="icon" href="<%= htmlWebpackPlugin.files.publicPath %>statics/icons/favicon.ico" type="image/x-icon">
<link rel="icon" type="image/png" sizes="32x32" href="/statics/icons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="32x32" href="<%= htmlWebpackPlugin.files.publicPath %>statics/icons/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/statics/icons/favicon-16x16.png"> <link rel="icon" type="image/png" sizes="16x16" href="<%= htmlWebpackPlugin.files.publicPath %>statics/icons/favicon-16x16.png">
<link rel="stylesheet" type="text/css" href="/statics/css/dragula.css"> <link rel="stylesheet" type="text/css" href="<%= htmlWebpackPlugin.files.publicPath %>assets/css/dragula.css">
<script defer src="/statics/js/material.min.js"></script> <script defer src="<%= htmlWebpackPlugin.files.publicPath %>assets/js/material.min.js"></script>
<script src="/statics/js/promise.js"></script> <script src="<%= htmlWebpackPlugin.files.publicPath %>assets/js/promise.js"></script>
<script src="/statics/js/fetch.js"></script> <script src="<%= htmlWebpackPlugin.files.publicPath %>assets/js/fetch.js"></script>
<script src="/statics/js/idb.js"></script> <script src="<%= htmlWebpackPlugin.files.publicPath %>assets/js/idb.js"></script>
<script src="/statics/js/storage.js"></script> <script src="<%= htmlWebpackPlugin.files.publicPath %>assets/js/storage.js"></script>
<!--<link type="text/css" rel="stylesheet" href="statics/firebaseui.css" />-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head> </head>
<body> <body>
<!-- DO NOT touch the following DIV -->
<div id="q-app"></div> <div id="q-app"></div>
</body> </body>
</html> </html>

View File

@@ -15,6 +15,7 @@ export let idbKeyval = (() => {
openreq.onupgradeneeded = () => { openreq.onupgradeneeded = () => {
// First time setup: create an empty object store // First time setup: create an empty object store
openreq.result.createObjectStore('todos', { keyPath: '_id' }); openreq.result.createObjectStore('todos', { keyPath: '_id' });
openreq.result.createObjectStore('categories', { keyPath: '_id' });
openreq.result.createObjectStore('sync_todos', { keyPath: '_id' }); openreq.result.createObjectStore('sync_todos', { keyPath: '_id' });
openreq.result.createObjectStore('sync_todos_patch', { keyPath: '_id' }); openreq.result.createObjectStore('sync_todos_patch', { keyPath: '_id' });
openreq.result.createObjectStore('delete_todos', { keyPath: '_id' }); openreq.result.createObjectStore('delete_todos', { keyPath: '_id' });
@@ -56,7 +57,7 @@ export let idbKeyval = (() => {
let req; let req;
await withStore('readonly', table, store => { await withStore('readonly', table, store => {
console.log('getdata', table, key) // console.log('getdata', table, key)
req = store.get(key); req = store.get(key);
}); });

View File

@@ -0,0 +1,50 @@
.background-red {
background-color: red;
padding: 2px;
}
.fixed-bottom {
margin-bottom: 1%;
}
.fixed-bottom a img {
width: 25px;
height: 25px;
}
#avatar {
padding: 20px;
}
#profile {
height: 130px;
background-color: #009688;
}
#user-name {
left: 90px;
bottom: 77px;
position: relative;
width: 159px;
}
#user-actions {
left: 90px;
bottom: 71px;
position: relative;
width: 171px;
}
#menu-collapse {
margin-top: 5%;
}
.fixed-left:hover {
cursor: ew-resize;
}
footer {
small {
color: red;
}
}

View File

@@ -0,0 +1,119 @@
import menuOne from './menuOne.vue'
import Vue from 'vue'
import { Component, Watch, Prop } from 'vue-property-decorator'
import { Store } from 'vuex'
import { UserStore } from '@modules'
import { GlobalStore } from '@modules'
import { ITodoList } from '../../model'
@Component({
components: {
menuOne
}
})
export default class Drawer extends Vue {
public $q
$t: any
public arrlista = GlobalStore.state.listatodo
photo = ''
user = null
links
created() {
let listatodo = []
this.arrlista.forEach((elem: ITodoList) => {
let item = {
route: '/todo/' + elem.namecat,
faIcon: 'fa fa-list-alt',
materialIcon: 'todo',
name: 'pages.' + elem.description
}
listatodo.push(item)
})
if (UserStore.state.isAdmin) {
this.links = {
Dashboard: {
routes: [
{ route: '/', faIcon: 'fa fa-home', materialIcon: 'home', name: 'pages.home' },
{
route: '/todo', faIcon: 'fa fa-list-alt', materialIcon: 'todo', name: 'pages.Todo',
routes2: listatodo
},
{ route: '/category', faIcon: 'fa fa-list-alt', materialIcon: 'category', name: 'pages.Category' },
{ route: '/signup', faIcon: 'fa fa-registered', materialIcon: 'home', name: 'pages.SignUp' },
{ route: '/admin/cfgserv', faIcon: 'fa fa-database', materialIcon: 'admin', name: 'pages.Admin' },
{ route: '/admin/testp1/par1', faIcon: 'fa fa-database', materialIcon: 'admin', name: 'pages.Test1' },
{ route: '/admin/testp1/par2', faIcon: 'fa fa-database', materialIcon: 'admin', name: 'pages.Test2' },
{ route: '/signin', faIcon: 'fa fa-anchor', materialIcon: 'home', name: 'pages.SignIn' },
/* {route: '/vreg?idlink=aaa', faIcon: 'fa fa-login', materialIcon: 'login', name: 'pages.vreg'},*/
],
show: true,
}
}
} else {
// PRODUCTION USER:
if (process.env.PROD) {
this.links = {
Dashboard: {
routes: [
{ route: '/', faIcon: 'fa fa-home', materialIcon: 'home', name: 'pages.home' },
],
show: true,
}
}
} else {
// SERVER TEST
this.links = {
Dashboard: {
routes: [
{ route: '/', faIcon: 'fa fa-home', materialIcon: 'home', name: 'pages.home' },
{
route: '/todo', faIcon: 'fa fa-list-alt', materialIcon: 'todo', name: 'pages.Todo',
routes2: listatodo
},
{ route: '/category', faIcon: 'fa fa-list-alt', materialIcon: 'category', name: 'pages.Category' },
{ route: '/signup', faIcon: 'fa fa-registered', materialIcon: 'home', name: 'pages.SignUp' },
{ route: '/signin', faIcon: 'fa fa-anchor', materialIcon: 'home', name: 'pages.SignIn' },
/* {route: '/vreg?idlink=aaa', faIcon: 'fa fa-login', materialIcon: 'login', name: 'pages.vreg'},*/
],
show: true,
}
}
}
}
}
get MenuCollapse() {
return GlobalStore.state.menuCollapse
// return true
}
get Username() {
return UserStore.state.username
}
get Verificato() {
return UserStore.state.verified_email
}
get Email() {
return UserStore.state.email
}
logoutHandler() {
UserStore.actions.logout()
this.$router.push('/signin')
this.$q.notify(this.$t('logout.uscito'))
}
}

View File

@@ -31,153 +31,8 @@
</div> </div>
</template> </template>
<script lang="ts"> <script lang="ts" src="./drawer.ts">
import menuOne from './menuOne.vue'
import Vue from 'vue'
import { Component, Watch, Prop } from 'vue-property-decorator'
import { Store } from 'vuex'
import { UserStore } from '@modules'
import { GlobalStore } from '@modules'
import { ITodoList } from "../../model";
@Component({
components: {
menuOne,
}
})
export default class Drawer extends Vue {
public $q
$t: any
public arrlista = GlobalStore.state.listatodo
photo = ''
user = null
links
created() {
let listatodo = []
this.arrlista.forEach((elem: ITodoList) => {
let item = { route: '/todo/' + elem.namecat, faIcon: 'fa fa-list-alt', materialIcon: 'todo', name: 'pages.' + elem.description }
listatodo.push(item)
})
if (UserStore.state.isAdmin) {
this.links = {
Dashboard: {
routes: [
{ route: '/', faIcon: 'fa fa-home', materialIcon: 'home', name: 'pages.home' },
{
route: '/todo', faIcon: 'fa fa-list-alt', materialIcon: 'todo', name: 'pages.Todo',
routes2: listatodo
},
{ route: '/category', faIcon: 'fa fa-list-alt', materialIcon: 'category', name: 'pages.Category' },
{ route: '/signup', faIcon: 'fa fa-registered', materialIcon: 'home', name: 'pages.SignUp' },
{ route: '/admin/cfgserv', faIcon: 'fa fa-database', materialIcon: 'admin', name: 'pages.Admin' },
{ route: '/signin', faIcon: 'fa fa-anchor', materialIcon: 'home', name: 'pages.SignIn' },
/* {route: '/vreg?idlink=aaa', faIcon: 'fa fa-login', materialIcon: 'login', name: 'pages.vreg'},*/
],
show: true,
}
}
} else {
// Normal USER:
this.links = {
Dashboard: {
routes: [
{ route: '/', faIcon: 'fa fa-home', materialIcon: 'home', name: 'pages.home' },
{
route: '/todo', faIcon: 'fa fa-list-alt', materialIcon: 'todo', name: 'pages.Todo',
routes2: listatodo
},
{ route: '/signup', faIcon: 'fa fa-registered', materialIcon: 'home', name: 'pages.SignUp' },
{ route: '/signin', faIcon: 'fa fa-anchor', materialIcon: 'home', name: 'pages.SignIn' },
],
show: true,
}
}
}
}
get MenuCollapse() {
return GlobalStore.state.menuCollapse
// return true
}
get Username() {
return UserStore.state.username
}
get Verificato() {
return UserStore.state.verified_email
}
get Email() {
return UserStore.state.email
}
logoutHandler() {
UserStore.actions.logout()
this.$router.push('/signin')
this.$q.notify(this.$t('logout.uscito'))
}
}
</script> </script>
<style scoped lang="scss"> <style lang="scss" scoped>
.background-red { @import './drawer.scss';
background-color: red;
padding: 2px;
}
.fixed-bottom {
margin-bottom: 1%;
}
.fixed-bottom a img {
width: 25px;
height: 25px;
}
#avatar {
padding: 20px;
}
#profile {
height: 130px;
background-color: #009688;
}
#user-name {
left: 90px;
bottom: 77px;
position: relative;
width: 159px;
}
#user-actions {
left: 90px;
bottom: 71px;
position: relative;
width: 171px;
}
#menu-collapse {
margin-top: 5%;
}
.fixed-left:hover {
cursor: ew-resize;
}
footer {
small {
color: red;
}
}
</style> </style>

View File

@@ -14,6 +14,11 @@ export interface ICfgServer {
valore: string valore: string
} }
export interface ITestp1 {
contatore: number
mioarray: ICfgServer[]
}
export type StateConnection = 'online' | 'offline' export type StateConnection = 'online' | 'offline'
export interface IGlobalState { export interface IGlobalState {
@@ -29,6 +34,7 @@ export interface IGlobalState {
stateConnection: string stateConnection: string
networkDataReceived: boolean networkDataReceived: boolean
cfgServer: ICfgServer[] cfgServer: ICfgServer[]
testp1: ITestp1
connData: IConnData connData: IConnData
posts: IPost[] posts: IPost[]
listatodo: ITodoList[] listatodo: ITodoList[]

View File

@@ -1,28 +1,48 @@
export interface ITodo { export interface ITodo {
_id?: any, _id?: any,
userId: string userId?: string
category?: string category?: string
descr?: string, descr?: string,
priority: number, priority?: number,
completed: boolean, completed?: boolean,
created_at: Date, created_at?: Date,
modify_at: Date, modify_at?: Date,
completed_at: Date, completed_at?: Date,
expiring_at: Date, expiring_at?: Date,
enableExpiring?: boolean, enableExpiring?: boolean,
id_prev?: string, id_prev?: string,
id_next?: string,
modified?: boolean, modified?: boolean,
pos?: number, pos?: number,
order?: number, order?: number,
progress?: number progress?: number
} }
export interface IParamTodo {
categorySel?: string
checkPending?: boolean
id?: string
objtodo?: ITodo
atfirst?: boolean
}
export interface IDrag {
field?: string
idelemtochange?: string
prioritychosen?: number
oldIndex?: number
newIndex?: number
category: string
atfirst?: boolean
}
export interface ITodosState { export interface ITodosState {
visuOnlyUncompleted: boolean visuOnlyUncompleted: boolean
todos: ITodo[] todos: [ ITodo[] ]
todos_changed: number categories: string[]
// todos_changed: number
reload_fromServer: number reload_fromServer: number
testpao: String testpao: String
insidePending: boolean insidePending: boolean
visuLastCompleted: number
} }

View File

@@ -1,13 +1,13 @@
// src/plugins/i18n.js // src/plugins/i18n.js
import VueI18n from 'vue-i18n'; import VueI18n from 'vue-i18n';
import messages from 'src/statics/i18n'; import messages from 'src/assets/i18n';
import { rescodes } from "../store/Modules/rescodes"; import { tools } from "../store/Modules/tools";
export default ({ app, store, Vue }) => { export default ({ app, store, Vue }) => {
Vue.use(VueI18n); Vue.use(VueI18n);
// Vue.config.lang = process.env.LANG_DEFAULT; // Vue.config.lang = process.env.LANG_DEFAULT;
let mylang = rescodes.getItemLS(rescodes.localStorage.lang) let mylang = tools.getItemLS(tools.localStorage.lang)
if ((navigator) && (mylang === '')) { if ((navigator) && (mylang === '')) {
mylang = navigator.language mylang = navigator.language

View File

@@ -1,3 +1,209 @@
.mycard { .mycard {
visibility: hidden; visibility: hidden;
} }
.landing {
background: #000 url(../../assets/images/cover.jpg) no-repeat 50% fixed;
background-size: cover
}
.landing > section {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center;
padding: 0 16px
}
.landing > section.padding {
padding: 180px 16px
}
.landing > section > div {
position: relative;
max-width: 1040px;
width: 100%
}
.landing__toolbar {
background: -webkit-gradient(linear, left top, left bottom, from(#000), to(transparent));
background: linear-gradient(180deg, #000, transparent);
padding: 0 !important
}
.landing__toolbar .q-btn {
border-radius: 0 0 5px 5px;
-ms-flex-item-align: stretch;
align-self: stretch
}
.landing__hero {
min-height: 100vh
}
.landing__arrow {
bottom: 8px;
opacity: .4
}
.landing__front {
background: -webkit-gradient(linear, left top, left bottom, from(transparent), color-stop(15%, rgba(0, 0, 0, .6)));
background: linear-gradient(180deg, transparent, rgba(0, 0, 0, .6) 15%)
}
.landing__logo {
width: 150px;
height: 150px;
margin-top: 21px;
-webkit-animation: logo-rotate 240s linear infinite;
animation: logo-rotate 240s linear infinite
}
.landing__features .q-icon {
font-size: 64px
}
.landing__features h4, .landing__features h6 {
margin: 26px 0
}
.landing__features p {
opacity: .6;
font-size: 16px
}
.landing__footer {
background: -webkit-gradient(linear, left top, left bottom, color-stop(65%, rgba(0, 0, 0, .1)), to(#000));
background: linear-gradient(180deg, rgba(0, 0, 0, .1) 65%, #000);
padding-top: 72px !important;
padding-bottom: 72px !important
}
.landing__footer .doc-link {
color: #fff
}
.landing__footer .doc-link:hover {
opacity: .8
}
.landing__swirl-bg {
background-repeat: no-repeat !important;
background-position: top;
background-size: contain !important;
background-image: url(https://cdn.quasar-framework.org/img/landing_first_section.png) !important
}
@media (max-width: 718px) {
.landing__hero {
text-align: center
}
.landing__hero .text-h1 {
font-size: 3rem;
line-height: 3.05rem;
margin-bottom: 24px
}
.landing > section.padding {
padding-top: 90px;
padding-bottom: 90px
}
.landing .feature-item {
text-align: center
}
.landing__hero-content {
padding-bottom: 180px
}
.landing__hero-btns {
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center
}
}
body.mobile .landing {
background: unset
}
body.mobile .landing:before {
content: "";
position: fixed;
top: 0;
height: 100vh;
left: 0;
right: 0;
bottom: 0;
z-index: -1;
background: #000 url(../../assets/images/cover.jpg) 50%;
background-size: cover
}
@-webkit-keyframes logo-rotate {
to {
-webkit-transform: rotate(-1turn);
transform: rotate(-1turn)
}
}
@keyframes logo-rotate {
to {
-webkit-transform: rotate(-1turn);
transform: rotate(-1turn)
}
}
.home {
//background-color: rgb(250, 250, 250);
padding: 5px;
display: flex;
//flex-wrap: nowrap;
flex-direction: column;
align-items: center;
justify-content: space-between;
}
.shadow {
//color: white;
text-shadow: 2px 2px 4px #000000;
}
.shadow-max {
//color: white;
text-shadow: 4px 4px 8px #000000;
}
.text-h1 {
font-size: 6rem;
font-weight: 300;
line-height: 6rem;
letter-spacing: -.01562em;
}
.text-weight-bold {
font-weight: 700;
}
.text-subtitle1 {
font-size: 1.25rem;
font-weight: 400;
line-height: 1.75rem;
letter-spacing: .00937em;
&.big {
font-size: 1.5rem;
}
}
.text-subtitle2 {
font-size: 1rem;
font-weight: 400;
line-height: 1.75rem;
letter-spacing: .00937em;
}

View File

@@ -30,6 +30,7 @@ export default class Home extends Vue {
GlobalStore.actions.prova() GlobalStore.actions.prova()
} }
meta() { meta() {
return { return {
keywords: { name: 'keywords', content: 'Quasar website' }, keywords: { name: 'keywords', content: 'Quasar website' },
@@ -95,7 +96,7 @@ export default class Home extends Vue {
options = { options = {
body: 'You successfully subscribed to our Notification service!', body: 'You successfully subscribed to our Notification service!',
icon: '/statics/icons/app-icon-96x96.png', icon: '/statics/icons/app-icon-96x96.png',
image: '/src/images/sf-boat.jpg', image: '/assets/images/sf-boat.jpg',
dir: 'ltr', dir: 'ltr',
lang: 'enUs', // BCP 47, lang: 'enUs', // BCP 47,
vibrate: [100, 50, 200], vibrate: [100, 50, 200],
@@ -152,7 +153,7 @@ export default class Home extends Vue {
options = { options = {
body: mythis.$t('notification.subscribed'), body: mythis.$t('notification.subscribed'),
icon: '/statics/icons/android-chrome-192x192.png', icon: '/statics/icons/android-chrome-192x192.png',
image: '/statics/images/freeplanet.png', image: '/assets/images/freeplanet.png',
dir: 'ltr', dir: 'ltr',
lang: 'enUs', // BCP 47, lang: 'enUs', // BCP 47,
vibrate: [100, 50, 200], vibrate: [100, 50, 200],

View File

@@ -1,33 +1,95 @@
<template > <template>
<q-page class="flex flex-center"> <q-page class="text-white">
<div class="landing">
<section>
<div class="landing__hero">
<div style="height: 18vh;"></div>
<div class="landing__hero-content row justify-center q-gutter-xl">
<div class="row">
<logo></logo> <logo></logo>
</div>
<div class="flex justify-end">
<div class="q-gutter-sm">
<div class="text-h1 shadow-max">FreePlanet</div>
<div class="text-subtitle1 shadow text-italic q-pl-sm">{{$t('msg.sottoTitoloApp')}}
</div>
<div class="text-subtitle1 shadow big text-italic q-pl-sm"><strong>{{$t('msg.sottoTitoloApp2')}}</strong>
</div>
<div class="text-subtitle2 shadow text-italic q-pl-sm ">{{$t('msg.sottoTitoloApp3')}}
</div>
<q-btn v-if="getPermission() !== 'granted'" class="enable-notifications" color="primary" rounded size="lg" icon="notifications" @click="askfornotification" :label="$t('notification.ask')"/> <div>
<q-btn v-if="getPermission() !== 'granted'" class="enable-notifications shadow"
color="primary" rounded
size="lg"
icon="notifications" @click="askfornotification"
:label="$t('notification.ask')"/>
<!--<q-btn v-if="getPermission() === 'granted'" class="enable-notifications" color="primary" rounded size="lg" icon="notifications" @click="showNotificationExample" label="Send Notification"/>--> <!--<q-btn v-if="getPermission() === 'granted'" class="enable-notifications" color="primary" rounded size="lg" icon="notifications" @click="showNotificationExample" label="Send Notification"/>-->
<!--<q-btn v-if="getPermission() === 'granted'" class="enable-notifications" color="secondary" rounded size="lg" icon="notifications" @click="createPushSubscription" label="Create Push Subscription !"/>--> <!--<q-btn v-if="getPermission() === 'granted'" class="enable-notifications" color="secondary" rounded size="lg" icon="notifications" @click="createPushSubscription" label="Create Push Subscription !"/>-->
</div>
<!--
<q-btn>
Canale Telegram: <a href="https://t.me/freeplanet_channel" target="_blank"
style="color: white;">
<q-icon class="fab fa-telegram" size="2rem"/>
</a>
</q-btn>
-->
<div style="margin: 5px;">
<q-alert
type="info"
class="q-mb-sm">
{{$t('msg.underconstruction')}}
</q-alert>
</div>
<br> <br>
<div> <div>
<q-chip square color="secondary">
Status:
</q-chip>
<q-field <q-field
v-if="getPermission() === 'granted'" v-if="getPermission() === 'granted'"
icon="notifications" icon="notifications"
class="shadow"
:label="$t('notification.titlegranted')" :label="$t('notification.titlegranted')"
helper="Stato Notifiche"> helper="Stato Notifiche">
</q-field> </q-field>
<q-field <q-field
v-if="NotServiceWorker()" v-if="NotServiceWorker()"
class="shadow"
icon="notifications" icon="notifications"
label="Service Worker not present" label="Service Worker not present"
> >
</q-field> </q-field>
</div> </div>
<!--<div class="q-pt-md q-pl-sm">-->
<!--<div class="landing__hero-btns q-gutter-md row items-center"><a tabindex="0"-->
<!--type="button"-->
<!--href="/introduction-to-quasar"-->
<!--class="q-btn inline relative-position q-btn-item non-selectable q-btn&#45;&#45;rectangle bg-white text-primary q-focusable q-hoverable q-btn&#45;&#45;push">-->
<!--<div class="q-focus-helper"></div>-->
<!--<div class="q-btn__content text-center col items-center q-anchor&#45;&#45;skip justify-center row">-->
<!--<div>About</div>-->
<!--</div>-->
<!--</a><a tabindex="0" type="button" href="/start"-->
<!--class="q-btn inline relative-position q-btn-item non-selectable q-btn&#45;&#45;rectangle bg-white text-primary q-focusable q-hoverable q-btn&#45;&#45;push">-->
<!--<div class="q-focus-helper"></div>-->
<!--<div class="q-btn__content text-center col items-center q-anchor&#45;&#45;skip justify-center row">-->
<!--<div>Get started</div>-->
<!--</div>-->
<!--</a>-->
<!--<div class="text-body2">v1.0.0-beta.4</div>-->
<!--</div>-->
<!--</div>-->
</div>
</div>
</div>
</div>
</section>
</div>
</q-page> </q-page>

View File

@@ -0,0 +1,98 @@
<template>
<q-page class="landing text-white">
<section>
<div class="landing__hero">
<div style="height: 28vh;"></div>
<div class="landing__hero-content row justify-center q-gutter-xl">
<div class="row"><img src="https://cdn.quasar-framework.org/logo/svg/quasar-logo.svg"
class="landing__logo"></div>
<div class="flex justify-end">
<div class="q-gutter-sm">
<div class="text-h1">
<div class="text-weight-bold">Quasar</div>
<div>Framework</div>
</div>
<div class="text-subtitle1 text-italic q-pl-sm">High performance, <strong>Material
Design
2</strong>, full front end stack with <strong>Vuejs</strong></div>
<div class="q-pt-md q-pl-sm">
<div class="landing__hero-btns q-gutter-md row items-center"><a tabindex="0"
type="button"
href="/introduction-to-quasar"
class="q-btn inline relative-position q-btn-item non-selectable q-btn--rectangle bg-white text-primary q-focusable q-hoverable q-btn--push">
<div class="q-focus-helper"></div>
<div class="q-btn__content text-center col items-center q-anchor--skip justify-center row">
<div>About</div>
</div>
</a><a tabindex="0" type="button" href="/start"
class="q-btn inline relative-position q-btn-item non-selectable q-btn--rectangle bg-white text-primary q-focusable q-hoverable q-btn--push">
<div class="q-focus-helper"></div>
<div class="q-btn__content text-center col items-center q-anchor--skip justify-center row">
<div>Get started</div>
</div>
</a>
<div class="text-body2">v1.0.0-beta.4</div>
</div>
</div>
</div>
</div>
</div>
<div class="landing__arrow absolute-bottom text-center"><i aria-hidden="true"
class="q-icon text-h2 text-white material-icons">expand_more</i>
</div>
</div>
<!--<div>-->
<!--<logo></logo>-->
<!--</div>-->
<!--<div>-->
<!--&lt;!&ndash; the row with a type of gutter &ndash;&gt;-->
<!--<q-alert-->
<!--avatar="assets/boy-avatar.png"-->
<!--color="primary"-->
<!--message="Jack"-->
<!--detail="Per un mondo più Consapevole"-->
<!--/>-->
<!--</div>-->
<!--<div>-->
<!--<q-btn v-if="getPermission() !== 'granted'" class="enable-notifications" color="primary" rounded-->
<!--size="lg"-->
<!--icon="notifications" @click="askfornotification" :label="$t('notification.ask')"/>-->
<!--&lt;!&ndash;<q-btn v-if="getPermission() === 'granted'" class="enable-notifications" color="primary" rounded size="lg" icon="notifications" @click="showNotificationExample" label="Send Notification"/>&ndash;&gt;-->
<!--&lt;!&ndash;<q-btn v-if="getPermission() === 'granted'" class="enable-notifications" color="secondary" rounded size="lg" icon="notifications" @click="createPushSubscription" label="Create Push Subscription !"/>&ndash;&gt;-->
<!--</div>-->
<!--<div>-->
<!--<q-chip square color="secondary">-->
<!--{{$t('notification.status')}}-->
<!--</q-chip>-->
<!--</div>-->
<!--<div>-->
<!--<q-field-->
<!--v-if="getPermission() === 'granted'"-->
<!--icon="notifications"-->
<!--:label="$t('notification.titlegranted')"-->
<!--helper="Stato Notifiche">-->
<!--</q-field>-->
<!--<q-field-->
<!--v-if="NotServiceWorker()"-->
<!--icon="notifications"-->
<!--label="Service Worker not present"-->
<!--&gt;-->
<!--</q-field>-->
<!--</div>-->
</section>
</q-page>
</template>
<script lang="ts" src="./home.ts">
</script>
<style lang="scss" scoped>
@import './home.scss';
</style>

View File

@@ -40,6 +40,11 @@ export const RouteConfig: VueRouteConfig[] = [
component: () => import('@/components/admin/cfgServer/cfgServer.vue'), component: () => import('@/components/admin/cfgServer/cfgServer.vue'),
meta: { name: 'Categories' } meta: { name: 'Categories' }
}, },
{
path: '/admin/testp1/:category',
component: () => import('@/components/admin/testp1/testp1.vue'),
meta: { name: 'Categories' }
},
{ {
path: '/offline', path: '/offline',
component: () => import('@/components/offline/offline.vue'), component: () => import('@/components/offline/offline.vue'),

Binary file not shown.

Before

Width:  |  Height:  |  Size: 163 KiB

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 190 KiB

File diff suppressed because one or more lines are too long

View File

@@ -4,7 +4,7 @@ import router from '@router'
import { clone } from 'lodash' import { clone } from 'lodash'
import * as Types from './ApiTypes' import * as Types from './ApiTypes'
import { GlobalStore, UserStore } from '@store' import { GlobalStore, UserStore } from '@store'
import { rescodes } from '@src/store/Modules/rescodes' import { tools } from '@src/store/Modules/tools'
import { serv_constants } from '@src/store/Modules/serv_constants' import { serv_constants } from '@src/store/Modules/serv_constants'
export const API_URL = process.env.MONGODB_HOST export const API_URL = process.env.MONGODB_HOST
@@ -40,7 +40,7 @@ export const removeAuthHeaders = () => {
async function Request(type: string, path: string, payload: any, setAuthToken?: boolean): Promise<Types.AxiosSuccess | Types.AxiosError> { async function Request(type: string, path: string, payload: any, setAuthToken?: boolean): Promise<Types.AxiosSuccess | Types.AxiosError> {
let ricevuto = false let ricevuto = false
try { try {
console.log(`Axios Request [${type}]:`, axiosInstance.defaults) // console.log(`Axios Request [${type}]:`, axiosInstance.defaults)
let response: AxiosResponse let response: AxiosResponse
if (type === 'post' || type === 'put' || type === 'patch') { if (type === 'post' || type === 'put' || type === 'patch') {
response = await axiosInstance[type](path, payload, { response = await axiosInstance[type](path, payload, {
@@ -50,7 +50,7 @@ async function Request(type: string, path: string, payload: any, setAuthToken?:
} }
}) })
ricevuto = true ricevuto = true
console.log('response', response) // console.log('Request Response: ', response)
// console.log(new Types.AxiosSuccess(response.data, response.status)) // console.log(new Types.AxiosSuccess(response.data, response.status))
const setAuthToken = (path === '/updatepwd') const setAuthToken = (path === '/updatepwd')
@@ -62,26 +62,26 @@ async function Request(type: string, path: string, payload: any, setAuthToken?:
x_auth_token = String(response.headers['x-auth']) x_auth_token = String(response.headers['x-auth'])
if (x_auth_token === '') { if (x_auth_token === '') {
UserStore.mutations.setServerCode(rescodes.ERR_AUTHENTICATION) UserStore.mutations.setServerCode(tools.ERR_AUTHENTICATION)
} }
if (setAuthToken) { if (setAuthToken) {
UserStore.mutations.UpdatePwd(x_auth_token) UserStore.mutations.UpdatePwd(x_auth_token)
localStorage.setItem(rescodes.localStorage.token, x_auth_token) localStorage.setItem(tools.localStorage.token, x_auth_token)
} }
UserStore.mutations.setAuth(x_auth_token) UserStore.mutations.setAuth(x_auth_token)
localStorage.setItem(rescodes.localStorage.token, x_auth_token) localStorage.setItem(tools.localStorage.token, x_auth_token)
} }
GlobalStore.mutations.setStateConnection(ricevuto ? 'online' : 'offline') GlobalStore.mutations.setStateConnection(ricevuto ? 'online' : 'offline')
UserStore.mutations.setServerCode(rescodes.OK) UserStore.mutations.setServerCode(tools.OK)
} catch (e) { } catch (e) {
if (setAuthToken) { if (setAuthToken) {
UserStore.mutations.setServerCode(rescodes.ERR_AUTHENTICATION) UserStore.mutations.setServerCode(tools.ERR_AUTHENTICATION)
UserStore.mutations.setAuth('') UserStore.mutations.setAuth('')
} }
GlobalStore.mutations.setStateConnection(ricevuto ? 'online' : 'offline') GlobalStore.mutations.setStateConnection(ricevuto ? 'online' : 'offline')
return Promise.reject(new Types.AxiosError(serv_constants.RIS_CODE__HTTP_FORBIDDEN_INVALID_TOKEN, null, rescodes.ERR_AUTHENTICATION)) return Promise.reject(new Types.AxiosError(serv_constants.RIS_CODE__HTTP_FORBIDDEN_INVALID_TOKEN, null, tools.ERR_AUTHENTICATION))
} }
} }
@@ -120,11 +120,11 @@ async function Request(type: string, path: string, payload: any, setAuthToken?:
} }
let mycode = 0 let mycode = 0
if (!ricevuto) { if (!ricevuto) {
mycode = rescodes.ERR_SERVERFETCH mycode = tools.ERR_SERVERFETCH
UserStore.mutations.setServerCode(rescodes.ERR_SERVERFETCH) UserStore.mutations.setServerCode(tools.ERR_SERVERFETCH)
} else { } else {
mycode = rescodes.ERR_GENERICO mycode = tools.ERR_GENERICO
UserStore.mutations.setServerCode(rescodes.ERR_GENERICO) UserStore.mutations.setServerCode(tools.ERR_GENERICO)
} }
if (error.response) { if (error.response) {

View File

@@ -7,7 +7,7 @@ import axios from 'axios'
export { addAuthHeaders, removeAuthHeaders, API_URL } from './Instance' export { addAuthHeaders, removeAuthHeaders, API_URL } from './Instance'
// import {AlgoliaSearch} from './AlgoliaController' // import {AlgoliaSearch} from './AlgoliaController'
import Paths from '@paths' import Paths from '@paths'
import { rescodes } from '@src/store/Modules/rescodes' import { tools } from '@src/store/Modules/tools'
import { GlobalStore, UserStore } from '@modules' import { GlobalStore, UserStore } from '@modules'
import globalroutines from './../../globalroutines/index' import globalroutines from './../../globalroutines/index'
@@ -62,7 +62,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: boolean = false): Promise<Types.AxiosSuccess | Types.AxiosError> {
UserStore.mutations.setServerCode(rescodes.EMPTY) UserStore.mutations.setServerCode(tools.EMPTY)
UserStore.mutations.setResStatus(0) UserStore.mutations.setResStatus(0)
return await new Promise(function (resolve, reject) { return await new Promise(function (resolve, reject) {
@@ -85,10 +85,10 @@ export namespace ApiTool {
if (res.status === serv_constants.RIS_CODE__HTTP_FORBIDDEN_INVALID_TOKEN) { if (res.status === serv_constants.RIS_CODE__HTTP_FORBIDDEN_INVALID_TOKEN) {
// Forbidden // Forbidden
// You probably is connectiong with other page... // You probably is connectiong with other page...
UserStore.mutations.setServerCode(rescodes.ERR_AUTHENTICATION) UserStore.mutations.setServerCode(tools.ERR_AUTHENTICATION)
UserStore.mutations.setAuth('') UserStore.mutations.setAuth('')
router.push('/signin') router.push('/signin')
return reject({ code: rescodes.ERR_AUTHENTICATION }) return reject({ code: tools.ERR_AUTHENTICATION })
} }
return resolve(res) return resolve(res)
@@ -147,7 +147,7 @@ export namespace ApiTool {
if (method !== 'POST') if (method !== 'POST')
link += '/' + rec._id link += '/' + rec._id
console.log(' [Alternative] ++++++++++++++++++ SYNCING !!!! ', rec.descr, table, 'FETCH: ', method, link, 'data:') // console.log(' [Alternative] ++++++++++++++++++ SYNCING !!!! ', rec.descr, table, 'FETCH: ', method, link, 'data:')
// Insert/Delete/Update table to the server // Insert/Delete/Update table to the server
return SendReq(link, method, rec) return SendReq(link, method, rec)

View File

@@ -7,14 +7,14 @@ import translate from './../../globalroutines/util'
import urlBase64ToUint8Array from '../../js/utility' import urlBase64ToUint8Array from '../../js/utility'
import messages from '../../statics/i18n' import messages from '../../assets/i18n'
import { GlobalStore, Todos, UserStore } from '@store' import { GlobalStore, Todos, UserStore } from '@store'
import globalroutines from './../../globalroutines/index' import globalroutines from './../../globalroutines/index'
import Api from '@api' import Api from '@api'
import { rescodes } from '@src/store/Modules/rescodes' import { tools } from '@src/store/Modules/tools'
const allTables = ['todos', 'sync_todos', 'sync_todos_patch', 'delete_todos', 'config', 'swmsg'] const allTables = ['todos', 'categories', 'sync_todos', 'sync_todos_patch', 'delete_todos', 'config', 'swmsg']
const allTablesAfterLogin = ['todos', 'sync_todos', 'sync_todos_patch', 'delete_todos', 'config', 'swmsg'] const allTablesAfterLogin = ['todos', 'categories', 'sync_todos', 'sync_todos_patch', 'delete_todos', 'config', 'swmsg']
async function getstateConnSaved() { async function getstateConnSaved() {
const config = await globalroutines(null, 'readall', 'config', null) const config = await globalroutines(null, 'readall', 'config', null)
@@ -44,6 +44,7 @@ const state: IGlobalState = {
stateConnection: stateConnDefault, stateConnection: stateConnDefault,
networkDataReceived: false, networkDataReceived: false,
cfgServer: [], cfgServer: [],
testp1: { contatore: 0, mioarray: [] },
category: 'personal', category: 'personal',
posts: [], posts: [],
listatodo: [ listatodo: [
@@ -69,7 +70,17 @@ namespace Getters {
const listatodo = b.read(state => state.listatodo, 'listatodo') const listatodo = b.read(state => state.listatodo, 'listatodo')
const category = b.read(state => state.category, 'category') const category = b.read(state => state.category, 'category')
const testpao1_getter_contatore = b.read(state => param1 => state.testp1.contatore + 100 + param1, 'testpao1_getter_contatore')
const testpao1_getter_array = b.read(state => param1 => state.testp1.mioarray.filter(item => item).map(item => item.valore) , 'testpao1_getter_array')
export const getters = { export const getters = {
get testpao1_getter_contatore() {
return testpao1_getter_contatore()
},
get testpao1_getter_array() {
return testpao1_getter_array()
},
get conta() { get conta() {
return conta() return conta()
}, },
@@ -89,7 +100,7 @@ namespace Getters {
get isNewVersionAvailable() { get isNewVersionAvailable() {
console.log('state.cfgServer', state.cfgServer) console.log('state.cfgServer', state.cfgServer)
const serversrec = state.cfgServer.find(x => x.chiave === rescodes.SERVKEY_VERS) const serversrec = state.cfgServer.find(x => x.chiave === tools.SERVKEY_VERS)
console.log('Record ', serversrec) console.log('Record ', serversrec)
if (serversrec) { if (serversrec) {
console.log('Vers Server ', serversrec.valore, 'Vers locale:', process.env.APP_VERSION) console.log('Vers Server ', serversrec.valore, 'Vers locale:', process.env.APP_VERSION)
@@ -101,6 +112,18 @@ namespace Getters {
} }
namespace Mutations { namespace Mutations {
function setPaoArray(state: IGlobalState, miorec: ICfgServer) {
state.testp1.mioarray[state.testp1.mioarray.length - 1] = miorec
tools.notifyarraychanged(state.testp1.mioarray)
console.log('last elem = ', state.testp1.mioarray[state.testp1.mioarray.length - 1])
}
function NewArray(state: IGlobalState, newarr: ICfgServer[]) {
state.testp1.mioarray = newarr
}
function setPaoArray_Delete(state: IGlobalState) {
state.testp1.mioarray.pop()
}
function setConta(state: IGlobalState, num: number) { function setConta(state: IGlobalState, num: number) {
state.conta = num state.conta = num
@@ -130,7 +153,10 @@ namespace Mutations {
setleftDrawerOpen: b.commit(setleftDrawerOpen), setleftDrawerOpen: b.commit(setleftDrawerOpen),
setCategorySel: b.commit(setCategorySel), setCategorySel: b.commit(setCategorySel),
setStateConnection: b.commit(setStateConnection), setStateConnection: b.commit(setStateConnection),
SetwasAlreadySubOnDb: b.commit(SetwasAlreadySubOnDb) SetwasAlreadySubOnDb: b.commit(SetwasAlreadySubOnDb),
setPaoArray: b.commit(setPaoArray),
setPaoArray_Delete: b.commit(setPaoArray_Delete),
NewArray: b.commit(NewArray)
} }
} }
@@ -170,7 +196,7 @@ namespace Actions {
mystate.wasAlreadySubscribed = !(subscription === null) mystate.wasAlreadySubscribed = !(subscription === null)
if (mystate.wasAlreadySubscribed) { if (mystate.wasAlreadySubscribed) {
console.log('User is already SAVED Subscribe on DB!') // console.log('User is already SAVED Subscribe on DB!')
// return null // return null
return subscription return subscription
} else { } else {
@@ -197,7 +223,7 @@ namespace Actions {
if (!newSub) if (!newSub)
return return
console.log('saveSubscriptionToServer: ', newSub) // console.log('saveSubscriptionToServer: ', newSub)
// console.log('context', context) // console.log('context', context)
let options = null let options = null
@@ -225,7 +251,7 @@ namespace Actions {
state.wasAlreadySubscribed = true state.wasAlreadySubscribed = true
state.wasAlreadySubOnDb = true state.wasAlreadySubOnDb = true
localStorage.setItem(rescodes.localStorage.wasAlreadySubOnDb, String(state.wasAlreadySubOnDb)) localStorage.setItem(tools.localStorage.wasAlreadySubOnDb, String(state.wasAlreadySubOnDb))
}) })
.catch(e => { .catch(e => {
console.log('Error during Subscription!', e) console.log('Error during Subscription!', e)
@@ -262,6 +288,7 @@ namespace Actions {
function prova(context) { function prova(context) {
// console.log('prova') // console.log('prova')
// state.testp1.mioarray[state.testp1.mioarray.length - 1].valore = 'VALMODIF';
// let msg = t('notification.title_subscribed') // let msg = t('notification.title_subscribed')
@@ -318,7 +345,7 @@ namespace Actions {
async function saveCfgServerKey(context, dataval: ICfgServer) { async function saveCfgServerKey(context, dataval: ICfgServer) {
console.log('saveCfgServerKey dataval', dataval) console.log('saveCfgServerKey dataval', dataval)
let ris = await Api.SendReq('/admin/updateval', 'POST', {pairval: dataval}) let ris = await Api.SendReq('/admin/updateval', 'POST', { pairval: dataval })
.then(res => { .then(res => {
}) })
@@ -341,7 +368,6 @@ namespace Actions {
if (res.data.cfgServer) { if (res.data.cfgServer) {
state.cfgServer = [...res.data.cfgServer] state.cfgServer = [...res.data.cfgServer]
console.log('res.data.cfgServer', res.data.cfgServer) console.log('res.data.cfgServer', res.data.cfgServer)
// Todos.mutations.setTodos_changed()
} }
// console.log('********** res', 'state.todos', state.todos, 'checkPending', checkPending) // console.log('********** res', 'state.todos', state.todos, 'checkPending', checkPending)

View File

@@ -1,92 +1,325 @@
import { IGlobalState, ITodo, ITodosState } from 'model' import { IGlobalState, ITodo, ITodosState, IParamTodo, IUserState, IDrag } from 'model'
import { storeBuilder } from './Store/Store' import { storeBuilder } from './Store/Store'
import Api from '@api' import Api from '@api'
import { rescodes } from './rescodes' import { tools } from './tools'
import { GlobalStore, Todos, UserStore } from '@store' import { GlobalStore, Todos, UserStore } from '@store'
import globalroutines from './../../globalroutines/index' import globalroutines from './../../globalroutines/index'
import { Mutation } from 'vuex-module-decorators' import { Mutation } from 'vuex-module-decorators'
import { serv_constants } from '@src/store/Modules/serv_constants' import { serv_constants } from '@src/store/Modules/serv_constants'
import { GetterTree } from 'vuex'
import objectId from '@src/js/objectId'
// import _ from 'lodash'
const state: ITodosState = { const state: ITodosState = {
visuOnlyUncompleted: false, visuOnlyUncompleted: false,
todos: [], todos: [[]],
todos_changed: 1, categories: [],
// todos_changed: 1,
reload_fromServer: 0, reload_fromServer: 0,
testpao: 'Test', testpao: 'Test',
insidePending: false insidePending: false,
visuLastCompleted: 10
} }
const b = storeBuilder.module<ITodosState>('TodosModule', state) const fieldtochange: String [] = ['descr', 'completed', 'category', 'expiring_at', 'priority', 'id_prev', 'pos', 'enableExpiring', 'progress']
const b = storeBuilder.module<ITodosState>('Todos', state)
const stateGetter = b.state() const stateGetter = b.state()
// Getters function getindexbycategory(category: string) {
namespace Getters { return state.categories.indexOf(category)
}
function gettodosByCategory(category: string) {
const indcat = state.categories.indexOf(category)
if (!state.todos[indcat])
return []
return state.todos[indcat]
}
function isValidIndex(cat, index) {
const myarr = gettodosByCategory(cat)
return (index >= 0 && index < myarr.length)
}
function getElemByIndex(cat, index) {
const myarr = gettodosByCategory(cat)
if (index >= 0 && index < myarr.length)
return myarr[index]
else
return null
}
function getElemById(cat, id) {
const myarr = gettodosByCategory(cat)
for (let indrec = 0; indrec < myarr.length; indrec++) {
if (myarr[indrec]._id === id) {
return myarr[indrec]
}
}
return null
}
function getIndexById(cat, id) {
const myarr = gettodosByCategory(cat)
for (let indrec = 0; indrec < myarr.length; indrec++) {
if (myarr[indrec]._id === id) {
return indrec
}
}
return -1
}
function getElemPrevById(cat, id_prev) {
const myarr = gettodosByCategory(cat)
for (let indrec = 0; indrec < myarr.length; indrec++) {
if (myarr[indrec].id_prev === id_prev) {
return myarr[indrec]
}
}
return null
}
function getLastFirstElemPriority(cat: string, priority: number, atfirst: boolean, escludiId: string) {
const myarr = gettodosByCategory(cat)
if (myarr === null)
return -1
let trovato: boolean = false
console.log('priority', priority)
for (let indrec = 0; indrec < myarr.length; indrec++) {
if ((myarr[indrec].priority === priority) && (myarr[indrec]._id !== escludiId)) {
trovato = true
if (atfirst) {
return indrec - 1
}
} else {
if (trovato) {
return indrec
}
}
}
console.log('trovato?', trovato, 'indrec')
if (trovato) {
return myarr.length - 1
} else {
if (priority === tools.Todos.PRIORITY_LOW)
return myarr.length - 1
else if (priority === tools.Todos.PRIORITY_HIGH)
return 0
}
}
function getFirstList(cat) {
const myarr = gettodosByCategory(cat)
for (let indrec in myarr) {
if (myarr[indrec].id_prev === tools.LIST_START) {
return myarr[indrec]
}
}
return null
}
function getLastListNotCompleted(cat) {
const arr = Todos.getters.todos_dacompletare(cat)
// console.log('cat', cat, 'arr', arr)
if (arr.length > 0)
return arr[arr.length - 1]
else
return null
}
function getstrelem(elem) {
return 'ID [' + elem._id + '] ' + elem.descr + ' [ID_PREV=' + elem.id_prev + '] modif=' + elem.modified
}
function update_idprev(indcat, indelemchange, indelemId) {
if (indelemchange >= 0 && indelemchange < state.todos[indcat].length) {
const id_prev = (indelemId >= 0) ? state.todos[indcat][indelemId]._id : tools.LIST_START
if (state.todos[indcat][indelemchange].id_prev !== id_prev) {
state.todos[indcat][indelemchange].id_prev = id_prev
tools.notifyarraychanged(state.todos[indcat][indelemchange])
// state.todos[indcat][indelemchange].modified = true
console.log('Index=', indelemchange, 'indtoget', indelemId, getstrelem(state.todos[indcat][indelemchange]))
return state.todos[indcat][indelemchange]
}
}
return null
}
function initcat() {
let tomorrow = new Date()
tomorrow.setDate(tomorrow.getDate() + 1)
const objtodo: ITodo = {
// _id: new Date().toISOString(), // Create NEW
_id: objectId(),
userId: UserStore.state.userId,
descr: '',
priority: tools.Todos.PRIORITY_NORMAL,
completed: false,
created_at: new Date(),
modify_at: new Date(),
completed_at: new Date(),
category: '',
expiring_at: tomorrow,
enableExpiring: false,
id_prev: '',
pos: 0,
modified: false,
progress: 0
}
// return this.copy(objtodo)
return objtodo
}
function deleteItemToSyncAndDb(table: String, item: ITodo, id) {
cmdToSyncAndDbTodo(tools.DB.CMD_DELETE_TODOS, table, 'DELETE', item, id, '')
}
async function saveItemToSyncAndDb(table: String, method, item: ITodo) {
return await cmdToSyncAndDbTodo(tools.DB.CMD_SYNC_NEW_TODOS, table, method, item, 0, '')
}
async function cmdToSyncAndDbTodo(cmd, table, method, item: ITodo, id, msg: String) {
// Send to Server to Sync
console.log('cmdToSyncAndDbTodo', cmd, table, method, item.descr, id, msg)
const risdata = await tools.cmdToSyncAndDb(cmd, table, method, item, id, msg)
if (cmd === tools.DB.CMD_SYNC_NEW_TODOS) {
if (method === 'POST')
await Todos.actions.dbInsertTodo(item)
else if (method === 'PATCH')
await Todos.actions.dbSaveTodo(item)
} else if (cmd === tools.DB.CMD_DELETE_TODOS) {
await Todos.actions.dbdeleteItem(item)
}
return risdata
}
namespace Getters {
// const fullName = b.read(function fullName(state): string {
// return state.userInfos.firstname?capitalize(state.userInfos.firstname) + " " + capitalize(state.userInfos.lastname):null;
// })
const todos_dacompletare = b.read((state: ITodosState) => (cat: string): ITodo[] => {
const indcat = getindexbycategory(cat)
if (state.todos[indcat]) {
return state.todos[indcat].filter(todo => !todo.completed)
} else return []
}, 'todos_dacompletare')
const todos_completati = b.read((state: ITodosState) => (cat: string): ITodo[] => {
const indcat = getindexbycategory(cat)
if (state.todos[indcat]) {
return state.todos[indcat].filter(todo => todo.completed).slice(0, state.visuLastCompleted) // Show only the first N completed
} else return []
}, 'todos_completati')
const doneTodosCount = b.read((state: ITodosState) => (cat: string): number => {
return getters.todos_completati(cat).length
}, 'doneTodosCount')
const TodosCount = b.read((state: ITodosState) => (cat: string): number => {
const indcat = getindexbycategory(cat)
if (state.todos[indcat]) {
return state.todos[indcat].length
} else {
return 0
}
}, 'TodosCount')
const visuOnlyUncompleted = b.read(state => state.visuOnlyUncompleted, 'visuOnlyUncompleted')
export const getters = { export const getters = {
get visuOnlyUncompleted() { // get fullName() { return fullName();},
return visuOnlyUncompleted get todos_dacompletare() {
return todos_dacompletare()
},
get todos_completati() {
return todos_completati()
},
get doneTodosCount() {
return doneTodosCount()
},
get TodosCount() {
return TodosCount()
} }
} }
} }
namespace Mutations { namespace Mutations {
function setTestpao(state: ITodosState, testpao: String) { function setTestpao(state: ITodosState, testpao: String) {
state.testpao = testpao state.testpao = testpao
} }
function setTodos_changed(state: ITodosState) { function findTodoById(state: ITodosState, data: IParamTodo) {
state.todos_changed++ const indcat = state.categories.indexOf(data.categorySel)
mutations.setTestpao('Cambiato : ' + String(state.todos_changed)) if (indcat >= 0) {
// console.log('******* state.todos_changed', state.todos_changed) if (state.todos[indcat]) {
} for (let i = 0; i < state.todos[indcat].length; i++) {
if (state.todos[indcat][i]._id === data.id)
function findTodoById(state: ITodosState, id: string) {
for (let i = 0; i < state.todos.length; i++) {
if (state.todos[i]._id === id)
return i return i
} }
}
}
return -1 return -1
} }
function createNewItem(state: ITodosState, { objtodo, atfirst }) { function createNewItem(state: ITodosState, { objtodo, atfirst, categorySel }) {
console.log('atfirst', atfirst) const indcat = state.categories.indexOf(categorySel)
if (atfirst) console.log('createNewItem', objtodo, 'cat=', categorySel, 'state.todos[indcat]', state.todos[indcat])
state.todos.unshift(objtodo) if (state.todos[indcat] === undefined) {
else state.todos[indcat] = []
state.todos.push(objtodo)
Todos.mutations.setTodos_changed()
} }
if (!state.todos[indcat]) {
state.todos[indcat].push(objtodo)
console.log('state.todos[indcat]', state.todos[indcat])
return
}
if (atfirst)
state.todos[indcat].unshift(objtodo)
else
state.todos[indcat].push(objtodo)
console.log('state.todos[indcat]', state.todos[indcat])
function modifymyItem(state: ITodosState, myitem: ITodo) {
// Find record
const ind = findTodoById(state, myitem._id)
if (ind >= 0)
state.todos[ind] = rescodes.jsonCopy(myitem)
} }
function deletemyitem(state: ITodosState, myitem: ITodo) { function deletemyitem(state: ITodosState, myitem: ITodo) {
// Find record // Find record
const ind = findTodoById(state, myitem._id) const indcat = state.categories.indexOf(myitem.category)
const ind = findTodoById(state, { id: myitem._id, categorySel: myitem.category })
console.log('PRIMA state.todos', state.todos)
// Delete Item in to Array // Delete Item in to Array
if (ind >= 0) if (ind >= 0)
state.todos.splice(ind, 1) state.todos[indcat].splice(ind, 1)
console.log('DOPO state.todos', state.todos, 'ind', ind)
// tools.notifyarraychanged(state.todos[indcat])
} }
export const mutations = { export const mutations = {
setTestpao: b.commit(setTestpao), setTestpao: b.commit(setTestpao),
setTodos_changed: b.commit(setTodos_changed),
modifymyItem: b.commit(modifymyItem),
deletemyitem: b.commit(deletemyitem), deletemyitem: b.commit(deletemyitem),
createNewItem: b.commit(createNewItem) createNewItem: b.commit(createNewItem)
} }
@@ -94,21 +327,12 @@ namespace Mutations {
} }
function consolelogpao(strlog, strlog2 = '', strlog3 = '') { function consolelogpao(strlog, strlog2 = '', strlog3 = '') {
globalroutines(null, 'log', strlog + strlog2 + strlog3, null) globalroutines(null, 'log', strlog + ' ' + strlog2 + ' ' + strlog3, null)
} }
namespace Actions { namespace Actions {
function json2array(json) {
let result = []
let keys = Object.keys(json)
keys.forEach(function (key) {
result.push(json[key])
})
return result
}
// If something in the call of Service Worker went wrong (Network or Server Down), then retry ! // If something in the call of Service Worker went wrong (Network or Server Down), then retry !
async function sendSwMsgIfAvailable() { async function sendSwMsgIfAvailable() {
let something = false let something = false
@@ -126,13 +350,10 @@ namespace Actions {
// let recclone = [...arr_recmsg] // let recclone = [...arr_recmsg]
if (arr_recmsg.length > 0) { if (arr_recmsg.length > 0) {
// console.log(' TROVATI MSG PENDENTI ! ORA LI MANDO: ', arr_recmsg)
// console.log('---------------------- 2) navigator (2) .serviceWorker.ready') // console.log('---------------------- 2) navigator (2) .serviceWorker.ready')
let promiseChain = Promise.resolve() let promiseChain = Promise.resolve()
for (let rec of arr_recmsg) { for (let indrec in arr_recmsg) {
// console.log(' .... sw.sync.register ( ', rec._id) // console.log(' .... sw.sync.register ( ', rec._id)
// if ('SyncManager' in window) { // if ('SyncManager' in window) {
// sw.sync.register(rec._id) // sw.sync.register(rec._id)
@@ -140,7 +361,7 @@ namespace Actions {
// #Alternative to SyncManager // #Alternative to SyncManager
promiseChain = promiseChain.then(() => { promiseChain = promiseChain.then(() => {
return Api.syncAlternative(rec._id) return Api.syncAlternative(arr_recmsg[indrec]._id)
.then(() => { .then(() => {
something = true something = true
}) })
@@ -180,13 +401,12 @@ namespace Actions {
}) })
} }
}) })
} }
async function waitAndRefreshData(context) { async function waitAndRefreshData(context) {
// await aspettansec(3000) // await aspettansec(3000)
return await dbLoadTodo(context, false) return await dbLoadTodo(context, { checkPending: false })
} }
async function checkPendingMsg(context) { async function checkPendingMsg(context) {
@@ -228,26 +448,27 @@ namespace Actions {
} }
async function dbLoadTodo(context, checkPending: boolean = false) { async function dbLoadTodo(context, { checkPending }) {
console.log('dbLoadTodo', checkPending) console.log('dbLoadTodo', checkPending, 'userid=', UserStore.state.userId)
if (UserStore.state.userId === '') if (UserStore.state.userId === '')
return false // Login not made return false // Login not made
GlobalStore.state.networkDataReceived = false
let ris = await Api.SendReq('/todos/' + UserStore.state.userId, 'GET', null) let ris = await Api.SendReq('/todos/' + UserStore.state.userId, 'GET', null)
.then(res => { .then(res => {
GlobalStore.state.networkDataReceived = true
// console.log('******* UPDATE TODOS.STATE.TODOS !:', res.todos)
if (res.data.todos) { if (res.data.todos) {
state.todos = [...res.data.todos] // console.log('RISULTANTE CATEGORIES DAL SERVER = ', res.data.categories)
Todos.mutations.setTodos_changed() // console.log('RISULTANTE TODOS DAL SERVER = ', res.data.todos)
state.todos = res.data.todos
state.categories = res.data.categories
} else {
state.todos = [[]]
} }
console.log('********** res', 'state.todos', state.todos, 'checkPending', checkPending) // console.log('ARRAY TODOS = ', state.todos)
// After Login will store into the indexedDb...
console.log('dbLoadTodo', 'state.todos', state.todos, 'state.categories', state.categories)
return res return res
}) })
@@ -257,11 +478,8 @@ namespace Actions {
return error return error
}) })
// console.log('ris : ', ris) if (ris.status !== 200) {
// console.log('ris STATUS: ', ris.status) console.log('ris.status', ris.status)
if (!GlobalStore.state.networkDataReceived) {
if (ris.status === serv_constants.RIS_CODE__HTTP_FORBIDDEN_INVALID_TOKEN) { if (ris.status === serv_constants.RIS_CODE__HTTP_FORBIDDEN_INVALID_TOKEN) {
consolelogpao('UNAUTHORIZING... TOKEN EXPIRED... !! ') consolelogpao('UNAUTHORIZING... TOKEN EXPIRED... !! ')
} else { } else {
@@ -272,7 +490,7 @@ namespace Actions {
await updatefromIndexedDbToStateTodo(context) await updatefromIndexedDbToStateTodo(context)
} }
} else { } else {
if (ris.status === rescodes.OK && checkPending) { if (ris.status === tools.OK && checkPending) {
waitAndcheckPendingMsg(context) waitAndcheckPendingMsg(context)
} }
} }
@@ -280,7 +498,7 @@ namespace Actions {
async function updatefromIndexedDbToStateTodo(context) { async function updatefromIndexedDbToStateTodo(context) {
// console.log('Update the array in memory, from todos table from IndexedDb') // console.log('Update the array in memory, from todos table from IndexedDb')
await globalroutines(null, 'updatefromIndexedDbToStateTodo', 'todos', null) await globalroutines(null, 'updatefromIndexedDbToStateTodo', 'categories', null)
.then(() => { .then(() => {
console.log('updatefromIndexedDbToStateTodo! ') console.log('updatefromIndexedDbToStateTodo! ')
return true return true
@@ -298,7 +516,6 @@ namespace Actions {
async function testfunc() { async function testfunc() {
while (true) { while (true) {
consolelogpao('testfunc') consolelogpao('testfunc')
Todos.mutations.setTodos_changed()
// console.log('Todos.state.todos_changed:', Todos.state.todos_changed) // console.log('Todos.state.todos_changed:', Todos.state.todos_changed)
await aspettansec(5000) await aspettansec(5000)
} }
@@ -343,16 +560,16 @@ namespace Actions {
return true return true
} }
async function dbDeleteTodo(context, item: ITodo) { async function dbdeleteItem(context, item: ITodo) {
if (!('serviceWorker' in navigator)) { if (!('serviceWorker' in navigator)) {
// console.log('dbDeleteTodo', item) // console.log('dbdeleteItem', item)
if (UserStore.state.userId === '') if (UserStore.state.userId === '')
return false // Login not made return false // Login not made
let res = await Api.SendReq('/todos/' + item._id, 'DELETE', item) let res = await Api.SendReq('/todos/' + item._id, 'DELETE', item)
.then(res => { .then(res => {
console.log('dbDeleteTodo to the Server') console.log('dbdeleteItem to the Server')
}) })
.catch((error) => { .catch((error) => {
UserStore.mutations.setErrorCatch(error) UserStore.mutations.setErrorCatch(error)
@@ -363,23 +580,274 @@ namespace Actions {
} }
} }
async function getTodosByCategory(context, category: string) { function setmodifiedIfchanged(recOut, recIn, field) {
let myarr = state.todos.filter((p) => { if (String(recOut[field]) !== String(recIn[field])) {
return p.category === category // console.log('*************** CAMPO ', field, 'MODIFICATO!', recOut[field], recIn[field])
recOut.modified = true
recOut[field] = recIn[field]
return true
}
return false
}
async function deleteItem(context, { cat, idobj }) {
console.log('deleteItem: KEY = ', idobj)
let myobjtrov = getElemById(cat, idobj)
if (myobjtrov !== null) {
let myobjnext = getElemPrevById(cat, myobjtrov._id)
if (myobjnext !== null) {
myobjnext.id_prev = myobjtrov.id_prev
myobjnext.modified = true
console.log('calling MODIFY 1')
await modify(context, { myitem: myobjnext, field: 'id_prev' })
}
// 1) Delete from the Todos Array
Todos.mutations.deletemyitem(myobjtrov)
// 2) Delete from the IndexedDb
globalroutines(context, 'delete', 'todos', null, idobj)
.then((ris) => {
}).catch((error) => {
console.log('err: ', error)
}) })
return myarr // 3) Delete from the Server (call)
deleteItemToSyncAndDb(tools.DB.TABLE_DELETE_TODOS, myobjtrov, idobj)
}
// console.log('FINE deleteItem')
}
async function insertTodo(context, { myobj, atfirst }) {
const objtodo = initcat()
objtodo.descr = myobj.descr
objtodo.category = myobj.category
let elemtochange: ITodo = null
if (atfirst) {
console.log('INSERT AT THE TOP')
elemtochange = getFirstList(objtodo.category)
objtodo.id_prev = tools.LIST_START
// objtodo.pos = (elemtochange !== null) ? elemtochange.pos - 1 : 1
} else {
console.log('INSERT AT THE BOTTOM')
// INSERT AT THE BOTTOM , so GET LAST ITEM
const lastelem = getLastListNotCompleted(objtodo.category)
console.log('lastelem', lastelem)
objtodo.id_prev = (lastelem !== null) ? lastelem._id : tools.LIST_START
// objtodo.pos = (elemtochange !== null) ? elemtochange.pos + 1 : 1
}
console.log('elemtochange TORNATO:', elemtochange)
objtodo.modified = false
console.log('objtodo', objtodo, 'ID_PREV=', objtodo.id_prev)
// 1) Create record in Memory
Todos.mutations.createNewItem({ objtodo, atfirst, categorySel: objtodo.category })
// 2) Insert into the IndexedDb
const id = await globalroutines(context, 'write', 'todos', objtodo)
let field = ''
// update also the last elem
if (atfirst) {
if (elemtochange !== null) {
elemtochange.id_prev = id
console.log('elemtochange', elemtochange)
field = 'id_prev'
// Modify the other record
await modify(context, { myitem: elemtochange, field })
}
}
// 3) send to the Server
await saveItemToSyncAndDb(tools.DB.TABLE_SYNC_TODOS, 'POST', objtodo)
.then((ris) => {
// Check if need to be moved...
const indelem = getIndexById(objtodo.category, objtodo._id)
let itemdragend = undefined
if (atfirst) {
// Check the second item, if it's different priority, then move to the first position of the priority
const secondindelem = indelem + 1
const secondelem = getElemByIndex(objtodo.category, secondindelem)
if (secondelem.priority !== objtodo.priority) {
itemdragend = {
field: 'priority',
idelemtochange: objtodo._id,
prioritychosen: objtodo.priority,
category: objtodo.category,
atfirst
}
}
} else {
// get previous of the last
const prevlastindelem = indelem - 1
const prevlastelem = getElemByIndex(objtodo.category, prevlastindelem)
if (prevlastelem.priority !== objtodo.priority) {
itemdragend = {
field: 'priority',
idelemtochange: objtodo._id,
prioritychosen: objtodo.priority,
category: objtodo.category,
atfirst
}
}
}
if (itemdragend)
swapElems(context, itemdragend)
return ris
})
}
async function modify(context, { myitem, field }) {
if (myitem === null)
return new Promise(function (resolve, reject) {
resolve()
})
const myobjsaved = tools.jsonCopy(myitem)
// get record from IndexedDb
const miorec = await globalroutines(context, 'read', 'todos', null, myobjsaved._id)
if (miorec === undefined) {
console.log('~~~~~~~~~~~~~~~~~~~~ !!!!!!!!!!!!!!!!!! Record not Found !!!!!! id=', myobjsaved._id)
return
}
if (setmodifiedIfchanged(miorec, myobjsaved, 'completed'))
miorec.completed_at = new Date().getDate()
fieldtochange.forEach(field => {
setmodifiedIfchanged(miorec, myobjsaved, field)
})
if (miorec.modified) {
// console.log('Todo MODIFICATO! ', miorec.descr, miorec.pos, 'SALVALO SULLA IndexedDB todos')
miorec.modify_at = new Date().getDate()
miorec.modified = false
// 1) Permit to Update the Views
tools.notifyarraychanged(miorec)
// Todos.mutations.modifymyItem(miorec)
// this.logelem('modify', miorec)
// 2) Modify on IndexedDb
return globalroutines(context, 'write', 'todos', miorec)
.then(ris => {
// 3) Modify on the Server (call)
saveItemToSyncAndDb(tools.DB.TABLE_SYNC_TODOS_PATCH, 'PATCH', miorec)
})
}
}
// async function updateModifyRecords(context, cat: string) {
//
// const indcat = getindexbycategory(cat)
// for (const elem of state.todos[indcat]) {
// if (elem.modified) {
// console.log('calling MODIFY 3')
// await modify(context, { myitem: elem, field })
// .then(() => {
// elem.modified = false
// })
// }
// }
// }
//
async function swapElems(context, itemdragend: IDrag) {
// console.log('swapElems', itemdragend)
const cat = itemdragend.category
const indcat = state.categories.indexOf(cat)
if (itemdragend.field === 'priority') {
// get last elem priority
itemdragend.newIndex = getLastFirstElemPriority(itemdragend.category, itemdragend.prioritychosen, itemdragend.atfirst, itemdragend.idelemtochange)
itemdragend.oldIndex = getIndexById(itemdragend.category, itemdragend.idelemtochange)
console.log('swapElems PRIORITY', itemdragend)
}
if (isValidIndex(cat, indcat) && isValidIndex(cat, itemdragend.newIndex) && isValidIndex(cat, itemdragend.oldIndex)) {
state.todos[indcat].splice(itemdragend.newIndex, 0, state.todos[indcat].splice(itemdragend.oldIndex, 1)[0])
tools.notifyarraychanged(state.todos[indcat][itemdragend.newIndex])
tools.notifyarraychanged(state.todos[indcat][itemdragend.oldIndex])
if (itemdragend.field !== 'priority') {
let precind = itemdragend.newIndex - 1
let nextind = itemdragend.newIndex + 1
if (isValidIndex(cat, precind) && isValidIndex(cat, nextind)) {
if ((state.todos[indcat][precind].priority === state.todos[indcat][nextind].priority) && (state.todos[indcat][precind].priority !== state.todos[indcat][itemdragend.newIndex].priority)) {
state.todos[indcat][itemdragend.newIndex].priority = state.todos[indcat][precind].priority
tools.notifyarraychanged(state.todos[indcat][itemdragend.newIndex])
}
} else {
if (!isValidIndex(cat, precind)) {
if ((state.todos[indcat][nextind].priority !== state.todos[indcat][itemdragend.newIndex].priority)) {
state.todos[indcat][itemdragend.newIndex].priority = state.todos[indcat][nextind].priority
tools.notifyarraychanged(state.todos[indcat][itemdragend.newIndex])
}
} else {
if ((state.todos[indcat][precind].priority !== state.todos[indcat][itemdragend.newIndex].priority)) {
state.todos[indcat][itemdragend.newIndex].priority = state.todos[indcat][precind].priority
tools.notifyarraychanged(state.todos[indcat][itemdragend.newIndex])
}
}
}
}
// Update the id_prev property
const elem1 = update_idprev(indcat, itemdragend.newIndex, itemdragend.newIndex - 1)
const elem2 = update_idprev(indcat, itemdragend.newIndex + 1, itemdragend.newIndex)
const elem3 = update_idprev(indcat, itemdragend.oldIndex, itemdragend.oldIndex - 1)
const elem4 = update_idprev(indcat, itemdragend.oldIndex + 1, itemdragend.oldIndex)
// Update the records:
await modify(context, { myitem: elem1, field: 'id_prev' })
await modify(context, { myitem: elem2, field: 'id_prev' })
await modify(context, { myitem: elem3, field: 'id_prev' })
await modify(context, { myitem: elem4, field: 'id_prev' })
}
} }
export const actions = { export const actions = {
dbInsertTodo: b.dispatch(dbInsertTodo), dbInsertTodo: b.dispatch(dbInsertTodo),
dbSaveTodo: b.dispatch(dbSaveTodo), dbSaveTodo: b.dispatch(dbSaveTodo),
dbLoadTodo: b.dispatch(dbLoadTodo), dbLoadTodo: b.dispatch(dbLoadTodo),
dbDeleteTodo: b.dispatch(dbDeleteTodo), dbdeleteItem: b.dispatch(dbdeleteItem),
updatefromIndexedDbToStateTodo: b.dispatch(updatefromIndexedDbToStateTodo), updatefromIndexedDbToStateTodo: b.dispatch(updatefromIndexedDbToStateTodo),
getTodosByCategory: b.dispatch(getTodosByCategory),
checkPendingMsg: b.dispatch(checkPendingMsg), checkPendingMsg: b.dispatch(checkPendingMsg),
waitAndcheckPendingMsg: b.dispatch(waitAndcheckPendingMsg), waitAndcheckPendingMsg: b.dispatch(waitAndcheckPendingMsg),
swapElems: b.dispatch(swapElems),
// updateModifyRecords: b.dispatch(updateModifyRecords),
deleteItem: b.dispatch(deleteItem),
insertTodo: b.dispatch(insertTodo),
modify: b.dispatch(modify)
} }
} }

View File

@@ -5,7 +5,7 @@ import { storeBuilder } from './Store/Store'
import router from '@router' import router from '@router'
import { serv_constants } from '../Modules/serv_constants' import { serv_constants } from '../Modules/serv_constants'
import { rescodes } from '../Modules/rescodes' import { tools } from '../Modules/tools'
import { GlobalStore, UserStore, Todos } from '@store' import { GlobalStore, UserStore, Todos } from '@store'
import globalroutines from './../../globalroutines/index' import globalroutines from './../../globalroutines/index'
@@ -36,6 +36,9 @@ const b = storeBuilder.module<IUserState>('UserModule', state)
const stateGetter = b.state() const stateGetter = b.state()
namespace Getters { namespace Getters {
// const fullName = b.read(function fullName(state): string {
// return state.userInfos.firstname?capitalize(state.userInfos.firstname) + " " + capitalize(state.userInfos.lastname):null;
// })
const lang = b.read(state => { const lang = b.read(state => {
if (state.lang !== '') { if (state.lang !== '') {
@@ -58,7 +61,7 @@ namespace Getters {
// }, 'tok') // }, 'tok')
const isServerError = b.read(state => { const isServerError = b.read(state => {
return (state.servercode === rescodes.ERR_SERVERFETCH) return (state.servercode === tools.ERR_SERVERFETCH)
}, 'isServerError') }, 'isServerError')
const getServerCode = b.read(state => { const getServerCode = b.read(state => {
@@ -78,6 +81,7 @@ namespace Getters {
get getServerCode() { get getServerCode() {
return getServerCode() return getServerCode()
} }
// get fullName() { return fullName();},
} }
@@ -116,7 +120,7 @@ namespace Mutations {
function setlang(state: IUserState, newstr: string) { function setlang(state: IUserState, newstr: string) {
console.log('SETLANG', newstr) console.log('SETLANG', newstr)
state.lang = newstr state.lang = newstr
localStorage.setItem(rescodes.localStorage.lang, state.lang) localStorage.setItem(tools.localStorage.lang, state.lang)
} }
function UpdatePwd(state: IUserState, x_auth_token: string) { function UpdatePwd(state: IUserState, x_auth_token: string) {
@@ -163,7 +167,7 @@ namespace Mutations {
function setErrorCatch(state: IUserState, axerr: Types.AxiosError) { function setErrorCatch(state: IUserState, axerr: Types.AxiosError) {
if (state.servercode !== rescodes.ERR_SERVERFETCH) { if (state.servercode !== tools.ERR_SERVERFETCH) {
state.servercode = axerr.getCode() state.servercode = axerr.getCode()
} }
console.log('Err catch: (servercode:', axerr.getCode(), axerr.getMsgError(), ')') console.log('Err catch: (servercode:', axerr.getCode(), axerr.getMsgError(), ')')
@@ -171,9 +175,9 @@ namespace Mutations {
function getMsgError(state: IUserState, err: number) { function getMsgError(state: IUserState, err: number) {
let msgerrore = '' let msgerrore = ''
if (err !== rescodes.OK) { if (err !== tools.OK) {
msgerrore = 'Error [' + state.servercode + ']: ' msgerrore = 'Error [' + state.servercode + ']: '
if (state.servercode === rescodes.ERR_SERVERFETCH) { if (state.servercode === tools.ERR_SERVERFETCH) {
msgerrore = translate('fetch.errore_server') msgerrore = translate('fetch.errore_server')
} else { } else {
msgerrore = translate('fetch.errore_generico') msgerrore = translate('fetch.errore_generico')
@@ -230,7 +234,7 @@ namespace Actions {
} }
console.log(usertosend) console.log(usertosend)
Mutations.mutations.setServerCode(rescodes.CALLING) Mutations.mutations.setServerCode(tools.CALLING)
return await Api.SendReq('/updatepwd', 'POST', usertosend, true) return await Api.SendReq('/updatepwd', 'POST', usertosend, true)
.then(res => { .then(res => {
@@ -252,7 +256,7 @@ namespace Actions {
} }
console.log(usertosend) console.log(usertosend)
Mutations.mutations.setServerCode(rescodes.CALLING) Mutations.mutations.setServerCode(tools.CALLING)
return await Api.SendReq('/requestnewpwd', 'POST', usertosend) return await Api.SendReq('/requestnewpwd', 'POST', usertosend)
.then(res => { .then(res => {
@@ -272,7 +276,7 @@ namespace Actions {
} }
console.log(usertosend) console.log(usertosend)
Mutations.mutations.setServerCode(rescodes.CALLING) Mutations.mutations.setServerCode(tools.CALLING)
return await Api.SendReq('/vreg', 'POST', usertosend) return await Api.SendReq('/vreg', 'POST', usertosend)
.then(res => { .then(res => {
@@ -280,7 +284,7 @@ namespace Actions {
// mutations.setServerCode(myres); // mutations.setServerCode(myres);
if (res.data.code === serv_constants.RIS_CODE_EMAIL_VERIFIED) { if (res.data.code === serv_constants.RIS_CODE_EMAIL_VERIFIED) {
console.log('VERIFICATO !!') console.log('VERIFICATO !!')
localStorage.setItem(rescodes.localStorage.verified_email, String(true)) localStorage.setItem(tools.localStorage.verified_email, String(true))
} else { } else {
console.log('Risultato di vreg: ', res.data.code) console.log('Risultato di vreg: ', res.data.code)
} }
@@ -312,7 +316,7 @@ namespace Actions {
console.log(usertosend) console.log(usertosend)
Mutations.mutations.setServerCode(rescodes.CALLING) Mutations.mutations.setServerCode(tools.CALLING)
return Api.SendReq('/users', 'POST', usertosend) return Api.SendReq('/users', 'POST', usertosend)
.then(res => { .then(res => {
@@ -340,19 +344,19 @@ namespace Actions {
const now = new Date() const now = new Date()
// const expirationDate = new Date(now.getTime() + myres.data.expiresIn * 1000); // const expirationDate = new Date(now.getTime() + myres.data.expiresIn * 1000);
const expirationDate = new Date(now.getTime() * 1000) const expirationDate = new Date(now.getTime() * 1000)
localStorage.setItem(rescodes.localStorage.lang, state.lang) localStorage.setItem(tools.localStorage.lang, state.lang)
localStorage.setItem(rescodes.localStorage.userId, userId) localStorage.setItem(tools.localStorage.userId, userId)
localStorage.setItem(rescodes.localStorage.username, username) localStorage.setItem(tools.localStorage.username, username)
localStorage.setItem(rescodes.localStorage.token, state.x_auth_token) localStorage.setItem(tools.localStorage.token, state.x_auth_token)
localStorage.setItem(rescodes.localStorage.expirationDate, expirationDate.toString()) localStorage.setItem(tools.localStorage.expirationDate, expirationDate.toString())
localStorage.setItem(rescodes.localStorage.verified_email, String(false)) localStorage.setItem(tools.localStorage.verified_email, String(false))
state.isLogged = true state.isLogged = true
// dispatch('storeUser', authData); // dispatch('storeUser', authData);
// dispatch('setLogoutTimer', myres.data.expiresIn); // dispatch('setLogoutTimer', myres.data.expiresIn);
return rescodes.OK return tools.OK
} else { } else {
return rescodes.ERR_GENERICO return tools.ERR_GENERICO
} }
}) })
.catch((error) => { .catch((error) => {
@@ -405,7 +409,7 @@ namespace Actions {
console.log(usertosend) console.log(usertosend)
Mutations.mutations.setServerCode(rescodes.CALLING) Mutations.mutations.setServerCode(tools.CALLING)
let myres: any let myres: any
@@ -416,7 +420,7 @@ namespace Actions {
myres = res myres = res
if (myres.status !== 200) { if (myres.status !== 200) {
return Promise.reject(rescodes.ERR_GENERICO) return Promise.reject(tools.ERR_GENERICO)
} }
return myres return myres
@@ -440,22 +444,22 @@ namespace Actions {
const now = new Date() const now = new Date()
// const expirationDate = new Date(now.getTime() + myres.data.expiresIn * 1000); // const expirationDate = new Date(now.getTime() + myres.data.expiresIn * 1000);
const expirationDate = new Date(now.getTime() * 1000) const expirationDate = new Date(now.getTime() * 1000)
localStorage.setItem(rescodes.localStorage.lang, state.lang) localStorage.setItem(tools.localStorage.lang, state.lang)
localStorage.setItem(rescodes.localStorage.userId, userId) localStorage.setItem(tools.localStorage.userId, userId)
localStorage.setItem(rescodes.localStorage.username, username) localStorage.setItem(tools.localStorage.username, username)
localStorage.setItem(rescodes.localStorage.token, state.x_auth_token) localStorage.setItem(tools.localStorage.token, state.x_auth_token)
localStorage.setItem(rescodes.localStorage.expirationDate, expirationDate.toString()) localStorage.setItem(tools.localStorage.expirationDate, expirationDate.toString())
localStorage.setItem(rescodes.localStorage.isLogged, String(true)) localStorage.setItem(tools.localStorage.isLogged, String(true))
localStorage.setItem(rescodes.localStorage.verified_email, String(verified_email)) localStorage.setItem(tools.localStorage.verified_email, String(verified_email))
localStorage.setItem(rescodes.localStorage.wasAlreadySubOnDb, String(GlobalStore.state.wasAlreadySubOnDb)) localStorage.setItem(tools.localStorage.wasAlreadySubOnDb, String(GlobalStore.state.wasAlreadySubOnDb))
} }
} }
return rescodes.OK return tools.OK
}).then(code => { }).then(code => {
if (code === rescodes.OK) { if (code === tools.OK) {
return setGlobal(true) return setGlobal(true)
.then(() => { .then(() => {
return code return code
@@ -473,15 +477,15 @@ namespace Actions {
async function logout(context) { async function logout(context) {
console.log('logout') console.log('logout')
localStorage.removeItem(rescodes.localStorage.expirationDate) localStorage.removeItem(tools.localStorage.expirationDate)
localStorage.removeItem(rescodes.localStorage.token) localStorage.removeItem(tools.localStorage.token)
localStorage.removeItem(rescodes.localStorage.userId) localStorage.removeItem(tools.localStorage.userId)
localStorage.removeItem(rescodes.localStorage.username) localStorage.removeItem(tools.localStorage.username)
localStorage.removeItem(rescodes.localStorage.isLogged) localStorage.removeItem(tools.localStorage.isLogged)
// localStorage.removeItem(rescodes.localStorage.leftDrawerOpen) // localStorage.removeItem(rescodes.localStorage.leftDrawerOpen)
localStorage.removeItem(rescodes.localStorage.verified_email) localStorage.removeItem(tools.localStorage.verified_email)
localStorage.removeItem(rescodes.localStorage.categorySel) localStorage.removeItem(tools.localStorage.categorySel)
localStorage.removeItem(rescodes.localStorage.wasAlreadySubOnDb) localStorage.removeItem(tools.localStorage.wasAlreadySubOnDb)
await GlobalStore.actions.clearDataAfterLogout() await GlobalStore.actions.clearDataAfterLogout()
@@ -509,14 +513,14 @@ namespace Actions {
async function setGlobal(loggedWithNetwork: boolean) { async function setGlobal(loggedWithNetwork: boolean) {
state.isLogged = true state.isLogged = true
GlobalStore.mutations.setleftDrawerOpen(localStorage.getItem(rescodes.localStorage.leftDrawerOpen) === 'true') GlobalStore.mutations.setleftDrawerOpen(localStorage.getItem(tools.localStorage.leftDrawerOpen) === 'true')
GlobalStore.mutations.setCategorySel(localStorage.getItem(rescodes.localStorage.categorySel)) GlobalStore.mutations.setCategorySel(localStorage.getItem(tools.localStorage.categorySel))
GlobalStore.actions.checkUpdates() GlobalStore.actions.checkUpdates()
await GlobalStore.actions.loadAfterLogin() await GlobalStore.actions.loadAfterLogin()
.then(() => { .then(() => {
Todos.actions.dbLoadTodo(true) Todos.actions.dbLoadTodo({ checkPending: true })
}) })
} }
@@ -526,24 +530,24 @@ namespace Actions {
// console.log('*** autologin_FromLocalStorage ***') // console.log('*** autologin_FromLocalStorage ***')
// INIT // INIT
UserStore.state.lang = rescodes.getItemLS(rescodes.localStorage.lang) UserStore.state.lang = tools.getItemLS(tools.localStorage.lang)
const token = localStorage.getItem(rescodes.localStorage.token) const token = localStorage.getItem(tools.localStorage.token)
if (!token) { if (!token) {
return false return false
} }
const expirationDateStr = localStorage.getItem(rescodes.localStorage.expirationDate) const expirationDateStr = localStorage.getItem(tools.localStorage.expirationDate)
let expirationDate = new Date(String(expirationDateStr)) let expirationDate = new Date(String(expirationDateStr))
const now = new Date() const now = new Date()
if (now >= expirationDate) { if (now >= expirationDate) {
console.log('!!! Login Expired') console.log('!!! Login Expired')
return false return false
} }
const userId = String(localStorage.getItem(rescodes.localStorage.userId)) const userId = String(localStorage.getItem(tools.localStorage.userId))
const username = String(localStorage.getItem(rescodes.localStorage.username)) const username = String(localStorage.getItem(tools.localStorage.username))
const verified_email = localStorage.getItem(rescodes.localStorage.verified_email) === 'true' const verified_email = localStorage.getItem(tools.localStorage.verified_email) === 'true'
GlobalStore.state.wasAlreadySubOnDb = localStorage.getItem(rescodes.localStorage.wasAlreadySubOnDb) === 'true' GlobalStore.state.wasAlreadySubOnDb = localStorage.getItem(tools.localStorage.wasAlreadySubOnDb) === 'true'
console.log('************* autologin userId', userId) console.log('************* autologin userId', userId)

View File

@@ -1,4 +1,9 @@
export const rescodes = { import { ITodo } from '@src/model'
import globalroutines from './../../globalroutines/index'
import { Todos, UserStore } from '@store'
import Api from '@api'
export const tools = {
EMPTY: 0, EMPTY: 0,
CALLING: 10, CALLING: 10,
OK: 20, OK: 20,
@@ -36,9 +41,9 @@ export const rescodes = {
CMD_SYNC_TODOS: 'sync-todos', CMD_SYNC_TODOS: 'sync-todos',
CMD_SYNC_NEW_TODOS: 'sync-new-todos', CMD_SYNC_NEW_TODOS: 'sync-new-todos',
CMD_DELETE_TODOS: 'sync-delete-todos', CMD_DELETE_TODOS: 'sync-delete-todos',
TABLE_SYNC_TODOS : 'sync_todos', TABLE_SYNC_TODOS: 'sync_todos',
TABLE_SYNC_TODOS_PATCH : 'sync_todos_patch', TABLE_SYNC_TODOS_PATCH: 'sync_todos_patch',
TABLE_DELETE_TODOS : 'delete_todos' TABLE_DELETE_TODOS: 'delete_todos'
}, },
MenuAction: { MenuAction: {
@@ -257,9 +262,77 @@ export const rescodes = {
ris = '' ris = ''
return ris return ris
},
notifyarraychanged(array) {
if (array.length > 0)
array.splice(array.length - 1, 1, array[array.length - 1])
},
existArr(x) {
return x = (typeof x !== 'undefined' && x instanceof Array) ? x : []
},
json2array(json) {
let result = []
let keys = Object.keys(json)
keys.forEach(function (key) {
result.push(json[key])
})
return result
},
async cmdToSyncAndDb(cmd, table, method, item: ITodo, id, msg: String) {
// Send to Server to Sync
console.log('cmdToSyncAndDb', cmd, table, method, item.descr, id, msg)
let cmdSw = cmd
if ((cmd === tools.DB.CMD_SYNC_NEW_TODOS) || (cmd === tools.DB.CMD_DELETE_TODOS)) {
cmdSw = tools.DB.CMD_SYNC_TODOS
}
if ('serviceWorker' in navigator) {
return await navigator.serviceWorker.ready
.then(function (sw) {
// console.log('---------------------- navigator.serviceWorker.ready')
return globalroutines(null, 'write', table, item, id)
.then(function (id) {
// console.log('id', id)
const sep = '|'
let multiparams = cmdSw + sep + table + sep + method + sep + UserStore.state.x_auth_token + sep + UserStore.state.lang
let mymsgkey = {
_id: multiparams,
value: multiparams
}
return globalroutines(null, 'write', 'swmsg', mymsgkey, multiparams)
.then(ris => {
// if ('SyncManager' in window) {
// console.log(' SENDING... sw.sync.register', multiparams)
// return sw.sync.register(multiparams)
// } else {
// #Todo ++ Alternative 2 to SyncManager
return Api.syncAlternative(multiparams)
// }
})
.then(function () {
let data = null
if (msg !== '') {
data = { message: msg, position: 'bottom', timeout: 3000 }
}
return data
})
.catch(function (err) {
console.error('Errore in globalroutines', table, err)
})
})
})
}
} }
} }

24
src/typings/index.d.ts vendored Normal file
View File

@@ -0,0 +1,24 @@
export interface ActionTree<S, R> {
[key: string]: Action<S, R>;
}
export interface GetterTree<S, R> {
[key: string]: Getter<S, R>;
}
export interface MutationTree<S> {
[key: string]: Mutation<S>;
}
export interface ModuleTree<S> {
[key: string]: Module<S>;
}
export interface Module<S, R> {
namespaced?: boolean;
state?: S | (() => S);
getters?: GetterTree<S, R>;
actions?: ActionTree<S, R>;
mutations?: MutationTree<S>;
modules?: ModuleTree<R>;
}

View File

@@ -49,7 +49,7 @@
import {mapActions} from 'vuex' import {mapActions} from 'vuex'
import * as types from '../../store/mutation-types' import * as types from '../../store/mutation-types'
import { rescodes } from '../../../store/Modules/rescodes' import { rescodes } from '../../../store/Modules/tools'
import {serv_constants} from '../../store/Modules/serv_constants' import {serv_constants} from '../../store/Modules/serv_constants'

View File

@@ -1,7 +1,7 @@
import Vue from 'vue' import Vue from 'vue'
import { Component, Prop, Watch } from 'vue-property-decorator' import { Component, Prop, Watch } from 'vue-property-decorator'
import { GlobalStore, UserStore } from '@store' import { GlobalStore, UserStore } from '@store'
import { rescodes } from '../../../store/Modules/rescodes' import { tools } from '../../../store/Modules/tools'
import { serv_constants } from '../../../store/Modules/serv_constants' import { serv_constants } from '../../../store/Modules/serv_constants'
@@ -78,7 +78,7 @@ export default class Signin extends Vue {
checkErrors(riscode) { checkErrors(riscode) {
// console.log('checkErrors: ', riscode) // console.log('checkErrors: ', riscode)
try { try {
if (riscode === rescodes.OK) { if (riscode === tools.OK) {
this.showNotif({ type: 'positive', message: this.$t('login.completato') }) this.showNotif({ type: 'positive', message: this.$t('login.completato') })
this.$router.push('/') this.$router.push('/')
} else if (riscode === serv_constants.RIS_CODE_LOGIN_ERR) { } else if (riscode === serv_constants.RIS_CODE_LOGIN_ERR) {
@@ -97,9 +97,9 @@ export default class Signin extends Vue {
this.$router.push('/signin') this.$router.push('/signin')
}) })
} else if (riscode === rescodes.ERR_SERVERFETCH) { } else if (riscode === tools.ERR_SERVERFETCH) {
this.showNotif(this.$t('fetch.errore_server')) this.showNotif(this.$t('fetch.errore_server'))
} else if (riscode === rescodes.ERR_GENERICO) { } else if (riscode === tools.ERR_GENERICO) {
let msg = this.$t('fetch.errore_generico') + UserStore.mutations.getMsgError(riscode) let msg = this.$t('fetch.errore_generico') + UserStore.mutations.getMsgError(riscode)
this.showNotif(msg) this.showNotif(msg)
} else { } else {
@@ -155,7 +155,7 @@ export default class Signin extends Vue {
UserStore.actions.signin(this.signin) UserStore.actions.signin(this.signin)
.then((riscode) => { .then((riscode) => {
// console.log('signin FINITO CALL: riscode=', riscode) // console.log('signin FINITO CALL: riscode=', riscode)
if (riscode === rescodes.OK) { if (riscode === tools.OK) {
router.push('/signin') router.push('/signin')
} }
return riscode return riscode
@@ -171,7 +171,7 @@ export default class Signin extends Vue {
return riscode return riscode
}) })
.then((riscode) => { .then((riscode) => {
if (riscode === rescodes.OK) { if (riscode === tools.OK) {
GlobalStore.actions.createPushSubscription() GlobalStore.actions.createPushSubscription()
.then(rissub => { .then(rissub => {

View File

@@ -1,7 +1,7 @@
import Vue from 'vue' import Vue from 'vue'
import { Component, Prop, Watch } from 'vue-property-decorator' import { Component, Prop, Watch } from 'vue-property-decorator'
import { UserStore } from '@store' import { UserStore } from '@store'
import { rescodes } from '../../../store/Modules/rescodes' import { tools } from '../../../store/Modules/tools'
import { ISignupOptions, IUserState } from 'model' import { ISignupOptions, IUserState } from 'model'
import { validations, TSignup } from './signup-validate' import { validations, TSignup } from './signup-validate'
@@ -125,16 +125,16 @@ export default class Signup extends Vue {
checkErrors(riscode: number) { checkErrors(riscode: number) {
console.log('checkErrors', riscode) console.log('checkErrors', riscode)
if (riscode === rescodes.DUPLICATE_EMAIL_ID) { if (riscode === tools.DUPLICATE_EMAIL_ID) {
this.showNotif(this.$t('reg.err.duplicate_email')) this.showNotif(this.$t('reg.err.duplicate_email'))
} else if (riscode === rescodes.DUPLICATE_USERNAME_ID) { } else if (riscode === tools.DUPLICATE_USERNAME_ID) {
this.showNotif(this.$t('reg.err.duplicate_username')) this.showNotif(this.$t('reg.err.duplicate_username'))
} else if (riscode === rescodes.ERR_SERVERFETCH) { } else if (riscode === tools.ERR_SERVERFETCH) {
this.showNotif(this.$t('fetch.errore_server')) this.showNotif(this.$t('fetch.errore_server'))
} else if (riscode === rescodes.ERR_GENERICO) { } else if (riscode === tools.ERR_GENERICO) {
let msg = this.$t('fetch.errore_generico') + UserStore.mutations.getMsgError(riscode) let msg = this.$t('fetch.errore_generico') + UserStore.mutations.getMsgError(riscode)
this.showNotif(msg) this.showNotif(msg)
} else if (riscode === rescodes.OK) { } else if (riscode === tools.OK) {
this.$router.push('/signin') this.$router.push('/signin')
this.showNotif({type: 'warning', textColor: 'black', message: this.$t('components.authentication.email_verification.link_sent')}) this.showNotif({type: 'warning', textColor: 'black', message: this.$t('components.authentication.email_verification.link_sent')})
} else { } else {

View File

@@ -60,7 +60,7 @@
import {mapActions} from 'vuex' import {mapActions} from 'vuex'
import * as types from '../../store/mutation-types' import * as types from '../../store/mutation-types'
//import {rescodes} from '../../store/Modules/user' //import {tools} from '../../store/Modules/user'
import {serv_constants} from '../../store/Modules/serv_constants'; import {serv_constants} from '../../store/Modules/serv_constants';

View File

@@ -25,6 +25,10 @@
"paths": { "paths": {
"@src/*": ["./*"], "@src/*": ["./*"],
"@components": ["./components/index.ts"], "@components": ["./components/index.ts"],
"@css/*": ["./assets/css/*"],
"@icons/*": ["./statics/icons/*"],
"@images/*": ["./assets/images/*"],
"@js/*": ["./assets/js/*"],
"@classes": ["./classes/index.ts"], "@classes": ["./classes/index.ts"],
"@utils/*": ["./utils/*"], "@utils/*": ["./utils/*"],
"@validators": ["./utils/validators.ts"], "@validators": ["./utils/validators.ts"],

View File

@@ -12680,7 +12680,7 @@ serve-index@^1.7.2:
serve-static@1.13.2: serve-static@1.13.2:
version "1.13.2" version "1.13.2"
resolved "https://registry.yarnpkg.com/serve-static/-/serve-static-1.13.2.tgz#095e8472fd5b46237db50ce486a43f4b86c6cec1" resolved "https://registry.yarnpkg.com/serve-statics/-/serve-static-1.13.2.tgz#095e8472fd5b46237db50ce486a43f4b86c6cec1"
integrity sha512-p/tdJrO4U387R9oMjb1oj7qSMaMfmOyd4j9hOFoxZe2baQszgHcSWjuya/CiT5kgZZKRudHNOA0pYXOl8rQ5nw== integrity sha512-p/tdJrO4U387R9oMjb1oj7qSMaMfmOyd4j9hOFoxZe2baQszgHcSWjuya/CiT5kgZZKRudHNOA0pYXOl8rQ5nw==
dependencies: dependencies:
encodeurl "~1.0.2" encodeurl "~1.0.2"