12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- 'use strict';
- const { CrudService } = require('naf-framework-mongoose-free/lib/service');
- const { BusinessError, ErrorCode } = require('naf-core').Error;
- const _ = require('lodash');
- const assert = require('assert');
- const moment = require('moment');
- //
- class PayOrderService extends CrudService {
- constructor(ctx) {
- super(ctx, 'payorder');
- this.model = this.ctx.model.Race.PayOrder;
- this.payService = this.ctx.service.wxpay;
- this.matchSignModel = this.ctx.model.Race.MatchSign;
- this.billModel = this.ctx.model.Race.Bill;
- }
- async beforeCreate(data) {
- if (!_.get(data, 'order_no')) data.order_no = this.getOrderNo();
- return data;
- }
- async afterCreate(body, data) {
- const wxSign = await this.payService.create(data);
- return { data, wxSign };
- }
- async afterUpdate(filter, body, data) {
- await this.syncData(data);
- return data;
- }
- // 同步修改----针对账单
- async syncData(data) {
- const { status } = data;
- // 未支付状态不做处理
- if (status === '0') return data;
- // 支付失败也不做处理
- if (status === '-1') return data;
- // 只有支付成功和退款才进行操作;不过这个退款是走线下,其实也没有
- if (status === '-3') throw new BusinessError(ErrorCode.DATA_INVALID, '退款应该是线下退款');
- const obj = _.pick(data, [ 'match_id', 'group_id', 'project_id' ]);
- const { _id: pay_id, status: pay_status, payer_id: user_id, money } = data;
- // 报名数据
- const signData = { ...obj, pay_id, pay_status, user_id };
- // 账单数据
- const billData = { ...obj, pay_id, payer_id: data.payer_id, type: '1', time: moment().format('YYYY-MM-DD HH:mm:ss'), is_pay: pay_status, money };
- // 生成报名数据,与账单数据. 如果失败,则删除报名数据并提示联系管理员
- const sign = await this.matchSignModel.create(signData);
- try {
- await this.billModel.create(billData);
- } catch (error) {
- await this.matchSignModel.deleteOne({ _id: sign._id });
- throw new BusinessError(ErrorCode.SERVICE_FAULT, '支付失败,请联系管理员处理该报名情况');
- }
- }
- getOrderNo() {
- return `ONCAPPRACE${moment().format('YYYYMMDDHHmmss')}-${_.random(1, 999999)}`;
- }
- }
- module.exports = PayOrderService;
|