payOrder.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. 'use strict';
  2. const { CrudService } = require('naf-framework-mongoose-free/lib/service');
  3. const { BusinessError, ErrorCode } = require('naf-core').Error;
  4. const _ = require('lodash');
  5. const assert = require('assert');
  6. const moment = require('moment');
  7. //
  8. class PayOrderService extends CrudService {
  9. constructor(ctx) {
  10. super(ctx, 'payorder');
  11. this.model = this.ctx.model.Race.PayOrder;
  12. this.payService = this.ctx.service.wxpay;
  13. this.matchSignModel = this.ctx.model.Race.MatchSign;
  14. this.billModel = this.ctx.model.Race.Bill;
  15. }
  16. async beforeCreate(data) {
  17. if (!_.get(data, 'order_no')) data.order_no = this.getOrderNo();
  18. return data;
  19. }
  20. async afterCreate(body, data) {
  21. const wxSign = await this.payService.create(data);
  22. return { data, wxSign };
  23. }
  24. async afterUpdate(filter, body, data) {
  25. await this.syncData(data);
  26. return data;
  27. }
  28. // 同步修改----针对账单
  29. async syncData(data) {
  30. const { status } = data;
  31. // 未支付状态不做处理
  32. if (status === '0') return data;
  33. // 支付失败也不做处理
  34. if (status === '-1') return data;
  35. // 只有支付成功和退款才进行操作;不过这个退款是走线下,其实也没有
  36. if (status === '-3') throw new BusinessError(ErrorCode.DATA_INVALID, '退款应该是线下退款');
  37. const obj = _.pick(data, [ 'match_id', 'group_id', 'project_id' ]);
  38. const { _id: pay_id, status: pay_status, payer_id: user_id, money } = data;
  39. // 报名数据
  40. const signData = { ...obj, pay_id, pay_status, user_id };
  41. // 账单数据
  42. 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 };
  43. // 生成报名数据,与账单数据. 如果失败,则删除报名数据并提示联系管理员
  44. const sign = await this.matchSignModel.create(signData);
  45. try {
  46. await this.billModel.create(billData);
  47. } catch (error) {
  48. await this.matchSignModel.deleteOne({ _id: sign._id });
  49. throw new BusinessError(ErrorCode.SERVICE_FAULT, '支付失败,请联系管理员处理该报名情况');
  50. }
  51. }
  52. getOrderNo() {
  53. return `ONCAPPRACE${moment().format('YYYYMMDDHHmmss')}-${_.random(1, 999999)}`;
  54. }
  55. }
  56. module.exports = PayOrderService;