payOrder.js 12 KB

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