wangzhibo
6 天以前 7dcc2997614f849258091f5d66e648317a40d323
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import { Init, Provide } from '@midwayjs/core';
import { BaseService, CoolCommException } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Equal, Repository } from 'typeorm';
import { MarketCouponUserEntity } from '../../entity/coupon/user';
 
/**
 * 优惠券用户
 */
@Provide()
export class MarketCouponUserService extends BaseService {
  @InjectEntityModel(MarketCouponUserEntity)
  marketCouponUserEntity: Repository<MarketCouponUserEntity>;
 
  @Init()
  async init() {
    await super.init();
    this.setEntity(this.marketCouponUserEntity);
  }
 
  /**
   * 保存
   * @param idcouponId
   * @param userId
   */
  async save(couponId: number, userId: number) {
    const couponUser = new MarketCouponUserEntity();
    couponUser.userId = userId;
    couponUser.couponId = couponId;
    await this.marketCouponUserEntity.save(couponUser);
  }
 
  /**
   * 检查优惠券是否可用
   * @param couponId
   * @param userId
   */
  async check(couponId: number, userId: number) {
    const info = await this.marketCouponUserEntity.findOneBy({
      couponId: Equal(couponId),
      userId: Equal(userId),
      status: 0,
    });
    if (!info) {
      throw new CoolCommException('优惠券未领取或已使用');
    }
    return info;
  }
 
  /**
   * 检查优惠券是否存在
   * @param couponId
   * @param userId
   */
  async checkExist(couponId: number, userId: number) {
    const info = await this.marketCouponUserEntity.findOneBy({
      couponId: Equal(couponId),
      userId: Equal(userId),
    });
    return !!info;
  }
 
  /**
   * 使用优惠券
   * @param couponId
   * @param userId
   */
  async use(couponId: number, userId: number) {
    await this.marketCouponUserEntity.update(
      { couponId: Equal(couponId), userId: Equal(userId) },
      { status: 1, useTime: new Date() }
    );
  }
}