93 lines
3.5 KiB
JavaScript
93 lines
3.5 KiB
JavaScript
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 } = operation;
|
||
assert(typeof filter?.id === 'string');
|
||
const [account] = await context.select('account', {
|
||
data: {
|
||
id: 1,
|
||
avail: 1,
|
||
pay$account: {
|
||
$entity: 'pay',
|
||
data: {
|
||
id: 1,
|
||
paid: 1,
|
||
price: 1,
|
||
},
|
||
filter: {
|
||
iState: 'paying',
|
||
orderId: {
|
||
$exists: true,
|
||
}
|
||
}
|
||
}
|
||
},
|
||
filter: {
|
||
id: filter.id,
|
||
}
|
||
}, {});
|
||
const { avail, pay$account: 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);
|
||
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;
|
||
},
|
||
},
|
||
];
|
||
export default triggers;
|