afterSale.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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. const hasData = await this.model.count({ order_detail, 'goods._id': goods_id, type: [ '0', '1', '2', '3' ] });
  22. if (hasData > 0) throw new BusinessError(ErrorCode.DATA_EXISTED, '该商品已有正在处理中的售后申请.请勿重复申请');
  23. const { goods: goodsList } = orderDetail;
  24. const goods = goodsList.find(f => ObjectId(f._id).equals(goods_id));
  25. if (!goods) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未在当前订单中搜索到要售后的商品');
  26. const { shop, customer } = orderDetail;
  27. const apply_time = moment().format('YYYY-MM-DD HH:mm:ss');
  28. const obj = { order_detail, customer, shop, goods, ...others, apply_time, status: '0' };
  29. await this.model.create(obj);
  30. }
  31. async update(filter, update, { projection } = {}) {
  32. assert(filter);
  33. assert(update);
  34. const beforeUpdateResult = await this.beforeUpdate(filter, update);
  35. filter = beforeUpdateResult.filter;
  36. update = beforeUpdateResult.update;
  37. const { _id, id } = filter;
  38. if (_id || id) filter = { _id: ObjectId(_id || id) };
  39. // 检查数据是否存在
  40. const entity = await this.model.findOne(filter).exec();
  41. if (!entity) throw new BusinessError(ErrorCode.DATA_NOT_EXIST);
  42. // 修改数据
  43. try {
  44. let refundInfo;
  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' || status === '2')) {
  51. refundInfo = await this.toRefund({ afterSale_id: entity._id, goods_id: _.get(entity, 'goods._id') }, this.tran);
  52. }
  53. // 2022-10-17 需求8:标记处理售后的人
  54. if (entity.status === '0' && update.status !== '0') {
  55. // 将状态从 审核中 变为不是 审核中的操作人
  56. const admin = this.ctx.admin;
  57. if (!admin) throw new BusinessError(ErrorCode.DATA_INVALID, '未找到管理人员的信息,无法进行操作');
  58. this.tran.update('AfterSale', entity._id, { deal_person: admin._id });
  59. }
  60. await this.tran.run();
  61. if (refundInfo) {
  62. // 退款请求, 将请求退款滞后,所有的信息处理完之后,再去退款,避免退款成功但是数据处理失败的问题
  63. const res = await this.ctx.service.trade.pay.refund(refundInfo);
  64. if (res.errcode && res.errcode !== 0) throw new BusinessError(ErrorCode.SERVICE_FAULT, res.errmsg);
  65. }
  66. } catch (error) {
  67. console.error(error);
  68. await this.tran.rollback();
  69. throw new BusinessError(ErrorCode.SERVICE_FAULT, '售后:修改失败');
  70. } finally {
  71. this.tran.clean();
  72. }
  73. const reSearchData = await this.model.findOne(filter, projection).exec();
  74. return reSearchData;
  75. }
  76. /**
  77. * 退款
  78. * @param {Object} param 参数
  79. * @param param.afterSale_id 售后申请id
  80. * @param param.goods_id 商品规格id
  81. * @param {Transaction} tran 事务的实例
  82. */
  83. async toRefund({ afterSale_id, goods_id }, tran) {
  84. let refundInfo = {};
  85. const data = await this.model.findById(afterSale_id);
  86. if (!data) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到售后信息');
  87. const { populate } = this.ctx.service.trade.orderDetail.getRefMods();
  88. const orderDetail = await this.orderDetailModel.findById(data.order_detail).populate(populate);
  89. if (!orderDetail) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到售后信息的订单');
  90. const reason = _.get(data, 'desc');
  91. const order_no = _.get(orderDetail, 'order.pay.pay_no');
  92. if (!order_no) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到支付订单号');
  93. // 用工具函数,获取退货商品的实际支付价格(常规/团购)
  94. const moneyDetail = this.ctx.service.util.orderDetail.moneyDetail(orderDetail);
  95. const goodsMoneyDetail = _.get(moneyDetail, goods_id, {});
  96. const type = _.get(orderDetail, 'type', '0');
  97. let priceKey;
  98. if (type === '1') priceKey = 'ggrp';
  99. else priceKey = 'grp';
  100. const money = _.get(goodsMoneyDetail, priceKey, 0);
  101. // 取出商品输入的价格
  102. const needRefund = _.get(data, 'money');
  103. let refundMoney = 0;
  104. if (money === needRefund) {
  105. // 如果这俩价格相同,说明是正常退
  106. refundMoney = money;
  107. } else {
  108. // 部分退,部分退是不退优惠券的
  109. refundMoney = needRefund;
  110. }
  111. // 组成退款单号
  112. const str = this.ctx.service.util.trade.createNonceStr();
  113. const out_refund_no = `${order_no}-r-${str}`;
  114. refundInfo = { reason, money: refundMoney, order_no, out_refund_no };
  115. if (data.status === '1') {
  116. tran.update('AfterSale', afterSale_id, { status: '-1', end_time: moment().format('YYYY-MM-DD HH:mm:ss') });
  117. }
  118. // #region 团购部分
  119. const status = _.get(orderDetail, 'status');
  120. // 团购单,且未收货的单子,才需要走退团逻辑,否则不需要走退团逻辑
  121. if (type === '1' && status !== '3') {
  122. // 团购单,走团购退货逻辑补充
  123. const { group, customer } = orderDetail;
  124. await this.ctx.service.group.group.refund({ group: group._id, customer: customer._id }, tran);
  125. }
  126. // #endregion
  127. // 检查优惠券是否都退了
  128. // 查看支付订单-优惠明细中,该优惠券影响的商品是否都有退款/退货成功的记录,且退款成功的记录为退全款的.退部分是不退优惠券的
  129. // 如果有,就说明该优惠券可以退了,没有影响任何一单了
  130. const payOrder = _.get(orderDetail, 'order');
  131. await this.checkToReturnUserCoupon(payOrder, tran);
  132. // 退积分,退多钱就退多少积分
  133. const { _id } = orderDetail;
  134. await this.ctx.service.user.point.refundOrderPoint(_id, tran);
  135. return refundInfo;
  136. }
  137. /**
  138. * 检查订单的优惠券并退优惠券, 必须是退全款,部分退款不退优惠券
  139. * @param {Object} order 订单信息
  140. * @param {Transaction} tran 事务的实例
  141. */
  142. async checkToReturnUserCoupon(order, tran) {
  143. // 该支付订单下所有拆分的子订单
  144. const orderDetailList = await this.orderDetailModel.find({ order: order._id });
  145. // 已退款记录
  146. const goodsRefundList = [];
  147. for (const od of orderDetailList) {
  148. const { goods, _id: order_detail } = od;
  149. // 组合成查售后的条件
  150. // 然后查这些商品有没有退款审核成功的记录, 且只有退全款的商品才能退券
  151. const afterSaleQuerys = goods.map(i => ({ order_detail, 'goods._id': i._id, status: '-1' }));
  152. for (const asq of afterSaleQuerys) {
  153. const asd = await this.model.findOne(asq);
  154. if (asd) {
  155. // 商品有退款审核通过的记录,查询每个商品是否退的是全款
  156. // money: 实际退款的金额
  157. const { money } = asd;
  158. const od_id = _.get(asd, 'order_detail');
  159. const goods_id = _.get(asd, 'goods._id');
  160. const moneyDetail = await this.computedGoodsForRefund({ order_detail: od_id, goods_id });
  161. if (moneyDetail) {
  162. const { payTotal } = moneyDetail;
  163. if (this.ctx.minus(payTotal, money) === 0) {
  164. // 添加到已退款的列表中
  165. goodsRefundList.push(asq);
  166. }
  167. }
  168. }
  169. }
  170. }
  171. // 获取支付单的优惠明细
  172. const dd = _.get(order, 'total_detail.discount_detail', {});
  173. for (const uc_id in dd) {
  174. // uc_id 用户领取优惠券的id
  175. // 该优惠券影响的商品id列表
  176. const goodsIds = Object.keys(_.get(dd, uc_id, {}));
  177. // 然后在已退款记录中找,这个优惠券影响的商品是否都退款了.都退款
  178. const r = goodsIds.every(i => goodsRefundList.find(f => i === f['goods._id']));
  179. if (r) {
  180. // 说明这个优惠券影响的商品都退了,这个优惠券也就能退了
  181. tran.update('UserCoupon', uc_id, { status: '0' });
  182. }
  183. }
  184. }
  185. /**
  186. * 计算商品退货的金额最大值
  187. * @param {Object} body 参数体
  188. * @param body.order_detail 订单详情id
  189. * @param body.goods_id 商品id
  190. */
  191. async computedGoodsForRefund({ order_detail, goods_id }) {
  192. const orderDetail = await this.orderDetailModel.findById(order_detail);
  193. if (!orderDetail) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到订单信息');
  194. const goods = orderDetail.goods.find(f => f._id === goods_id);
  195. // 货物支付金额, 数量*购买数量+ 数量*运费 - 优惠
  196. const goodsTotal = this.ctx.multiply(goods.sell_money, goods.buy_num);
  197. const freightTotal = this.ctx.multiply(goods.freight, goods.buy_num);
  198. let discountTotal = 0;
  199. const { total_detail = {} } = orderDetail;
  200. const { discount_detail = {} } = total_detail;
  201. for (const dd in discount_detail) {
  202. const dm = _.get(discount_detail, `${dd}.${goods_id}`, 0);
  203. discountTotal = this.ctx.plus(discountTotal, dm);
  204. }
  205. const payTotal = this.ctx.minus(this.ctx.plus(goodsTotal, freightTotal), discountTotal);
  206. const obj = { payTotal, goodsTotal, freightTotal, discountTotal };
  207. return obj;
  208. }
  209. /**
  210. * 退单
  211. * @param {Object} body 参数体
  212. * @param body.order_detail 订单详情id
  213. * @param body.desc 退单理由
  214. */
  215. async orderCancel({ order_detail, desc }) {
  216. // 查询要退的订单
  217. const orderDetail = await this.orderDetailModel.findById(order_detail);
  218. if (!orderDetail) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到订单信息');
  219. const { customer } = orderDetail;
  220. const basic = { order_detail, customer, type: '1', desc };
  221. const moneyDetail = this.ctx.service.util.orderDetail.moneyDetail(orderDetail);
  222. let priceKey;
  223. if (_.get(orderDetail, 'type') === '1') priceKey = 'ggrp';
  224. else priceKey = 'grp';
  225. for (const goods_id in moneyDetail) {
  226. const d = _.get(moneyDetail, goods_id, {});
  227. const money = _.get(d, priceKey, 0);
  228. const obj = { ...basic, goods_id, money };
  229. await this.create(obj);
  230. }
  231. // 组织数据
  232. // for (const g of goods) {
  233. // let money = this.ctx.multiply(g.buy_num, g.sell_money);
  234. // let dmt = 0;
  235. // for (const dd in discount_detail) {
  236. // const detail = _.get(discount_detail, dd, {});
  237. // const dm = _.get(detail, g._id);
  238. // dmt = this.ctx.plus(dmt, dm);
  239. // }
  240. // money = this.ctx.minus(money, dmt);
  241. // if (money <= 0) money = 0;
  242. // const obj = { ...basic, goods_id: g._id, money };
  243. // await this.create(obj);
  244. // }
  245. }
  246. async fetch(filter) {
  247. assert(filter);
  248. filter = await this.beforeFetch(filter);
  249. const { _id, id } = filter;
  250. if (_id || id) filter = { _id: ObjectId(_id || id) };
  251. const { populate } = this.getRefMods();
  252. let res = await this.model.findOne(filter).populate(populate).exec();
  253. res = await this.afterFetch(filter, res);
  254. return res;
  255. }
  256. }
  257. module.exports = AfterSaleService;