12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- '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 TradeService extends CrudService {
- constructor(ctx) {
- super(ctx, 'trade');
- this.redis = this.app.redis;
- this.shopModel = this.ctx.model.Shop.Shop;
- this.goodsModel = this.ctx.model.Shop.Goods;
- this.goodsSpecModel = this.ctx.model.Shop.GoodsSpec;
- this.orderKeyPrefix = 'orderKey:';
- }
- /**
- * 检测是否可以购买该物品
- * @param {Object} param 查询条件
- * @param param.shop 商店id
- * @param param.goods 商品id
- * @param param.goodsSpec 商品规格id
- * @param param.num 购买数量
- */
- async checkCanBuy({ shop, goods, goodsSpec, num }) {
- assert(shop, '缺少店铺信息');
- assert(goods, '缺少商品信息');
- assert(goodsSpec, '缺少商品规格信息');
- assert(num, '缺少购买数量');
- const result = { result: true };
- // 1.检查商店是否正常运行
- const shopData = await this.shopModel.findById(shop);
- if (!shopData) {
- result.msg = '未找到店铺';
- result.result = false;
- return result;
- }
- if (shopData.status !== '1') {
- result.msg = '店铺不处于营业状态';
- result.result = false;
- return result;
- }
- // 2.检查商品是否可以购买
- const goodsData = await this.goodsModel.findById(goods);
- if (!goodsData) {
- result.msg = '未找到商品';
- result.result = false;
- return result;
- }
- if (goodsData.status === '0') {
- result.msg = '该商品已下架';
- result.result = false;
- return result;
- }
- // 3.检验该规格是否可以购买
- const goodsSpecData = await this.goodsSpecModel.findById(goodsSpec);
- if (!goodsSpecData) {
- result.msg = '未找到商品的指定规格';
- result.result = false;
- return result;
- }
- if (goodsSpecData.status !== '0') {
- result.msg = '该规格的商品已下架';
- result.result = false;
- return result;
- }
- if (goodsSpecData.num < num) {
- result.msg = '库存量不足';
- result.result = false;
- return result;
- }
- const key = `${this.orderKeyPrefix}${this.createNonceStr()}`;
- const value = JSON.stringify({ shop, goods, goodsSpec, num });
- await this.redis.set(key, value, 'EX', 180);
- result.key = key;
- return result;
- }
- // 随机字符串产生函数
- createNonceStr() {
- return Math.random().toString(36).substr(2, 15);
- }
- }
- module.exports = TradeService;
|