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

107 lines
4.4 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 assert from 'assert';
import { updateWithdrawState } from './withdraw';
import { getPayClazz } from '../utils/payClazz';
const triggers = [
{
entity: 'withdrawTransfer',
name: '当转账完成或失败后更新withdraw的状态',
action: ['succeed', 'fail'],
when: 'after',
fn: async ({ operation }, context) => {
const { filter, action } = operation;
assert(typeof filter?.id === 'string');
const [transfer] = await context.select('withdrawTransfer', {
data: {
id: 1,
price: 1,
loss: 1,
withdrawId: 1,
withdrawAccount: {
channel: {
entity: 1,
entityId: 1,
},
ofSystemId: 1,
},
},
filter: {
id: filter.id,
}
}, { dontCollect: true });
let cnt = await updateWithdrawState(context, transfer.withdrawId);
if (action === 'succeed') {
// 如果转账成功对应的sysAccount中的余额应减少
const { withdrawAccount, price, loss } = transfer;
const { entity, entityId } = withdrawAccount.channel;
const actualPrice = price - loss;
// wpAccount不可能成为转账账户offline这样取应当是安全的
const payClazz = await getPayClazz(entity, entityId, context);
const [tax] = payClazz.calcTransferTax(actualPrice);
await context.operate('sysAccountOper', {
id: await generateNewIdAsync(),
action: 'create',
data: {
id: await generateNewIdAsync(),
delta: -actualPrice - tax,
entity,
entityId,
withdrawTransferId: transfer.id,
type: 'withdrawTransfer',
}
}, {});
cnt++;
if (tax || loss) {
const systemId = withdrawAccount.ofSystemId;
const [account] = await context.select('account', {
data: {
id: 1,
},
filter: {
entity: 'system',
entityId: systemId,
}
}, { dontCollect: true });
if (loss) {
// loss也进system account的账户
await context.operate('accountOper', {
id: await generateNewIdAsync(),
action: 'create',
data: {
id: await generateNewIdAsync(),
accountId: account.id,
type: 'earn',
totalPlus: loss,
availPlus: loss,
entity: 'withdrawTransfer',
entityId: transfer.id,
},
}, {});
cnt++;
}
if (tax) {
// 如果转账有手续费由system的account来承受
assert(tax > 0);
await context.operate('accountOper', {
id: await generateNewIdAsync(),
action: 'create',
data: {
id: await generateNewIdAsync(),
accountId: account.id,
type: 'tax',
totalPlus: -tax,
availPlus: -tax,
entity: 'withdrawTransfer',
entityId: transfer.id,
},
}, {});
cnt++;
}
}
}
return cnt;
}
}
];
export default triggers;