trade.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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.shopModel = this.ctx.model.Shop.Shop;
  11. this.goodsModel = this.ctx.model.Shop.Goods;
  12. this.goodsSpecModel = this.ctx.model.Shop.GoodsSpec;
  13. }
  14. /**
  15. * 检测是否可以购买该物品
  16. * @param {Object} param 查询条件
  17. * @param param.shop_id 商店id
  18. * @param param.goods_id 商品id
  19. * @param param.goodsSpec_id 商品规格id
  20. * @param param.num 购买数量
  21. */
  22. async checkCanBuy({ shop_id, goods_id, goodsSpec_id, num }) {
  23. assert(shop_id, '缺少店铺信息');
  24. assert(goods_id, '缺少商品信息');
  25. assert(goodsSpec_id, '缺少商品规格信息');
  26. assert(num, '缺少购买数量');
  27. const result = { result: true };
  28. // 1.检查商店是否正常运行
  29. const shop = await this.shopModel.findById(shop_id);
  30. if (!shop) {
  31. result.msg = '未找到店铺';
  32. result.result = false;
  33. return result;
  34. }
  35. if (shop.status !== '1') {
  36. result.msg = '店铺不处于营业状态';
  37. result.result = false;
  38. return result;
  39. }
  40. // 2.检查商品是否可以购买
  41. const goods = await this.goodsModel.findById(goods_id);
  42. if (!goods) {
  43. result.msg = '未找到商品';
  44. result.result = false;
  45. return result;
  46. }
  47. if (goods.status === '0') {
  48. result.msg = '该商品已下架';
  49. result.result = false;
  50. return result;
  51. }
  52. // 3.检验该规格是否可以购买
  53. const goodsSpec = await this.goodsSpecModel.findById(goodsSpec_id);
  54. if (!goodsSpec) {
  55. result.msg = '未找到商品的指定规格';
  56. result.result = false;
  57. return result;
  58. }
  59. if (goods.status !== '0') {
  60. result.msg = '该规格的商品已下架';
  61. result.result = false;
  62. return result;
  63. }
  64. if (goods.num < num) {
  65. result.msg = '库存量不足';
  66. result.result = false;
  67. return result;
  68. }
  69. return result;
  70. }
  71. }
  72. module.exports = TradeService;