import { Application } from '@feathersjs/express'; import { HookContext } from '@feathersjs/feathers'; import service from 'feathers-mongoose'; import { populate, alterItems } from 'feathers-hooks-common'; import Bluebird from 'bluebird'; import _ from 'lodash'; import Model from '../models/waybill/waybill.model'; import { WaybillSchema } from '../models/waybill/waybill.schema'; import Contractor from '../models/contractor/contractor.model'; import Product from '../models/product/product.model'; const waybills = service({ Model }); const populateSchema = { include: [ { service: 'contractors', nameAs: 'contractor', parentField: 'contractorId', childField: '_id' }, { service: 'products', nameAs: 'product', parentField: 'productId', childField: '_id' }, ] }; const performWaybillOperation = async (id: string, cancel = false) => { const waybill = await Model.findById(id); if (!waybill) return; waybill.status = cancel ? 'cancelled' : 'executed'; const signMultiplier = (waybill.operation === 'in' ? 1 : -1) * (cancel ? -1 : 1); const total = waybill.records.reduce((sum, record) => sum + record.price * record.quantity, 0); await Bluebird.map(waybill.records, record => Product.updateOne( { _id: record.productId }, { $inc: { quantity: record.quantity * signMultiplier } } )); await Contractor.updateOne( { _id: waybill.contractorId }, { $inc: { debt: total * signMultiplier * (-1) } } ); return waybill.save(); }; const addFields = (item: WaybillSchema) => { const { operation, records } = item; const total = item.records.reduce((sum, record) => sum + record.price * record.quantity, 0); const op = operation === 'in' ? 'приход' : 'расход'; const name = `Накладная: ${op} $${total}`; return { name, total, ...item }; }; export default (app: Application): void => { app.use('/waybills', waybills); app.post('/waybills/:id/execute', async (req, res) => { const result = await performWaybillOperation(req.params.id); res.send(result); }); app.post('/waybills/:id/cancel', async (req, res) => { const result = await performWaybillOperation(req.params.id, true); res.send(result); }); app.service('waybills').hooks({ after: { all: [ populate({ schema: populateSchema }), alterItems(addFields) ], }, }) };