Files
freeplanet_serverside/src/server/models/product.js

1042 lines
24 KiB
JavaScript
Raw Normal View History

2022-09-14 11:32:04 +02:00
mongoose = require('mongoose').set('debug', false)
2020-12-21 02:16:42 +01:00
const Schema = mongoose.Schema;
const tools = require('../tools/general');
2023-12-14 15:20:21 +01:00
const Producer = require('../models/producer');
const Storehouse = require('../models/storehouse');
const Provider = require('../models/provider');
2023-12-27 02:58:15 +01:00
const CatProd = require('../models/catprod');
2024-01-12 13:02:59 +01:00
const SubCatProd = require('../models/subcatprod');
2023-12-21 02:23:52 +01:00
const Gasordine = require('../models/gasordine');
2023-12-16 00:51:03 +01:00
const Scontistica = require('../models/scontistica');
2023-12-14 15:20:21 +01:00
2023-12-12 15:42:41 +01:00
const shared_consts = require('../tools/shared_nodejs');
const { ObjectId } = require('mongodb');
2020-12-21 02:16:42 +01:00
mongoose.Promise = global.Promise;
mongoose.level = "F";
2023-12-11 10:10:52 +01:00
// A1P
2020-12-21 02:16:42 +01:00
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const productSchema = new Schema({
idapp: {
type: String,
},
active: {
type: Boolean,
2023-12-13 19:17:53 +01:00
default: true,
},
2024-05-04 14:49:02 +02:00
isbn: {
type: String,
},
2023-12-27 02:58:15 +01:00
idProductInfo: { type: Schema.Types.ObjectId, ref: 'ProductInfo' },
2023-12-12 15:42:41 +01:00
idProducer: { type: Schema.Types.ObjectId, ref: 'Producer' },
2020-12-25 03:54:16 +01:00
idStorehouses: [
{ type: Schema.Types.ObjectId, ref: 'Storehouse' }
],
2024-01-16 16:56:39 +01:00
idGasordine: { type: Schema.Types.ObjectId, ref: 'Gasordine' },
2023-12-16 00:51:03 +01:00
idScontisticas: [
{ type: Schema.Types.ObjectId, ref: 'Scontistica' }
],
idProvider: { type: Schema.Types.ObjectId, ref: 'Provider' },
2023-11-28 15:04:17 +01:00
prezzo_ivato: { // Con IVA
2023-11-28 14:20:22 +01:00
type: Number
},
perc_iva: { // 4, 10, 22 &
type: Number
2020-12-21 02:16:42 +01:00
},
price: {
2023-12-12 15:42:41 +01:00
type: Number,
required: true,
2020-12-21 02:16:42 +01:00
},
arrvariazioni: [
{
active: {
type: Boolean,
},
2024-06-21 16:11:03 +02:00
versione: {
type: Number,
2024-06-21 16:11:03 +02:00
},
status: { //publish
type: String,
},
price: {
type: Number,
},
sale_price: {
type: Number,
},
quantita: { // in magazzino
type: Number,
},
2024-11-19 19:18:54 +01:00
pagine: {
type: Number,
},
2024-11-19 19:18:54 +01:00
misure: {
type: String,
},
formato: {
type: String,
},
tipologia: {
type: String,
},
edizione: {
type: String,
},
preOrderDate: {
type: Date
},
addtocart_link: {
type: String
},
eta: {
type: String
},
}
],
2023-12-14 15:20:21 +01:00
price_acquistato: {
type: Number,
required: true,
},
2021-06-04 10:07:57 +02:00
after_price: {
type: String
},
minBuyQty: { // quantità minima acquistabile
type: Number,
default: 1,
required: true,
},
2023-12-29 15:19:15 +01:00
minStepQty: { // step quantità acquistabile
type: Number,
default: 1,
required: true,
},
maxBookableSinglePersQty: { // quantità massima Pre-ordinabile (singolarmente)
2023-12-27 02:58:15 +01:00
type: Number,
default: 0,
},
stockQty: { // in magazzino
type: Number,
2023-12-12 15:42:41 +01:00
default: 0,
},
stockBloccatiQty: { // Prenotati Bloccati
type: Number,
default: 0,
},
2024-01-03 15:46:42 +01:00
bookedQtyOrdered: { // Quantità Prenotate ordinate (in Lavorazione)
type: Number,
default: 0,
},
bookedQtyConfirmed: { // Quantità Prenotate Confermate Totali
type: Number,
default: 0,
},
// GAS:
qtyToReachForGas: { // Quantità minima da raggiungere per fare l'ordine GAS
2023-12-20 21:52:17 +01:00
type: Number,
default: 0,
},
maxbookableGASQty: { // Quantità massima (ancora disponibile) Ordine GAS prenotabile (Complessivamente tra tutti gli ordini)
2023-12-29 21:17:17 +01:00
type: Number,
default: 0,
},
2024-01-03 15:46:42 +01:00
bookedGASQtyOrdered: { // Quantità Ordine GAS Prenotate Totali
type: Number,
default: 0,
},
bookedGASQtyConfirmed: { // Quantità Ordine GAS Confermate Totali
2023-12-29 21:17:17 +01:00
type: Number,
default: 0,
},
bookableGASBloccatiQty: { // Quantità Prenotate Bloccate GAS
type: Number,
default: 0,
},
quantityLow: { //Soglia disponibilità bassa
2023-12-12 15:42:41 +01:00
type: Number,
default: 0,
},
visibilityProductOutOfStock: { // Visibilità prodotto "esaurito"
2023-12-12 15:42:41 +01:00
type: Boolean,
default: false,
},
2021-01-18 00:48:17 +01:00
canBeShipped: { // è spedibile
2023-12-12 15:42:41 +01:00
type: Boolean,
default: false,
2021-01-18 00:48:17 +01:00
},
canBeBuyOnline: { // è acquistabile online
2023-12-12 15:42:41 +01:00
type: Boolean,
default: false,
2021-01-18 00:48:17 +01:00
},
2020-12-25 03:54:16 +01:00
stars: {
2023-12-12 15:42:41 +01:00
type: Number,
default: 0,
2020-12-21 02:16:42 +01:00
},
2020-12-25 03:54:16 +01:00
dateAvailableFrom: {
type: Date
},
note: {
type: String,
},
2023-12-14 15:20:21 +01:00
producer_name: {
type: String,
},
provider_name: {
type: String,
},
magazzino_name: {
type: String,
},
2023-12-27 02:58:15 +01:00
cat_name: {
type: String,
},
2024-01-12 13:02:59 +01:00
subcat_name: {
type: String,
},
2023-12-29 15:19:15 +01:00
sconto1: {
type: String,
},
sconto2: {
type: String,
},
2023-12-29 21:17:17 +01:00
gas_name: {
type: String,
},
date_created: {
type: Date,
default: Date.now
},
date_updated: {
type: Date,
},
2020-12-21 02:16:42 +01:00
});
var Product = module.exports = mongoose.model('Product', productSchema);
2023-12-09 11:55:58 +01:00
productSchema.index({ idapp: 1 });
2020-12-21 02:16:42 +01:00
module.exports.getFieldsForSearch = function () {
return [
{ field: 'name', type: tools.FieldType.string },
{ field: 'description', type: tools.FieldType.string },
]
2020-12-21 02:16:42 +01:00
};
module.exports.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
module.exports.executeQueryPickup = async function (idapp, params) {
let strfind = params.search;
strfind = strfind.replace(/[-@]/g, '');
if (strfind === '' && !params.filter) {
return [];
}
let filterfindexact = {};
if (strfind) {
filterfindexact = { comune: strfind };
}
let limit = 20;
let risexact = [];
let filterfind = {
idapp,
$or: [
{
'productInfo.name': {
$regex: `\\b${strfind}`, // Cerca parole che iniziano con strfind
$options: 'i' // Rende la ricerca case-insensitive
}
},
{
'productInfo.code': {
$regex: `\\b${strfind}`, // Cerca parole che iniziano con strfind
$options: 'i' // Rende la ricerca case-insensitive
}
},
{
'productInfo.sku': {
$regex: `\\b${strfind}`, // Cerca parole che iniziano con strfind
$options: 'i' // Rende la ricerca case-insensitive
}
},
{
'productInfo.authors.name': {
$regex: `\\b${strfind}`, // Cerca parole che iniziano con strfind nel nome dell'autore
$options: 'i' // Rende la ricerca case-insensitive
}
},
{
'productInfo.authors.surname': {
$regex: `\\b${strfind}`, // Cerca parole che iniziano con strfind nel cognome dell'autore
$options: 'i' // Rende la ricerca case-insensitive
}
},
]
};
if (params.filter) {
filterfind = { ...params.filter, ...filterfind };
limit = 200;
}
let aggr2 = [
{
$lookup: {
from: 'productinfos',
localField: 'idProductInfo',
foreignField: '_id',
as: 'productInfo'
}
},
{
$unwind: {
path: '$productInfo',
preserveNullAndEmptyArrays: true,
},
},
{
$lookup: {
from: 'authors',
localField: 'productInfo.idAuthors',
foreignField: '_id',
as: 'productInfo.authors'
}
},
{
$unwind: {
path: '$authors',
preserveNullAndEmptyArrays: true,
},
},
{
$match: filterfind,
},
{ $limit: limit },
{
$project: {
name: '$productInfo.name', // Nome del prodotto
authors: '$productInfo.authors',
productInfo: {
name: '$productInfo.name', // Nome del prodotto
authors: '$productInfo.authors',
},
}
}
];
let ris = await this.aggregate(aggr2).limit(limit);
return [...risexact, ...ris];
};
module.exports.getProductByCode = function (idapp, code) {
return Product.findAllIdApp(idapp, code);
}
2021-01-18 00:48:17 +01:00
module.exports.getProductById = async function (id) {
const arrris = await Product.findAllIdApp('', '', id);
return arrris && arrris.length > 0 ? arrris[0] : null
}
2020-12-21 02:16:42 +01:00
2024-01-23 00:10:40 +01:00
module.exports.getInStockById = async function (id) {
const myprod = await Product.findOne({ _id: id });
if (myprod) {
let instock = 0;
if (myprod.idGasordine) {
instock = myprod.maxbookableGASQty;
} else {
instock = myprod.stockQty;
}
return instock
}
return null;
}
module.exports.isLowQuantityInStockById = async function (id) {
const instock = await Product.getInStockById(id);
const myprod = await Product.findOne({ _id: id });
if (instock) {
return (instock <= (myprod.quantityLow + 1));
}
return false;
}
2024-01-13 16:21:07 +01:00
module.exports.findAllIdApp = async function (idapp, code, id, all) {
let myfind = {};
let myqueryadd = {};
let query = [];
2020-12-25 03:54:16 +01:00
try {
2024-01-16 16:56:39 +01:00
if (idapp) {
2024-01-13 16:21:07 +01:00
myfind = { idapp };
}
if (!all) {
myfind = { ...myfind, active: true }
}
if (code) {
myfind = { ...myfind, code }
}
if (id) {
myqueryadd = {
$addFields: {
myId1: {
$toObjectId: id,
},
},
}
myfind = {
$expr: {
$eq: ["$_id", "$myId1"],
},
2020-12-25 03:54:16 +01:00
}
query.push(myqueryadd);
}
// DA TOGLIEREE
// myfind = { ...myfind, code: '4012824406094' };
// return await Product.find(myfind);
query.push(
{ $match: myfind },
{
$lookup: {
from: 'producers',
localField: 'idProducer',
foreignField: '_id',
as: 'producer'
}
},
2023-12-16 00:51:03 +01:00
{
$unwind: {
path: '$producer',
preserveNullAndEmptyArrays: true,
},
},
2023-12-27 02:58:15 +01:00
{
$lookup: {
from: 'productinfos',
localField: 'idProductInfo',
foreignField: '_id',
as: 'productInfo'
}
},
{
$unwind: {
path: '$productInfo',
preserveNullAndEmptyArrays: true,
},
},
{
$lookup: {
from: 'gasordines',
2024-01-16 16:56:39 +01:00
localField: 'idGasordine',
foreignField: '_id',
2024-01-16 16:56:39 +01:00
as: 'gasordine'
}
},
{
$unwind: {
2024-01-16 16:56:39 +01:00
path: '$gasordine',
preserveNullAndEmptyArrays: true,
},
},
{
$match: {
$or: [
2024-01-16 16:56:39 +01:00
{ 'gasordine.active': true }, // Include documents where gasordines.active is true
{ 'gasordine': { $exists: false } } // Include documents where gasordines array doesn't exist
]
}
},
{
$group: {
_id: '$_id',
2024-01-16 16:56:39 +01:00
gasordine: { $first: '$gasordine' },
originalFields: { $first: '$$ROOT' } // Preserve all existing fields
}
},
{
$replaceRoot: {
newRoot: {
2024-01-16 16:56:39 +01:00
$mergeObjects: ['$originalFields', { gasordine: '$gasordine' }]
}
}
},
{
$lookup: {
from: 'providers',
localField: 'idProvider',
foreignField: '_id',
as: 'provider'
}
},
2023-12-16 00:51:03 +01:00
{
$unwind: {
path: '$provider',
preserveNullAndEmptyArrays: true,
},
},
2024-05-04 14:49:02 +02:00
{
$lookup: {
from: 'authors',
localField: 'productInfo.idAuthors',
foreignField: '_id',
as: 'productInfo.authors'
}
},
2024-06-21 16:11:03 +02:00
{
$lookup: {
from: 'publishers',
localField: 'productInfo.idPublisher',
foreignField: '_id',
as: 'productInfo.publisher'
}
},
{
$unwind: {
path: '$productInfo.publisher',
preserveNullAndEmptyArrays: true,
},
},
{
$lookup: {
from: 'collanas',
localField: 'productInfo.idCollana',
foreignField: '_id',
as: 'productInfo.collana'
}
},
{
$unwind: {
path: '$productInfo.collana',
preserveNullAndEmptyArrays: true,
},
},
2023-12-27 02:58:15 +01:00
{
$lookup: {
from: 'catprods',
2024-05-08 16:07:32 +02:00
localField: 'productInfo.idCatProds',
2023-12-27 02:58:15 +01:00
foreignField: '_id',
2024-05-08 16:07:32 +02:00
as: 'productInfo.catprods'
2023-12-27 02:58:15 +01:00
}
},
2024-01-12 13:02:59 +01:00
{
$lookup: {
from: 'subcatprods',
2024-05-08 16:07:32 +02:00
localField: 'productInfo.idSubCatProds',
2024-01-12 13:02:59 +01:00
foreignField: '_id',
2024-05-08 16:07:32 +02:00
as: 'productInfo.subcatprods'
2024-01-12 13:02:59 +01:00
}
},
2023-12-16 00:51:03 +01:00
{
$lookup: {
from: 'scontisticas',
localField: 'idScontisticas',
foreignField: '_id',
as: 'scontisticas'
2023-12-16 00:51:03 +01:00
}
},
{
$lookup: {
from: 'storehouses',
localField: 'idStorehouses',
foreignField: '_id',
as: 'storehouses'
}
},
{
$lookup: {
from: 'orders',
let: { productId: '$_id' },
pipeline: [
{
$match: {
$expr: {
$and: [
{ $eq: ['$idProduct', '$$productId'] },
2023-12-28 21:00:02 +01:00
{
$or: [
{
$eq: ['$status', shared_consts.OrderStatus.CHECKOUT_SENT]
},
{
$and: [{ $lt: ['$status', shared_consts.OrderStatus.CHECKOUT_SENT] },
{
$gt: [
'$modify_at',
{ $subtract: [new Date(), 60 * 60 * 1000] } // 1 hour in milliseconds 60 * 60
]
}]
}
]
}
]
}
}
},
{
$group: {
_id: null,
2023-12-20 21:52:17 +01:00
totalQty: { $sum: '$quantity' },
2023-12-12 15:42:41 +01:00
}
2023-12-13 19:17:53 +01:00
}
],
as: 'productOrders'
}
},
2023-12-20 21:52:17 +01:00
{
$lookup: {
from: 'orders',
let: { productId: '$_id' },
pipeline: [
{
$match: {
$expr: {
$and: [
{ $eq: ['$idProduct', '$$productId'] },
2023-12-28 21:00:02 +01:00
{
$or: [
{
$eq: ['$status', shared_consts.OrderStatus.CHECKOUT_SENT]
},
{
$and: [{ $lt: ['$status', shared_consts.OrderStatus.CHECKOUT_SENT] },
{
$gt: [
'$modify_at',
{ $subtract: [new Date(), 60 * 60 * 1000] } // 1 hour in milliseconds 60 * 60
]
}]
}
]
}
2023-12-20 21:52:17 +01:00
]
}
}
},
{
$group: {
_id: null,
totalQtyPreordered: { $sum: '$quantitypreordered' }
}
}
],
as: 'productPreOrders'
}
},
{
$addFields: {
QuantitaOrdinateInAttesa: {
2023-12-20 21:52:17 +01:00
$ifNull: [
{
$cond: {
if: { $isArray: '$productOrders' },
then: { $arrayElemAt: ['$productOrders.totalQty', 0] },
else: 0
}
},
0
]
},
QuantitaPrenotateInAttesa: {
$ifNull: [
{
$cond: {
if: { $isArray: '$productPreOrders' },
then: { $arrayElemAt: ['$productPreOrders.totalQtyPreordered', 0] },
else: 0
}
},
0
]
},
},
},
{
$addFields: {
quantityAvailable: {
$subtract: ["$stockQty", "$QuantitaOrdinateInAttesa"],
},
bookableAvailableQty: {
$subtract: ["$maxbookableGASQty", "$QuantitaPrenotateInAttesa"],
2023-12-12 15:42:41 +01:00
}
}
},
{
$unset: 'productOrders'
},
2023-12-20 21:52:17 +01:00
{
$unset: 'productPreOrders'
},
2023-12-27 02:58:15 +01:00
{
$sort: {
'productInfo.name': 1 // 1 for ascending order, -1 for descending order
}
},
);
2020-12-25 03:54:16 +01:00
2023-12-17 19:19:04 +01:00
// console.log('query=', query);
let ris = await Product.aggregate(query)
2020-12-25 03:54:16 +01:00
2023-12-17 19:19:04 +01:00
// console.table('ris', ris);
return ris;
} catch (e) {
console.error('E', e);
}
2020-12-25 03:54:16 +01:00
2020-12-21 02:16:42 +01:00
};
module.exports.getAllProducts = function (query, sort, callback) {
Product.find(query, null, sort, callback)
}
2020-12-25 03:54:16 +01:00
module.exports.getProductByDepartment = function (query, sort, callback) {
2020-12-21 02:16:42 +01:00
Product.find(query, null, sort, callback)
}
2023-12-27 02:58:15 +01:00
module.exports.getProductByCatProd = function (query, sort, callback) {
2020-12-21 02:16:42 +01:00
Product.find(query, null, sort, callback)
}
2020-12-25 03:54:16 +01:00
module.exports.getProductByTitle = function (query, sort, callback) {
2020-12-21 02:16:42 +01:00
Product.find(query, null, sort, callback)
}
module.exports.filterProductByDepartment = function (department, callback) {
let regexp = new RegExp(`^${department}$`, 'i')
2020-12-21 02:16:42 +01:00
var query = { department: { $regex: regexp } };
Product.find(query, callback)
}
2023-12-27 02:58:15 +01:00
module.exports.filterProductByCatProd = function (catprod, callback) {
let regexp = new RegExp(`^${catprod}$`, 'i')
var query = { catprod: { $regex: regexp } };
2020-12-21 02:16:42 +01:00
Product.find(query, callback);
}
module.exports.filterProductByTitle = function (title, callback) {
let regexp = new RegExp(`^${title}$`, 'i')
2020-12-21 02:16:42 +01:00
var query = { title: { $regex: regexp } };
Product.find(query, callback);
}
module.exports.getProductByID = function (id, callback) {
Product.findById(id, callback);
}
2023-12-20 21:52:17 +01:00
module.exports.updateProductInOrder = async function (order) {
2023-12-20 21:52:17 +01:00
if (order.product)
order.product = await Product.getProductById(order.product._id);
2023-12-20 21:52:17 +01:00
return order;
}
module.exports.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
2023-11-28 15:04:17 +01:00
module.exports.convertAfterImportALLPROD = async function (idapp, dataObjects) {
2023-12-14 15:20:21 +01:00
const arrprod = await Product.find({ idapp }).lean();
2023-12-14 15:20:21 +01:00
for (const prod of arrprod) {
await this.singlerecconvert_AfterImport_AndSave(prod);
2023-12-18 12:11:12 +01:00
}
};
2024-01-23 00:10:40 +01:00
module.exports.getArrCatProds = async function (idapp, cosa) {
try {
let addquery = [];
2024-01-23 00:10:40 +01:00
let arr = [];
if (cosa === shared_consts.PROD.GAS) {
addquery = [
{ $match: { idapp, idGasordine: { $exists: true, $ne: null, $type: 'objectId' } } }
];
addquery.push(
{
$lookup: {
from: 'gasordines',
localField: 'idGasordine',
foreignField: '_id',
as: 'gasordine'
}
}
);
addquery.push(
{
$match: {
"gasordine.active": true
}
}
);
2024-01-23 00:10:40 +01:00
} else if (cosa === shared_consts.PROD.BOTTEGA) {
addquery = [{
$match: {
idapp, $or: [
{ idGasordine: { $exists: false } },
{ idGasordine: { $exists: true, $eq: null } }
]
}
}]
2024-01-23 00:10:40 +01:00
} else {
addquery = [{ $match: { idapp } }];
2024-01-23 00:10:40 +01:00
}
let myquery = [...addquery,
{
$lookup: {
from: "productinfos",
localField: "idProductInfo",
foreignField: "_id",
as: "productInfo",
2024-01-23 00:10:40 +01:00
},
},
{
$lookup: {
from: "catprods",
localField: "productInfo.idCatProds",
foreignField: "_id",
as: "category"
}
},
{ $unwind: "$category" },
{ $group: { _id: "$category._id", name: { $first: "$category.name" } } },
{ $sort: { name: 1 } }
2024-01-23 00:10:40 +01:00
];
try {
let arr = [];
arr = await Product.aggregate(myquery);
// arr = result.map(category => category.name);
return arr;
} catch (e) {
console.error('err', e);
}
// Ora uniqueCategories contiene l'array delle categorie univoche utilizzate in tutti i prodotti con active = true
2024-01-23 00:10:40 +01:00
return arr;
} catch (e) {
console.error('err', e);
return [];
}
}
module.exports.singlerecconvert_AfterImport_AndSave = async function (idapp, prod, isnuovo) {
2023-12-18 12:11:12 +01:00
let setta = false;
2023-12-18 12:11:12 +01:00
try {
2023-12-27 02:58:15 +01:00
let objtoset = {}
2023-12-29 21:17:17 +01:00
let rec = null
2023-12-27 02:58:15 +01:00
// Impostazioni Base:
2023-12-27 02:58:15 +01:00
if (isnuovo) {
objtoset = {
idapp,
// minBuyQty: 1,
// minStepQty: 1,
maxBookableSinglePersQty: 0,
bookedGASQtyOrdered: 0,
bookableGASBloccatiQty: 0,
2024-01-03 15:46:42 +01:00
bookedGASQtyConfirmed: 0,
// qtyToReachForGas: 0,
// maxbookableGASQty: 0,
2023-12-27 02:58:15 +01:00
}
}
2023-12-14 15:20:21 +01:00
if (prod.producer_name) {
// Cerca il produttore
let recproducer = await Producer.findOne({ idapp, name: prod.producer_name }).lean();
if (!recproducer) {
// Non esiste questo produttore, quindi lo creo !
recproducer = new Producer({ idapp, name: prod.producer_name });
ris = await recproducer.save();
recproducer = await Producer.findOne({ idapp, name: prod.producer_name }).lean();
}
if (recproducer) {
objtoset = {
...objtoset,
idProducer: recproducer._id,
}
setta = true;
}
}
2023-12-14 15:20:21 +01:00
if (prod.magazzino_name) {
2023-12-14 15:20:21 +01:00
// Cerca il produttore
let recstorehouse = await Storehouse.findOne({ idapp, name: prod.magazzino_name }).lean();
if (!recstorehouse) {
// Non esiste questo produttore, quindi lo creo !
recstorehouse = new Storehouse({ idapp, name: prod.magazzino_name });
ris = await recstorehouse.save();
recstorehouse = await Storehouse.findOne({ idapp, name: prod.magazzino_name }).lean();
}
2023-12-14 15:20:21 +01:00
if (recstorehouse) {
objtoset = {
...objtoset,
idStorehouses: [recstorehouse._id],
}
setta = true;
}
}
2023-12-14 15:20:21 +01:00
if (prod.provider_name) {
// Cerca il produttore
let recprovider = await Provider.findOne({ idapp, name: prod.provider_name }).lean();
if (!recprovider) {
recprovider = new Provider({ idapp, name: prod.provider_name });
// Non esiste questo produttore, quindi lo creo !
ris = await recprovider.save();
recprovider = await Provider.findOne({ idapp, name: prod.provider_name }).lean();
}
if (recprovider) {
objtoset = {
...objtoset,
idProvider: recprovider._id,
}
setta = true;
2023-12-14 15:20:21 +01:00
}
}
2023-12-29 21:17:17 +01:00
if (prod.gas_name) {
// Cerca il GAS
rec = await Gasordine.findOne({ idapp, name: prod.gas_name }).lean();
if (!rec) {
rec = new Gasordine({ idapp, name: prod.gas_name, active: true });
// Non esiste questo GAS, quindi lo creo !
ris = await rec.save();
rec = await Gasordine.findOne({ idapp, name: prod.gas_name }).lean();
}
if (rec) {
objtoset = {
...objtoset,
2024-01-16 16:56:39 +01:00
idGasordine: rec._id,
2023-12-29 21:17:17 +01:00
}
setta = true;
}
}
2023-12-14 15:20:21 +01:00
2023-12-29 15:19:15 +01:00
let arrsconti = []
if (prod.sconto1) {
// Cerca la scontistica
let recscontistica = await Scontistica.findOne({ idapp, code: prod.sconto1 }).lean();
if (!recscontistica) {
recscontistica = new Scontistica({ idapp, code: prod.sconto1 });
// Non esiste questa scontistica, quindi lo creo !
ris = await recscontistica.save();
recscontistica = await Scontistica.findOne({ idapp, code: prod.sconto1 }).lean();
}
if (recscontistica) {
arrsconti.push(recscontistica);
}
}
if (prod.sconto2) {
// Cerca la scontistica
let recscontistica = await Scontistica.findOne({ idapp, code: prod.sconto2 }).lean();
if (!recscontistica) {
recscontistica = new Scontistica({ idapp, code: prod.sconto2 });
// Non esiste questa scontistica, quindi lo creo !
ris = await recscontistica.save();
recscontistica = await Scontistica.findOne({ idapp, code: prod.sconto2 }).lean();
}
if (recscontistica) {
arrsconti.push(recscontistica);
}
}
if (arrsconti.length > 0) {
objtoset = {
...objtoset,
idScontisticas: arrsconti,
}
setta = true;
}
// Aggiorna il prezzo ?
const aggiornaprezzo = false;
if (aggiornaprezzo) {
// cerca il prodotto
const myprodinput = dataObjects.find((rec) => rec._id === prod._id)
if (myprodinput) {
objtoset = {
...objtoset,
price: myprodinput.price,
}
}
}
2023-11-28 15:04:17 +01:00
2023-12-27 02:58:15 +01:00
if (!tools.isObjectEmpty(objtoset)) {
ris = await Product.findOneAndUpdate({ _id: new ObjectId(prod._id) }, { $set: objtoset })
2023-12-27 02:58:15 +01:00
const objDelete = {
cat_name: 1,
2024-01-12 13:02:59 +01:00
subcat_name: 1,
2023-12-27 02:58:15 +01:00
producer_name: 1,
provider_name: 1,
magazzino_name: 1,
2023-12-29 15:19:15 +01:00
sconto1: 1,
sconto2: 1,
2023-12-29 21:17:17 +01:00
gas_name: 1,
2023-12-27 02:58:15 +01:00
};
ris = await Product.updateOne({ _id: new ObjectId(prod._id) }, { $unset: objDelete })
2023-12-18 12:11:12 +01:00
if (ris && ris.modifiedCount > 0) {
2024-05-04 14:49:02 +02:00
console.log('Modificato: ', objtoset.name);
2023-12-18 12:11:12 +01:00
}
2020-12-21 02:16:42 +01:00
// const campodarimuovere = 'producer_name';
// await Product.findOneAndUpdate({ _id: prod._id }, { $unset: { [campodarimuovere]: 1 } })
}
2023-12-18 12:11:12 +01:00
} catch (e) {
console.error('Err', e);
}
}