oak-pay-business/es/checkers/pay.js

89 lines
3.2 KiB
JavaScript

import { OakInputIllegalException } from 'oak-domain/lib/types';
import { PAY_CHANNEL_ACCOUNT_NAME } from '../types/PayConfig';
const checkers = [
{
entity: 'pay',
type: 'logical',
action: 'create',
checker(operation, context) {
const { data } = operation;
data.refunded = 0;
data.paid = 0;
data.applicationId = context.getApplicationId();
},
},
{
entity: 'pay',
type: 'data',
action: 'create',
checker(data) {
const { channel, price, orderId, accountId } = data;
if (price <= 0) {
throw new OakInputIllegalException('pay', ['price'], '支付金额必须大于0');
}
if (!orderId) {
// 充值类订单
if (!accountId) {
throw new OakInputIllegalException('pay', ['accountId'], '充值类支付必须指定accountId');
}
else if (channel === PAY_CHANNEL_ACCOUNT_NAME) {
throw new OakInputIllegalException('pay', ['channel'], '充值类支付不能使用帐户支付');
}
}
else {
if (channel === PAY_CHANNEL_ACCOUNT_NAME) {
if (!accountId) {
throw new OakInputIllegalException('pay', ['accountId'], '使用account支付必须指向accountId');
}
}
}
}
},
{
entity: 'pay',
type: 'logicalData',
action: 'create',
checker(operation, context) {
const { data } = operation;
const { orderId, price } = data;
if (orderId) {
// 所有已经支付和正在支付的pay之和不能超过订单总和
const order = context.select('order', {
data: {
id: 1,
price: 1,
pay$order: {
$entity: 'pay',
data: {
id: 1,
price: 1,
},
filter: {
iState: {
$in: ['paying', 'paid'],
}
}
}
},
filter: {
id: orderId,
}
}, {});
const checkPays = (order) => {
const { price: orderPrice, pay$order: pays } = order;
let pricePaying = 0;
pays.forEach((pay) => pricePaying += pay.price);
if (pricePaying + price > orderPrice) {
throw new OakInputIllegalException('pay', ['price'], 'pay.create.priceOverflow');
}
};
if (order instanceof Promise) {
return order.then(([o]) => checkPays(o));
}
return checkPays(order[0]);
}
}
}
];
export default checkers;