mirror of
https://github.com/Tria-plc/edr-platform.git
synced 2026-08-26 18:42:49 +00:00
247 lines
9.9 KiB
TypeScript
247 lines
9.9 KiB
TypeScript
import { Injectable, Logger } from '@nestjs/common';
|
|
import { Cron } from '@nestjs/schedule';
|
|
import { PrismaService } from '../../common/prisma.service';
|
|
import { SmsClientService } from '../notifications/sms-client.service';
|
|
|
|
/** Maximum time (hours) a passenger has to pay after booking. */
|
|
const MAX_PAYMENT_HOURS = 2;
|
|
/** Minutes before departure: cutoff for new bookings and payment deadline. */
|
|
const CUTOFF_MINUTES = 30;
|
|
|
|
/**
|
|
* payment_deadline = MIN(booking_time + 2h, departure_time - 30min)
|
|
*/
|
|
function computePaymentDeadline(createdAt: Date, departureAt: Date): Date {
|
|
const maxDeadline = new Date(createdAt.getTime() + MAX_PAYMENT_HOURS * 60 * 60 * 1000);
|
|
const cutoffDeadline = new Date(departureAt.getTime() - CUTOFF_MINUTES * 60 * 1000);
|
|
return maxDeadline < cutoffDeadline ? maxDeadline : cutoffDeadline;
|
|
}
|
|
|
|
function fmtTime(d: Date): string {
|
|
return d.toLocaleTimeString('en-GB', {
|
|
hour: '2-digit',
|
|
minute: '2-digit',
|
|
timeZone: 'Africa/Addis_Ababa',
|
|
});
|
|
}
|
|
|
|
@Injectable()
|
|
export class TasksService {
|
|
private readonly logger = new Logger(TasksService.name);
|
|
|
|
constructor(
|
|
private readonly prisma: PrismaService,
|
|
private readonly sms: SmsClientService,
|
|
) {}
|
|
|
|
// ─────────────────────────────────────────────────────────────────────────
|
|
// Every 1 min: advance TrainSchedule statuses.
|
|
//
|
|
// SCHEDULED → BOARDING when departure ≤ 30 min away (closed to new bookings)
|
|
// BOARDING → EN_ROUTE at actual departure
|
|
// EN_ROUTE → ARRIVED at arrival time
|
|
// ─────────────────────────────────────────────────────────────────────────
|
|
@Cron('*/1 * * * *')
|
|
async syncScheduleStatuses() {
|
|
const now = new Date();
|
|
const thirtyMinFromNow = new Date(now.getTime() + CUTOFF_MINUTES * 60 * 1000);
|
|
|
|
const [boarding, departed, arrived] = await Promise.all([
|
|
this.prisma.trainSchedule.updateMany({
|
|
where: { status: 'SCHEDULED', departureAt: { lte: thirtyMinFromNow } },
|
|
data: { status: 'BOARDING' },
|
|
}),
|
|
this.prisma.trainSchedule.updateMany({
|
|
where: { status: 'BOARDING', departureAt: { lte: now } },
|
|
data: { status: 'EN_ROUTE' },
|
|
}),
|
|
this.prisma.trainSchedule.updateMany({
|
|
where: { status: 'EN_ROUTE', arrivalAt: { lte: now } },
|
|
data: { status: 'ARRIVED' },
|
|
}),
|
|
]);
|
|
|
|
if (boarding.count > 0 || departed.count > 0 || arrived.count > 0) {
|
|
this.logger.log(
|
|
`Schedule sync: ${boarding.count} → BOARDING, ${departed.count} → EN_ROUTE, ${arrived.count} → ARRIVED`,
|
|
);
|
|
}
|
|
}
|
|
|
|
// ─────────────────────────────────────────────────────────────────────────
|
|
// Every 1 min: payment deadline enforcement.
|
|
//
|
|
// Reminder — sent once at the midpoint of the booking's payment window:
|
|
// reminder_at = booking_time + total_window / 2
|
|
//
|
|
// Cancel — when now ≥ payment_deadline
|
|
// payment_deadline = MIN(booking_time + 2h, departure_time - 30min)
|
|
//
|
|
// Examples (departure 10:00, cutoff 9:30):
|
|
// Booked 8:00 → deadline 9:30, window 1.5h, reminder at 8:45
|
|
// Booked 9:00 → deadline 9:30, window 30min, reminder at 9:15
|
|
// ─────────────────────────────────────────────────────────────────────────
|
|
@Cron('*/1 * * * *')
|
|
async enforcePaymentDeadlines() {
|
|
const now = new Date();
|
|
await Promise.all([
|
|
this.sendPaymentReminders(now),
|
|
this.cancelExpiredPendingBookings(now),
|
|
]);
|
|
}
|
|
|
|
// ── Send reminder at the midpoint of each booking's payment window ────────
|
|
private async sendPaymentReminders(now: Date) {
|
|
// Only look at bookings created within the last 3 h with a future departure.
|
|
const threeHoursAgo = new Date(now.getTime() - 3 * 60 * 60 * 1000);
|
|
|
|
const bookings = await this.prisma.booking.findMany({
|
|
where: {
|
|
status: 'PENDING_PAYMENT',
|
|
paymentReminderSentAt: null,
|
|
createdAt: { gte: threeHoursAgo },
|
|
schedule: { departureAt: { gte: now } },
|
|
} as any,
|
|
include: {
|
|
schedule: {
|
|
include: {
|
|
originStation: { select: { name: true } },
|
|
destinationStation: { select: { name: true } },
|
|
},
|
|
},
|
|
},
|
|
});
|
|
|
|
for (const booking of bookings) {
|
|
try {
|
|
const createdAt = booking.createdAt as Date;
|
|
const dep = booking.schedule.departureAt as Date;
|
|
const paymentDeadline = computePaymentDeadline(createdAt, dep);
|
|
const totalWindowMs = paymentDeadline.getTime() - createdAt.getTime();
|
|
|
|
// Skip degenerate windows (< 2 min) — the cancel job will handle these immediately
|
|
if (totalWindowMs < 2 * 60 * 1000) continue;
|
|
|
|
// Remind once, at the midpoint of the total payment window
|
|
const reminderAt = new Date(createdAt.getTime() + totalWindowMs / 2);
|
|
if (now < reminderAt) continue;
|
|
|
|
const origin = booking.schedule.originStation?.name ?? '';
|
|
const dest = booking.schedule.destinationStation?.name ?? '';
|
|
const remainingMs = Math.max(0, paymentDeadline.getTime() - now.getTime());
|
|
const remainingMin = Math.round(remainingMs / 60_000);
|
|
|
|
const message =
|
|
`EDR: Your booking ${booking.bookingRef} ` +
|
|
`(${origin} → ${dest}) departs at ${fmtTime(dep)}. ` +
|
|
`Complete payment within ${remainingMin} minute(s) (by ${fmtTime(paymentDeadline)}) ` +
|
|
`or your booking will be cancelled.`;
|
|
|
|
if (booking.contactPhone) {
|
|
await this.sms.sendSms({ to: booking.contactPhone, message }).catch(() => null);
|
|
}
|
|
|
|
await this.prisma.booking.update({
|
|
where: { id: booking.id },
|
|
data: { paymentReminderSentAt: now } as any,
|
|
});
|
|
|
|
this.logger.log(
|
|
`Payment reminder sent: ${booking.bookingRef} ` +
|
|
`(deadline ${fmtTime(paymentDeadline)}, ${remainingMin} min remaining)`,
|
|
);
|
|
} catch (err) {
|
|
this.logger.error(
|
|
`Reminder failed for ${booking.bookingRef}: ${err instanceof Error ? err.message : String(err)}`,
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
// ── Cancel bookings whose payment deadline has passed ─────────────────────
|
|
private async cancelExpiredPendingBookings(now: Date) {
|
|
const twoHoursAgo = new Date(now.getTime() - MAX_PAYMENT_HOURS * 60 * 60 * 1000);
|
|
const departureCutoff = new Date(now.getTime() + CUTOFF_MINUTES * 60 * 1000);
|
|
|
|
// payment_deadline = MIN(createdAt + 2h, departureAt - 30min)
|
|
// Deadline is reached when either branch of the MIN is in the past:
|
|
// (a) createdAt ≤ now - 2h → 2-hour max window elapsed
|
|
// (b) departureAt ≤ now + 30min → departure within 30 min
|
|
const expiredBookings = await this.prisma.booking.findMany({
|
|
where: {
|
|
status: 'PENDING_PAYMENT',
|
|
OR: [
|
|
{ createdAt: { lte: twoHoursAgo } },
|
|
{ schedule: { departureAt: { lte: departureCutoff } } },
|
|
],
|
|
},
|
|
include: {
|
|
schedule: {
|
|
include: {
|
|
originStation: { select: { name: true } },
|
|
destinationStation: { select: { name: true } },
|
|
},
|
|
},
|
|
paymentIntent: { select: { method: true } },
|
|
},
|
|
});
|
|
|
|
let cancelledCount = 0;
|
|
|
|
for (const booking of expiredBookings) {
|
|
try {
|
|
// Re-verify exact deadline to avoid racing with a concurrent payment confirmation
|
|
const createdAt = booking.createdAt as Date;
|
|
const dep = booking.schedule.departureAt as Date;
|
|
const paymentDeadline = computePaymentDeadline(createdAt, dep);
|
|
if (now < paymentDeadline) continue;
|
|
|
|
// 1. Release held seats (Journey rows are the occupancy source of truth)
|
|
await this.prisma.journey.deleteMany({ where: { bookingId: booking.id } as any });
|
|
|
|
// 2. Audit record (no refund — payment was never completed)
|
|
await this.prisma.bookingCancellation.create({
|
|
data: {
|
|
bookingId: booking.id,
|
|
cancelledBy: 'SYSTEM',
|
|
reason: 'Payment not completed before deadline',
|
|
refundAmount: 0,
|
|
refundMethod: booking.paymentIntent?.method ?? 'NONE',
|
|
refundStatus: 'NOT_APPLICABLE',
|
|
},
|
|
}).catch(() => null);
|
|
|
|
// 3. Mark cancelled
|
|
await this.prisma.booking.update({
|
|
where: { id: booking.id },
|
|
data: { status: 'CANCELLED' },
|
|
});
|
|
|
|
// 4. Notify passenger
|
|
const origin = booking.schedule.originStation?.name ?? '';
|
|
const dest = booking.schedule.destinationStation?.name ?? '';
|
|
|
|
const message =
|
|
`EDR: Your booking ${booking.bookingRef} ` +
|
|
`(${origin} → ${dest}, departs ${fmtTime(dep)}) has been cancelled ` +
|
|
`because payment was not completed before the deadline (${fmtTime(paymentDeadline)}).`;
|
|
|
|
if (booking.contactPhone) {
|
|
await this.sms.sendSms({ to: booking.contactPhone, message }).catch(() => null);
|
|
}
|
|
|
|
this.logger.log(`Auto-cancelled: ${booking.bookingRef} (deadline was ${fmtTime(paymentDeadline)})`);
|
|
cancelledCount++;
|
|
} catch (err) {
|
|
this.logger.error(
|
|
`Auto-cancel failed for ${booking.bookingRef}: ${err instanceof Error ? err.message : String(err)}`,
|
|
);
|
|
}
|
|
}
|
|
|
|
if (cancelledCount > 0) {
|
|
this.logger.log(`Auto-cancelled ${cancelledCount} expired pending booking(s)`);
|
|
}
|
|
}
|
|
}
|