afterSale.js 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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 { ObjectId } = require('mongoose').Types;
  7. const moment = require('moment');
  8. const Transaction = require('mongoose-transactions');
  9. //
  10. class AfterSaleService extends CrudService {
  11. constructor(ctx) {
  12. super(ctx, 'aftersale');
  13. this.model = this.ctx.model.Trade.AfterSale;
  14. this.orderDetailModel = this.ctx.model.Trade.OrderDetail;
  15. this.tran = new Transaction();
  16. }
  17. async create({ order_detail, goods_id, ...others }) {
  18. const orderDetail = await this.orderDetailModel.findById(order_detail);
  19. if (!orderDetail) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到订单信息');
  20. // 查看订单是否签收
  21. // 查看该商品是否已经申请售后
  22. const hasData = await this.model.count({ order_detail, 'goods._id': goods_id, type: [ '0', '1', '2', '3' ] });
  23. if (hasData > 0) throw new BusinessError(ErrorCode.DATA_EXISTED, '该商品已有正在处理中的售后申请.请勿重复申请');
  24. const { goods: goodsList } = orderDetail;
  25. const goods = goodsList.find(f => ObjectId(f._id).equals(goods_id));
  26. if (!goods) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未在当前订单中搜索到要售后的商品');
  27. const { shop, customer } = orderDetail;
  28. const apply_time = moment().format('YYYY-MM-DD HH:mm:ss');
  29. const obj = { order_detail, customer, shop, goods, ...others, apply_time, status: '0' };
  30. await this.model.create(obj);
  31. }
  32. async update(filter, update, { projection } = {}) {
  33. assert(filter);
  34. assert(update);
  35. const beforeUpdateResult = await this.beforeUpdate(filter, update);
  36. filter = beforeUpdateResult.filter;
  37. update = beforeUpdateResult.update;
  38. const { _id, id } = filter;
  39. if (_id || id) filter = { _id: ObjectId(_id || id) };
  40. // 检查数据是否存在
  41. const entity = await this.model.findOne(filter).exec();
  42. if (!entity) throw new BusinessError(ErrorCode.DATA_NOT_EXIST);
  43. // 修改数据
  44. try {
  45. this.tran.update('AfterSale', entity._id, update);
  46. await this.tran.run();
  47. const type = _.get(entity, 'type');
  48. const status = _.get(update, 'status');
  49. // 同意退款,则直接进行退款,然后再将状态修改为已退款
  50. if (type !== '2' && status === '1') {
  51. await this.toRefund({ afterSale_id: entity._id, goods_id: _.get(entity, 'goods._id') }, this.tran);
  52. }
  53. await this.tran.run();
  54. } catch (error) {
  55. console.error(error);
  56. await this.tran.rollback();
  57. throw new BusinessError(ErrorCode.SERVICE_FAULT, '售后:修改失败');
  58. }
  59. const reSearchData = await this.model.findOne(filter, projection).exec();
  60. return reSearchData;
  61. }
  62. /**
  63. * 退款
  64. * @param {Object} param 参数
  65. * @param param.afterSale_id 售后申请id
  66. * @param param.goods_id 商品规格id
  67. * @param {Transaction} tran 事务的实例
  68. */
  69. async toRefund({ afterSale_id, goods_id }, tran) {
  70. const data = await this.model.findById(afterSale_id);
  71. if (!data) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到售后信息');
  72. const { populate } = this.ctx.service.trade.orderDetail.getRefMods();
  73. const orderDetail = await this.orderDetailModel.findById(data.order_detail).populate(populate);
  74. if (!orderDetail) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到售后信息的订单');
  75. // 计算商品原价,运费
  76. let money = this.ctx.multiply(_.get(data, 'goods.sell_money'), _.get(data, 'goods.buy_num'));
  77. const freight = this.ctx.multiply(_.get(data, 'goods.buy_num'), _.get(data, 'goods.freight'));
  78. money = this.ctx.plus(money, freight);
  79. const reason = _.get(data, 'desc');
  80. const order_no = _.get(orderDetail, 'order.pay.pay_no');
  81. if (!order_no) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到支付订单号');
  82. // 查查优惠中,是否有这个商品:将这个商品的每一个优惠券的优惠部分都加一起,然后用原价-优惠价=实付价
  83. const discount_detail = _.get(orderDetail, 'total_detail.discount_detail');
  84. if (discount_detail) {
  85. let discountMoney = 0;
  86. for (const uc_id in discount_detail) {
  87. const detail = discount_detail[uc_id];
  88. discountMoney = this.ctx.plus(discountMoney, detail[goods_id]);
  89. }
  90. money = this.ctx.minus(money, discountMoney);
  91. }
  92. // 取出商品输入的价格
  93. const needRefund = _.get(data, 'money');
  94. let refundMoney = 0;
  95. if (money === needRefund) {
  96. // 如果这俩价格相同,说明是正常退
  97. refundMoney = money;
  98. } else {
  99. // 部分退,部分退是不退优惠券的
  100. refundMoney = needRefund;
  101. }
  102. // 找下当前这个订单有多少次售后记录
  103. let num = await this.model.count({ order_detail: data.order_detail });
  104. num += 2;
  105. // 组成退款单号
  106. const out_refund_no = `${order_no}-r${num}`;
  107. const obj = { reason, money: refundMoney, order_no, out_refund_no };
  108. // 退款请求
  109. const res = await this.ctx.service.trade.pay.refund(obj);
  110. if (res.errcode && res.errcode !== 0) throw new BusinessError(ErrorCode.SERVICE_FAULT, res.errmsg);
  111. tran.update('AfterSale', afterSale_id, { status: '-1' });
  112. await tran.run();
  113. // 检查优惠券是否都退了
  114. // 查看支付订单-优惠明细中,该优惠券影响的商品是否都有退款/退货成功的记录,且退款成功的记录为退全款的.退部分是不退优惠券的
  115. // 如果有,就说明该优惠券可以退了,没有影响任何一单了
  116. const payOrder = _.get(orderDetail, 'order');
  117. await this.checkToReturnUserCoupon(payOrder, tran);
  118. }
  119. /**
  120. * 检查订单的优惠券并退优惠券, 必须是退全款,部分退款不退优惠券
  121. * @param {Object} order 订单信息
  122. * @param {Transaction} tran 事务的实例
  123. */
  124. async checkToReturnUserCoupon(order, tran) {
  125. // 该支付订单下所有拆分的子订单
  126. const orderDetailList = await this.orderDetailModel.find({ order: order._id });
  127. // 已退款记录
  128. const goodsRefundList = [];
  129. for (const od of orderDetailList) {
  130. const { goods, _id: order_detail } = od;
  131. // 组合成查售后的条件
  132. // 然后查这些商品有没有退款审核成功的记录, 且只有退全款的商品才能退券
  133. const afterSaleQuerys = goods.map(i => ({ order_detail, 'goods._id': i._id, status: '-1' }));
  134. for (const asq of afterSaleQuerys) {
  135. const asd = await this.model.findOne(asq);
  136. if (asd) {
  137. // 商品有退款审核通过的记录,查询每个商品是否退的是全款
  138. // money: 实际退款的金额
  139. const { money } = asd;
  140. const od_id = _.get(asd, 'order_detail');
  141. const goods_id = _.get(asd, 'goods._id');
  142. const moneyDetail = await this.computedGoodsForRefund({ order_detail: od_id, goods_id });
  143. if (moneyDetail) {
  144. const { payTotal } = moneyDetail;
  145. if (this.ctx.minus(payTotal, money) === 0) {
  146. // 添加到已退款的列表中
  147. goodsRefundList.push(asq);
  148. }
  149. }
  150. }
  151. }
  152. }
  153. // 获取支付单的优惠明细
  154. const dd = _.get(order, 'total_detail.discount_detail', {});
  155. for (const uc_id in dd) {
  156. // uc_id 用户领取优惠券的id
  157. // 该优惠券影响的商品id列表
  158. const goodsIds = Object.keys(_.get(dd, uc_id, {}));
  159. // 然后在已退款记录中找,这个优惠券影响的商品是否都退款了.都退款
  160. const r = goodsIds.every(i => goodsRefundList.find(f => i === f['goods._id']));
  161. if (r) {
  162. // 说明这个优惠券影响的商品都退了,这个优惠券也就能退了
  163. tran.update('UserCoupon', uc_id, { status: '0' });
  164. }
  165. }
  166. }
  167. /**
  168. * 计算商品退货的金额最大值
  169. * @param {Object} body 参数体
  170. * @param body.order_detail 订单详情id
  171. * @param body.goods_id 商品id
  172. */
  173. async computedGoodsForRefund({ order_detail, goods_id }) {
  174. const orderDetail = await this.orderDetailModel.findById(order_detail);
  175. if (!orderDetail) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到订单信息');
  176. const goods = orderDetail.goods.find(f => f._id === goods_id);
  177. // 货物支付金额, 数量*购买数量+ 数量*运费 - 优惠
  178. const goodsTotal = this.ctx.multiply(goods.sell_money, goods.buy_num);
  179. const freightTotal = this.ctx.multiply(goods.freight, goods.buy_num);
  180. let discountTotal = 0;
  181. const { total_detail = {} } = orderDetail;
  182. const { discount_detail = {} } = total_detail;
  183. for (const dd in discount_detail) {
  184. const dm = _.get(discount_detail, `${dd}.${goods_id}`, 0);
  185. discountTotal = this.ctx.plus(discountTotal, dm);
  186. }
  187. const payTotal = this.ctx.minus(this.ctx.plus(goodsTotal, freightTotal), discountTotal);
  188. const obj = { payTotal, goodsTotal, freightTotal, discountTotal };
  189. return obj;
  190. }
  191. async fetch(filter) {
  192. assert(filter);
  193. filter = await this.beforeFetch(filter);
  194. const { _id, id } = filter;
  195. if (_id || id) filter = { _id: ObjectId(_id || id) };
  196. const { populate } = this.getRefMods();
  197. let res = await this.model.findOne(filter).populate(populate).exec();
  198. res = await this.afterFetch(filter, res);
  199. return res;
  200. }
  201. }
  202. module.exports = AfterSaleService;