From 0bc7ef4bd32e5e65db502eec63f9723f345a66d7 Mon Sep 17 00:00:00 2001 From: eug-vs Date: Sat, 24 Apr 2021 21:11:10 +0300 Subject: feat: change balance when applying transfer --- src/services/transfers.service.ts | 28 +++++++++++++++++++++------- 1 file changed, 21 insertions(+), 7 deletions(-) (limited to 'src/services/transfers.service.ts') diff --git a/src/services/transfers.service.ts b/src/services/transfers.service.ts index d835844..1f8aaf5 100644 --- a/src/services/transfers.service.ts +++ b/src/services/transfers.service.ts @@ -26,19 +26,33 @@ const addFields = (item: any) => { }; const applyTransfer = async (context: HookContext): Promise => { - const { contractorId, amount, operation } = getItems(context); + const { contractorId, accountId, amount, operation } = getItems(context); // If amount is not supplied, do nothing if (!amount) return context; const inc = amount - (context.params.before?.amount || 0); - const sign = (operation === 'in' ? -1 : 1) * (context.method === 'remove' ? -1 : 1); + const sign = (operation === 'in' ? 1 : -1) * (context.method === 'remove' ? -1 : 1); + + if (inc) { + // TODO: start transaction + await context.app + .service('accounts') + .patch(accountId, { + $inc: { + balance: inc * sign + } + }); + + await context.app + .service('contractors') + .patch(contractorId, { + $inc: { + debt: inc * sign * (-1) + } + }); + } - if (inc) await context.app.service('contractors').patch(contractorId, { - $inc: { - debt: inc * sign - } - }); return context; }; -- cgit v1.2.3