order.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  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. goodsData.push(data);
  277. }
  278. }
  279. return { actList, goodsSpecs, goodsData };
  280. }
  281. /**
  282. * 将加购商品组织进商品数据中
  283. * @param {Array} goodsData 上面组织过的数据
  284. * @param {Array} plus_goods 加购商品
  285. */
  286. async addPlusGoods(goodsData, plus_goods) {
  287. for (const i of plus_goods) {
  288. const { shop, shop_name, goods: goods_id, spec: spec_id, _id, config, platform_act, platform_act_type } = i;
  289. // 1,验证活动中是否有数据
  290. let num = await this.platformActModel.count({ _id: platform_act });
  291. // 没找到活动:下一个
  292. if (num <= 0) continue;
  293. num = await this.gjaModel.count({ _id });
  294. // 没有商品数据:下一个
  295. if (num <= 0) continue;
  296. // 2.做商品,规格的快照
  297. let goodsSpec = await this.goodsSpecModel.findById(spec_id);
  298. if (!goodsSpec) continue;
  299. goodsSpec = JSON.parse(JSON.stringify(goodsSpec));
  300. const goods = await this.goodsModel.findById(goods_id);
  301. if (goods) goodsSpec.goods = JSON.parse(JSON.stringify(goods));
  302. // 3.向上面一样组织数据
  303. const price = _.get(config, 'plus_money', _.get(goodsSpec, 'sell_money'));
  304. const act = [{ platform_act, platform_act_type, goods: goods_id, spec: spec_id }];
  305. goodsSpec.price = price;
  306. goodsSpec.act = act;
  307. // 商品数量固定为1
  308. goodsSpec.buy_num = 1;
  309. // 4.合并进goodsData
  310. const r = goodsData.find(f => f.shop === shop);
  311. if (r) r.goods.push(goodsSpec);
  312. else {
  313. goodsData.push({ shop, shop_name, goods: [ goodsSpec ] });
  314. }
  315. }
  316. return goodsData;
  317. }
  318. // #endregion
  319. // #region 活动部分
  320. /**
  321. * 检查商品是否满足加价购
  322. * @param {Array} goodsList 平铺的商品列表
  323. * @param {Array} actList 活动
  324. */
  325. async dealAct_plus(goodsList, actList) {
  326. for (const act of actList) {
  327. const { platform_act, plus_money } = act;
  328. const goodsInAct = await this.getGoodsInAct(goodsList, platform_act);
  329. // 没有有关活动的商品,直接下个活动
  330. if (goodsInAct.length <= 0) continue;
  331. const total = goodsInAct.reduce((p, n) => {
  332. const rp = this.getGoodsPayAfterAct(n);
  333. return this.ctx.plus(p, rp);
  334. }, 0);
  335. // 商品,优惠过后的金额,大于等于 活动下限:活动可以进行
  336. if (this.ctx.minus(total, plus_money) >= 0) act.activity = true;
  337. }
  338. }
  339. /**
  340. * 设置商品特价部分
  341. * @param {Array} goodsList 平铺的商品列表
  342. * @param {Array} actList 活动
  343. */
  344. dealAct_sp(goodsList, actList) {
  345. for (const act of actList) {
  346. const { spec, sp_price, platform_act_type, platform_act } = act;
  347. if (!spec) continue;
  348. const goods = goodsList.find(f => f.goodsSpec_id === spec);
  349. if (goods) {
  350. // 默认特价为商品金额
  351. goods.sp_price = sp_price;
  352. // 有团长价格,且团长价格比特价低,就用团长价格
  353. if (goods.leader_price && this.ctx.minus(goods.leader_price, goods.sp_price) < 0) goods.price = goods.leader_price;
  354. else goods.price = sp_price;
  355. const { act = [] } = goods;
  356. act.push({ platform_act_type, platform_act, sp_price });
  357. goods.act = act;
  358. }
  359. }
  360. }
  361. /**
  362. * 商品满减/折处理:主要区分在于 将折扣转换为金额,剩下都是按比例分配
  363. * @param {Array} goodsList 平铺的商品列表
  364. * @param {Array} actList 活动
  365. */
  366. async dealAct_discount(goodsList, actList) {
  367. for (const act of actList) {
  368. const { discount = [], platform_act, platform_act_type } = act;
  369. // 整理出区间
  370. const range = this.getDiscountRange(discount);
  371. // 找到在当前活动的商品
  372. const goodsInAct = await this.getGoodsInAct(goodsList, platform_act);
  373. if (goodsInAct.length <= 0) continue;
  374. // 计算总价格够不够线(因为活动有优先级问题,如果发生满减够, 而满减之后的价格就不足以满折, 那就不给满折,所以要重新计算)
  375. const total = goodsInAct.reduce((p, n) => {
  376. const rp = this.getGoodsPayAfterAct(n);
  377. return this.ctx.plus(p, rp);
  378. }, 0);
  379. for (const r of range) {
  380. const { ls, le, number, max } = r;
  381. let res = false;
  382. if (ls && le) res = _.inRange(total, ls, le);
  383. else if (ls && !le) res = this.ctx.minus(total, ls) >= 0;
  384. if (res) {
  385. // 在区间中,处理钱的问题.
  386. // 按比例分配金额; 分配完后,结果统一放回原数据中
  387. const actResult = [];
  388. let discountTotal = number;
  389. if (platform_act_type === '6') {
  390. // 满折:因为输入的是折扣,所以需要将折扣转换成具体金额,然后与优惠上限对比,决定最后优惠总金额
  391. const dp = this.ctx.minus(1, this.ctx.divide(number, 10));
  392. // 计算优惠的金额
  393. discountTotal = this.ctx.multiply(dp, total);
  394. // 如果超出上限,则使用上限值作为优惠金额
  395. if (_.isNumber(max)) {
  396. if (this.ctx.minus(discountTotal, max) > 0) discountTotal = max;
  397. }
  398. }
  399. for (const gia of goodsInAct) {
  400. const { goodsSpec_id } = gia;
  401. // 不是最后一个
  402. if (!_.isEqual(gia, _.last(goodsInAct))) {
  403. const rp = this.getGoodsPayAfterAct(gia);
  404. const percent = this.ctx.divide(rp, total);
  405. const money = this.ctx.multiply(percent, discountTotal);
  406. actResult.push({ platform_act, platform_act_type, discount: money, goodsSpec_id });
  407. } else {
  408. const allready = actResult.reduce((p, n) => this.ctx.plus(p, n.money), 0);
  409. const el = this.ctx.minus(discountTotal, allready);
  410. actResult.push({ platform_act, platform_act_type, discount: el, goodsSpec_id });
  411. }
  412. }
  413. // 修改数据
  414. for (const i of actResult) {
  415. const { goodsSpec_id, ...others } = i;
  416. const r = goodsList.find(f => f.goodsSpec_id === goodsSpec_id);
  417. if (r) {
  418. const { act = [] } = r;
  419. act.push(others);
  420. r.act = act;
  421. }
  422. }
  423. // 修改活动数据,做明细
  424. const text = `满${platform_act_type === '6' ? '折' : '减'}活动`;
  425. const actData = await this.platformActModel.findById(platform_act);
  426. act.title = _.get(actData, 'act_time.title', text);
  427. act.discount = actResult.reduce((p, n) => this.ctx.minus(p, n.discount), 0);
  428. break;
  429. }
  430. }
  431. }
  432. }
  433. /**
  434. * 商品买赠处理
  435. * @param {Array} goodsList 平铺的商品列表
  436. * @param {Array} actList 活动
  437. */
  438. async dealAct_gift(goodsList, actList) {
  439. for (const act of actList) {
  440. const { spec, gift, platform_act, platform_act_type } = act;
  441. const goodsInAct = await this.getGoodsInAct(goodsList, platform_act);
  442. const actResult = [];
  443. for (const goods of goodsInAct) {
  444. const { goodsSpec_id } = goods;
  445. if (spec === goodsSpec_id) {
  446. actResult.push({ platform_act, platform_act_type, gift, goodsSpec_id });
  447. }
  448. }
  449. for (const i of actResult) {
  450. const { goodsSpec_id, ...others } = i;
  451. const r = goodsList.find(f => f.goodsSpec_id === goodsSpec_id);
  452. if (r) {
  453. const { act = [] } = r;
  454. act.push(others);
  455. r.act = act;
  456. r.gift = _.get(i, 'gift');
  457. }
  458. }
  459. }
  460. }
  461. /**
  462. * 查看商品是否在活动中
  463. * @param {Array} goodsList 平铺商品列表
  464. * @param {String} platform_act 活动id
  465. */
  466. async getGoodsInAct(goodsList, platform_act) {
  467. const num = await this.platformActModel.count({ _id: platform_act, is_use: '0' });
  468. if (num <= 0) return [];
  469. // 查询商品是否参与活动
  470. const goodsInAct = [];
  471. for (const goods of goodsList) {
  472. const { goodsSpec_id } = goods;
  473. const gnum = await this.gjaModel.count({ 'spec._id': goodsSpec_id, platform_act });
  474. if (gnum <= 0) continue;
  475. goodsInAct.push(goods);
  476. }
  477. return goodsInAct;
  478. }
  479. /**
  480. * 获取商品经活动后实付的价格
  481. * @param {Object} goods 平铺的商品数据
  482. */
  483. getGoodsPayAfterAct(goods) {
  484. const { act = [], price, num } = goods;
  485. const actDiscount = act.reduce((p, n) => this.ctx.plus(p, n.discount), 0);
  486. const sp = this.ctx.multiply(price, num);
  487. const rp = this.ctx.minus(sp, actDiscount);
  488. return rp;
  489. }
  490. /**
  491. * 获取满减/折区间范围
  492. * @param {Array} discount 满减/折阶梯设置
  493. */
  494. getDiscountRange(discount) {
  495. const range = [];
  496. for (let i = 0; i < discount.length; i++) {
  497. const e1 = _.get(discount, i);
  498. const e2 = _.get(discount, i + 1);
  499. if (e1 && e2) {
  500. const { limit: ls, number, max } = e1;
  501. const { limit: le } = e2;
  502. const obj = { ls: this.ctx.toNumber(ls), le: this.ctx.toNumber(le), number: this.ctx.toNumber(number) };
  503. if (max) obj.max = max;
  504. range.push(obj);
  505. } else if (e1 && !e2) {
  506. const { limit: ls, number, max } = e1;
  507. const obj = { ls: this.ctx.toNumber(ls), number: this.ctx.toNumber(number) };
  508. if (max) obj.max = max;
  509. range.push(obj);
  510. }
  511. }
  512. return range;
  513. }
  514. // #endregion
  515. }
  516. module.exports = OrderService;