import { Injectable, ConflictException, NotFoundException, BadRequestException } from '@nestjs/common'; import { PrismaService } from '../../common/prisma.service'; import { HoldSeatsDto } from './seats.dto'; import { Cron, CronExpression } from '@nestjs/schedule'; import { SegmentsService } from '../segments/segments.service'; import { SystemConfigService, CONFIG_KEYS } from '../system-config/system-config.service'; @Injectable() export class SeatsService { constructor( private prisma: PrismaService, private segmentsService: SegmentsService, private systemConfig: SystemConfigService, ) {} async getSeatMap(scheduleId: string, coachTypeId?: string) { const schedule = await this.prisma.trainSchedule.findUnique({ where: { id: scheduleId }, select: { originStationId: true, destinationStationId: true }, }); if (!schedule) throw new NotFoundException('Schedule not found'); const assignments = await this.prisma.coachAssignment.findMany({ where: { scheduleId, ...(coachTypeId ? { coach: { coachTypeId } } : {}), }, include: { coach: { include: { seats: { orderBy: [{ row: 'asc' }, { col: 'asc' }] }, coachType: { include: { seatClasses: true } }, }, }, }, orderBy: { positionNumber: 'asc' }, }); const allSeatIds = assignments.flatMap((a: any) => a.coach.seats.map((s: any) => s.id)); const effectiveStatuses = await this.resolveEffectiveStatuses(scheduleId, allSeatIds, schedule.originStationId, schedule.destinationStationId); return { coaches: assignments.map((a) => { const allSeats = a.coach.seats; const coachTypeName = a.coach.coachType?.name ?? ''; const seatClassNames = a.coach.coachType.seatClasses.map((sc: any) => sc.name); const isBedCoach = this.isBedCoach(coachTypeName); // Compute actual beds-per-room from first room to correctly identify VIP (4) vs Economy (6) const bedsPerRoom = isBedCoach ? allSeats.filter((s: any) => s.row === (allSeats[0] as any)?.row).length : 0; const bedCategory = isBedCoach ? this.getBedCategory(coachTypeName, bedsPerRoom) : null; const mappedSeats = allSeats.map((s: any) => { const resolvedBedPosition = isBedCoach ? this.resolveBedPosition(s.col, s.bedPosition) : s.bedPosition; return { id: s.id, seatNumber: s.seatNumber, label: s.seatNumber, status: effectiveStatuses.get(s.id) ?? s.status, kind: s.kind, row: s.row, col: s.col, isWindow: s.isWindow, isAisle: s.isAisle, bedPosition: resolvedBedPosition, // Bed-specific fields (only when coach is a bed coach) ...(isBedCoach ? { room_id: `${a.coach.id}-R${s.row}`, category: bedCategory, position: this.colToPosition(s.col, a.coach.arrangement), bed_type: this.bedPositionToType(resolvedBedPosition), } : {}), }; }); const base = { id: a.coach.id, assignmentId: a.id, coachNumber: a.coach.number, label: a.coach.number, mode: a.coach.status, name: `Coach ${a.coach.number}`, coachTypeName, isBedCoach, bedCategory, seatClasses: seatClassNames, seatClass: seatClassNames.length > 0 ? seatClassNames[0] : 'Standard', positionNumber: a.positionNumber, seatArrangement: a.coach.arrangement, totalSeats: a.coach.capacity, }; if (isBedCoach) { // Group seats into rooms; row = room number const roomMap = new Map(); for (const seat of mappedSeats) { if (!roomMap.has(seat.row)) roomMap.set(seat.row, []); roomMap.get(seat.row)!.push(seat); } const rooms = Array.from(roomMap.entries()) .sort(([a], [b]) => a - b) .map(([roomNumber, beds]) => ({ room_id: `${a.coach.id}-R${roomNumber}`, roomNumber, category: bedCategory, totalBeds: beds.length, beds, })); return { ...base, rooms, seats: mappedSeats }; } return { ...base, seats: mappedSeats }; }), }; } private isBedCoach(coachTypeName: string): boolean { const n = coachTypeName.toLowerCase(); return n.includes('bed') || n.includes('berth') || n.includes('sleeper') || n.includes('couchette'); } private getBedCategory(coachTypeName: string, bedsPerRoom?: number): 'ECONOMY_BED' | 'VIP_BED' { const n = coachTypeName.toLowerCase(); // Explicit VIP name check first if (n.includes('vip')) return 'VIP_BED'; // Fall back to actual beds-per-room count: 4 = VIP, 6 = Economy if (bedsPerRoom === 4) return 'VIP_BED'; return 'ECONOMY_BED'; } // col format: L1, L2, L3, R1, R2, R3 (new) or A, B, C, D (legacy) // arrangement e.g. "2+2", "3+3", "2+0" → "leftCount+rightCount" private colToPosition(col: string, arrangement?: string): 'LEFT' | 'RIGHT' | null { if (!col) return null; // New named-col format: L1, L2, R1, R2 … if (/^L\d+$/.test(col)) return 'LEFT'; if (/^R\d+$/.test(col)) return 'RIGHT'; // Legacy single-letter cols (A, B, C, D …): derive from arrangement const colIndex = col.toUpperCase().charCodeAt(0) - 65; // A=0, B=1, C=2 … if (arrangement) { const [leftStr, rightStr] = arrangement.split('+'); const rightCount = parseInt(rightStr ?? '0', 10); if (rightCount === 0) return 'LEFT'; // single-side berth coach — all LEFT const leftCount = parseInt(leftStr, 10) || 0; return colIndex < leftCount ? 'LEFT' : 'RIGHT'; } return 'LEFT'; // safe default when no arrangement info } private bedPositionToType(bedPosition: string | null): 'LOWER' | 'MIDDLE' | 'UPPER' | null { if (!bedPosition) return null; const map: Record = { lower: 'LOWER', middle: 'MIDDLE', upper: 'UPPER', }; return map[bedPosition.toLowerCase()] ?? null; } // Derives bedPosition from col when the seat was created with legacy A/B/C columns // (new coaches use L1/L2/L3/R1/R2/R3 and store bedPosition explicitly). // Col-to-tier mapping: A → lower, B → middle, C → upper, D → upper (4-tier). private resolveBedPosition(col: string, storedBedPosition: string | null): string | null { if (storedBedPosition) return storedBedPosition; const legacyMap: Record = { A: 'lower', B: 'middle', C: 'upper', D: 'upper' }; // Also handle numeric suffix in L/R cols: L1→lower, L2→middle, L3→upper if (/^[LR]\d+$/.test(col)) { const tier = parseInt(col.slice(1), 10); if (tier === 1) return 'lower'; if (tier === 2) return 'middle'; return 'upper'; } return legacyMap[col?.toUpperCase()] ?? null; } async resolveEffectiveStatuses( scheduleId: string, seatIds: string[], originStationId?: string, destinationStationId?: string, ): Promise> { const statusMap = new Map(); if (seatIds.length === 0) return statusMap; // Resolve the requested leg's sequence range once let reqFrom: number | undefined; let reqTo: number | undefined; let allStopTimes: { stationId: string; sequence: number }[] | null = null; const getStopTimes = async () => { if (!allStopTimes) { allStopTimes = await this.prisma.tripStopTime.findMany({ where: { scheduleId }, select: { stationId: true, sequence: true }, }); } return allStopTimes; }; if (originStationId && destinationStationId) { const stops = await getStopTimes(); const seqOf = (id: string) => stops.find(s => s.stationId === id)?.sequence; reqFrom = seqOf(originStationId); reqTo = seqOf(destinationStationId); } // ── Active holds ────────────────────────────────────────────────────────── const activeHolds = await this.prisma.seatHold.findMany({ where: { scheduleId, expiresAt: { gt: new Date() }, seatIds: { hasSome: seatIds } }, select: { seatIds: true, createdBy: true }, }); for (const hold of activeHolds) { let holdFrom: number | undefined; let holdTo: number | undefined; try { if (hold.createdBy?.trimStart().startsWith('{')) { const meta = JSON.parse(hold.createdBy); const stops = await getStopTimes(); const seqOf = (id: string) => stops.find(s => s.stationId === id)?.sequence; holdFrom = seqOf(meta.originStationId); holdTo = seqOf(meta.destinationStationId); } } catch { /* ignore */ } for (const seatId of hold.seatIds) { if (!seatIds.includes(seatId)) continue; if (reqFrom !== undefined && reqTo !== undefined && holdFrom !== undefined && holdTo !== undefined) { if (holdFrom < reqTo && reqFrom < holdTo) statusMap.set(seatId, 'HELD'); } else { statusMap.set(seatId, 'HELD'); } } } // ── Confirmed bookings via JourneySegment ───────────────────────────────── const bookedSegments = await this.prisma.journeySegment.findMany({ where: { scheduleId, seatId: { in: seatIds }, journey: { status: { in: ['CONFIRMED', 'PENDING_PAYMENT'] } }, }, select: { seatId: true, departureStationId: true, arrivalStationId: true }, }); if (reqFrom !== undefined && reqTo !== undefined) { const stops = await getStopTimes(); const seqOf = (id: string) => stops.find(s => s.stationId === id)?.sequence; for (const seg of bookedSegments) { if (!seg.seatId) continue; const segFrom = seqOf(seg.departureStationId); const segTo = seqOf(seg.arrivalStationId); if (segFrom !== undefined && segTo !== undefined) { if (segFrom < reqTo && reqFrom < segTo) statusMap.set(seg.seatId, 'BOOKED'); } else { statusMap.set(seg.seatId, 'BOOKED'); } } } else { for (const seg of bookedSegments) { if (seg.seatId) statusMap.set(seg.seatId, 'BOOKED'); } } return statusMap; } async holdSeats(dto: HoldSeatsDto) { const passengerIds = dto.passengers.map(p => p.passengerId); const seatIds = dto.passengers.map(p => p.seatId); if (new Set(passengerIds).size !== passengerIds.length) throw new BadRequestException('Duplicate passengerId in passengers list'); if (new Set(seatIds).size !== seatIds.length) throw new BadRequestException('Duplicate seatId in passengers list'); const [holdMinutes, cutoffHours] = await Promise.all([ this.systemConfig.getNumber(CONFIG_KEYS.SEAT_HOLD_DURATION_MINUTES), this.systemConfig.getNumber(CONFIG_KEYS.HOLD_CUTOFF_HOURS_BEFORE_DEPARTURE), ]); const expiresAt = new Date(Date.now() + holdMinutes * 60 * 1000); const schedule = await this.prisma.trainSchedule.findUnique({ where: { id: dto.scheduleId }, select: { departureAt: true }, }); if (!schedule) throw new NotFoundException('Schedule not found'); const msUntilDeparture = schedule.departureAt.getTime() - Date.now(); const cutoffMs = cutoffHours * 60 * 60 * 1000; if (msUntilDeparture <= cutoffMs) { throw new BadRequestException( `Seats cannot be held within ${cutoffHours} hour${cutoffHours !== 1 ? 's' : ''} of departure`, ); } const hold = await this.prisma.$transaction(async (tx) => { const seats = await tx.seat.findMany({ where: { id: { in: seatIds } }, select: { id: true, status: true, seatNumber: true }, }); if (seats.length !== seatIds.length) { const found = new Set(seats.map(s => s.id)); const missing = seatIds.filter(id => !found.has(id)); throw new NotFoundException(`Seat(s) not found: ${missing.join(', ')}`); } const blocked = seats.filter(s => s.status === 'BLOCKED'); if (blocked.length > 0) throw new ConflictException(`Seat(s) ${blocked.map(s => s.seatNumber).join(', ')} are blocked`); const seatLabelById = Object.fromEntries(seats.map(s => [s.id, s.seatNumber])); const stopTimes = await tx.tripStopTime.findMany({ where: { scheduleId: dto.scheduleId }, select: { stationId: true, sequence: true }, }); const seqOf = (stationId: string) => stopTimes.find(s => s.stationId === stationId)?.sequence; const reqFrom = seqOf(dto.originStationId); const reqTo = seqOf(dto.destinationStationId); if (reqFrom === undefined || reqTo === undefined) throw new BadRequestException('Origin or destination station not found'); if (reqFrom >= reqTo) throw new BadRequestException('Origin must come before destination'); // ── Check existing holds for overlap ──────────────────────────────────── const activeHolds = await tx.seatHold.findMany({ where: { scheduleId: dto.scheduleId, expiresAt: { gt: new Date() } }, select: { seatIds: true, createdBy: true }, }); const parsedHolds: { seatIds: string[]; from: number; to: number; passengerIds: string[] }[] = []; for (const h of activeHolds) { try { if (h.createdBy?.trimStart().startsWith('{')) { const meta = JSON.parse(h.createdBy); const holdFrom = seqOf(meta.originStationId); const holdTo = seqOf(meta.destinationStationId); if (holdFrom !== undefined && holdTo !== undefined) { parsedHolds.push({ seatIds: h.seatIds, from: holdFrom, to: holdTo, passengerIds: (meta.passengers ?? []).map((p: any) => p.passengerId), }); } } } catch { /* ignore */ } } for (const { passengerId, seatId } of dto.passengers) { for (const hold of parsedHolds) { const legsOverlap = hold.from < reqTo && reqFrom < hold.to; if (!legsOverlap) continue; if (hold.seatIds.includes(seatId)) { throw new ConflictException( `Seat ${seatLabelById[seatId]} is already held for this leg`, ); } if (hold.passengerIds.includes(passengerId)) { throw new ConflictException( `Passenger already holds a seat on this journey leg`, ); } } } // ── Check confirmed JourneySegments for overlap ────────────────────────── const bookedSegments = await tx.journeySegment.findMany({ where: { scheduleId: dto.scheduleId, seatId: { in: seatIds }, journey: { status: { in: ['CONFIRMED', 'PENDING_PAYMENT'] } }, }, select: { seatId: true, departureStationId: true, arrivalStationId: true }, }); for (const seg of bookedSegments) { if (!seg.seatId) continue; const segFrom = seqOf(seg.departureStationId); const segTo = seqOf(seg.arrivalStationId); if (segFrom !== undefined && segTo !== undefined) { if (segFrom < reqTo && reqFrom < segTo) { throw new ConflictException( `Seat ${seatLabelById[seg.seatId]} is already booked for this leg`, ); } } } const holdMeta = { originStationId: dto.originStationId, destinationStationId: dto.destinationStationId, passengers: dto.passengers.map(p => ({ passengerId: p.passengerId, seatId: p.seatId })), }; return tx.seatHold.create({ data: { scheduleId: dto.scheduleId, passengerId: dto.passengers[0].passengerId, seatIds, createdBy: JSON.stringify(holdMeta), expiresAt, }, }); }); return this.enrichHold(hold); } async getHolds(scheduleId?: string, passengerId?: string) { const holds = await this.prisma.seatHold.findMany({ where: { expiresAt: { gt: new Date() }, ...(scheduleId ? { scheduleId } : {}), ...(passengerId ? { passengerId } : {}), }, orderBy: { createdAt: 'desc' }, }); return Promise.all(holds.map(h => this.enrichHold(h))); } async getHold(holdId: string) { const hold = await this.prisma.seatHold.findUnique({ where: { id: holdId } }); if (!hold) throw new NotFoundException('Hold not found'); return this.enrichHold(hold); } private async enrichHold(hold: any) { let originStationId: string | null = null; let destinationStationId: string | null = null; let passengerSeatMap: { passengerId: string; seatId: string }[] = []; try { if (hold.createdBy) { const raw = hold.createdBy; if (typeof raw === 'string' && raw.trimStart().startsWith('{')) { const meta = JSON.parse(raw); originStationId = meta.originStationId ?? null; destinationStationId = meta.destinationStationId ?? null; passengerSeatMap = Array.isArray(meta.passengers) ? meta.passengers : []; } } } catch { /* ignore */ } const seatIds = hold.seatIds as string[]; const [schedule, originStation, destinationStation, seats] = await Promise.all([ this.prisma.trainSchedule.findUnique({ where: { id: hold.scheduleId }, include: { train: true, originStation: true, destinationStation: true }, }), originStationId ? this.prisma.station.findUnique({ where: { id: originStationId } }) : null, destinationStationId ? this.prisma.station.findUnique({ where: { id: destinationStationId } }) : null, this.prisma.seat.findMany({ where: { id: { in: seatIds } }, include: { coach: true }, }), ]); let originSequence: number | null = null; let destinationSequence: number | null = null; if (originStationId && destinationStationId) { const stopTimes = await this.prisma.tripStopTime.findMany({ where: { scheduleId: hold.scheduleId, stationId: { in: [originStationId, destinationStationId] } }, select: { stationId: true, sequence: true }, }); originSequence = stopTimes.find(s => s.stationId === originStationId)?.sequence ?? null; destinationSequence = stopTimes.find(s => s.stationId === destinationStationId)?.sequence ?? null; } const seatById = Object.fromEntries(seats.map(s => [s.id, s])); const passengers = passengerSeatMap.length > 0 ? passengerSeatMap.map(({ passengerId, seatId }) => { const s = seatById[seatId]; return { passengerId, seat: s ? { id: s.id, label: s.seatNumber, seatNumber: s.seatNumber, coach: s.coach.number, seatClass: 'Standard', row: s.row, col: s.col, } : { id: seatId }, }; }) : seatIds.map(seatId => { const s = seatById[seatId]; return { passengerId: hold.passengerId, seat: s ? { id: s.id, label: s.seatNumber, seatNumber: s.seatNumber, coach: s.coach.number, seatClass: 'Standard', row: s.row, col: s.col, } : { id: seatId }, }; }); return { holdId: hold.id, expiresAt: hold.expiresAt, createdAt: hold.createdAt, ttlSeconds: Math.max(0, Math.floor((hold.expiresAt.getTime() - Date.now()) / 1000)), schedule: schedule ? { id: schedule.id, trainNumber: schedule.train.number, trainName: schedule.train.name, departureAt: schedule.departureAt, arrivalAt: schedule.arrivalAt, fullRouteOrigin: schedule.originStation.name, fullRouteDestination: schedule.destinationStation.name, } : null, leg: { originStationId, originStationName: originStation?.name ?? null, originStationCode: originStation?.code ?? null, originSequence, destinationStationId, destinationStationName: destinationStation?.name ?? null, destinationStationCode: destinationStation?.code ?? null, destinationSequence, }, passengers, }; } async releaseHold(holdId: string) { const hold = await this.prisma.seatHold.findUnique({ where: { id: holdId } }); if (!hold) throw new NotFoundException('Hold not found'); await this.prisma.seatHold.delete({ where: { id: holdId } }); return { released: true, holdId }; } // Physical seat.status stays AVAILABLE — segment rows are the source of truth for occupancy. async confirmSeats(_seatIds: string[]) {} // Delete the Journey (and its JourneySegments) scoped to this booking. async releaseSeats(bookingId: string) { await this.prisma.journey.deleteMany({ where: { bookingId } as any }); } async autoAssignSeats(scheduleId: string, count: number, seatClassName: string): Promise { const seats = await this.prisma.seat.findMany({ where: { coach: { assignments: { some: { scheduleId } } }, status: 'AVAILABLE', seatNumber: { not: '' }, NOT: { seatNumber: { startsWith: '-' } }, }, orderBy: [{ coach: { number: 'asc' } }, { row: 'asc' }, { col: 'asc' }], }); if (seats.length < count) { throw new ConflictException(`Only ${seats.length} seats available, requested ${count}`); } const assigned = this.findContiguousSeats(seats, count); return assigned.map((s) => s.id); } private findContiguousSeats(seats: any[], count: number): any[] { if (count === 1) return [seats[0]]; const grouped = new Map(); for (const seat of seats) { const key = `${seat.coachId}-${seat.row}`; if (!grouped.has(key)) grouped.set(key, []); grouped.get(key)!.push(seat); } for (const rowSeats of grouped.values()) { if (rowSeats.length >= count) { return rowSeats.slice(0, count); } } return seats.slice(0, count); } async exportSeatsCSV(scheduleId: string): Promise { const assignments = await this.prisma.coachAssignment.findMany({ where: { scheduleId }, include: { coach: { include: { seats: { orderBy: [{ row: 'asc' }, { col: 'asc' }] } } } }, }); const rows = ['coachId,coachLabel,row,col,seatNumber,kind,status,premiumFeeMinor']; for (const a of assignments) { for (const seat of a.coach.seats) { rows.push(`${a.coach.id},${a.coach.number},${seat.row},${seat.col},${seat.seatNumber},${seat.kind},${seat.status},${seat.premiumFeeMinor}`); } } return rows.join('\n'); } async previewSeatsCSV(csvContent: string): Promise<{ valid: number; invalid: number; errors: string[] }> { const lines = csvContent.trim().split('\n').slice(1); const errors: string[] = []; let valid = 0; let invalid = 0; for (let i = 0; i < lines.length; i++) { const parts = lines[i].split(','); if (parts.length < 8) { errors.push(`Line ${i + 2}: Invalid format`); invalid++; continue; } const [coachId, , row, col, seatNumber] = parts; if (!coachId || !row || !col || !seatNumber) { errors.push(`Line ${i + 2}: Missing required fields`); invalid++; continue; } valid++; } return { valid, invalid, errors: errors.slice(0, 10) }; } async importSeatsCSV(scheduleId: string, csvContent: string, commit: boolean): Promise<{ imported: number; errors: string[] }> { const lines = csvContent.trim().split('\n').slice(1); const errors: string[] = []; let imported = 0; if (!commit) { return { imported: 0, errors: ['Preview mode'] }; } for (let i = 0; i < lines.length; i++) { try { const parts = lines[i].split(','); const [coachId, , row, col, seatNumber, kind, status, premiumFeeMinor] = parts; await this.prisma.seat.upsert({ where: { coachId_row_col: { coachId, row: parseInt(row), col } }, update: { seatNumber, kind: kind as any, status: status as any, premiumFeeMinor: parseInt(premiumFeeMinor) || 0, }, create: { coachId, row: parseInt(row), col, seatNumber, kind: kind as any, status: status as any, premiumFeeMinor: parseInt(premiumFeeMinor) || 0, }, }); imported++; } catch (err) { errors.push(`Line ${i + 2}: ${err instanceof Error ? err.message : String(err)}`); } } return { imported, errors: errors.slice(0, 10) }; } async blockSeat(seatId: string, reason: string) { const seat = await this.prisma.seat.findUnique({ where: { id: seatId } }); if (!seat) throw new NotFoundException('Seat not found'); await this.prisma.seat.update({ where: { id: seatId }, data: { status: 'BLOCKED' } }); await this.prisma.seatBlock.create({ data: { seatId, reason, blockedBy: 'system' } }); return { blocked: true, seatId, reason }; } async unblockSeat(seatId: string) { const seat = await this.prisma.seat.findUnique({ where: { id: seatId } }); if (!seat) throw new NotFoundException('Seat not found'); await this.prisma.seat.update({ where: { id: seatId }, data: { status: 'AVAILABLE' } }); await this.prisma.seatBlock.deleteMany({ where: { seatId } }); return { unblocked: true, seatId }; } async removeSeat(seatId: string) { const seat = await this.prisma.seat.findUnique({ where: { id: seatId } }); if (!seat) throw new NotFoundException('Seat not found'); if (!seat.seatNumber) throw new BadRequestException('Seat already removed'); await this.prisma.seat.update({ where: { id: seatId }, data: { seatNumber: `-${seat.seatNumber}` }, }); return { removed: true, seatId, originalSeatNumber: seat.seatNumber }; } async undoRemoveSeat(seatId: string) { const seat = await this.prisma.seat.findUnique({ where: { id: seatId } }); if (!seat) throw new NotFoundException('Seat not found'); if (!seat.seatNumber || !seat.seatNumber.startsWith('-')) { throw new BadRequestException('Seat is not removed'); } const originalNumber = seat.seatNumber.slice(1); await this.prisma.seat.update({ where: { id: seatId }, data: { seatNumber: originalNumber } }); return { restored: true, seatId, seatNumber: originalNumber }; } @Cron(CronExpression.EVERY_MINUTE) async expireHolds() { // Holds are temporary and don't create Journey rows — just delete expired ones. await this.prisma.seatHold.deleteMany({ where: { expiresAt: { lt: new Date() } } }); } }