1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
|
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';
const waybills = service({ Model });
const populateSchema = {
include: [
{
service: 'contractors',
nameAs: 'contractor',
parentField: 'contractorId',
childField: '_id'
},
{
service: 'products',
nameAs: 'product',
parentField: 'productId',
childField: '_id'
},
]
};
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) * (status === 'cancelled' ? -1 : 1);
const total = waybill.records.reduce((sum, record) => sum + record.price * record.quantity, 0);
await Bluebird.map(waybill.records, record => {
return context.app.service('products').patch(record.productId, {
$inc: {
quantity: record.quantity * signMultiplier
}
});
});
await context.app.service('contractors').patch(waybill.contractorId, {
$inc: {
debt: total * signMultiplier * (-1)
}
});
}
return context;
};
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.service('waybills').hooks({
after: {
all: [
populate({ schema: populateSchema }),
alterItems(addFields)
],
},
before: {
patch: reflectStatus,
},
})
};
|