trade.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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.redis = this.app.redis;
  11. this.redisKey = this.app.config.redisKey;
  12. this.shopModel = this.ctx.model.Shop.Shop;
  13. this.goodsModel = this.ctx.model.Shop.Goods;
  14. this.goodsSpecModel = this.ctx.model.Shop.GoodsSpec;
  15. }
  16. /**
  17. * 检测是否可以购买该物品
  18. * @param {Object} param 查询条件
  19. * @param param.shop 商店id
  20. * @param param.goods 商品id
  21. * @param param.goodsSpec 商品规格id
  22. * @param param.num 购买数量
  23. */
  24. async checkCanBuy({ shop, goods, goodsSpec, num }) {
  25. assert(shop, '缺少店铺信息');
  26. assert(goods, '缺少商品信息');
  27. assert(goodsSpec, '缺少商品规格信息');
  28. assert(num, '缺少购买数量');
  29. const result = { result: true };
  30. // 1.检查商店是否正常运行
  31. const shopData = await this.shopModel.findById(shop);
  32. if (!shopData) {
  33. result.msg = '未找到店铺';
  34. result.result = false;
  35. return result;
  36. }
  37. if (shopData.status !== '1') {
  38. result.msg = '店铺不处于营业状态';
  39. result.result = false;
  40. return result;
  41. }
  42. // 2.检查商品是否可以购买
  43. const goodsData = await this.goodsModel.findById(goods);
  44. if (!goodsData) {
  45. result.msg = '未找到商品';
  46. result.result = false;
  47. return result;
  48. }
  49. if (goodsData.status === '0') {
  50. result.msg = '该商品已下架';
  51. result.result = false;
  52. return result;
  53. }
  54. // 3.检验该规格是否可以购买
  55. const goodsSpecData = await this.goodsSpecModel.findById(goodsSpec);
  56. if (!goodsSpecData) {
  57. result.msg = '未找到商品的指定规格';
  58. result.result = false;
  59. return result;
  60. }
  61. if (goodsSpecData.status !== '0') {
  62. result.msg = '该规格的商品已下架';
  63. result.result = false;
  64. return result;
  65. }
  66. if (goodsSpecData.num < num) {
  67. result.msg = '库存量不足';
  68. result.result = false;
  69. return result;
  70. }
  71. const str = this.createNonceStr();
  72. const key = `${this.redisKey.orderKeyPrefix}${str}`;
  73. const value = JSON.stringify({ shop, goods, goodsSpec, num });
  74. await this.redis.set(key, value, 'EX', 180);
  75. result.key = str;
  76. return result;
  77. }
  78. // 随机字符串产生函数
  79. createNonceStr() {
  80. return Math.random().toString(36).substr(2, 15);
  81. }
  82. }
  83. module.exports = TradeService;