order.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  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, _.get(g, 'price'));
  28. freight_total = this.ctx.plus(freight_total, _.get(g, 'freight'));
  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 = 'price';
  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. ** grp:商品实际支付价格(goods_real_pay: gt - dt)
  138. ** gsm:规格团购销售价格(group_sell_money)
  139. ** gst: 规格团购销售总价(group_sell_total: gsm * bn)
  140. ** ggt: 商品团购支付原价(goods_group_total: gst + ft)
  141. ** ggrp: 商品团购实际支付价格(goods_group_real_pay: ggt - dt)
  142. ** }
  143. ** }
  144. ** }
  145. */
  146. moneyDetail(data) {
  147. if (!data) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到订单信息');
  148. // 优惠部分
  149. const ddt = _.get(data, 'total_detail.discount_detail', {});
  150. // 活动部分
  151. const act = _.get(data, 'total_detail.act', []);
  152. // 店铺规格商品数据
  153. const shopGoods = _.get(data, 'goods', []);
  154. const result = {};
  155. for (const s of shopGoods) {
  156. const { goods, shop } = s;
  157. const shopResult = {};
  158. for (const g of goods) {
  159. const { sell_money, freight: f, buy_num: bn, group_config, _id } = g;
  160. // 优先获取price字段,没有再取sell_money
  161. const sm = _.get(g, 'price', sell_money);
  162. const st = this.ctx.multiply(sm, bn);
  163. const ft = this.ctx.multiply(f, bn);
  164. const gt = this.ctx.plus(st, ft);
  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. const grp = this.ctx.minus(gt, dt);
  173. let obj = { sm, f, bn, st, ft, gt, dd, dt, grp };
  174. const gsm = _.get(group_config, 'money');
  175. if (gsm) {
  176. const gst = this.ctx.multiply(gsm, bn);
  177. const ggt = this.ctx.plus(gst, ft);
  178. const ggrp = this.ctx.minus(ggt, dt);
  179. obj = { ...obj, gsm, gst, ggt, ggrp };
  180. }
  181. shopResult[_id] = obj;
  182. }
  183. result[shop] = shopResult;
  184. }
  185. return result;
  186. }
  187. /**
  188. * 检查商品是否满足加价购
  189. * @param {Array} goodsList 平铺的商品列表
  190. * @param {Array} actList 活动
  191. */
  192. async dealAct_plus(goodsList, actList) {
  193. for (const act of actList) {
  194. const { platform_act, plus_money } = act;
  195. const goodsInAct = await this.getGoodsInAct(goodsList, platform_act);
  196. // 没有有关活动的商品,直接下个活动
  197. if (goodsInAct.length <= 0) continue;
  198. const total = goodsInAct.reduce((p, n) => {
  199. const rp = this.getGoodsPayAfterAct(n);
  200. return this.ctx.plus(p, rp);
  201. }, 0);
  202. // 商品,优惠过后的金额,大于等于 活动下限:活动可以进行
  203. if (this.ctx.minus(total, plus_money) >= 0) act.activity = true;
  204. }
  205. }
  206. /**
  207. * 设置商品特价部分
  208. * @param {Array} goodsList 平铺的商品列表
  209. * @param {Array} actList 活动
  210. */
  211. dealAct_sp(goodsList, actList) {
  212. for (const act of actList) {
  213. const { spec, sp_price, platform_act_type, platform_act } = act;
  214. if (!spec) continue;
  215. const goods = goodsList.find(f => f.goodsSpec_id === spec);
  216. if (goods) {
  217. // 默认特价为商品金额
  218. goods.sp_price = sp_price;
  219. goods.price = sp_price;
  220. const { act = [] } = goods;
  221. act.push({ platform_act_type, platform_act, sp_price });
  222. goods.act = act;
  223. }
  224. }
  225. }
  226. /**
  227. * 商品满减/折处理:主要区分在于 将折扣转换为金额,剩下都是按比例分配
  228. * @param {Array} goodsList 平铺的商品列表
  229. * @param {Array} actList 活动
  230. */
  231. async dealAct_discount(goodsList, actList) {
  232. for (const act of actList) {
  233. const { discount = [], platform_act, platform_act_type } = act;
  234. // 整理出区间
  235. const range = this.getDiscountRange(discount);
  236. // 找到在当前活动的商品
  237. const goodsInAct = await this.getGoodsInAct(goodsList, platform_act);
  238. if (goodsInAct.length <= 0) continue;
  239. // 计算总价格够不够线(因为活动有优先级问题,如果发生满减够, 而满减之后的价格就不足以满折, 那就不给满折,所以要重新计算)
  240. const total = goodsInAct.reduce((p, n) => {
  241. const rp = this.getGoodsPayAfterAct(n);
  242. return this.ctx.plus(p, rp);
  243. }, 0);
  244. for (const r of range) {
  245. const { ls, le, number, max } = r;
  246. let res = false;
  247. if (ls && le) res = _.inRange(total, ls, le);
  248. else if (ls && !le) res = this.ctx.minus(total, ls) >= 0;
  249. if (res) {
  250. // 在区间中,处理钱的问题.
  251. // 按比例分配金额; 分配完后,结果统一放回原数据中
  252. const actResult = [];
  253. let discountTotal = number;
  254. if (platform_act_type === '6') {
  255. // 满折:因为输入的是折扣,所以需要将折扣转换成具体金额,然后与优惠上限对比,决定最后优惠总金额
  256. const dp = this.ctx.minus(1, this.ctx.divide(number, 10));
  257. // 计算优惠的金额
  258. discountTotal = this.ctx.multiply(dp, total);
  259. // 如果超出上限,则使用上限值作为优惠金额
  260. if (_.isNumber(max)) {
  261. if (this.ctx.minus(discountTotal, max) > 0) discountTotal = max;
  262. }
  263. }
  264. for (const gia of goodsInAct) {
  265. const { goodsSpec_id } = gia;
  266. // 不是最后一个
  267. if (!_.isEqual(gia, _.last(goodsInAct))) {
  268. const rp = this.getGoodsPayAfterAct(gia);
  269. const percent = this.ctx.divide(rp, total);
  270. const money = this.ctx.multiply(percent, discountTotal);
  271. actResult.push({ platform_act, platform_act_type, discount: money, goodsSpec_id });
  272. } else {
  273. const allready = actResult.reduce((p, n) => this.ctx.plus(p, n.money), 0);
  274. const el = this.ctx.minus(discountTotal, allready);
  275. actResult.push({ platform_act, platform_act_type, discount: el, goodsSpec_id });
  276. }
  277. }
  278. // 修改数据
  279. for (const i of actResult) {
  280. const { goodsSpec_id, ...others } = i;
  281. const r = goodsList.find(f => f.goodsSpec_id === goodsSpec_id);
  282. if (r) {
  283. const { act = [] } = r;
  284. act.push(others);
  285. r.act = act;
  286. }
  287. }
  288. // 修改活动数据,做明细
  289. const text = `满${platform_act_type === '6' ? '折' : '减'}活动`;
  290. const actData = await this.platformActModel.findById(platform_act);
  291. act.title = _.get(actData, 'act_time.title', text);
  292. act.discount = actResult.reduce((p, n) => this.ctx.minus(p, n.discount), 0);
  293. break;
  294. }
  295. }
  296. }
  297. }
  298. /**
  299. * 商品买赠处理
  300. * @param {Array} goodsList 平铺的商品列表
  301. * @param {Array} actList 活动
  302. */
  303. async dealAct_gift(goodsList, actList) {
  304. for (const act of actList) {
  305. const { spec, gift, platform_act, platform_act_type } = act;
  306. const goodsInAct = await this.getGoodsInAct(goodsList, platform_act);
  307. const actResult = [];
  308. for (const goods of goodsInAct) {
  309. const { goodsSpec_id } = goods;
  310. if (spec === goodsSpec_id) {
  311. actResult.push({ platform_act, platform_act_type, gift, goodsSpec_id });
  312. }
  313. }
  314. for (const i of actResult) {
  315. const { goodsSpec_id, gift, ...others } = i;
  316. const r = goodsList.find(f => f.goodsSpec_id === goodsSpec_id);
  317. if (r) {
  318. const { act = [] } = r;
  319. act.push(others);
  320. r.act = act;
  321. r.gift = gift;
  322. }
  323. }
  324. }
  325. }
  326. /**
  327. * 查看商品是否在活动中
  328. * @param {Array} goodsList 平铺商品列表
  329. * @param {String} platform_act 活动id
  330. */
  331. async getGoodsInAct(goodsList, platform_act) {
  332. const num = await this.platformActModel.count({ _id: platform_act, is_use: '0' });
  333. if (num <= 0) return [];
  334. // 查询商品是否参与活动
  335. const goodsInAct = [];
  336. for (const goods of goodsList) {
  337. const { goodsSpec_id } = goods;
  338. const gnum = await this.gjaModel.count({ 'spec._id': goodsSpec_id, platform_act });
  339. if (gnum <= 0) continue;
  340. goodsInAct.push(goods);
  341. }
  342. return goodsInAct;
  343. }
  344. /**
  345. * 获取商品经活动后实付的价格
  346. * @param {Object} goods 平铺的商品数据
  347. */
  348. getGoodsPayAfterAct(goods) {
  349. const { act = [], price } = goods;
  350. const actDiscount = act.reduce((p, n) => this.ctx.plus(p, n.discount), 0);
  351. const rp = this.ctx.minus(price, actDiscount);
  352. return rp;
  353. }
  354. /**
  355. * 获取满减/折区间范围
  356. * @param {Array} discount 满减/折阶梯设置
  357. */
  358. getDiscountRange(discount) {
  359. const range = [];
  360. for (let i = 0; i < discount.length; i++) {
  361. const e1 = _.get(discount, i);
  362. const e2 = _.get(discount, i + 1);
  363. if (e1 && e2) {
  364. const { limit: ls, number, max } = e1;
  365. const { limit: le } = e2;
  366. const obj = { ls: this.ctx.toNumber(ls), le: this.ctx.toNumber(le), number: this.ctx.toNumber(number) };
  367. if (max) obj.max = max;
  368. range.push(obj);
  369. } else if (e1 && !e2) {
  370. const { limit: ls, number, max } = e1;
  371. const obj = { ls: this.ctx.toNumber(ls), number: this.ctx.toNumber(number) };
  372. if (max) obj.max = max;
  373. range.push(obj);
  374. }
  375. }
  376. return range;
  377. }
  378. }
  379. module.exports = OrderService;