lrf 2 年之前
父節點
當前提交
d9494819de
共有 1 個文件被更改,包括 42 次插入1 次删除
  1. 42 1
      app/service/trade/cart.js

+ 42 - 1
app/service/trade/cart.js

@@ -4,11 +4,52 @@ const { BusinessError, ErrorCode } = require('naf-core').Error;
 const _ = require('lodash');
 const assert = require('assert');
 
-// 
+//
 class CartService extends CrudService {
   constructor(ctx) {
     super(ctx, 'cart');
     this.model = this.ctx.model.Trade.Cart;
+    this.goodsSpecModel = this.ctx.model.Shop.GoodsSpec;
+  }
+
+  /**
+   * 创建购物车信息,若找到该店的该商品规格.进行库存校验
+   * 数量进行合并;
+   * 反之创建
+   * @param {Object} body 请求参数
+   * @param body.num 数量
+   */
+  async create({ num, ...body }) {
+    const { customer, shop, goods, goodsSpec } = body;
+    assert(customer, '缺少顾客信息');
+    assert(shop, '缺少店铺信息');
+    assert(goods, '缺少商品信息');
+    assert(goodsSpec, '缺少商品规格信息');
+    const data = await this.model.findOne(body);
+    if (data) {
+      const buyNum = parseInt(data.num) + parseInt(num);
+      const enough = await this.checkGoodsNum(goodsSpec, buyNum);
+      if (!enough) throw new BusinessError(ErrorCode.SERVICE_FAULT, '库存不足,无法添加至购物车');
+      data.num = buyNum;
+      await data.save();
+    } else {
+      const enough = await this.checkGoodsNum(goodsSpec, num);
+      if (!enough) throw new BusinessError(ErrorCode.SERVICE_FAULT, '库存不足,无法添加至购物车');
+      await this.model.create({ num, ...body });
+    }
+  }
+
+  /**
+   * 检查商品规格的库存
+   * @param {String} goodsSpecId 商品规格id
+   * @param {Number} num 需要的库存数量
+   * @return {Boolean} true:库存满足购物车条件;false:库存不满足条件
+   */
+  async checkGoodsNum(goodsSpecId, num) {
+    const goodsSpec = await this.goodsSpecModel.findById(goodsSpecId);
+    if (!goodsSpec) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到商品的规格数据');
+    const { num: gsnum = 0 } = goodsSpec;
+    return gsnum >= num;
   }
 }