oak-pay-business/es/triggers/account.js

98 lines
4.0 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { generateNewIdAsync } from 'oak-domain/lib/utils/uuid';
import { DATA_SUBSCRIBER_KEYS } from '../config/constants';
import assert from 'assert';
const triggers = [
{
name: '当account帐户的值发生变化时向订阅者推送',
entity: 'account',
action: ['deposit', 'withdraw', 'withdrawBack', 'consume', 'loan', 'repay'],
check(operation) {
return operation.data.hasOwnProperty('total') || operation.data.hasOwnProperty('avail');
},
when: 'after',
fn: async ({ operation }, context, option) => {
const { id, filter } = operation;
assert(typeof filter?.id === 'string');
context.saveOperationToEvent(id, `${DATA_SUBSCRIBER_KEYS.accountNumberChanged}-${filter.id}`);
return 1;
},
},
{
name: '当account帐户的avail增加时如果有等待中的pay则继续完成支付',
entity: 'account',
action: ['deposit', 'withdrawBack', 'repay'],
when: 'after',
fn: async ({ operation }, context, option) => {
const { id, filter, data } = operation;
assert(typeof filter?.id === 'string');
if (data.avail && data.avail > 0) {
const [account] = await context.select('account', {
data: {
id: 1,
avail: 1,
pay$entity: {
$entity: 'pay',
data: {
id: 1,
paid: 1,
price: 1,
},
filter: {
iState: 'unpaid',
orderId: {
$exists: true,
}
}
}
},
filter: {
id: filter.id,
}
}, {});
const { avail, pay$entity: pays } = account;
let rest = avail;
let count = 0;
if (pays && pays.length > 0) {
for (const pay of pays) {
if (rest === 0) {
break;
}
const { price, paid } = pay;
const paid2 = Math.min(price - paid, rest);
if (paid2 > 0) {
await context.operate('pay', {
id: await generateNewIdAsync(),
action: 'continuePaying',
data: {
paid: paid + paid2,
accountOper$entity: [
{
id: await generateNewIdAsync(),
action: 'create',
data: {
id: await generateNewIdAsync(),
type: 'consume',
availPlus: -paid2,
totalPlus: -paid2,
accountId: filter.id,
}
}
]
},
filter: {
id: pay.id,
}
}, {});
rest = rest - paid2;
count++;
}
}
}
return 1;
}
return 0;
},
},
];
export default triggers;