order.js 14 KB

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