'use strict'; const { CrudService } = require('naf-framework-mongoose-free/lib/service'); const { BusinessError, ErrorCode } = require('naf-core').Error; const _ = require('lodash'); const assert = require('assert'); // class OrderService extends CrudService { constructor(ctx) { super(ctx, 'order'); this.orderModel = this.ctx.model.Trade.Order; this.platformActModel = this.ctx.model.System.PlatformAct; this.gjaModel = this.ctx.model.Shop.GoodsJoinAct; this.goodsModel = this.ctx.model.Shop.Goods; this.goodsSpecModel = this.ctx.model.Shop.GoodsSpec; this.goodsSetService = this.ctx.service.shop.goodsSet; } // #region 下单前计算函数 /** * 计算每个店铺的价格 * list是经过 getPageData 处理过的数据 * @param {Array} list 按店铺分组的商品列表 */ makeOrder_computedShopTotal(list) { for (const i of list) { let goods_total = 0, freight_total = 0, discount = 0; const { is_set = '1' } = i; if (is_set === '1') { for (const g of i.goods) { // 如果有特价,那就使用特价,没有特价就是用正常销售价 goods_total = this.ctx.plus(goods_total, this.ctx.multiply(_.get(g, 'price'), _.get(g, 'num'))); freight_total = this.ctx.plus(freight_total, this.ctx.multiply(_.get(g, 'freight'), _.get(g, 'num'))); if (_.isArray(g.act)) { const actDiscount = g.act.reduce((p, n) => this.ctx.plus(p, n.discount), 0); discount = this.ctx.plus(discount, actDiscount); } } i.goods_total = goods_total; i.freight_total = freight_total; i.discount = this.ctx.minus(0, discount); } else { const { sell_money, num, freight } = i; i.goods_total = this.ctx.multiply(num, sell_money); i.freight_total = this.ctx.multiply(num, freight); } } return list; } /** * 计算整个订单的价格 * @param {Array} list 按店铺分组的商品列表 * list是经过 getPageData 处理过的数据 */ makerOrder_computedOrderTotal(list) { const arr = []; arr.push({ key: 'goods_total', zh: '商品总价', money: list.reduce((p, n) => this.ctx.plus(p, n.goods_total), 0) }); arr.push({ key: 'freight_total', zh: '运费总价', money: list.reduce((p, n) => this.ctx.plus(p, n.freight_total), 0) }); return arr; } // #endregion /** * 计算需要支付的金额 * @param {Object} order 支付订单信息 * @return {Number} 订单实付金额 */ payOrder_RealPay(order) { const priceKey = 'grp'; const detail = this.moneyDetail(order); // 解除店铺层 const sd = Object.values(detail); // 取出规格层 const sgd = sd.map(i => Object.values(i)); // 将规格明细降维至一维 const oneLevel = _.flattenDeep(sgd); // 根据订单类型,计算应付(优惠券部分已经按订单类型计算并分配完了.这地方只是复现) const realPay = oneLevel.reduce((p, n) => this.ctx.plus(p, n[priceKey]), 0); return realPay; } /** * 计算需要支付的金额 * @param {Object} list 店铺-商品列表 */ computedShopDetail(list) { for (const i of list) { let goods_total = 0, freight_total = 0, discount = 0; const { is_set = '1' } = i; if (is_set === '1') { for (const g of i.goods) { // 如果有特价,那就使用特价,没有特价就是用正常销售价 goods_total = this.ctx.plus(goods_total, this.ctx.multiply(_.get(g, 'price'), _.get(g, 'buy_num'))); freight_total = this.ctx.plus(freight_total, this.ctx.multiply(_.get(g, 'freight'), _.get(g, 'buy_num'))); if (_.isArray(g.act)) { const actDiscount = g.act.reduce((p, n) => this.ctx.plus(p, n.discount), 0); discount = this.ctx.plus(discount, actDiscount); } } i.goods_total = goods_total; i.freight_total = freight_total; i.discount = this.ctx.minus(0, discount); } else { const { sell_money, buy_num, freight } = i; i.goods_total = this.ctx.multiply(buy_num, sell_money); i.freight_total = this.ctx.multiply(buy_num, freight); } } return list; } /** * 计算店铺的金额明细 * @param {Object} order 支付订单信息 * @return {Object} 返回:{ * 店铺id:{ * goods_total:商品总价, * freight_total:商品总价 * } * } */ shopMoneyDetail(order) { if (!order) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到订单信息'); let priceKey; if (_.get(order, 'type', '0') === '1') priceKey = 'gst'; else priceKey = 'st'; const result = {}; const moneyDetail = this.moneyDetail(order); for (const s in moneyDetail) { const obj = {}; const d = _.get(moneyDetail, s, {}); obj.goods_total = Object.values(d).reduce((p, n) => this.ctx.plus(p, _.get(n, priceKey, 0)), 0); obj.freight_total = Object.values(d).reduce((p, n) => this.ctx.plus(p, _.get(n, 'ft', 0)), 0); const act = Object.values(d).reduce((p, n) => [ ...p, ..._.get(n, 'ad', []) ], []); obj.act = act.filter(f => f.platform_act_type === '5' || f.platform_act_type === '6'); result[s] = obj; } return result; } /** * 按店铺-商品 计算该订单的价格明细 * @param {Object} data 支付订单数据 * @return {Object} 返回:{ ** 店铺id:{ ** 规格id:{ ** sm: 规格正常销售价格(sell_money), ** f: 规格运费(freight), ** bn: 购买数量(buy_num), ** st: 规格正常销售总价(sell_total: sm * bn) ** ft: 规格运费总价(freight_total: f * bn) ** gt: 商品支付原价(goods_total: st + ft) ** dd: { ** key:优惠券id, ** value:优惠价格 ** }, ** dt: 优惠总价(d_detail的value之和) ** ad: [{ ** money:活动优惠金额(负数), ** platform_act:活动金额 ** }] ** at: 活动优惠总金额 ** }, ** 套装id:{ ** sm: 套装正常销售价格(sell_money), ** f: 套装运费(freight), ** bn: 购买数量(buy_num), ** st: 套装正常销售总价(sell_total: sm * bn) ** ft: 套装运费总价(freight_total: f * bn) ** gt: 套装支付原价(goods_total: st + ft) ** } ** }, ** } */ moneyDetail(data) { if (!data) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到订单信息'); // 优惠部分 const ddt = _.get(data, 'total_detail.discount_detail', {}); // 店铺规格商品数据 const shopGoods = _.get(data, 'goods', []); const groupShop = _.groupBy(shopGoods, 'shop'); const result = {}; for (const shop_id in groupShop) { const list = groupShop[shop_id]; const shopResult = {}; for (const s of list) { const { is_set = '1' } = s; if (is_set === '1') { const { goods } = s; for (const g of goods) { const { sell_money, freight: f, buy_num: bn, _id, act: ad = [] } = g; // 优先获取price字段,没有再取sell_money const sm = _.get(g, 'price', sell_money); const st = this.ctx.multiply(sm, bn); const ft = this.ctx.multiply(f, bn); const gt = this.ctx.plus(st, ft); // 优惠券部分 const dd = {}; for (const uc_id in ddt) { const detail = _.get(ddt, uc_id, {}); const value = detail[_id]; if (value) dd[uc_id] = value; } const dt = Object.values(dd).reduce((p, n) => this.ctx.plus(p, n), 0); // 活动部分 const at = ad.reduce((p, n) => this.ctx.plus(p, n.discount), 0); const grp = this.ctx.minus(this.ctx.minus(gt, dt), at); const obj = { sm, f, bn, st, ft, gt, dd, dt, grp, ad, at }; shopResult[_id] = obj; } } else { const { freight, sell_money, buy_num, set_id } = s; const sm = sell_money, f = freight, bn = buy_num, st = this.ctx.multiply(sm, bn), ft = this.ctx.multiply(f, bn), gt = this.ctx.plus(ft, st), grp = gt; shopResult[set_id] = { sm, f, bn, st, ft, gt, grp }; } } result[shop_id] = shopResult; } return result; } // #region 创建订单数据组织部分 /** * 组织商品数据 * @param {Array} goods 商品列表 * @property {Array} actList 活动列表 * @property {Array} goodsSpec 后面优惠券使用有关计算的数据 * @property {Array} goodsData 组织新的商品数据 */ async makeOrderGoodsData(goods) { // 商店不做快照,但是商品和商品对应的规格做快照 const actList = [], goodsSpecs = [], goodsData = []; for (const i of goods) { const { goods: goodsList, is_set = '1', set_id, ...others } = i; const qp = []; if (is_set === '1') { for (const g of goodsList) { const { goodsSpec_id, goods_id } = g; // 需要的订单数据 const orderNeedData = _.pick(g, [ 'act', 'price', 'sp_price', 'num', 'cart_id', 'gift' ]); if (orderNeedData.num) { orderNeedData.buy_num = orderNeedData.num; delete orderNeedData.num; } let goodsSpec = await this.goodsSpecModel.findById(goodsSpec_id); if (!goodsSpec) continue; goodsSpec = JSON.parse(JSON.stringify(goodsSpec)); const goods = await this.goodsModel.findById(goods_id); if (goods) goodsSpec.goods = JSON.parse(JSON.stringify(goods)); goodsSpec = { ...goodsSpec, ...orderNeedData }; qp.push(goodsSpec); const ogs = _.pick(goodsSpec, [ '_id', 'buy_num', 'sell_money', 'price' ]); if (ogs._id) { ogs.id = ogs._id; delete ogs._id; } goodsSpecs.push({ ...ogs }); // 将活动提取出来:只需要满减/折;买赠和特价跟着规格走,计算过程中已经处理;加价购是外面处理 const { act = [] } = goodsSpec; let gAct = act.filter(f => f.platform_act_type === '5' || f.platform_act_type === '6'); gAct = gAct.map(i => ({ ...i, goodsSpec_id: goodsSpec._id })); actList.push(...gAct); } goodsData.push({ ...others, goods: qp }); } else { const data = await this.goodsSetService.getSnapshot(set_id); data.cart_id = i.cart_id; data.buy_num = i.num; data.is_set = '0'; data.set_id = i.set_id; data.remarks = i.remarks; goodsData.push(data); } } return { actList, goodsSpecs, goodsData }; } /** * 将加购商品组织进商品数据中 * @param {Array} goodsData 上面组织过的数据 * @param {Array} plus_goods 加购商品 */ async addPlusGoods(goodsData, plus_goods) { for (const i of plus_goods) { const { shop, shop_name, goods: goods_id, spec: spec_id, _id, config, platform_act, platform_act_type } = i; // 1,验证活动中是否有数据 let num = await this.platformActModel.count({ _id: platform_act }); // 没找到活动:下一个 if (num <= 0) continue; num = await this.gjaModel.count({ _id }); // 没有商品数据:下一个 if (num <= 0) continue; // 2.做商品,规格的快照 let goodsSpec = await this.goodsSpecModel.findById(spec_id); if (!goodsSpec) continue; goodsSpec = JSON.parse(JSON.stringify(goodsSpec)); const goods = await this.goodsModel.findById(goods_id); if (goods) goodsSpec.goods = JSON.parse(JSON.stringify(goods)); // 3.向上面一样组织数据 const price = _.get(config, 'plus_money', _.get(goodsSpec, 'sell_money')); const act = [{ platform_act, platform_act_type, goods: goods_id, spec: spec_id }]; goodsSpec.price = price; goodsSpec.act = act; // 商品数量固定为1 goodsSpec.buy_num = 1; // 4.合并进goodsData const r = goodsData.find(f => f.shop === shop); if (r) r.goods.push(goodsSpec); else { goodsData.push({ shop, shop_name, goods: [ goodsSpec ] }); } } return goodsData; } // #endregion // #region 活动部分 /** * 检查商品是否满足加价购 * @param {Array} goodsList 平铺的商品列表 * @param {Array} actList 活动 */ async dealAct_plus(goodsList, actList) { for (const act of actList) { const { platform_act, plus_money } = act; const goodsInAct = await this.getGoodsInAct(goodsList, platform_act); // 没有有关活动的商品,直接下个活动 if (goodsInAct.length <= 0) continue; const total = goodsInAct.reduce((p, n) => { const rp = this.getGoodsPayAfterAct(n); return this.ctx.plus(p, rp); }, 0); // 商品,优惠过后的金额,大于等于 活动下限:活动可以进行 if (this.ctx.minus(total, plus_money) >= 0) act.activity = true; } } /** * 设置商品特价部分 * @param {Array} goodsList 平铺的商品列表 * @param {Array} actList 活动 */ dealAct_sp(goodsList, actList) { for (const act of actList) { const { spec, sp_price, platform_act_type, platform_act } = act; if (!spec) continue; const goods = goodsList.find(f => f.goodsSpec_id === spec); if (goods) { // 默认特价为商品金额 goods.sp_price = sp_price; // 有团长价格,且团长价格比特价低,就用团长价格 if (goods.leader_price && this.ctx.minus(goods.leader_price, goods.sp_price) < 0) goods.price = goods.leader_price; else goods.price = sp_price; const { act = [] } = goods; act.push({ platform_act_type, platform_act, sp_price }); goods.act = act; } } } /** * 商品满减/折处理:主要区分在于 将折扣转换为金额,剩下都是按比例分配 * @param {Array} goodsList 平铺的商品列表 * @param {Array} actList 活动 */ async dealAct_discount(goodsList, actList) { for (const act of actList) { const { discount = [], platform_act, platform_act_type } = act; // 整理出区间 const range = this.getDiscountRange(discount); // 找到在当前活动的商品 const goodsInAct = await this.getGoodsInAct(goodsList, platform_act); if (goodsInAct.length <= 0) continue; // 计算总价格够不够线(因为活动有优先级问题,如果发生满减够, 而满减之后的价格就不足以满折, 那就不给满折,所以要重新计算) const total = goodsInAct.reduce((p, n) => { const rp = this.getGoodsPayAfterAct(n); return this.ctx.plus(p, rp); }, 0); for (const r of range) { const { ls, le, number, max } = r; let res = false; if (ls && le) res = _.inRange(total, ls, le); else if (ls && !le) res = this.ctx.minus(total, ls) >= 0; if (res) { // 在区间中,处理钱的问题. // 按比例分配金额; 分配完后,结果统一放回原数据中 const actResult = []; let discountTotal = number; if (platform_act_type === '6') { // 满折:因为输入的是折扣,所以需要将折扣转换成具体金额,然后与优惠上限对比,决定最后优惠总金额 const dp = this.ctx.minus(1, this.ctx.divide(number, 10)); // 计算优惠的金额 discountTotal = this.ctx.multiply(dp, total); // 如果超出上限,则使用上限值作为优惠金额 if (_.isNumber(max)) { if (this.ctx.minus(discountTotal, max) > 0) discountTotal = max; } } for (const gia of goodsInAct) { const { goodsSpec_id } = gia; // 不是最后一个 if (!_.isEqual(gia, _.last(goodsInAct))) { const rp = this.getGoodsPayAfterAct(gia); const percent = this.ctx.divide(rp, total); const money = this.ctx.multiply(percent, discountTotal); actResult.push({ platform_act, platform_act_type, discount: money, goodsSpec_id }); } else { const allready = actResult.reduce((p, n) => this.ctx.plus(p, n.money), 0); const el = this.ctx.minus(discountTotal, allready); actResult.push({ platform_act, platform_act_type, discount: el, goodsSpec_id }); } } // 修改数据 for (const i of actResult) { const { goodsSpec_id, ...others } = i; const r = goodsList.find(f => f.goodsSpec_id === goodsSpec_id); if (r) { const { act = [] } = r; act.push(others); r.act = act; } } // 修改活动数据,做明细 const text = `满${platform_act_type === '6' ? '折' : '减'}活动`; const actData = await this.platformActModel.findById(platform_act); act.title = _.get(actData, 'act_time.title', text); act.discount = actResult.reduce((p, n) => this.ctx.minus(p, n.discount), 0); break; } } } } /** * 商品买赠处理 * @param {Array} goodsList 平铺的商品列表 * @param {Array} actList 活动 */ async dealAct_gift(goodsList, actList) { for (const act of actList) { const { spec, gift, platform_act, platform_act_type } = act; const goodsInAct = await this.getGoodsInAct(goodsList, platform_act); const actResult = []; for (const goods of goodsInAct) { const { goodsSpec_id } = goods; if (spec === goodsSpec_id) { actResult.push({ platform_act, platform_act_type, gift, goodsSpec_id }); } } for (const i of actResult) { const { goodsSpec_id, ...others } = i; const r = goodsList.find(f => f.goodsSpec_id === goodsSpec_id); if (r) { const { act = [] } = r; act.push(others); r.act = act; r.gift = _.get(i, 'gift'); } } } } /** * 查看商品是否在活动中 * @param {Array} goodsList 平铺商品列表 * @param {String} platform_act 活动id */ async getGoodsInAct(goodsList, platform_act) { const num = await this.platformActModel.count({ _id: platform_act, is_use: '0' }); if (num <= 0) return []; // 查询商品是否参与活动 const goodsInAct = []; for (const goods of goodsList) { const { goodsSpec_id } = goods; const gnum = await this.gjaModel.count({ 'spec._id': goodsSpec_id, platform_act }); if (gnum <= 0) continue; goodsInAct.push(goods); } return goodsInAct; } /** * 获取商品经活动后实付的价格 * @param {Object} goods 平铺的商品数据 */ getGoodsPayAfterAct(goods) { const { act = [], price, num } = goods; const actDiscount = act.reduce((p, n) => this.ctx.plus(p, n.discount), 0); const sp = this.ctx.multiply(price, num); const rp = this.ctx.minus(sp, actDiscount); return rp; } /** * 获取满减/折区间范围 * @param {Array} discount 满减/折阶梯设置 */ getDiscountRange(discount) { const range = []; for (let i = 0; i < discount.length; i++) { const e1 = _.get(discount, i); const e2 = _.get(discount, i + 1); if (e1 && e2) { const { limit: ls, number, max } = e1; const { limit: le } = e2; const obj = { ls: this.ctx.toNumber(ls), le: this.ctx.toNumber(le), number: this.ctx.toNumber(number) }; if (max) obj.max = max; range.push(obj); } else if (e1 && !e2) { const { limit: ls, number, max } = e1; const obj = { ls: this.ctx.toNumber(ls), number: this.ctx.toNumber(number) }; if (max) obj.max = max; range.push(obj); } } return range; } // #endregion } module.exports = OrderService;