order.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  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. //
  7. class OrderService extends CrudService {
  8. constructor(ctx) {
  9. super(ctx, 'order');
  10. this.orderModel = this.ctx.model.Trade.Order;
  11. this.platformActModel = this.ctx.model.System.PlatformAct;
  12. this.gjaModel = this.ctx.model.Shop.GoodsJoinAct;
  13. this.goodsModel = this.ctx.model.Shop.Goods;
  14. this.goodsSpecModel = this.ctx.model.Shop.GoodsSpec;
  15. this.goodsSetService = this.ctx.service.shop.goodsSet;
  16. }
  17. // #region 下单前计算函数
  18. /**
  19. * 计算每个店铺的价格
  20. * list是经过 getPageData 处理过的数据
  21. * @param {Array} list 按店铺分组的商品列表
  22. */
  23. makeOrder_computedShopTotal(list) {
  24. for (const i of list) {
  25. let goods_total = 0,
  26. freight_total = 0,
  27. discount = 0;
  28. const { is_set = '1' } = i;
  29. if (is_set === '1') {
  30. for (const g of i.goods) {
  31. // 如果有特价,那就使用特价,没有特价就是用正常销售价
  32. goods_total = this.ctx.plus(goods_total, this.ctx.multiply(_.get(g, 'price'), _.get(g, 'num')));
  33. freight_total = this.ctx.plus(freight_total, this.ctx.multiply(_.get(g, 'freight'), _.get(g, 'num')));
  34. if (_.isArray(g.act)) {
  35. const actDiscount = g.act.reduce((p, n) => this.ctx.plus(p, n.discount), 0);
  36. discount = this.ctx.plus(discount, actDiscount);
  37. }
  38. }
  39. i.goods_total = goods_total;
  40. i.freight_total = freight_total;
  41. i.discount = this.ctx.minus(0, discount);
  42. } else {
  43. const { sell_money, num, freight } = i;
  44. i.goods_total = this.ctx.multiply(num, sell_money);
  45. i.freight_total = this.ctx.multiply(num, freight);
  46. }
  47. }
  48. return list;
  49. }
  50. /**
  51. * 计算整个订单的价格
  52. * @param {Array} list 按店铺分组的商品列表
  53. * list是经过 getPageData 处理过的数据
  54. */
  55. makerOrder_computedOrderTotal(list) {
  56. const arr = [];
  57. arr.push({ key: 'goods_total', zh: '商品总价', money: list.reduce((p, n) => this.ctx.plus(p, n.goods_total), 0) });
  58. arr.push({ key: 'freight_total', zh: '运费总价', money: list.reduce((p, n) => this.ctx.plus(p, n.freight_total), 0) });
  59. return arr;
  60. }
  61. // #endregion
  62. /**
  63. * 计算需要支付的金额
  64. * @param {Object} order 支付订单信息
  65. * @return {Number} 订单实付金额
  66. */
  67. payOrder_RealPay(order) {
  68. const priceKey = 'grp';
  69. const detail = this.moneyDetail(order);
  70. // 解除店铺层
  71. const sd = Object.values(detail);
  72. // 取出规格层
  73. const sgd = sd.map(i => Object.values(i));
  74. // 将规格明细降维至一维
  75. const oneLevel = _.flattenDeep(sgd);
  76. // 根据订单类型,计算应付(优惠券部分已经按订单类型计算并分配完了.这地方只是复现)
  77. const realPay = oneLevel.reduce((p, n) => this.ctx.plus(p, n[priceKey]), 0);
  78. return realPay;
  79. }
  80. /**
  81. * 计算需要支付的金额
  82. * @param {Object} list 店铺-商品列表
  83. */
  84. computedShopDetail(list) {
  85. for (const i of list) {
  86. let goods_total = 0,
  87. freight_total = 0,
  88. discount = 0;
  89. const { is_set = '1' } = i;
  90. if (is_set === '1') {
  91. for (const g of i.goods) {
  92. // 如果有特价,那就使用特价,没有特价就是用正常销售价
  93. goods_total = this.ctx.plus(goods_total, this.ctx.multiply(_.get(g, 'price'), _.get(g, 'buy_num')));
  94. freight_total = this.ctx.plus(freight_total, this.ctx.multiply(_.get(g, 'freight'), _.get(g, 'buy_num')));
  95. if (_.isArray(g.act)) {
  96. const actDiscount = g.act.reduce((p, n) => this.ctx.plus(p, n.discount), 0);
  97. discount = this.ctx.plus(discount, actDiscount);
  98. }
  99. }
  100. i.goods_total = goods_total;
  101. i.freight_total = freight_total;
  102. i.discount = this.ctx.minus(0, discount);
  103. } else {
  104. const { sell_money, buy_num, freight } = i;
  105. i.goods_total = this.ctx.multiply(buy_num, sell_money);
  106. i.freight_total = this.ctx.multiply(buy_num, freight);
  107. }
  108. }
  109. return list;
  110. }
  111. /**
  112. * 计算店铺的金额明细
  113. * @param {Object} order 支付订单信息
  114. * @return {Object} 返回:{
  115. * 店铺id:{
  116. * goods_total:商品总价,
  117. * freight_total:商品总价
  118. * }
  119. * }
  120. */
  121. shopMoneyDetail(order) {
  122. if (!order) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到订单信息');
  123. let priceKey;
  124. if (_.get(order, 'type', '0') === '1') priceKey = 'gst';
  125. else priceKey = 'st';
  126. const result = {};
  127. const moneyDetail = this.moneyDetail(order);
  128. for (const s in moneyDetail) {
  129. const obj = {};
  130. const d = _.get(moneyDetail, s, {});
  131. obj.goods_total = Object.values(d).reduce((p, n) => this.ctx.plus(p, _.get(n, priceKey, 0)), 0);
  132. obj.freight_total = Object.values(d).reduce((p, n) => this.ctx.plus(p, _.get(n, 'ft', 0)), 0);
  133. const act = Object.values(d).reduce((p, n) => [ ...p, ..._.get(n, 'ad', []) ], []);
  134. obj.act = act.filter(f => f.platform_act_type === '5' || f.platform_act_type === '6');
  135. result[s] = obj;
  136. }
  137. return result;
  138. }
  139. /**
  140. * 按店铺-商品 计算该订单的价格明细
  141. * @param {Object} data 支付订单数据
  142. * @return {Object} 返回:{
  143. ** 店铺id:{
  144. ** 规格id:{
  145. ** sm: 规格正常销售价格(sell_money),
  146. ** f: 规格运费(freight),
  147. ** bn: 购买数量(buy_num),
  148. ** st: 规格正常销售总价(sell_total: sm * bn)
  149. ** ft: 规格运费总价(freight_total: f * bn)
  150. ** gt: 商品支付原价(goods_total: st + ft)
  151. ** dd: {
  152. ** key:优惠券id,
  153. ** value:优惠价格
  154. ** },
  155. ** dt: 优惠总价(d_detail的value之和)
  156. ** ad: [{
  157. ** money:活动优惠金额(负数),
  158. ** platform_act:活动金额
  159. ** }]
  160. ** at: 活动优惠总金额
  161. ** },
  162. ** 套装id:{
  163. ** sm: 套装正常销售价格(sell_money),
  164. ** f: 套装运费(freight),
  165. ** bn: 购买数量(buy_num),
  166. ** st: 套装正常销售总价(sell_total: sm * bn)
  167. ** ft: 套装运费总价(freight_total: f * bn)
  168. ** gt: 套装支付原价(goods_total: st + ft)
  169. ** }
  170. ** },
  171. ** }
  172. */
  173. moneyDetail(data) {
  174. if (!data) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到订单信息');
  175. // 优惠部分
  176. const ddt = _.get(data, 'total_detail.discount_detail', {});
  177. // 店铺规格商品数据
  178. const shopGoods = _.get(data, 'goods', []);
  179. const groupShop = _.groupBy(shopGoods, 'shop');
  180. const result = {};
  181. for (const shop_id in groupShop) {
  182. const list = groupShop[shop_id];
  183. const shopResult = {};
  184. for (const s of list) {
  185. const { is_set = '1' } = s;
  186. if (is_set === '1') {
  187. const { goods } = s;
  188. for (const g of goods) {
  189. const { sell_money, freight: f, buy_num: bn, _id, act: ad = [] } = g;
  190. // 优先获取price字段,没有再取sell_money
  191. const sm = _.get(g, 'price', sell_money);
  192. const st = this.ctx.multiply(sm, bn);
  193. const ft = this.ctx.multiply(f, bn);
  194. const gt = this.ctx.plus(st, ft);
  195. // 优惠券部分
  196. const dd = {};
  197. for (const uc_id in ddt) {
  198. const detail = _.get(ddt, uc_id, {});
  199. const value = detail[_id];
  200. if (value) dd[uc_id] = value;
  201. }
  202. const dt = Object.values(dd).reduce((p, n) => this.ctx.plus(p, n), 0);
  203. // 活动部分
  204. const at = ad.reduce((p, n) => this.ctx.plus(p, n.discount), 0);
  205. const grp = this.ctx.minus(this.ctx.minus(gt, dt), at);
  206. const obj = { sm, f, bn, st, ft, gt, dd, dt, grp, ad, at };
  207. shopResult[_id] = obj;
  208. }
  209. } else {
  210. const { freight, sell_money, buy_num, set_id } = s;
  211. const sm = sell_money,
  212. f = freight,
  213. bn = buy_num,
  214. st = this.ctx.multiply(sm, bn),
  215. ft = this.ctx.multiply(f, bn),
  216. gt = this.ctx.plus(ft, st),
  217. grp = gt;
  218. shopResult[set_id] = { sm, f, bn, st, ft, gt, grp };
  219. }
  220. }
  221. result[shop_id] = shopResult;
  222. }
  223. return result;
  224. }
  225. // #region 创建订单数据组织部分
  226. /**
  227. * 组织商品数据
  228. * @param {Array} goods 商品列表
  229. * @property {Array} actList 活动列表
  230. * @property {Array} goodsSpec 后面优惠券使用有关计算的数据
  231. * @property {Array} goodsData 组织新的商品数据
  232. */
  233. async makeOrderGoodsData(goods) {
  234. // 商店不做快照,但是商品和商品对应的规格做快照
  235. const actList = [],
  236. goodsSpecs = [],
  237. goodsData = [];
  238. for (const i of goods) {
  239. const { goods: goodsList, is_set = '1', set_id, ...others } = i;
  240. const qp = [];
  241. if (is_set === '1') {
  242. for (const g of goodsList) {
  243. const { goodsSpec_id, goods_id } = g;
  244. // 需要的订单数据
  245. const orderNeedData = _.pick(g, [ 'act', 'price', 'sp_price', 'num', 'cart_id', 'gift' ]);
  246. if (orderNeedData.num) {
  247. orderNeedData.buy_num = orderNeedData.num;
  248. delete orderNeedData.num;
  249. }
  250. let goodsSpec = await this.goodsSpecModel.findById(goodsSpec_id);
  251. if (!goodsSpec) continue;
  252. goodsSpec = JSON.parse(JSON.stringify(goodsSpec));
  253. const goods = await this.goodsModel.findById(goods_id);
  254. if (goods) goodsSpec.goods = JSON.parse(JSON.stringify(goods));
  255. goodsSpec = { ...goodsSpec, ...orderNeedData };
  256. qp.push(goodsSpec);
  257. const ogs = _.pick(goodsSpec, [ '_id', 'buy_num', 'sell_money', 'price' ]);
  258. if (ogs._id) {
  259. ogs.id = ogs._id;
  260. delete ogs._id;
  261. }
  262. goodsSpecs.push({ ...ogs });
  263. // 将活动提取出来:只需要满减/折;买赠和特价跟着规格走,计算过程中已经处理;加价购是外面处理
  264. const { act = [] } = goodsSpec;
  265. let gAct = act.filter(f => f.platform_act_type === '5' || f.platform_act_type === '6');
  266. gAct = gAct.map(i => ({ ...i, goodsSpec_id: goodsSpec._id }));
  267. actList.push(...gAct);
  268. }
  269. goodsData.push({ ...others, goods: qp });
  270. } else {
  271. const data = await this.goodsSetService.getSnapshot(set_id);
  272. data.cart_id = i.cart_id;
  273. data.buy_num = i.num;
  274. data.is_set = '0';
  275. data.set_id = i.set_id;
  276. data.remarks = i.remarks;
  277. goodsData.push(data);
  278. }
  279. }
  280. return { actList, goodsSpecs, goodsData };
  281. }
  282. /**
  283. * 将加购商品组织进商品数据中
  284. * @param {Array} goodsData 上面组织过的数据
  285. * @param {Array} plus_goods 加购商品
  286. */
  287. async addPlusGoods(goodsData, plus_goods) {
  288. for (const i of plus_goods) {
  289. const { shop, shop_name, goods: goods_id, spec: spec_id, _id, config, platform_act, platform_act_type } = i;
  290. // 1,验证活动中是否有数据
  291. let num = await this.platformActModel.count({ _id: platform_act });
  292. // 没找到活动:下一个
  293. if (num <= 0) continue;
  294. num = await this.gjaModel.count({ _id });
  295. // 没有商品数据:下一个
  296. if (num <= 0) continue;
  297. // 2.做商品,规格的快照
  298. let goodsSpec = await this.goodsSpecModel.findById(spec_id);
  299. if (!goodsSpec) continue;
  300. goodsSpec = JSON.parse(JSON.stringify(goodsSpec));
  301. const goods = await this.goodsModel.findById(goods_id);
  302. if (goods) goodsSpec.goods = JSON.parse(JSON.stringify(goods));
  303. // 3.向上面一样组织数据
  304. const price = _.get(config, 'plus_money', _.get(goodsSpec, 'sell_money'));
  305. const act = [{ platform_act, platform_act_type, goods: goods_id, spec: spec_id }];
  306. goodsSpec.price = price;
  307. goodsSpec.act = act;
  308. // 商品数量固定为1
  309. goodsSpec.buy_num = 1;
  310. // 4.合并进goodsData
  311. const r = goodsData.find(f => f.shop === shop);
  312. if (r) r.goods.push(goodsSpec);
  313. else {
  314. goodsData.push({ shop, shop_name, goods: [ goodsSpec ] });
  315. }
  316. }
  317. return goodsData;
  318. }
  319. // #endregion
  320. // #region 活动部分
  321. /**
  322. * 检查商品是否满足加价购
  323. * @param {Array} goodsList 平铺的商品列表
  324. * @param {Array} actList 活动
  325. */
  326. async dealAct_plus(goodsList, actList) {
  327. for (const act of actList) {
  328. const { platform_act, plus_money } = act;
  329. const goodsInAct = await this.getGoodsInAct(goodsList, platform_act);
  330. // 没有有关活动的商品,直接下个活动
  331. if (goodsInAct.length <= 0) continue;
  332. const total = goodsInAct.reduce((p, n) => {
  333. const rp = this.getGoodsPayAfterAct(n);
  334. return this.ctx.plus(p, rp);
  335. }, 0);
  336. // 商品,优惠过后的金额,大于等于 活动下限:活动可以进行
  337. if (this.ctx.minus(total, plus_money) >= 0) act.activity = true;
  338. }
  339. }
  340. /**
  341. * 设置商品特价部分
  342. * @param {Array} goodsList 平铺的商品列表
  343. * @param {Array} actList 活动
  344. */
  345. dealAct_sp(goodsList, actList) {
  346. for (const act of actList) {
  347. const { spec, sp_price, platform_act_type, platform_act } = act;
  348. if (!spec) continue;
  349. const goods = goodsList.find(f => f.goodsSpec_id === spec);
  350. if (goods) {
  351. // 默认特价为商品金额
  352. goods.sp_price = sp_price;
  353. // 有团长价格,且团长价格比特价低,就用团长价格
  354. if (goods.leader_price && this.ctx.minus(goods.leader_price, goods.sp_price) < 0) goods.price = goods.leader_price;
  355. else goods.price = sp_price;
  356. const { act = [] } = goods;
  357. act.push({ platform_act_type, platform_act, sp_price });
  358. goods.act = act;
  359. }
  360. }
  361. }
  362. /**
  363. * 商品满减/折处理:主要区分在于 将折扣转换为金额,剩下都是按比例分配
  364. * @param {Array} goodsList 平铺的商品列表
  365. * @param {Array} actList 活动
  366. */
  367. async dealAct_discount(goodsList, actList) {
  368. for (const act of actList) {
  369. const { discount = [], platform_act, platform_act_type } = act;
  370. // 整理出区间
  371. const range = this.getDiscountRange(discount);
  372. // 找到在当前活动的商品
  373. const goodsInAct = await this.getGoodsInAct(goodsList, platform_act);
  374. if (goodsInAct.length <= 0) continue;
  375. // 计算总价格够不够线(因为活动有优先级问题,如果发生满减够, 而满减之后的价格就不足以满折, 那就不给满折,所以要重新计算)
  376. const total = goodsInAct.reduce((p, n) => {
  377. const rp = this.getGoodsPayAfterAct(n);
  378. return this.ctx.plus(p, rp);
  379. }, 0);
  380. for (const r of range) {
  381. const { ls, le, number, max } = r;
  382. let res = false;
  383. if (ls && le) res = _.inRange(total, ls, le);
  384. else if (ls && !le) res = this.ctx.minus(total, ls) >= 0;
  385. if (res) {
  386. // 在区间中,处理钱的问题.
  387. // 按比例分配金额; 分配完后,结果统一放回原数据中
  388. const actResult = [];
  389. let discountTotal = number;
  390. if (platform_act_type === '6') {
  391. // 满折:因为输入的是折扣,所以需要将折扣转换成具体金额,然后与优惠上限对比,决定最后优惠总金额
  392. const dp = this.ctx.minus(1, this.ctx.divide(number, 10));
  393. // 计算优惠的金额
  394. discountTotal = this.ctx.multiply(dp, total);
  395. // 如果超出上限,则使用上限值作为优惠金额
  396. if (_.isNumber(max)) {
  397. if (this.ctx.minus(discountTotal, max) > 0) discountTotal = max;
  398. }
  399. }
  400. for (const gia of goodsInAct) {
  401. const { goodsSpec_id } = gia;
  402. // 不是最后一个
  403. if (!_.isEqual(gia, _.last(goodsInAct))) {
  404. const rp = this.getGoodsPayAfterAct(gia);
  405. const percent = this.ctx.divide(rp, total);
  406. const money = this.ctx.multiply(percent, discountTotal);
  407. actResult.push({ platform_act, platform_act_type, discount: money, goodsSpec_id });
  408. } else {
  409. const allready = actResult.reduce((p, n) => this.ctx.plus(p, n.money), 0);
  410. const el = this.ctx.minus(discountTotal, allready);
  411. actResult.push({ platform_act, platform_act_type, discount: el, goodsSpec_id });
  412. }
  413. }
  414. // 修改数据
  415. for (const i of actResult) {
  416. const { goodsSpec_id, ...others } = i;
  417. const r = goodsList.find(f => f.goodsSpec_id === goodsSpec_id);
  418. if (r) {
  419. const { act = [] } = r;
  420. act.push(others);
  421. r.act = act;
  422. }
  423. }
  424. // 修改活动数据,做明细
  425. const text = `满${platform_act_type === '6' ? '折' : '减'}活动`;
  426. const actData = await this.platformActModel.findById(platform_act);
  427. act.title = _.get(actData, 'act_time.title', text);
  428. act.discount = actResult.reduce((p, n) => this.ctx.minus(p, n.discount), 0);
  429. break;
  430. }
  431. }
  432. }
  433. }
  434. /**
  435. * 商品买赠处理
  436. * @param {Array} goodsList 平铺的商品列表
  437. * @param {Array} actList 活动
  438. */
  439. async dealAct_gift(goodsList, actList) {
  440. for (const act of actList) {
  441. const { spec, gift, platform_act, platform_act_type } = act;
  442. const goodsInAct = await this.getGoodsInAct(goodsList, platform_act);
  443. const actResult = [];
  444. for (const goods of goodsInAct) {
  445. const { goodsSpec_id } = goods;
  446. if (spec === goodsSpec_id) {
  447. actResult.push({ platform_act, platform_act_type, gift, goodsSpec_id });
  448. }
  449. }
  450. for (const i of actResult) {
  451. const { goodsSpec_id, ...others } = i;
  452. const r = goodsList.find(f => f.goodsSpec_id === goodsSpec_id);
  453. if (r) {
  454. const { act = [] } = r;
  455. act.push(others);
  456. r.act = act;
  457. r.gift = _.get(i, 'gift');
  458. }
  459. }
  460. }
  461. }
  462. /**
  463. * 查看商品是否在活动中
  464. * @param {Array} goodsList 平铺商品列表
  465. * @param {String} platform_act 活动id
  466. */
  467. async getGoodsInAct(goodsList, platform_act) {
  468. const num = await this.platformActModel.count({ _id: platform_act, is_use: '0' });
  469. if (num <= 0) return [];
  470. // 查询商品是否参与活动
  471. const goodsInAct = [];
  472. for (const goods of goodsList) {
  473. const { goodsSpec_id } = goods;
  474. const gnum = await this.gjaModel.count({ 'spec._id': goodsSpec_id, platform_act });
  475. if (gnum <= 0) continue;
  476. goodsInAct.push(goods);
  477. }
  478. return goodsInAct;
  479. }
  480. /**
  481. * 获取商品经活动后实付的价格
  482. * @param {Object} goods 平铺的商品数据
  483. */
  484. getGoodsPayAfterAct(goods) {
  485. const { act = [], price, num } = goods;
  486. const actDiscount = act.reduce((p, n) => this.ctx.plus(p, n.discount), 0);
  487. const sp = this.ctx.multiply(price, num);
  488. const rp = this.ctx.minus(sp, actDiscount);
  489. return rp;
  490. }
  491. /**
  492. * 获取满减/折区间范围
  493. * @param {Array} discount 满减/折阶梯设置
  494. */
  495. getDiscountRange(discount) {
  496. const range = [];
  497. for (let i = 0; i < discount.length; i++) {
  498. const e1 = _.get(discount, i);
  499. const e2 = _.get(discount, i + 1);
  500. if (e1 && e2) {
  501. const { limit: ls, number, max } = e1;
  502. const { limit: le } = e2;
  503. const obj = { ls: this.ctx.toNumber(ls), le: this.ctx.toNumber(le), number: this.ctx.toNumber(number) };
  504. if (max) obj.max = max;
  505. range.push(obj);
  506. } else if (e1 && !e2) {
  507. const { limit: ls, number, max } = e1;
  508. const obj = { ls: this.ctx.toNumber(ls), number: this.ctx.toNumber(number) };
  509. if (max) obj.max = max;
  510. range.push(obj);
  511. }
  512. }
  513. return range;
  514. }
  515. // #endregion
  516. }
  517. module.exports = OrderService;