payOrder.js 11 KB

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