afterSale.js 11 KB

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