const mongoose = require('mongoose').set('debug', false) const Schema = mongoose.Schema; const shared_consts = require('../tools/shared_nodejs'); const { ObjectID } = require('mongodb'); mongoose.Promise = global.Promise; mongoose.level = "F"; // Resolving error Unknown modifier: $pushAll mongoose.plugin(schema => { schema.options.usePushEach = true }); const orderSchema = new Schema({ idapp: { type: String, }, userId: { type: Schema.Types.ObjectId, ref: 'User' }, status: { type: Number, }, idProduct: { type: Schema.Types.ObjectId, ref: 'Product' }, idProducer: { type: Schema.Types.ObjectId, ref: 'Producer' }, idStorehouse: { type: Schema.Types.ObjectId, ref: 'StoreHouse' }, idScontisticas: [{ type: Schema.Types.ObjectId, ref: 'Scontistica' }], idProvider: { type: Schema.Types.ObjectId, ref: 'Provider' }, idGasordine: { type: Schema.Types.ObjectId, ref: 'Gasordine' }, price: { type: Number, default: 0, }, after_price: { type: String }, color: { type: String }, size: { type: String }, quantity: { type: Number, default: 0, }, quantitypreordered: { type: Number, default: 0, }, TotalPriceProduct: { type: Number, default: 0, }, evaso: { // e quindi รจ stato tolto dal magazzino (aggiornando il campo stockQty) type: Boolean, default: false, }, date_evaso: { type: Date }, pagato: { type: Boolean, default: false, }, date_pagato: { type: Date }, spedito: { type: Boolean, default: false, }, date_spedito: { type: Date }, completato: { type: Boolean, default: false, }, date_completato: { type: Date }, consegnato: { type: Boolean, default: false, }, date_consegnato: { type: Date }, ricevuto: { type: Boolean, default: false, }, date_ricevuto: { type: Date }, weight: { type: Number }, unit: { type: Number }, stars: { type: Number }, date_created: { type: Date }, date_checkout: { type: Date }, date_payment: { type: Date }, date_shipping: { type: Date }, date_delivered: { type: Date }, notes: { type: String } }); var Order = module.exports = mongoose.model('Order', orderSchema); module.exports.createIndexes((err) => { if (err) throw err; }); module.exports.getFieldsForSearch = function () { return [] }; module.exports.executeQueryTable = function (idapp, params) { const tools = require('../tools/general'); params.fieldsearch = this.getFieldsForSearch(); return tools.executeQueryTable(this, idapp, params); }; module.exports.findAllIdApp = async function (idapp) { const query = [ { $match: { idapp } }, { $lookup: { from: 'products', localField: 'idProduct', foreignField: '_id', as: 'product' } }, { $lookup: { from: 'productinfos', localField: 'product.idProduct', foreignField: '_id', as: 'product.productInfo' } }, { $unwind: { path: '$product.productInfo', preserveNullAndEmptyArrays: true, }, }, { $lookup: { from: 'producers', localField: 'product.idProducer', foreignField: '_id', as: 'producer' } }, { $lookup: { from: 'providers', localField: 'product.idProvider', foreignField: '_id', as: 'provider' } }, { $lookup: { from: 'gasordines', localField: 'idGasordine', foreignField: '_id', as: 'gasordine' } }, { $unwind: { path: '$gasordine', preserveNullAndEmptyArrays: true, }, }, { $match: { $or: [ { 'gasordine': { $exists: false } }, { 'gasordine.active': true } ] } }, { $lookup: { from: 'scontisticas', localField: 'product.idScontisticas', foreignField: '_id', as: 'scontistica' } }, { $unwind: { path: '$product', preserveNullAndEmptyArrays: true, }, }, { $unwind: { path: '$producer', preserveNullAndEmptyArrays: true, }, }, { $unwind: { path: '$provider', preserveNullAndEmptyArrays: true, }, }, ]; return await Order.aggregate(query) }; module.exports.getAllOrders = function (query, sort, callback) { Order.find(query, null, sort, callback) } module.exports.getOrderByUserId = function (userId, sort, callback) { Order.find({ userId }, null, sort, callback) } module.exports.getOrderByID = function (id, callback) { Order.findById(id, callback); } module.exports.createOrder = async function (order) { try { Order.updateTotals(order); return await Order.create(order) .then((ris) => { if (!!ris) return ris._id; return null; }); } catch (e) { console.error('err', e); } } module.exports.updateStatusOrders = async function (arrOrders, status) { for (const order of arrOrders) { const ret = await this.findOneAndUpdate({ _id: order._id }, { $set: status }); } } module.exports.updateStatusOrdersElements = async function (arrOrders, myelements) { for (const order of arrOrders) { const ret = await this.findOneAndUpdate({ _id: order._id }, { $set: myelements }); } } module.exports.updateTotals = function (order) { try { if (!order) { return; } let mypricecalc = 0; order.TotalPriceProduct = 0; // Calcolo Sconto let sconti_da_applicare = []; if (order.scontisticas) { let qtadascontare = order.quantity + order.quantitypreordered let qtanonscontata = 0 while (qtadascontare > 0) { let scontoapplicato = null for (const sconto of order.scontisticas.filter((rec) => !rec.cumulativo)) { if (qtadascontare >= sconto.qta) { scontoapplicato = sconto scontoapplicato.qtadascontare = sconto.qta } } if (scontoapplicato && scontoapplicato.qtadascontare > 0) { sconti_da_applicare.push(scontoapplicato) qtadascontare -= scontoapplicato.qtadascontare } else { qtanonscontata = qtadascontare qtadascontare = 0 } } /*for (const sconto of order.scontisticas.filter((rec) => rec.cumulativo)) { if ((sconto.qta % order.quantity) === 0) { sconti_da_applicare.push(sconto) } }*/ if (sconti_da_applicare.length > 0) { for (const sconto of sconti_da_applicare) { if (sconto.perc_sconto > 0) { mypricecalc += (sconto.qtadascontare * order.price) * (1 - (sconto.perc_sconto / 100)) } else { mypricecalc += sconto.price } } } if (qtanonscontata > 0) { mypricecalc += order.price * qtanonscontata; } } else { mypricecalc = (order.price * order.quantity) + (order.price * order.quantitypreordered); } order.TotalPriceProduct += mypricecalc; return order; } catch (e) { console.error('Err:', e); } } module.exports.getTotalOrderById = async function (id) { const query = [ { $match: { _id: ObjectID(id) } }, { $lookup: { from: 'products', localField: 'idProduct', foreignField: '_id', as: 'product' } }, { $unwind: { path: '$product', preserveNullAndEmptyArrays: true, }, }, { $lookup: { from: 'productinfos', localField: 'product.idProductInfo', foreignField: '_id', as: 'product.productInfo' } }, { $unwind: { path: '$product.productInfo', preserveNullAndEmptyArrays: true, }, }, { $lookup: { from: 'producers', localField: 'product.idProducer', foreignField: '_id', as: 'producer' } }, { $lookup: { from: 'storehouses', localField: 'idStorehouse', foreignField: '_id', as: 'storehouse' } }, { $lookup: { from: 'providers', localField: 'product.idProvider', foreignField: '_id', as: 'provider' } }, { $lookup: { from: 'gasordines', localField: 'idGasordine', foreignField: '_id', as: 'gasordine' } }, { $unwind: { path: '$gasordine', preserveNullAndEmptyArrays: true, }, }, { $match: { $or: [ { 'gasordine': { $exists: false } }, { 'gasordine.active': true } ] } }, { $lookup: { from: 'scontisticas', localField: 'product.idScontisticas', foreignField: '_id', as: 'scontisticas' } }, { $unwind: { path: '$producer', preserveNullAndEmptyArrays: true, }, }, { $unwind: { path: '$storehouse', preserveNullAndEmptyArrays: true, }, }, { $unwind: { path: '$provider', preserveNullAndEmptyArrays: true, }, }, { $lookup: { from: 'orders', let: { productId: '$product._id' }, pipeline: [ { $match: { $expr: { $and: [ { $eq: ['$idProduct', '$$productId'] }, { $lt: ['$status', shared_consts.OrderStatus.ORDER_CONFIRMED] } ] } } }, { $group: { _id: null, totalQty: { $sum: '$quantity' }, } } ], as: 'productOrders' } }, { $lookup: { from: 'orders', let: { productId: '$product._id' }, pipeline: [ { $match: { $expr: { $and: [ { $eq: ['$idProduct', '$$productId'] }, { $lt: ['$status', shared_consts.OrderStatus.ORDER_CONFIRMED] } ] } } }, { $group: { _id: null, totalQtyPreordered: { $sum: '$quantitypreordered' } } } ], as: 'productPreOrders' } }, { $addFields: { 'product.QuantitaOrdinateInAttesa': { $ifNull: [ { $cond: { if: { $isArray: '$productOrders' }, then: { $arrayElemAt: ['$productOrders.totalQty', 0] }, else: 0 } }, 0 ] }, 'product.QuantitaPrenotateInAttesa': { $ifNull: [ { $cond: { if: { $isArray: '$productPreOrders' }, then: { $arrayElemAt: ['$productPreOrders.totalQtyPreordered', 0] }, else: 0 } }, 0 ] }, }, }, { $addFields: { 'product.quantityAvailable': { $subtract: ["$product.stockQty", "$product.QuantitaOrdinateInAttesa"], }, 'product.bookableAvailableQty': { $subtract: ["$product.bookableQty", "$product.QuantitaPrenotateInAttesa"], } } }, { $unset: 'productOrders' }, { $unset: 'productPreOrders' }, ]; return await Order.aggregate(query); } // const Order = mongoose.model('Order', OrderSchema); // module.exports = { Order };