order.js 18 KB

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