order.js 18 KB

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