orderDetail.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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 Transaction = require('mongoose-transactions');
  8. //
  9. class OrderDetailService extends CrudService {
  10. constructor(ctx) {
  11. super(ctx, 'orderdetail');
  12. this.model = this.ctx.model.Trade.OrderDetail;
  13. this.orderModel = this.ctx.model.Trade.Order;
  14. this.goodsSpecModel = this.ctx.model.Shop.GoodsSpec;
  15. this.userCouponModel = this.ctx.model.User.UserCoupon;
  16. this.goodsRateModel = this.ctx.model.Shop.GoodsRate;
  17. this.afterSaleModel = this.ctx.model.Trade.AfterSale;
  18. this.platformActModel = this.ctx.model.System.PlatformAct;
  19. this.tran = new Transaction();
  20. }
  21. async searchOrderTransport({ id, goods_id }) {
  22. const orderDetail = await this.model.findById(id);
  23. if (!id) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到订单信息');
  24. const { transport = [] } = orderDetail;
  25. let toSearch = [];
  26. if (goods_id) {
  27. // 传来指定商品,查有该商品的订单,但是如果没有,就查每一项中是否有 shop_transport_no 和 shop_transport_type
  28. // 如果有这俩属性,说明也有单子,也查出来
  29. toSearch = transport.filter(f => _.isArray(f.goods) && f.goods.find(fg => fg.goods_id === goods_id));
  30. console.log(toSearch);
  31. if (toSearch.length <= 0) {
  32. toSearch = transport.filter(f => f.shop_transport_no && f.shop_transport_type);
  33. }
  34. } else {
  35. toSearch = transport;
  36. }
  37. const result = [];
  38. for (const t of toSearch) {
  39. const { shop_transport_no: no, shop_transport_type: type } = t;
  40. if (!no || !type) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '缺少快递信息');
  41. const res = await this.ctx.service.util.kd100.search({ no, type });
  42. result.push(res);
  43. }
  44. return result;
  45. }
  46. /**
  47. * 创建:用户支付完成后的订单
  48. * @param {Object} body 请求参数体
  49. * @param body.order_id 下单的id
  50. * @param {Transaction} tran 数据库事务实例
  51. */
  52. async create({ order_id }, tran) {
  53. assert(order_id, '缺少支付订单信息');
  54. const order = await this.orderModel.findById(order_id);
  55. if (!order) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到支付订单的数据');
  56. // 返现部分
  57. const { customer, address, goods: shopGoods, no, status, buy_time, pay, total_detail: otd, inviter } = order;
  58. if (status === '0') throw new BusinessError(ErrorCode.DATA_INVALID, '订单未支付');
  59. const orderDetailData = { customer, address, order: order_id, buy_time, pay_time: _.get(pay, 'pay_time'), status, inviter };
  60. const shopMoneyDetail = this.ctx.service.util.order.shopMoneyDetail(order);
  61. // 分订单计数器
  62. let noTimes = 1;
  63. // const list = [];
  64. const ids = [];
  65. for (const s of shopGoods) {
  66. const shop = _.get(s, 'shop');
  67. const remarks = _.get(s, 'remarks');
  68. const goodsList = _.get(s, 'goods', []);
  69. const detailNo = `${no}-${noTimes}`;
  70. const total_detail = shopMoneyDetail[shop];
  71. // 优惠部分分割
  72. if (_.get(otd, 'discount_detail')) {
  73. // 如果有优惠部分,那就得找,优惠里面有没有对应的商品规格
  74. const discount_detail = this.getGoodsListDiscountDetail(goodsList, _.get(otd, 'discount_detail'));
  75. total_detail.discount_detail = discount_detail;
  76. }
  77. noTimes++;
  78. const obj = { ...orderDetailData, shop, goods: goodsList, no: detailNo, total_detail, remarks };
  79. // 测试用
  80. obj.status = '1';
  81. // list.push(obj);
  82. const od_id = tran.insert('OrderDetail', obj);
  83. ids.push(od_id);
  84. // 添加该商品是否和平台活动有关,做记录
  85. // await this.ctx.service.trade.actOrder.create(orderDetail_id, obj, tran);
  86. }
  87. return ids;
  88. // await this.model.insertMany(list);
  89. }
  90. /**
  91. * 将商品规格列表中,优惠的部分提取出来,分单用
  92. * @param {Array} goodsList 某店的商品列表
  93. * @param {Object} odd discount_detail 支付订单的优惠券设置
  94. */
  95. getGoodsListDiscountDetail(goodsList, odd) {
  96. const result = {};
  97. for (const uc_id in odd) {
  98. const detail = odd[uc_id];
  99. const obj = {};
  100. for (const g of goodsList) {
  101. const { _id } = g;
  102. const gdd = detail[_id];
  103. if (gdd) obj[_id] = gdd;
  104. }
  105. result[uc_id] = obj;
  106. }
  107. return result;
  108. }
  109. /**
  110. * 计算某店铺的金额总计
  111. * @param {Array} goodsList 商品规格列表
  112. */
  113. getTotalDetail(goodsList) {
  114. const goods_total = goodsList.reduce((p, n) => this.ctx.plus(p, this.ctx.multiply(n.sell_money, n.buy_num)), 0);
  115. const freight_total = goodsList.reduce((p, n) => this.ctx.plus(p, this.ctx.multiply(n.freight, n.buy_num)), 0);
  116. return { goods_total, freight_total };
  117. }
  118. async fetch(filter) {
  119. assert(filter);
  120. filter = await this.beforeFetch(filter);
  121. const { _id, id } = filter;
  122. if (_id || id) filter = { _id: ObjectId(_id || id) };
  123. const { populate } = this.getRefMods();
  124. let res = await this.model.findOne(filter).populate(populate).exec();
  125. res = JSON.parse(JSON.stringify(res));
  126. // 找售后和评论
  127. const afterSale = await this.afterSaleModel.find({ order_detail: res._id });
  128. const rate = await this.goodsRateModel.find({ orderDetail: res._id });
  129. const goods = _.get(res, 'goods', []);
  130. for (const g of goods) {
  131. const r = afterSale.find(f => ObjectId(_.get(f, 'goods._id')).equals(g._id));
  132. if (r) g.is_afterSale = true;
  133. else g.is_afterSale = false;
  134. const r2 = rate.find(f => ObjectId(_.get(f, 'goodsSpec')).equals(g._id));
  135. if (r2) {
  136. g.is_rate = true;
  137. g.rate = r2._id;
  138. } else g.is_rate = false;
  139. }
  140. res.goods = goods;
  141. // 整理total_detail为列表:让前端显示更方便
  142. const total_detail = _.get(res, 'total_detail', {});
  143. res.total_detail = await this.fetchResetTotalDetail(total_detail);
  144. return res;
  145. }
  146. async fetchResetTotalDetail(total_detail) {
  147. const tarr = [];
  148. if (_.isNumber(_.get(total_detail, 'goods_total', 0))) tarr.push({ key: 'goods_total', zh: '商品总价', money: _.get(total_detail, 'goods_total', 0) });
  149. if (_.isNumber(_.get(total_detail, 'freight_total', 0))) tarr.push({ key: 'freight_total', zh: '运费总价', money: _.get(total_detail, 'freight_total', 0) });
  150. const act = _.get(total_detail, 'act', []);
  151. for (const a of act) {
  152. const { platform_act, platform_act_type, discount } = a;
  153. const text = `满${platform_act_type === '6' ? '折' : '减'}活动`;
  154. const actData = await this.platformActModel.findById(platform_act);
  155. const title = _.get(actData, 'act_time.title', text);
  156. const obj = { key: platform_act, zh: title, money: this.ctx.minus(0, discount) };
  157. tarr.push(obj);
  158. }
  159. const discount_detail = _.get(total_detail, 'discount_detail', {});
  160. const userCoupons = Object.keys(discount_detail);
  161. if (userCoupons.length > 0) {
  162. let dm = 0;
  163. for (const uc_id of userCoupons) {
  164. const detail = _.get(discount_detail, uc_id, {});
  165. const values = Object.values(detail);
  166. dm = values.reduce((p, n) => this.ctx.minus(p, n), dm);
  167. }
  168. tarr.push({ key: 'coupons', zh: '优惠券优惠', money: dm });
  169. }
  170. return tarr;
  171. }
  172. async query(filter, { skip = 0, limit, sort, desc, projection } = {}) {
  173. // 处理排序
  174. if (sort && _.isString(sort)) {
  175. sort = { [sort]: desc ? -1 : 1 };
  176. } else if (sort && _.isArray(sort)) {
  177. sort = sort.map(f => ({ [f]: desc ? -1 : 1 })).reduce((p, c) => ({ ...p, ...c }), {});
  178. }
  179. let condition = _.cloneDeep(filter);
  180. condition = await this.beforeQuery(condition);
  181. condition = this.dealFilter(condition);
  182. // 过滤出ref字段
  183. const pipline = [{ $sort: { 'meta.createdAt': -1 } }];
  184. pipline.push({ $match: condition });
  185. // 整理字段
  186. // 店铺需要的字段
  187. pipline.push({ $addFields: { shop_id: { $toObjectId: '$shop' } } });
  188. pipline.push({
  189. $lookup: {
  190. from: 'shop',
  191. localField: 'shop_id',
  192. foreignField: '_id',
  193. as: 'shopInfo',
  194. },
  195. });
  196. pipline.push({ $addFields: { customer_id: { $toObjectId: '$customer' } } });
  197. pipline.push({
  198. $lookup: {
  199. from: 'user',
  200. localField: 'customer_id',
  201. foreignField: '_id',
  202. as: 'customerInfo',
  203. },
  204. });
  205. pipline.push({ $unwind: '$shopInfo' });
  206. pipline.push({ $unwind: '$customerInfo' });
  207. const lastProject = {
  208. $project: {
  209. _id: 1,
  210. type: 1,
  211. order: 1,
  212. buy_time: 1,
  213. pay_time: 1,
  214. status: 1,
  215. no: 1,
  216. address: 1,
  217. goods: {
  218. _id: 1,
  219. sell_money: 1,
  220. freight: 1,
  221. name: 1,
  222. buy_num: 1,
  223. goods: { name: 1, file: 1 },
  224. file: 1,
  225. act: 1,
  226. price: 1,
  227. sp_price: 1,
  228. gift: 1,
  229. },
  230. shop: {
  231. _id: '$shopInfo._id',
  232. name: '$shopInfo.name',
  233. },
  234. customer: {
  235. _id: '$customerInfo._id',
  236. name: '$customerInfo.name',
  237. },
  238. total_detail: 1,
  239. },
  240. };
  241. pipline.push(lastProject);
  242. const qPipline = _.cloneDeep(pipline);
  243. if (parseInt(skip) >= 0) qPipline.push({ $skip: parseInt(skip) });
  244. if (parseInt(limit)) qPipline.push({ $limit: parseInt(limit) });
  245. const rs = await this.model.aggregate(qPipline);
  246. const tPipline = _.cloneDeep(pipline);
  247. tPipline.push({ $addFields: { id: { $toString: '$_id' } } });
  248. tPipline.push({ $count: 'id' });
  249. const t = await this.model.aggregate(tPipline);
  250. const total = _.get(_.head(t), 'id');
  251. const list = [];
  252. for (const i of rs) {
  253. const { goods, _id: orderDetail } = i;
  254. const obj = _.cloneDeep(i);
  255. const real_pay = this.ctx.service.util.orderDetail.computedRealPay(obj);
  256. obj.real_pay = real_pay;
  257. obj.buy_num_total = goods.reduce((p, n) => this.ctx.plus(p, n.buy_num), 0);
  258. for (const og of obj.goods) {
  259. const { file = [], _id: goodsSpec } = og;
  260. const gfile = _.get(og, 'goods.file', []);
  261. const nf = [ ...file, ...gfile ];
  262. const url = _.get(_.head(nf), 'url');
  263. og.url = url;
  264. delete og.file;
  265. delete og.goods.file;
  266. // 评价
  267. const q = { orderDetail, goodsSpec };
  268. const rate = await this.goodsRateModel.findOne(q, { _id: 1 });
  269. obj.rate = _.get(rate, '_id');
  270. obj.price = _.get(obj, 'price', obj.sell_money);
  271. }
  272. // 售后
  273. const asum = await this.afterSaleModel.count({ order_detail: obj._id, status: { $nin: [ '-1', '!1', '-2', '!2', '-3', '!3', '-4', '!4', '-5', '!5' ] } });
  274. obj.is_afterSale = asum > 0;
  275. list.push(obj);
  276. }
  277. return { data: list, total };
  278. }
  279. async update(filter, update, { projection } = {}) {
  280. // 需要注意不能让order和orderDetail修改total_detail
  281. assert(filter);
  282. assert(update);
  283. const { _id, id } = filter;
  284. if (_id || id) filter = { _id: ObjectId(_id || id) };
  285. const entity = await this.model.findOne(filter).exec();
  286. if (!entity) throw new BusinessError(ErrorCode.DATA_NOT_EXIST);
  287. try {
  288. this.tran.update('OrderDetail', filter._id, update);
  289. if (_.get(update, 'status') === '3') {
  290. // 积分部分
  291. await this.ctx.service.user.point.addPoints(filter._id, this.tran);
  292. // 返现部分
  293. await this.ctx.service.user.cashBack.create(filter._id, this.tran);
  294. // 店铺流水部分
  295. await this.ctx.service.shop.shopInBill.createByOrder(entity, this.tran);
  296. }
  297. await this.tran.run();
  298. const e = await this.model.findOne(filter, projection).exec();
  299. return e;
  300. } catch (error) {
  301. await this.tran.rollback();
  302. } finally {
  303. this.tran.clean();
  304. }
  305. }
  306. }
  307. module.exports = OrderDetailService;