File size: 4,285 Bytes
675f6bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
import { ActiveRole } from '@common/enums/active-role.enum';
import { SubscriptionTier } from '@common/enums/subscription-tier';
import { SubscriptionPrice } from '@common/enums/subscription-price.enum';
import { TransactionType } from '@common/enums/transaction-type.enum';
import {
  ConflictException,
  Injectable,
  NotFoundException,
  UnauthorizedException,
} from '@nestjs/common';
import { PrismaService } from 'prisma/prisma.service';
import { ActivateSubscriptionDto } from 'src/subscriptions/dto/activate-subscription.dto';
import { addMonths } from 'date-fns';
import { AuthService } from 'src/auth/auth.service';
import { UnprocessableEntityException } from '@nestjs/common';
import { EventEmitter2 } from '@nestjs/event-emitter';

@Injectable()
export class SubscriptionService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly authService: AuthService,
    private readonly eventEmitter: EventEmitter2,
  ) {}

  async activateSubscription(userId: string, activateSubscriptionDto: ActivateSubscriptionDto) {
    const user = await this.prisma.user.findUnique({
      where: { id: userId },
    });

    if (!user) {
      throw new UnauthorizedException('User not found!');
    }

    const userCurrentActiveRole = activateSubscriptionDto.activeRole;

    if (user.activeRole !== userCurrentActiveRole) {
      throw new ConflictException(
        'You must switch to the target role before activating subscription!',
      );
    }

    const tierKey =
      userCurrentActiveRole === ActiveRole.CLIENT
        ? 'subscriptionClientTier'
        : 'subscriptionExpertTier';

    const expiresKey =
      userCurrentActiveRole === ActiveRole.CLIENT ? 'subClientExpiresAt' : 'subExpertExpiresAt';

    const price =
      userCurrentActiveRole === ActiveRole.CLIENT
        ? SubscriptionPrice.CLIENT_PRO_PRICE
        : SubscriptionPrice.EXPERT_PRO_PRICE;

    const roleTypeLabel = userCurrentActiveRole === ActiveRole.CLIENT ? 'client' : 'expert';

    const currentTime = new Date();
    const isCurrentlyActive =
      user[tierKey] === SubscriptionTier.PRO &&
      user[expiresKey] !== null &&
      user[expiresKey] > currentTime;

    if (isCurrentlyActive) {
      throw new ConflictException('Your subscription is still available');
    }

    const updatedUser = await this.prisma.$transaction(async (tx) => {
      const userWallet = await tx.wallet.findUnique({
        where: { userId: user.id },
      });
      
      if (userWallet.availableBalance < price) {
        throw new UnprocessableEntityException('INSUFFICIENT_BALANCE');
      }

      await tx.wallet.update({
        where: { userId: user.id },
        data: {
          availableBalance: { decrement: BigInt(price) },
        },
      });

      await tx.walletTransaction.create({
        data: {
          walletId: userWallet.id,
          amount: BigInt(price),
          transactionType: TransactionType.SUBSCRIPTION,
          referenceId: `SUB-${userId}:${roleTypeLabel}:${Date.now()}`,
        },
      });

      return tx.user.update({
        where: { id: user.id },
        data: {
          [tierKey]: SubscriptionTier.PRO,
          [expiresKey]: addMonths(new Date(), 6),
        },
      });
    });
    this.eventEmitter.emit('socket.broadcast', {
      userId: user.id,
      event: 'notification:generic',
      payload: {
        type: 'system',
        title: 'Pro Activated',
        body: `Welcome to ${roleTypeLabel === 'client' ? 'Client Pro' : 'Expert Pro'}!`,
      }
    });
    const access_token = await this.authService.jwtGeneratePayload(updatedUser);

    return { access_token };
  }

  async getSubscriptionStatus(userId: string) {
    const user = await this.prisma.user.findUnique({
      where: { id: userId },
    });

    if (!user) {
      throw new NotFoundException('User not found!');
    }

    const tierKey =
      user.activeRole === ActiveRole.CLIENT
        ? ('subscriptionClientTier' as const)
        : ('subscriptionExpertTier' as const);

    const expiresKey =
      user.activeRole === ActiveRole.CLIENT
        ? ('subClientExpiresAt' as const)
        : ('subExpertExpiresAt' as const);

    return {
      subscriptionTier: user[tierKey],
      subscriptionExpires: user[expiresKey],
    };
  }
}