diff options
author | eug-vs <eug-vs@keemail.me> | 2021-03-16 00:50:08 +0300 |
---|---|---|
committer | eug-vs <eug-vs@keemail.me> | 2021-03-16 00:50:08 +0300 |
commit | f20f6ac6785510be9c36a942277271f82db277ce (patch) | |
tree | 315a9eb127cd9ecf966be023870230e4f832bee6 | |
parent | 3b0e3280421c94089cd86e833246daebe5424fc9 (diff) | |
download | commercel-api-f20f6ac6785510be9c36a942277271f82db277ce.tar.gz |
feat: add execute/cancel waybill endpoints
-rw-r--r-- | src/services/waybills.service.ts | 33 |
1 files changed, 33 insertions, 0 deletions
diff --git a/src/services/waybills.service.ts b/src/services/waybills.service.ts index e947f0a..961516e 100644 --- a/src/services/waybills.service.ts +++ b/src/services/waybills.service.ts @@ -2,8 +2,11 @@ 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 }); @@ -24,6 +27,25 @@ const populateSchema = { ] }; +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} шт.` @@ -32,6 +54,17 @@ const addName = (context: HookContext): HookContext => { 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], |