continua upgrade Vue 3

This commit is contained in:
Paolo Arena
2021-09-02 03:22:13 +02:00
parent 1d6c55807c
commit 04a9ce2232
31 changed files with 5615 additions and 721 deletions

View File

@@ -32,9 +32,9 @@ module.exports = {
// https://github.com/typescript-eslint/typescript-eslint/tree/master/packages/eslint-plugin#usage // https://github.com/typescript-eslint/typescript-eslint/tree/master/packages/eslint-plugin#usage
// ESLint typescript rules // ESLint typescript rules
// 'plugin:@typescript-eslint/recommended', 'plugin:@typescript-eslint/recommended',
// consider disabling this class of rules if linting takes too long // consider disabling this class of rules if linting takes too long
// 'plugin:@typescript-eslint/recommended-requiring-type-checking', 'plugin:@typescript-eslint/recommended-requiring-type-checking',
// Uncomment any of the lines below to choose desired strictness, // Uncomment any of the lines below to choose desired strictness,
// but leave only one uncommented! // but leave only one uncommented!

View File

@@ -17,38 +17,38 @@
"generate-sw": "workbox generateSW workbox-config.js" "generate-sw": "workbox generateSW workbox-config.js"
}, },
"dependencies": { "dependencies": {
"@quasar/extras": "^1.10.11", "@quasar/extras": "^1.10.12",
"@types/googlemaps": "^3.43.3", "@types/googlemaps": "^3.43.3",
"@types/vuelidate": "^0.7.15", "@types/vuelidate": "^0.7.15",
"@vue/compat": "^3.2.6", "@vue/compat": "^3.2.7",
"@vue/compiler-sfc": "^3.2.6", "@vue/compiler-sfc": "^3.2.7",
"@vue/eslint-config-standard": "^6.1.0", "@vue/eslint-config-standard": "^6.1.0",
"acorn": "^8.4.1", "acorn": "^8.4.1",
"autoprefixer": "^10.3.2", "autoprefixer": "^10.3.3",
"axios": "^0.21.1", "axios": "^0.21.1",
"bcrypt-nodejs": "0.0.3", "bcrypt-nodejs": "0.0.3",
"bcryptjs": "^2.4.3", "bcryptjs": "^2.4.3",
"core-js": "^3.16.2", "core-js": "^3.17.1",
"date-fns": "^2.23.0", "date-fns": "^2.23.0",
"dotenv": "^10.0.0", "dotenv": "^10.0.0",
"element-ui": "^2.15.5", "element-ui": "^2.15.5",
"eslint-plugin-quasar": "^1.0.0", "eslint-plugin-quasar": "^1.0.0",
"graphql": "^15.5.1", "graphql": "^15.5.2",
"graphql-tag": "^2.12.5", "graphql-tag": "^2.12.5",
"gsap": "^3.7.1", "gsap": "^3.7.1",
"jquery": "^3.6.0", "jquery": "^3.6.0",
"js-cookie": "^3.0.0", "js-cookie": "^3.0.1",
"localforage": "^1.10.0", "localforage": "^1.10.0",
"lodash": "^4.17.21", "lodash": "^4.17.21",
"normalize.css": "^8.0.1", "normalize.css": "^8.0.1",
"npm": "^7.21.0", "npm": "^7.21.1",
"nprogress": "^0.2.0", "nprogress": "^0.2.0",
"pinia": "^2.0.0-beta.5", "pinia": "^2.0.0-rc.6",
"prerender-spa-plugin": "^3.4.0", "prerender-spa-plugin": "^3.4.0",
"quasar": "^2.0.4", "quasar": "^2.0.4",
"quasar-extras": "^2.0.9", "quasar-extras": "^2.0.9",
"register-service-worker": "^1.7.2", "register-service-worker": "^1.7.2",
"vee-validate": "^3.4.11", "vee-validate": "^3.4.12",
"vue": "^3.1.0", "vue": "^3.1.0",
"vue-class-component": "^8.0.0-rc.1", "vue-class-component": "^8.0.0-rc.1",
"vue-i18n": "^9.1.7", "vue-i18n": "^9.1.7",
@@ -72,20 +72,20 @@
"@types/dotenv": "^8.2.0", "@types/dotenv": "^8.2.0",
"@types/jest": "^27.0.1", "@types/jest": "^27.0.1",
"@types/js-cookie": "^2.2.7", "@types/js-cookie": "^2.2.7",
"@types/node": "^16.7.1", "@types/node": "^16.7.10",
"@types/nprogress": "^0.2.0", "@types/nprogress": "^0.2.0",
"@typescript-eslint/eslint-plugin": "^4.29.3", "@typescript-eslint/eslint-plugin": "^4.30.0",
"@typescript-eslint/parser": "^4.29.3", "@typescript-eslint/parser": "^4.30.0",
"eslint": "^7.32.0", "eslint": "^7.32.0",
"eslint-config-airbnb-base": "^14.2.1", "eslint-config-airbnb-base": "^14.2.1",
"eslint-config-airbnb-typescript": "^14.0.0", "eslint-config-airbnb-typescript": "^14.0.0",
"eslint-plugin-import": "^2.24.1", "eslint-plugin-import": "^2.24.2",
"eslint-plugin-vue": "^7.16.0", "eslint-plugin-vue": "^7.17.0",
"eslint-webpack-plugin": "^3.0.1", "eslint-webpack-plugin": "^3.0.1",
"file-loader": "^6.2.0", "file-loader": "^6.2.0",
"html-webpack-plugin": "^5.3.2", "html-webpack-plugin": "^5.3.2",
"http-proxy-middleware": "^2.0.1", "http-proxy-middleware": "^2.0.1",
"jest": "^27.0.6", "jest": "^27.1.0",
"json-loader": "^0.5.7", "json-loader": "^0.5.7",
"node-sass": "^6.0.1", "node-sass": "^6.0.1",
"npm-check-updates": "^11.8.3", "npm-check-updates": "^11.8.3",
@@ -98,7 +98,7 @@
"tslint": "^6.1.3", "tslint": "^6.1.3",
"tslint-config-standard": "^9.0.0", "tslint-config-standard": "^9.0.0",
"tslint-loader": "^3.5.4", "tslint-loader": "^3.5.4",
"typescript": "^4.3.5", "typescript": "^4.4.2",
"vue-cli-plugin-element-ui": "^1.1.4", "vue-cli-plugin-element-ui": "^1.1.4",
"vueify": "^9.4.1", "vueify": "^9.4.1",
"workbox-cli": "^6.2.4", "workbox-cli": "^6.2.4",

View File

@@ -1,4 +1,5 @@
import { createI18n } from 'vue-i18n' // @ts-ignore
import { createI18n } from 'vue-i18n/dist/vue-i18n.esm-bundler'
import messages from '../statics/i18n' import messages from '../statics/i18n'
import { boot } from 'quasar/wrappers' import { boot } from 'quasar/wrappers'
// you'll need to create the src/i18n/index.js file too // you'll need to create the src/i18n/index.js file too
@@ -15,9 +16,7 @@ export default ({ app }: { app: any }) => {
export function useI18n() { export function useI18n() {
// eslint-disable-next-line @typescript-eslint/unbound-method // eslint-disable-next-line @typescript-eslint/unbound-method
const { const { t, te, tm, rt, d, n, ...globalApi } = i18n.global;
t, te, tm, rt, d, n, ...globalApi
} = i18n.global;
return { return {
t: t.bind(i18n), t: t.bind(i18n),

View File

@@ -0,0 +1,4 @@
.myflex{
display: flex;
flex: 1;
}

View File

@@ -0,0 +1,62 @@
import { defineComponent, onMounted, ref, watch } from 'vue'
import { useUserStore } from '@store/UserStore'
export default defineComponent({
name: 'CMyAvatar',
props: {
myimg: {
type: String,
required: false,
default: '',
},
size: {
type: String,
required: false,
default: '40px',
},
},
setup(props) {
let myicon = ref('')
let myimgint = ref('')
const userStore = useUserStore()
const imgprofile = ref(userStore.my.profile.img)
function refresh() {
if (!props.myimg) {
myicon.value = 'fas fa-user-circle'
} else {
myimgint.value = props.myimg
}
// console.log('myimgint', this.myimgint)
}
watch(
imgprofile,
// @ts-ignore
(value: string, oldValue: string) => {
userStore.my.profile.img = value
refresh()
},
)
watch(
// @ts-ignore
props.myimg,
// @ts-ignore
(value: string, oldValue: string) => {
myimgint.value = ''
refresh()
},
)
onMounted(refresh)
return {
myimgint,
}
},
})

View File

@@ -0,0 +1,17 @@
<template>
<div>
<q-avatar v-if="!myimgint" class="q-mb-sx center_img" :icon="myicon" :font-size="size">
</q-avatar>
<q-avatar v-if="myimgint" class="q-mb-sx center_img">
<img :src="myimgint" :font-size="size" alt="my avatar">
</q-avatar>
</div>
</template>
<script lang="ts" src="./CMyAvatar.ts">
</script>
<style lang="scss" scoped>
@import './CMyAvatar.scss';
</style>

View File

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

View File

@@ -0,0 +1,18 @@
.card .product-image {
height: 300px;
}
html, body {
margin:0;
padding:0;
height:100%;
}
.text-title {
font-size: 0.9rem;
}
.centeritems{
place-content: center;
}

View File

@@ -0,0 +1,55 @@
import { Component, Prop, Watch } from 'vue-property-decorator'
import { tools } from '../../store/Modules/tools'
import MixinBase from '@src/mixins/mixin-base'
import { CTitleBanner } from '@components'
import { CCardState } from '../CCardState'
import { CCopyBtn } from '../CCopyBtn'
import { IOrder, IProduct } from '@src/model'
import { CSingleCart } from '../../components/CSingleCart'
import MixinUsers from '@src/mixins/mixin-users'
import { computed, defineComponent, ref } from "vue"
import { useGlobalStore } from "@store/globalStore"
@Component({
name: 'CMyCart',
components: { CTitleBanner, CCardState, CCopyBtn, CSingleCart }
})
export default defineComponent({
name: 'CMyCart',
props: {},
setup() {
const globalStore = useGlobalStore()
const myCart = computed(() => Products.cart)
const myTotalPrice = computed(() => {
if (Products.cart) {
return Products.cart.totalPrice
} else {
return 0
}
})
const ordersCart = computed(() => {
if (!!Products.cart) {
return Products.cart.items
} else {
return null
}
})
const numOrders = computed(() => {
if (!!Products.cart) {
return Products.cart.items.length
} else {
return 0
}
})
function closecart() {
globalStore.rightCartOpen = false
}
}

View File

@@ -0,0 +1,46 @@
<template>
<div>
<div id="mycontainer">
<div class="myheader row justify-between">
<div class="col-6">
<q-btn class="q-mx-xs" round dense flat icon="fas fa-shopping-cart">
<q-badge v-if="getnumItemsCart > 0" color="red" floating transparent>
{{ getnumItemsCart }}
</q-badge>
</q-btn>
</div>
<div class="col-6" style="text-align: right">
<span v-if="myTotalPrice" class="text-grey q-mr-xs">Totale:</span> <span
class="text-subtitle1 q-mr-sm "> {{ myTotalPrice.toFixed(2) }}</span>
</div>
</div>
<q-separator></q-separator>
<div id="mybody">
<div v-for="(rec, index) in ordersCart" :key="index" class="col">
<CSingleCart
:order="rec.order"
:showall="false">
</CSingleCart>
</div>
</div>
<div v-if="numOrders === 0" style="text-align: center" class="text-grey">
Il Carrello è Vuoto
</div>
<div v-else style="text-align: center">
<q-btn rounded icon="fas fa-shopping-cart" color="green" label="Vai alla Cassa" class="q-mb-sm" to="/checkout" @click="closecart"></q-btn>
</div>
</div>
</div>
</div>
</template>
<script lang="ts" src="./CMyCart.ts">
</script>
<style lang="scss" scoped>
@import './CMyCart.scss';
</style>

View File

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

View File

@@ -9,20 +9,22 @@ import { shared_consts } from '@src/common/shared_vuejs'
import { useI18n } from '@src/boot/i18n' import { useI18n } from '@src/boot/i18n'
import { boot } from 'quasar/wrappers' import { boot } from 'quasar/wrappers'
import { useRouter } from 'vue-router' import { useRouter } from 'vue-router'
import MixinUsers from '../../mixins/mixin-users'
import { static_data } from '../../db/static_data' import { static_data } from '../../db/static_data'
import messagePopover from '../../layouts/toolbar/messagePopover/messagePopover.vue' import messagePopover from '../../layouts/toolbar/messagePopover/messagePopover.vue'
import drawer from '../../layouts/drawer/drawer.vue' import drawer from '../../layouts/drawer/drawer.vue'
import CMyAvatar from '../../components/CMyAvatar/CMyAvatar'
import { toolsext } from '@store/Modules/toolsext' import { toolsext } from '@store/Modules/toolsext'
import { useGlobalStore } from '@store/globalStore' import { useGlobalStore } from '@store/globalStore'
import { useTestStore } from '@store/testStore' import { useTestStore } from '@store/testStore'
import { useUserStore } from '@store/UserStore' import { useUserStore } from '@store/UserStore'
import MixinUsers from '../../mixins/mixin-users'
export default defineComponent({ export default defineComponent({
name: 'Header', name: 'Header',
mixins: [MixinUsers],
components: { components: {
drawer, messagePopover, // CSigninNoreg, CMyAvatar, CMyCart drawer, messagePopover, CMyAvatar, // CSigninNoreg, CMyCart
}, },
props: { props: {
extraContent: { extraContent: {
@@ -36,7 +38,6 @@ export default defineComponent({
}, },
setup() { setup() {
const store = inject('store')
const $q = useQuasar() const $q = useQuasar()
const { t } = useI18n() const { t } = useI18n()
@@ -59,6 +60,27 @@ export default defineComponent({
const stateconn = ref(globalStore.stateConnection) const stateconn = ref(globalStore.stateConnection)
const {
getUsernameChatByMsg,
getMyUsername,
Username,
myName,
mySurname,
myCell,
Verificato,
MadeGift,
Email,
getMyImg,
getMyImgforIcon,
getImgByMsg,
getUserByUsername,
getImgByUsername,
isValidUsername,
getNumMsg,
getNumMsgUnread,
getMsgText,
paotest } = MixinUsers();
function isonline() { function isonline() {
return globalStore.stateConnection === 'online' return globalStore.stateConnection === 'online'
} }
@@ -82,8 +104,7 @@ export default defineComponent({
} }
function getcolormenu() { function getcolormenu() {
// @ts-ignore return isSocio.value ? 'green-7' : 'white'
return this.isSocio ? 'green-7' : 'white'
} }
function isTutor() { function isTutor() {
@@ -267,7 +288,7 @@ export default defineComponent({
registration.unregister() registration.unregister()
} }
}) })
window.location.reload(true) window.location.reload()
} }
function changeIconConn() { function changeIconConn() {
@@ -432,13 +453,13 @@ export default defineComponent({
onMounted(mounted) onMounted(mounted)
return { return {
store,
static_data, static_data,
globalStore, globalStore,
leftDrawerOpen, leftDrawerOpen,
rightDrawerOpen, rightDrawerOpen,
rightCartOpen, rightCartOpen,
lang, lang,
langshort,
isLogged, isLogged,
isEmailVerified, isEmailVerified,
getnumOrdersCart, getnumOrdersCart,
@@ -453,6 +474,31 @@ export default defineComponent({
imglogo, imglogo,
getappname, getappname,
toggleanimation, toggleanimation,
getClassColorHeader,
getcart,
getnumItemsCart,
isTutor,
isZoomeri,
isTratuttrici,
getUsernameChatByMsg,
getMyUsername,
Username,
myName,
mySurname,
myCell,
Verificato,
MadeGift,
Email,
getMyImg,
getMyImgforIcon,
getImgByMsg,
getUserByUsername,
getImgByUsername,
isValidUsername,
getNumMsg,
getNumMsgUnread,
getMsgText,
paotest,
} }
}, },

View File

@@ -104,13 +104,13 @@
<!-- BUTTON USER BAR --> <!-- BUTTON USER BAR -->
<q-btn <q-btn
class="q-mx-xs" v-if="static_data.functionality.SHOW_USER_MENU && !isLogged" dense flat round class="q-mx-xs" v-if="static_data.functionality.SHOW_USER_MENU && !isLogged()" dense flat round
icon="menu" icon="menu"
@click="rightDrawerOpen = !rightDrawerOpen"> @click="rightDrawerOpen = !rightDrawerOpen">
</q-btn> </q-btn>
<q-btn <q-btn
class="q-mx-xs" v-if="static_data.functionality.ENABLE_ECOMMERCE && isLogged" round dense flat class="q-mx-xs" v-if="static_data.functionality.ENABLE_ECOMMERCE && isLogged()" round dense flat
@click="rightCartOpen = !rightCartOpen" icon="fas fa-shopping-cart"> @click="rightCartOpen = !rightCartOpen" icon="fas fa-shopping-cart">
<q-badge v-if="getnumItemsCart > 0" color="red" floating transparent> <q-badge v-if="getnumItemsCart > 0" color="red" floating transparent>
@@ -123,14 +123,14 @@
round dense flat round dense flat
to="/orderinfo" icon="fas fa-list-ol"> to="/orderinfo" icon="fas fa-list-ol">
<q-badge v-if="getnumOrdersCart > 0" color="blue" floating transparent> <q-badge v-if="getnumOrdersCart() > 0" color="blue" floating transparent>
{{ getnumOrdersCart }} {{ getnumOrdersCart() }}
</q-badge> </q-badge>
</q-btn> </q-btn>
<q-btn <q-btn
class="q-mx-xs" v-if="static_data.functionality.SHOW_USER_MENU && isLogged" round dense flat class="q-mx-xs" v-if="static_data.functionality.SHOW_USER_MENU && isLogged()" round dense flat
@click="rightDrawerOpen = !rightDrawerOpen" :icon="getMyImgforIcon" :color="getcolormenu"> @click="rightDrawerOpen = !rightDrawerOpen" :icon="getMyImgforIcon()" :color="getcolormenu()">
<!--<q-badge v-if="isSocio" color="green" floating transparent> <!--<q-badge v-if="isSocio" color="green" floating transparent>
s s
</q-badge>--> </q-badge>-->
@@ -159,7 +159,7 @@
class="absolute-top-right" style="margin-right: 10px; color: white;" class="absolute-top-right" style="margin-right: 10px; color: white;"
dense flat round icon="close" @click="rightCartOpen = !rightCartOpen"> dense flat round icon="close" @click="rightCartOpen = !rightCartOpen">
</q-btn> </q-btn>
<div v-if="isLogged" class="text-weight-bold text-cart">Carrello <div v-if="isLogged()" class="text-weight-bold text-cart">Carrello
</div> </div>
<CMyCart></CMyCart> <CMyCart></CMyCart>
</q-drawer> </q-drawer>
@@ -180,22 +180,22 @@
dense flat round icon="close" @click="rightDrawerOpen = !rightDrawerOpen"> dense flat round icon="close" @click="rightDrawerOpen = !rightDrawerOpen">
</q-btn> </q-btn>
<div v-if="isLogged" class="text-weight-bold text-user">{{ Username }} - {{ myName }} <div v-if="isLogged()" class="text-weight-bold text-user">{{ Username() }} - {{ myName() }}
</div> </div>
<div class="row justify-evenly q-pa-xs-sm"> <div class="row justify-evenly q-pa-xs-sm">
<div v-if="isLogged && isAdmin" class="text-weight-bold text-user bg-red q-px-xs">Admin</div> <div v-if="isLogged() && isAdmin()" class="text-weight-bold text-user bg-red q-px-xs">Admin</div>
<div v-if="isSocio" class="text-weight-bold text-user q-px-xs">Socio</div> <div v-if="isSocio" class="text-weight-bold text-user q-px-xs">Socio</div>
<div v-if="isSocioResidente" class="text-weight-bold text-user q-px-xs bg-amber">Residente</div> <div v-if="isSocioResidente()" class="text-weight-bold text-user q-px-xs bg-amber">Residente</div>
<div v-if="isConsiglio" class="text-weight-bold text-user q-px-xs bg-deep-orange-10">Consiglio</div> <div v-if="isConsiglio()" class="text-weight-bold text-user q-px-xs bg-deep-orange-10">Consiglio</div>
<div v-if="isManager" class="text-weight-bold text-user bg-blue q-px-xs">Segreteria</div> <div v-if="isManager()" class="text-weight-bold text-user bg-blue q-px-xs">Segreteria</div>
<div v-if="isTutor" class="text-weight-bold text-user q-px-xs">Tutor</div> <div v-if="isTutor()" class="text-weight-bold text-user q-px-xs">Tutor</div>
<div v-if="isTratuttrici" class="text-weight-bold text-user q-px-xs">Editor</div> <div v-if="isTratuttrici()" class="text-weight-bold text-user q-px-xs">Editor</div>
</div> </div>
<div v-if="!isLogged" class="text-user text-italic bg-red"> <div v-if="!isLogged()" class="text-user text-italic bg-red">
{{ t('user.loggati') }} {{ t('user.loggati') }}
</div> </div>
<div v-if="isLogged && !isEmailVerified" class="text-verified">{{ <div v-if="isLogged() && !isEmailVerified()" class="text-verified">{{
t('components.authentication.email_verification.verify_email') t('components.authentication.email_verification.verify_email')
}} }}
</div> </div>
@@ -203,7 +203,7 @@
<!--<span class="text-white" v-if="Verificato"> {{t('reg.verificato')}} </span>--> <!--<span class="text-white" v-if="Verificato"> {{t('reg.verificato')}} </span>-->
<!--<span class="text-white background-red" v-else> {{t('reg.non_verificato')}} </span>--> <!--<span class="text-white background-red" v-else> {{t('reg.non_verificato')}} </span>-->
<div v-if="isLogged" id="user-actions" class="column justify-center q-gutter-sm q-ma-sm center-150"> <div v-if="isLogged()" id="user-actions" class="column justify-center q-gutter-sm q-ma-sm center-150">
<q-btn rounded color="primary" icon="person" to="/profile">{{ t('pages.profile') }}</q-btn> <q-btn rounded color="primary" icon="person" to="/profile">{{ t('pages.profile') }}</q-btn>
<!--<q-btn round color="warning" icon="lock"></q-btn>--> <!--<q-btn round color="warning" icon="lock"></q-btn>-->
<q-btn rounded color="negative" icon="exit_to_app" @click='logoutHandler'>{{ t('login.esci') }}</q-btn> <q-btn rounded color="negative" icon="exit_to_app" @click='logoutHandler'>{{ t('login.esci') }}</q-btn>
@@ -211,7 +211,7 @@
</div> </div>
<div style="margin-top:120px;"></div> <div style="margin-top:120px;"></div>
<div v-show="!isLogged"> <div v-show="!isLogged()">
<div class="q-ma-md" style=""> <div class="q-ma-md" style="">
<CSigninNoreg :showregbutt="true"> <CSigninNoreg :showregbutt="true">
@@ -221,7 +221,7 @@
</div> </div>
</div> </div>
<div v-if="isLogged" class="q-mt-lg"></div> <div v-if="isLogged()" class="q-mt-lg"></div>
<slot></slot> <slot></slot>

View File

@@ -1,5 +1,6 @@
export * from './logo' export * from './logo'
export * from './CMyPage' export * from './CMyPage'
export * from './CMyAvatar'
export * from './CTitle' export * from './CTitle'
export * from './CImgTitle' export * from './CImgTitle'
export * from './BannerCookies' export * from './BannerCookies'

View File

@@ -95,13 +95,14 @@ const msg_website_it = {
hours: 'Ore', hours: 'Ore',
}, },
msg: { msg: {
myAppDescription: '', myAppName: 'FreePlanet',
keywords_base: '', myAppDescription: 'Il primo Vero Social Libero, Equo e Solidale, dove Vive Consapevolezza e Aiuto Comunitario. Gratuito e senza Pubblicità',
underconstruction: 'App in costruzione...',
myDescriz: '', myDescriz: '',
sottoTitoloApp: 'Il primo Vero Social', sottoTitoloApp: 'Il primo Vero Social',
sottoTitoloApp2: '', sottoTitoloApp2: 'Libero, Equo e Solidale',
sottoTitoloApp3: '', sottoTitoloApp3: 'dove Vive Consapevolezza e Aiuto Comunitario',
sottoTitoloApp4: '', sottoTitoloApp4: 'Gratuito e senza Pubblicità',
}, },
homepage: { homepage: {
descrapp_title1: 'Uniti per Evolvere e Sperimentare', descrapp_title1: 'Uniti per Evolvere e Sperimentare',
@@ -111,11 +112,86 @@ const msg_website_it = {
descrapp_pag2: 'E\' giunta l\'ora di utilizzare i nuovi strumenti <strong>Tecnologici</strong> a nostro <strong>favore</strong>, per <strong>Liberarci</strong> ' descrapp_pag2: 'E\' giunta l\'ora di utilizzare i nuovi strumenti <strong>Tecnologici</strong> a nostro <strong>favore</strong>, per <strong>Liberarci</strong> '
+ 'così piano piano dalla <strong>schiavitù</strong> del <strong>"Lavoro per generare Denaro"</strong> e trasformando le nostre <strong>Capacitá</strong> in ' + 'così piano piano dalla <strong>schiavitù</strong> del <strong>"Lavoro per generare Denaro"</strong> e trasformando le nostre <strong>Capacitá</strong> in '
+ '<strong>Risorse Umane</strong> per poterci sostenere e vivere in <strong>Armonia</strong> con gli altri.', + '<strong>Risorse Umane</strong> per poterci sostenere e vivere in <strong>Armonia</strong> con gli altri.',
nostra_missione: 'Nostra Missione', freesocial: {
associazione: '', title: 'Free Social',
tit_come_associarsi: 'Come Associarsi', descr: 'Una Community organizzata per <strong>Categorie</strong>, dove potrai unirti a <strong>Gruppi Tematici</strong>, '
testo_come_associarsi: '', + 'Condividere <strong>Esperienze</strong> e unire Competenze per organizzare e sostenere <strong>Progetti Innovativi</strong> per il Popolo.<br><br>'
titlecontatti: 'CONTATTI', + 'Verranno evidenziati sviluppi <strong>Etici</strong> come l\'<strong>Auto-Produzione</strong>, la <strong>Sostenibilitá</strong>, '
+ 'la Buona <strong>Salute Naturale</strong> e il <strong>Rispetto per l\'Ambiente</strong> e per tutti gli <strong>Esseri Viventi</strong> di questo '
+ '<strong>Pianeta</strong>. Chiunque potrá esprimere il proprio <strong>Consenso o Dissenso</strong> partecipando a <strong>Sondaggi Interattivi</strong>'
+ ' e realizzare insieme i <strong>Cambiamenti</strong> necessari alla nostra Società.',
},
freetalent: {
title: 'Free Talent',
descr: 'Condividi i tuoi <strong>Talenti</strong> e <strong>Abilità</strong>, '
+ 'al posto del denaro guadagnagnerai <strong>Tempo</strong>.<br> '
+ '<strong>"1 ora"</strong> diventa moneta di scambio, uguale per tutti.<br>'
+ 'Potrai utilizzare questi tuoi <strong>"Crediti Tempo"</strong> per soddisfare le tue necessità, cercando nelle <strong>Competenze Disponibili</strong>.<br>'
+ 'Nel Dare e Ricevere, si creeranno così legami di <strong>Amicizia, Solidarietà, Cooperazione e Divertimento</strong><br><br>'
+ 'Questo progetto vuole diffondere, ora in maniera informatizzata, questa realtà che gia esiste da tanti anni, e viene chiamata <strong>"Banca del Tempo"</strong>. '
+ 'Le <strong>segreterie</strong> sparse in tutto il mondo, serviranno a dare maggiore <strong>affidabilità</strong> e <strong>fiducia</strong> negli scambi di talenti tra persone sconosciute. '
+ 'Creeremo così una <strong>rete di fiducia</strong> nel vicinato, come giá viene praticato in numerosi <strong>Ecovillaggi</strong> e Comunità del mondo.',
},
freegas: {
title: 'Free G.A.S.',
descr: 'Ti piacerebbe utilizzare una App che ti permetta facilmente di acquistare Prodotti Locali direttamente dal <strong>Produttore</strong>?<br>'
+ 'Con i <strong>Gruppi di Acquisto Solidale</strong> si evitano intermediazioni inutili, ottenendo parecchi benefici tra cui:<br>'
+ '<ul class="mylist" style="padding-left: 20px;"><li><strong>Qualitá Superiore</strong> del prodotto</li>'
+ '<li>Le <strong>Recensioni</strong> dei consumatori favoriranno i Produttori con Sani Intenti</li>'
+ '<li>Possiblità d\'interagire con il Produttore</li>'
+ '<li>Apertura alle Relazioni tra persone, condividendo <strong>Ricette</strong> e <strong>Consigli</strong> preziosi</li>'
+ '<li><strong>Risparmio</strong> di soldi (prezzi all\'Ingrosso)</li>'
+ '<li>Valorizzare il <strong>Territorio</strong> e l\'Economia <strong>Locale</strong></li>'
+ '<li>Condizioni <strong>Eque</strong> per i Lavoratori</li>'
+ '<li>Ridotto <strong>Impatto Ambientale</strong></ul>',
},
freeliving: {
title: 'Free Co-Living',
descr: 'Unire più realtà, condividendo l\'esperienza di abitare insieme, per un periodo definito:<br>'
+ '1) C\'è chi <strong>Vive solo</strong> ed ha una casa.<br>'
+ '2) Chi ha bisogno di un <strong>alloggio</strong> temporaneo.<br><br>'
+ 'Oggi sempre più persone <strong>abitano da sole</strong> e vorrebbero continuare a vivere nella propria abitazione.<br>'
+ 'Altre persone invece hanno bisogno di una <strong>stanza</strong>, per scelta o per necessita, ed in cambio sono disponibili a '
+ '<strong>contribuire alle spese</strong> per le utenze domestiche o magari <strong>aiutare</strong> la persona a <strong>fare la spesa</strong>, cucinare, <strong>pulire casa</strong> oppure offrendogli semplicemente <strong>compagnia</strong>.<br><br>'
+ 'Tramite questo strumento, le persone potranno trovarsi, mettersi in contatto e decidere in che forma <strong>co-abitare</strong> e per quanto tempo. Le <strong>recensioni</strong> rilasciate ed il <strong>dettaglio</strong> dei profili utenti, '
+ 'aiuterà nella scelta della persona più in <strong>sintonia</strong>.',
},
freecollabora: {
title: 'Chi può Collaborare?',
descr: 'Tutti coloro che sono in linea con <strong>Princìpi Etici</strong> e ricerca del <strong>Benessere Globale del Pianeta</strong><br>'
+ 'Pertanto sono i benvenuti:'
+ '<ul class="mylist" style="padding-left: 20px;">'
+ '<li><strong>Associazioni no-profit, Ecovillaggi, Comunità</strong></li>'
+ '<li>Gruppi che intendono promuovere <strong>Progetti Sociali Innovativi</strong> per una <strong>Decrescita Felice</strong></li>'
+ '<li>Chi gestisce un <strong>Gruppo di Acquisto Solidale (G.A.S.)</strong></li>'
+ '<li><strong>Produttori Locali Etici</strong></li>'
+ '<li>Chi gestisce una <strong>Banca del Tempo</strong></li>'
+ '<li><strong>Chiunque voglia partecipare</strong>, nella forma che ritiene più opportuna.</li>'
+ '</ul>',
},
freesostieni: {
title: 'Come Sostenere il progetto?',
descr: '<ul class="mylist" style="padding-left: 20px;">'
+ '<li><strong>Condividendolo</strong> a tutti coloro che vogliono far parte insieme della crescita e sviluppo di una Nuova Era</li>'
+ '<li>Rispondendo ai <strong>Sondaggi Popolari</strong> e lasciando <strong>Feedback</strong></li>'
+ '<li>Tramite una <strong>donazione</strong> (<strong>anche 1€</strong> ) per le spese.<br>'
+ '</ul>'
+ 'Vedo un <strong>futuro</strong> dove non si utilizzerà più denaro. Dove le persone si <strong>aiuteranno</strong> a vicenda e non avranno bisogno di "possedere" cose, ma le <strong>condivideranno</strong> con gli altri.<br>',
},
multiplatform: {
title: 'Multi-piattaforma',
descr: 'E\' compatibile con Google Chrome, Firefox, Safari, iOS, Android e PC. L\'Applicazione s\'installa facilmente, senza passare dallo store. '
+ 'basta condividere il nome del sito <strong>www.freeplanet.app</strong>.<br>'
+ 'Dopo la registrazione chiederà di aggiungerlo alla lista delle applicazioni e sullo sfondo',
},
free: {
title: 'Gratuita, Open Source e Niente Pubblicità',
descr: 'Questa App <strong>non è in vendita</strong>, non ha scopi commerciali, <strong>non ha prezzo</strong> ed appartiene al <strong>Popolo del Nuovo Mondo</strong>.<br>Chiunque potrá utilizzarla e beneficiarne.<br>A me il compito di gestirla e proteggerla. '
+ 'Verranno accettate solo donazioni Libere di privati ed Associazioni no-profit, in linea con i Principi, che serviranno per coprire le spese.<br>'
+ '<strong>Grazie a Tutti per il sostegno</strong>. ',
},
contacts: 'Contatti',
}, },
}; };

View File

@@ -3,7 +3,7 @@
import { idbKeyval as storage } from '@src/js/storage' import { idbKeyval as storage } from '@src/js/storage'
export default async (context: any, cmd: string, table: string, data: any = null, id = '') => { export default async (cmd: string, table: string, data: any = null, id = '') => {
// const globalStore = useGlobalStore() // const globalStore = useGlobalStore()
// const descr = data !== null ? data.descr : '' // const descr = data !== null ? data.descr : ''

View File

@@ -15,8 +15,6 @@ const namespace = 'MessageModule'
export default defineComponent({ export default defineComponent({
name: 'MessagePopover', name: 'MessagePopover',
mixins: [MixinUsers],
setup(props) { setup(props) {
const $router = useRouter() const $router = useRouter()
// function lasts_messages (state: IUserState) => IMessage[] { // function lasts_messages (state: IUserState) => IMessage[] {

View File

@@ -1,16 +1,9 @@
import { Vue, Options } from 'vue-class-component'
import { defineComponent, ref } from 'vue'
import { IMessage } from '@src/model' import { IMessage } from '@src/model'
import { useUserStore } from '@store/UserStore' import { useUserStore } from '@store/UserStore'
import { useGlobalStore } from '@store/globalStore' import { useGlobalStore } from '@store/globalStore'
import { tools } from '../store/Modules/tools'
import { func_tools } from '../store/Modules/toolsext'
// You can declare a mixin as the same style as components. // You can declare a mixin as the same style as components.
export default defineComponent({ export default function () {
name: 'MixinUsers',
setup(props) {
function getUserByUsername(username: string) { function getUserByUsername(username: string) {
const userStore = useUserStore() const userStore = useUserStore()
return userStore.getNameSurnameByUsername(username) return userStore.getNameSurnameByUsername(username)
@@ -110,6 +103,10 @@ export default defineComponent({
return userStore.my.verified_email return userStore.my.verified_email
} }
function paotest() {
return 'Ciaoooooooooooooooo!'
}
function MadeGift() { function MadeGift() {
const userStore = useUserStore() const userStore = useUserStore()
return userStore.my.made_gift return userStore.my.made_gift
@@ -148,6 +145,23 @@ export default defineComponent({
return { return {
getUsernameChatByMsg, getUsernameChatByMsg,
getMyUsername, getMyUsername,
Username,
myName,
mySurname,
myCell,
Verificato,
MadeGift,
Email,
getMyImg,
getMyImgforIcon,
getImgByMsg,
getnumItemsCart,
getUserByUsername,
getImgByUsername,
isValidUsername,
getNumMsg,
getNumMsgUnread,
getMsgText,
paotest,
}
} }
},
})

View File

@@ -3,8 +3,8 @@ export interface IProduct {
active?: boolean active?: boolean
idProducer?: string, idProducer?: string,
idStorehouses?: string[], idStorehouses?: string[],
producer?: IProducer, producer: IProducer,
storehouses?: IStorehouse[], storehouses: IStorehouse[],
code?: string, code?: string,
name?: string, name?: string,
description?: string, description?: string,
@@ -25,7 +25,7 @@ export interface IProduct {
} }
export interface IBaseOrder { export interface IBaseOrder {
order?: IOrder order: IOrder
} }
export interface IOrder { export interface IOrder {

View File

@@ -50,7 +50,7 @@ export interface IDrag {
export interface ITodosState { export interface ITodosState {
showtype: number showtype: number
todos: {} todos: any
categories: string[] categories: string[]
// todos_changed: number // todos_changed: number
reload_fromServer: number reload_fromServer: number

View File

@@ -50,7 +50,7 @@
<br> <br>
</div> </div>
<div v-else> <div v-else>
<div v-if="!isLogged" style="margin: 5px; padding: 5px;" class="home"> <div v-if="!isLogged()" style="margin: 5px; padding: 5px;" class="home">
<q-btn <q-btn
rounded size="lg" color="primary" @click="PagLogin" rounded size="lg" color="primary" @click="PagLogin"
class="btn-start"> class="btn-start">
@@ -64,7 +64,7 @@
</div> </div>
</div> </div>
<div v-if="isLogged"> <div v-if="isLogged()">
<div> <div>
<!--<q-field--> <!--<q-field-->
<!--v-if="getPermission() === 'granted'"--> <!--v-if="getPermission() === 'granted'"-->
@@ -141,7 +141,7 @@
<br> <br>
</div> </div>
<div v-else> <div v-else>
<div v-if="!isLogged" style="margin: 5px; padding: 5px;" class="home"> <div v-if="!isLogged()" style="margin: 5px; padding: 5px;" class="home">
<q-btn <q-btn
rounded size="lg" color="primary" @click="PagLogin" rounded size="lg" color="primary" @click="PagLogin"
class="btn-start"> class="btn-start">
@@ -155,7 +155,7 @@
</div> </div>
</div> </div>
<div v-if="isLogged"> <div v-if="isLogged()">
<div> <div>
<!--<q-field--> <!--<q-field-->
<!--v-if="getPermission() === 'granted'"--> <!--v-if="getPermission() === 'granted'"-->
@@ -236,7 +236,7 @@
<br> <br>
</div> </div>
<div v-else> <div v-else>
<div v-if="!isLogged" style="margin: 5px; padding: 5px;" class="home"> <div v-if="!isLogged()" style="margin: 5px; padding: 5px;" class="home">
<q-btn <q-btn
rounded size="lg" color="primary" @click="PagLogin" rounded size="lg" color="primary" @click="PagLogin"
class="btn-start"> class="btn-start">
@@ -250,7 +250,7 @@
</div> </div>
</div> </div>
<div v-if="isLogged"> <div v-if="isLogged()">
<div> <div>
<!--<q-field--> <!--<q-field-->
<!--v-if="getPermission() === 'granted'"--> <!--v-if="getPermission() === 'granted'"-->
@@ -392,10 +392,10 @@
<section class="landing__footer"> <section class="landing__footer">
<div class="text-center"> <div class="text-center">
<div class="landing__footer-icons row flex-center"> <div class="landing__footer-icons row flex-center">
<a :href="FBPage" target="_blank"> <a :href="FBPage()" target="_blank">
<i aria-hidden="true" class="q-icon fab fa-facebook-f icon_contact"> </i></a> <i aria-hidden="true" class="q-icon fab fa-facebook-f icon_contact"> </i></a>
<a :href="TelegramSupport" target="_blank"> <a :href="TelegramSupport()" target="_blank">
<i aria-hidden="true" class="q-icon fab fa-telegram icon_contact"></i></a> <i aria-hidden="true" class="q-icon fab fa-telegram icon_contact"></i></a>
<!--<a href="" target="_blank"><i aria-hidden="true" class="q-icon fab fa-github"> </i></a>--> <!--<a href="" target="_blank"><i aria-hidden="true" class="q-icon fab fa-github"> </i></a>-->

View File

@@ -1,6 +1,5 @@
import axios, { AxiosInstance, AxiosResponse } from 'axios' import axios, { AxiosInstance, AxiosResponse } from 'axios'
// import LoginModule from '../Modules/Auth/LoginStore' // import LoginModule from '../Modules/Auth/LoginStore'
import router from '@router'
import { tools } from '@src/store/Modules/tools' import { tools } from '@src/store/Modules/tools'
import { toolsext } from '@src/store/Modules/toolsext' import { toolsext } from '@src/store/Modules/toolsext'
import { serv_constants } from '@src/store/Modules/serv_constants' import { serv_constants } from '@src/store/Modules/serv_constants'
@@ -122,7 +121,7 @@ async function Request(type: string, path: string, payload: any): Promise<Types.
ricevuto = true ricevuto = true
return new Types.AxiosSuccess(response.data, response.status) return new Types.AxiosSuccess(response.data, response.status)
} }
} catch (error) { } catch (error: any) {
setTimeout(() => { setTimeout(() => {
globalStore.connData.uploading_server = (globalStore.connData.uploading_server === 1) ? -1 : globalStore.connData.uploading_server globalStore.connData.uploading_server = (globalStore.connData.uploading_server === 1) ? -1 : globalStore.connData.uploading_server
globalStore.connData.downloading_server = (globalStore.connData.downloading_server === 1) ? -1 : globalStore.connData.downloading_server globalStore.connData.downloading_server = (globalStore.connData.downloading_server === 1) ? -1 : globalStore.connData.downloading_server

173
src/store/MessageStore.ts Executable file
View File

@@ -0,0 +1,173 @@
import Api from '@api'
import { storeBuilder } from './Store/Store'
import { serv_constants } from '../Modules/serv_constants'
import { toolsext } from '@src/store/Modules/toolsext'
import { GlobalStore, UserStore, Todos, Projects, CalendarStore } from '@store'
import { IMessage, IMessageState, StatusMessage } from '../../model'
import { tools } from '@src/store/Modules/tools'
import { MsgDefault } from '@src/model'
import { shared_consts } from '@src/common/shared_vuejs'
// State
const state: IMessageState = {
last_msgs: [],
users_msg: []
// last_update: []
}
const b = storeBuilder.module<IMessageState>('MessageModule', state)
namespace Getters {
const getlasts_messages = b.read((mystate: IMessageState) => (): IMessage[] => {
const ctrec = (mystate.last_msgs) ? mystate.last_msgs.slice(0, 5) : []
// const ctrec = (mystate.msgs) ? mystate.msgs.slice().reverse().slice(0, 5) : []
return (ctrec)
}, 'getlasts_messages')
const getnumMsgUnread = b.read((mystate: IMessageState) => () => {
return mystate.last_msgs.filter((msg) => !msg.read).length
}, 'getnumMsgUnread')
export const getters = {
get getlasts_messages() {
return getlasts_messages()
},
get getnumMsgUnread() {
return getnumMsgUnread()
}
}
}
namespace Mutations {
export const mutations = {
}
}
function setMsg(arrmsg: IMessage[], username) {
// console.log('arrmsg', arrmsg)
if (arrmsg.length > 0) {
let users_msg = state.users_msg.find((rec) => rec.username === username)
if (!users_msg) {
state.users_msg.push({ username, msgs: [] })
users_msg = state.users_msg.find((rec) => rec.username === username)
}
users_msg.msgs.push(...arrmsg)
// console.table(users_msg.msgs)
// users_msg.msgs = tools.getUnique(users_msg.msgs, '_id')
// console.table(users_msg.msgs)
if (users_msg.msgs) {
let userother = users_msg.msgs.slice(-1)[0].dest.username
if (userother === UserStore.state.my.username)
userother = users_msg.msgs.slice(-1)[0].origin.username
let index = state.last_msgs.findIndex((rec) => (rec.dest.username === userother) || (rec.origin.username === userother))
if (index >= 0) {
// Update last message
state.last_msgs[index] = users_msg.msgs.slice(-1)[0]
} else {
state.last_msgs.push(users_msg.msgs.slice(-1)[0])
index = state.last_msgs.findIndex((rec) => (rec.dest.username === userother) || (rec.origin.username === userother))
}
if (state.last_msgs[index])
users_msg.lastdataread = state.last_msgs[index].datemsg
else
users_msg.lastdataread = tools.getLastDateReadReset()
} else {
users_msg.lastdataread = tools.getLastDateReadReset()
}
// console.log('RICeVUTO', arrmsg, 'lastdataread', users_msg.lastdataread)
// console.log('state.users_msg', users_msg)
}
}
namespace Actions {
async function updateMsgDataFromServer(context, { username, lastdataread } ) {
// console.log('updateMsgDataFromServer', username, lastdataread)
return await Api.SendReq(`/sendmsg/${username}/${lastdataread}/${process.env.APP_ID}`, 'GET', null)
.then((res) => {
// console.log('res', res)
if (res.status === 200) {
setMsg(res.data.arrmsg, username)
return true
}
return false
})
.catch((error) => {
console.error(error)
return false
})
}
async function SendMsgEvent(context, msg: IMessage) {
console.log('SendMsgEvent', msg)
const data: IMessage = { ...MsgDefault, ...msg}
data.source.page = ''
data.idapp = process.env.APP_ID
data.origin.idapp = process.env.APP_ID
data.origin.username = UserStore.state.my.username
data.datemsg = tools.getDateNow()
data.status = StatusMessage.WaitingToSend
// Options
data.options = tools.SetBit(data.options, shared_consts.MessageOptions.Notify_ByEmail)
data.options = tools.SetBit(data.options, shared_consts.MessageOptions.Notify_ByPushNotification)
// console.log('DOPO:')
// console.table(data)
return await Api.SendReq('/sendmsg', 'POST', data)
.then((res) => {
// console.log('res', res)
if (res.status === 200) {
if (res.data.code === serv_constants.RIS_CODE_OK) {
data._id = res.data.id
const myarr = []
myarr.push(data)
setMsg(myarr, data.dest.username)
return true
}
}
return false
})
.catch((error) => {
console.error(error)
return false
})
}
export const actions = {
updateMsgDataFromServer: b.dispatch(updateMsgDataFromServer),
SendMsgEvent: b.dispatch(SendMsgEvent)
}
}
const stateGetter = b.state()
// Module
const MessageModule = {
get state() {
return stateGetter()
},
actions: Actions.actions,
getters: Getters.getters,
mutations: Mutations.mutations
}
export default MessageModule

File diff suppressed because it is too large Load Diff

382
src/store/Products.ts Executable file
View File

@@ -0,0 +1,382 @@
import { IBaseOrder, ICart, IOrder, IOrderCart, IProduct, IProductsState } from 'model'
import Api from '@api'
import { serv_constants } from '@src/store/Modules/serv_constants'
import * as Types from '@src/store/Api/ApiTypes'
import { static_data } from '@src/db/static_data'
import { shared_consts } from '@src/common/shared_vuejs'
import { tools } from "@store/Modules/tools"
import { defineStore } from "pinia"
import { useUserStore } from '@store/UserStore'
import { toolsext } from "@store/Modules/toolsext"
export const useProducts = defineStore('Products', {
state: (): IProductsState => ({
products: [],
cart: { items: [], totalPrice: 0, totalQty: 0, userId: '' },
orders: []
}),
getters: {
getProducts: (state: IProductsState) => (): IProduct[] => {
return state.products
},
getCart: (state: IProductsState) => (): ICart => {
return state.cart
},
getOrdersAllCart: (state: IProductsState) => (): IOrderCart[] => {
return state.orders
},
getOrdersCart: (state: IProductsState) => (tipoord: string): IOrderCart[] | undefined => {
console.log('state.orders', state.orders)
if (tipoord === 'incorso')
return state.orders.filter((rec: IOrderCart) => (rec.status ? rec.status : 0) <= shared_consts.OrderStatus.CHECKOUT_SENT)
else if (tipoord === 'confermati')
return state.orders.filter((rec: IOrderCart) => rec.status === shared_consts.OrderStatus.ORDER_CONFIRMED)
else if (tipoord === 'pagati')
return state.orders.filter((rec: IOrderCart) => rec.status === shared_consts.OrderStatus.PAYED)
else if (tipoord === 'completati')
return state.orders.filter((rec: IOrderCart) => rec.status === shared_consts.OrderStatus.RECEIVED)
else if (tipoord === 'cancellati')
return state.orders.filter((rec: IOrderCart) => rec.status === shared_consts.OrderStatus.CANCELED)
},
existProductInCart: (state: IProductsState) => (idproduct: string): boolean => {
// console.log('.cart.items', this.cart.items)
if (state.cart.items) {
const ris = state.cart.items.filter((item: IBaseOrder) => item.order.idProduct === idproduct).reduce((sum, rec) => sum + 1, 0)
return ris > 0
}
return false
},
getRecordEmpty: (state: IProductsState) => (): IProduct => {
const tomorrow = tools.getDateNow()
tomorrow.setDate(tomorrow.getDate() + 1)
return {
// _id: tools.getDateNow().toISOString(), // Create NEW
active: false,
idProducer: '',
idStorehouses: [],
producer: {},
storehouses: [],
code: '',
name: '',
description: '',
department: '',
category: '',
price: 0.0,
color: '',
size: '',
quantityAvailable: 0,
canBeShipped: false,
canBeBuyOnline: false,
weight: 0,
stars: 0,
date: tools.getDateNow(),
icon: '',
img: ''
}
}
},
actions: {
getProductsByCategory(category: string): any[] {
return this.products.filter((rec) => rec.category === category)
},
createOrderByProduct(product: IProduct, order: IOrder): IOrder {
const userStore = useUserStore()
const myorder: IOrder = {
userId: userStore.my._id,
idapp: process.env.APP_ID,
idProduct: product._id,
idProducer: product.idProducer,
status: shared_consts.OrderStatus.IN_CART,
price: product.price,
after_price: product.after_price,
color: product.color,
size: product.size,
weight: product.weight,
quantity: order.quantity,
idStorehouse: order.idStorehouse
}
if (product.storehouses.length === 1) {
order.idStorehouse = product.storehouses[0]._id
}
return myorder
},
initcat() {
// rec.userId = userStore.my._id
return this.getRecordEmpty()
},
async loadProducts() {
const userStore = useUserStore()
console.log('loadProducts')
if (!static_data.functionality.ENABLE_ECOMMERCE)
return null
console.log('getProducts', 'userid=', userStore.my._id)
// if (userStore.my._id === '') {
// return new Types.AxiosError(0, null, 0, '')
// }
let ris = null
ris = await Api.SendReq('/products', 'POST', null)
.then((res) => {
if (res.data.products) { // console.log('RISULTANTE CATEGORIES DAL SERVER = ', res.data.categories)
this.products = res.data.products
} else {
this.products = []
}
// console.log('ARRAY PRODUCTS = ', this.products)
if (process.env.DEBUG === '1') {
// console.log('dbLoad', 'this.products', this.products)
}
return res
})
.catch((error) => {
console.log('error getProducts', error)
userStore.setErrorCatch(error)
return new Types.AxiosError(serv_constants.RIS_CODE_ERR, null, toolsext.ERR_GENERICO, error)
})
// ApiTables.aftercalling(ris, checkPending, 'categories')
return ris
},
async loadProduct({ code }: {code: any}) {
console.log('loadProduct', code)
const userStore = useUserStore()
if (!static_data.functionality.ENABLE_ECOMMERCE)
return null
console.log('getProduct', 'code', code)
// if (userStore.my._id === '') {
// return new Types.AxiosError(0, null, 0, '')
// }
let ris = null
ris = await Api.SendReq('/products/' + code, 'POST', { code })
.then((res) => {
console.log('product', res.data.product)
if (res.data.product) { // console.log('RISULTANTE CATEGORIES DAL SERVER = ', res.data.categories)
return res.data.product
} else {
return null
}
})
.catch((error) => {
console.log('error getProduct', error)
userStore.setErrorCatch(error)
return new Types.AxiosError(serv_constants.RIS_CODE_ERR, null, toolsext.ERR_GENERICO, error)
})
return ris
},
async loadOrders() {
console.log('loadOrders')
const userStore = useUserStore()
if (!static_data.functionality.ENABLE_ECOMMERCE)
return null
console.log('loadOrders', 'userid=', userStore.my._id)
// if (userStore.my._id === '') {
// return new Types.AxiosError(0, null, 0, '')
// }
let ris = null
ris = await Api.SendReq('/cart/' + userStore.my._id, 'GET', null)
.then((res) => {
if (res.data.cart) { // console.log('RISULTANTE CATEGORIES DAL SERVER = ', res.data.categories)
this.cart = res.data.cart
} else {
this.cart = { items: [], totalPrice: 0, totalQty: 0, userId: '' }
}
return res
})
.catch((error) => {
console.log('error loadOrders', error)
userStore.setErrorCatch(error)
return new Types.AxiosError(serv_constants.RIS_CODE_ERR, null, toolsext.ERR_GENERICO, error)
})
// ApiTables.aftercalling(ris, checkPending, 'categories')
return ris
},
async removeFromCart({ order }: {order: IOrder}) {
const userStore = useUserStore()
return await Api.SendReq('/cart/' + userStore.my._id, 'DELETE', { orderId: order._id })
.then((res) => {
if (res.data.cart) { // console.log('RISULTANTE CATEGORIES DAL SERVER = ', res.data.categories)
this.cart = res.data.cart
} else {
this.cart = { items: [], totalPrice: 0, totalQty: 0, userId: '' }
}
return res
})
},
async addToCart({ product, order }: {product: IProduct, order: IOrder}) {
const userStore = useUserStore()
if (!static_data.functionality.ENABLE_ECOMMERCE)
return null
const neworder = this.createOrderByProduct(product, order)
if (!neworder.idStorehouse)
return new Types.AxiosError(serv_constants.RIS_CODE_ERR, null, toolsext.ERR_GENERICO, 'Nessuno Store')
console.log('addToCart', 'userid=', userStore.my._id, neworder)
let ris = null
ris = await Api.SendReq('/cart/' + userStore.my._id, 'POST', { order: neworder })
.then((res) => {
if (res.data.cart) { // console.log('RISULTANTE CATEGORIES DAL SERVER = ', res.data.categories)
this.cart = res.data.cart
} else {
this.cart = { items: [], totalPrice: 0, totalQty: 0, userId: '' }
}
return res
})
.catch((error) => {
console.log('error addToCart', error)
userStore.setErrorCatch(error)
return new Types.AxiosError(serv_constants.RIS_CODE_ERR, null, toolsext.ERR_GENERICO, error)
})
// ApiTables.aftercalling(ris, checkPending, 'categories')
return ris
},
async addSubQtyToItem({ addqty, subqty, order } : { addqty: number, subqty: number, order: IOrder}) {
const userStore = useUserStore()
if (!static_data.functionality.ENABLE_ECOMMERCE)
return null
// console.log('addSubQtyToItem', 'userid=', userStore.my._id, order)
let ris = null
ris = await Api.SendReq('/cart/' + userStore.my._id, 'POST', { addqty, subqty, order })
.then((res) => {
this.cart = res.data.cart
if (!!res.data.qty) {
// const ind = this.cart.items.findIndex((rec) => rec.order._id === order._id)
// this.cart.items[ind].order.quantity = res.data.qty
return res.data.qty
}
return 0
})
.catch((error) => {
console.log('error addSubQtyToItem', error)
userStore.setErrorCatch(error)
return new Types.AxiosError(serv_constants.RIS_CODE_ERR, null, toolsext.ERR_GENERICO, error)
})
// ApiTables.aftercalling(ris, checkPending, 'categories')
return ris
},
async UpdateStatusCart({ cart_id, status }: { cart_id:string, status: number }) {
const userStore = useUserStore()
if (!static_data.functionality.ENABLE_ECOMMERCE)
return null
// console.log('addSubQtyToItem', 'userid=', userStore.my._id, order)
let ris = null
ris = await Api.SendReq('/cart/' + userStore.my._id + '/cartstatus', 'POST', { cart_id, status })
.then((res) => {
if (res.data.status === shared_consts.OrderStatus.CHECKOUT_SENT) {
this.cart = {}
if (res.data.orders)
this.orders = res.data.orders
}
return res.data.status
})
.catch((error) => {
console.log('error UpdateStatusCart', error)
userStore.setErrorCatch(error)
return new Types.AxiosError(serv_constants.RIS_CODE_ERR, null, toolsext.ERR_GENERICO, error)
})
return ris
},
async UpdateOrderStatus({ order_id, status }: { order_id: string, status: number }) {
const userStore = useUserStore()
if (!static_data.functionality.ENABLE_ECOMMERCE)
return null
// console.log('addSubQtyToItem', 'userid=', userStore.my._id, order)
let ris = null
ris = await Api.SendReq('/cart/' + userStore.my._id + '/orderstatus', 'POST', { order_id, status })
.then((res) => {
return res.data.status
})
.catch((error) => {
console.log('error UpdateOrderStatus', error)
userStore.setErrorCatch(error)
return new Types.AxiosError(serv_constants.RIS_CODE_ERR, null, toolsext.ERR_GENERICO, error)
})
return ris
},
}
})

558
src/store/Projects.ts Executable file
View File

@@ -0,0 +1,558 @@
import { IProject, IProjectsState, IDrag, IMenuList, IAction } from 'model'
import { Privacy, TipoVisu } from '@src/model'
import Api from '@api'
import { tools } from './Modules/tools'
import { toolsext } from '@src/store/Modules/toolsext'
import { lists } from './Modules/lists'
import * as ApiTables from './Modules/ApiTables'
import globalroutines from './../globalroutines/index'
import objectId from '@src/js/objectId'
import { costanti } from '@src/store/Modules/costanti'
import { RouteNames } from '@src/router/route-names'
import * as Types from '@src/store/Api/ApiTypes'
import { serv_constants } from '@src/store/Modules/serv_constants'
import { static_data } from '@src/db/static_data'
import { defineStore } from "pinia"
import { useUserStore } from "@store/UserStore"
import { useGlobalStore } from "@store/globalStore"
const nametable = 'projects'
// import _ from 'lodash'
const listFieldsToChange: string [] = ['descr', 'respUsername', 'viceRespUsername', 'vice2RespUsername', 'longdescr', 'hoursplanned', 'hoursleft', 'hoursworked', 'id_parent', 'statusproj',
'category', 'expiring_at', 'priority', 'pos', 'groupId', 'enableExpiring', 'progressCalc', 'live_url', 'test_url',
'begin_development', 'begin_test', 'actualphase', 'totalphases', 'hoursweeky_plannedtowork', 'endwork_estimate',
'privacyread', 'privacywrite', 'tipovisu', 'id_main_project', 'typeproj', 'favourite', 'themecolor', 'themebgcolor', 'view']
const listFieldsUpdateCalculation: string [] = ['hoursplanned', 'hoursleft', 'hoursworked', 'progressCalc', 'endwork_estimate']
export const useProjectStore = defineStore('Projects', {
state: (): IProjectsState => ({
showtype: costanti.ShowTypeTask.SHOW_LAST_N_COMPLETED,
projects: [],
insidePending: false,
visuLastCompleted: 10
}),
getters: {
getRecordEmpty: (state: IProjectsState) => (): IProject => {
// const tomorrow = tools.getDateNow()
// tomorrow.setDate(tomorrow.getDate() + 1)
const obj: IProject = {
_id: objectId(),
descr: '',
longdescr: '',
typeproj: 0,
id_parent: '',
id_main_project: '',
priority: tools.Priority.PRIORITY_NORMAL,
statusproj: tools.Status.OPENED,
created_at: tools.getDateNow(),
modify_at: tools.getDateNow(),
completed_at: tools.getDateNull(),
category: '',
// expiring_at: tomorrow,
enableExpiring: false,
pos: 0,
modified: false,
live_url: '',
test_url: '',
totalphases: 1,
actualphase: 1,
hoursworked: 0,
hoursplanned: 0,
hoursleft: 0,
progressCalc: 0,
privacyread: 'inherited',
privacywrite: 'inherited',
begin_development: tools.getDateNull(),
begin_test: tools.getDateNull(),
hoursweeky_plannedtowork: 0,
endwork_estimate: tools.getDateNull(),
themecolor: '',
themebgcolor: '',
groupId: '',
respUsername: '',
viceRespUsername: '',
vice2RespUsername: '',
tipovisu: 0
}
return obj
},
projs_dacompletare: (state: IProjectsState) => (id_parent: string, tipoproj: string): IProject[] => {
// console.log('projs_dacompletare')
if (state.projects) {
// console.log('projs_dacompletare', state.projects)
// @ts-ignore
return this.getproj(state.projects, id_parent, tipoproj)
} else {
return []
}
},
listaprojects: (state: IProjectsState) => (tipoproj: string): IMenuList[] => {
if (state.projects) {
console.log('listaprojects')
// @ts-ignore
const listaproj = this.getproj(state.projects, process.env.PROJECT_ID_MAIN, tipoproj)
const myarr: IMenuList[] = []
for (const proj of listaproj) {
myarr.push({ nametranslate: '', description: proj.descr, idelem: proj._id })
}
console.log(' myarr', myarr, listaproj)
return myarr
} else {
return []
}
},
listagerarchia: (state: IProjectsState) => (tipoproj: string, idparent: string): IMenuList[] => {
if (state.projects) {
// console.log('listagerarchia', idparent)
const myarrgerarchia: IMenuList[] = []
let myidparent = idparent
let precmyparent = '-1'
while (state.projects && myidparent) {
const proj = state.projects.find((rec) => rec._id === myidparent)
if (proj) {
myarrgerarchia.push({ nametranslate: '', description: proj.descr, idelem: proj._id })
} else {
break
}
if (myidparent === proj.id_parent || (!proj.id_parent && (precmyparent === myidparent)))
break
precmyparent = myidparent
myidparent = proj.id_parent!
}
// console.log(' myarrgerarchia', myarrgerarchia)
return myarrgerarchia.reverse()
} else {
return []
}
},
getDescrById: (state: IProjectsState) => (id: string): string => {
if (id === process.env.PROJECT_ID_MAIN)
return 'Projects'
if (state.projects) {
const itemtrov = state.projects.find((item) => item._id === id)
if (!!itemtrov)
return itemtrov.descr!
}
return ''
},
getRecordById: (state: IProjectsState) => (id: string): IProject | null => {
// console.log('state.projects', state.projects)
// console.log('find', state.projects.find((item) => item._id === id))
if (state.projects) {
return state.projects.find((item) => item._id === id)!
}
return null
},
getifCanISeeProj: (state: IProjectsState) => (proj: IProject): boolean => {
if ((proj === undefined) || (proj === null))
return false
const userStore = useUserStore()
if (!!userStore.my) {
if (userStore.my._id === proj.userId) // If it's the owner
return true
let myprojtocheck = proj
if (proj.privacyread === Privacy.inherited) {
// @ts-ignore
myprojtocheck = this.getFirstInherited(proj, proj.id_parent, state)
if (!myprojtocheck)
return true
}
console.log('privacyread', myprojtocheck.privacyread)
return (userStore.my._id === myprojtocheck.userId) || (myprojtocheck.privacyread === Privacy.all) ||
(myprojtocheck.privacyread === Privacy.friends) && (userStore.IsMyFriend(myprojtocheck.userId!))
|| ((myprojtocheck.privacyread === Privacy.mygroup) && (userStore.IsMyGroup(myprojtocheck.userId!)))
} else {
return false
}
},
getTipoVisuProj: (state: IProjectsState) => (proj: IProject): number => {
if ((proj === undefined) || (proj === null))
return TipoVisu.simplelist
const userStore = useUserStore()
if (!!userStore) {
let tipovisuproj = proj
if (tipovisuproj.tipovisu === TipoVisu.inherited) {
// @ts-ignore
tipovisuproj = this.getFirstInheritedTipoVisu(proj, proj.id_parent, state)
if (!tipovisuproj)
return TipoVisu.simplelist
}
return tipovisuproj.tipovisu!
} else {
return TipoVisu.simplelist
}
},
CanIModifyPanelPrivacy: (state: IProjectsState) => (proj: IProject): boolean => {
if ((proj === undefined) || (proj === null))
return false
const userStore = useUserStore()
if (!!userStore) {
let myprojtocheck = proj
if (proj.privacywrite === Privacy.inherited) {
// @ts-ignore
myprojtocheck = this.getFirstInherited(proj, proj.id_parent, state)
if (!myprojtocheck)
return true
}
if (!!userStore)
return (userStore.my._id === myprojtocheck.userId) || (myprojtocheck.privacywrite === Privacy.all) ||
(myprojtocheck.privacywrite === Privacy.friends) && (userStore.IsMyFriend(myprojtocheck.userId!))
|| ((myprojtocheck.privacywrite === Privacy.mygroup) && (userStore.IsMyGroup(myprojtocheck.userId!)))
else
return false
}
return false
},
},
actions: {
getFirstInherited(proj: IProject, idparent: string) {
let myprojtocheck = null
while (proj.privacyread === Privacy.inherited) {
myprojtocheck = this.projects.find((rec) => rec._id === idparent)
if (!myprojtocheck)
return null
idparent = myprojtocheck.id_parent!
proj = myprojtocheck
}
return myprojtocheck
},
getFirstInheritedTipoVisu(proj: IProject, idparent: string) {
let tipovisuproj = null
while (!proj.tipovisu || proj.tipovisu <= 0) {
tipovisuproj = this.projects.find((rec) => rec._id === idparent)
if (!tipovisuproj)
return null
idparent = tipovisuproj.id_parent!
proj = tipovisuproj
}
return tipovisuproj!.tipovisu
},
getarrByCategory(category: string) {
if (!this.projects) {
return []
}
return this.projects
},
initcat() {
const userStore = useUserStore()
const rec = this.getRecordEmpty()
rec.userId = userStore.my._id
return rec
},
updateDataCalculated(projout: any, projin: any) {
listFieldsUpdateCalculation.forEach((field) => {
projout[field] = projin[field]
})
},
getproj(projects: any, idproj: any, tipoproj: string) {
let ris = null
const userStore = useUserStore()
if (tipoproj === RouteNames.myprojects)
ris = projects.filter((proj: IProject) => (proj.id_parent === idproj) && (proj.userId === userStore.my._id))
else if (tipoproj === RouteNames.projectsshared)
ris = projects.filter((proj: IProject) => (proj.id_parent === idproj) && (proj.userId === userStore.my._id) && (proj.privacyread !== Privacy.onlyme))
else if (tipoproj === RouteNames.projectsall)
ris = projects.filter((proj: IProject) => (proj.id_parent === idproj) && (proj.userId !== userStore.my._id))
else
ris = projects.filter((proj: IProject) => (proj.id_parent === idproj))
if (ris)
{ // @ts-ignore
ris = ris.sort((a: IProject, b: IProject) => a.pos - b.pos)
}
// console.log('idproj', idproj, 'projects', projects, 'getproj', tipoproj, 'ris=', ris)
return ris
},
createNewItem({ objproj, atfirst, categorySel }: { objproj: IProject, atfirst: boolean, categorySel: string }) {
// console.log('createNewItem', objproj, 'cat=', categorySel, 'this.projects', this.projects)
if (this.projects === undefined) {
this.projects = []
this.projects.push(objproj)
console.log('push this.projects', this.projects)
return
}
if (atfirst) {
this.projects.unshift(objproj)
} else {
this.projects.push(objproj)
}
},
updateProject({ objproj }: { objproj: IProject }) {
if (!!objproj) {
// console.log('updateProject', objproj)
const index = tools.getIndexById(this.projects, objproj._id)
// console.log('index', index)
if (index >= 0) {
this.updateDataCalculated(this.projects[index], objproj)
// this.projects.splice(index, 1, objproj)
// tools.notifyarraychanged(this.projects)
}
}
},
deletemyitem(myitem: IProject) {
// Find record
const ind = tools.getIndexById(this.projects, myitem._id)
ApiTables.removeitemfromarray(this.projects, ind)
},
async movemyitem({ myitemorig, myitemdest }: { myitemorig: IProject, myitemdest: IProject }) {
const indorig = tools.getIndexById(this.projects, myitemorig._id)
this.projects.splice(indorig, 1)
this.projects.push(myitemdest)
await this.modify({ myitem: myitemdest, field: 'id_parent' })
},
async dbLoad({ checkPending, onlyiffirsttime }: { checkPending: boolean, onlyiffirsttime: boolean }) {
if (!static_data.functionality.ENABLE_PROJECTS_LOADING)
return null
if (onlyiffirsttime) {
if (this.projects.length > 0) {
// if already set, then exit.
return new Types.AxiosError(0, null, 0, '')
}
}
// if (userStore.my._id === '') {
// return false // Login not made
// }
// console.log('userStore.my', userStore.my)
// console.log('dbLoad', nametable, checkPending, 'userid=', userStore.my._id)
const userStore = useUserStore()
const globalStore = useGlobalStore()
const ris = await Api.SendReq('/projects/' + userStore.my._id, 'GET', null)
.then((res) => {
if (res.data.projects) { // console.log('RISULTANTE CATEGORIES DAL SERVER = ', res.data.categories)
this.projects = res.data.projects
} else {
this.projects = []
}
this.showtype = parseInt(globalStore.getConfigStringbyId({
id: costanti.CONFIG_ID_SHOW_TYPE_TODOS,
default: costanti.ShowTypeTask.SHOW_LAST_N_COMPLETED
}), 10)
if (process.env.DEBUG === '1') {
console.log('dbLoad', 'this.projects', this.projects)
}
return res
})
.catch((error) => {
console.log('error dbLoad', error)
userStore.setErrorCatch(error)
return new Types.AxiosError(serv_constants.RIS_CODE_ERR, null, toolsext.ERR_GENERICO, error)
})
ApiTables.aftercalling(ris, checkPending, nametable)
},
async calculateHoursProjects({ projId, actualphase }: { projId: string, actualphase: string }) {
let ris = null
ris = await Api.SendReq('/projects/calc/' + projId + '/' + actualphase, 'GET', null)
.then((res) => {
if (res.data.rec) { // console.log('RISULTANTE CATEGORIES DAL SERVER = ', res.data.categories)
return res.data.rec
}
return null
})
.catch((error) => {
console.log('error calculateHoursProjects', error)
})
return ris
},
async deleteItem({ idobj }: { idobj: any }) {
console.log('deleteItem: KEY = ', idobj)
const myarr = this.getarrByCategory('')
const myobjtrov = tools.getElemById(myarr, idobj)
console.log('myobjtrov', myobjtrov.descr)
if (!!myobjtrov) {
/*
const myobjnext = tools.getElemPrevById(myarr, myobjtrov._id)
if (!!myobjnext) {
myobjnext.pos = myobjtrov.pos + 1
myobjnext.modified = true
await modify( { myitem: myobjnext, field: 'pos' })
}
*/
// ApiTables.table_DeleteRecord(nametable, myobjtrov, idobj)
ApiTables.table_HideRecord(nametable, myobjtrov, idobj)
}
},
async dbInsert({ myobj, atfirst }: { myobj: IProject, atfirst: boolean}) {
const objproj = this.initcat()
objproj.descr = myobj.descr
objproj.category = myobj.category
objproj.id_parent = myobj.id_parent
objproj.id_main_project = myobj.id_main_project
objproj.typeproj = myobj.typeproj
objproj.privacyread = myobj.privacyread
objproj.privacywrite = myobj.privacywrite
objproj.actualphase = myobj.actualphase
objproj.tipovisu = myobj.tipovisu
let elemtochange: IProject = { }
const myarr = this.getarrByCategory(objproj.category!)
const tipoProj = ''
if (atfirst) {
console.log('INSERT AT THE TOP')
elemtochange = tools.getFirstList(myarr)
objproj.pos = 10
} else {
console.log('INSERT AT THE BOTTOM')
// INSERT AT THE BOTTOM , so GET LAST ITEM
const lastelem = tools.getLastListNotCompleted(nametable, objproj.id_parent!, tipoProj)
objproj.pos = (!!lastelem) ? lastelem.pos + 10 : 10
}
objproj.modified = false
this.createNewItem({ objproj, atfirst, categorySel: objproj.category! }) // 1) Create record in Memory
const id = await globalroutines('write', nametable, objproj) // 2) Insert into the IndexedDb
let field = ''
if (atfirst) { // update also the last elem
if (!!elemtochange) {
elemtochange.pos = objproj.pos
console.log('elemtochange', elemtochange)
field = 'pos'
// Modify the other record
await this.modify({ myitem: elemtochange, field })
}
}
// 3) send to the Server
await ApiTables.Sync_SaveItem(nametable, 'POST', objproj)
return id
},
async modify({ myitem, field }: { myitem: any, field: any } ) {
return ApiTables.table_ModifyRecord(nametable, myitem, listFieldsToChange, field)
},
async swapElems(itemdragend: IDrag) {
console.log('PROJECT swapElems', itemdragend, this.projects)
const myarr = this.projs_dacompletare(itemdragend.id_proj!, itemdragend.tipoproj!)
tools.swapGeneralElem(nametable, myarr, itemdragend, listFieldsToChange)
},
async ActionCutPaste(action: IAction) {
const globalStore = useGlobalStore()
if (action.type === lists.MenuAction.CUT) {
globalStore.lastaction = action
} else if (action.type === lists.MenuAction.PASTE) {
if (globalStore.lastaction.type === lists.MenuAction.CUT) {
// Change id_parent
const orig_obj = this.getRecordById(globalStore.lastaction._id)
const dest = this.getRecordById(action._id)
// console.log('dest', dest)
const dest_obj = tools.jsonCopy(orig_obj)
if (!!dest_obj) {
dest_obj.id_parent = dest!._id
dest_obj.id_main_project = dest!.id_main_project
dest_obj.modified = true
globalStore.lastaction.type = 0
return this.movemyitem({ myitemorig: orig_obj!, myitemdest: dest_obj })
}
}
}
},
},
})

501
src/store/Todos.ts Executable file
View File

@@ -0,0 +1,501 @@
import {
ITodo,
ITodosState,
IParamTodo,
IDrag,
IAction
} from 'model'
import Api from '@api'
import { tools } from '@store/Modules/tools'
import { lists } from './Modules/lists'
import * as ApiTables from './Modules/ApiTables'
import globalroutines from './../globalroutines/index'
import { serv_constants } from '@src/store/Modules/serv_constants'
import objectId from '@src/js/objectId'
import { costanti } from '@src/store/Modules/costanti'
import * as Types from '@src/store/Api/ApiTypes'
import { static_data } from '@src/db/static_data'
import { defineStore } from "pinia"
import { useUserStore } from '@store/UserStore'
import { useGlobalStore } from "@store/globalStore"
import { toolsext } from "@store/Modules/toolsext"
const nametable = 'todos'
// import _ from 'lodash'
const state: ITodosState = {
showtype: costanti.ShowTypeTask.SHOW_LAST_N_COMPLETED,
todos: {},
categories: [],
// todos_changed: 1,
reload_fromServer: 0,
testpao: 'Test',
insidePending: false,
visuLastCompleted: 10
}
const listFieldsToChange: string [] = ['descr', 'statustodo', 'category', 'expiring_at', 'priority', 'pos', 'enableExpiring', 'progress', 'phase', 'assigned_to_userId', 'hoursplanned', 'hoursworked', 'start_date', 'completed_at', 'themecolor', 'themebgcolor', 'assignedToUsers']
export const useTodoStore = defineStore('Todos', {
state: (): ITodosState => (
{
showtype: costanti.ShowTypeTask.SHOW_LAST_N_COMPLETED,
todos: {},
categories: [],
// todos_changed: 1,
reload_fromServer: 0,
testpao: 'Test',
insidePending: false,
visuLastCompleted: 10,
}),
getters: {
getindexbycategory: (state: ITodosState) => (category: string): number => {
if (state.categories) {
return state.categories.indexOf(category)
}
return -1
},
getRecordEmpty: (state: ITodosState) => (): ITodo => {
const userStore = useUserStore()
const tomorrow = tools.getDateNow()
tomorrow.setDate(tomorrow.getDate() + 1)
const objtodo: ITodo = {
// _id: tools.getDateNow().toISOString(), // Create NEW
_id: objectId(),
userId: userStore.my._id,
descr: '',
note: '',
priority: tools.Priority.PRIORITY_NORMAL,
statustodo: tools.Status.OPENED,
created_at: tools.getDateNow(),
modify_at: tools.getDateNow(),
completed_at: tools.getDateNull(),
category: '',
expiring_at: tomorrow,
enableExpiring: false,
pos: 0,
modified: false,
progress: 0,
progressCalc: 0,
phase: 0,
assigned_to_userId: '',
hoursplanned: 0,
hoursworked: 0,
start_date: tools.getDateNull(),
themecolor: 'blue',
themebgcolor: 'white',
assignedToUsers: []
}
// return this.copy(objtodo)
return objtodo
},
items_dacompletare: (state: ITodosState) => (cat: string): ITodo[] => {
// console.log('items_dacompletare')
// @ts-ignore
const indcat: number = this.getindexbycategory(cat)
let arrout = []
// console.log('items_dacompletare', 'indcat', indcat, state.todos[indcat])
if (indcat >= 0 && state.todos) {
// @ts-ignore
if (state.todos[indcat] ) {
// @ts-ignore
arrout = state.todos[indcat].filter((todo: ITodo) => todo.statustodo !== tools.Status.COMPLETED)
}
}
if (arrout)
{ // @ts-ignore
arrout = arrout.sort((a: ITodo, b: ITodo) => a.pos - b.pos)
}
// return tools.mapSort(arrout)
return arrout
},
todos_completati: (state: ITodosState) => (cat: string): ITodo[] => {
// @ts-ignore
let indcat = this.getindexbycategory(cat)
// console.log('todos_completati', cat, 'indcat=', indcat, 'this.categories=', this.categories)
// @ts-ignore
if (state.todos[indcat]) {
let arrout = []
if (state.showtype === costanti.ShowTypeTask.SHOW_LAST_N_COMPLETED) { // Show only the first N completed
// @ts-ignore
arrout = state.todos[indcat].filter((todo: ITodo) => todo.statustodo === tools.Status.COMPLETED).slice(0, state.visuLastCompleted)
} else if (state.showtype === costanti.ShowTypeTask.SHOW_ONLY_TOCOMPLETE) {
arrout = []
} else if (state.showtype === costanti.ShowTypeTask.SHOW_ALL) {
// @ts-ignore
arrout = state.todos[indcat].filter((todo: ITodo) => todo.statustodo === tools.Status.COMPLETED)
} else {
arrout = []
}
if (arrout)
{ // @ts-ignore
arrout = arrout.sort((a: ITodo, b: ITodo) => a.pos - b.pos)
}
// console.log('arrout', arrout)
return arrout
// return tools.mapSort(arrout)
} else {
return []
}
},
doneTodosCount: (state: ITodosState) => (cat: string): number => {
// @ts-ignore
return this.todos_completati(cat).length
},
TodosCount: (state: ITodosState) => (cat: string): number => {
// @ts-ignore
const indcat = this.getindexbycategory(cat)
// @ts-ignore
if (state.todos[indcat]) {
// @ts-ignore
return state.todos[indcat].length
} else {
return 0
}
},
getRecordById: (state: ITodosState) => (id: string, cat: string): ITodo => {
// @ts-ignore
const indcat = this.getindexbycategory(cat)
if (state.todos) {
// @ts-ignore
return state.todos[indcat].find((item) => item._id === id)
}
return {}
},
},
actions: {
gettodosByCategory(category: string): any[] {
const indcat = this.categories.indexOf(category)
// @ts-ignore
if (!this.todos[indcat]) {
return []
}
// @ts-ignore
return this.todos[indcat]
},
initcat(): any {
const userStore = useUserStore()
const rec = this.getRecordEmpty()
rec.userId = userStore.my._id
return rec
},
findIndTodoById(data: IParamTodo) {
const indcat = this.categories.indexOf(data.categorySel!)
if (indcat >= 0) {
// @ts-ignore
return tools.getIndexById(this.todos[indcat], data.id)
}
return -1
},
createNewItem({ objtodo, atfirst, categorySel }: { objtodo: ITodo, atfirst: boolean, categorySel: string }) {
let indcat = state.categories.indexOf(categorySel)
if (indcat === -1) {
this.categories.push(categorySel)
indcat = this.categories.indexOf(categorySel)
}
console.log('createNewItem', objtodo, 'cat=', categorySel, 'this.todos[indcat]', this.todos[indcat])
if (this.todos[indcat] === undefined) {
this.todos[indcat] = []
this.todos[indcat].push(objtodo)
console.log('push this.todos[indcat]', this.todos)
return
}
if (atfirst) {
this.todos[indcat].unshift(objtodo)
} else {
this.todos[indcat].push(objtodo)
}
console.log('this.todos[indcat]', this.todos[indcat])
},
deletemyitem(myitem: ITodo) {
// Find record
const indcat = this.categories.indexOf(myitem.category!)
const ind = this.findIndTodoById({ id: myitem._id, categorySel: myitem.category })
ApiTables.removeitemfromarray(this.todos[indcat], ind)
},
async movemyitem({ myitemorig, myitemdest }: { myitemorig: ITodo, myitemdest: ITodo }) {
const indcat = this.categories.indexOf(myitemorig.category!)
const indorig = tools.getIndexById(this.todos[indcat], myitemorig._id)
let indcatdest = this.categories.indexOf(myitemdest.category!)
console.log('this.categories', this.categories)
console.log('myitemdest', myitemdest)
// console.log('indcat', indcat, 'indcatdest', indcatdest, 'indorig', indorig)
if (indcatdest === -1) {
this.categories.push(myitemdest.category!)
const newindcat = this.categories.indexOf(myitemdest.category!)
this.todos[newindcat] = []
indcatdest = newindcat
}
this.todos[indcat].splice(indorig, 1)
this.todos[indcatdest].push(myitemdest)
await this.modify({ myitem: myitemdest, field: 'category' })
},
async dbLoad({ checkPending }: { checkPending: boolean }) {
const globalStore = useGlobalStore()
const userStore = useUserStore()
if (!static_data.functionality.ENABLE_PROJECTS_LOADING)
return null
// console.log('dbLoad', nametable, checkPending, 'userid=', userStore.my._id)
// if (userStore.my._id === '') {
// return new Types.AxiosError(0, null, 0, '')
// }
let ris = null
ris = await Api.SendReq('/todos/' + userStore.my._id, 'GET', null)
.then((res) => {
if (res.data.todos) { // console.log('RISULTANTE CATEGORIES DAL SERVER = ', res.data.categories)
this.todos = res.data.todos
this.categories = res.data.categories
} else {
this.todos = [[]]
}
this.showtype = parseInt(globalStore.getConfigStringbyId({
id: costanti.CONFIG_ID_SHOW_TYPE_TODOS,
default: costanti.ShowTypeTask.SHOW_LAST_N_COMPLETED
}), 10)
// console.log('ARRAY TODOS = ', this.todos)
if (process.env.DEBUG === '1') {
// console.log('dbLoad', 'this.todos', this.todos, 'this.categories', this.categories)
}
return res
})
.catch((error) => {
console.log('error dbLoad', error)
userStore.setErrorCatch(error)
return new Types.AxiosError(serv_constants.RIS_CODE_ERR, null, toolsext.ERR_GENERICO, error)
})
ApiTables.aftercalling(ris, checkPending, 'categories')
return ris
},
async calculateHoursTodo({ todoId }: { todoId: string }) {
let ris = null
ris = await Api.SendReq('/todos/calc/' + todoId, 'GET', null)
.then((res) => {
if (res.data.rec) { // console.log('RISULTANTE CATEGORIES DAL SERVER = ', res.data.categories)
return res.data.rec
}
return null
})
.catch((error) => {
console.log('error calculateHoursTodo', error)
})
return ris
},
async deleteItemtodo({ cat, idobj }: { cat: string, idobj: string }) {
console.log('deleteItemtodo: KEY = ', idobj)
const myarr = this.gettodosByCategory(cat)
const myobjtrov = tools.getElemById(myarr, idobj)
if (!!myobjtrov) {
console.log('myobjtrov', myobjtrov.descr)
if (!!myobjtrov) {
/*
const myobjnext = tools.getElemPrevById(myarr, myobjtrov._id)
if (!!myobjnext) {
myobjnext.pos = myobjtrov.pos + 1
myobjnext.modified = true
await modify( { myitem: myobjnext, field: 'pos' })
}
*/
ApiTables.table_HideRecord(nametable, myobjtrov, idobj)
}
}
},
async dbInsert({ myobj, atfirst }: { myobj: ITodo, atfirst: boolean }) {
const objtodo = this.initcat()
objtodo.descr = myobj.descr
objtodo.category = myobj.category
const tipoProj = '' //++Todo: ?? nuovo tipoProj ?
let elemtochange: ITodo = {}
const myarr = this.gettodosByCategory(objtodo.category)
if (atfirst) {
console.log('INSERT AT THE TOP')
elemtochange = tools.getFirstList(myarr)
objtodo.pos = 10
} else {
console.log('INSERT AT THE BOTTOM')
// INSERT AT THE BOTTOM , so GET LAST ITEM
const lastelem = tools.getLastListNotCompleted(nametable, objtodo.category, tipoProj)
objtodo.pos = (!!lastelem) ? lastelem.pos + 10 : 10
}
objtodo.modified = false
this.createNewItem({ objtodo, atfirst, categorySel: objtodo.category }) // 1) Create record in Memory
const id = await globalroutines('write', nametable, objtodo) // 2) Insert into the IndexedDb
let field = ''
if (atfirst) { // update also the last elem
if (!!elemtochange) {
elemtochange.pos = objtodo.pos
console.log('elemtochange', elemtochange)
field = 'pos'
// Modify the other record
await this.modify({ myitem: elemtochange, field })
}
}
// 3) send to the Server
return ApiTables.Sync_SaveItem(nametable, 'POST', objtodo)
.then((ris) => {
// *** Check if need to be moved because of the --- Priority Ordering --- ...
const indelem = tools.getIndexById(myarr, objtodo._id)
let itemdragend
if (atfirst) {
// Check the second item, if it's different priority, then move to the first position of the priority
const secondindelem = indelem + 1
if (tools.isOkIndex(myarr, secondindelem)) {
const secondelem = tools.getElemByIndex(myarr, 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
if (tools.isOkIndex(myarr, prevlastindelem)) {
const prevlastelem = tools.getElemByIndex(myarr, prevlastindelem)
if (prevlastelem.priority !== objtodo.priority) {
itemdragend = {
field: 'priority',
idelemtochange: objtodo._id,
prioritychosen: objtodo.priority,
category: objtodo.category,
atfirst
}
}
}
}
if (itemdragend) {
this.swapElems(itemdragend)
}
return ris
})
},
async modify({ myitem, field }: { myitem: any, field: any }) {
return ApiTables.table_ModifyRecord(nametable, myitem, listFieldsToChange, field)
},
async swapElems(itemdragend: IDrag) {
// console.log('TODOS swapElems', itemdragend, this.todos, this.categories)
const cat = itemdragend.category
const indcat = this.categories.indexOf(cat!)
// @ts-ignore
const myarr = this.todos[indcat]
tools.swapGeneralElem(nametable, myarr, itemdragend, listFieldsToChange)
},
async ActionCutPaste(action: IAction) {
console.log('ActionCutPaste', action)
const globalStore = useGlobalStore()
if (action.type === lists.MenuAction.CUT) {
globalStore.lastaction = action
} else if (action.type === lists.MenuAction.PASTE) {
if (globalStore.lastaction.type === lists.MenuAction.CUT) {
// Change id_parent
const orig_obj = this.getRecordById(globalStore.lastaction._id, globalStore.lastaction.cat!)
// const dest = this.getRecordById(action._id, action.cat)
console.log('action', action, 'orig_obj', orig_obj)
const dest_obj = tools.jsonCopy(orig_obj)
if (!!dest_obj) {
dest_obj.category = action._id
dest_obj.modified = true
dest_obj.pos = 1
globalStore.lastaction.type = 0
return await this.movemyitem({ myitemorig: orig_obj, myitemdest: dest_obj })
}
}
}
},
}
})

View File

@@ -130,6 +130,9 @@ export const useUserStore = defineStore('UserStore', {
getServerCode: (state: IUserState): number => (state.servercode ? state.servercode : 0), getServerCode: (state: IUserState): number => (state.servercode ? state.servercode : 0),
getNameSurnameByUserId: (state: IUserState) => (userId: string): string => { getNameSurnameByUserId: (state: IUserState) => (userId: string): string => {
// @ts-ignore
const prova: number = this.getServerCode(state)
// @ts-ignore // @ts-ignore
const user = this.getUserByUserId(state, userId) const user = this.getUserByUserId(state, userId)
if (user) return `${user.name} ${user.surname}` if (user) return `${user.name} ${user.surname}`
@@ -143,6 +146,23 @@ export const useUserStore = defineStore('UserStore', {
return `(${username})` return `(${username})`
}, },
getUsersList: (mystate: IUserState) => {
return mystate.usersList
},
IsMyFriend: (mystate: IUserState) => (userIdOwner: string): boolean => {
// ++TODO Check if userIdOwner is my friend
// userIdOwner is my friend ?
return true
},
IsMyGroup: (mystate: IUserState) => (userIdOwner: string): boolean => {
// ++TODO Check if userIdOwner is on my groups
// userIdOwner is on my groups ?
return true
},
getUserByUserId: (state: IUserState) => (userId: string): IUserFields | null => { getUserByUserId: (state: IUserState) => (userId: string): IUserFields | null => {
// Check if is this User! // Check if is this User!
if (state.my._id === userId) return state.my if (state.my._id === userId) return state.my
@@ -500,7 +520,7 @@ export const useUserStore = defineStore('UserStore', {
// console.log('autologin _id STATE ', this._id) // console.log('autologin _id STATE ', this._id)
// return true // return true
} catch (e) { } catch (e: any) {
console.error('ERR autologin ', e.message) console.error('ERR autologin ', e.message)
return false return false
} }

View File

@@ -20,7 +20,6 @@ import { shared_consts } from '@src/common/shared_vuejs'
const stateConnDefault = 'online' const stateConnDefault = 'online'
export const useGlobalStore = defineStore('GlobalStore', { export const useGlobalStore = defineStore('GlobalStore', {
// @ts-ignore
state: (): IGlobalState => ({ state: (): IGlobalState => ({
finishLoading: false, finishLoading: false,
conta: 0, conta: 0,
@@ -86,8 +85,23 @@ export const useGlobalStore = defineStore('GlobalStore', {
}), }),
getters: { getters: {
// conta: (state: IGlobalState) => { state.conta },
// listatodo: (state: IGlobalState) => { state.listatodo },
// category: (state: IGlobalState) => { state.category },
isNewVersionAvailable(state: IGlobalState) { testpao1_getter_contatore: (state: IGlobalState) => (param1: number) => state.testp1.contatore + 100 + param1,
testpao1_getter_array: (state: IGlobalState) => (param1: number) => state.testp1.mioarray.filter((item) => item).map((item) => item.valore),
getConfigbyId: (state: IGlobalState) => (id: string) => state.arrConfig.find((item) => item._id === id),
getConfigStringbyId: (state: IGlobalState) => (params: any) => {
const config = state.arrConfig.find((item) => item._id === params.id)
if (config) {
return config.value
} else {
return params.default
}
},
isNewVersionAvailable: (state: IGlobalState) => {
// console.log('cfgServer', cfgServer) // console.log('cfgServer', cfgServer)
const serversrec = state.cfgServer.find((x) => (x.chiave === toolsext.SERVKEY_VERS) && (x.idapp === process.env.APP_ID)) const serversrec = state.cfgServer.find((x) => (x.chiave === toolsext.SERVKEY_VERS) && (x.idapp === process.env.APP_ID))
// console.log('Record ', serversrec) // console.log('Record ', serversrec)

View File

@@ -20,9 +20,15 @@ export const useTestStore = defineStore({
return (rec.lang === toolsext.getLocale(false) || toolsext.getLocale() === '') return (rec.lang === toolsext.getLocale(false) || toolsext.getLocale() === '')
}, },
prova2(): boolean { prova1: (state: ITest) => (myval: number): boolean => {
return this.finishLoading return (myval > 1)
}, },
prova2: (): boolean => {
// @ts-ignore
return this.prova1(2)
},
}, },
actions: { actions: {

990
yarn.lock

File diff suppressed because it is too large Load Diff