order.js 14 KB

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