orderDetail.js 14 KB

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