Files
myprojplanet_vite/src/views/ecommerce/catalogo/catalogo.ts
Surya Paolo 6d0efaadb9 - aggiornamento cataloghi.
possibilità di estrapolare i dati da GM direttamente
- migrazione delle tabelle di GM in locale
- corretto l'ordinamento del Catalogo
2025-04-18 13:23:52 +02:00

1332 lines
46 KiB
TypeScript
Executable File

import type { PropType } from 'vue';
import { defineComponent, onMounted, ref, watch, computed, onBeforeUnmount, nextTick } from 'vue'
import { tools } from '@tools'
import { useUserStore } from '@store/UserStore'
import { useRouter } from 'vue-router'
import { useGlobalStore } from '@store/globalStore'
import { useProducts } from '@store/Products'
import { useI18n } from 'vue-i18n'
import { toolsext } from '@store/Modules/toolsext'
import { useQuasar } from 'quasar'
import { costanti } from '@costanti'
import { shared_consts } from '@src/common/shared_vuejs'
import { CProductCard } from '@src/components/CProductCard'
import { CMyDialog } from '@src/components/CMyDialog'
import { CMySelect } from '@src/components/CMySelect'
import { CProductTable } from '@src/components/CProductTable'
import { CSearchProduct } from '@src/components/CSearchProduct'
import { CContainerCatalogoCard } from '@src/components/CContainerCatalogoCard'
import { CSelectUserActive } from '@src/components/CSelectUserActive'
import type {
IOptCatalogo, IDimensioni, IFilterCatalogo,
IMyScheda, IProdView, IProduct, ISchedaSingola, ISearchList, ICatalog, IImg,
IText,
ICollana,
} from 'model';
import {
IMyPage,
} from 'model'
import { fieldsTable } from '@store/Modules/fieldsTable'
import { useCatalogStore } from '@src/store/CatalogStore'
import { Catalogo } from '.';
export default defineComponent({
name: 'Catalogo',
components: {
CContainerCatalogoCard, CProductCard,
CSelectUserActive, CMySelect, CProductTable, CSearchProduct, CMyDialog,
},
emits: ['update:modelValue', 'updateCatalogo'],
props: {
modelValue: {
type: Object as PropType<IOptCatalogo>,
required: true,
},
idPage: {
type: String,
required: false,
default: '',
},
},
setup(props, { emit }) {
const userStore = useUserStore()
const globalStore = useGlobalStore()
const productStore = useProducts()
const router = useRouter()
const $q = useQuasar()
const { t } = useI18n()
const search = ref('')
const optauthors = ref(<any>[])
const pdfContent = ref(null);
const addnewProd = ref(false)
const optcatalogo = ref(<IOptCatalogo>{ ...props.modelValue });
function updateCatalogoPadre() {
console.log('catalogo.ts PADRE')
emit('update:modelValue', optcatalogo.value);
//emit('updateCatalogo', optcatalogo.value);
}
// Metodo per aggiornare optcatalogo
const updateOptCatalogo = <K extends keyof IOptCatalogo>(key: K, value: IOptCatalogo[K]) => {
optcatalogo.value[key] = value;
updateCatalogoPadre()
}
// Utile anche per sincronizzare con le modifiche ricevute da props
watch(() => props.modelValue, (newVal) => {
optcatalogo.value = { ...newVal };
}, { deep: false });
/*watch(optcatalogo, (newValue) => {
emit('update:modelValue', newValue);
}, { deep: true });*/
const filter = ref(<IFilterCatalogo>{
author: '',
publisher: '',
type: '',
ageGroup: ''
})
const cosa = ref(0)
const cat = ref('')
const idGasSel = ref('')
const loadpage = ref(false)
const refreshpage = ref(false)
const show_hide = ref(false)
const mycolumns = ref([])
const catalogStore = useCatalogStore()
const tabvisu = ref('categorie')
const tabcatalogo = ref()
const searchList = ref([] as ISearchList[])
const arrProducts = ref<IProduct[]>([])
const arrProdToView = ref<IProdView[]>([])
const numRecLoaded = ref(0)
// Create a ref for the component to fix
const componentToFixRef = ref(<any>null);
const isFixed = ref(false);
watch(() => tabcatalogo.value, () => {
tools.setCookie('TAB_CAT', tabcatalogo.value)
})
const labelcombo = computed(() => (item: any) => {
let lab = item.label
if (item.showcount)
lab += ' (' + valoriopt.value(item, false, false).length + ')'
return lab
})
const arrLoaded = computed(() => {
if (arrProducts.value && numRecLoaded.value)
return arrProducts.value.slice(0, numRecLoaded.value)
else {
return []
}
})
const getTestoIntroduttivo = computed(() => (recscheda: ISchedaSingola) => {
let testo = recscheda.scheda!.dimensioni.pagina?.testo_up?.contenuto
if (recscheda.scheda!.isPagIntro) {
const catalogStore = useCatalogStore()
const catalog = getCatalogoByMyPage.value
if (catalog && catalog.descr_introduttiva) {
// Cerca se la descrizione introduttiva è stata impostata
testo = catalog.descr_introduttiva
let clcol = ''
if (catalog.pagina_introduttiva_sfondo_nero) {
clcol = `text-white`
}
testo = `<span class="book-text-up ${clcol}">` + testo + `</span>`
}
}
return testo
})
function getTextSostituito(testo: IText) {
const replacements = {
'{titolo_catalogo}': getTitoloCatalogo() || '',
};
// Esegue le sostituzioni
let result = testo.contenuto;
for (const [key, value] of Object.entries(replacements)) {
result = result.replace(new RegExp(key, 'g'), value);
}
return result
}
const getTitoloPagina = computed(() => (product: IProduct, recscheda: ISchedaSingola) => {
let testo = getTextSostituito(recscheda.scheda!.dimensioni.pagina?.testo_title)
return testo
})
const getCatalogoByMyPage = computed(() => {
return catalogStore.catalogs?.find((catalog: ICatalog) => catalog.idPageAssigned === props.idPage)
})
const lista_prodotti = computed(() => {
const arr = catalogStore.catalogs?.find((catalog: ICatalog) => catalog.idPageAssigned === props.idPage)
return arr?.lista_prodotti
})
const ispageCatalogata = computed(() => {
return !!getCatalogoByMyPage.value
})
// Register the scroll event on component mount
const handleScroll = () => {
const scrollTop = window.scrollY || document.documentElement.scrollTop;
// Set a threshold value based on how much scroll is needed to fix the components
const threshold = 300
// Update the isFixed ref based on the scroll position
isFixed.value = scrollTop > threshold;
};
watch(() => cat.value, (newval, oldval) => {
if (loadpage.value)
tools.setCookie(tools.COOK_CATEGORIA, cat.value.toString())
filter.value.author = '' // disattivo il filtro autore
resetSearch()
calcArrProducts()
})
watch(() => idGasSel.value, (newval, oldval) => {
calcArrProducts()
})
watch(() => getSearchText(), (newval, oldval) => {
calcArrProducts()
if (tools.scrollTop() > 300) {
tools.scrollToTopValue(300)
}
})
watch(() => filter.value.author, (newval, oldval) => {
// Se filtroAuthor attivato, allora evito il filtro per Categoria
if (filter.value.author) {
cat.value = '' // disattivo il filtro categoria
if (loadpage.value)
tools.setCookie(tools.COOK_CATEGORIA, '')
resetSearch()
}
calcArrProducts()
if (tools.scrollTop() > 300) {
tools.scrollToTopValue(300)
}
})
watch(() => filter.value.sort_field, (newval, oldval) => {
calcArrProducts()
if (tools.scrollTop() > 300) {
tools.scrollToTopValue(300)
}
})
watch(() => filter.value.sort_dir, (newval, oldval) => {
calcArrProducts()
if (tools.scrollTop() > 300) {
tools.scrollToTopValue(300)
}
})
watch(() => cosa.value, (newval, oldval) => {
if (oldval !== 0) {
tools.setCookie(tools.COOK_COSA_PRODOTTI, cosa.value.toString())
if (cosa.value !== shared_consts.PROD.TUTTI) {
cat.value = ''
if (loadpage.value)
tools.setCookie(tools.COOK_CATEGORIA, '')
}
calcArrProducts()
}
})
watch(() => optcatalogo.value.aggiorna, (newval, oldval) => {
console.log('Aggiorna array...')
generatearrProdToViewSorted()
})
function resetSearch() {
const mialista = getSearchList()
if (mialista && mialista.value && tools.existProp(mialista.value, 'name')) {
mialista.value = null
}
search.value = ''
}
function getSearchList() {
const mylist = searchList.value.find((rec: any) => rec.table === 'products' && rec.key === 'titolo')
return mylist
}
function getSearchText(): string {
const lista = getSearchList()
return lista && lista.value && tools.existProp(lista.value, 'name') ? lista.value.name : ''
}
function getTitoloCatalogo(): string {
const trovatocatalogo = getCatalogoByMyPage.value
return trovatocatalogo ? trovatocatalogo.title : 'Catalogo'
}
function getImgIntroCatalogo(scheda: IMyScheda): IImg {
const trovatocatalogo = getCatalogoByMyPage.value
let imagefile = ''
let fit = 'contain'
if (trovatocatalogo && scheda.isPagIntro) {
const recimg = trovatocatalogo.img_intro
if (recimg) {
imagefile = recimg.imagefile!
fit = recimg.fit! || 'contain'
imagefile = imagefile ? `url(${tools.getDirUpload() + shared_consts.getDirectoryByTable(shared_consts.TABLES_CATALOG) + '/' + trovatocatalogo._id + '/' + imagefile})` : ''
}
}
return { imagefile, fit }
}
function getSfondoImgCatalogo(scheda?: IMyScheda | null, mypage?: IDimensioni): IImg {
const trovatocatalogo = getCatalogoByMyPage.value
let imagefile = ''
let fit = 'contain'
if (trovatocatalogo) {
// Cerca prima se c'è un Immagine Introduttiva
const recimgintro = getImgIntroCatalogo(scheda)
if (recimgintro.imagefile) {
imagefile = recimgintro.imagefile!
fit = recimgintro.fit! || 'contain'
}
// Poi cerca se c'è l'immagine di sfondo
const recimg = trovatocatalogo.img_bordata!
if (!imagefile && recimg) {
imagefile = recimg.imagefile!
fit = recimg.fit! || 'contain'
imagefile = imagefile ? `url(${tools.getDirUpload() + shared_consts.getDirectoryByTable(shared_consts.TABLES_CATALOG) + '/' + trovatocatalogo._id + '/' + imagefile})` : ''
}
}
if (!imagefile) {
let myimg = costanti.CATALOGHI.PAG_SFONDO_DEFAULT
if (scheda.isPagIntro) {
myimg = costanti.CATALOGHI.PAG_INTRO_DEFAULT
}
// Se non c'è un immagine di sfondo, allora prende quella di default
imagefile = `url(${tools.getDirUpload() + shared_consts.getDirectoryByTable(shared_consts.TABLES_CATALOG) + '/' + myimg})`
}
if (!imagefile && scheda) {
imagefile = scheda.dimensioni?.pagina?.dimensioni?.imgsfondo!.imagefile
imagefile = imagefile ? `url(${tools.getDirUpload() + costanti.DIR_SCHEDA + imagefile})` : ''
fit = scheda.dimensioni?.pagina?.dimensioni?.imgsfondo!.fit
}
if (!imagefile && mypage) {
imagefile = mypage.imgsfondo!.imagefile!
imagefile = imagefile ? `url(${tools.getDirUpload() + costanti.DIR_CATALOGO + imagefile})` : ''
fit = mypage.imgsfondo!.fit!
}
return { imagefile, fit }
}
function getIdCollaneDaFiltrare(def_idCollane?: number[]) {
let idCollane: number[] = []
// Cerca se nella lista cataloghi c'è la Collana di questa Pagina !
const trovatocatalogo = getCatalogoByMyPage.value
if (trovatocatalogo) {
idCollane = trovatocatalogo.idCollane! || []
} else {
idCollane = def_idCollane || []
}
return idCollane
}
function getArgomentiDaFiltrare(def_argomenti?: string[]) {
let argomenti: string[] = []
// Cerca se nella lista cataloghi c'è la Collana di questa Pagina !
const trovatocatalogo = getCatalogoByMyPage.value
if (trovatocatalogo) {
argomenti = trovatocatalogo.argomenti! || []
} else {
if (def_argomenti && def_argomenti.length > 0) {
argomenti = def_argomenti
} else {
argomenti = []
}
}
return argomenti
}
function getEditoreDaFiltrare(def_editori?: string[]) {
let editore: string[] = []
// Cerca se nella lista cataloghi c'è la Collana di questa Pagina !
const trovatocatalogo = getCatalogoByMyPage.value
if (trovatocatalogo) {
editore = trovatocatalogo.editore! || []
} else {
editore = def_editori || []
}
return editore
}
function populateDataWithlinkIdTemplate() {
// console.log('populateDataWithlinkIdTemplate')
if (optcatalogo.value) {
for (const recscheda of optcatalogo.value.arrSchede!) {
if (recscheda.scheda?.linkIdTemplate) {
// ricopia da Template:
const myscheda = globalStore.sovrascriviSchedaFromTemplate(recscheda.scheda?.linkIdTemplate, recscheda)
if (myscheda) {
recscheda.scheda = { ...myscheda }
}
}
}
}
// console.log(' FINE - populateDataWithlinkIdTemplate')
}
function filterProducts(
products: IProduct[],
searchtext: string | string[],
filtroAuthor: string,
filtroProductTypes: number[],
filtroExcludeProductTypes: number[],
editore: string[],
idCollane: ICollana[],
arrargomstr: any[],
catstr: string,
gasselstr: string,
cosaValue: any,
sortField?: string,
sortDir?: number
): IProduct[] {
const lowerSearchTexts = Array.isArray(searchtext)
? searchtext.map((text: string) => text.toLowerCase().trim().replace(/[-@:=]/g, ''))
: [searchtext.toLowerCase().trim().replace(/[-@:=]/g, '')];
const boolfiltroVuotoProductTypes =
filtroProductTypes.length === 0 || (filtroProductTypes.length === 1 && filtroProductTypes[0] === 0);
const boolfiltroVuotoExcludeProductTypes = filtroExcludeProductTypes.length === 0;
const boolfiltroVuotoEditore = editore.length === 0;
const boolfiltroVuotoCollane = idCollane.length === 0;
// const boolfiltroVuotoArgomenti = arrargomstr.length === 0;
const arrris = products
.filter((product: IProduct) => {
if (!product || !product.productInfo) {
console.error('product or product.productInfo is null');
return false;
}
const lowerName = (product.productInfo.name || '').toLowerCase();
const lowerCode = (product.productInfo.code || '').toLowerCase();
// Filtri per argomenti e categorie
let hasCategoria = false;
let hasArgomentiCat = true;
if (arrargomstr && arrargomstr.length > 0) {
hasArgomentiCat = (product.productInfo.idCatProds || []).some((idCat: any) => arrargomstr.includes(idCat));
hasCategoria = true;
} else {
hasCategoria = !catstr || (catstr && (product.productInfo.idCatProds || []).includes(catstr));
}
// Filtri per autore
const hasAuthor = !filtroAuthor || (product.productInfo.idAuthors || []).includes(filtroAuthor);
// Filtri per tipi di prodotto
const hasProductTypes = boolfiltroVuotoProductTypes
? true
: (product.productInfo.productTypes || []).some((item: any) => filtroProductTypes.includes(item));
// Filtri per esclusione di tipi di prodotto
const hasExcludeProductTypes = boolfiltroVuotoExcludeProductTypes
? false
: (product.productInfo.productTypes || []).every((item: any) => filtroExcludeProductTypes.includes(item));
// Filtri per editore
const hasPublished = boolfiltroVuotoEditore
? true
: editore.includes(product.productInfo.idPublisher);
// Filtri per collana
const hasCollana = boolfiltroVuotoCollane
? true
: (idCollane || []).some((item: ICollana) => product.productInfo.idCollana === item.idCollana)
// Filtri per GAS
const productgassel = !gasselstr || (cosaValue === shared_consts.PROD.GAS && product.idGasordine === gasselstr);
// Filtri per testo di ricerca
const searchMatch = lowerSearchTexts.length === 0 || lowerSearchTexts.some((searchTerm: string) => {
const codeMatch = new RegExp(`\\b${searchTerm}\\b`, 'i').test(lowerCode);
const allWordsPresent = searchTerm.split(/\s+/).every((word: string) =>
new RegExp(`\\b${word}\\b`, 'i').test(lowerName)
);
return codeMatch || allWordsPresent;
});
return (
searchMatch &&
hasAuthor &&
productgassel &&
hasProductTypes &&
(
hasPublished &&
hasCollana &&
hasCategoria &&
hasArgomentiCat
)
&&
!hasExcludeProductTypes
);
})
.sort((a, b) => getProductsSorted([a, b], sortField, sortDir)[0] === a ? -1 : 1);
console.log(' sortField=' + sortField)
console.log(' sortDir=' + sortDir)
console.log(' Filtro=' + arrargomstr)
console.log(' idCollane=' + idCollane)
console.log('PRODOTTI FILTRATI:', arrris.length)
return arrris
}
function calcArrProducts(generalista?: boolean) {
console.log('calcArrProducts (generalista=' + generalista + ')')
const searchtext = getSearchText();
let arrprod = [];
const filtroAuthor = filter.value.author || '';
const filtroProductTypes = optcatalogo.value.productTypes || [0];
const filtroExcludeProductTypes = optcatalogo.value.excludeproductTypes || [0];
const editore = getEditoreDaFiltrare(optcatalogo.value.editore);
const filtroPublishers = editore || [];
const idCollane = getIdCollaneDaFiltrare(optcatalogo.value.idCollane);
const filtroCollane = idCollane || [];
const arrargomstr = optcatalogo.value.argomenti && optcatalogo.value.argomenti.length > 0
? getArgomentiDaFiltrare(optcatalogo.value.argomenti)
: getArgomentiDaFiltrare(cat.value ? [cat.value] : []);
const catstr = cat.value || '';
const gasselstr = cosa.value === shared_consts.PROD.GAS ? idGasSel.value || '' : '';
let salva = false
// Se nel catalogo è stato già generato, allora gli passo quello.
const trovatocatalogo = getCatalogoByMyPage.value
if (trovatocatalogo?.lista_prodotti.length === 0) {
generalista = true
}
if (!generalista && (trovatocatalogo?.lista_prodotti.length > 0)) {
arrprod = trovatocatalogo?.lista_prodotti
} else {
arrprod = productStore.getProducts(cosa.value)
arrprod = filterProducts(
arrprod,
searchtext,
filtroAuthor,
filtroProductTypes,
filtroExcludeProductTypes,
filtroPublishers,
filtroCollane,
arrargomstr,
catstr,
gasselstr,
cosa.value,
filter.value.sort_field,
filter.value.sort_dir
);
salva = true
}
arrProducts.value = arrprod;
// console.log('arrprod', arrprod)
populateDataWithlinkIdTemplate();
generatearrProdToViewSorted(!generalista, salva);
loaddata();
refreshpage.value = false;
}
function generaListaLibri() {
// chiedi prima "Sei sicuro di rigenerare il catalogo?"
let risposta_si = false
$q.dialog({
title: 'Rigenera lista',
message: 'Sicuri di rigenerare questa lista di libri, perdendo l\'ordinamento attuale ?',
cancel: true,
persistent: true
}).onOk(() => {
calcArrProducts(true)
})
}
function getProductsFilteredByScheda(scheda: IMyScheda): IProduct[] {
let arrprod = productStore.getProducts(cosa.value) || [];
const filtroAuthor = filter.value.author || '';
const filtroProductTypes = scheda.productTypes || [0];
const filtroExcludeProductTypes = scheda.excludeproductTypes || [0];
const editore = getEditoreDaFiltrare(scheda.editore);
const filtroPublishers = editore || [];
const idCollane = getIdCollaneDaFiltrare(scheda.idCollane);
const filtroCollane = idCollane || [];
const arrargomstr = optcatalogo.value.argomenti && optcatalogo.value.argomenti.length > 0
? getArgomentiDaFiltrare(optcatalogo.value.argomenti)
: [];
const catstr = cat.value || '';
const gasselstr = cosa.value === shared_consts.PROD.GAS ? idGasSel.value || '' : '';
const trovatocatalogo = getCatalogoByMyPage.value
if (trovatocatalogo?.lista_prodotti.length > 0) {
arrprod = trovatocatalogo?.lista_prodotti
} else {
arrprod = filterProducts(
arrprod,
scheda.arrProdottiSpeciali || [],
filtroAuthor,
filtroProductTypes,
filtroExcludeProductTypes,
filtroPublishers,
filtroCollane,
arrargomstr,
catstr,
gasselstr,
cosa.value,
scheda?.sort_field,
scheda?.sort_dir
);
}
return arrprod;
}
/**
* Funzione che ordina un array di prodotti in base a un campo specifico
* @param arrprod array di prodotti da ordinare
* @param sort_field campo su cui effettuare l'ordinamento
* @param sort_dir direzione dell'ordinamento (1 asc, -1 desc)
* @returns array di prodotti ordinati
*/
function getProductsSorted(arrprod: IProduct[], sort_field: string, sort_dir: number): IProduct[] {
if (sort_field) {
console.log('--- Primi 10 elementi INIZIALI:');
arrprod.slice(0, 15).forEach((product, index) => {
console.log(
`${index + 1}. ${product.productInfo?.name} (${product.productInfo?.date_pub})`
);
});
// Crea una copia dell'array per non modificare l'originale
const sortedArr = [...arrprod].sort((a: IProduct, b: IProduct) => {
const valA = a.productInfo?.[sort_field] ?? (typeof a.productInfo?.[sort_field] === 'number' ? 0 : '');
const valB = b.productInfo?.[sort_field] ?? (typeof b.productInfo?.[sort_field] === 'number' ? 0 : '');
// Ordinamento per data
if (valA instanceof Date && valB instanceof Date) {
return sort_dir === 1 ? valA.getTime() - valB.getTime() : valB.getTime() - valA.getTime();
}
// Ordinamento per numeri
if (typeof valA === 'number' && typeof valB === 'number') {
return sort_dir === 1 ? valA - valB : valB - valA;
}
// Ordinamento per stringhe o altri tipi
const compA = valA.toString().toLowerCase();
const compB = valB.toString().toLowerCase();
return sort_dir === 1
? compA.localeCompare(compB)
: compB.localeCompare(compA);
});
// logga i primi N elementi, mostrando il nome del prodotto (productInfo.name e la data di pibblicazione : productinfo.date_pub
if (sortedArr.length > 0) {
console.log('Primi 15 elementi ordinati: ***** ');
sortedArr.slice(0, 15).forEach((product, index) => {
console.log(
`${index + 1}. ${product.productInfo?.name} (${product.productInfo?.date_pub})`
);
});
} else {
console.log('Nessun prodotto trovato.');
}
return sortedArr
}
return arrprod;
}
function addNextProductToTheView(arrproductfiltrati: IProduct[], indprod: number) {
try {
while (indprod < arrproductfiltrati.length) {
const rectrovato = arrProdToView.value.find(
(prodview: IProdView) => prodview.id === arrproductfiltrati[indprod]._id
);
if (!rectrovato) {
const myrec = arrproductfiltrati[indprod];
arrProdToView.value.push({ id: myrec._id });
return { myrec, added: true, indprod: indprod + 1 };
}
indprod++;
}
return { end: true };
} catch (e) {
console.error(e);
return { rec: null, indprod };
}
}
function getProdBySchedaRigaCol(recscheda: ISchedaSingola, pagina: number, riga: number, col: number) {
try {
return recscheda.arrProdToShow![pagina][riga][col]
} catch (e) {
return null
}
}
function generatearrProdToViewSorted(usaprodottiSalvati?: boolean, salva?: boolean) {
console.log('generatearrProdToViewSorted... usaprodottiSalvati=', usaprodottiSalvati, ' salva=', salva)
try {
// Svuota
arrProdToView.value = []
const trovatocatalogo = getCatalogoByMyPage.value
let arrGeneraleProdotti = []
if (usaprodottiSalvati && trovatocatalogo?.lista_prodotti.length > 0) {
} else {
arrGeneraleProdotti = arrProducts.value;
}
let indprod = 0
const indprodGenerale = 0
let indtotale = 0
let arrprod = []
for (const recscheda of optcatalogo.value.arrSchede!) {
if (recscheda && recscheda.scheda) {
const schedePerRiga = recscheda.scheda.numschede_perRiga || 1
const schedePerCol = recscheda.scheda.numschede_perCol || 1
const schedePerPagina = schedePerRiga * schedePerCol
let arrProdFiltrati: IProduct[] = []
if (usaprodottiSalvati && trovatocatalogo?.lista_prodotti.length > 0) {
arrProdFiltrati = trovatocatalogo?.lista_prodotti
} else {
if (recscheda.scheda.productTypes!.length > 0) {
// Filtra i prodotti in base ai filtri impostati !
arrProdFiltrati = getProductsFilteredByScheda(recscheda.scheda)
indprod = 0
} else {
if (recscheda.scheda.sort_field!) {
arrProdFiltrati = getProductsSorted(arrGeneraleProdotti, recscheda.scheda.sort_field, recscheda.scheda.sort_dir);
indprod = 0
} else {
indprod = indprodGenerale
arrProdFiltrati = arrGeneraleProdotti
}
}
}
let indadded = 0
recscheda.arrProdToShow = []
for (let pagina = 0; pagina < 600; pagina++) {
indadded = 0
let lastresultend = false
if (!recscheda.arrProdToShow[pagina]) {
recscheda.arrProdToShow[pagina] = [];
}
for (let giro = 0; giro < schedePerPagina; giro++) {
// Aggiunge il prossimo prodotto che non è stato ancora inserito
const result = addNextProductToTheView(arrProdFiltrati, indprod);
if (result.end) {
lastresultend = true
break; // Esci dal ciclo se non ci sono più prodotti disponibili
} else {
if (result.indprod)
indprod = result.indprod // Aggiorna indprod per il prossimo giro
if (result.myrec) {
const riga = Math.floor(indadded / schedePerCol)
const col = indadded % schedePerCol
if (!recscheda.arrProdToShow[pagina][riga]) {
recscheda.arrProdToShow[pagina][riga] = [];
}
arrprod.push(result.myrec)
recscheda.arrProdToShow[pagina][riga][col] = result.myrec
indadded++
indtotale++
// console.log('indadded', indadded)
if (optcatalogo.value.maxnumlibri! > 0) {
if (indtotale > optcatalogo.value.maxnumlibri!)
return
//} else {
// if (indtotale > 5000)
// return
}
}
}
}
if (lastresultend)
break; // Esci dal ciclo se non ci sono più prodotti disponibili
if (recscheda.numPagineMax! > 0) {
if (pagina + 1 >= recscheda.numPagineMax!)
break; // fine pagine
}
}
// console.log('*** arrProdToShow', recscheda.arrProdToShow)
}
// console.log('Fine Generazione')
}
// console.log(' FINE - generatearrProdToViewSorted !')
if (!usaprodottiSalvati && salva) {
if (trovatocatalogo) {
trovatocatalogo.lista_prodotti = arrprod
salvaListaProdotti(false)
}
}
} catch (e) {
console.error('Err', e)
}
// console.log('Fine...')
}
function salvaListaProdotti(ricarica: boolean) {
// Estrai solo gli ID dei prodotti filtrati
const myarr = [...getCatalogoByMyPage.value.lista_prodotti]
const productIds = myarr.map(product => product._id);
let mydata = {
lista_prodotti: productIds
}
// Salva gli ID dei prodotti nel catalogo
tools.saveFieldToServer($q, 'catalogs', getCatalogoByMyPage.value._id, mydata, true, false)
if (ricarica) {
generatearrProdToViewSorted(true, false);
}
}
/*function getProducts() {
let arrprod = productStore.getProducts(cosa.value)
if (!search.value) {
return arrprod
}
let lowerSearchText = search.value.toLowerCase();
let catstr = cat.value;
return arrprod.filter((product: IProduct) => {
let lowerName = product.productInfo.name!.toLowerCase();
const hasCategoria = !catstr || (catstr && product.productInfo.idCatProds?.includes(catstr));
return (product.productInfo.code!.includes(search.value) || lowerName.includes(lowerSearchText)) && hasCategoria
});
}*/
async function mounted() {
// console.log('mounted Catalogo')
tabcatalogo.value = tools.getCookie('TAB_CAT', 'visu')
loadpage.value = false
await productStore.loadProducts()
mycolumns.value = fieldsTable.getArrColsByTable('products')
searchList.value = [
{
visible: true,
label: 'Ricerca',
table: 'products',
key: 'titolo',
type: costanti.FieldType.select_by_server,
value: '',
// addall: true,
arrvalue: [],
useinput: true,
filter: null,
tablesel: 'products',
},
]
optauthors.value = productStore.getAuthors()
//++Todo: Per ora visualizzo solo il "Negozio" e non i GAS...
cosa.value = shared_consts.PROD.BOTTEGA
cat.value = tools.getCookie(tools.COOK_CATEGORIA, '')
//cosa.value = tools.getCookie(tools.COOK_COSA_PRODOTTI, shared_consts.PROD.GAS, true)
//if (cosa.value === shared_consts.PROD.TUTTI)
// Inizializza
loadpage.value = true
window.addEventListener('scroll', handleScroll);
calcArrProducts()
loaddata()
}
function loaddata() {
numRecLoaded.value = 20
}
// Remove the event listener on component destroy
onBeforeUnmount(() => {
window.removeEventListener('scroll', handleScroll);
});
function getCatProds() {
const arrcat = productStore.getCatProds(cosa.value)
const riscat: any = [{ label: 'Tutti', value: '', icon: undefined, color: undefined }]
for (const rec of arrcat) {
riscat.push({ label: rec.name, value: rec._id, icon: rec.icon, color: rec.color })
}
return riscat
}
function onLoadScroll(index: number, done: any) {
if (index >= 1) {
if (numRecLoaded.value < arrProducts.value.length) {
const step = 10
let mynrec = numRecLoaded.value + step
if (mynrec > arrProducts.value.length)
mynrec = arrProducts.value.length
numRecLoaded.value = mynrec
}
done()
} else {
done(true)
}
}
function filterFn(val: any, update: any, abort: any) {
update(() => {
const needle = val.toLowerCase();
optauthors.value = productStore.getAuthors().filter(v => {
const authorName = v.label.toLowerCase();
const wordsToSearch = needle.split(' ');
return wordsToSearch.every((word: any) => {
if (word.length > 1) {
return authorName.includes(word);
} else {
return authorName.split(' ').some((namePart: any) => namePart.startsWith(word));
}
});
});
});
}
function selauthor(id: string, value: string) {
filter.value.author = id
}
/*function searchval(newval: any, table: any, tablesel: any) {
console.log('REFRR searchval', newval, table, 'tablesel', tablesel)
if (newval) {
if (newval.hasOwnProperty('name')) {
search.value = newval.name
}
} else {
resetSearch()
}
}*/
const valoriopt = computed(() => (item: any, addall: boolean, addnone: boolean = false) => {
// console.log('valoriopt', item.table)
return globalStore.getTableJoinByName(item.table, addall, addnone, item.filter)
})
const loadImage = (src: any) => {
return new Promise((resolve, reject) => {
const img = new Image()
img.onload = () => resolve(img)
img.onerror = reject
img.src = src
})
}
function groupedPages(recscheda: ISchedaSingola) {
return recscheda.arrProdToShow
}
function generateStyleCatalogo(optcatalogo: IOptCatalogo) {
return {
}
}
function generateStylePageScheda(optcatalogo: IOptCatalogo, scheda: IMyScheda) {
const marginTop = scheda.dimensioni?.pagina?.dimensioni?.margini?.top ? tools.adjustSize(optcatalogo, scheda.dimensioni?.pagina?.dimensioni?.margini?.top) : (tools.adjustSize(optcatalogo, optcatalogo.dimensioni_def?.pagina?.margini?.top) || '')
const marginBottom = scheda.dimensioni?.pagina?.dimensioni?.margini?.bottom ? tools.adjustSize(optcatalogo, scheda.dimensioni?.pagina?.dimensioni?.margini?.bottom) : (tools.adjustSize(optcatalogo, optcatalogo.dimensioni_def?.pagina?.margini?.bottom) || '')
const marginLeft = scheda.dimensioni?.pagina?.dimensioni?.margini?.left ? tools.adjustSize(optcatalogo, scheda.dimensioni?.pagina?.dimensioni?.margini?.left) : (tools.adjustSize(optcatalogo, optcatalogo.dimensioni_def?.pagina?.margini?.left) || '')
const marginRight = scheda.dimensioni?.pagina?.dimensioni?.margini?.right ? tools.adjustSize(optcatalogo, scheda.dimensioni?.pagina?.dimensioni?.margini?.right) : (tools.adjustSize(optcatalogo, optcatalogo.dimensioni_def?.pagina?.margini?.right) || '')
const paddingTop = scheda.dimensioni?.pagina?.dimensioni?.padding?.top ? tools.adjustSize(optcatalogo, scheda.dimensioni?.pagina?.dimensioni?.padding?.top) : (tools.adjustSize(optcatalogo, optcatalogo.dimensioni_def?.pagina?.padding?.top) || '')
const paddingBottom = scheda.dimensioni?.pagina?.dimensioni?.padding?.bottom ? tools.adjustSize(optcatalogo, scheda.dimensioni?.pagina?.dimensioni?.padding?.bottom) : (tools.adjustSize(optcatalogo, optcatalogo.dimensioni_def?.pagina?.padding?.bottom) || '')
const paddingLeft = scheda.dimensioni?.pagina?.dimensioni?.padding?.left ? tools.adjustSize(optcatalogo, scheda.dimensioni?.pagina?.dimensioni?.padding?.left) : (tools.adjustSize(optcatalogo, optcatalogo.dimensioni_def?.pagina?.padding?.left) || '')
const paddingRight = scheda.dimensioni?.pagina?.dimensioni?.padding?.right ? tools.adjustSize(optcatalogo, scheda.dimensioni?.pagina?.dimensioni?.padding?.right) : (tools.adjustSize(optcatalogo, optcatalogo.dimensioni_def?.pagina?.padding?.right) || '')
// Esiste un immagine di sfondo specifica della singola pagina ?
const recimg = getSfondoImgCatalogo(scheda)
const backgroundImage = recimg.imagefile! ?? ''
const backgroundSize = recimg.fit
const width = scheda.dimensioni?.pagina?.dimensioni?.size?.width ? tools.adjustSize(optcatalogo, scheda.dimensioni?.pagina?.dimensioni?.size?.width) : (tools.adjustSize(optcatalogo, optcatalogo.dimensioni_def?.pagina?.size?.width) ?? '')
const height = scheda.dimensioni?.pagina?.dimensioni?.size?.height ? tools.adjustSize(optcatalogo, scheda.dimensioni?.pagina?.dimensioni?.size?.height) : (tools.adjustSize(optcatalogo, optcatalogo.dimensioni_def?.pagina?.size?.height) ?? '')
return {
marginBottom,
marginTop,
marginLeft,
marginRight,
paddingBottom,
paddingTop,
paddingLeft,
paddingRight,
backgroundImage,
backgroundSize,
'--width': width,
'--height': height,
...((width && width !== '0px') ? { width: `${width} !important` } : {}),
...((height && height !== '0px') ? { height: `${height} !important` } : {}) // Aggiungi l'altezza solo se è valorizzata
};
}
function generateStyleByPageDim(optcatalogo: IOptCatalogo, mypage: IDimensioni) {
const marginTop = mypage.margini?.top ? tools.adjustSize(optcatalogo, mypage.margini?.top) : (tools.adjustSize(optcatalogo, optcatalogo.dimensioni_def?.pagina?.margini?.top) || '')
const marginBottom = mypage.margini?.bottom ? tools.adjustSize(optcatalogo, mypage.margini?.bottom) : (tools.adjustSize(optcatalogo, optcatalogo.dimensioni_def?.pagina?.margini?.bottom) || '')
const marginLeft = mypage.margini?.left ? tools.adjustSize(optcatalogo, mypage.margini?.left) : (tools.adjustSize(optcatalogo, optcatalogo.dimensioni_def?.pagina?.margini?.left) || '')
const marginRight = mypage.margini?.right ? tools.adjustSize(optcatalogo, mypage.margini?.right) : (tools.adjustSize(optcatalogo, optcatalogo.dimensioni_def?.pagina?.margini?.right) || '')
const paddingTop = mypage.padding?.top ? tools.adjustSize(optcatalogo, mypage.padding?.top) : (tools.adjustSize(optcatalogo, optcatalogo.dimensioni_def?.pagina?.padding?.top) || '')
const paddingBottom = mypage.padding?.bottom ? tools.adjustSize(optcatalogo, mypage.padding?.bottom) : (tools.adjustSize(optcatalogo, optcatalogo.dimensioni_def?.pagina?.padding?.bottom) ?? '')
const paddingLeft = mypage.padding?.left ? tools.adjustSize(optcatalogo, mypage.padding?.left) : (tools.adjustSize(optcatalogo, optcatalogo.dimensioni_def?.pagina?.padding?.left) ?? '')
const paddingRight = mypage.padding?.right ? tools.adjustSize(optcatalogo, mypage.padding?.right) : (tools.adjustSize(optcatalogo, optcatalogo.dimensioni_def?.pagina?.padding?.right) ?? '')
// Esiste un immagine di sfondo specifica della singola pagina ?
const recimg = getSfondoImgCatalogo(null, mypage)
let fileimg = recimg.imagefile! ?? ''
let backgroundSize = recimg.fit
if (!fileimg) {
// Esiste un immagine di sfondo uguali per tutte le pagine ?
fileimg = optcatalogo.dimensioni_def?.pagina.imgsfondo?.imagefile
backgroundSize = optcatalogo.dimensioni_def?.pagina.imgsfondo?.fit
fileimg = fileimg ? `url(${tools.getDirUpload() + costanti.DIR_CATALOGO + fileimg})` : ''
}
const backgroundImage = fileimg ?? ''
const width = mypage.size?.width ? tools.adjustSize(optcatalogo, mypage.size?.width) : (tools.adjustSize(optcatalogo, optcatalogo.dimensioni_def?.pagina?.size?.width) ?? '')
const height = mypage.size?.height ? tools.adjustSize(optcatalogo, mypage.size?.height) : (tools.adjustSize(optcatalogo, optcatalogo.dimensioni_def?.pagina?.size?.height) ?? '')
return {
marginBottom,
marginTop,
marginLeft,
marginRight,
paddingBottom,
paddingTop,
paddingLeft,
paddingRight,
backgroundImage,
backgroundSize,
'--width': width,
'--height': height,
...((width && width !== '0px') ? { width: `${width} !important` } : {}),
...((height && height !== '0px') ? { height: `${height} !important` } : {}) // Aggiungi l'altezza solo se è valorizzata
};
}
function getWidthPagina(optcatalogo: IOptCatalogo, scheda: IMyScheda) {
return scheda.dimensioni?.pagina?.dimensioni?.size?.width ? tools.adjustSize(optcatalogo, scheda.dimensioni?.pagina?.dimensioni?.size?.width) : (tools.adjustSize(optcatalogo, optcatalogo.dimensioni_def?.pagina?.size?.width) ?? '')
}
function getHeightPagina(optcatalogo: IOptCatalogo, scheda: IMyScheda) {
return scheda.dimensioni?.pagina?.dimensioni?.size?.height ? tools.adjustSize(optcatalogo, scheda.dimensioni?.pagina?.dimensioni?.size?.height) : (tools.adjustSize(optcatalogo, optcatalogo.dimensioni_def?.pagina?.size?.height) ?? '')
}
function getStyleRowSeparator(recscheda: ISchedaSingola) {
const paddingLeft = tools.adjustSize(optcatalogo.value, recscheda.scheda?.dimensioni?.scheda_prodotto?.padding?.left) ?? '0px';
const paddingRight = tools.adjustSize(optcatalogo.value, recscheda.scheda?.dimensioni?.scheda_prodotto?.padding?.right) ?? '0px';
return {
paddingLeft: `${paddingLeft}`,
paddingRight: `${paddingRight}`,
};
}
function getStyleRow(recscheda: ISchedaSingola) {
const placeContent = 'center';
const width = tools.adjustSize(optcatalogo.value, recscheda.scheda?.dimensioni?.riga?.size?.width) ?? '';
const height = tools.adjustSize(optcatalogo.value, recscheda.scheda?.dimensioni?.riga?.size?.height) ?? '';
const marginTop = tools.adjustSize(optcatalogo.value, recscheda.scheda?.dimensioni?.riga?.margini?.top) || '0';
const marginBottom = tools.adjustSize(optcatalogo.value, recscheda.scheda?.dimensioni?.riga?.margini?.bottom) || '0';
const marginLeft = tools.adjustSize(optcatalogo.value, recscheda.scheda?.dimensioni?.riga?.margini?.left) || '0';
const marginRight = tools.adjustSize(optcatalogo.value, recscheda.scheda?.dimensioni?.riga?.margini?.right) || '0';
const paddingTop = tools.adjustSize(optcatalogo.value, recscheda.scheda?.dimensioni?.riga?.padding?.top) || '0';
const paddingBottom = tools.adjustSize(optcatalogo.value, recscheda.scheda?.dimensioni?.riga?.padding?.bottom) || '0';
const paddingLeft = tools.adjustSize(optcatalogo.value, recscheda.scheda?.dimensioni?.riga?.padding?.left) || '0';
const paddingRight = tools.adjustSize(optcatalogo.value, recscheda.scheda?.dimensioni?.riga?.padding?.right) || '0';
const out: any = {
placeContent,
flex: `0 1 ${width} !important`,
margin: `${marginTop} ${marginRight} ${marginBottom} ${marginLeft}`,
padding: `${paddingTop} ${paddingRight} ${paddingBottom} ${paddingLeft}`,
...((width && width !== '0px') ? { width: `${width} !important` } : {}),
...((height && height !== '0px') ? { height: `${height} !important` } : {})
}
/*if (width) {
out.width = `${width} !important`
}
if (height) {
out.height = `${height} !important`
}*/
return out
}
function getStyleSchedaProdotto(recscheda: ISchedaSingola) {
const placeContent = 'center';
const width = tools.adjustSize(optcatalogo.value, recscheda.scheda?.dimensioni?.scheda_prodotto?.size?.width) ?? '100px';
const height = tools.adjustSize(optcatalogo.value, recscheda.scheda?.dimensioni?.scheda_prodotto?.size?.height);
const marginTop = tools.adjustSize(optcatalogo.value, recscheda.scheda?.dimensioni?.scheda_prodotto?.margini?.top) || '0px';
const marginBottom = tools.adjustSize(optcatalogo.value, recscheda.scheda?.dimensioni?.scheda_prodotto?.margini?.bottom) || '0px';
const marginLeft = tools.adjustSize(optcatalogo.value, recscheda.scheda?.dimensioni?.scheda_prodotto?.margini?.left) || '0px';
const marginRight = tools.adjustSize(optcatalogo.value, recscheda.scheda?.dimensioni?.scheda_prodotto?.margini?.right) || '0px';
const paddingTop = tools.adjustSize(optcatalogo.value, recscheda.scheda?.dimensioni?.scheda_prodotto?.padding?.top) || '0px';
const paddingBottom = tools.adjustSize(optcatalogo.value, recscheda.scheda?.dimensioni?.scheda_prodotto?.padding?.bottom) || '0px';
const paddingLeft = tools.adjustSize(optcatalogo.value, recscheda.scheda?.dimensioni?.scheda_prodotto?.padding?.left) || '0px';
const paddingRight = tools.adjustSize(optcatalogo.value, recscheda.scheda?.dimensioni?.scheda_prodotto?.padding?.right) || '0px';
return {
placeContent,
alignSelf: 'flex-start',
flex: `0 1 ${width} !important`,
margin: `${marginTop} ${marginRight} ${marginBottom} ${marginLeft}`,
padding: `${paddingTop} ${paddingRight} ${paddingBottom} ${paddingLeft}`,
...((height && height !== '0px') ? { height: `${height} !important` } : {}) // Aggiungi l'altezza solo se è valorizzata
};
}
function containsProducts(page: IProduct[][]) {
return page && page.length > 0 && page[0] && page[0].length > 0
}
function naviga(path: string) {
router.push(path)
}
function updateProducts(arr: any) {
if (getCatalogoByMyPage.value) {
getCatalogoByMyPage.value.lista_prodotti = [...arr]
salvaListaProdotti(true)
}
}
function addProductToList(element: IProduct) {
// console.log('addProductToList', element)
if (element) {
// add this record to lista_prodotti
if (getCatalogoByMyPage.value && !getCatalogoByMyPage.value.lista_prodotti.some((p) => p._id === element._id)) {
// inserire il record in cima
const arr = getCatalogoByMyPage.value.lista_prodotti
arr.unshift(element)
updateProducts(arr)
addnewProd.value = false
}
}
}
function clickaddNewBook() {
addnewProd.value = true
}
onMounted(mounted)
return {
userStore,
costanti,
tools,
toolsext,
search,
cosa,
shared_consts,
getCatProds,
cat,
idGasSel,
productStore,
t,
loadpage,
refreshpage,
componentToFixRef,
isFixed,
arrProducts,
show_hide,
onLoadScroll,
numRecLoaded,
arrLoaded,
filter,
optauthors,
filterFn,
selauthor,
searchList,
fieldsTable,
valoriopt,
labelcombo,
mycolumns,
tabvisu,
getSearchText,
pdfContent,
tabcatalogo,
groupedPages,
getProdBySchedaRigaCol,
generateStylePageScheda,
generateStyleCatalogo,
getStyleRow,
getStyleSchedaProdotto,
getWidthPagina,
getHeightPagina,
getStyleRowSeparator,
generateStyleByPageDim,
containsProducts,
updateOptCatalogo,
optcatalogo,
getTestoIntroduttivo,
ispageCatalogata,
naviga,
getTitoloCatalogo,
getTitoloPagina,
generaListaLibri,
lista_prodotti,
updateProducts,
clickaddNewBook,
addProductToList,
addnewProd,
}
}
})