Files
freeplanet_serverside/src/server/models/product.js
2023-12-15 21:50:21 +01:00

419 lines
9.0 KiB
JavaScript
Executable File

mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
const tools = require('../tools/general');
const Producer = require('../models/producer');
const Storehouse = require('../models/storehouse');
const Provider = require('../models/provider');
const shared_consts = require('../tools/shared_nodejs');
const { ObjectID } = require('mongodb');
mongoose.Promise = global.Promise;
mongoose.level = "F";
// A1P
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const productSchema = new Schema({
idapp: {
type: String,
},
active: {
type: Boolean,
default: true,
},
idProducer: { type: Schema.Types.ObjectId, ref: 'Producer' },
idStorehouses: [
{ type: Schema.Types.ObjectId, ref: 'Storehouse' }
],
idProvider: { type: Schema.Types.ObjectId, ref: 'Provider' },
code: {
type: String,
unique: true,
},
codice_EAN: {
type: String,
},
barcode: {
type: String,
},
name: {
type: String,
},
description: {
type: String,
},
department: {
type: String, ref: 'Department'
},
category: {
type: Array,
},
prezzo_ivato: { // Con IVA
type: Number
},
perc_iva: { // 4, 10, 22 &
type: Number
},
price: {
type: Number,
required: true,
},
price_acquistato: {
type: Number,
required: true,
},
after_price: {
type: String
},
color: {
type: String
},
size: {
type: String
},
weight: {
type: Number
},
vegan: {
type: Boolean
},
unit: {
type: Number
},
stockQty: { // in magazzino
type: Number,
default: 0,
},
quantityLow: { //Soglia disponibilità bassa
type: Number,
default: 0,
},
visibilityProductOutOfStock: { // Visibilità prodotto "esaurito"
type: Boolean,
default: false,
},
canBeShipped: { // è spedibile
type: Boolean,
default: false,
},
canBeBuyOnline: { // è acquistabile online
type: Boolean,
default: false,
},
stars: {
type: Number,
default: 0,
},
dateAvailableFrom: {
type: Date
},
icon: {
type: String,
},
img: {
type: String,
},
link: {
type: String,
},
img2: {
type: String,
},
img3: {
type: String,
},
ingredienti: {
type: String,
},
valori_nutrizionali: {
type: String,
},
note: {
type: String,
},
producer_name: {
type: String,
},
provider_name: {
type: String,
},
magazzino_name: {
type: String,
},
});
var Product = module.exports = mongoose.model('Product', productSchema);
productSchema.index({ idapp: 1 });
module.exports.getFieldsForSearch = function () {
return [{ field: 'name', type: tools.FieldType.string }]
};
module.exports.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
module.exports.getProductByCode = function (idapp, code) {
return Product.findAllIdApp(idapp, code);
}
module.exports.getProductById = async function (id) {
const arrris = await Product.findAllIdApp('', '', id);
return arrris && arrris.length > 0 ? arrris[0] : null
}
module.exports.findAllIdApp = async function (idapp, code, id) {
let myfind = {};
let myqueryadd = {};
let query = [];
try {
if (idapp)
myfind = { idapp, active: true };
if (code) {
myfind = { ...myfind, code }
}
if (id) {
myqueryadd = {
$addFields: {
myId1: {
$toObjectId: id,
},
},
}
myfind = {
$expr: {
$eq: ["$_id", "$myId1"],
},
}
query.push(myqueryadd);
}
// return await Product.find(myfind);
query.push(
{ $match: myfind },
{
$lookup: {
from: 'producers',
localField: 'idProducer',
foreignField: '_id',
as: 'producer'
}
},
{ $unwind: '$producer' },
{
$lookup: {
from: 'providers',
localField: 'idProvider',
foreignField: '_id',
as: 'provider'
}
},
{ $unwind: '$provider' },
{
$lookup: {
from: 'storehouses',
localField: 'idStorehouses',
foreignField: '_id',
as: 'storehouses'
}
},
{
$lookup: {
from: 'orders',
let: { productId: '$_id' },
pipeline: [
{
$match: {
$expr: {
$and: [
{ $eq: ['$idProduct', '$$productId'] },
{ $lt: ['$status', shared_consts.OrderStatus.ORDER_CONFIRMED] }
]
}
}
},
{
$group: {
_id: null,
totalQty: { $sum: '$quantity' }
}
}
],
as: 'productOrders'
}
},
{
$addFields: {
QuantitaOrdinateInAttesa: {
$cond: {
if: { $isArray: '$productOrders' },
then: { $arrayElemAt: ['$productOrders.totalQty', 0] },
else: 0
}
}
}
},
{
$unset: 'productOrders'
},
);
let ris = await Product.aggregate(query)
return ris;
} catch (e) {
console.error('E', e);
}
};
module.exports.getAllProducts = function (query, sort, callback) {
Product.find(query, null, sort, callback)
}
module.exports.getProductByDepartment = function (query, sort, callback) {
Product.find(query, null, sort, callback)
}
module.exports.getProductByCategory = function (query, sort, callback) {
Product.find(query, null, sort, callback)
}
module.exports.getProductByTitle = function (query, sort, callback) {
Product.find(query, null, sort, callback)
}
module.exports.filterProductByDepartment = function (department, callback) {
let regexp = new RegExp(`^${department}$`, 'i')
var query = { department: { $regex: regexp } };
Product.find(query, callback)
}
module.exports.filterProductByCategory = function (category, callback) {
let regexp = new RegExp(`^${category}$`, 'i')
var query = { category: { $regex: regexp } };
Product.find(query, callback);
}
module.exports.filterProductByTitle = function (title, callback) {
let regexp = new RegExp(`^${title}$`, 'i')
var query = { title: { $regex: regexp } };
Product.find(query, callback);
}
module.exports.getProductByID = function (id, callback) {
Product.findById(id, callback);
}
module.exports.createIndexes((err) => {
if (err) throw err;
});
module.exports.convertAfterImport = async function (idapp, dataObjects) {
const arrprod = await Product.find({ idapp }).lean();
for (const prod of arrprod) {
let setta = false;
// Impostazioni Base:
let objtoset = {
idapp,
img: 'upload/products/' + prod.code + '.jpg',
}
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 = await Producer.create({ idapp, name: prod.producer_name }, (err, recordCreato) => {
return recordCreato
})
}
if (recproducer) {
objtoset = {
...objtoset,
idProducer: recproducer._id,
}
setta = true;
}
}
if (prod.magazzino_name) {
// Cerca il produttore
let recstorehouse = await Storehouse.findOne({ idapp, name: prod.magazzino_name }).lean();
if (!recstorehouse) {
// Non esiste questo produttore, quindi lo creo !
recstorehouse = await Storehouse.create({ idapp, name: prod.magazzino_name }, (err, recordCreato) => {
return recordCreato
})
}
if (recstorehouse) {
objtoset = {
...objtoset,
idStorehouses: [recstorehouse._id],
}
setta = true;
}
}
if (prod.provider_name) {
// Cerca il produttore
let recprovider = await Provider.findOne({ idapp, name: prod.provider_name }).lean();
if (!recprovider) {
// Non esiste questo produttore, quindi lo creo !
recprovider = await Provider.create({ idapp, name: prod.provider_name }, (err, recordCreato) => {
return recordCreato
})
}
if (recprovider) {
objtoset = {
...objtoset,
idProvider: recprovider._id,
}
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,
}
}
}
if (setta) {
await Product.findOneAndUpdate({ _id: prod._id }, { $set: objtoset })
// const campodarimuovere = 'producer_name';
// await Product.findOneAndUpdate({ _id: prod._id }, { $unset: { [campodarimuovere]: 1 } })
}
}
}