lrf 2 년 전
부모
커밋
63f229692f
3개의 변경된 파일125개의 추가작업 그리고 51개의 파일을 삭제
  1. 73 21
      app/service/trade/order.js
  2. 2 1
      app/service/util/order.js
  3. 50 29
      app/service/util/trade.js

+ 73 - 21
app/service/trade/order.js

@@ -190,6 +190,7 @@ class OrderService extends CrudService {
    * 进入下单页面
    * @param {Object} body 请求参数
    * @param body.key 缓存key
+   * @property {Array} data key中的数据,可能是 [string],[object]; [string]:数据是购物车id; [object] :是直接购买的数据
    */
   async toMakeOrder({ key }) {
     key = `${this.redisKey.orderKeyPrefix}${key}`;
@@ -197,22 +198,16 @@ class OrderService extends CrudService {
     if (!data) throw new BusinessError(ErrorCode.SERVICE_FAULT, '请求超时,请重新进入下单页');
     data = JSON.parse(data);
     let specsData = [];
-    if (_.isArray(data)) {
-      // 购物车来的: 1.循环校验 规格商品; 2.按店铺分组
-      const { populate } = this.ctx.service.trade.cart.getRefMods();
-      const carts = await this.cartModel.find({ _id: data }).populate(populate);
-      for (const cart of carts) {
-        const { result, msg } = await this.ctx.service.util.trade.checkCanBuy(cart, false);
-        if (!result) throw new BusinessError(ErrorCode.DATA_INVALID, msg);
-      }
-      specsData = this.setCartsGoodsToPageData(carts);
-    } else if (_.isObject(data)) {
-      // 商品页单独买: 1.校验规格商品; 2:按店铺分组
+    // 根据缓存,整理商品数据
+    if (!_.isArray(data)) throw new BusinessError(ErrorCode.DATA_INVALID, '数据不正确,请重新下单');
+    const head = _.head(data);
+    if (_.isString(head)) {
+      // 购物车来的
+    } else if (_.isObject(head)) {
+      // 直接购买来的
       const { result, msg } = await this.ctx.service.util.trade.checkCanBuy(data, false);
       if (!result) throw new BusinessError(ErrorCode.DATA_INVALID, msg);
-      const { populate } = this.ctx.service.shop.goodsSpec.getRefMods();
-      const list = await this.goodsSpecModel.find({ _id: data.goodsSpec }).populate(populate);
-      specsData = this.setGoodsToPageData(list, data.num);
+      specsData = await this.getPageData(data);
     } else throw new BusinessError(ErrorCode.DATA_INVALID, '数据不正确,请重新下单');
     // 组装页面的数据
     const user = this.ctx.user;
@@ -222,13 +217,8 @@ class OrderService extends CrudService {
     // 找到默认地址
     const address = await this.addressModel.findOne({ customer, is_default: '1' });
     pageData.address = address;
-    // #region 团购部分
-    const { type, group } = data;
-    pageData.type = type; // 新添字段,订单类型
-    pageData.group = group; // 新添字段,团购的团id
-    // #endregion
     // 商品总价,各店铺的价格明细
-    specsData = this.ctx.service.util.order.makeOrder_computedShopTotal(specsData, type);
+    specsData = this.ctx.service.util.order.makeOrder_computedShopTotal(specsData);
     const shopTotalDetail = this.ctx.service.util.order.makerOrder_computedOrderTotal(specsData);
     pageData.goodsData = specsData;
     pageData.orderTotal = shopTotalDetail;
@@ -241,6 +231,69 @@ class OrderService extends CrudService {
     return pageData;
   }
 
+  // 直接购买&购物车,这俩字段基本没差, 组织订单页商品数据
+  async getPageData(data) {
+    let arr = [];
+    for (const i of data) {
+      const { goodsSpec, num } = i;
+      const d = await this.goodsSpecModel.aggregate([
+        { $match: { _id: ObjectId(goodsSpec) } },
+        { $addFields: { goods_id: { $toObjectId: '$goods' } } },
+        {
+          $lookup: {
+            from: 'goods',
+            localField: 'goods_id',
+            foreignField: '_id',
+            pipeline: [
+              { $addFields: { shop_id: { $toObjectId: '$shop' } } },
+              {
+                $lookup: {
+                  from: 'shop',
+                  localField: 'shop_id',
+                  foreignField: '_id',
+                  pipeline: [{ $project: { name: 1 } }],
+                  as: 'shop',
+                },
+              },
+              { $project: { name: 1, file: 1, tag: 1, act_tag: 1, shop: { $first: '$shop' } } },
+            ],
+            as: 'goods',
+          },
+        },
+        { $unwind: '$goods' },
+        {
+          $project: {
+            _id: 0,
+            shop: '$goods.shop._id',
+            shop_name: '$goods.shop.name',
+            goods_id: '$goods._id',
+            goods_name: '$goods.name',
+            goodsSpec_id: '$_id',
+            goodsSpec_name: '$name',
+            freight: { $toString: '$freight' },
+            sell_money: { $toString: '$sell_money' },
+            num: { $toDouble: num },
+            file: '$goods.file',
+            tags: '$goods.tags',
+            act_tags: '$goods.act_tags',
+          },
+        },
+      ]);
+      arr.push(...d);
+    }
+    arr = Object.values(_.groupBy(arr, 'shop'));
+    const result = [];
+    // 按店铺分组
+    for (const i of arr) {
+      const head = _.head(i);
+      const obj = { shop: _.get(head, 'shop'), shop_name: _.get(head, 'shop_name') };
+      const goods = i.map(e => _.omit(e, [ 'shop', 'shop_name' ]));
+      obj.goods = goods;
+      result.push(obj);
+    }
+    return result;
+  }
+
   /**
    * 单商品整理数据,剩下的可以简略
    * @param {Array} list 规格数组
@@ -328,7 +381,6 @@ class OrderService extends CrudService {
     return data;
   }
 
-
   async toMakeTask(order_id) {
     const { taskMqConfig } = this.app.config;
     const data = { service: 'trade.order', method: 'cancel', params: { order_id } };

+ 2 - 1
app/service/util/order.js

@@ -21,8 +21,9 @@ class OrderService extends CrudService {
   makeOrder_computedShopTotal(list, type = '0') {
     let sell_money_key;
     if (type === '1') sell_money_key = 'group_sell_money';
-    else sell_money_key = 'money';
+    else sell_money_key = 'sell_money';
     for (const i of list) {
+      i.goods = i.goods.map(e => ({ ...e, price: _.get(e, sell_money_key) }));
       i.goods_total = i.goods.reduce((p, n) => this.ctx.plus(p, this.ctx.multiply(_.get(n, sell_money_key), n.num)), 0);
       i.freight_total = i.goods.reduce((p, n) => this.ctx.plus(p, this.ctx.multiply(n.freight, n.num)), 0);
     }

+ 50 - 29
app/service/util/trade.js

@@ -43,7 +43,7 @@ class TradeService extends CrudService {
 
   /**
    * 检测是否可以购买该物品
-   * @param {Object} param 查询条件
+   * @param {Object} data 查询条件
    * @param param.shop 商店id
    * @param param.goods 商品id
    * @param param.goodsSpec 商品规格id
@@ -53,36 +53,57 @@ class TradeService extends CrudService {
    * @param param.inviter 邀请用户id 返现部分
    * @param makeCache 生成缓存
    */
-  async checkCanBuy({ shop, goods, goodsSpec, num, type = '0', group, inviter }, makeCache = true) {
-    console.log(inviter);
-    assert(shop, '缺少店铺信息');
-    assert(goods, '缺少商品信息');
-    assert(goodsSpec, '缺少商品规格信息');
-    assert(num, '缺少购买数量');
-    const result = { result: true };
-    // 1.检查商店是否正常运行
-    const shopData = await this.shopModel.findById(shop);
-    const shopRes = this.checkShop(shopData);
-    if (shopRes.result !== true) return shopRes;
-    // 2.检查商品是否可以购买
-    const goodsData = await this.goodsModel.findById(goods);
-    const goodsRes = this.checkGoods(goodsData);
-    if (shopRes.result !== true) return goodsRes;
-    // 3.检验该规格是否可以购买
-    const goodsSpecData = await this.goodsSpecModel.findById(goodsSpec);
-    const gsRes = this.checkGoodsSpec(goodsSpecData, num);
-    if (gsRes.result !== true) return gsRes;
-    // #region 团购部分
-    // 4.检查是否是团购单
-    if (type === '1' && group) {
-      // 为团购单,但是没有团id,团长开团.不需要检查
-      // 为团购单,且有团id: 团员参团
-      const groupRes = await this.ctx.service.group.group.checkGroupCanJoin({ id: group });
-      if (groupRes.result !== true) return groupRes;
+  async checkCanBuy(data, makeCache = true) {
+    if (!_.isArray(data)) data = [ data ];
+    let result = { result: true };
+    for (const i of data) {
+      const { shop, goods, goodsSpec, num, inviter } = i;
+      if (!shop) {
+        result.result = false;
+        result.msg = '缺少店铺信息';
+        break;
+      }
+      if (!goods) {
+        result.result = false;
+        result.msg = '缺少商品信息';
+        break;
+      }
+      if (!goodsSpec) {
+        result.result = false;
+        result.msg = '缺少商品规格信息';
+        break;
+      }
+      if (!num) {
+        result.result = false;
+        result.msg = '缺少购买数量';
+        break;
+      }
+      // 1.检查商店是否正常运行
+      const shopData = await this.shopModel.findById(shop);
+      const shopRes = this.checkShop(shopData);
+      if (shopRes.result !== true) {
+        result = shopRes;
+        break;
+      }
+      // 2.检查商品是否可以购买
+      const goodsData = await this.goodsModel.findById(goods);
+      const goodsRes = this.checkGoods(goodsData);
+      if (shopRes.result !== true) {
+        result = goodsRes;
+        break;
+      }
+      // 3.检验该规格是否可以购买
+      const goodsSpecData = await this.goodsSpecModel.findById(goodsSpec);
+      const gsRes = this.checkGoodsSpec(goodsSpecData, num);
+      if (gsRes.result !== true) {
+        result = gsRes;
+        break;
+      }
     }
+
     // #endregion
-    if (makeCache) {
-      const key = await this.makeOrderKey({ shop, goods, goodsSpec, num, type, group, inviter });
+    if (result.result && makeCache) {
+      const key = await this.makeOrderKey(data);
       result.key = key;
     }