tickets-service.service.ts281 lines, 7.4 KB
| 1 | import { PurchaseTicketDto } from '@app/common'; |
| 2 | import { DatabaseService, events, tickets } from '@app/database'; |
| 3 | import { KAFKA_SERVICE, KAFKA_TOPICS } from '@app/kafka'; |
| 4 | import { |
| 5 | BadRequestException, |
| 6 | ForbiddenException, |
| 7 | Inject, |
| 8 | Injectable, |
| 9 | NotFoundException, |
| 10 | OnModuleInit, |
| 11 | } from '@nestjs/common'; |
| 12 | import { ClientKafka } from '@nestjs/microservices'; |
| 13 | import { randomBytes } from 'crypto'; |
| 14 | import { and, eq, sql } from 'drizzle-orm'; |
| 15 | |
| 16 | @Injectable() |
| 17 | export class TicketsServiceService implements OnModuleInit { |
| 18 | constructor( |
| 19 | @Inject(KAFKA_SERVICE) private readonly kafkClient: ClientKafka, |
| 20 | private readonly dbService: DatabaseService, |
| 21 | ) {} |
| 22 | |
| 23 | async onModuleInit() { |
| 24 | // connect to kafka when module initializes |
| 25 | await this.kafkClient.connect(); |
| 26 | } |
| 27 | |
| 28 | private generateTicketCode(): string { |
| 29 | return randomBytes(6).toString('hex').toUpperCase(); |
| 30 | } |
| 31 | |
| 32 | async purchase(purchaseDto: PurchaseTicketDto, userId: string) { |
| 33 | const { eventId, quantity } = purchaseDto; |
| 34 | |
| 35 | const [event] = await this.dbService.db |
| 36 | .select() |
| 37 | .from(events) |
| 38 | .where(eq(events.id, eventId)) |
| 39 | .limit(1); |
| 40 | |
| 41 | if (!event) { |
| 42 | throw new NotFoundException('Event not found'); |
| 43 | } |
| 44 | |
| 45 | if (event.status !== 'PUBLISHED') { |
| 46 | throw new BadRequestException('Event is not published'); |
| 47 | } |
| 48 | |
| 49 | const soldTickets = await this.dbService.db |
| 50 | .select({ total: sql<number>`COALESCE(SUM(${tickets.quantity}), 0)` }) |
| 51 | .from(tickets) |
| 52 | .where( |
| 53 | and(eq(tickets.eventId, eventId), eq(tickets.status, 'CONFIRMED')), |
| 54 | ); |
| 55 | |
| 56 | const currentSold = Number(soldTickets[0]?.total || 0); |
| 57 | const remaining = event.capacity - currentSold; |
| 58 | |
| 59 | if (quantity > remaining) { |
| 60 | throw new BadRequestException(`Only ${remaining} tickets remaining`); |
| 61 | } |
| 62 | |
| 63 | const totalPrice = event.price * quantity; |
| 64 | |
| 65 | const [ticket] = await this.dbService.db |
| 66 | .insert(tickets) |
| 67 | .values({ |
| 68 | eventId, |
| 69 | userId, |
| 70 | quantity, |
| 71 | totalPrice, |
| 72 | ticketCode: this.generateTicketCode(), |
| 73 | status: 'CONFIRMED', |
| 74 | }) |
| 75 | .returning(); |
| 76 | |
| 77 | this.kafkClient.emit(KAFKA_TOPICS.TICKET_PURCHASED, { |
| 78 | ticketId: ticket.id, |
| 79 | eventId: ticket.eventId, |
| 80 | userId: ticket.userId, |
| 81 | quantity: ticket.quantity, |
| 82 | totalPrice: ticket.totalPrice, |
| 83 | ticketCode: ticket.ticketCode, |
| 84 | timestamp: new Date().toISOString(), |
| 85 | }); |
| 86 | |
| 87 | return { |
| 88 | message: 'Ticket purchased successfully', |
| 89 | ticket: { |
| 90 | id: ticket.id, |
| 91 | ticketCode: ticket.ticketCode, |
| 92 | eventTitle: event.title, |
| 93 | quantity: ticket.quantity, |
| 94 | totalPrice: ticket.totalPrice, |
| 95 | status: ticket.status, |
| 96 | purchasedAt: ticket.purchasedAt, |
| 97 | }, |
| 98 | }; |
| 99 | } |
| 100 | |
| 101 | async findMyTicket(userId: string) { |
| 102 | const userTickets = await this.dbService.db |
| 103 | .select({ |
| 104 | id: tickets.id, |
| 105 | ticketCode: tickets.ticketCode, |
| 106 | quantity: tickets.quantity, |
| 107 | totalPrice: tickets.totalPrice, |
| 108 | status: tickets.status, |
| 109 | purchasedAt: tickets.purchasedAt, |
| 110 | checkedInAt: tickets.checkedInAt, |
| 111 | eventId: events.id, |
| 112 | eventTitle: events.title, |
| 113 | eventDate: events.date, |
| 114 | eventLocation: events.location, |
| 115 | }) |
| 116 | .from(tickets) |
| 117 | .innerJoin(events, eq(tickets.eventId, events.id)) |
| 118 | .where(eq(tickets.userId, userId)); |
| 119 | |
| 120 | return userTickets; |
| 121 | } |
| 122 | |
| 123 | async findOne(id: string, userId: string) { |
| 124 | const [ticket] = await this.dbService.db |
| 125 | .select({ |
| 126 | id: tickets.id, |
| 127 | ticketCode: tickets.ticketCode, |
| 128 | quantity: tickets.quantity, |
| 129 | totalPrice: tickets.totalPrice, |
| 130 | status: tickets.status, |
| 131 | purchasedAt: tickets.purchasedAt, |
| 132 | checkedInAt: tickets.checkedInAt, |
| 133 | userId: tickets.userId, |
| 134 | eventId: events.id, |
| 135 | eventTitle: events.title, |
| 136 | eventDate: events.date, |
| 137 | eventLocation: events.location, |
| 138 | }) |
| 139 | .from(tickets) |
| 140 | .innerJoin(events, eq(tickets.eventId, events.id)) |
| 141 | .where(and(eq(tickets.id, id), eq(tickets.userId, userId))) |
| 142 | .limit(1); |
| 143 | |
| 144 | if (!ticket) { |
| 145 | throw new NotFoundException('Ticket not found'); |
| 146 | } |
| 147 | |
| 148 | if (ticket.userId !== userId) { |
| 149 | throw new ForbiddenException('Ticket does not belong to user'); |
| 150 | } |
| 151 | |
| 152 | return ticket; |
| 153 | } |
| 154 | |
| 155 | async cancel(id: string, userId: string) { |
| 156 | const [ticket] = await this.dbService.db |
| 157 | .select() |
| 158 | .from(tickets) |
| 159 | .where(eq(tickets.id, id)) |
| 160 | .limit(1); |
| 161 | |
| 162 | if (!ticket) { |
| 163 | throw new NotFoundException('Ticket not found'); |
| 164 | } |
| 165 | |
| 166 | if (ticket.userId !== userId) { |
| 167 | throw new ForbiddenException('Ticket does not belong to user'); |
| 168 | } |
| 169 | |
| 170 | if (ticket.status === 'CANCELLED') { |
| 171 | throw new BadRequestException('Ticket is already cancelled'); |
| 172 | } |
| 173 | |
| 174 | if (ticket.status === 'CHECKED_IN') { |
| 175 | throw new BadRequestException('Ticket is already checked in'); |
| 176 | } |
| 177 | |
| 178 | const [cancelled] = await this.dbService.db |
| 179 | .update(tickets) |
| 180 | .set({ status: 'CANCELLED', updatedAt: new Date() }) |
| 181 | .where(eq(tickets.id, id)) |
| 182 | .returning(); |
| 183 | |
| 184 | this.kafkClient.emit(KAFKA_TOPICS.TICKET_CANCELLED, { |
| 185 | ticketId: cancelled.id, |
| 186 | eventId: cancelled.eventId, |
| 187 | userId: cancelled.userId, |
| 188 | timestamp: new Date().toISOString(), |
| 189 | }); |
| 190 | |
| 191 | return { message: 'Ticket cancelled successfully' }; |
| 192 | } |
| 193 | |
| 194 | async checkIn(ticketCode: string, organizerId: string) { |
| 195 | const [ticket] = await this.dbService.db |
| 196 | .select({ |
| 197 | id: tickets.id, |
| 198 | status: tickets.status, |
| 199 | eventId: events.id, |
| 200 | quantity: tickets.quantity, |
| 201 | }) |
| 202 | .from(tickets) |
| 203 | .where(eq(tickets.ticketCode, ticketCode)) |
| 204 | .limit(1); |
| 205 | |
| 206 | if (!ticket) { |
| 207 | throw new NotFoundException('Ticket not found'); |
| 208 | } |
| 209 | |
| 210 | const [event] = await this.dbService.db |
| 211 | .select() |
| 212 | .from(events) |
| 213 | .where(eq(events.id, ticket.eventId)) |
| 214 | .limit(1); |
| 215 | |
| 216 | if (event.organizerId !== organizerId) { |
| 217 | throw new ForbiddenException( |
| 218 | 'You are not authorized to check in this ticket', |
| 219 | ); |
| 220 | } |
| 221 | |
| 222 | if (ticket.status === 'CHECKED_IN') { |
| 223 | throw new BadRequestException('Ticket is already checked in'); |
| 224 | } |
| 225 | |
| 226 | if (ticket.status === 'CANCELLED') { |
| 227 | throw new BadRequestException('Ticket is already cancelled'); |
| 228 | } |
| 229 | |
| 230 | const [checkedIn] = await this.dbService.db |
| 231 | .update(tickets) |
| 232 | .set({ |
| 233 | status: 'CHECKED_IN', |
| 234 | checkedInAt: new Date(), |
| 235 | updatedAt: new Date(), |
| 236 | }) |
| 237 | .where(eq(tickets.id, ticket.id)) |
| 238 | .returning(); |
| 239 | |
| 240 | this.kafkClient.emit(KAFKA_TOPICS.TICKET_CHECKED_IN, { |
| 241 | ticketId: checkedIn.id, |
| 242 | eventId: checkedIn.eventId, |
| 243 | ticketCode: checkedIn.ticketCode, |
| 244 | timestamp: new Date().toISOString(), |
| 245 | }); |
| 246 | |
| 247 | return { |
| 248 | message: 'Ticket checked in successfully', |
| 249 | ticket: { |
| 250 | id: checkedIn.id, |
| 251 | ticketCode: checkedIn.ticketCode, |
| 252 | quantity: checkedIn.quantity, |
| 253 | status: checkedIn.status, |
| 254 | checkedInAt: checkedIn.checkedInAt, |
| 255 | }, |
| 256 | }; |
| 257 | } |
| 258 | |
| 259 | async findEventTickst(eventId: string, organizerId: string) { |
| 260 | const [event] = await this.dbService.db |
| 261 | .select() |
| 262 | .from(events) |
| 263 | .where(eq(events.id, eventId)) |
| 264 | .limit(1); |
| 265 | |
| 266 | if (!event) { |
| 267 | throw new NotFoundException('Event not found'); |
| 268 | } |
| 269 | |
| 270 | if (event.organizerId !== organizerId) { |
| 271 | throw new ForbiddenException( |
| 272 | 'You are not authorized to check in this ticket', |
| 273 | ); |
| 274 | } |
| 275 | |
| 276 | return this.dbService.db |
| 277 | .select() |
| 278 | .from(tickets) |
| 279 | .where(eq(tickets.eventId, eventId)); |
| 280 | } |
| 281 | } |