order.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  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, '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, num, freight } = i;
  105. i.goods_total = this.ctx.multiply(num, sell_money);
  106. i.freight_total = this.ctx.multiply(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. ** }
  163. ** }
  164. */
  165. moneyDetail(data) {
  166. if (!data) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到订单信息');
  167. // 优惠部分
  168. const ddt = _.get(data, 'total_detail.discount_detail', {});
  169. // 店铺规格商品数据
  170. const shopGoods = _.get(data, 'goods', []);
  171. const result = {};
  172. for (const s of shopGoods) {
  173. const { goods, shop } = s;
  174. const shopResult = {};
  175. for (const g of goods) {
  176. const { sell_money, freight: f, buy_num: bn, _id, act: ad = [] } = g;
  177. // 优先获取price字段,没有再取sell_money
  178. const sm = _.get(g, 'price', sell_money);
  179. const st = this.ctx.multiply(sm, bn);
  180. const ft = this.ctx.multiply(f, bn);
  181. const gt = this.ctx.plus(st, ft);
  182. // 优惠券部分
  183. const dd = {};
  184. for (const uc_id in ddt) {
  185. const detail = _.get(ddt, uc_id, {});
  186. const value = detail[_id];
  187. if (value) dd[uc_id] = value;
  188. }
  189. const dt = Object.values(dd).reduce((p, n) => this.ctx.plus(p, n), 0);
  190. // 活动部分
  191. const at = ad.reduce((p, n) => this.ctx.plus(p, n.discount), 0);
  192. const grp = this.ctx.minus(this.ctx.minus(gt, dt), at);
  193. const obj = { sm, f, bn, st, ft, gt, dd, dt, grp, ad, at };
  194. shopResult[_id] = obj;
  195. }
  196. result[shop] = shopResult;
  197. }
  198. return result;
  199. }
  200. // #region 创建订单数据组织部分
  201. /**
  202. * 组织商品数据
  203. * @param {Array} goods 商品列表
  204. * @property {Array} actList 活动列表
  205. * @property {Array} goodsSpec 后面优惠券使用有关计算的数据
  206. * @property {Array} goodsData 组织新的商品数据
  207. */
  208. async makeOrderGoodsData(goods) {
  209. // 商店不做快照,但是商品和商品对应的规格做快照
  210. const actList = [],
  211. goodsSpecs = [],
  212. goodsData = [];
  213. for (const i of goods) {
  214. const { goods: goodsList, is_set = '1', set_id, ...others } = i;
  215. const qp = [];
  216. if (is_set === '1') {
  217. for (const g of goodsList) {
  218. const { goodsSpec_id, goods_id } = g;
  219. // 需要的订单数据
  220. const orderNeedData = _.pick(g, [ 'act', 'price', 'sp_price', 'num', 'cart_id', 'gift' ]);
  221. if (orderNeedData.num) {
  222. orderNeedData.buy_num = orderNeedData.num;
  223. delete orderNeedData.num;
  224. }
  225. let goodsSpec = await this.goodsSpecModel.findById(goodsSpec_id);
  226. if (!goodsSpec) continue;
  227. goodsSpec = JSON.parse(JSON.stringify(goodsSpec));
  228. const goods = await this.goodsModel.findById(goods_id);
  229. if (goods) goodsSpec.goods = JSON.parse(JSON.stringify(goods));
  230. goodsSpec = { ...goodsSpec, ...orderNeedData };
  231. qp.push(goodsSpec);
  232. const ogs = _.pick(goodsSpec, [ '_id', 'buy_num', 'sell_money', 'price' ]);
  233. if (ogs._id) {
  234. ogs.id = ogs._id;
  235. delete ogs._id;
  236. }
  237. goodsSpecs.push({ ...ogs });
  238. // 将活动提取出来:只需要满减/折;买赠和特价跟着规格走,计算过程中已经处理;加价购是外面处理
  239. const { act = [] } = goodsSpec;
  240. let gAct = act.filter(f => f.platform_act_type === '5' || f.platform_act_type === '6');
  241. gAct = gAct.map(i => ({ ...i, goodsSpec_id: goodsSpec._id }));
  242. actList.push(...gAct);
  243. }
  244. goodsData.push({ ...others, goods: qp });
  245. } else {
  246. const data = await this.goodsSetService.getSnapshot(set_id);
  247. data.cart_id = i.cart_id;
  248. data.buy_num = i.num;
  249. data.is_set = '0';
  250. data.set_id = i.set_id;
  251. goodsData.push(data);
  252. }
  253. }
  254. return { actList, goodsSpecs, goodsData };
  255. }
  256. /**
  257. * 将加购商品组织进商品数据中
  258. * @param {Array} goodsData 上面组织过的数据
  259. * @param {Array} plus_goods 加购商品
  260. */
  261. async addPlusGoods(goodsData, plus_goods) {
  262. for (const i of plus_goods) {
  263. const { shop, shop_name, goods: goods_id, spec: spec_id, _id, config, platform_act, platform_act_type } = i;
  264. // 1,验证活动中是否有数据
  265. let num = await this.platformActModel.count({ _id: platform_act });
  266. // 没找到活动:下一个
  267. if (num <= 0) continue;
  268. num = await this.gjaModel.count({ _id });
  269. // 没有商品数据:下一个
  270. if (num <= 0) continue;
  271. // 2.做商品,规格的快照
  272. let goodsSpec = await this.goodsSpecModel.findById(spec_id);
  273. if (!goodsSpec) continue;
  274. goodsSpec = JSON.parse(JSON.stringify(goodsSpec));
  275. const goods = await this.goodsModel.findById(goods_id);
  276. if (goods) goodsSpec.goods = JSON.parse(JSON.stringify(goods));
  277. // 3.向上面一样组织数据
  278. const price = _.get(config, 'plus_money', _.get(goodsSpec, 'sell_money'));
  279. const act = [{ platform_act, platform_act_type, goods: goods_id, spec: spec_id }];
  280. goodsSpec.price = price;
  281. goodsSpec.act = act;
  282. // 商品数量固定为1
  283. goodsSpec.buy_num = 1;
  284. // 4.合并进goodsData
  285. const r = goodsData.find(f => f.shop === shop);
  286. if (r) r.goods.push(goodsSpec);
  287. else {
  288. goodsData.push({ shop, shop_name, goods: [ goodsSpec ] });
  289. }
  290. }
  291. return goodsData;
  292. }
  293. // #endregion
  294. // #region 活动部分
  295. /**
  296. * 检查商品是否满足加价购
  297. * @param {Array} goodsList 平铺的商品列表
  298. * @param {Array} actList 活动
  299. */
  300. async dealAct_plus(goodsList, actList) {
  301. for (const act of actList) {
  302. const { platform_act, plus_money } = act;
  303. const goodsInAct = await this.getGoodsInAct(goodsList, platform_act);
  304. // 没有有关活动的商品,直接下个活动
  305. if (goodsInAct.length <= 0) continue;
  306. const total = goodsInAct.reduce((p, n) => {
  307. const rp = this.getGoodsPayAfterAct(n);
  308. return this.ctx.plus(p, rp);
  309. }, 0);
  310. // 商品,优惠过后的金额,大于等于 活动下限:活动可以进行
  311. if (this.ctx.minus(total, plus_money) >= 0) act.activity = true;
  312. }
  313. }
  314. /**
  315. * 设置商品特价部分
  316. * @param {Array} goodsList 平铺的商品列表
  317. * @param {Array} actList 活动
  318. */
  319. dealAct_sp(goodsList, actList) {
  320. for (const act of actList) {
  321. const { spec, sp_price, platform_act_type, platform_act } = act;
  322. if (!spec) continue;
  323. const goods = goodsList.find(f => f.goodsSpec_id === spec);
  324. if (goods) {
  325. // 默认特价为商品金额
  326. goods.sp_price = sp_price;
  327. // 有团长价格,且团长价格比特价低,就用团长价格
  328. if (goods.leader_price && this.ctx.minus(goods.leader_price, goods.sp_price) < 0) goods.price = goods.leader_price;
  329. else goods.price = sp_price;
  330. const { act = [] } = goods;
  331. act.push({ platform_act_type, platform_act, sp_price });
  332. goods.act = act;
  333. }
  334. }
  335. }
  336. /**
  337. * 商品满减/折处理:主要区分在于 将折扣转换为金额,剩下都是按比例分配
  338. * @param {Array} goodsList 平铺的商品列表
  339. * @param {Array} actList 活动
  340. */
  341. async dealAct_discount(goodsList, actList) {
  342. for (const act of actList) {
  343. const { discount = [], platform_act, platform_act_type } = act;
  344. // 整理出区间
  345. const range = this.getDiscountRange(discount);
  346. // 找到在当前活动的商品
  347. const goodsInAct = await this.getGoodsInAct(goodsList, platform_act);
  348. if (goodsInAct.length <= 0) continue;
  349. // 计算总价格够不够线(因为活动有优先级问题,如果发生满减够, 而满减之后的价格就不足以满折, 那就不给满折,所以要重新计算)
  350. const total = goodsInAct.reduce((p, n) => {
  351. const rp = this.getGoodsPayAfterAct(n);
  352. return this.ctx.plus(p, rp);
  353. }, 0);
  354. for (const r of range) {
  355. const { ls, le, number, max } = r;
  356. let res = false;
  357. if (ls && le) res = _.inRange(total, ls, le);
  358. else if (ls && !le) res = this.ctx.minus(total, ls) >= 0;
  359. if (res) {
  360. // 在区间中,处理钱的问题.
  361. // 按比例分配金额; 分配完后,结果统一放回原数据中
  362. const actResult = [];
  363. let discountTotal = number;
  364. if (platform_act_type === '6') {
  365. // 满折:因为输入的是折扣,所以需要将折扣转换成具体金额,然后与优惠上限对比,决定最后优惠总金额
  366. const dp = this.ctx.minus(1, this.ctx.divide(number, 10));
  367. // 计算优惠的金额
  368. discountTotal = this.ctx.multiply(dp, total);
  369. // 如果超出上限,则使用上限值作为优惠金额
  370. if (_.isNumber(max)) {
  371. if (this.ctx.minus(discountTotal, max) > 0) discountTotal = max;
  372. }
  373. }
  374. for (const gia of goodsInAct) {
  375. const { goodsSpec_id } = gia;
  376. // 不是最后一个
  377. if (!_.isEqual(gia, _.last(goodsInAct))) {
  378. const rp = this.getGoodsPayAfterAct(gia);
  379. const percent = this.ctx.divide(rp, total);
  380. const money = this.ctx.multiply(percent, discountTotal);
  381. actResult.push({ platform_act, platform_act_type, discount: money, goodsSpec_id });
  382. } else {
  383. const allready = actResult.reduce((p, n) => this.ctx.plus(p, n.money), 0);
  384. const el = this.ctx.minus(discountTotal, allready);
  385. actResult.push({ platform_act, platform_act_type, discount: el, goodsSpec_id });
  386. }
  387. }
  388. // 修改数据
  389. for (const i of actResult) {
  390. const { goodsSpec_id, ...others } = i;
  391. const r = goodsList.find(f => f.goodsSpec_id === goodsSpec_id);
  392. if (r) {
  393. const { act = [] } = r;
  394. act.push(others);
  395. r.act = act;
  396. }
  397. }
  398. // 修改活动数据,做明细
  399. const text = `满${platform_act_type === '6' ? '折' : '减'}活动`;
  400. const actData = await this.platformActModel.findById(platform_act);
  401. act.title = _.get(actData, 'act_time.title', text);
  402. act.discount = actResult.reduce((p, n) => this.ctx.minus(p, n.discount), 0);
  403. break;
  404. }
  405. }
  406. }
  407. }
  408. /**
  409. * 商品买赠处理
  410. * @param {Array} goodsList 平铺的商品列表
  411. * @param {Array} actList 活动
  412. */
  413. async dealAct_gift(goodsList, actList) {
  414. for (const act of actList) {
  415. const { spec, gift, platform_act, platform_act_type } = act;
  416. const goodsInAct = await this.getGoodsInAct(goodsList, platform_act);
  417. const actResult = [];
  418. for (const goods of goodsInAct) {
  419. const { goodsSpec_id } = goods;
  420. if (spec === goodsSpec_id) {
  421. actResult.push({ platform_act, platform_act_type, gift, goodsSpec_id });
  422. }
  423. }
  424. for (const i of actResult) {
  425. const { goodsSpec_id, ...others } = i;
  426. const r = goodsList.find(f => f.goodsSpec_id === goodsSpec_id);
  427. if (r) {
  428. const { act = [] } = r;
  429. act.push(others);
  430. r.act = act;
  431. r.gift = _.get(i, 'gift');
  432. }
  433. }
  434. }
  435. }
  436. /**
  437. * 查看商品是否在活动中
  438. * @param {Array} goodsList 平铺商品列表
  439. * @param {String} platform_act 活动id
  440. */
  441. async getGoodsInAct(goodsList, platform_act) {
  442. const num = await this.platformActModel.count({ _id: platform_act, is_use: '0' });
  443. if (num <= 0) return [];
  444. // 查询商品是否参与活动
  445. const goodsInAct = [];
  446. for (const goods of goodsList) {
  447. const { goodsSpec_id } = goods;
  448. const gnum = await this.gjaModel.count({ 'spec._id': goodsSpec_id, platform_act });
  449. if (gnum <= 0) continue;
  450. goodsInAct.push(goods);
  451. }
  452. return goodsInAct;
  453. }
  454. /**
  455. * 获取商品经活动后实付的价格
  456. * @param {Object} goods 平铺的商品数据
  457. */
  458. getGoodsPayAfterAct(goods) {
  459. const { act = [], price, num } = goods;
  460. const actDiscount = act.reduce((p, n) => this.ctx.plus(p, n.discount), 0);
  461. const sp = this.ctx.multiply(price, num);
  462. const rp = this.ctx.minus(sp, actDiscount);
  463. return rp;
  464. }
  465. /**
  466. * 获取满减/折区间范围
  467. * @param {Array} discount 满减/折阶梯设置
  468. */
  469. getDiscountRange(discount) {
  470. const range = [];
  471. for (let i = 0; i < discount.length; i++) {
  472. const e1 = _.get(discount, i);
  473. const e2 = _.get(discount, i + 1);
  474. if (e1 && e2) {
  475. const { limit: ls, number, max } = e1;
  476. const { limit: le } = e2;
  477. const obj = { ls: this.ctx.toNumber(ls), le: this.ctx.toNumber(le), number: this.ctx.toNumber(number) };
  478. if (max) obj.max = max;
  479. range.push(obj);
  480. } else if (e1 && !e2) {
  481. const { limit: ls, number, max } = e1;
  482. const obj = { ls: this.ctx.toNumber(ls), number: this.ctx.toNumber(number) };
  483. if (max) obj.max = max;
  484. range.push(obj);
  485. }
  486. }
  487. return range;
  488. }
  489. // #endregion
  490. }
  491. module.exports = OrderService;