order.js 13 KB

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