import { Application } from '@feathersjs/express'; import { HookContext } from '@feathersjs/feathers'; import service from 'feathers-mongoose'; import { populate } from 'feathers-hooks-common'; import Bluebird from 'bluebird'; import _ from 'lodash'; import Model from '../models/waybill/waybill.model'; 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 product = await Product.findById(waybill.productId); if (!product) return; product.quantity += waybill.quantity * signMultiplier; if (product.quantity < 0) console.log('ВНИМАНИЕ: Недостаточно товара на складе'); const contractor = await Contractor.findById(waybill.contractorId); if (!contractor) return; contractor.debt -= waybill.quantity * product.price * signMultiplier; return Bluebird.all([waybill.save(), product.save(), contractor.save()]); }; const addName = (context: HookContext): HookContext => { const { result: { operation, product, quantity } } = context; const name = `Накладная: ${product?.name} ${operation === 'in' ? 'приход' : 'расход' } ${quantity} шт.` return _.set(context, 'result.name', name); }; 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 }), addName], }, }) };