payOrder.js 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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.Business.PayOrder;
  12. this.payService = this.ctx.service.wxpay;
  13. this.lessonStudentModel = this.ctx.model.Business.LessonStudent;
  14. this.lessonStudentService = this.ctx.service.business.lessonStudent;
  15. this.chargeModel = this.ctx.model.Business.Charge;
  16. this.tempLessonApplyModel = this.ctx.model.Apply.TempLessonApply;
  17. this.userModel = this.ctx.model.User.User;
  18. this.studentModel = this.ctx.model.User.Student;
  19. this.coachModel = this.ctx.model.User.Coach;
  20. this.rcsModel = this.ctx.model.Relation.RelationCoachSchool;
  21. this.rssModel = this.ctx.model.Relation.RelationStudentSchool;
  22. this.costDetailModel = this.ctx.model.Business.CostDetail;
  23. }
  24. async beforeCreate(data) {
  25. if (!_.get(data, 'order_no')) data.order_no = this.getOrderNo();
  26. const { data: nd, next } = await this.checkSurplus(data);
  27. if (!next) throw new BusinessError(0, '扣除余额成功');
  28. data = nd;
  29. return data;
  30. }
  31. // 检查是否扣除余额
  32. async checkSurplus(data) {
  33. const pay_for = _.get(data, 'pay_for');
  34. // 充值不检查余额
  35. if (pay_for && pay_for === 'charge') return { data, next: true };
  36. const payer_id = _.get(data, 'payer_id');
  37. const payer_role = _.get(data, 'payer_role');
  38. let costDetailData;
  39. let relation;
  40. // 没有要支付的人及其角色,那就找不到余额,返回下单
  41. if (!(payer_id && payer_role)) return { data, next: true };
  42. // 有支付的人,可以查查这个人的余额
  43. if (payer_role === 'Student') relation = await this.rssModel.findOne({ student_id: payer_id });
  44. else if (payer_role === 'Coach') relation = await this.rcsModel.findOne({ coach_id: payer_id });
  45. // 没找到关系,那就直接返回正常下单缴费
  46. if (!relation) return { data, next: true };
  47. // 有关系,找余额
  48. const { money: surplus } = relation;
  49. const { money } = data;
  50. // 没有余额,或者余额没钱,返回正常下单缴费
  51. if (surplus && surplus <= 0) return { data, next: true };
  52. // 有余额,看余额够不够
  53. if (surplus >= money) {
  54. try {
  55. // 余额够, 无需生成订单,直接去使用余额缴费
  56. const costDetail = _.pick(data, [ 'school_id', 'payer_id', 'payer_role', 'pay_for', 'from_id' ]);
  57. // 本次扣除余额的金额就是本次需要支付的金额
  58. costDetail.money = money;
  59. costDetail.type = '1';
  60. costDetailData = await this.costDetailModel.create(costDetail);
  61. // 余额需要扣除本次支付的费用
  62. relation.money = surplus - money;
  63. await relation.save();
  64. return false;
  65. } catch (error) {
  66. // 抓取数据库创建和修改的异常,
  67. // 如果 costDetailData没有值,说明是创建消费记录时发生的错误,不需要做回滚处理;如果有值,那就删除
  68. if (costDetailData) {
  69. await this.costDetailModel.deleteOne({ _id: costDetailData._id });
  70. }
  71. // 如果是余额修改错误,上面的回滚删除就足够了.因为保存新余额发生错误,余额不会保存,只要把消费记录删了,就回到原样了
  72. }
  73. } else {
  74. // 余额不够,在config里记录部分使用了余额,再进行下单,下单完后,生成余额的扣款
  75. const needPay = surplus - money;
  76. const costDetail = _.pick(data, [ 'school_id', 'payer_id', 'payer_role', 'pay_for', 'from_id' ]);
  77. costDetail.money = surplus;
  78. costDetail.type = '1';
  79. if (!data.config) data.config = {};
  80. // 添加余额的设置, 等支付成功后,再生成余额的消费记录
  81. data.config.useSurplus = true;
  82. data.config.costDetail = costDetail;
  83. data.money = needPay;
  84. }
  85. return { data, next: true };
  86. }
  87. async afterCreate(body, data) {
  88. await this.syncData(data);
  89. const wxSign = await this.payService.create(data);
  90. return { data, wxSign };
  91. }
  92. async afterUpdate(filter, body, data) {
  93. await this.syncData(data);
  94. return data;
  95. }
  96. /**
  97. * 支付同步
  98. * @param {Object} data 支付单数据
  99. */
  100. async syncData(data) {
  101. const pay_for = _.get(data, 'pay_for');
  102. // 不知道该去同步哪个表的支付状态,不处理
  103. if (!pay_for) return;
  104. const { from_id: _id, status: is_pay, money, _id: pay_id, config } = data;
  105. if (pay_for === 'lessonStudent') {
  106. // 因为上课产生的支付,去找lessonStudent,修改指定学生的支付状态
  107. await this.lessonStudentModel.updateOne({ _id }, { is_pay });
  108. } else if (pay_for === 'tempLessonApply') {
  109. // 私教课临时上课,需要到临时申请那找到相关数据
  110. const tempApply = await this.tempLessonApplyModel.findById(_id);
  111. if (!tempApply) return;
  112. tempApply.pay_id = pay_id;
  113. await tempApply.save();
  114. // 修改完申请,再创建 lessonStudent
  115. const { lesson_id, student_id, school_id } = tempApply;
  116. const obj = { lesson_id, student_id, school_id, is_pay, pay_id, config, money };
  117. await this.lessonStudentService.create(obj);
  118. } else if (pay_for === 'charge' && is_pay !== '0') {
  119. // 充值记录,找到充值记录,没有就生成
  120. const chargeData = await this.chargeModel.findOne({ pay_id });
  121. if (chargeData) {
  122. // 有就修改
  123. chargeData.is_pay = is_pay;
  124. await chargeData.save();
  125. } else {
  126. const obj = _.pick(data, [ 'school_id', 'payer_id', 'payer_role' ]);
  127. await this.chargeModel.create({ ...obj, pay_id, is_pay, time: moment().format('YYYY-MM-DD HH:mm:ss') });
  128. }
  129. }
  130. }
  131. /**
  132. * 重新支付
  133. * @param {String} body 参数体
  134. * @property {String} id 数据id
  135. */
  136. async toRePay({ id }) {
  137. const data = await this.model.findById(id);
  138. if (!data) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到支付的信息');
  139. // 找到这个订单,然后获取到订单号
  140. const { order_no } = data;
  141. // 利用订单号去查询微信那边,该订单是否还存在
  142. const wxOrder = await this.payService.search(order_no);
  143. let wxSign;
  144. if (_.get(wxOrder, 'trade_state') === 'NOTPAY') {
  145. // 未支付就用原数据,去支付
  146. wxSign = await this.payService.create(data);
  147. } else if (_.get(wxOrder, 'trade_state') === 'SUCCESS') {
  148. throw new BusinessError(ErrorCode.SERVICE_FAULT, '订单已支付,无需重复支付');
  149. } else if (_.get(wxOrder, 'trade_state') === 'USERPAYING') {
  150. throw new BusinessError(ErrorCode.SERVICE_FAULT, '订单支付中');
  151. } else {
  152. // 其他情况就当订单被关闭了.直接新订单
  153. const order_no = this.getOrderNo();
  154. data.order_no = order_no;
  155. await data.save();
  156. wxSign = await this.payService.create(data);
  157. }
  158. return { data, wxSign };
  159. }
  160. /**
  161. * 申请退款
  162. * @param {Object} body 参数体
  163. * @property {String} id 支付单的数据id
  164. */
  165. async toRefund({ id }) {
  166. // 查询支付
  167. const data = await this.model.findById(id);
  168. if (!data) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到要退款的支付数据');
  169. const wxOrderReq = await this.payService.search(data.order_no);
  170. if (wxOrderReq) {
  171. if (!wxOrderReq) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未查询到微信支付订单');
  172. const wxRefundReq = await this.payService.refund(data.order_no, '退赛');
  173. if (wxRefundReq) {
  174. if (wxRefundReq.status !== 'REFUND') throw new BusinessError(ErrorCode.SERVICE_FAULT, '退款失败');
  175. // 退款成功
  176. data.status = '-3';
  177. await data.save();
  178. await this.syncData(data);
  179. return 'ok';
  180. }
  181. }
  182. throw new BusinessError(ErrorCode.SERVICE_FAULT, '查询微信支付订单失败');
  183. }
  184. /**
  185. * 关闭订单
  186. * @param {String} id 支付id
  187. * @return {Object} 关闭订单结果
  188. */
  189. async closeOrder(id) {
  190. const data = await this.model.findById(id);
  191. if (!data) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到要退款的支付数据');
  192. const res = await this.payService.close(data.order_no);
  193. return res;
  194. }
  195. getOrderNo() {
  196. return `ONCAPP${moment().format('YYYYMMDDHHmmss')}-${_.random(1, 999999)}`;
  197. }
  198. // 二维码扫码
  199. async toPayNative(body) {
  200. body = await this.beforeCreate(body);
  201. const data = await this.model.create(body);
  202. const qrcode = await this.payService.createNative({ ...body, notice_url: '/newCourt/v2/api/payOrder/nativeReturn' });
  203. return qrcode;
  204. }
  205. // 二维码扫码回调
  206. async nativeReturn(body) {
  207. const result = _.get(body, 'result');
  208. if (!result) throw new BusinessError(ErrorCode.BADPARAM, '参数错误');
  209. const { out_trade_no: order_no, trade_state, payer } = result;
  210. const obj = {};
  211. if (trade_state === 'SUCCESS') obj.status = '1';
  212. else if (trade_state === 'REFUND') obj.status = '-3';
  213. const openid = _.get(payer, 'openid');
  214. if (openid) {
  215. obj.openid = openid;
  216. // 找payer_id的信息,学员,教练
  217. const user = await this.userModel.findOne({ openid });
  218. if (user) {
  219. const { _id: user_id } = user;
  220. let roleUser = await this.studentModel.findOne({ user_id });
  221. if (!roleUser) {
  222. roleUser = await this.coachModel.findOne({ user_id });
  223. if (roleUser) {
  224. obj.payer_role = 'Coach';
  225. obj.payer_id = roleUser._id;
  226. }
  227. } else {
  228. obj.payer_role = 'Student';
  229. obj.payer_id = roleUser._id;
  230. }
  231. }
  232. }
  233. await this.model.updateOne({ order_no }, obj);
  234. const data = await this.model.findOne({ order_no });
  235. await this.syncData(data);
  236. }
  237. }
  238. module.exports = PayOrderService;