trade.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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 TradeService extends CrudService {
  8. constructor(ctx) {
  9. super(ctx, 'trade');
  10. this.goodsModel = this.ctx.model.Shop.Goods;
  11. this.goodsSpecModel = this.ctx.model.Shop.GoodsSpec;
  12. }
  13. /**
  14. * 检测是否可以购买该物品
  15. * @param {Object} param 查询条件
  16. * @param param.goods_id 商品id
  17. * @param param.goodsSpec_id 商品规格id
  18. * @param param.num 购买数量
  19. */
  20. async checkCanBuy({ goods_id, goodsSpec_id, num }) {
  21. const result = { result: true };
  22. // 1.检查商品是否可以购买
  23. const goods = await this.goodsModel.findById(goods_id);
  24. if (!goods) {
  25. result.msg = '未找到商品';
  26. result.result = false;
  27. return result;
  28. }
  29. if (goods.status === '0') {
  30. result.msg = '该商品已下架';
  31. result.result = false;
  32. return result;
  33. }
  34. // 2.检验该规格是否可以购买
  35. const goodsSpec = await this.goodsSpecModel.findById(goodsSpec_id);
  36. if (!goodsSpec) {
  37. result.msg = '未找到商品的指定规格';
  38. result.result = false;
  39. return result;
  40. }
  41. if (goods.status !== '0') {
  42. result.msg = '该规格的商品已下架';
  43. result.result = false;
  44. return result;
  45. }
  46. if (goods.num < num) {
  47. result.msg = '库存量不足';
  48. result.result = false;
  49. return result;
  50. }
  51. return result;
  52. }
  53. }
  54. module.exports = TradeService;