Files
myprojplanet_vite/src/views/ecommerce/catalogo/catalogo.ts

2185 lines
73 KiB
TypeScript
Raw Normal View History

2025-03-01 14:14:43 +01:00
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 { CTitleBanner } from '@src/components/CTitleBanner';
import { CMySelect } from '@src/components/CMySelect';
import { CMyValueDb } from '@src/components/CMyValueDb';
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 html2pdf from 'html2pdf.js';
import { PDFDocument } from 'pdf-lib';
import { saveAs } from 'file-saver';
2025-03-01 14:14:43 +01:00
import type {
IOptCatalogo,
IDimensioni,
IFilterCatalogo,
IMyScheda,
IProdView,
IProduct,
ISchedaSingola,
ISearchList,
ICatalog,
IImg,
IText,
ICollana,
2025-04-24 19:31:34 +02:00
IOptRigenera,
IOpAndOr,
2025-03-01 14:14:43 +01:00
} from 'model';
import { IMyPage } from 'model';
import { fieldsTable } from '@store/Modules/fieldsTable';
import { useCatalogStore } from '@src/store/CatalogStore';
2024-01-30 14:00:48 +01:00
export default defineComponent({
name: 'Catalogo',
components: {
CContainerCatalogoCard,
CProductCard,
CSelectUserActive,
CMySelect,
CProductTable,
CSearchProduct,
CMyDialog,
CMyValueDb,
CTitleBanner,
},
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();
2024-01-30 14:00:48 +01:00
2025-05-15 22:37:39 +02:00
const myCatalog = ref<ICatalog | null>(null as ICatalog);
const rigeneraLibri = ref(false);
2025-04-24 19:31:34 +02:00
const search = ref('');
const optauthors = ref(<any>[]);
2024-05-08 16:07:42 +02:00
const pdfContent = ref(null);
const addnewProd = ref(false);
const widthpdf = ref('8.88');
const heightpdf = ref('12.31');
const compressionepdf = ref('prepress');
const ismounting = ref(false);
const pdfColumns = [
{ name: 'name', label: 'Nome', field: 'name', align: 'left' },
{ name: 'pdf', label: 'PDF', field: 'pdf', align: 'left' },
{ name: 'data', label: 'Data', field: 'data', align: 'left' },
{ name: 'azioni', label: 'Azioni', field: 'azioni', align: 'center' },
];
const pdfRows = computed(() => [
{
name: 'PDF Generato',
2025-05-15 22:37:39 +02:00
pdf: myCatalog.value.pdf_generato,
data: myCatalog.value.data_generato,
showButton: myCatalog.value.data_generato !== myCatalog.value.data_online,
buttonLabel: 'Pubblica PDF OnLine',
action: pubblicaPDF,
},
{
name: 'PDF Generato Stampa',
2025-05-15 22:37:39 +02:00
pdf: myCatalog.value.pdf_generato_stampa,
data: myCatalog.value.data_generato_stampa,
showButton: myCatalog.value.data_generato_stampa !== myCatalog.value.data_online_stampa,
buttonLabel: 'Pubblica PDF Stampa',
action: pubblicaPDFStampa,
},
]);
2025-04-24 19:31:34 +02:00
const optDisp = ref([
{ label: 'Tutti', value: costanti.DISP.TUTTI },
{ label: 'Disponibili', value: costanti.DISP.DISPONIBILI },
{ label: 'Esauriti', value: costanti.DISP.ESAURITI },
]);
2025-04-24 19:31:34 +02:00
const optRigeneraModalita = ref([
{ label: 'Sovrascrivi', value: costanti.RIGENERAMOD.SOVRASCRIVI },
{ label: 'Aggiungi solo', value: costanti.RIGENERAMOD.AGGIUNGI_SOLO },
]);
2025-04-24 19:31:34 +02:00
const optStato = ref([
{ label: 'Tutti', value: costanti.STATO.TUTTI },
{ label: 'In Commercio', value: costanti.STATO.IN_COMMERCIO },
{ label: 'Prossima Uscita', value: costanti.STATO.SOLO_PROSSIMA_USCITA },
{ label: 'Prevendita', value: costanti.STATO.PREVENDITA },
{ label: 'Non Vendibile', value: costanti.STATO.NON_VENDIBILE },
]);
2025-04-24 19:31:34 +02:00
const generatinglist = ref(false);
2025-04-24 19:31:34 +02:00
const optrigenera = ref<IOptRigenera>({
visibilitaDisp: costanti.DISP.DISPONIBILI,
stato: costanti.STATO.IN_COMMERCIO,
rig_mod: costanti.RIGENERAMOD.SOVRASCRIVI,
});
2025-04-24 19:31:34 +02:00
const optcatalogo = ref(<IOptCatalogo>{ ...props.modelValue });
const ispageCatalogata = computed(() => {
2025-05-15 22:37:39 +02:00
return !!myCatalog.value;
});
const filtroStrApplicato = computed(() => {
return optcatalogo.value.showListaArgomenti
? 'un Argomento'
: optcatalogo.value.showListaCollane
? 'una Collana'
: false;
});
const showListaFiltrata = computed(() => {
return optcatalogo.value.showListaArgomenti ? true : optcatalogo.value.showListaCollane ? true : false;
});
const getPdfFilename = () => {
let myfilename = optcatalogo.value.pdf_filename ?? 'catalogo_completo';
2025-05-15 22:37:39 +02:00
const catalog = myCatalog.value;
if (catalog) {
myfilename = productStore.getPathByPage(catalog.idPageAssigned);
}
return myfilename;
};
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(
optrigenera.value,
(newVal) => {
tools.setCookie((showListaFiltrata.value ? 'INC_ES_' : '') + 'VIS_DISP', newVal.visibilitaDisp);
tools.setCookie((showListaFiltrata.value ? 'INC_ES_' : '') + 'VIS_STATO', newVal.stato);
tools.setCookie((showListaFiltrata.value ? 'INC_ES_' : '') + 'RIG_MOD', newVal.rig_mod);
if (showListaFiltrata.value) calcArrProducts();
},
{ deep: true }
);
2025-04-24 19:31:34 +02:00
/*watch(optcatalogo, (newValue) => {
emit('update:modelValue', newValue);
}, { deep: true });*/
2024-10-31 23:23:06 +01:00
const filter = ref(<IFilterCatalogo>{
2024-05-04 14:49:09 +02:00
author: '',
publisher: '',
type: '',
ageGroup: '',
});
2024-01-30 14:00:48 +01:00
const cosa = ref(0);
const cat = ref('');
const collana = ref('');
const idGasSel = ref('');
const loadpage = ref(false);
const show_hide = ref(false);
2024-01-30 14:00:48 +01:00
const mycolumns = ref([]);
const catalogStore = useCatalogStore();
const tabvisu = ref('categorie');
const tabcatalogo = ref('lista');
const searchList = ref([] as ISearchList[]);
const arrProducts = ref<IProduct[]>([]);
const arrProdToView = ref<IProdView[]>([]);
2024-01-30 14:00:48 +01:00
const numRecLoaded = ref(0);
2024-05-04 14:49:09 +02:00
2024-01-30 14:00:48 +01:00
// 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;
});
2024-05-04 14:49:09 +02:00
const arrLoaded = computed(() => {
if (arrProducts.value && numRecLoaded.value) return arrProducts.value.slice(0, numRecLoaded.value);
2024-05-04 14:49:09 +02:00
else {
return [];
2024-05-04 14:49:09 +02:00
}
});
2024-05-04 14:49:09 +02:00
const getTestoIntroduttivo = computed(() => (recscheda: ISchedaSingola) => {
let testo = recscheda.scheda!.dimensioni.pagina?.testo_up?.contenuto;
if (recscheda.scheda!.isPagIntro) {
2025-05-15 22:37:39 +02:00
const catalog = myCatalog.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);
2025-05-15 22:37:39 +02:00
const catalog = myCatalog.value;
let clcol = '';
if (catalog?.pagina_introduttiva_sfondo_nero) {
clcol = `text-white`;
}
testo = `<span class="book-pagina-title ${clcol}">` + testo + `</span>`;
return testo;
});
2024-01-30 14:00:48 +01:00
// 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;
2024-01-30 14:00:48 +01:00
// Update the isFixed ref based on the scroll position
isFixed.value = scrollTop > threshold;
};
watch(
() => cat.value,
(newval, oldval) => {
if (showListaFiltrata.value) {
if (loadpage.value) {
tools.setCookie(getKeyCatAtLoad(), cat.value.toString());
filter.value.author = ''; // disattivo il filtro autore
resetSearch();
calcArrProducts();
}
}
2025-04-24 19:31:34 +02:00
}
);
watch(
() => collana.value,
(newval, oldval) => {
if (showListaFiltrata.value) {
if (loadpage.value) {
tools.setCookie(getKeyCollanaAtLoad(), collana.value.toString());
filter.value.author = ''; // disattivo il filtro autore
resetSearch();
calcArrProducts();
}
}
}
);
2024-05-04 14:49:09 +02:00
watch(
() => idGasSel.value,
(newval, oldval) => {
calcArrProducts();
2024-01-30 14:00:48 +01:00
}
);
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
collana.value = '';
if (loadpage.value) tools.setCookie(getKeyCatAtLoad(), '');
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 = '';
collana.value = '';
if (loadpage.value) tools.setCookie(getKeyCatAtLoad(), '');
}
calcArrProducts();
}
}
);
2024-01-30 14:00:48 +01:00
watch(
() => optcatalogo.value.aggiorna,
(newval, oldval) => {
// console.log('Aggiorna array...');
generatearrProdToViewSorted();
}
);
function resetSearch() {
const mialista = getSearchList();
2025-03-01 14:14:43 +01:00
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 : '';
2025-03-01 14:14:43 +01:00
}
function getTitoloCatalogo(): string {
2025-05-15 22:37:39 +02:00
const trovatocatalogo = myCatalog.value;
2025-03-01 14:14:43 +01:00
return trovatocatalogo ? trovatocatalogo.title : 'Catalogo';
}
function getReferentiCatalogo(): string {
2025-05-15 22:37:39 +02:00
const trovatocatalogo = myCatalog.value;
if (trovatocatalogo && trovatocatalogo.referenti && trovatocatalogo.referenti.length > 0) {
return trovatocatalogo.referenti.join(', ');
} else {
return '[Nessun Referente]';
}
}
function getImgIntroCatalogo(scheda: IMyScheda): IImg {
2025-05-15 22:37:39 +02:00
const trovatocatalogo = myCatalog.value;
2025-02-05 12:13:36 +01:00
let imagefile = '';
let fit = 'contain';
2025-02-05 12:13:36 +01:00
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 {
2025-05-15 22:37:39 +02:00
const trovatocatalogo = myCatalog.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';
}
2025-02-05 12:13:36 +01:00
// 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})`
: '';
}
2025-03-26 23:23:35 +01:00
}
if (!imagefile) {
let myimg = costanti.CATALOGHI.PAG_SFONDO_DEFAULT;
2025-03-26 23:23:35 +01:00
if (scheda.isPagIntro) {
myimg = costanti.CATALOGHI.PAG_INTRO_DEFAULT;
2025-03-26 23:23:35 +01:00
}
// 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!;
}
2025-02-05 12:13:36 +01:00
return { imagefile, fit };
}
function getIdCollaneDaFiltrare(def_idCollane?: string[]) {
let idCollane: string[] = [];
// Cerca se nella lista cataloghi c'è la Collana di questa Pagina !
2025-05-15 22:37:39 +02:00
const trovatocatalogo = myCatalog.value;
if (trovatocatalogo) {
idCollane = trovatocatalogo.idCollane! || [];
2025-02-05 12:13:36 +01:00
} else {
idCollane = def_idCollane || [];
2025-02-05 12:13:36 +01:00
}
return idCollane;
2025-02-05 12:13:36 +01:00
}
2025-02-11 18:58:06 +01:00
function getArgomentiDaFiltrare(def_argomenti?: string[]) {
let argomenti: string[] = [];
2025-02-11 18:58:06 +01:00
// Cerca se nella lista cataloghi c'è la Collana di questa Pagina !
2025-05-15 22:37:39 +02:00
const trovatocatalogo = myCatalog.value;
2025-02-11 18:58:06 +01:00
if (trovatocatalogo) {
argomenti = trovatocatalogo.argomenti! || [];
2025-02-11 18:58:06 +01:00
} else {
2025-03-01 14:14:43 +01:00
if (def_argomenti && def_argomenti.length > 0) {
argomenti = def_argomenti;
2025-03-01 14:14:43 +01:00
} else {
argomenti = [];
2025-03-01 14:14:43 +01:00
}
2025-02-11 18:58:06 +01:00
}
return argomenti;
2025-02-11 18:58:06 +01:00
}
function getidTipoFormatoDaFiltrare(def_idTipoFormato?: number[]) {
let idTipoFormato: number[] = [];
// Cerca se nella lista cataloghi c'è la Collana di questa Pagina !
2025-05-15 22:37:39 +02:00
const trovatocatalogo = myCatalog.value;
if (trovatocatalogo) {
idTipoFormato = trovatocatalogo.idTipoFormato! || [];
} else {
if (def_idTipoFormato && def_idTipoFormato.length > 0) {
idTipoFormato = def_idTipoFormato;
} else {
idTipoFormato = [];
}
}
return idTipoFormato;
}
function getEditoreDaFiltrare(def_editori?: string[]) {
let editore: string[] = [];
// Cerca se nella lista cataloghi c'è la Collana di questa Pagina !
2025-05-15 22:37:39 +02:00
const trovatocatalogo = myCatalog.value;
if (trovatocatalogo) {
editore = trovatocatalogo.editore! || [];
} else {
editore = def_editori || [];
}
return editore;
}
2024-11-28 16:04:48 +01:00
function populateDataWithlinkIdTemplate() {
// console.log('populateDataWithlinkIdTemplate')
2024-11-28 16:04:48 +01:00
if (optcatalogo.value) {
// LINK PAGINA
if (optcatalogo.value.dimensioni_def.linkIdTemplate) {
const reccatalog = globalStore.sovrascriviPaginaDefaultFromTemplate(
optcatalogo.value.dimensioni_def.linkIdTemplate,
optcatalogo.value.dimensioni_def
);
if (reccatalog) {
optcatalogo.value.dimensioni_def.pagina = { ...reccatalog.dimensioni_def.pagina };
}
}
if (optcatalogo.value.print_linkIdTemplate) {
const reccat2 = globalStore.sovrascriviAreadistampaFromTemplate(
optcatalogo.value.print_linkIdTemplate,
optcatalogo.value
);
if (reccat2) {
const optcatalogo2 = { ...optcatalogo.value };
// optcatalogo2.areadistampa = { ...reccat2.areadistampa};
optcatalogo2.areadistampa.margini = reccat2.areadistampa.margini;
optcatalogo2.areadistampa.unit = reccat2.areadistampa.unit;
optcatalogo2.areadistampa.scalecanvas = reccat2.areadistampa.scalecanvas;
optcatalogo2.areadistampa.scale_printable = reccat2.areadistampa.scale_printable;
optcatalogo2.areadistampa.format = reccat2.areadistampa.format;
optcatalogo2.areadistampa.orientation = reccat2.areadistampa.orientation;
optcatalogo2.areadistampa.compress = reccat2.areadistampa.compress;
// optcatalogo.value = optcatalogo2;
// optcatalogo.value.areadistampa.margini = { left: '50'};
}
// console.log('areadistampa', optcatalogo.value.areadistampa)
}
for (const recscheda of optcatalogo.value.arrSchede!) {
2024-11-28 16:04:48 +01:00
if (recscheda.scheda?.linkIdTemplate) {
// ricopia da Template:
const myscheda = globalStore.sovrascriviSchedaFromTemplate(
recscheda.scheda?.linkIdTemplate,
recscheda,
optcatalogo.value
);
2024-11-28 16:04:48 +01:00
if (myscheda) {
recscheda.scheda = { ...myscheda };
2024-11-28 16:04:48 +01:00
}
}
}
}
2025-03-01 14:14:43 +01:00
// console.log(' FINE - populateDataWithlinkIdTemplate')
2024-11-28 16:04:48 +01:00
}
2025-03-26 23:23:35 +01:00
function filterProducts(
products: IProduct[],
searchtext: string | string[],
filtroAuthor: string,
filtroProductTypes: number[],
filtroExcludeProductTypes: number[],
2025-04-24 19:31:34 +02:00
filtroidTipologie: number[],
filtroidTipoFormato: number[],
2025-03-26 23:23:35 +01:00
editore: string[],
idCollane: string[],
2025-03-26 23:23:35 +01:00
arrargomstr: any[],
op_andor: IOpAndOr,
2025-03-26 23:23:35 +01:00
catstr: string,
collanastr: string,
2025-03-26 23:23:35 +01:00
gasselstr: string,
cosaValue: any,
sortField?: string,
sortDir?: number
2025-03-26 23:23:35 +01:00
): IProduct[] {
const lowerSearchTexts = Array.isArray(searchtext)
? searchtext.map((text: string) =>
text
.toLowerCase()
.trim()
.replace(/[-@:=]/g, '')
)
: [
searchtext
.toLowerCase()
.trim()
.replace(/[-@:=]/g, ''),
];
2025-03-26 23:23:35 +01:00
const boolfiltroVuotoProductTypes =
filtroProductTypes.length === 0 || (filtroProductTypes.length === 1 && filtroProductTypes[0] === 0);
const boolfiltroVuotoExcludeProductTypes = filtroExcludeProductTypes.length === 0;
2025-04-24 19:31:34 +02:00
const boolfiltroVuotoidTipologie = filtroidTipologie.length === 0;
const boolfiltroVuotoidTipoFormato = filtroidTipoFormato.length === 0;
2025-03-26 23:23:35 +01:00
const boolfiltroVuotoEditore = editore.length === 0;
const boolfiltroVuotoCollane = idCollane.length === 0;
const boolfiltroVuotoArgomenti = arrargomstr.length === 0;
const se_tutti_veri = op_andor.condition_andor === costanti.OP_ANDOR.OP_AND;
2025-05-15 22:37:39 +02:00
const trovatocatalogo = myCatalog.value;
if (
boolfiltroVuotoProductTypes &&
boolfiltroVuotoExcludeProductTypes &&
boolfiltroVuotoidTipologie &&
boolfiltroVuotoidTipoFormato &&
boolfiltroVuotoEditore &&
boolfiltroVuotoCollane &&
boolfiltroVuotoArgomenti &&
catstr === '' &&
collanastr === ''
) {
// Nessun filtro selezionato, pertanto non mostrare niente!
return [];
}
const arrris = products
2025-03-26 23:23:35 +01:00
.filter((product: IProduct) => {
if (!product || !product.productInfo) {
console.error('product or product.productInfo is null');
return false;
}
2024-10-31 23:23:06 +01:00
2025-04-22 18:30:42 +02:00
// il prodotto dev'essere disponibile
2025-04-24 19:31:34 +02:00
//if (!productStore.isPubblicato(product.productInfo))
// return false
if (
!(
optrigenera.value.visibilitaDisp === costanti.DISP.TUTTI ||
(optrigenera.value.visibilitaDisp === costanti.DISP.ESAURITI && productStore.isEsaurito(product)) ||
(optrigenera.value.visibilitaDisp === costanti.DISP.DISPONIBILI &&
(productStore.isDisponibile(product) || productStore.isPrevendita(product.productInfo)))
)
) {
2025-04-24 19:31:34 +02:00
return false;
}
if (
!(
optrigenera.value.stato === costanti.STATO.TUTTI ||
(optrigenera.value.stato === costanti.STATO.IN_COMMERCIO &&
productStore.isPubblicato(product.productInfo)) ||
(optrigenera.value.stato === costanti.STATO.SOLO_PROSSIMA_USCITA &&
productStore.isProssimaUscita(product.productInfo)) ||
(optrigenera.value.stato === costanti.STATO.PREVENDITA &&
productStore.isPrevendita(product.productInfo)) ||
(optrigenera.value.stato === costanti.STATO.NON_VENDIBILE &&
productStore.isNonVendibile(product.productInfo))
)
) {
2025-04-24 19:31:34 +02:00
return false;
}
2025-04-22 18:30:42 +02:00
2025-03-01 14:14:43 +01:00
const lowerName = (product.productInfo.name || '').toLowerCase();
const lowerCode = (product.productInfo.code || '').toLowerCase();
2024-10-31 23:23:06 +01:00
const boolfiltroVuotoCat = product.productInfo.idCatProds?.length === 0;
2025-03-26 23:23:35 +01:00
// Filtri per argomenti e categorie
let hasCategoria = se_tutti_veri;
let hasArgomentiCat = se_tutti_veri;
if (arrargomstr && arrargomstr.length > 0) {
2025-03-26 23:23:35 +01:00
hasArgomentiCat = (product.productInfo.idCatProds || []).some((idCat: any) => arrargomstr.includes(idCat));
hasCategoria = se_tutti_veri;
2025-02-11 18:58:06 +01:00
} else {
if (optcatalogo.value.showListaArgomenti) {
const isCatVuoto = boolfiltroVuotoCat || (product.productInfo.idCatProds || []).length === 0;
const isCatSenzaArgomento = catstr === costanti.NO_CATEGORY;
const isCatCorretto = !catstr || (product.productInfo.idCatProds || []).includes(catstr);
hasCategoria = isCatSenzaArgomento && isCatVuoto ? true : isCatCorretto;
hasArgomentiCat = boolfiltroVuotoArgomenti ? se_tutti_veri : hasArgomentiCat;
}
}
let hasCollana = se_tutti_veri;
let hasCollanaStr = se_tutti_veri;
if (idCollane && idCollane.length > 0) {
hasCollanaStr = idCollane.includes(product.productInfo.idCollana);
hasCollana = se_tutti_veri;
} else {
if (optcatalogo.value.showListaCollane) {
const isCollanaVuoto = boolfiltroVuotoCollane || (product.productInfo.idCollana || []).length === 0;
const isCollanaSenzaColl = collanastr === costanti.NO_CATEGORY;
const isCollanaCorretto = !collanastr || product.productInfo.idCollana === collanastr;
hasCollana = isCollanaSenzaColl && isCollanaVuoto ? true : isCollanaCorretto;
hasCollanaStr = boolfiltroVuotoCollane ? se_tutti_veri : hasCollanaStr;
}
}
// Filtri per collana
/*
const hasCollana = boolfiltroVuotoCollane
? se_tutti_veri
: (idCollane || []).includes(product.productInfo.idCollana);
*/
2025-03-26 23:23:35 +01:00
// Filtri per autore
const hasAuthor = !filtroAuthor || (product.productInfo.idAuthors || []).includes(filtroAuthor);
2024-10-31 23:23:06 +01:00
2025-03-26 23:23:35 +01:00
// 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));
2024-10-31 23:23:06 +01:00
2025-04-24 19:31:34 +02:00
const hasidTipologie = boolfiltroVuotoidTipologie
? true
: filtroidTipologie.includes(product.arrvariazioni?.[0].idTipologia);
const hasidTipoFormato = boolfiltroVuotoidTipoFormato
? true
: filtroidTipoFormato.includes(product.arrvariazioni?.[0].idTipoFormato);
2025-03-26 23:23:35 +01:00
// Filtri per editore
const hasPublished = boolfiltroVuotoEditore
? se_tutti_veri
2025-03-26 23:23:35 +01:00
: editore.includes(product.productInfo.idPublisher);
// Filtri per GAS
const productgassel =
!gasselstr || (cosaValue === shared_consts.PROD.GAS && product.idGasordine === gasselstr);
2025-03-26 23:23:35 +01:00
// 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;
});
2024-10-31 23:23:06 +01:00
// Funzione che valuta un gruppo in base a OP_AND o OP_OR
// Raccolgo tutti i gruppi attivi
const filtri = [hasArgomentiCat, hasCategoria, hasCollana, hasCollanaStr, hasPublished];
// Decido se combinare in AND o OR sulla base della scelta globale
let risult = searchMatch && hasAuthor && productgassel && hasidTipologie && hasidTipoFormato;
if (op_andor.condition_andor === costanti.OP_ANDOR.OP_AND) {
risult = risult && filtri.every(Boolean); // Tutti i gruppi devono essere veri
} else {
risult = risult && filtri.some(Boolean);
}
return risult;
// && !hasExcludeProductTypes
2025-03-26 23:23:35 +01:00
})
.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;
2025-03-26 23:23:35 +01:00
}
2024-11-28 16:04:48 +01:00
2025-04-24 19:31:34 +02:00
async function calcArrProducts(generalista?: boolean) {
// console.log('calcArrProducts (generalista=' + generalista + ')');
if (generalista) {
// Devono esistere tutti i prodotti
await productStore.loadProducts(true);
}
if (!loadpage.value) return;
2025-04-24 19:31:34 +02:00
generatinglist.value = true;
2025-04-24 19:31:34 +02:00
2025-03-26 23:23:35 +01:00
const searchtext = getSearchText();
let arrprod = [];
2025-03-26 23:23:35 +01:00
const filtroAuthor = filter.value.author || '';
const filtroProductTypes = optcatalogo.value.productTypes || [0];
const filtroExcludeProductTypes = optcatalogo.value.excludeproductTypes || [0];
2025-04-24 19:31:34 +02:00
const filtroidTipologie = optcatalogo.value.idTipologie || [];
const filtroidTipoFormato = getidTipoFormatoDaFiltrare(optcatalogo.value.idTipoFormato);
2025-03-26 23:23:35 +01:00
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] : []);
2025-03-26 23:23:35 +01:00
const catstr = cat.value || '';
const collanastr = collana.value || '';
2025-03-26 23:23:35 +01:00
const gasselstr = cosa.value === shared_consts.PROD.GAS ? idGasSel.value || '' : '';
let salva = false;
// Se nel catalogo è stato già generato, allora gli passo quello.
2025-05-15 22:37:39 +02:00
const trovatocatalogo = myCatalog.value;
// if (editore) console.log('FILTRO editore', editore);
2025-04-24 19:31:34 +02:00
if (showListaFiltrata.value) {
generalista = true;
}
2025-05-15 22:37:39 +02:00
/*if (myCatalog.value.lista_prodotti.length === 0) {
generalista = true
}*/
let op_andor: IOpAndOr = {
condition_andor:
trovatocatalogo?.condition_andor !== undefined ? trovatocatalogo.condition_andor : costanti.OP_ANDOR.OP_AND,
};
if (!generalista && myCatalog.value?.lista_prodotti?.length > 0) {
2025-05-15 22:37:39 +02:00
arrprod = myCatalog.value.lista_prodotti;
} else {
arrprod = productStore.getProducts(cosa.value);
arrprod = filterProducts(
arrprod,
searchtext,
filtroAuthor,
filtroProductTypes,
filtroExcludeProductTypes,
2025-04-24 19:31:34 +02:00
filtroidTipologie,
filtroidTipoFormato,
filtroPublishers,
filtroCollane,
arrargomstr,
op_andor,
catstr,
collanastr,
gasselstr,
cosa.value,
filter.value.sort_field,
filter.value.sort_dir
);
salva = true;
}
2025-03-26 23:23:35 +01:00
arrProducts.value = arrprod;
// console.log('arrprod', arrprod)
2025-03-26 23:23:35 +01:00
populateDataWithlinkIdTemplate();
// Ordina la lista
generatearrProdToViewSorted(!generalista, salva, !showListaFiltrata.value);
2025-03-26 23:23:35 +01:00
loaddata();
if (generalista) {
2025-05-15 22:37:39 +02:00
const catalog = myCatalog.value;
if (catalog && !showListaFiltrata.value) {
catalog.data_lista_generata = tools.getDateNow();
catalog.username_lista_generata = userStore.my.username;
await saveCatalog();
}
}
// console.log('***** FINE calcArrPROD');
2025-04-24 19:31:34 +02:00
// console.log('areadistampa FINITO...', optcatalogo.value.areadistampa)
generatinglist.value = false;
rigeneraLibri.value = false;
2025-03-26 23:23:35 +01:00
}
2024-11-28 16:04:48 +01:00
async function saveCatalog() {
2025-05-15 22:37:39 +02:00
const catalog = myCatalog.value;
const mydata = {
table: 'catalogs',
data: catalog,
};
await globalStore.saveTable(mydata);
}
function generaListaLibri() {
// chiedi prima "Sei sicuro di rigenerare il catalogo?"
let risposta_si = false;
let msg = 'Sicuri di RIGENERARE Sovrascrivendo questa lista di libri ?';
if (optrigenera.value.rig_mod == costanti.RIGENERAMOD.AGGIUNGI_SOLO) {
msg = 'Aggiungere i libri di questa nuova generazione ?';
}
$q.dialog({
title: 'Rigenera lista',
message: msg,
cancel: true,
persistent: false,
}).onOk(() => {
calcArrProducts(true);
});
}
function reSortList() {
let risposta_si = false;
let msg = 'Sicuri di Riordinare questa lista ?';
$q.dialog({
title: 'Riordina lista',
message: msg,
cancel: true,
persistent: false,
}).onOk(() => {
calcArrProducts(false);
});
}
2025-04-24 19:31:34 +02:00
function arraysEqual(arr1, arr2) {
return (
Array.isArray(arr1) &&
Array.isArray(arr2) &&
arr1.length === arr2.length &&
arr1.every((val, index) => val === arr2[index])
);
}
function checkIfFiltriDiversi(scheda: IMyScheda, schedaprec: IMyScheda) {
if (schedaprec === null) return true;
2025-04-24 19:31:34 +02:00
const isDifferent =
!arraysEqual(scheda.productTypes, schedaprec?.productTypes) ||
!arraysEqual(scheda.excludeproductTypes, schedaprec?.excludeproductTypes) ||
!arraysEqual(scheda.idTipologie, schedaprec?.idTipologie) ||
!arraysEqual(scheda.idTipoFormato, schedaprec?.idTipoFormato) ||
2025-04-24 19:31:34 +02:00
!arraysEqual(scheda.editore, schedaprec?.editore) ||
!arraysEqual(scheda.idCollane, schedaprec?.idCollane);
2025-04-24 19:31:34 +02:00
return isDifferent;
}
2025-03-26 23:23:35 +01:00
function getProductsFilteredByScheda(scheda: IMyScheda): IProduct[] {
2025-04-24 19:31:34 +02:00
let arrprod = [];
2025-03-26 23:23:35 +01:00
const filtroAuthor = filter.value.author || '';
const filtroProductTypes = scheda.productTypes || [0];
const filtroExcludeProductTypes = scheda.excludeproductTypes || [0];
2025-04-24 19:31:34 +02:00
const filtroidTipologie = scheda.idTipologie || [];
const filtroidTipoFormato = getidTipoFormatoDaFiltrare(scheda.idTipoFormato);
2025-03-26 23:23:35 +01:00
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)
: [];
2025-03-26 23:23:35 +01:00
const catstr = cat.value || '';
const collanastr = collana.value || '';
2025-03-26 23:23:35 +01:00
const gasselstr = cosa.value === shared_consts.PROD.GAS ? idGasSel.value || '' : '';
2025-05-15 22:37:39 +02:00
const trovatocatalogo = myCatalog.value;
let op_andor: IOpAndOr = {
condition_andor: trovatocatalogo?.condition_andor ?? costanti.OP_ANDOR.OP_AND,
};
if (myCatalog.value?.lista_prodotti?.length > 0) {
2025-05-15 22:37:39 +02:00
arrprod = myCatalog.value.lista_prodotti;
} else {
arrprod = productStore.getProducts(cosa.value);
arrprod = filterProducts(
arrprod,
scheda.arrProdottiSpeciali || [],
filtroAuthor,
filtroProductTypes,
filtroExcludeProductTypes,
2025-04-24 19:31:34 +02:00
filtroidTipologie,
filtroidTipoFormato,
filtroPublishers,
filtroCollane,
arrargomstr,
op_andor,
catstr,
collanastr,
gasselstr,
cosa.value,
scheda?.sort_field,
scheda?.sort_dir
);
}
2025-03-26 23:23:35 +01:00
return arrprod;
2024-11-28 16:04:48 +01:00
}
2025-04-11 18:49:42 +02:00
/**
* 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})`);
});*/
2025-04-11 18:49:42 +02:00
// 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 : '');
2024-11-28 16:04:48 +01:00
2025-04-11 18:49:42 +02:00
// 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;
}
2025-04-11 18:49:42 +02:00
// 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);
});
2024-10-31 23:23:06 +01:00
// logga i primi N elementi, mostrando il nome del prodotto (productInfo.name e la data di pibblicazione : productinfo.date_pub
2025-04-11 18:49:42 +02:00
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})`);
});*/
2025-04-11 18:49:42 +02:00
} else {
// console.log('Nessun prodotto trovato.');
2025-04-11 18:49:42 +02:00
}
return sortedArr;
2024-10-31 23:23:06 +01:00
}
return arrprod;
2024-10-31 23:23:06 +01:00
}
function addNextProductToTheView(arrproductfiltrati: IProduct[], indprod: number) {
try {
while (indprod < arrproductfiltrati.length) {
const rectrovato = arrProdToView.value.find(
2024-10-31 23:23:06 +01:00
(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 };
2024-10-31 23:23:06 +01:00
}
indprod++;
2024-10-31 23:23:06 +01:00
}
return { end: true };
2024-10-31 23:23:06 +01:00
} catch (e) {
console.error(e);
return { rec: null, indprod };
2024-10-31 23:23:06 +01:00
}
}
2024-11-19 19:19:14 +01:00
function getProdBySchedaRigaCol(recscheda: ISchedaSingola, pagina: number, riga: number, col: number) {
2024-10-31 23:23:06 +01:00
try {
return recscheda.arrProdToShow![pagina][riga][col];
2024-10-31 23:23:06 +01:00
} catch (e) {
return null;
2024-10-31 23:23:06 +01:00
}
}
function generatearrProdToViewSorted(usaprodottiSalvati?: boolean, salva?: boolean, salvasudb?: boolean) {
console.log('generatearrProdToViewSorted... usaprodottiSalvati=', usaprodottiSalvati, ' salva=', salva);
2024-10-31 23:23:06 +01:00
try {
// Svuota
arrProdToView.value = [];
2024-11-28 16:04:48 +01:00
2025-05-15 22:37:39 +02:00
const trovatocatalogo = myCatalog.value;
let arrGeneraleProdotti = [];
if (usaprodottiSalvati && myCatalog.value?.lista_prodotti?.length > 0) {
} else {
arrGeneraleProdotti = arrProducts.value;
}
2024-11-28 16:04:48 +01:00
let indprod = 0;
const indprodGenerale = 0;
2024-10-31 23:23:06 +01:00
let indtotale = 0;
2025-02-11 18:58:06 +01:00
let arrprod = [];
2025-04-24 19:31:34 +02:00
let schedaprec = null;
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;
2024-11-28 16:04:48 +01:00
let arrProdFiltrati: IProduct[] = [];
if (usaprodottiSalvati && myCatalog.value?.lista_prodotti?.length > 0) {
2025-05-15 22:37:39 +02:00
arrProdFiltrati = myCatalog.value.lista_prodotti;
2024-11-28 16:04:48 +01:00
} else {
if (recscheda.scheda.productTypes!.length > 0) {
// Filtra i prodotti in base ai filtri impostati !
2025-04-24 19:31:34 +02:00
if (checkIfFiltriDiversi(recscheda.scheda, schedaprec) || indprod === 0) {
arrProdFiltrati = getProductsFilteredByScheda(recscheda.scheda);
schedaprec = { ...recscheda.scheda };
indprod = 0;
2025-04-24 19:31:34 +02:00
}
} else {
let sort_field = recscheda.scheda.sort_field! || optcatalogo.value.sort_field;
let sort_dir = recscheda.scheda.sort_dir || optcatalogo.value.sort_dir;
2025-04-22 18:30:42 +02:00
if (sort_field) {
arrProdFiltrati = getProductsSorted(arrGeneraleProdotti, sort_field, sort_dir);
indprod = 0;
} else {
indprod = indprodGenerale;
arrProdFiltrati = arrGeneraleProdotti;
}
}
2024-11-28 16:04:48 +01:00
}
let indadded = 0;
recscheda.arrProdToShow = [];
2024-11-28 16:04:48 +01:00
for (let pagina = 0; pagina < 600; pagina++) {
indadded = 0;
let lastresultend = false;
if (!recscheda.arrProdToShow[pagina]) {
recscheda.arrProdToShow[pagina] = [];
}
2024-11-28 16:04:48 +01:00
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;
2024-10-31 23:23:06 +01:00
if (!recscheda.arrProdToShow[pagina][riga]) {
recscheda.arrProdToShow[pagina][riga] = [];
}
2024-10-31 23:23:06 +01:00
arrprod.push(result.myrec);
recscheda.arrProdToShow[pagina][riga][col] = result.myrec;
2024-10-31 23:23:06 +01:00
indadded++;
indtotale++;
// console.log('indadded', indadded)
2025-02-11 18:58:06 +01:00
if (optcatalogo.value.maxnumlibri! > 0) {
if (indtotale > optcatalogo.value.maxnumlibri!) break;
} else {
// if (indtotale > 1000)
// break
2025-02-11 18:58:06 +01:00
}
2024-11-19 19:19:14 +01:00
}
}
2024-10-31 23:23:06 +01:00
}
if (lastresultend) break; // Esci dal ciclo se non ci sono più prodotti disponibili
2025-02-11 18:58:06 +01:00
if (recscheda.numPagineMax! > 0) {
if (pagina + 1 >= recscheda.numPagineMax!) break; // fine pagine
}
2024-11-28 16:04:48 +01:00
}
// console.log('*** arrProdToShow', recscheda.arrProdToShow)
2024-10-31 23:23:06 +01:00
}
// console.log('Fine Generazione')
2024-10-31 23:23:06 +01:00
}
2025-03-01 14:14:43 +01:00
// console.log(' FINE - generatearrProdToViewSorted !')
2025-02-11 18:58:06 +01:00
if (!usaprodottiSalvati && salva) {
if (trovatocatalogo) {
if (optrigenera.value.rig_mod === costanti.RIGENERAMOD.AGGIUNGI_SOLO) {
// aggiungi solo i record che non sono presenti su lista_prodotti
trovatocatalogo.lista_prodotti = trovatocatalogo.lista_prodotti.filter(
(p) => !arrprod.some((ap) => ap._id === p._id)
);
trovatocatalogo.lista_prodotti.push(
...arrprod.filter((ap) => !trovatocatalogo.lista_prodotti.some((p) => p._id === ap._id))
);
} else {
trovatocatalogo.lista_prodotti = arrprod;
}
if (salvasudb) {
salvaListaProdotti(false);
}
}
}
} catch (e) {
console.error('Err', e);
2024-10-31 23:23:06 +01:00
}
2024-11-28 16:04:48 +01:00
// console.log('Fine...')
2024-10-31 23:23:06 +01:00
}
function salvaListaProdotti(ricarica: boolean) {
// Estrai solo gli ID dei prodotti filtrati
2025-05-15 22:37:39 +02:00
const myarr = [...myCatalog.value.lista_prodotti];
const productIds = myarr.map((product) => product._id);
let mydata = {
lista_prodotti: productIds,
};
// Salva gli ID dei prodotti nel catalogo
2025-05-15 22:37:39 +02:00
tools.saveFieldToServer($q, 'catalogs', myCatalog.value._id, mydata, !showListaFiltrata.value, false);
if (ricarica) {
generatearrProdToViewSorted(true, false);
}
}
2024-01-30 14:00:48 +01:00
/*function getProducts() {
let arrprod = productStore.getProducts(cosa.value)
if (!search.value) {
return arrprod
}
2025-03-01 14:14:43 +01:00
2024-01-30 14:00:48 +01:00
let lowerSearchText = search.value.toLowerCase();
let catstr = cat.value;
2025-03-01 14:14:43 +01:00
2024-01-30 14:00:48 +01:00
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
});
}*/
2025-04-24 19:31:34 +02:00
function getKeyCatAtLoad() {
return tools.COOK_CATEGORIA + (showListaFiltrata.value ? '_LA' : '');
}
function getKeyCollanaAtLoad() {
return tools.COOK_COLLANA + (showListaFiltrata.value ? '_LA' : '');
2025-04-24 19:31:34 +02:00
}
2024-01-30 14:00:48 +01:00
async function mounted() {
// console.log('mounted Catalogo')
2025-05-15 22:37:39 +02:00
let mycat = catalogStore.getCatalogByIdPageAssigned(props.idPage) || null;
if (mycat && !mycat.lista_prodotti) {
mycat = await catalogStore.fetchCatalogById(mycat._id);
}
myCatalog.value = mycat;
ismounting.value = true;
generatinglist.value = true;
if (optcatalogo.value.showListaArgomenti) cat.value = tools.getCookie(getKeyCatAtLoad(), '');
if (optcatalogo.value.showListaCollane) collana.value = tools.getCookie(getKeyCollanaAtLoad(), '');
2025-04-24 19:31:34 +02:00
2025-05-15 22:37:39 +02:00
if (myCatalog.value) {
tabcatalogo.value = tools.getCookie('TAB_CAT', 'lista');
} else {
2025-05-15 22:37:39 +02:00
tabcatalogo.value = 'visu';
}
optrigenera.value.visibilitaDisp = tools.getCookie(
(showListaFiltrata.value ? 'INC_ES_' : '') + 'VIS_DISP',
costanti.DISP.DISPONIBILI
);
if (!showListaFiltrata.value)
optrigenera.value.rig_mod = tools.getCookie(
(showListaFiltrata.value ? 'INC_ES_' : '') + 'RIG_MOD',
costanti.RIGENERAMOD.AGGIUNGI_SOLO
);
optrigenera.value.stato = tools.getCookie(
(showListaFiltrata.value ? 'INC_ES_' : '') + 'VIS_STATO',
costanti.STATO.IN_COMMERCIO
);
2025-04-24 19:31:34 +02:00
loadpage.value = false;
2025-05-15 22:37:39 +02:00
if (showListaFiltrata.value || !myCatalog.value) {
// Carica tutti i prodotti
await productStore.loadProducts(true);
} else {
2025-05-15 22:37:39 +02:00
/*if (myCatalog.value && props.idPage) {
myCatalog.value.lista_prodotti = await catalogStore.loadProductsOnlyByIdPageCatalog(props.idPage);
}*/
}
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;
//cosa.value = tools.getCookie(tools.COOK_COSA_PRODOTTI, shared_consts.PROD.GAS, true)
//if (cosa.value === shared_consts.PROD.TUTTI)
2024-01-30 14:00:48 +01:00
// Inizializza
loadpage.value = true;
2024-01-30 14:00:48 +01:00
window.addEventListener('scroll', handleScroll);
calcArrProducts();
ismounting.value = false;
2024-05-04 14:49:09 +02:00
}
function loaddata() {
numRecLoaded.value = 20;
2024-01-30 14:00:48 +01:00
}
// Remove the event listener on component destroy
onBeforeUnmount(() => {
window.removeEventListener('scroll', handleScroll);
});
function getCatProds() {
return [{ label: '[Seleziona un Argomento]', value: '', icon: undefined, color: undefined }].concat(
productStore
.getCatProds(cosa.value)
.map((rec) => ({
label: `${rec.name} (${productStore.getTotaliProdottiByIdCatProd(rec._id)})`,
value: rec._id,
icon: rec.icon,
color: rec.color,
}))
.concat({ label: '[Senza Argomento]', value: costanti.NO_CATEGORY, icon: undefined, color: undefined })
);
}
function getCollane() {
return [{ label: '[Seleziona una Collana]', value: '', icon: undefined, color: undefined }].concat(
productStore
.getCollane()
.map((rec) => ({
label: `${rec.title} (${productStore.getTotaliProdottiByIdCollana(rec._id)})`,
value: rec._id,
icon: rec.icon,
color: rec.color,
}))
.concat({ label: '[Senza Collana]', value: costanti.NO_CATEGORY, icon: undefined, color: undefined })
2025-04-24 19:31:34 +02:00
);
2024-01-30 14:00:48 +01:00
}
// productStore.getTotaliProdottiByIdCollana(rec._id)
2025-04-24 19:31:34 +02:00
2024-05-04 14:49:09 +02:00
function onLoadScroll(index: number, done: any) {
if (index >= 1) {
if (numRecLoaded.value < arrProducts.value.length) {
const step = 10;
let mynrec = numRecLoaded.value + step;
2024-05-04 14:49:09 +02:00
if (mynrec > arrProducts.value.length) mynrec = arrProducts.value.length;
2024-05-04 14:49:09 +02:00
numRecLoaded.value = mynrec;
2024-05-04 14:49:09 +02:00
}
done();
2024-05-04 14:49:09 +02:00
} else {
done(true);
2024-05-04 14:49:09 +02:00
}
}
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()
}
}*/
2025-03-21 19:51:55 +01:00
const valoriopt = computed(() => (item: any, addall: boolean, addnone: boolean = false) => {
// console.log('valoriopt', item.table)
return globalStore.getTableJoinByName(item.table, addall, addnone, item.filter);
});
2024-10-31 23:23:06 +01:00
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;
2024-11-28 16:04:48 +01:00
}
function generateStyleCatalogo(optcatalogo: IOptCatalogo) {
return {};
2024-11-28 16:04:48 +01:00
}
2024-10-26 17:12:05 +02:00
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) || '';
2024-10-26 17:12:05 +02:00
// Esiste un immagine di sfondo specifica della singola pagina ?
const recimg = getSfondoImgCatalogo(scheda);
const backgroundImage = recimg.imagefile! ?? '';
const backgroundSize = recimg.fit;
2024-10-26 17:12:05 +02:00
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) ?? '');
2024-11-19 19:19:14 +01:00
return {
2024-11-28 16:04:48 +01:00
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
2024-11-28 16:04:48 +01:00
};
2024-11-19 19:19:14 +01:00
}
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) ?? '');
2024-11-19 19:19:14 +01:00
// Esiste un immagine di sfondo specifica della singola pagina ?
const recimg = getSfondoImgCatalogo(null, mypage);
let fileimg = recimg.imagefile! ?? '';
let backgroundSize = recimg.fit;
2024-11-19 19:19:14 +01:00
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})` : '';
2024-11-19 19:19:14 +01:00
}
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 {
2024-11-19 19:19:14 +01:00
marginBottom,
marginTop,
marginLeft,
marginRight,
paddingBottom,
paddingTop,
paddingLeft,
paddingRight,
backgroundImage,
backgroundSize,
2024-11-19 19:19:14 +01:00
'--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) ?? '');
2024-11-19 19:19:14 +01:00
}
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}`,
};
2024-11-19 19:19:14 +01:00
}
2024-11-19 19:19:14 +01:00
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';
2025-03-01 14:14:43 +01:00
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 {
2024-11-19 19:19:14 +01:00
placeContent,
alignSelf: 'flex-start',
flex: `0 1 ${width} !important`,
2024-11-19 19:19:14 +01:00
margin: `${marginTop} ${marginRight} ${marginBottom} ${marginLeft}`,
padding: `${paddingTop} ${paddingRight} ${paddingBottom} ${paddingLeft}`,
...(height && height !== '0px' ? { height: `${height} !important` } : {}), // Aggiungi l'altezza solo se è valorizzata
};
}
2024-12-02 19:38:01 +01:00
function containsProducts(page: IProduct[][]) {
return page && page.length > 0 && page[0] && page[0].length > 0;
2024-12-02 19:38:01 +01:00
}
function naviga(path: string) {
router.push(path);
}
function updateProducts(arr: any) {
2025-05-15 22:37:39 +02:00
if (myCatalog.value) {
myCatalog.value.lista_prodotti = [...arr];
2025-05-11 21:59:16 +02:00
if (!showListaFiltrata.value) salvaListaProdotti(true);
else generatearrProdToViewSorted(true, false);
}
}
function addProductToList(element: IProduct, where: string) {
// console.log('addProductToList', element)
if (element) {
// add this record to lista_prodotti
if (myCatalog.value && !myCatalog.value?.lista_prodotti?.some((p) => p._id === element._id)) {
// inserire il record in cima
const arr = myCatalog.value?.lista_prodotti || [];
if (where === shared_consts.WHERE_INSERT.ONTOP) arr.unshift(element);
else if (where === shared_consts.WHERE_INSERT.ONBOTTOM) arr.push(element);
updateProducts(arr);
addnewProd.value = false;
}
}
}
function clickaddNewBook() {
addnewProd.value = true;
}
function toggleDebug() {
optcatalogo.value.indebug = !optcatalogo.value.indebug;
}
const preparePDF = () => {
$q.dialog({
message: 'Generare il PDF ?',
ok: {
label: t('dialog.yes'),
push: true,
},
cancel: {
label: t('dialog.cancel'),
},
title: 'Generazione PDF',
}).onOk(async () => {
optcatalogo.value.generazionePDFInCorso = true;
optcatalogo.value.areadistampa!.scale = optcatalogo.value.areadistampa!.scale_printable;
setTimeout(() => {
optcatalogo.value.generazionePDFInCorso = true;
setTimeout(() => {
generatePDF();
}, 500);
}, 500);
});
};
const terminaPDF = () => {
optcatalogo.value.generazionePDFInCorso = false;
optcatalogo.value.areadistampa!.scale = 1;
};
async function generateLargePDF(
opt: any,
pagesSelector = '.page',
salvasufiledascaricare: boolean,
dir_out: string,
file_out: string
) {
const pages = document.querySelectorAll(pagesSelector);
const pdfs = [];
2025-05-12 16:33:58 +02:00
try {
for (let i = 0; i < pages.length; i++) {
const page = pages[i];
// Nascondi altre pagine
pages.forEach((p) => p.classList.add('hidden'));
page.classList.remove('hidden');
await new Promise((resolve) => setTimeout(resolve, 100));
// Genera singolo PDF
const pdfBlob = await new Promise<Blob | null>((resolve) => {
html2pdf()
.set(opt)
.from(page)
.toPdf()
.output('blob', { compress: true })
.then(resolve)
.catch(() => resolve(null));
});
2025-05-12 16:33:58 +02:00
if (pdfBlob) {
pdfs.push(pdfBlob);
}
}
2025-05-12 16:33:58 +02:00
// Unisci PDF
const finalPdf = await PDFDocument.create();
for (const blob of pdfs) {
const pdf = await PDFDocument.load(await blob.arrayBuffer());
const copiedPages = await finalPdf.copyPages(pdf, pdf.getPageIndices());
copiedPages.forEach((p) => finalPdf.addPage(p));
}
2025-05-12 16:33:58 +02:00
const finalPdfBytes = await finalPdf.save(); // Uint8Array
2025-05-12 16:33:58 +02:00
// ✅ Conversione in Blob
const blob = new Blob([finalPdfBytes], { type: 'application/pdf' });
2025-05-12 16:33:58 +02:00
// ✅ Download
if (salvasufiledascaricare) {
saveAs(blob, opt.filename);
} else {
// ✅ Crea un oggetto File da Blob
const pdfFile = new File([blob], 'report.pdf', { type: 'application/pdf' });
// Converti il file appena generato
const ris = await globalStore.convertPdf(
pdfFile,
widthpdf.value,
heightpdf.value,
compressionepdf.value,
dir_out,
file_out,
true,
optcatalogo.value,
salvasufiledascaricare
);
if (ris) {
2025-05-15 22:37:39 +02:00
const catalog = myCatalog.value;
2025-05-12 16:33:58 +02:00
if (ris.pdf_generato) {
catalog.pdf_generato = ris.pdf_generato;
catalog.data_generato = tools.getDateNow();
}
if (ris.pdf_generato_stampa) {
catalog.pdf_generato_stampa = ris.pdf_generato_stampa;
catalog.data_generato_stampa = tools.getDateNow();
}
2025-05-12 16:33:58 +02:00
await saveCatalog();
}
}
// Ripristina visibilità
pages.forEach((p) => p.classList.remove('hidden'));
} catch (e) {
console.error('Err', e.message);
}
}
const generatePDF = async () => {
await nextTick();
$q.loading.show({
message: 'Generazione PDF in corso, attendere ...',
});
try {
let defaultMargin = 0.1;
if (optcatalogo.value.printable) {
defaultMargin = 0;
} else {
defaultMargin = 0;
}
const unit = optcatalogo.value.areadistampa!.unit;
let myformat = { ...optcatalogo.value.areadistampa!.format };
const scale = tools.getScale(optcatalogo.value);
const scalecanvas = optcatalogo.value.areadistampa!.scalecanvas;
if (tools.isObject(myformat) && scale > 0) {
} else {
myformat = [210, 297];
}
const formatwidth = myformat[0] * scale;
const formatheight = myformat[1] * scale;
let myfile = getPdfFilename();
// myfile += '_' + tools.getDateYYYYMMDD_Today();
myfile += '.pdf';
let file_out = myfile;
const element = document.getElementById('pdf-content');
const opt = {
margin: [defaultMargin, defaultMargin, defaultMargin, defaultMargin],
filename: myfile,
image: {
type: 'jpeg',
quality: 0.98,
},
html2canvas: {
scale: scalecanvas,
useCORS: true,
letterRendering: true,
},
jsPDF: {
unit: unit,
format: [formatwidth, formatheight],
orientation: optcatalogo.value.areadistampa!.orientation,
compress: optcatalogo.value.areadistampa!.compress,
},
enableLinks: true,
pagebreak: { mode: 'avoid-all', before: '.card-page' },
};
console.log('opt di stampa', opt);
// a4: [595.28, 841.89]
if (true) {
await generateLargePDF(opt, '.pdf-section', false, 'upload/cataloghi/', file_out);
} else {
await html2pdf().set(opt).from(element).save();
}
optcatalogo.value.generazionePDFInCorso = false;
optcatalogo.value.areadistampa!.scale = 1;
$q.loading.hide();
$q.notify({
color: 'positive',
message: 'PDF generato con successo!',
icon: 'check',
});
} catch (error) {
$q.loading.hide();
$q.notify({
color: 'negative',
message: 'Errore nella generazione del PDF',
icon: 'error',
});
console.error('Errore nella generazione del PDF:', error);
}
};
const pubblicaPDF = async () => {
2025-05-15 22:37:39 +02:00
const catalog = myCatalog.value;
const confirm = await $q
.dialog({
title: 'Conferma',
message: 'Vuoi pubblicare OnLine questo PDF?',
ok: {
label: 'S ',
push: true,
},
cancel: {
label: 'Annulla',
},
})
.onOk(async () => {
if (!confirm) return;
const ris = await globalStore.execOnlinePDF({ id_catalog: catalog._id, stampa: false });
if (ris) {
if (ris.record?.pdf_online) {
catalog.pdf_online = ris.record.pdf_online;
catalog.data_online = ris.record.data_online;
}
$q.notify({
color: 'positive',
message: 'PDF inviato ONLINE!',
icon: 'check',
});
} else {
$q.loading.hide();
$q.notify({
color: 'negative',
message: "Errore nell'invio del PDF OnLine",
icon: 'error',
});
}
});
};
const pubblicaPDFStampa = async () => {
2025-05-15 22:37:39 +02:00
const catalog = myCatalog.value;
const confirm = await $q
.dialog({
title: 'Conferma',
message: 'Vuoi pubblicare OnLine questo PDF di STAMPA ?',
ok: {
label: 'S ',
push: true,
},
cancel: {
label: 'Annulla',
},
})
.onOk(async () => {
const ris = await globalStore.execOnlinePDF({ id_catalog: catalog._id, stampa: true });
if (ris) {
if (ris.record.pdf_online_stampa) {
catalog.pdf_online_stampa = ris.record.pdf_online_stampa;
catalog.data_online_stampa = ris.record.data_online_stampa;
}
$q.notify({
color: 'positive',
message: 'PDF STAMPA inviato ONLINE!',
icon: 'check',
});
} else {
$q.loading.hide();
$q.notify({
color: 'negative',
message: "Errore nell'invio del PDF STAMPA OnLine",
icon: 'error',
});
}
});
// await saveCatalog();
};
onMounted(mounted);
2024-01-30 14:00:48 +01:00
return {
userStore,
costanti,
tools,
toolsext,
search,
cosa,
shared_consts,
getCatProds,
cat,
2024-05-04 14:49:09 +02:00
idGasSel,
2024-01-30 14:00:48 +01:00
productStore,
t,
loadpage,
componentToFixRef,
isFixed,
arrProducts,
2024-05-04 14:49:09 +02:00
show_hide,
onLoadScroll,
numRecLoaded,
arrLoaded,
filter,
optauthors,
filterFn,
selauthor,
searchList,
fieldsTable,
valoriopt,
labelcombo,
mycolumns,
tabvisu,
getSearchText,
pdfContent,
2024-10-26 17:12:05 +02:00
tabcatalogo,
groupedPages,
2024-10-31 23:23:06 +01:00
getProdBySchedaRigaCol,
generateStylePageScheda,
generateStyleCatalogo,
2024-11-19 19:19:14 +01:00
getStyleRow,
getStyleSchedaProdotto,
2024-11-19 19:19:14 +01:00
getWidthPagina,
getHeightPagina,
getStyleRowSeparator,
2024-11-28 16:04:48 +01:00
generateStyleByPageDim,
2024-12-02 19:38:01 +01:00
containsProducts,
updateOptCatalogo,
optcatalogo,
getTestoIntroduttivo,
ispageCatalogata,
naviga,
2025-03-01 14:14:43 +01:00
getTitoloCatalogo,
getTitoloPagina,
generaListaLibri,
updateProducts,
clickaddNewBook,
addProductToList,
addnewProd,
showListaFiltrata,
2025-04-24 19:31:34 +02:00
rigeneraLibri,
optrigenera,
generatinglist,
optDisp,
optRigeneraModalita,
2025-04-24 19:31:34 +02:00
optStato,
2025-05-15 22:37:39 +02:00
myCatalog,
getReferentiCatalogo,
reSortList,
preparePDF,
terminaPDF,
toggleDebug,
generatePDF,
getPdfFilename,
filtroStrApplicato,
getCollane,
pubblicaPDF,
pubblicaPDFStampa,
ismounting,
pdfColumns,
pdfRows,
};
},
});