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

531 lines
12 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-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,
},
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' }
],
2023-12-16 00:51:03 +01:00
idScontisticas: [
{ type: Schema.Types.ObjectId, ref: 'Scontistica' }
],
idProvider: { type: Schema.Types.ObjectId, ref: 'Provider' },
2021-01-18 00:48:17 +01:00
code: {
type: String,
unique: true,
2021-01-18 00:48:17 +01:00
},
codice_EAN: {
type: String,
},
barcode: {
type: String,
},
2020-12-21 02:16:42 +01:00
name: {
type: String,
},
description: {
type: String,
},
department: {
2020-12-25 03:54:16 +01:00
type: String, ref: 'Department'
2020-12-21 02:16:42 +01:00
},
category: {
2023-11-28 14:20:22 +01:00
type: Array,
},
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
},
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
},
2020-12-21 02:16:42 +01:00
color: {
type: String
},
size: {
type: String
},
2020-12-25 03:54:16 +01:00
weight: {
type: Number
},
vegan: {
type: Boolean
},
2023-11-30 14:27:37 +01:00
unit: {
type: Number
},
stockQty: { // in magazzino
type: Number,
2023-12-12 15:42:41 +01:00
default: 0,
},
2023-12-20 21:52:17 +01:00
bookableQty: { // Quantità prenotabili
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
},
2020-12-21 02:16:42 +01:00
icon: {
type: String,
},
img: {
type: String,
},
2023-12-14 15:20:21 +01:00
link: {
type: String,
},
2021-01-18 00:48:17 +01:00
img2: {
type: String,
},
img3: {
type: String,
},
ingredienti: {
type: String,
},
valori_nutrizionali: {
type: String,
},
note: {
type: String,
},
2023-12-14 15:20:21 +01:00
producer_name: {
type: String,
},
provider_name: {
type: String,
},
magazzino_name: {
type: String,
},
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 () {
2020-12-25 03:54:16 +01:00
return [{ field: 'name', 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.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
module.exports.findAllIdApp = async function (idapp, code, id) {
let myfind = {};
let myqueryadd = {};
let query = [];
2020-12-25 03:54:16 +01:00
try {
if (idapp)
myfind = { idapp, 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,
},
},
{
$lookup: {
from: 'providers',
localField: 'idProvider',
foreignField: '_id',
as: 'provider'
}
},
2023-12-16 00:51:03 +01:00
{
$unwind: {
path: '$provider',
preserveNullAndEmptyArrays: true,
},
},
{
$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'] },
{ $lt: ['$status', shared_consts.OrderStatus.ORDER_CONFIRMED] }
]
}
}
},
{
$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'] },
{ $lt: ['$status', shared_consts.OrderStatus.ORDER_CONFIRMED] }
]
}
}
},
{
$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: ["$bookableQty", "$QuantitaPrenotateInAttesa"],
2023-12-12 15:42:41 +01:00
}
}
},
{
$unset: 'productOrders'
},
2023-12-20 21:52:17 +01:00
{
$unset: 'productPreOrders'
},
2023-12-13 19:17:53 +01:00
);
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)
}
2020-12-25 03:54:16 +01:00
module.exports.getProductByCategory = 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)
}
module.exports.filterProductByCategory = function (category, callback) {
let regexp = new RegExp(`^${category}$`, 'i')
2020-12-21 02:16:42 +01:00
var query = { category: { $regex: regexp } };
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) {
if (order.product)
order.product = await Product.getProductById(order.product._id);
return order;
}
2023-12-09 11:55:58 +01:00
module.exports.createIndexes((err) => {
if (err) throw err;
});
2023-11-28 15:04:17 +01:00
module.exports.convertAfterImport = 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) {
2023-12-18 12:11:12 +01:00
await this.singlerecconvert_AfterImport(prod);
}
};
module.exports.singlerecconvert_AfterImport = async function (idapp, prod) {
let setta = false;
2023-12-18 12:11:12 +01:00
try {
// Impostazioni Base:
let objtoset = {
idapp,
img: 'upload/products/' + prod.code + '.jpg',
}
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
}
}
// 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
if (setta) {
2023-12-18 12:11:12 +01:00
const ris = await Product.findOneAndUpdate({ _id: ObjectID(prod._id) }, { $set: objtoset })
if (ris) {
console.log('ris', ris);
}
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);
}
2023-12-18 12:11:12 +01:00
}