diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/services/waybills.service.ts | 58 | 
1 files changed, 26 insertions, 32 deletions
diff --git a/src/services/waybills.service.ts b/src/services/waybills.service.ts index cf4bd7e..8c8c718 100644 --- a/src/services/waybills.service.ts +++ b/src/services/waybills.service.ts @@ -28,36 +28,37 @@ const populateSchema = {    ]  }; -const performWaybillOperation = async (id: string, cancel = false) => { -  const waybill = await Model.findById(id); -  if (!waybill) return; -  waybill.status = cancel ? 'cancelled' : 'executed'; +const reflectStatus = async (context: HookContext): Promise<HookContext> => { +  const { status } = context.data; +  if (['cancelled', 'executed'].includes(status) && context.id) { +    const waybill: WaybillSchema = await context.service.get(context.id); -  const signMultiplier = (waybill.operation === 'in' ? 1 : -1) * (cancel ? -1 : 1); -  const total = waybill.records.reduce((sum, record) => sum + record.price * record.quantity, 0); +    const signMultiplier = (waybill.operation === 'in' ? 1 : -1) * (status === 'cancelled' ? -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 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) +    await Contractor.updateOne( +      { _id: waybill.contractorId }, +      { +        $inc: { +          debt: total * signMultiplier * (-1) +        }        } -    } -  ); - -  return waybill.save(); +    ); +  } +  return context;  }; +  const addFields = (item: WaybillSchema) => {    const { operation, records } = item;    const total = item.records.reduce((sum, record) => sum + record.price * record.quantity, 0); @@ -69,16 +70,6 @@ const addFields = (item: WaybillSchema) => {  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: [ @@ -86,6 +77,9 @@ export default (app: Application): void => {          alterItems(addFields)        ],      }, +    before: { +      patch: reflectStatus, +    },    })  };  |