mirror of
https://github.com/Tria-plc/edr-platform.git
synced 2026-08-26 18:42:49 +00:00
Merge pull request #323 from Tria-plc/alpha
Boarding, payment methods, journey direction on seat hold, and more updates
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
-- DropForeignKey
|
||||
ALTER TABLE "passenger"."TicketSeat" DROP CONSTRAINT IF EXISTS "TicketSeat_seatId_fkey";
|
||||
|
||||
-- DropForeignKey
|
||||
ALTER TABLE "passenger"."TicketSeat" DROP CONSTRAINT IF EXISTS "TicketSeat_ticketId_fkey";
|
||||
|
||||
-- DropIndex
|
||||
DROP INDEX IF EXISTS "passenger"."Ticket_bookingId_key";
|
||||
|
||||
-- AlterTable: Station
|
||||
ALTER TABLE "passenger"."Station" DROP COLUMN IF EXISTS "timezone";
|
||||
|
||||
-- AlterTable: Ticket — add columns with safe defaults
|
||||
ALTER TABLE "passenger"."Ticket"
|
||||
ADD COLUMN IF NOT EXISTS "leg" INTEGER NOT NULL DEFAULT 1,
|
||||
ADD COLUMN IF NOT EXISTS "passengerName" TEXT NOT NULL DEFAULT '',
|
||||
ADD COLUMN IF NOT EXISTS "scheduleId" TEXT,
|
||||
ADD COLUMN IF NOT EXISTS "seatId" TEXT NOT NULL DEFAULT '';
|
||||
|
||||
-- DropTable
|
||||
DROP TABLE IF EXISTS "passenger"."TicketSeat";
|
||||
|
||||
-- Remove GateValidationLog rows referencing orphan tickets first
|
||||
DELETE FROM "passenger"."GateValidationLog"
|
||||
WHERE "ticketId" IN (
|
||||
SELECT "id" FROM "passenger"."Ticket"
|
||||
WHERE "seatId" = ''
|
||||
OR "seatId" NOT IN (SELECT "id" FROM "passenger"."Seat")
|
||||
);
|
||||
|
||||
-- Remove orphan ticket rows
|
||||
DELETE FROM "passenger"."Ticket"
|
||||
WHERE "seatId" = ''
|
||||
OR "seatId" NOT IN (SELECT "id" FROM "passenger"."Seat");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX IF NOT EXISTS "Ticket_bookingId_idx" ON "passenger"."Ticket"("bookingId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX IF NOT EXISTS "Ticket_seatId_idx" ON "passenger"."Ticket"("seatId");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "passenger"."Ticket"
|
||||
ADD CONSTRAINT "Ticket_seatId_fkey"
|
||||
FOREIGN KEY ("seatId") REFERENCES "passenger"."Seat"("id")
|
||||
ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,3 @@
|
||||
-- Drop temporary defaults that were only needed for the backfill
|
||||
ALTER TABLE "passenger"."Ticket" ALTER COLUMN "passengerName" DROP DEFAULT;
|
||||
ALTER TABLE "passenger"."Ticket" ALTER COLUMN "seatId" DROP DEFAULT;
|
||||
@@ -0,0 +1,2 @@
|
||||
-- Remove timezone column if it still exists
|
||||
ALTER TABLE "passenger"."Station" DROP COLUMN IF EXISTS "timezone";
|
||||
@@ -0,0 +1,2 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "passenger"."TravelerProfile" ADD COLUMN "gender" TEXT;
|
||||
@@ -0,0 +1,117 @@
|
||||
-- Migration: Add Configurable Fare Management System
|
||||
|
||||
-- Main fare configuration table
|
||||
CREATE TABLE "fare_configurations" (
|
||||
"id" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"description" TEXT,
|
||||
"effective_date" TIMESTAMP(3) NOT NULL,
|
||||
"expiry_date" TIMESTAMP(3),
|
||||
"is_active" BOOLEAN NOT NULL DEFAULT false,
|
||||
"is_default" BOOLEAN NOT NULL DEFAULT false,
|
||||
"created_by" TEXT,
|
||||
"approved_by" TEXT,
|
||||
"approved_at" TIMESTAMP(3),
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "fare_configurations_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- Rate structure by nationality and coach/position
|
||||
CREATE TABLE "fare_rate_rules" (
|
||||
"id" TEXT NOT NULL,
|
||||
"fare_config_id" TEXT NOT NULL,
|
||||
"nationality_type" TEXT NOT NULL, -- 'LOCAL' or 'INTERNATIONAL'
|
||||
"coach_type" TEXT NOT NULL, -- 'REGULAR_SEAT', 'ECONOMY_BED', 'VIP_BED'
|
||||
"bed_position" TEXT, -- 'UPPER', 'MIDDLE', 'LOWER', NULL for seats
|
||||
"rate_per_km_minor" INTEGER NOT NULL,
|
||||
"is_active" BOOLEAN NOT NULL DEFAULT true,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "fare_rate_rules_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- Configurable fare components (insurance, premiums, service charges, taxes)
|
||||
CREATE TABLE "fare_components" (
|
||||
"id" TEXT NOT NULL,
|
||||
"fare_config_id" TEXT NOT NULL,
|
||||
"component_type" TEXT NOT NULL, -- 'INSURANCE', 'PREMIUM', 'SERVICE_CHARGE', 'TAX', 'DEMAND'
|
||||
"component_name" TEXT NOT NULL,
|
||||
"calculation_method" TEXT NOT NULL, -- 'MULTIPLIER', 'PERCENTAGE', 'FIXED_AMOUNT'
|
||||
"value_minor" INTEGER, -- For fixed amounts
|
||||
"percentage_value" DECIMAL(10,6), -- For percentages (e.g., 0.02 for 2%)
|
||||
"applies_to" TEXT NOT NULL DEFAULT 'SUBTOTAL', -- 'BASE_FARE', 'SUBTOTAL', 'TOTAL'
|
||||
"apply_order" INTEGER NOT NULL DEFAULT 1, -- Order of application
|
||||
"is_active" BOOLEAN NOT NULL DEFAULT true,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "fare_components_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- Age-based pricing rules
|
||||
CREATE TABLE "age_pricing_rules" (
|
||||
"id" TEXT NOT NULL,
|
||||
"fare_config_id" TEXT NOT NULL,
|
||||
"rule_name" TEXT NOT NULL,
|
||||
"min_age" INTEGER NOT NULL,
|
||||
"max_age" INTEGER,
|
||||
"pricing_type" TEXT NOT NULL, -- 'FREE', 'FULL_FARE', 'DISCOUNTED'
|
||||
"discount_percentage" DECIMAL(5,4), -- For discounted fares
|
||||
"max_free_passengers" INTEGER, -- For free fares (e.g., 1 free child)
|
||||
"applies_to_components" BOOLEAN NOT NULL DEFAULT false, -- Whether discount applies to components too
|
||||
"is_active" BOOLEAN NOT NULL DEFAULT true,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "age_pricing_rules_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- Audit trail for configuration changes
|
||||
CREATE TABLE "fare_configuration_audit" (
|
||||
"id" TEXT NOT NULL,
|
||||
"fare_config_id" TEXT NOT NULL,
|
||||
"action" TEXT NOT NULL, -- 'CREATED', 'UPDATED', 'ACTIVATED', 'DEACTIVATED'
|
||||
"changed_by" TEXT,
|
||||
"changes" JSONB, -- Store the actual changes made
|
||||
"timestamp" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "fare_configuration_audit_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- Foreign key constraints
|
||||
ALTER TABLE "fare_rate_rules" ADD CONSTRAINT "fare_rate_rules_fare_config_id_fkey" FOREIGN KEY ("fare_config_id") REFERENCES "fare_configurations"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
ALTER TABLE "fare_components" ADD CONSTRAINT "fare_components_fare_config_id_fkey" FOREIGN KEY ("fare_config_id") REFERENCES "fare_configurations"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
ALTER TABLE "age_pricing_rules" ADD CONSTRAINT "age_pricing_rules_fare_config_id_fkey" FOREIGN KEY ("fare_config_id") REFERENCES "fare_configurations"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
ALTER TABLE "fare_configuration_audit" ADD CONSTRAINT "fare_configuration_audit_fare_config_id_fkey" FOREIGN KEY ("fare_config_id") REFERENCES "fare_configurations"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- Indexes for performance
|
||||
CREATE INDEX "fare_configurations_effective_date_idx" ON "fare_configurations"("effective_date");
|
||||
CREATE INDEX "fare_configurations_is_active_idx" ON "fare_configurations"("is_active");
|
||||
CREATE UNIQUE INDEX "fare_configurations_default_unique_idx" ON "fare_configurations"("is_default") WHERE "is_default" = true;
|
||||
|
||||
CREATE INDEX "fare_rate_rules_config_lookup_idx" ON "fare_rate_rules"("fare_config_id", "nationality_type", "coach_type", "bed_position");
|
||||
CREATE INDEX "fare_components_config_order_idx" ON "fare_components"("fare_config_id", "apply_order");
|
||||
CREATE INDEX "age_pricing_rules_age_lookup_idx" ON "age_pricing_rules"("fare_config_id", "min_age", "max_age");
|
||||
|
||||
-- Add legacy mode flag to existing fare tables for gradual migration
|
||||
ALTER TABLE "FareRule" ADD COLUMN "migrated_to_config_id" TEXT;
|
||||
ALTER TABLE "SegmentFareRule" ADD COLUMN "migrated_to_config_id" TEXT;
|
||||
|
||||
-- Add feature flag support
|
||||
CREATE TABLE "system_features" (
|
||||
"id" TEXT NOT NULL,
|
||||
"feature_name" TEXT NOT NULL UNIQUE,
|
||||
"is_enabled" BOOLEAN NOT NULL DEFAULT false,
|
||||
"config" JSONB,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "system_features_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- Insert the configurable fares feature flag
|
||||
INSERT INTO "system_features" ("id", "feature_name", "is_enabled", "config")
|
||||
VALUES ('cf-001', 'USE_CONFIGURABLE_FARES', false, '{"rollout_percentage": 0}');
|
||||
@@ -304,6 +304,7 @@ model TravelerProfile {
|
||||
id String @id @default(uuid())
|
||||
passengerId String
|
||||
fullName String
|
||||
gender String?
|
||||
relationship String
|
||||
dateOfBirth DateTime?
|
||||
nationalId String?
|
||||
@@ -321,7 +322,6 @@ model Station {
|
||||
countryCode String?
|
||||
sequence Int @default(0)
|
||||
isOperational Boolean @default(true)
|
||||
timezone String @default("Africa/Addis_Ababa")
|
||||
lat Decimal? @db.Decimal(9, 6)
|
||||
lng Decimal? @db.Decimal(9, 6)
|
||||
originSchedules TrainSchedule[] @relation("OriginTrips")
|
||||
@@ -459,7 +459,7 @@ model Seat {
|
||||
coach Coach @relation(fields: [coachId], references: [id])
|
||||
bookingSeats BookingSeat[]
|
||||
blocks SeatBlock[]
|
||||
ticketSeats TicketSeat[]
|
||||
tickets Ticket[]
|
||||
|
||||
@@unique([coachId, seatNumber])
|
||||
@@unique([coachId, row, col])
|
||||
@@ -542,7 +542,7 @@ model Booking {
|
||||
returnSchedule TrainSchedule? @relation("ReturnSchedule", fields: [returnScheduleId], references: [id])
|
||||
seats BookingSeat[]
|
||||
paymentIntent PaymentIntent?
|
||||
ticket Ticket?
|
||||
tickets Ticket[]
|
||||
foodOrders FoodOrder[]
|
||||
agentBooking AgentBooking?
|
||||
modifications BookingModification[]
|
||||
@@ -660,8 +660,12 @@ model PaymentRefund {
|
||||
|
||||
model Ticket {
|
||||
id String @id @default(uuid())
|
||||
bookingId String @unique
|
||||
bookingId String
|
||||
bookingRef String
|
||||
passengerName String
|
||||
seatId String
|
||||
leg Int @default(1)
|
||||
scheduleId String?
|
||||
status String @default("ACTIVE")
|
||||
qrPayload String
|
||||
barcodePayload String?
|
||||
@@ -672,20 +676,9 @@ model Ticket {
|
||||
validatorId String?
|
||||
boardedAt DateTime?
|
||||
booking Booking @relation(fields: [bookingId], references: [id])
|
||||
seat Seat @relation(fields: [seatId], references: [id])
|
||||
validationLogs GateValidationLog[]
|
||||
seats TicketSeat[]
|
||||
@@schema("passenger")
|
||||
}
|
||||
|
||||
model TicketSeat {
|
||||
id String @id @default(uuid())
|
||||
ticketId String
|
||||
seatId String
|
||||
seatIndex Int @default(0)
|
||||
ticket Ticket @relation(fields: [ticketId], references: [id], onDelete: Cascade)
|
||||
seat Seat @relation(fields: [seatId], references: [id])
|
||||
|
||||
@@index([ticketId])
|
||||
@@index([bookingId])
|
||||
@@index([seatId])
|
||||
@@schema("passenger")
|
||||
}
|
||||
@@ -1013,7 +1006,7 @@ model RouteStop {
|
||||
routeId String
|
||||
stationId String
|
||||
sequence Int
|
||||
distanceKm Int?
|
||||
distanceKm Float?
|
||||
createdAt DateTime @default(now())
|
||||
route Route @relation(fields: [routeId], references: [id], onDelete: Cascade)
|
||||
|
||||
|
||||
@@ -208,7 +208,7 @@ async function seedRoute() {
|
||||
const station = await prisma.station.findUnique({ where: { code: stationCodes[i] } });
|
||||
await prisma.routeStop.upsert({
|
||||
where: { routeId_sequence: { routeId: route.id, sequence: i + 1 } },
|
||||
update: {},
|
||||
update: { distanceKm: routeDistancesKm[i] },
|
||||
create: { routeId: route.id, stationId: station!.id, sequence: i + 1, distanceKm: routeDistancesKm[i] },
|
||||
});
|
||||
}
|
||||
@@ -227,12 +227,13 @@ async function seedRoute() {
|
||||
});
|
||||
|
||||
const returnStationCodes = ['DRE', 'BIK', 'MIS', 'MTE', 'ADM', 'MOJ', 'BSH', 'LEB', 'SBT'];
|
||||
// Cumulative distances from origin (Dire Dawa), mirroring the outbound route in reverse
|
||||
const returnRouteDistancesKm = [0, 119.4, 181.4, 232.8, 306.3, 323.1, 345.8, 401.5, 413.0];
|
||||
for (let i = 0; i < returnStationCodes.length; i++) {
|
||||
const station = await prisma.station.findUnique({ where: { code: returnStationCodes[i] } });
|
||||
await prisma.routeStop.upsert({
|
||||
where: { routeId_sequence: { routeId: returnRoute!.id, sequence: i + 1 } },
|
||||
update: {},
|
||||
update: { distanceKm: returnRouteDistancesKm[i] },
|
||||
create: { routeId: returnRoute!.id, stationId: station!.id, sequence: i + 1, distanceKm: returnRouteDistancesKm[i] },
|
||||
});
|
||||
}
|
||||
@@ -757,13 +758,7 @@ async function runStep(name: string, step: () => Promise<unknown>): Promise<bool
|
||||
async function main() {
|
||||
console.log('🌱 Comprehensive EDR Seed Starting...\n');
|
||||
|
||||
const steps: Array<[string, () => Promise<unknown>]> = [
|
||||
['system users', seedSystemUsers],
|
||||
['fare rules', seedFareRules],
|
||||
['segment fares', seedSegmentFares],
|
||||
['currency', seedCurrency],
|
||||
['notification templates', seedNotificationTemplates],
|
||||
['kulubbi package', seedKulubbiPackage],
|
||||
const steps: Array<[string, () => Promise<unknown>]> = [
|
||||
];
|
||||
|
||||
let failed = 0;
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
} from '@nestjs/common';
|
||||
import { ThrottlerModule } from '@nestjs/throttler';
|
||||
import { DynamicThrottlerGuard } from './common/dynamic-throttler.guard';
|
||||
import { APP_GUARD } from '@nestjs/core';
|
||||
import { APP_GUARD, APP_FILTER } from '@nestjs/core';
|
||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||
import { ScheduleModule } from '@nestjs/schedule';
|
||||
import { EventEmitterModule } from '@nestjs/event-emitter';
|
||||
@@ -24,6 +24,7 @@ import { PrismaModule } from './common/prisma.module';
|
||||
import { AuditModule } from './common/audit.module';
|
||||
import { I18nModule } from './common/i18n/i18n.module';
|
||||
import { LocaleMiddleware } from './common/i18n/locale.middleware';
|
||||
import { DeleteExceptionFilter } from './common/exceptions/delete-exception.filter';
|
||||
import appConfig from './config/app.config';
|
||||
import dbConfig from './config/database.config';
|
||||
import iamDatabaseConfig from './config/iam-database.config';
|
||||
@@ -65,6 +66,7 @@ import { PackagesModule } from './modules/packages/packages.module';
|
||||
import { ExcessBaggageModule } from './modules/excess-baggage/excess-baggage.module';
|
||||
import { HealthModule } from './modules/health/health.module';
|
||||
import { TasksModule } from './modules/tasks/tasks.module';
|
||||
import { ConfigurableFareModule } from './modules/configurable-fare/configurable-fare.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -134,9 +136,11 @@ import { TasksModule } from './modules/tasks/tasks.module';
|
||||
ExcessBaggageModule,
|
||||
HealthModule,
|
||||
TasksModule,
|
||||
ConfigurableFareModule,
|
||||
],
|
||||
providers: [
|
||||
{ provide: APP_GUARD, useClass: DynamicThrottlerGuard },
|
||||
{ provide: APP_FILTER, useClass: DeleteExceptionFilter },
|
||||
DynamicThrottlerGuard,
|
||||
EdrPassengerOrgSeeder,
|
||||
PassengerStaffUsersSeeder,
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import { ExceptionFilter, Catch, ArgumentsHost, HttpException, HttpStatus } from '@nestjs/common';
|
||||
import { Response } from 'express';
|
||||
import { DeleteOperationException } from './delete-operation.exception';
|
||||
|
||||
@Catch(DeleteOperationException, HttpException)
|
||||
export class DeleteExceptionFilter implements ExceptionFilter {
|
||||
catch(exception: DeleteOperationException | HttpException, host: ArgumentsHost) {
|
||||
const ctx = host.switchToHttp();
|
||||
const response = ctx.getResponse<Response>();
|
||||
const status = exception.getStatus?.() || HttpStatus.BAD_REQUEST;
|
||||
|
||||
if (exception instanceof DeleteOperationException) {
|
||||
// Format the response specifically for delete operations
|
||||
response.status(status).json({
|
||||
statusCode: status,
|
||||
error: 'Delete Operation Failed',
|
||||
message: exception.message,
|
||||
timestamp: new Date().toISOString(),
|
||||
type: 'DELETE_CONSTRAINT_VIOLATION',
|
||||
userFriendly: true,
|
||||
details: {
|
||||
canRetry: true,
|
||||
action: 'RESOLVE_DEPENDENCIES',
|
||||
hint: 'Please resolve the listed dependencies and try again.'
|
||||
}
|
||||
});
|
||||
} else if (exception instanceof HttpException) {
|
||||
// Handle other HTTP exceptions normally
|
||||
const exceptionResponse = exception.getResponse();
|
||||
|
||||
response.status(status).json({
|
||||
statusCode: status,
|
||||
timestamp: new Date().toISOString(),
|
||||
...(typeof exceptionResponse === 'object'
|
||||
? exceptionResponse
|
||||
: { message: exceptionResponse }
|
||||
)
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { BadRequestException } from '@nestjs/common';
|
||||
|
||||
export interface DeleteConstraint {
|
||||
entityName: string;
|
||||
count: number;
|
||||
action: 'delete' | 'reassign' | 'cancel' | 'complete';
|
||||
}
|
||||
|
||||
export class DeleteOperationException extends BadRequestException {
|
||||
constructor(
|
||||
entityType: string,
|
||||
entityName: string,
|
||||
constraints: DeleteConstraint[]
|
||||
) {
|
||||
const message = DeleteOperationException.buildUserFriendlyMessage(
|
||||
entityType,
|
||||
entityName,
|
||||
constraints
|
||||
);
|
||||
super(message);
|
||||
}
|
||||
|
||||
private static buildUserFriendlyMessage(
|
||||
entityType: string,
|
||||
entityName: string,
|
||||
constraints: DeleteConstraint[]
|
||||
): string {
|
||||
const baseMessage = `Cannot delete ${entityType.toLowerCase()} "${entityName}".`;
|
||||
|
||||
if (constraints.length === 0) {
|
||||
return `${baseMessage} Unknown constraint violation.`;
|
||||
}
|
||||
|
||||
const constraintMessages = constraints.map(constraint => {
|
||||
const { entityName: constraintEntity, count, action } = constraint;
|
||||
|
||||
const entityDisplayName = count === 1
|
||||
? constraintEntity.toLowerCase()
|
||||
: `${constraintEntity.toLowerCase()}s`;
|
||||
|
||||
const actionText = this.getActionText(action, count);
|
||||
|
||||
return `• ${count} ${entityDisplayName} ${count === 1 ? 'is' : 'are'} still ${this.getStatusText(constraintEntity)}. Please ${actionText} first.`;
|
||||
});
|
||||
|
||||
return [
|
||||
baseMessage,
|
||||
'',
|
||||
'The following dependencies must be resolved:',
|
||||
...constraintMessages,
|
||||
'',
|
||||
'Once all dependencies are resolved, you can retry the deletion.'
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
private static getActionText(action: string, count: number): string {
|
||||
const actions: Record<string, string> = {
|
||||
delete: count === 1 ? 'delete it' : 'delete them',
|
||||
reassign: count === 1 ? 'reassign it' : 'reassign them',
|
||||
cancel: count === 1 ? 'cancel it' : 'cancel them',
|
||||
complete: count === 1 ? 'complete it' : 'complete them'
|
||||
};
|
||||
return actions[action] || (count === 1 ? 'resolve it' : 'resolve them');
|
||||
}
|
||||
|
||||
private static getStatusText(entityName: string): string {
|
||||
const statusTexts: Record<string, string> = {
|
||||
booking: 'active',
|
||||
schedule: 'in use',
|
||||
coach: 'assigned',
|
||||
seat: 'occupied or blocked',
|
||||
'seat class': 'in use by fare rules',
|
||||
'coach type': 'in use by coaches or seat classes',
|
||||
train: 'scheduled',
|
||||
ticket: 'issued',
|
||||
'payment record': 'linked',
|
||||
'fare rule': 'active',
|
||||
route: 'in use by schedules',
|
||||
passenger: 'active with bookings or accounts',
|
||||
promotion: 'active',
|
||||
station: 'in use by routes'
|
||||
};
|
||||
return statusTexts[entityName.toLowerCase()] || 'in use';
|
||||
}
|
||||
}
|
||||
2
apps/edr-passenger-api/src/common/exceptions/index.ts
Normal file
2
apps/edr-passenger-api/src/common/exceptions/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export { DeleteOperationException, DeleteConstraint } from './delete-operation.exception';
|
||||
export { DeleteExceptionFilter } from './delete-exception.filter';
|
||||
33
apps/edr-passenger-api/src/common/iam.guard.ts
Normal file
33
apps/edr-passenger-api/src/common/iam.guard.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { Injectable, CanActivate, ExecutionContext, UnauthorizedException } from '@nestjs/common';
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
@Injectable()
|
||||
export class IamGuard implements CanActivate {
|
||||
canActivate(
|
||||
context: ExecutionContext,
|
||||
): boolean | Promise<boolean> | Observable<boolean> {
|
||||
const request = context.switchToHttp().getRequest();
|
||||
const authHeader = request.headers.authorization;
|
||||
|
||||
if (!authHeader || !authHeader.startsWith('Bearer ')) {
|
||||
throw new UnauthorizedException('No IAM token provided');
|
||||
}
|
||||
|
||||
const token = authHeader.substring(7);
|
||||
|
||||
// TODO: Implement actual IAM token validation
|
||||
// For now, just check if token exists
|
||||
if (!token) {
|
||||
throw new UnauthorizedException('Invalid IAM token');
|
||||
}
|
||||
|
||||
// Add user info to request for downstream usage
|
||||
request.user = {
|
||||
id: 'iam-user-id',
|
||||
roles: ['AGENT'],
|
||||
permissions: []
|
||||
};
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
137
apps/edr-passenger-api/src/common/utils/timezone.utils.ts
Normal file
137
apps/edr-passenger-api/src/common/utils/timezone.utils.ts
Normal file
@@ -0,0 +1,137 @@
|
||||
/**
|
||||
* Timezone Utility for Ethiopian Railway
|
||||
*
|
||||
* All dates/times in the system are stored and handled in Ethiopian Time (EAT - UTC+3).
|
||||
* This utility ensures consistent date handling across the application.
|
||||
*
|
||||
* IMPORTANT: The application timezone is set to 'Africa/Addis_Ababa' in main.ts
|
||||
*/
|
||||
|
||||
/**
|
||||
* Parse a date string or Date object ensuring it's treated as Ethiopian time (EAT - UTC+3)
|
||||
*
|
||||
* @param dateInput - ISO string, date string, or Date object
|
||||
* @returns Date object in Ethiopian time
|
||||
*
|
||||
* @example
|
||||
* parseEthiopianTime('2026-06-15T08:00:00') // Treats as 08:00 EAT, not UTC
|
||||
* parseEthiopianTime('2026-06-15') // Treats as midnight EAT
|
||||
*/
|
||||
export function parseEthiopianTime(dateInput: string | Date): Date {
|
||||
if (dateInput instanceof Date) {
|
||||
return dateInput;
|
||||
}
|
||||
|
||||
// Parse as local time (EAT) since TZ is set to Africa/Addis_Ababa
|
||||
return new Date(dateInput);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the start of day (00:00:00) in Ethiopian time
|
||||
*
|
||||
* @param date - Date object or date string
|
||||
* @returns Date object set to midnight EAT
|
||||
*/
|
||||
export function startOfDayEAT(date: Date | string): Date {
|
||||
const d = typeof date === 'string' ? new Date(date) : new Date(date);
|
||||
d.setHours(0, 0, 0, 0);
|
||||
return d;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the end of day (23:59:59.999) in Ethiopian time
|
||||
*
|
||||
* @param date - Date object or date string
|
||||
* @returns Date object set to end of day EAT
|
||||
*/
|
||||
export function endOfDayEAT(date: Date | string): Date {
|
||||
const d = typeof date === 'string' ? new Date(date) : new Date(date);
|
||||
d.setHours(23, 59, 59, 999);
|
||||
return d;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the start of the next day in Ethiopian time
|
||||
*
|
||||
* @param date - Date object or date string
|
||||
* @returns Date object set to midnight of next day EAT
|
||||
*/
|
||||
export function startOfNextDayEAT(date: Date | string): Date {
|
||||
const d = startOfDayEAT(date);
|
||||
d.setDate(d.getDate() + 1);
|
||||
return d;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format a date for display in Ethiopian time
|
||||
*
|
||||
* @param date - Date object
|
||||
* @param options - Intl.DateTimeFormatOptions
|
||||
* @returns Formatted date string
|
||||
*/
|
||||
export function formatEthiopianTime(
|
||||
date: Date,
|
||||
options: Intl.DateTimeFormatOptions = {
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
hour12: false,
|
||||
}
|
||||
): string {
|
||||
return new Intl.DateTimeFormat('en-ET', {
|
||||
...options,
|
||||
timeZone: 'Africa/Addis_Ababa',
|
||||
}).format(date);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add minutes to a date
|
||||
*
|
||||
* @param date - Date object
|
||||
* @param minutes - Number of minutes to add
|
||||
* @returns New Date object
|
||||
*/
|
||||
export function addMinutes(date: Date, minutes: number): Date {
|
||||
return new Date(date.getTime() + minutes * 60_000);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add hours to a date
|
||||
*
|
||||
* @param date - Date object
|
||||
* @param hours - Number of hours to add
|
||||
* @returns New Date object
|
||||
*/
|
||||
export function addHours(date: Date, hours: number): Date {
|
||||
return new Date(date.getTime() + hours * 60 * 60_000);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add days to a date
|
||||
*
|
||||
* @param date - Date object
|
||||
* @param days - Number of days to add
|
||||
* @returns New Date object
|
||||
*/
|
||||
export function addDays(date: Date, days: number): Date {
|
||||
const result = new Date(date);
|
||||
result.setDate(result.getDate() + days);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if two dates are on the same day (Ethiopian time)
|
||||
*
|
||||
* @param date1 - First date
|
||||
* @param date2 - Second date
|
||||
* @returns true if both dates are on the same calendar day in EAT
|
||||
*/
|
||||
export function isSameDayEAT(date1: Date, date2: Date): boolean {
|
||||
return (
|
||||
date1.getFullYear() === date2.getFullYear() &&
|
||||
date1.getMonth() === date2.getMonth() &&
|
||||
date1.getDate() === date2.getDate()
|
||||
);
|
||||
}
|
||||
@@ -11,6 +11,9 @@ import { HttpExceptionFilter } from "./common/filters/http-exception.filter";
|
||||
import { ResponseTransformInterceptor } from "./common/interceptors/response-transform.interceptor";
|
||||
import { SessionActivityInterceptor } from "./common/interceptors/session-activity.interceptor";
|
||||
|
||||
// Set timezone to Africa/Addis_Ababa (EAT - UTC+3) for Ethiopian Railway operations
|
||||
process.env.TZ = 'Africa/Addis_Ababa';
|
||||
|
||||
async function bootstrap() {
|
||||
// rawBody: true buffers the unparsed request body onto req.rawBody so webhook handlers
|
||||
// (e.g. Waafi HMAC verification) can sign over the exact bytes the provider signed.
|
||||
@@ -44,6 +47,7 @@ async function bootstrap() {
|
||||
Enterprise-grade REST API for the Ethio-Djibouti Railway passenger booking and management platform. Built with NestJS, TypeScript, PostgreSQL, and Prisma ORM.
|
||||
|
||||
## Latest Updates
|
||||
- **Enhanced Module Coverage:** Complete API coverage with 25+ core modules including System Config, Excess Baggage, Packages, and comprehensive CRUD operations across all entities.
|
||||
- **Health Check Endpoints:** Three public probes added under \`/health\`. Liveness (\`GET /health\`), readiness with live DB ping (\`GET /health/ready\`), and app info (\`GET /health/info\`). All are exempt from rate limiting.
|
||||
- **Rate Limiting:** Global throttle enforced via ThrottlerGuard with three named tiers: auth (5 req/min on \`/auth\` and \`/fayda/verification\`), strict (20 req/min on \`/bookings\`, \`/passengers\`, \`/payments\`, \`/wallet\`), default (100 req/min everywhere else). Health probes, webhook handlers, and internal service endpoints are exempt.
|
||||
- **Boarding Pass on Gate Validation:** Every successful gate validation at \`POST /tickets/:ref/validate\` now automatically delivers a boarding pass to the passenger via email (full HTML with QR code, route, seat table) and SMS (compact text with ref, route, seats, barcode). The leg label (OUTBOUND, RETURN, LEG1, etc.) is included so passengers know which boarding it covers.
|
||||
@@ -313,10 +317,9 @@ Payment providers send notifications to:
|
||||
.addTag("Agents", "Counter booking, shift management, commission tracking, and reconciliation")
|
||||
.addTag("Excess Baggage", "IAM-protected agent/supervisor endpoints to log excess baggage charges, waive fees, resend payment links, and manage allowance rules per seat class. Public token-based endpoints let passengers self-pay outstanding charges.")
|
||||
.addTag("Packages", "Bundled travel packages with tiered pricing. Public endpoints for browsing and booking; JWT-authenticated endpoints for purchase history; IAM-protected endpoints for admin CRUD and tier management.")
|
||||
.addTag("Config", "System-wide configuration management including feature flags, maintenance modes, and operational parameters. IAM-protected endpoints for administrative control.")
|
||||
.addTag("Audit", "User activity logging, system changes, compliance tracking, and audit trails")
|
||||
.addTag("Passenger Auth", "Passenger registration, login, OTP, password reset, Fayda password setup, and profile management")
|
||||
.addTag("Booking", "Complete booking lifecycle: create, modify, cancel, guest checkout. Supports ONE_WAY | ROUND_TRIP | TRANSIT | ROUND_TRIP_TRANSIT booking types. returnLegStatus filter for round-trip no-show management")
|
||||
.addTag("Config", "System settings, feature flags, and configuration management")
|
||||
.addTag("Currencies", "Multi-currency support, exchange rates, and currency conversion")
|
||||
.addTag("Dashboard", "Home screen aggregations: trips, loyalty, wallet, notifications")
|
||||
.addTag("Fare Engine", "Distance-based fare calculation with age-based pricing and multi-currency")
|
||||
@@ -328,9 +331,10 @@ Payment providers send notifications to:
|
||||
.addTag("Live Tracking", "Real-time trip status, location updates, delays, and crowd signals")
|
||||
.addTag("Loyalty", "Points ledger, tier management (Bronze/Silver/Gold/Platinum), rewards")
|
||||
.addTag("Notifications", "Multi-channel delivery (email, SMS, push) and preference management. Boarding pass email+SMS sent automatically on gate validation.")
|
||||
.addTag("Configurable Fares", "Advanced fare management system with flexible configurations, rate rules, components, age-based pricing, and migration tools. Supports nationality-based rates, bed position pricing, and dynamic component calculations.")
|
||||
.addTag("Passenger Auth", "JWT-authenticated passenger login, profile, and session management")
|
||||
.addTag("Passengers", "Registration, Fayda verification, international passports, saved profiles. Rate limited: 20 req/min.")
|
||||
.addTag("Payment", "Telebirr, CBE Birr, Waafi, Card, Wallet payment processing and refunds. Rate limited: 20 req/min.")
|
||||
.addTag("Payment Webhooks", "Payment provider webhook handlers and transaction confirmation. Exempt from rate limiting.")
|
||||
.addTag("Promotions", "Promo codes, campaigns, discounts, and redemption tracking")
|
||||
.addTag("Reports", "Revenue analytics, occupancy reports, agent sales, and KPI dashboards")
|
||||
.addTag("Routes", "Route templates with ordered stops, fare rules, and baggage allowance")
|
||||
@@ -342,7 +346,6 @@ Payment providers send notifications to:
|
||||
.addTag("Stations", "Station directory, location data, baggage facilities, and amenities")
|
||||
.addTag("Support", "FAQ management, search, live chat conversations, and ticket resolution")
|
||||
.addTag("Tickets", "QR/barcode generation, gate validation with per-leg tracking (OUTBOUND/RETURN/LEG1/LEG2/OUTBOUND_LEG1/OUTBOUND_LEG2/RETURN_LEG1/RETURN_LEG2), audit trails. Boarding pass email+SMS sent automatically on every successful validation.")
|
||||
.addTag("Transit Stops", "Cross-border journey management, Dire Dawa hub, TRANSIT and ROUND_TRIP_TRANSIT bookings")
|
||||
.addTag("Wallet", "Balance management, top-ups, withdrawals, and transaction ledger. Rate limited: 20 req/min.")
|
||||
//.addServer('http://localhost:4000', 'Development')
|
||||
// .addServer("https://api.edr-platform.com", "Production")
|
||||
|
||||
@@ -10,6 +10,7 @@ import { VerifaydaService } from '../verifayda/verifayda.service';
|
||||
import { CurrencyService } from '../currency/currency.service';
|
||||
import { FareEngineService } from '../fare-engine/fare-engine.service';
|
||||
import { Currency, PassengerCategory, IdDocumentType } from '@prisma/client';
|
||||
import { DeleteOperationException } from '../../common/exceptions/delete-operation.exception';
|
||||
|
||||
function generateRef(): string {
|
||||
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
|
||||
@@ -277,6 +278,16 @@ export class BookingsService {
|
||||
return {
|
||||
items: items.map(booking => {
|
||||
const iam = booking.passenger?.iamUserId ? iamMap.get(booking.passenger.iamUserId) : undefined;
|
||||
// Build passenger list with categories
|
||||
const passengerDetails = booking.seats.map((s: any) => ({
|
||||
name: s.passengerName,
|
||||
category: s.passengerCategory // 'ADULT' or 'CHILD'
|
||||
}));
|
||||
// Get unique names with their categories
|
||||
const uniquePassengers = Array.from(
|
||||
new Map(passengerDetails.map(p => [p.name, p])).values()
|
||||
);
|
||||
|
||||
return {
|
||||
id: booking.id,
|
||||
bookingRef: booking.bookingRef,
|
||||
@@ -296,6 +307,7 @@ export class BookingsService {
|
||||
? { fullName: iam.name?.en ?? iam.name?.am ?? null, email: iam.email, phone: iam.phone_number }
|
||||
: null,
|
||||
passengerNames: [...new Set(booking.seats.map((s: any) => s.passengerName))],
|
||||
passengers: uniquePassengers, // Include category info
|
||||
schedule: {
|
||||
train: booking.schedule.train,
|
||||
originStation: booking.schedule.originStation,
|
||||
@@ -359,6 +371,24 @@ export class BookingsService {
|
||||
displayTotalMinor = await this.currencyService.convertAmount(fareCalculation.totalMinor, Currency.ETB, displayCurrency);
|
||||
}
|
||||
|
||||
// Track which child gets free fare (first child encountered)
|
||||
let freeChildUsed = false;
|
||||
const passengersWithFares = passengersData.map(p => {
|
||||
let fareMinor: number;
|
||||
if (p.category === PassengerCategory.ADULT) {
|
||||
fareMinor = fareCalculation.baseFareMinor;
|
||||
} else {
|
||||
// Child: first child is free, subsequent children pay full fare
|
||||
if (!freeChildUsed) {
|
||||
fareMinor = 0;
|
||||
freeChildUsed = true;
|
||||
} else {
|
||||
fareMinor = fareCalculation.baseFareMinor;
|
||||
}
|
||||
}
|
||||
return { ...p, fareMinor };
|
||||
});
|
||||
|
||||
const booking = await this.prisma.booking.create({
|
||||
data: {
|
||||
bookingRef: generateRef(),
|
||||
@@ -372,7 +402,7 @@ export class BookingsService {
|
||||
displayCurrency,
|
||||
displayTotalMinor,
|
||||
seats: {
|
||||
create: passengersData.map(p => ({
|
||||
create: passengersWithFares.map(p => ({
|
||||
seat: { connect: { id: p.seatId } },
|
||||
passengerName: p.passengerName,
|
||||
dateOfBirth: p.dateOfBirth,
|
||||
@@ -382,7 +412,7 @@ export class BookingsService {
|
||||
passportCountry: p.passportCountry,
|
||||
verifaydaVerified: p.verifaydaVerified,
|
||||
verifaydaData: p.verifaydaData,
|
||||
fareMinor: p.category === PassengerCategory.ADULT ? fareCalculation.baseFareMinor : (fareCalculation.paidChildrenCount > 0 ? fareCalculation.baseFareMinor : 0),
|
||||
fareMinor: p.fareMinor,
|
||||
displayCurrency
|
||||
}))
|
||||
}
|
||||
@@ -462,6 +492,37 @@ export class BookingsService {
|
||||
displayTotalMinor = await this.currencyService.convertAmount(totalMinor, Currency.ETB, displayCurrency);
|
||||
}
|
||||
|
||||
// Track which child gets free fare for outbound and return legs
|
||||
let outboundFreeChildUsed = false;
|
||||
let returnFreeChildUsed = false;
|
||||
const passengersWithFares = passengersData.map(p => {
|
||||
let outboundFareMinor: number;
|
||||
let returnFareMinor: number;
|
||||
|
||||
if (p.category === PassengerCategory.ADULT) {
|
||||
outboundFareMinor = outboundFare.baseFareMinor;
|
||||
returnFareMinor = returnFare.baseFareMinor;
|
||||
} else {
|
||||
// Child fare for outbound
|
||||
if (!outboundFreeChildUsed) {
|
||||
outboundFareMinor = 0;
|
||||
outboundFreeChildUsed = true;
|
||||
} else {
|
||||
outboundFareMinor = outboundFare.baseFareMinor;
|
||||
}
|
||||
|
||||
// Child fare for return
|
||||
if (!returnFreeChildUsed) {
|
||||
returnFareMinor = 0;
|
||||
returnFreeChildUsed = true;
|
||||
} else {
|
||||
returnFareMinor = returnFare.baseFareMinor;
|
||||
}
|
||||
}
|
||||
|
||||
return { ...p, outboundFareMinor, returnFareMinor };
|
||||
});
|
||||
|
||||
const booking = await this.prisma.booking.create({
|
||||
data: {
|
||||
bookingRef: generateRef(),
|
||||
@@ -482,7 +543,7 @@ export class BookingsService {
|
||||
returnLegStatus: 'NEITHER_USED',
|
||||
seats: {
|
||||
create: [
|
||||
...passengersData.map(p => ({
|
||||
...passengersWithFares.map(p => ({
|
||||
seat: { connect: { id: p.outboundSeatId } },
|
||||
leg: 1,
|
||||
scheduleId: dto.scheduleId,
|
||||
@@ -494,10 +555,10 @@ export class BookingsService {
|
||||
passportCountry: p.passportCountry,
|
||||
verifaydaVerified: p.verifaydaVerified,
|
||||
verifaydaData: p.verifaydaData,
|
||||
fareMinor: p.category === PassengerCategory.ADULT ? outboundFare.baseFareMinor : (outboundFare.paidChildrenCount > 0 ? outboundFare.baseFareMinor : 0),
|
||||
fareMinor: p.outboundFareMinor,
|
||||
displayCurrency,
|
||||
})),
|
||||
...passengersData.map(p => ({
|
||||
...passengersWithFares.map(p => ({
|
||||
seat: { connect: { id: p.returnSeatId } },
|
||||
leg: 2,
|
||||
scheduleId: dto.returnScheduleId,
|
||||
@@ -509,7 +570,7 @@ export class BookingsService {
|
||||
passportCountry: p.passportCountry,
|
||||
verifaydaVerified: p.verifaydaVerified,
|
||||
verifaydaData: p.verifaydaData,
|
||||
fareMinor: p.category === PassengerCategory.ADULT ? returnFare.baseFareMinor : (returnFare.paidChildrenCount > 0 ? returnFare.baseFareMinor : 0),
|
||||
fareMinor: p.returnFareMinor,
|
||||
displayCurrency,
|
||||
})),
|
||||
],
|
||||
@@ -606,6 +667,37 @@ export class BookingsService {
|
||||
? await this.currencyService.convertAmount(totalMinor, Currency.ETB, displayCurrency)
|
||||
: totalMinor;
|
||||
|
||||
// Track which child gets free fare for leg1 and leg2
|
||||
let leg1FreeChildUsed = false;
|
||||
let leg2FreeChildUsed = false;
|
||||
const passengersWithFares = passengersData.map(p => {
|
||||
let leg1FareMinor: number;
|
||||
let leg2FareMinor: number;
|
||||
|
||||
if (p.category === PassengerCategory.ADULT) {
|
||||
leg1FareMinor = leg1Fare.baseFareMinor;
|
||||
leg2FareMinor = leg2Fare.baseFareMinor;
|
||||
} else {
|
||||
// Child fare for leg1
|
||||
if (!leg1FreeChildUsed) {
|
||||
leg1FareMinor = 0;
|
||||
leg1FreeChildUsed = true;
|
||||
} else {
|
||||
leg1FareMinor = leg1Fare.baseFareMinor;
|
||||
}
|
||||
|
||||
// Child fare for leg2
|
||||
if (!leg2FreeChildUsed) {
|
||||
leg2FareMinor = 0;
|
||||
leg2FreeChildUsed = true;
|
||||
} else {
|
||||
leg2FareMinor = leg2Fare.baseFareMinor;
|
||||
}
|
||||
}
|
||||
|
||||
return { ...p, leg1FareMinor, leg2FareMinor };
|
||||
});
|
||||
|
||||
// Single booking — leg-1 seats at leg=1, leg-2 seats at leg=2
|
||||
const booking = await this.prisma.booking.create({
|
||||
data: {
|
||||
@@ -625,7 +717,7 @@ export class BookingsService {
|
||||
leg2SeatClassId,
|
||||
seats: {
|
||||
create: [
|
||||
...passengersData.map(p => ({
|
||||
...passengersWithFares.map(p => ({
|
||||
seat: { connect: { id: p.seatId } },
|
||||
leg: 1,
|
||||
scheduleId: dto.scheduleId,
|
||||
@@ -637,10 +729,10 @@ export class BookingsService {
|
||||
passportCountry: p.passportCountry,
|
||||
verifaydaVerified: p.verifaydaVerified,
|
||||
verifaydaData: p.verifaydaData,
|
||||
fareMinor: p.category === PassengerCategory.ADULT ? leg1Fare.baseFareMinor : (leg1Fare.paidChildrenCount > 0 ? leg1Fare.baseFareMinor : 0),
|
||||
fareMinor: p.leg1FareMinor,
|
||||
displayCurrency,
|
||||
})),
|
||||
...passengersData.map(p => ({
|
||||
...passengersWithFares.map(p => ({
|
||||
seat: { connect: { id: p.leg2SeatId ?? p.seatId } },
|
||||
leg: 2,
|
||||
scheduleId: dto.leg2ScheduleId,
|
||||
@@ -652,7 +744,7 @@ export class BookingsService {
|
||||
passportCountry: p.passportCountry,
|
||||
verifaydaVerified: p.verifaydaVerified,
|
||||
verifaydaData: p.verifaydaData,
|
||||
fareMinor: p.category === PassengerCategory.ADULT ? leg2Fare.baseFareMinor : (leg2Fare.paidChildrenCount > 0 ? leg2Fare.baseFareMinor : 0),
|
||||
fareMinor: p.leg2FareMinor,
|
||||
displayCurrency,
|
||||
})),
|
||||
],
|
||||
@@ -769,7 +861,32 @@ export class BookingsService {
|
||||
? await this.currencyService.convertAmount(totalMinor, Currency.ETB, displayCurrency)
|
||||
: totalMinor;
|
||||
|
||||
const makeSeat = (p: any, seatId: string, leg: number, scheduleId: string, fare: Awaited<ReturnType<BookingsService['calculateFare']>>) => ({
|
||||
// Track which child gets free fare for all 4 legs
|
||||
let obL1FreeChildUsed = false;
|
||||
let obL2FreeChildUsed = false;
|
||||
let retL1FreeChildUsed = false;
|
||||
let retL2FreeChildUsed = false;
|
||||
|
||||
const passengersWithFares = passengersData.map(p => {
|
||||
let obL1FareMinor: number, obL2FareMinor: number, retL1FareMinor: number, retL2FareMinor: number;
|
||||
|
||||
if (p.category === PassengerCategory.ADULT) {
|
||||
obL1FareMinor = obL1Fare.baseFareMinor;
|
||||
obL2FareMinor = obL2Fare.baseFareMinor;
|
||||
retL1FareMinor = retL1Fare.baseFareMinor;
|
||||
retL2FareMinor = retL2Fare.baseFareMinor;
|
||||
} else {
|
||||
// Child fares for each leg
|
||||
obL1FareMinor = !obL1FreeChildUsed ? (obL1FreeChildUsed = true, 0) : obL1Fare.baseFareMinor;
|
||||
obL2FareMinor = !obL2FreeChildUsed ? (obL2FreeChildUsed = true, 0) : obL2Fare.baseFareMinor;
|
||||
retL1FareMinor = !retL1FreeChildUsed ? (retL1FreeChildUsed = true, 0) : retL1Fare.baseFareMinor;
|
||||
retL2FareMinor = !retL2FreeChildUsed ? (retL2FreeChildUsed = true, 0) : retL2Fare.baseFareMinor;
|
||||
}
|
||||
|
||||
return { ...p, obL1FareMinor, obL2FareMinor, retL1FareMinor, retL2FareMinor };
|
||||
});
|
||||
|
||||
const makeSeat = (p: any, seatId: string, leg: number, scheduleId: string, fareMinor: number) => ({
|
||||
seat: { connect: { id: seatId } },
|
||||
leg,
|
||||
scheduleId,
|
||||
@@ -781,7 +898,7 @@ export class BookingsService {
|
||||
passportCountry: p.passportCountry,
|
||||
verifaydaVerified: p.verifaydaVerified,
|
||||
verifaydaData: p.verifaydaData,
|
||||
fareMinor: p.category === PassengerCategory.ADULT ? fare.baseFareMinor : (fare.paidChildrenCount > 0 ? fare.baseFareMinor : 0),
|
||||
fareMinor,
|
||||
displayCurrency,
|
||||
});
|
||||
|
||||
@@ -811,13 +928,13 @@ export class BookingsService {
|
||||
seats: {
|
||||
create: [
|
||||
// Outbound leg-1 (sequence 1)
|
||||
...passengersData.map(p => makeSeat(p, p.outboundSeatId, 1, dto.scheduleId, obL1Fare)),
|
||||
...passengersWithFares.map(p => makeSeat(p, p.outboundSeatId, 1, dto.scheduleId, p.obL1FareMinor)),
|
||||
// Outbound leg-2 (sequence 2)
|
||||
...passengersData.map(p => makeSeat(p, p.outboundLeg2SeatId ?? p.outboundSeatId, 2, dto.leg2ScheduleId!, obL2Fare)),
|
||||
...passengersWithFares.map(p => makeSeat(p, p.outboundLeg2SeatId ?? p.outboundSeatId, 2, dto.leg2ScheduleId!, p.obL2FareMinor)),
|
||||
// Return leg-1 (sequence 3)
|
||||
...passengersData.map(p => makeSeat(p, p.returnSeatId, 3, dto.returnScheduleId!, retL1Fare)),
|
||||
...passengersWithFares.map(p => makeSeat(p, p.returnSeatId, 3, dto.returnScheduleId!, p.retL1FareMinor)),
|
||||
// Return leg-2 (sequence 4)
|
||||
...passengersData.map(p => makeSeat(p, p.returnLeg2SeatId ?? p.returnSeatId, 4, dto.returnLeg2ScheduleId!, retL2Fare)),
|
||||
...passengersWithFares.map(p => makeSeat(p, p.returnLeg2SeatId ?? p.returnSeatId, 4, dto.returnLeg2ScheduleId!, p.retL2FareMinor)),
|
||||
],
|
||||
},
|
||||
} as any,
|
||||
@@ -1060,7 +1177,7 @@ export class BookingsService {
|
||||
include: {
|
||||
schedule: { include: { originStation: true, destinationStation: true, train: true } },
|
||||
seats: { include: { seat: { include: { coach: { include: { coachType: { include: { seatClasses: true } } } } } } } },
|
||||
paymentIntent: true, ticket: true,
|
||||
paymentIntent: true, tickets: { take: 1 },
|
||||
},
|
||||
});
|
||||
if (!booking) throw new NotFoundException('Booking not found');
|
||||
@@ -1077,14 +1194,14 @@ export class BookingsService {
|
||||
contactPhone: booking.contactPhone,
|
||||
createdAt: booking.createdAt,
|
||||
schedule: {
|
||||
id: booking.schedule.id,
|
||||
trainNumber: booking.schedule.train.number,
|
||||
trainName: booking.schedule.train.name,
|
||||
origin: { id: booking.schedule.originStation.id, name: booking.schedule.originStation.name, code: booking.schedule.originStation.code, city: booking.schedule.originStation.city },
|
||||
destination: { id: booking.schedule.destinationStation.id, name: booking.schedule.destinationStation.name, code: booking.schedule.destinationStation.code, city: booking.schedule.destinationStation.city },
|
||||
departureAt: booking.schedule.departureAt, arrivalAt: booking.schedule.arrivalAt,
|
||||
id: (booking as any).schedule.id,
|
||||
trainNumber: (booking as any).schedule.train.number,
|
||||
trainName: (booking as any).schedule.train.name,
|
||||
origin: { id: (booking as any).schedule.originStation.id, name: (booking as any).schedule.originStation.name, code: (booking as any).schedule.originStation.code, city: (booking as any).schedule.originStation.city },
|
||||
destination: { id: (booking as any).schedule.destinationStation.id, name: (booking as any).schedule.destinationStation.name, code: (booking as any).schedule.destinationStation.code, city: (booking as any).schedule.destinationStation.city },
|
||||
departureAt: (booking as any).schedule.departureAt, arrivalAt: (booking as any).schedule.arrivalAt,
|
||||
},
|
||||
passengers: booking.seats?.map((bs: any) => ({
|
||||
passengers: (booking as any).seats?.map((bs: any) => ({
|
||||
fullName: bs.passengerName,
|
||||
category: bs.passengerCategory,
|
||||
leg: bs.leg ?? 1,
|
||||
@@ -1098,8 +1215,8 @@ export class BookingsService {
|
||||
seatClass: bs.seat.coach.coachType?.seatClasses?.[0]?.name ?? null,
|
||||
},
|
||||
})),
|
||||
payment: booking.paymentIntent ? { method: booking.paymentIntent.method, status: booking.paymentIntent.status } : undefined,
|
||||
ticket: booking.ticket ? { id: booking.ticket.id, qrPayload: booking.ticket.qrPayload, barcodePayload: booking.ticket.barcodePayload, status: booking.ticket.status } : undefined,
|
||||
payment: (booking as any).paymentIntent ? { method: (booking as any).paymentIntent.method, status: (booking as any).paymentIntent.status } : undefined,
|
||||
ticket: (booking as any).tickets?.[0] ? { id: (booking as any).tickets[0].id, qrPayload: (booking as any).tickets[0].qrPayload, barcodePayload: (booking as any).tickets[0].barcodePayload, status: (booking as any).tickets[0].status } : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1153,6 +1270,12 @@ export class BookingsService {
|
||||
const booking = await this.prisma.booking.findUnique({ where: { id }, include: { seats: true } });
|
||||
if (!booking) throw new NotFoundException('Booking not found');
|
||||
|
||||
// Check usage before allowing deletion
|
||||
const usage = await this.checkBookingUsage(id);
|
||||
if (usage.isInUse && usage.constraints) {
|
||||
throw new DeleteOperationException('Booking', booking.bookingRef, usage.constraints);
|
||||
}
|
||||
|
||||
await this.seatsService.releaseSeats(booking.id);
|
||||
|
||||
await this.prisma.bookingSeat.deleteMany({ where: { bookingId: id } });
|
||||
@@ -1172,15 +1295,16 @@ export class BookingsService {
|
||||
this.prisma.bookingCancellation.count({ where: { bookingId: id } }),
|
||||
]);
|
||||
|
||||
const usage = [];
|
||||
if (ticketCount > 0) usage.push('Ticket(s)');
|
||||
if (paymentIntentCount > 0) usage.push('Payment record(s)');
|
||||
if (modificationsCount > 0) usage.push('Modification history');
|
||||
if (cancellationCount > 0) usage.push('Cancellation record(s)');
|
||||
const constraints = [];
|
||||
if (ticketCount > 0) constraints.push({ entityName: 'ticket', count: ticketCount, action: 'complete' as const });
|
||||
if (paymentIntentCount > 0) constraints.push({ entityName: 'payment record', count: paymentIntentCount, action: 'complete' as const });
|
||||
if (modificationsCount > 0) constraints.push({ entityName: 'modification record', count: modificationsCount, action: 'complete' as const });
|
||||
if (cancellationCount > 0) constraints.push({ entityName: 'cancellation record', count: cancellationCount, action: 'complete' as const });
|
||||
|
||||
return {
|
||||
isInUse: usage.length > 0,
|
||||
affectedModules: usage,
|
||||
isInUse: constraints.length > 0,
|
||||
affectedModules: constraints.map(c => `${c.count} ${c.entityName}${c.count > 1 ? 's' : ''}`),
|
||||
constraints
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -231,6 +231,9 @@ export class GuestBookingService {
|
||||
},
|
||||
});
|
||||
|
||||
// Save passenger details as traveler profiles
|
||||
await this.createTravelerProfiles(guestPassengerId, passengersData);
|
||||
|
||||
// Confirm seats
|
||||
await this.seatsService.confirmSeats(dto.passengers.map(p => p.seatId));
|
||||
this.eventEmitter.emit('booking.created', { booking });
|
||||
@@ -443,6 +446,8 @@ export class GuestBookingService {
|
||||
},
|
||||
});
|
||||
|
||||
await this.createTravelerProfiles(guestPassengerId, passengersData);
|
||||
|
||||
await Promise.all([
|
||||
this.seatsService.confirmSeats(outboundSeatIds),
|
||||
this.seatsService.confirmSeats(returnSeatIds),
|
||||
@@ -635,6 +640,8 @@ export class GuestBookingService {
|
||||
},
|
||||
});
|
||||
|
||||
await this.createTravelerProfiles(guestPassengerId, passengersData);
|
||||
|
||||
await Promise.all([
|
||||
this.seatsService.confirmSeats(dto.passengers.map(p => p.seatId)),
|
||||
this.seatsService.confirmSeats(dto.passengers.map(p => p.leg2SeatId!)),
|
||||
@@ -822,6 +829,8 @@ export class GuestBookingService {
|
||||
},
|
||||
});
|
||||
|
||||
await this.createTravelerProfiles(guestPassengerId, passengersData);
|
||||
|
||||
await Promise.all([
|
||||
this.seatsService.confirmSeats(dto.passengers.map(p => p.seatId)),
|
||||
this.seatsService.confirmSeats(dto.passengers.map(p => p.leg2SeatId!)),
|
||||
@@ -870,12 +879,44 @@ export class GuestBookingService {
|
||||
return { guestPassengerId: result.user.passengerId, iamUserId: result.user.iamUserId, createdAccount: true };
|
||||
}
|
||||
|
||||
// Create guest passenger with basic profile
|
||||
const guestPassenger = await this.prisma.passenger.create({ data: {} });
|
||||
await this.prisma.loyaltyAccount.create({ data: { passengerId: guestPassenger.id, pointsBalance: 0, tier: 'BRONZE' } });
|
||||
await this.prisma.walletAccount.create({ data: { passengerId: guestPassenger.id, balanceMinor: 0 } });
|
||||
|
||||
return { guestPassengerId: guestPassenger.id, iamUserId: null, createdAccount: false };
|
||||
}
|
||||
|
||||
private async createTravelerProfiles(passengerId: string, passengersData: any[]): Promise<void> {
|
||||
for (const passenger of passengersData) {
|
||||
let gender: string | null = null;
|
||||
if (passenger.verifaydaData && typeof passenger.verifaydaData === 'object') {
|
||||
gender = passenger.verifaydaData.gender || passenger.verifaydaData.Gender || null;
|
||||
}
|
||||
|
||||
await this.prisma.travelerProfile.create({
|
||||
data: {
|
||||
passengerId,
|
||||
fullName: passenger.passengerName,
|
||||
gender,
|
||||
dateOfBirth: passenger.dateOfBirth,
|
||||
nationalId: passenger.idDocumentType === IdDocumentType.NATIONAL_ID ? passenger.idDocumentNumber : null,
|
||||
relationship: 'self',
|
||||
notes: JSON.stringify({
|
||||
idDocumentType: passenger.idDocumentType,
|
||||
idDocumentNumber: passenger.idDocumentNumber,
|
||||
passportNumber: passenger.passportNumber,
|
||||
passportCountry: passenger.passportCountry,
|
||||
nationality: passenger.nationality,
|
||||
phone: passenger.phone,
|
||||
email: passenger.email,
|
||||
verifaydaVerified: passenger.verifaydaVerified,
|
||||
}),
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async getSavedPassengers(userId?: string, deviceId?: string): Promise<SavedPassengerProfileDto[]> {
|
||||
if (!userId && !deviceId) {
|
||||
throw new BadRequestException('Either userId or deviceId is required');
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
import { Body, Controller, Get, Post, Put, Delete, Param, UseGuards, Request, Query } from '@nestjs/common';
|
||||
import { ApiTags, ApiBearerAuth, ApiOperation, ApiResponse, ApiParam, ApiQuery } from '@nestjs/swagger';
|
||||
import { ConfigurableFareService } from './configurable-fare.service';
|
||||
import {
|
||||
CreateFareConfigurationDto,
|
||||
UpdateFareConfigurationDto,
|
||||
FareTestScenarioDto,
|
||||
FareCalculationResultDto,
|
||||
MigrateLegacyDto,
|
||||
CreateNewFormulaDto,
|
||||
ToggleFeatureDto
|
||||
} from './configurable-fare.dto';
|
||||
import { IamGuard } from '../../common/iam-adapter';
|
||||
import { Roles } from '../../common/roles.decorator';
|
||||
|
||||
@ApiTags('Configurable Fares')
|
||||
@Controller('admin/fare-configurations')
|
||||
@ApiBearerAuth('IAM-auth')
|
||||
@UseGuards(IamGuard)
|
||||
@Roles('ADMIN')
|
||||
export class ConfigurableFareController {
|
||||
constructor(private service: ConfigurableFareService) {}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: 'List all fare configurations' })
|
||||
@ApiResponse({ status: 200, description: 'List of all configurations with summary counts' })
|
||||
async getAllConfigurations() {
|
||||
return this.service.getAllConfigurations();
|
||||
}
|
||||
|
||||
@Post()
|
||||
@ApiOperation({ summary: 'Create new fare configuration' })
|
||||
@ApiResponse({ status: 201, description: 'Configuration created successfully' })
|
||||
@ApiResponse({ status: 400, description: 'Invalid configuration data' })
|
||||
async createConfiguration(
|
||||
@Body() dto: CreateFareConfigurationDto,
|
||||
@Request() req: any
|
||||
) {
|
||||
const createdBy = req.user?.id || req.user?.sub;
|
||||
return this.service.createConfiguration(dto, createdBy);
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
@ApiOperation({ summary: 'Get configuration details' })
|
||||
@ApiParam({ name: 'id', description: 'Configuration ID' })
|
||||
@ApiResponse({ status: 200, description: 'Configuration details with all rules' })
|
||||
@ApiResponse({ status: 404, description: 'Configuration not found' })
|
||||
async getConfigurationById(@Param('id') id: string) {
|
||||
return this.service.getConfigurationById(id);
|
||||
}
|
||||
|
||||
@Put(':id')
|
||||
@ApiOperation({ summary: 'Update configuration' })
|
||||
@ApiParam({ name: 'id', description: 'Configuration ID' })
|
||||
@ApiResponse({ status: 200, description: 'Configuration updated successfully' })
|
||||
@ApiResponse({ status: 404, description: 'Configuration not found' })
|
||||
async updateConfiguration(
|
||||
@Param('id') id: string,
|
||||
@Body() dto: UpdateFareConfigurationDto,
|
||||
@Request() req: any
|
||||
) {
|
||||
const updatedBy = req.user?.id || req.user?.sub;
|
||||
return this.service.updateConfiguration(id, dto, updatedBy);
|
||||
}
|
||||
|
||||
@Post(':id/activate')
|
||||
@ApiOperation({ summary: 'Activate configuration' })
|
||||
@ApiParam({ name: 'id', description: 'Configuration ID' })
|
||||
@ApiResponse({ status: 200, description: 'Configuration activated successfully' })
|
||||
@ApiResponse({ status: 404, description: 'Configuration not found' })
|
||||
async activateConfiguration(@Param('id') id: string, @Request() req: any) {
|
||||
const activatedBy = req.user?.id || req.user?.sub;
|
||||
return this.service.activateConfiguration(id, activatedBy);
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
@ApiOperation({ summary: 'Delete configuration' })
|
||||
@ApiParam({ name: 'id', description: 'Configuration ID' })
|
||||
@ApiResponse({ status: 200, description: 'Configuration deleted successfully' })
|
||||
@ApiResponse({ status: 404, description: 'Configuration not found' })
|
||||
@ApiResponse({ status: 409, description: 'Cannot delete active configuration' })
|
||||
async deleteConfiguration(@Param('id') id: string, @Request() req: any) {
|
||||
const deletedBy = req.user?.id || req.user?.sub;
|
||||
return this.service.deleteConfiguration(id, deletedBy);
|
||||
}
|
||||
|
||||
@Post(':id/test')
|
||||
@ApiOperation({ summary: 'Test fare calculation with configuration' })
|
||||
@ApiParam({ name: 'id', description: 'Configuration ID' })
|
||||
@ApiResponse({ status: 200, type: FareCalculationResultDto, description: 'Fare calculation result' })
|
||||
@ApiResponse({ status: 400, description: 'Invalid test scenario or missing rate rules' })
|
||||
async testConfiguration(
|
||||
@Param('id') id: string,
|
||||
@Body() scenario: FareTestScenarioDto
|
||||
): Promise<FareCalculationResultDto> {
|
||||
return this.service.testConfiguration(id, scenario);
|
||||
}
|
||||
|
||||
@Get(':id/audit')
|
||||
@ApiOperation({ summary: 'Get configuration audit trail' })
|
||||
@ApiParam({ name: 'id', description: 'Configuration ID' })
|
||||
@ApiResponse({ status: 200, description: 'Audit trail entries' })
|
||||
async getAuditTrail(@Param('id') id: string) {
|
||||
return this.service.getAuditTrail(id);
|
||||
}
|
||||
}
|
||||
|
||||
@ApiTags('Configurable Fares')
|
||||
@Controller('admin/fare-migration')
|
||||
@ApiBearerAuth('IAM-auth')
|
||||
@UseGuards(IamGuard)
|
||||
@Roles('ADMIN')
|
||||
export class FareMigrationController {
|
||||
constructor(private service: ConfigurableFareService) {}
|
||||
|
||||
@Post('migrate-legacy')
|
||||
@ApiOperation({ summary: 'Migrate existing fare rules to configurable system' })
|
||||
@ApiResponse({ status: 200, description: 'Migration completed successfully' })
|
||||
@ApiResponse({ status: 400, description: 'Migration failed' })
|
||||
async migrateLegacySystem(@Body() dto: MigrateLegacyDto) {
|
||||
return this.service.migrateLegacySystem(dto);
|
||||
}
|
||||
|
||||
@Post('create-new-formula')
|
||||
@ApiOperation({ summary: 'Create new formula configuration with defaults' })
|
||||
@ApiResponse({ status: 201, description: 'New formula configuration created' })
|
||||
async createNewFormulaConfiguration(@Body() dto: CreateNewFormulaDto) {
|
||||
return this.service.createNewFormulaConfiguration(dto);
|
||||
}
|
||||
|
||||
@Post('complete-setup')
|
||||
@ApiOperation({
|
||||
summary: 'Complete system setup (migrate + create + activate)',
|
||||
description: 'Performs full system migration and setup in one operation'
|
||||
})
|
||||
@ApiResponse({ status: 200, description: 'System setup completed successfully' })
|
||||
async completeSetup(@Body() body: { activateNewFormula?: boolean; enableFeature?: boolean }) {
|
||||
// Step 1: Migrate legacy system
|
||||
const migrationResult = await this.service.migrateLegacySystem({ dryRun: false });
|
||||
|
||||
// Step 2: Create new formula configuration
|
||||
const newConfig = await this.service.createNewFormulaConfiguration({
|
||||
name: 'Default System Configuration',
|
||||
description: 'System-generated configuration with optimal defaults',
|
||||
activateImmediately: body.activateNewFormula !== false
|
||||
});
|
||||
|
||||
// Step 3: Enable feature flag if requested
|
||||
if (body.enableFeature) {
|
||||
await this.service.toggleFeature({
|
||||
featureName: 'USE_CONFIGURABLE_FARES',
|
||||
enabled: true,
|
||||
config: { rollout_percentage: 100 }
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
migration: migrationResult,
|
||||
newConfiguration: newConfig,
|
||||
featureEnabled: body.enableFeature || false,
|
||||
message: 'System setup completed successfully'
|
||||
};
|
||||
}
|
||||
|
||||
@Get('status')
|
||||
@ApiOperation({ summary: 'Get migration and setup status' })
|
||||
@ApiResponse({ status: 200, description: 'Current system status' })
|
||||
async getStatus() {
|
||||
const featureStatus = await this.service.getFeatureStatus('USE_CONFIGURABLE_FARES');
|
||||
const configurations = await this.service.getAllConfigurations();
|
||||
|
||||
const activeConfig = (configurations as any[]).find(config => config.is_active);
|
||||
|
||||
return {
|
||||
configurableFaresEnabled: featureStatus.enabled,
|
||||
rolloutPercentage: featureStatus.config?.rollout_percentage || 0,
|
||||
totalConfigurations: (configurations as any[]).length,
|
||||
activeConfiguration: activeConfig?.id || null,
|
||||
activeConfigurationName: activeConfig?.name || null,
|
||||
systemReady: featureStatus.enabled && !!activeConfig
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@ApiTags('Configurable Fares')
|
||||
@Controller('admin/fare-configurations/system')
|
||||
@ApiBearerAuth('IAM-auth')
|
||||
@UseGuards(IamGuard)
|
||||
@Roles('ADMIN')
|
||||
export class FareSystemController {
|
||||
constructor(private service: ConfigurableFareService) {}
|
||||
|
||||
@Get('feature-status')
|
||||
@ApiOperation({ summary: 'Check configurable fares feature status' })
|
||||
@ApiQuery({ name: 'feature', required: false, description: 'Feature name (defaults to USE_CONFIGURABLE_FARES)' })
|
||||
@ApiResponse({ status: 200, description: 'Feature status retrieved' })
|
||||
async getFeatureStatus(@Query('feature') featureName = 'USE_CONFIGURABLE_FARES') {
|
||||
return this.service.getFeatureStatus(featureName);
|
||||
}
|
||||
|
||||
@Post('toggle-feature')
|
||||
@ApiOperation({ summary: 'Enable or disable configurable fares system' })
|
||||
@ApiResponse({ status: 200, description: 'Feature toggled successfully' })
|
||||
async toggleFeature(@Body() dto: ToggleFeatureDto) {
|
||||
return this.service.toggleFeature(dto);
|
||||
}
|
||||
|
||||
@Post('enable-configurable-fares')
|
||||
@ApiOperation({
|
||||
summary: 'Enable configurable fares with rollout percentage',
|
||||
description: 'Quick endpoint to enable the configurable fares feature'
|
||||
})
|
||||
@ApiResponse({ status: 200, description: 'Configurable fares enabled successfully' })
|
||||
async enableConfigurableFares(@Body() body: { rolloutPercentage?: number }) {
|
||||
return this.service.toggleFeature({
|
||||
featureName: 'USE_CONFIGURABLE_FARES',
|
||||
enabled: true,
|
||||
config: { rollout_percentage: body.rolloutPercentage || 100 }
|
||||
});
|
||||
}
|
||||
|
||||
@Post('disable-configurable-fares')
|
||||
@ApiOperation({
|
||||
summary: 'Disable configurable fares (fallback to legacy system)',
|
||||
description: 'Disables the configurable fares feature and falls back to legacy fare calculation'
|
||||
})
|
||||
@ApiResponse({ status: 200, description: 'Configurable fares disabled successfully' })
|
||||
async disableConfigurableFares() {
|
||||
return this.service.toggleFeature({
|
||||
featureName: 'USE_CONFIGURABLE_FARES',
|
||||
enabled: false,
|
||||
config: { rollout_percentage: 0 }
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,362 @@
|
||||
import { IsString, IsOptional, IsBoolean, IsInt, IsArray, ValidateNested, IsDateString, IsEnum, IsNumber, Min, Max } from 'class-validator';
|
||||
import { Type } from 'class-transformer';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
export enum NationalityType {
|
||||
LOCAL = 'LOCAL',
|
||||
INTERNATIONAL = 'INTERNATIONAL'
|
||||
}
|
||||
|
||||
export enum CoachType {
|
||||
REGULAR_SEAT = 'REGULAR_SEAT',
|
||||
ECONOMY_BED = 'ECONOMY_BED',
|
||||
VIP_BED = 'VIP_BED'
|
||||
}
|
||||
|
||||
export enum BedPosition {
|
||||
UPPER = 'UPPER',
|
||||
MIDDLE = 'MIDDLE',
|
||||
LOWER = 'LOWER'
|
||||
}
|
||||
|
||||
export enum ComponentType {
|
||||
INSURANCE = 'INSURANCE',
|
||||
PREMIUM = 'PREMIUM',
|
||||
SERVICE_CHARGE = 'SERVICE_CHARGE',
|
||||
TAX = 'TAX',
|
||||
DEMAND = 'DEMAND'
|
||||
}
|
||||
|
||||
export enum CalculationMethod {
|
||||
MULTIPLIER = 'MULTIPLIER',
|
||||
PERCENTAGE = 'PERCENTAGE',
|
||||
FIXED_AMOUNT = 'FIXED_AMOUNT'
|
||||
}
|
||||
|
||||
export enum AppliesTo {
|
||||
BASE_FARE = 'BASE_FARE',
|
||||
SUBTOTAL = 'SUBTOTAL',
|
||||
TOTAL = 'TOTAL'
|
||||
}
|
||||
|
||||
export enum PricingType {
|
||||
FREE = 'FREE',
|
||||
FULL_FARE = 'FULL_FARE',
|
||||
DISCOUNTED = 'DISCOUNTED'
|
||||
}
|
||||
|
||||
export class FareRateRuleDto {
|
||||
@ApiProperty({ enum: NationalityType })
|
||||
@IsEnum(NationalityType)
|
||||
nationalityType: NationalityType;
|
||||
|
||||
@ApiProperty({ enum: CoachType })
|
||||
@IsEnum(CoachType)
|
||||
coachType: CoachType;
|
||||
|
||||
@ApiPropertyOptional({ enum: BedPosition })
|
||||
@IsOptional()
|
||||
@IsEnum(BedPosition)
|
||||
bedPosition?: BedPosition;
|
||||
|
||||
@ApiProperty({ example: 3000, description: 'Rate per km in minor units (e.g., 30.00 ETB = 3000)' })
|
||||
@IsInt()
|
||||
@Min(0)
|
||||
ratePerKmMinor: number;
|
||||
|
||||
@ApiPropertyOptional({ default: true })
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
isActive?: boolean;
|
||||
}
|
||||
|
||||
export class FareComponentDto {
|
||||
@ApiProperty({ enum: ComponentType })
|
||||
@IsEnum(ComponentType)
|
||||
componentType: ComponentType;
|
||||
|
||||
@ApiProperty({ example: 'Travel Insurance' })
|
||||
@IsString()
|
||||
componentName: string;
|
||||
|
||||
@ApiProperty({ enum: CalculationMethod })
|
||||
@IsEnum(CalculationMethod)
|
||||
calculationMethod: CalculationMethod;
|
||||
|
||||
@ApiPropertyOptional({ example: 500, description: 'Fixed amount in minor units' })
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(0)
|
||||
valueMinor?: number;
|
||||
|
||||
@ApiPropertyOptional({ example: 0.02, description: 'Percentage value (e.g., 0.02 for 2%)' })
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Min(0)
|
||||
@Max(1)
|
||||
percentageValue?: number;
|
||||
|
||||
@ApiProperty({ enum: AppliesTo, default: AppliesTo.SUBTOTAL })
|
||||
@IsEnum(AppliesTo)
|
||||
appliesTo: AppliesTo;
|
||||
|
||||
@ApiProperty({ example: 1, description: 'Order of application' })
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
applyOrder: number;
|
||||
|
||||
@ApiPropertyOptional({ default: true })
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
isActive?: boolean;
|
||||
}
|
||||
|
||||
export class AgePricingRuleDto {
|
||||
@ApiProperty({ example: 'Adult Passengers' })
|
||||
@IsString()
|
||||
ruleName: string;
|
||||
|
||||
@ApiProperty({ example: 5 })
|
||||
@IsInt()
|
||||
@Min(0)
|
||||
minAge: number;
|
||||
|
||||
@ApiPropertyOptional({ example: 120 })
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(0)
|
||||
maxAge?: number;
|
||||
|
||||
@ApiProperty({ enum: PricingType })
|
||||
@IsEnum(PricingType)
|
||||
pricingType: PricingType;
|
||||
|
||||
@ApiPropertyOptional({ example: 0.5, description: 'Discount percentage for DISCOUNTED type' })
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Min(0)
|
||||
@Max(1)
|
||||
discountPercentage?: number;
|
||||
|
||||
@ApiPropertyOptional({ example: 1, description: 'Max free passengers for FREE type' })
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(0)
|
||||
maxFreePassengers?: number;
|
||||
|
||||
@ApiPropertyOptional({ default: false })
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
appliesToComponents?: boolean;
|
||||
|
||||
@ApiPropertyOptional({ default: true })
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
isActive?: boolean;
|
||||
}
|
||||
|
||||
export class CreateFareConfigurationDto {
|
||||
@ApiProperty({ example: 'Summer 2024 Rates' })
|
||||
@IsString()
|
||||
name: string;
|
||||
|
||||
@ApiPropertyOptional({ example: 'Updated rates for summer season' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
description?: string;
|
||||
|
||||
@ApiProperty({ example: '2024-06-01T00:00:00.000Z' })
|
||||
@IsDateString()
|
||||
effectiveDate: string;
|
||||
|
||||
@ApiPropertyOptional({ example: '2024-08-31T23:59:59.000Z' })
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
expiryDate?: string;
|
||||
|
||||
@ApiProperty({ type: [FareRateRuleDto] })
|
||||
@IsArray()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => FareRateRuleDto)
|
||||
rateRules: FareRateRuleDto[];
|
||||
|
||||
@ApiProperty({ type: [FareComponentDto] })
|
||||
@IsArray()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => FareComponentDto)
|
||||
components: FareComponentDto[];
|
||||
|
||||
@ApiProperty({ type: [AgePricingRuleDto] })
|
||||
@IsArray()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => AgePricingRuleDto)
|
||||
ageRules: AgePricingRuleDto[];
|
||||
|
||||
@ApiPropertyOptional({ default: false })
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
isDefault?: boolean;
|
||||
}
|
||||
|
||||
export class UpdateFareConfigurationDto {
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
name?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
description?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
effectiveDate?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
expiryDate?: string;
|
||||
|
||||
@ApiPropertyOptional({ type: [FareRateRuleDto] })
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => FareRateRuleDto)
|
||||
rateRules?: FareRateRuleDto[];
|
||||
|
||||
@ApiPropertyOptional({ type: [FareComponentDto] })
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => FareComponentDto)
|
||||
components?: FareComponentDto[];
|
||||
|
||||
@ApiPropertyOptional({ type: [AgePricingRuleDto] })
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => AgePricingRuleDto)
|
||||
ageRules?: AgePricingRuleDto[];
|
||||
}
|
||||
|
||||
export class FareTestScenarioDto {
|
||||
@ApiProperty({ example: 100 })
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
distanceKm: number;
|
||||
|
||||
@ApiProperty({ example: 'Ethiopian' })
|
||||
@IsString()
|
||||
nationality: string;
|
||||
|
||||
@ApiProperty({ enum: CoachType })
|
||||
@IsEnum(CoachType)
|
||||
coachType: CoachType;
|
||||
|
||||
@ApiPropertyOptional({ enum: BedPosition })
|
||||
@IsOptional()
|
||||
@IsEnum(BedPosition)
|
||||
bedPosition?: BedPosition;
|
||||
|
||||
@ApiProperty({ example: 2, default: 1 })
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
adultCount: number;
|
||||
|
||||
@ApiPropertyOptional({ example: 1, default: 0 })
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(0)
|
||||
childCount?: number;
|
||||
|
||||
@ApiPropertyOptional({ example: 'SUMMER20' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
promoCode?: string;
|
||||
|
||||
@ApiPropertyOptional({ example: 500 })
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(0)
|
||||
loyaltyPoints?: number;
|
||||
}
|
||||
|
||||
export class FareCalculationResultDto {
|
||||
@ApiProperty()
|
||||
baseFareMinor: number;
|
||||
|
||||
@ApiProperty()
|
||||
componentsTotal: number;
|
||||
|
||||
@ApiProperty()
|
||||
totalBeforeDiscounts: number;
|
||||
|
||||
@ApiProperty()
|
||||
discountsTotal: number;
|
||||
|
||||
@ApiProperty()
|
||||
finalTotalMinor: number;
|
||||
|
||||
@ApiProperty()
|
||||
breakdown: Array<{
|
||||
step: string;
|
||||
description: string;
|
||||
amount: number;
|
||||
runningTotal: number;
|
||||
}>;
|
||||
|
||||
@ApiProperty()
|
||||
currency: string;
|
||||
|
||||
@ApiProperty()
|
||||
calculationTimestamp: Date;
|
||||
}
|
||||
|
||||
export class MigrateLegacyDto {
|
||||
@ApiPropertyOptional({ default: false })
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
dryRun?: boolean;
|
||||
|
||||
@ApiPropertyOptional({ default: true })
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
migrateScheduleFares?: boolean;
|
||||
|
||||
@ApiPropertyOptional({ default: true })
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
migrateSegmentFares?: boolean;
|
||||
}
|
||||
|
||||
export class CreateNewFormulaDto {
|
||||
@ApiProperty({ example: 'Default Formula Configuration' })
|
||||
@IsString()
|
||||
name: string;
|
||||
|
||||
@ApiPropertyOptional({ example: 'System-generated default configuration' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
description?: string;
|
||||
|
||||
@ApiPropertyOptional({ default: true })
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
activateImmediately?: boolean;
|
||||
}
|
||||
|
||||
export class ToggleFeatureDto {
|
||||
@ApiProperty({ example: 'USE_CONFIGURABLE_FARES' })
|
||||
@IsString()
|
||||
featureName: string;
|
||||
|
||||
@ApiProperty()
|
||||
@IsBoolean()
|
||||
enabled: boolean;
|
||||
|
||||
@ApiPropertyOptional({ example: { rollout_percentage: 50 } })
|
||||
@IsOptional()
|
||||
config?: Record<string, any>;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigurableFareService } from './configurable-fare.service';
|
||||
import { ConfigurableFareController, FareMigrationController, FareSystemController } from './configurable-fare.controller';
|
||||
import { PrismaModule } from '../../common/prisma.module';
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule],
|
||||
controllers: [ConfigurableFareController, FareMigrationController, FareSystemController],
|
||||
providers: [ConfigurableFareService],
|
||||
exports: [ConfigurableFareService],
|
||||
})
|
||||
export class ConfigurableFareModule {}
|
||||
@@ -0,0 +1,623 @@
|
||||
import { Injectable, BadRequestException, NotFoundException, ConflictException } from '@nestjs/common';
|
||||
import { PrismaService } from '../../common/prisma.service';
|
||||
import {
|
||||
CreateFareConfigurationDto,
|
||||
UpdateFareConfigurationDto,
|
||||
FareTestScenarioDto,
|
||||
FareCalculationResultDto,
|
||||
MigrateLegacyDto,
|
||||
CreateNewFormulaDto,
|
||||
ToggleFeatureDto,
|
||||
NationalityType,
|
||||
CoachType,
|
||||
BedPosition,
|
||||
ComponentType,
|
||||
CalculationMethod,
|
||||
AppliesTo,
|
||||
PricingType
|
||||
} from './configurable-fare.dto';
|
||||
|
||||
@Injectable()
|
||||
export class ConfigurableFareService {
|
||||
constructor(private prisma: PrismaService) {}
|
||||
|
||||
// Helper method to map nationality to type
|
||||
private mapNationalityToType(nationality: string): NationalityType {
|
||||
const upperNationality = nationality.toUpperCase();
|
||||
if (upperNationality === 'ETHIOPIAN' || upperNationality === 'DJIBOUTIAN') {
|
||||
return NationalityType.LOCAL;
|
||||
}
|
||||
return NationalityType.INTERNATIONAL;
|
||||
}
|
||||
|
||||
// Generate unique IDs
|
||||
private generateId(prefix: string): string {
|
||||
return `${prefix}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
|
||||
}
|
||||
|
||||
// Configuration Management
|
||||
async getAllConfigurations() {
|
||||
return this.prisma.$queryRaw`
|
||||
SELECT
|
||||
fc.*,
|
||||
COUNT(DISTINCT frr.id) as rate_rules_count,
|
||||
COUNT(DISTINCT fcmp.id) as components_count,
|
||||
COUNT(DISTINCT apr.id) as age_rules_count
|
||||
FROM fare_configurations fc
|
||||
LEFT JOIN fare_rate_rules frr ON fc.id = frr.fare_config_id AND frr.is_active = true
|
||||
LEFT JOIN fare_components fcmp ON fc.id = fcmp.fare_config_id AND fcmp.is_active = true
|
||||
LEFT JOIN age_pricing_rules apr ON fc.id = apr.fare_config_id AND apr.is_active = true
|
||||
GROUP BY fc.id, fc.name, fc.description, fc.effective_date, fc.expiry_date,
|
||||
fc.is_active, fc.is_default, fc.created_by, fc.approved_by,
|
||||
fc.approved_at, fc.created_at, fc.updated_at
|
||||
ORDER BY fc.created_at DESC
|
||||
`;
|
||||
}
|
||||
|
||||
async getConfigurationById(id: string) {
|
||||
const config = await this.prisma.$queryRaw`
|
||||
SELECT * FROM fare_configurations WHERE id = ${id}
|
||||
`;
|
||||
|
||||
if (!Array.isArray(config) || config.length === 0) {
|
||||
throw new NotFoundException(`Fare configuration ${id} not found`);
|
||||
}
|
||||
|
||||
const rateRules = await this.prisma.$queryRaw`
|
||||
SELECT * FROM fare_rate_rules WHERE fare_config_id = ${id} ORDER BY nationality_type, coach_type, bed_position
|
||||
`;
|
||||
|
||||
const components = await this.prisma.$queryRaw`
|
||||
SELECT * FROM fare_components WHERE fare_config_id = ${id} ORDER BY apply_order
|
||||
`;
|
||||
|
||||
const ageRules = await this.prisma.$queryRaw`
|
||||
SELECT * FROM age_pricing_rules WHERE fare_config_id = ${id} ORDER BY min_age
|
||||
`;
|
||||
|
||||
return {
|
||||
...config[0],
|
||||
rateRules,
|
||||
components,
|
||||
ageRules
|
||||
};
|
||||
}
|
||||
|
||||
async createConfiguration(dto: CreateFareConfigurationDto, createdBy?: string) {
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
const configId = this.generateId('fc');
|
||||
|
||||
// Validate no overlapping active configurations
|
||||
if (dto.isDefault) {
|
||||
await tx.$executeRaw`
|
||||
UPDATE fare_configurations SET is_default = false WHERE is_default = true
|
||||
`;
|
||||
}
|
||||
|
||||
// Create main configuration
|
||||
await tx.$executeRaw`
|
||||
INSERT INTO fare_configurations (
|
||||
id, name, description, effective_date, expiry_date,
|
||||
is_active, is_default, created_by, created_at, updated_at
|
||||
) VALUES (
|
||||
${configId}, ${dto.name}, ${dto.description}, ${dto.effectiveDate},
|
||||
${dto.expiryDate}, false, ${dto.isDefault || false}, ${createdBy},
|
||||
NOW(), NOW()
|
||||
)
|
||||
`;
|
||||
|
||||
// Create rate rules
|
||||
for (const rule of dto.rateRules) {
|
||||
const ruleId = this.generateId('frr');
|
||||
await tx.$executeRaw`
|
||||
INSERT INTO fare_rate_rules (
|
||||
id, fare_config_id, nationality_type, coach_type, bed_position,
|
||||
rate_per_km_minor, is_active, created_at, updated_at
|
||||
) VALUES (
|
||||
${ruleId}, ${configId}, ${rule.nationalityType}, ${rule.coachType},
|
||||
${rule.bedPosition || null}, ${rule.ratePerKmMinor}, ${rule.isActive !== false},
|
||||
NOW(), NOW()
|
||||
)
|
||||
`;
|
||||
}
|
||||
|
||||
// Create components
|
||||
for (const component of dto.components) {
|
||||
const componentId = this.generateId('fcmp');
|
||||
await tx.$executeRaw`
|
||||
INSERT INTO fare_components (
|
||||
id, fare_config_id, component_type, component_name, calculation_method,
|
||||
value_minor, percentage_value, applies_to, apply_order, is_active,
|
||||
created_at, updated_at
|
||||
) VALUES (
|
||||
${componentId}, ${configId}, ${component.componentType}, ${component.componentName},
|
||||
${component.calculationMethod}, ${component.valueMinor || null},
|
||||
${component.percentageValue || null}, ${component.appliesTo},
|
||||
${component.applyOrder}, ${component.isActive !== false}, NOW(), NOW()
|
||||
)
|
||||
`;
|
||||
}
|
||||
|
||||
// Create age rules
|
||||
for (const ageRule of dto.ageRules) {
|
||||
const ageRuleId = this.generateId('apr');
|
||||
await tx.$executeRaw`
|
||||
INSERT INTO age_pricing_rules (
|
||||
id, fare_config_id, rule_name, min_age, max_age, pricing_type,
|
||||
discount_percentage, max_free_passengers, applies_to_components,
|
||||
is_active, created_at, updated_at
|
||||
) VALUES (
|
||||
${ageRuleId}, ${configId}, ${ageRule.ruleName}, ${ageRule.minAge},
|
||||
${ageRule.maxAge || null}, ${ageRule.pricingType},
|
||||
${ageRule.discountPercentage || null}, ${ageRule.maxFreePassengers || null},
|
||||
${ageRule.appliesToComponents !== false}, ${ageRule.isActive !== false},
|
||||
NOW(), NOW()
|
||||
)
|
||||
`;
|
||||
}
|
||||
|
||||
// Log audit entry
|
||||
await this.createAuditEntry(tx, configId, 'CREATED', createdBy, { action: 'Configuration created' });
|
||||
|
||||
return this.getConfigurationById(configId);
|
||||
});
|
||||
}
|
||||
|
||||
async updateConfiguration(id: string, dto: UpdateFareConfigurationDto, updatedBy?: string) {
|
||||
await this.getConfigurationById(id); // Validate exists
|
||||
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
// Update main configuration
|
||||
if (dto.name || dto.description !== undefined || dto.effectiveDate || dto.expiryDate !== undefined) {
|
||||
await tx.$executeRaw`
|
||||
UPDATE fare_configurations
|
||||
SET
|
||||
name = COALESCE(${dto.name}, name),
|
||||
description = COALESCE(${dto.description}, description),
|
||||
effective_date = COALESCE(${dto.effectiveDate}, effective_date),
|
||||
expiry_date = COALESCE(${dto.expiryDate}, expiry_date),
|
||||
updated_at = NOW()
|
||||
WHERE id = ${id}
|
||||
`;
|
||||
}
|
||||
|
||||
// Update rate rules if provided
|
||||
if (dto.rateRules) {
|
||||
await tx.$executeRaw`DELETE FROM fare_rate_rules WHERE fare_config_id = ${id}`;
|
||||
|
||||
for (const rule of dto.rateRules) {
|
||||
const ruleId = this.generateId('frr');
|
||||
await tx.$executeRaw`
|
||||
INSERT INTO fare_rate_rules (
|
||||
id, fare_config_id, nationality_type, coach_type, bed_position,
|
||||
rate_per_km_minor, is_active, created_at, updated_at
|
||||
) VALUES (
|
||||
${ruleId}, ${id}, ${rule.nationalityType}, ${rule.coachType},
|
||||
${rule.bedPosition || null}, ${rule.ratePerKmMinor}, ${rule.isActive !== false},
|
||||
NOW(), NOW()
|
||||
)
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
// Update components if provided
|
||||
if (dto.components) {
|
||||
await tx.$executeRaw`DELETE FROM fare_components WHERE fare_config_id = ${id}`;
|
||||
|
||||
for (const component of dto.components) {
|
||||
const componentId = this.generateId('fcmp');
|
||||
await tx.$executeRaw`
|
||||
INSERT INTO fare_components (
|
||||
id, fare_config_id, component_type, component_name, calculation_method,
|
||||
value_minor, percentage_value, applies_to, apply_order, is_active,
|
||||
created_at, updated_at
|
||||
) VALUES (
|
||||
${componentId}, ${id}, ${component.componentType}, ${component.componentName},
|
||||
${component.calculationMethod}, ${component.valueMinor || null},
|
||||
${component.percentageValue || null}, ${component.appliesTo},
|
||||
${component.applyOrder}, ${component.isActive !== false}, NOW(), NOW()
|
||||
)
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
// Update age rules if provided
|
||||
if (dto.ageRules) {
|
||||
await tx.$executeRaw`DELETE FROM age_pricing_rules WHERE fare_config_id = ${id}`;
|
||||
|
||||
for (const ageRule of dto.ageRules) {
|
||||
const ageRuleId = this.generateId('apr');
|
||||
await tx.$executeRaw`
|
||||
INSERT INTO age_pricing_rules (
|
||||
id, fare_config_id, rule_name, min_age, max_age, pricing_type,
|
||||
discount_percentage, max_free_passengers, applies_to_components,
|
||||
is_active, created_at, updated_at
|
||||
) VALUES (
|
||||
${ageRuleId}, ${id}, ${ageRule.ruleName}, ${ageRule.minAge},
|
||||
${ageRule.maxAge || null}, ${ageRule.pricingType},
|
||||
${ageRule.discountPercentage || null}, ${ageRule.maxFreePassengers || null},
|
||||
${ageRule.appliesToComponents !== false}, ${ageRule.isActive !== false},
|
||||
NOW(), NOW()
|
||||
)
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
await this.createAuditEntry(tx, id, 'UPDATED', updatedBy, { changes: dto });
|
||||
|
||||
return this.getConfigurationById(id);
|
||||
});
|
||||
}
|
||||
|
||||
async activateConfiguration(id: string, activatedBy?: string) {
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
// Deactivate all other configurations
|
||||
await tx.$executeRaw`UPDATE fare_configurations SET is_active = false`;
|
||||
|
||||
// Activate this one
|
||||
await tx.$executeRaw`
|
||||
UPDATE fare_configurations
|
||||
SET is_active = true, approved_by = ${activatedBy}, approved_at = NOW()
|
||||
WHERE id = ${id}
|
||||
`;
|
||||
|
||||
await this.createAuditEntry(tx, id, 'ACTIVATED', activatedBy, {});
|
||||
|
||||
return { success: true, message: `Configuration ${id} activated successfully` };
|
||||
});
|
||||
}
|
||||
|
||||
async deleteConfiguration(id: string, deletedBy?: string) {
|
||||
const config = await this.getConfigurationById(id);
|
||||
|
||||
if ((config as any).is_active) {
|
||||
throw new ConflictException('Cannot delete active configuration. Deactivate first.');
|
||||
}
|
||||
|
||||
await this.prisma.$executeRaw`DELETE FROM fare_configurations WHERE id = ${id}`;
|
||||
|
||||
return { success: true, message: `Configuration ${id} deleted successfully` };
|
||||
}
|
||||
|
||||
// Fare Calculation
|
||||
async testConfiguration(id: string, scenario: FareTestScenarioDto): Promise<FareCalculationResultDto> {
|
||||
const config = await this.getConfigurationById(id);
|
||||
|
||||
// Find matching rate rule
|
||||
const nationalityType = this.mapNationalityToType(scenario.nationality);
|
||||
|
||||
const rateRule = (config.rateRules as any[]).find((rule: any) =>
|
||||
rule.nationality_type === nationalityType &&
|
||||
rule.coach_type === scenario.coachType &&
|
||||
(scenario.bedPosition ? rule.bed_position === scenario.bedPosition : !rule.bed_position)
|
||||
);
|
||||
|
||||
if (!rateRule) {
|
||||
throw new BadRequestException(`No rate rule found for ${nationalityType}/${scenario.coachType}${scenario.bedPosition ? `/${scenario.bedPosition}` : ''}`);
|
||||
}
|
||||
|
||||
// Calculate base fare
|
||||
const baseFareMinor = scenario.distanceKm * rateRule.rate_per_km_minor;
|
||||
const breakdown = [
|
||||
{
|
||||
step: '1',
|
||||
description: `Base fare: ${scenario.distanceKm}km × ${rateRule.rate_per_km_minor} minor units/km`,
|
||||
amount: baseFareMinor,
|
||||
runningTotal: baseFareMinor
|
||||
}
|
||||
];
|
||||
|
||||
let runningTotal = baseFareMinor;
|
||||
|
||||
// Apply age-based pricing
|
||||
const { adultCount = 1, childCount = 0 } = scenario;
|
||||
let totalPassengerFare = 0;
|
||||
|
||||
// Process adults
|
||||
totalPassengerFare += adultCount * baseFareMinor;
|
||||
breakdown.push({
|
||||
step: '2a',
|
||||
description: `Adult passengers: ${adultCount} × ${baseFareMinor}`,
|
||||
amount: adultCount * baseFareMinor,
|
||||
runningTotal: adultCount * baseFareMinor
|
||||
});
|
||||
|
||||
// Process children with age rules
|
||||
if (childCount > 0) {
|
||||
const childRule = (config.ageRules as any[]).find((rule: any) =>
|
||||
rule.pricing_type === PricingType.FREE && rule.max_free_passengers > 0
|
||||
);
|
||||
|
||||
if (childRule) {
|
||||
const freeChildren = Math.min(childCount, childRule.max_free_passengers);
|
||||
const paidChildren = Math.max(0, childCount - freeChildren);
|
||||
|
||||
if (freeChildren > 0) {
|
||||
breakdown.push({
|
||||
step: '2b',
|
||||
description: `Free children: ${freeChildren} × 0 (first ${childRule.max_free_passengers} free)`,
|
||||
amount: 0,
|
||||
runningTotal: totalPassengerFare
|
||||
});
|
||||
}
|
||||
|
||||
if (paidChildren > 0) {
|
||||
const paidChildrenFare = paidChildren * baseFareMinor;
|
||||
totalPassengerFare += paidChildrenFare;
|
||||
breakdown.push({
|
||||
step: '2c',
|
||||
description: `Paid children: ${paidChildren} × ${baseFareMinor}`,
|
||||
amount: paidChildrenFare,
|
||||
runningTotal: totalPassengerFare
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// All children pay
|
||||
const childrenFare = childCount * baseFareMinor;
|
||||
totalPassengerFare += childrenFare;
|
||||
breakdown.push({
|
||||
step: '2b',
|
||||
description: `Child passengers: ${childCount} × ${baseFareMinor}`,
|
||||
amount: childrenFare,
|
||||
runningTotal: totalPassengerFare
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
runningTotal = totalPassengerFare;
|
||||
|
||||
// Apply components in order
|
||||
let componentsTotal = 0;
|
||||
const components = (config.components as any[])
|
||||
.filter((c: any) => c.is_active)
|
||||
.sort((a: any, b: any) => a.apply_order - b.apply_order);
|
||||
|
||||
for (const component of components) {
|
||||
let componentAmount = 0;
|
||||
let baseAmount = runningTotal;
|
||||
|
||||
if (component.applies_to === 'BASE_FARE') {
|
||||
baseAmount = baseFareMinor;
|
||||
} else if (component.applies_to === 'SUBTOTAL') {
|
||||
baseAmount = runningTotal;
|
||||
}
|
||||
|
||||
switch (component.calculation_method) {
|
||||
case 'PERCENTAGE':
|
||||
componentAmount = Math.round(baseAmount * (component.percentage_value || 0));
|
||||
break;
|
||||
case 'MULTIPLIER':
|
||||
componentAmount = Math.round(baseAmount * (component.percentage_value || 0));
|
||||
break;
|
||||
case 'FIXED_AMOUNT':
|
||||
componentAmount = component.value_minor || 0;
|
||||
break;
|
||||
}
|
||||
|
||||
componentsTotal += componentAmount;
|
||||
runningTotal += componentAmount;
|
||||
|
||||
breakdown.push({
|
||||
step: `3${String.fromCharCode(97 + component.apply_order - 1)}`,
|
||||
description: `${component.component_name}: ${component.calculation_method} on ${component.applies_to}`,
|
||||
amount: componentAmount,
|
||||
runningTotal
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
baseFareMinor,
|
||||
componentsTotal,
|
||||
totalBeforeDiscounts: runningTotal,
|
||||
discountsTotal: 0, // TODO: Implement promo code discounts
|
||||
finalTotalMinor: runningTotal,
|
||||
breakdown,
|
||||
currency: 'ETB',
|
||||
calculationTimestamp: new Date()
|
||||
};
|
||||
}
|
||||
|
||||
// Migration Methods
|
||||
async migrateLegacySystem(dto: MigrateLegacyDto) {
|
||||
const results = {
|
||||
scheduleFareRules: 0,
|
||||
segmentFareRules: 0,
|
||||
configurationsCreated: 0,
|
||||
dryRun: dto.dryRun || false
|
||||
};
|
||||
|
||||
if (dto.dryRun) {
|
||||
// Count what would be migrated
|
||||
const scheduleFares = await this.prisma.$queryRaw`
|
||||
SELECT COUNT(*) as count FROM "FareRule" WHERE migrated_to_config_id IS NULL
|
||||
`;
|
||||
|
||||
const segmentFares = await this.prisma.$queryRaw`
|
||||
SELECT COUNT(*) as count FROM "SegmentFareRule" WHERE migrated_to_config_id IS NULL
|
||||
`;
|
||||
|
||||
results.scheduleFareRules = Number((scheduleFares as any[])[0]?.count || 0);
|
||||
results.segmentFareRules = Number((segmentFares as any[])[0]?.count || 0);
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
// Create a migration configuration based on existing rules
|
||||
const migrationConfig: CreateFareConfigurationDto = {
|
||||
name: 'Legacy Migration Configuration',
|
||||
description: 'Automatically migrated from existing fare rules',
|
||||
effectiveDate: new Date().toISOString(),
|
||||
rateRules: [
|
||||
// Default rates based on current system
|
||||
{ nationalityType: NationalityType.LOCAL, coachType: CoachType.REGULAR_SEAT, ratePerKmMinor: 3000 },
|
||||
{ nationalityType: NationalityType.LOCAL, coachType: CoachType.ECONOMY_BED, bedPosition: BedPosition.UPPER, ratePerKmMinor: 4000 },
|
||||
{ nationalityType: NationalityType.LOCAL, coachType: CoachType.ECONOMY_BED, bedPosition: BedPosition.MIDDLE, ratePerKmMinor: 5500 },
|
||||
{ nationalityType: NationalityType.LOCAL, coachType: CoachType.ECONOMY_BED, bedPosition: BedPosition.LOWER, ratePerKmMinor: 6000 },
|
||||
{ nationalityType: NationalityType.INTERNATIONAL, coachType: CoachType.REGULAR_SEAT, ratePerKmMinor: 6000 },
|
||||
{ nationalityType: NationalityType.INTERNATIONAL, coachType: CoachType.ECONOMY_BED, bedPosition: BedPosition.UPPER, ratePerKmMinor: 8000 },
|
||||
{ nationalityType: NationalityType.INTERNATIONAL, coachType: CoachType.ECONOMY_BED, bedPosition: BedPosition.MIDDLE, ratePerKmMinor: 11000 },
|
||||
{ nationalityType: NationalityType.INTERNATIONAL, coachType: CoachType.ECONOMY_BED, bedPosition: BedPosition.LOWER, ratePerKmMinor: 12000 },
|
||||
],
|
||||
components: [
|
||||
{
|
||||
componentType: ComponentType.INSURANCE,
|
||||
componentName: 'Travel Insurance',
|
||||
calculationMethod: CalculationMethod.PERCENTAGE,
|
||||
percentageValue: 0.02,
|
||||
appliesTo: AppliesTo.BASE_FARE,
|
||||
applyOrder: 1
|
||||
},
|
||||
{
|
||||
componentType: ComponentType.TAX,
|
||||
componentName: 'Government Tax',
|
||||
calculationMethod: CalculationMethod.PERCENTAGE,
|
||||
percentageValue: 0.05,
|
||||
appliesTo: AppliesTo.SUBTOTAL,
|
||||
applyOrder: 2
|
||||
}
|
||||
],
|
||||
ageRules: [
|
||||
{
|
||||
ruleName: 'Adult Passengers',
|
||||
minAge: 5,
|
||||
pricingType: PricingType.FULL_FARE
|
||||
},
|
||||
{
|
||||
ruleName: 'Child Passengers (First Free)',
|
||||
minAge: 0,
|
||||
maxAge: 4,
|
||||
pricingType: PricingType.FREE,
|
||||
maxFreePassengers: 1
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
const newConfig = await this.createConfiguration(migrationConfig, 'system-migration');
|
||||
results.configurationsCreated = 1;
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
async createNewFormulaConfiguration(dto: CreateNewFormulaDto) {
|
||||
const config = await this.createConfiguration({
|
||||
name: dto.name,
|
||||
description: dto.description || 'System-generated default configuration',
|
||||
effectiveDate: new Date().toISOString(),
|
||||
rateRules: [
|
||||
// Default rates for all combinations
|
||||
{ nationalityType: NationalityType.LOCAL, coachType: CoachType.REGULAR_SEAT, ratePerKmMinor: 3000 },
|
||||
{ nationalityType: NationalityType.LOCAL, coachType: CoachType.ECONOMY_BED, bedPosition: BedPosition.UPPER, ratePerKmMinor: 4000 },
|
||||
{ nationalityType: NationalityType.LOCAL, coachType: CoachType.ECONOMY_BED, bedPosition: BedPosition.MIDDLE, ratePerKmMinor: 5500 },
|
||||
{ nationalityType: NationalityType.LOCAL, coachType: CoachType.ECONOMY_BED, bedPosition: BedPosition.LOWER, ratePerKmMinor: 6000 },
|
||||
{ nationalityType: NationalityType.LOCAL, coachType: CoachType.VIP_BED, bedPosition: BedPosition.LOWER, ratePerKmMinor: 8000 },
|
||||
// International rates (2x local)
|
||||
{ nationalityType: NationalityType.INTERNATIONAL, coachType: CoachType.REGULAR_SEAT, ratePerKmMinor: 6000 },
|
||||
{ nationalityType: NationalityType.INTERNATIONAL, coachType: CoachType.ECONOMY_BED, bedPosition: BedPosition.UPPER, ratePerKmMinor: 8000 },
|
||||
{ nationalityType: NationalityType.INTERNATIONAL, coachType: CoachType.ECONOMY_BED, bedPosition: BedPosition.MIDDLE, ratePerKmMinor: 11000 },
|
||||
{ nationalityType: NationalityType.INTERNATIONAL, coachType: CoachType.ECONOMY_BED, bedPosition: BedPosition.LOWER, ratePerKmMinor: 12000 },
|
||||
{ nationalityType: NationalityType.INTERNATIONAL, coachType: CoachType.VIP_BED, bedPosition: BedPosition.LOWER, ratePerKmMinor: 16000 },
|
||||
],
|
||||
components: [
|
||||
{
|
||||
componentType: ComponentType.INSURANCE,
|
||||
componentName: 'Travel Insurance',
|
||||
calculationMethod: CalculationMethod.PERCENTAGE,
|
||||
percentageValue: 0.02,
|
||||
appliesTo: AppliesTo.BASE_FARE,
|
||||
applyOrder: 1
|
||||
},
|
||||
{
|
||||
componentType: ComponentType.SERVICE_CHARGE,
|
||||
componentName: 'Service Charge',
|
||||
calculationMethod: CalculationMethod.PERCENTAGE,
|
||||
percentageValue: 0.03,
|
||||
appliesTo: AppliesTo.SUBTOTAL,
|
||||
applyOrder: 2
|
||||
},
|
||||
{
|
||||
componentType: ComponentType.TAX,
|
||||
componentName: 'Government Tax',
|
||||
calculationMethod: CalculationMethod.PERCENTAGE,
|
||||
percentageValue: 0.05,
|
||||
appliesTo: AppliesTo.TOTAL,
|
||||
applyOrder: 3
|
||||
}
|
||||
],
|
||||
ageRules: [
|
||||
{
|
||||
ruleName: 'Adult Passengers',
|
||||
minAge: 5,
|
||||
pricingType: PricingType.FULL_FARE
|
||||
},
|
||||
{
|
||||
ruleName: 'Child Passengers (First Free)',
|
||||
minAge: 0,
|
||||
maxAge: 4,
|
||||
pricingType: PricingType.FREE,
|
||||
maxFreePassengers: 1
|
||||
}
|
||||
],
|
||||
isDefault: true
|
||||
}, 'system');
|
||||
|
||||
if (dto.activateImmediately) {
|
||||
await this.activateConfiguration((config as any).id, 'system');
|
||||
}
|
||||
|
||||
return config;
|
||||
}
|
||||
|
||||
// Feature Management
|
||||
async toggleFeature(dto: ToggleFeatureDto) {
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
await tx.$executeRaw`
|
||||
INSERT INTO system_features (id, feature_name, is_enabled, config, created_at, updated_at)
|
||||
VALUES (${this.generateId('sf')}, ${dto.featureName}, ${dto.enabled},
|
||||
${JSON.stringify(dto.config || {})}, NOW(), NOW())
|
||||
ON CONFLICT (feature_name) DO UPDATE SET
|
||||
is_enabled = ${dto.enabled},
|
||||
config = ${JSON.stringify(dto.config || {})},
|
||||
updated_at = NOW()
|
||||
`;
|
||||
|
||||
return { success: true, message: `Feature ${dto.featureName} ${dto.enabled ? 'enabled' : 'disabled'}` };
|
||||
});
|
||||
}
|
||||
|
||||
async getFeatureStatus(featureName: string) {
|
||||
const result = await this.prisma.$queryRaw`
|
||||
SELECT * FROM system_features WHERE feature_name = ${featureName}
|
||||
`;
|
||||
|
||||
if (!Array.isArray(result) || result.length === 0) {
|
||||
return { enabled: false, config: {} };
|
||||
}
|
||||
|
||||
const feature = result[0] as any;
|
||||
return {
|
||||
enabled: feature.is_enabled,
|
||||
config: feature.config || {}
|
||||
};
|
||||
}
|
||||
|
||||
async getAuditTrail(configId: string) {
|
||||
return this.prisma.$queryRaw`
|
||||
SELECT * FROM fare_configuration_audit
|
||||
WHERE fare_config_id = ${configId}
|
||||
ORDER BY timestamp DESC
|
||||
`;
|
||||
}
|
||||
|
||||
// Private helper methods
|
||||
private async createAuditEntry(tx: any, configId: string, action: string, changedBy?: string, changes?: any) {
|
||||
const auditId = this.generateId('fca');
|
||||
await tx.$executeRaw`
|
||||
INSERT INTO fare_configuration_audit (
|
||||
id, fare_config_id, action, changed_by, changes, timestamp
|
||||
) VALUES (
|
||||
${auditId}, ${configId}, ${action}, ${changedBy || 'system'},
|
||||
${JSON.stringify(changes || {})}, NOW()
|
||||
)
|
||||
`;
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,7 @@ export class DashboardService {
|
||||
include: {
|
||||
schedule: { include: { originStation: true, destinationStation: true, train: true, liveStatus: true } },
|
||||
seats: { include: { seat: { include: { coach: true } } }, take: 1 },
|
||||
ticket: true,
|
||||
tickets: { take: 1 },
|
||||
},
|
||||
orderBy: { createdAt: 'asc' },
|
||||
}),
|
||||
@@ -42,16 +42,16 @@ export class DashboardService {
|
||||
const name = iamRows[0]?.name;
|
||||
firstName = (name?.en ?? name?.am ?? '').split(' ')[0];
|
||||
}
|
||||
const seat = upcomingBooking?.seats[0];
|
||||
const seat = (upcomingBooking as any)?.seats?.[0];
|
||||
|
||||
return {
|
||||
user: { firstName, greetingKey },
|
||||
upcomingTicket: upcomingBooking ? {
|
||||
ticketId: upcomingBooking.ticket?.id, bookingRef: upcomingBooking.bookingRef,
|
||||
from: upcomingBooking.schedule.originStation.name, to: upcomingBooking.schedule.destinationStation.name,
|
||||
trainName: upcomingBooking.schedule.train.name, coachLabel: seat?.seat.coach.number, seatLabel: seat?.seat.seatNumber,
|
||||
departureAt: upcomingBooking.schedule.departureAt,
|
||||
punctualityLabel: (upcomingBooking.schedule.liveStatus?.delayMinutes ?? 0) > 0 ? 'DELAYED' : 'ON_TIME',
|
||||
ticketId: (upcomingBooking as any).tickets?.[0]?.id, bookingRef: upcomingBooking.bookingRef,
|
||||
from: (upcomingBooking as any).schedule.originStation.name, to: (upcomingBooking as any).schedule.destinationStation.name,
|
||||
trainName: (upcomingBooking as any).schedule.train.name, coachLabel: seat?.seat.coach.number, seatLabel: seat?.seat.seatNumber,
|
||||
departureAt: (upcomingBooking as any).schedule.departureAt,
|
||||
punctualityLabel: ((upcomingBooking as any).schedule.liveStatus?.delayMinutes ?? 0) > 0 ? 'DELAYED' : 'ON_TIME',
|
||||
} : null,
|
||||
wallet: wallet ? { balanceMinor: wallet.balanceMinor, currency: wallet.currency } : null,
|
||||
activePromotionsCount: promos,
|
||||
|
||||
@@ -91,6 +91,12 @@ export class ExcessBaggageAgentController {
|
||||
deleteAllowance(@Param('id') id: string) {
|
||||
return this.service.deleteAllowance(id);
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
@ApiOperation({ summary: 'Delete excess baggage charge (admin only)' })
|
||||
deleteCharge(@Param('id') id: string) {
|
||||
return this.service.deleteCharge(id);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Public pay-by-token routes (passenger self-service) ──────────────────────
|
||||
|
||||
@@ -252,6 +252,15 @@ export class ExcessBaggageService {
|
||||
};
|
||||
}
|
||||
|
||||
// Mark expired charges before fetching
|
||||
await this.prisma.excessBaggageCharge.updateMany({
|
||||
where: {
|
||||
status: 'PENDING',
|
||||
expiresAt: { lt: new Date() },
|
||||
},
|
||||
data: { status: 'EXPIRED' },
|
||||
});
|
||||
|
||||
const [items, total] = await Promise.all([
|
||||
this.prisma.excessBaggageCharge.findMany({
|
||||
where,
|
||||
@@ -291,4 +300,12 @@ export class ExcessBaggageService {
|
||||
await this.prisma.baggageAllowance.delete({ where: { id } });
|
||||
return { deleted: true };
|
||||
}
|
||||
|
||||
async deleteCharge(id: string) {
|
||||
const charge = await this.prisma.excessBaggageCharge.findUnique({ where: { id } });
|
||||
if (!charge) throw new NotFoundException('Charge not found');
|
||||
|
||||
await this.prisma.excessBaggageCharge.delete({ where: { id } });
|
||||
return { deleted: true };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,14 +28,16 @@ export class FareEngineService {
|
||||
if (originStop.sequence >= destStop.sequence)
|
||||
throw new BadRequestException('Origin must come before destination in the route sequence');
|
||||
|
||||
const legStops = route.stops.filter(
|
||||
s => s.sequence > originStop.sequence && s.sequence <= destStop.sequence,
|
||||
);
|
||||
|
||||
const seatClass = await this.prisma.seatClass.findUnique({ where: { id: dto.seatClassId } });
|
||||
if (!seatClass) throw new NotFoundException('Seat class not found');
|
||||
if (!seatClass.isActive) throw new BadRequestException('Seat class is not active');
|
||||
|
||||
// Calculate distance: distanceKm represents cumulative distance from route origin
|
||||
// For a segment, distance = destination.distanceKm - origin.distanceKm
|
||||
const totalDistanceKm = destStop.distanceKm! - originStop.distanceKm!;
|
||||
if (totalDistanceKm < 0 || isNaN(totalDistanceKm))
|
||||
throw new BadRequestException('Invalid distance calculation - check route stop distances');
|
||||
|
||||
// Resolve fare: FareRule (schedule-scoped → route-scoped) takes precedence over distance×rate
|
||||
const now = new Date();
|
||||
const [originStation, destStation] = await Promise.all([
|
||||
@@ -64,23 +66,15 @@ export class FareEngineService {
|
||||
|
||||
let baseFarePerPassengerMinor: number;
|
||||
let ratePerKmMinor: number;
|
||||
let totalDistanceKm: number;
|
||||
let fareSource: string;
|
||||
|
||||
if (fareRule) {
|
||||
// Flat fare from FareRule — distance is informational only
|
||||
baseFarePerPassengerMinor = fareRule.baseFareMinor;
|
||||
totalDistanceKm = legStops.reduce((sum, s) => sum + (s.distanceKm ?? 0), 0);
|
||||
ratePerKmMinor = totalDistanceKm > 0 ? Math.round(baseFarePerPassengerMinor / totalDistanceKm) : 0;
|
||||
fareSource = fareRule.tripId ? 'SCHEDULE_FARE_RULE' : 'ROUTE_FARE_RULE';
|
||||
} else {
|
||||
// Distance × rate fallback
|
||||
const missingDistance = legStops.filter(s => s.distanceKm === null || s.distanceKm === undefined);
|
||||
if (missingDistance.length > 0)
|
||||
throw new BadRequestException(
|
||||
`Missing distanceKm on route stops at sequences: ${missingDistance.map(s => s.sequence).join(', ')}`,
|
||||
);
|
||||
totalDistanceKm = legStops.reduce((sum, s) => sum + (s.distanceKm ?? 0), 0);
|
||||
ratePerKmMinor = seatClass.baseFareMinor;
|
||||
baseFarePerPassengerMinor = totalDistanceKm * ratePerKmMinor;
|
||||
fareSource = 'DISTANCE_RATE';
|
||||
|
||||
@@ -174,13 +174,13 @@ export class FleetController {
|
||||
example: [
|
||||
{
|
||||
id: '550e8400-e29b-41d4-a716-446655440000',
|
||||
number: 'A-001',
|
||||
number: 'HSC-0001',
|
||||
sequence: 1,
|
||||
coachTypeId: 'coach-type-uuid',
|
||||
coachType: {
|
||||
id: 'coach-type-uuid',
|
||||
code: 'sleeper',
|
||||
name: 'Sleeper Coach'
|
||||
code: 'HSC',
|
||||
name: 'Hard Seat Coach'
|
||||
},
|
||||
arrangement: '2+2',
|
||||
capacity: 60,
|
||||
@@ -215,13 +215,13 @@ export class FleetController {
|
||||
schema: {
|
||||
example: {
|
||||
id: '550e8400-e29b-41d4-a716-446655440000',
|
||||
number: 'A-001',
|
||||
number: 'HSC-0001',
|
||||
sequence: 1,
|
||||
coachTypeId: 'coach-type-uuid',
|
||||
coachType: {
|
||||
id: 'coach-type-uuid',
|
||||
code: 'sleeper',
|
||||
name: 'Sleeper Coach'
|
||||
code: 'HSC',
|
||||
name: 'Hard Seat Coach'
|
||||
},
|
||||
arrangement: '2+2',
|
||||
capacity: 60,
|
||||
@@ -257,7 +257,7 @@ export class FleetController {
|
||||
schema: {
|
||||
example: {
|
||||
id: '550e8400-e29b-41d4-a716-446655440000',
|
||||
number: 'A-001',
|
||||
number: 'HSC-0001',
|
||||
sequence: 1,
|
||||
coachTypeId: 'coach-type-uuid',
|
||||
arrangement: '2+2',
|
||||
@@ -283,7 +283,7 @@ export class FleetController {
|
||||
schema: {
|
||||
example: {
|
||||
id: '550e8400-e29b-41d4-a716-446655440000',
|
||||
number: 'A-001',
|
||||
number: 'HSC-0001',
|
||||
sequence: 1,
|
||||
coachTypeId: 'coach-type-uuid',
|
||||
arrangement: '2+2',
|
||||
|
||||
@@ -11,7 +11,7 @@ export class CreateTrainDto {
|
||||
}
|
||||
|
||||
export class CreateCoachDto {
|
||||
@ApiProperty({ example: 'A-001', description: 'Unique coach number' }) @IsString() number: string;
|
||||
@ApiProperty({ example: 'HSC-0001', description: 'Unique coach number' }) @IsString() number: string;
|
||||
@ApiProperty({ example: 'coach-type-uuid', description: 'Coach Type UUID' }) @IsString() coachTypeId: string;
|
||||
@ApiProperty({ example: '2+2', description: 'Seat arrangement for regular coaches (e.g., "2+2", "3+2"). Ignored for bed coaches.' }) @IsString() arrangement: string;
|
||||
@ApiProperty({ example: 60, description: 'Total seat/bed capacity' }) @IsInt() capacity: number;
|
||||
@@ -53,22 +53,22 @@ export class ListCoachesDto {
|
||||
|
||||
// Legacy DTO types for backward compatibility
|
||||
export class CreateCoachTypeDto {
|
||||
@ApiProperty({ example: 'sleeper' }) @IsString() code: string;
|
||||
@ApiProperty({ example: 'Sleeper Coach' }) @IsString() name: string;
|
||||
@ApiProperty({ example: 'HSC' }) @IsString() code: string;
|
||||
@ApiProperty({ example: 'Hard Seat Coach' }) @IsString() name: string;
|
||||
@IsOptional() @IsString() type?: string;
|
||||
}
|
||||
|
||||
export class UpdateCoachTypeDto {
|
||||
@ApiPropertyOptional({ example: 'sleeper' }) @IsOptional() @IsString() code?: string;
|
||||
@ApiPropertyOptional({ example: 'Sleeper Coach' }) @IsOptional() @IsString() name?: string;
|
||||
@ApiPropertyOptional({ example: 'sleeper' }) @IsOptional() @IsString() type?: string;
|
||||
@ApiPropertyOptional({ example: 'HSC' }) @IsOptional() @IsString() code?: string;
|
||||
@ApiPropertyOptional({ example: 'Hard Seat Coach' }) @IsOptional() @IsString() name?: string;
|
||||
@ApiPropertyOptional({ example: 'Regular Seat' }) @IsOptional() @IsString() type?: string;
|
||||
}
|
||||
|
||||
export class CreateClassDto {
|
||||
@ApiProperty({ example: 'coach-type-uuid' }) @IsString() coachTypeId: string;
|
||||
@ApiProperty({ example: 'Economy' }) @IsString() name: string;
|
||||
@IsOptional() @IsString() description?: string;
|
||||
@ApiProperty({ example: 5000 }) @IsInt() baseFareMinor: number;
|
||||
@ApiProperty({ example: 500 }) @IsInt() baseFareMinor: number;
|
||||
@ApiPropertyOptional({ example: 0 }) @IsOptional() @IsInt() premiumMinor?: number;
|
||||
@ApiPropertyOptional({ example: 0 }) @IsOptional() @IsInt() insuranceFeeMinor?: number;
|
||||
@ApiPropertyOptional({ example: true }) @IsOptional() @IsBoolean() isActive?: boolean;
|
||||
@@ -78,7 +78,7 @@ export class UpdateClassDto {
|
||||
@ApiPropertyOptional({ example: 'coach-type-uuid' }) @IsOptional() @IsString() coachTypeId?: string;
|
||||
@ApiPropertyOptional({ example: 'Economy' }) @IsOptional() @IsString() name?: string;
|
||||
@ApiPropertyOptional() @IsOptional() @IsString() description?: string;
|
||||
@ApiPropertyOptional({ example: 5000 }) @IsOptional() @IsInt() baseFareMinor?: number;
|
||||
@ApiPropertyOptional({ example: 500 }) @IsOptional() @IsInt() baseFareMinor?: number;
|
||||
@ApiPropertyOptional({ example: true })
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Injectable, NotFoundException, BadRequestException } from '@nestjs/comm
|
||||
import { PrismaService } from '../../common/prisma.service';
|
||||
import { CreateTrainDto, CreateCoachDto, UpdateCoachDto, AssignCoachDto, ListCoachesDto, CreateCoachTypeDto, UpdateCoachTypeDto, CreateClassDto, UpdateClassDto, GenerateSeatMapDto } from './fleet.dto';
|
||||
import { SeatKind } from '@prisma/client';
|
||||
import { DeleteOperationException } from '../../common/exceptions/delete-operation.exception';
|
||||
|
||||
// Parses '2+2' → [2, 2], '2+2+2' → [2, 2, 2]
|
||||
function parseArrangement(arrangement: string): number[] {
|
||||
@@ -41,7 +42,7 @@ const DEFAULT_BEDS_PER_ROOM: Record<'ECONOMY_BED' | 'VIP_BED', number> = {
|
||||
ECONOMY_BED: 6,
|
||||
};
|
||||
|
||||
// Name-based fallback: checks if 'vip' is present for any bed/sleeper coach type
|
||||
// Name-based fallback: checks if 'vip' is present for any bed coach type
|
||||
function detectBedCategory(coachTypeName: string): BedCategory {
|
||||
const name = coachTypeName.toLowerCase();
|
||||
const isBed = name.includes('bed') || name.includes('berth') || name.includes('sleeper') || name.includes('couchette');
|
||||
@@ -201,17 +202,25 @@ export class FleetService {
|
||||
});
|
||||
if (!coachType) throw new NotFoundException('Coach type not found');
|
||||
|
||||
// Check for related records
|
||||
const constraints = [];
|
||||
if (coachType.coaches.length > 0) {
|
||||
throw new BadRequestException(
|
||||
`Cannot delete coach type. ${coachType.coaches.length} coach(es) are still using this coach type. Please reassign or delete the coaches first.`
|
||||
);
|
||||
constraints.push({
|
||||
entityName: 'coach',
|
||||
count: coachType.coaches.length,
|
||||
action: 'reassign' as const
|
||||
});
|
||||
}
|
||||
|
||||
if (coachType.seatClasses.length > 0) {
|
||||
throw new BadRequestException(
|
||||
`Cannot delete coach type. ${coachType.seatClasses.length} seat class(es) are still using this coach type. Please reassign or delete the seat classes first.`
|
||||
);
|
||||
constraints.push({
|
||||
entityName: 'seat class',
|
||||
count: coachType.seatClasses.length,
|
||||
action: 'reassign' as const
|
||||
});
|
||||
}
|
||||
|
||||
if (constraints.length > 0) {
|
||||
throw new DeleteOperationException('Coach Type', coachType.name, constraints);
|
||||
}
|
||||
|
||||
return this.prisma.coachType.delete({ where: { id } });
|
||||
@@ -273,17 +282,19 @@ export class FleetService {
|
||||
});
|
||||
if (!seatClass) throw new NotFoundException('Seat class not found');
|
||||
|
||||
// Check for related records
|
||||
const relatedRecords = [
|
||||
...seatClass.fareRules,
|
||||
...seatClass.routeFareRules,
|
||||
...seatClass.segmentFares,
|
||||
];
|
||||
const totalFareRules = seatClass.fareRules.length + seatClass.routeFareRules.length + seatClass.segmentFares.length;
|
||||
const constraints = [];
|
||||
|
||||
if (relatedRecords.length > 0) {
|
||||
throw new BadRequestException(
|
||||
`Cannot delete seat class. ${relatedRecords.length} fare rule(s) are still using this seat class. Please delete the fare rules first.`
|
||||
);
|
||||
if (totalFareRules > 0) {
|
||||
constraints.push({
|
||||
entityName: 'fare rule',
|
||||
count: totalFareRules,
|
||||
action: 'delete' as const
|
||||
});
|
||||
}
|
||||
|
||||
if (constraints.length > 0) {
|
||||
throw new DeleteOperationException('Seat Class', seatClass.name, constraints);
|
||||
}
|
||||
|
||||
return this.prisma.seatClass.delete({ where: { id } });
|
||||
@@ -344,11 +355,20 @@ export class FleetService {
|
||||
include: { schedules: true },
|
||||
});
|
||||
if (!train) throw new NotFoundException('Train not found');
|
||||
|
||||
const constraints = [];
|
||||
if (train.schedules.length > 0) {
|
||||
throw new BadRequestException(
|
||||
`Cannot delete train. This train has ${train.schedules.length} schedule(s). Please delete the schedules first.`
|
||||
);
|
||||
constraints.push({
|
||||
entityName: 'schedule',
|
||||
count: train.schedules.length,
|
||||
action: 'delete' as const
|
||||
});
|
||||
}
|
||||
|
||||
if (constraints.length > 0) {
|
||||
throw new DeleteOperationException('Train', `${train.number} (${train.name})`, constraints);
|
||||
}
|
||||
|
||||
return this.prisma.train.delete({ where: { id } });
|
||||
}
|
||||
|
||||
@@ -460,45 +480,54 @@ export class FleetService {
|
||||
include: {
|
||||
bookingSeats: true,
|
||||
blocks: true,
|
||||
ticketSeats: true,
|
||||
tickets: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!coach) throw new NotFoundException('Coach not found');
|
||||
|
||||
// Check for active assignments
|
||||
if (coach.assignments.length > 0) {
|
||||
throw new BadRequestException(
|
||||
`Cannot delete coach. This coach is assigned to ${coach.assignments.length} schedule(s). Please remove the assignments first.`
|
||||
);
|
||||
const constraints = [];
|
||||
|
||||
if ((coach as any).assignments.length > 0) {
|
||||
constraints.push({
|
||||
entityName: 'schedule assignment',
|
||||
count: (coach as any).assignments.length,
|
||||
action: 'reassign' as const
|
||||
});
|
||||
}
|
||||
|
||||
// Check for booked seats
|
||||
const bookedSeats = coach.seats.filter(seat => seat.bookingSeats.length > 0);
|
||||
const bookedSeats = (coach as any).seats.filter((seat: any) => seat.bookingSeats.length > 0);
|
||||
if (bookedSeats.length > 0) {
|
||||
throw new BadRequestException(
|
||||
`Cannot delete coach. ${bookedSeats.length} seat(s) have active bookings. Please wait for bookings to complete or cancel them first.`
|
||||
);
|
||||
constraints.push({
|
||||
entityName: 'booked seat',
|
||||
count: bookedSeats.length,
|
||||
action: 'complete' as const
|
||||
});
|
||||
}
|
||||
|
||||
// Check for blocked seats
|
||||
const blockedSeats = coach.seats.filter(seat => seat.blocks.length > 0);
|
||||
const blockedSeats = (coach as any).seats.filter((seat: any) => seat.blocks.length > 0);
|
||||
if (blockedSeats.length > 0) {
|
||||
throw new BadRequestException(
|
||||
`Cannot delete coach. ${blockedSeats.length} seat(s) are blocked. Please unblock them first.`
|
||||
);
|
||||
constraints.push({
|
||||
entityName: 'blocked seat',
|
||||
count: blockedSeats.length,
|
||||
action: 'delete' as const
|
||||
});
|
||||
}
|
||||
|
||||
// Check for tickets
|
||||
const seatsWithTickets = coach.seats.filter(seat => seat.ticketSeats.length > 0);
|
||||
const seatsWithTickets = (coach as any).seats.filter((seat: any) => seat.tickets.length > 0);
|
||||
if (seatsWithTickets.length > 0) {
|
||||
throw new BadRequestException(
|
||||
`Cannot delete coach. ${seatsWithTickets.length} seat(s) have issued tickets. Please wait for travel completion.`
|
||||
);
|
||||
constraints.push({
|
||||
entityName: 'seat with issued ticket',
|
||||
count: seatsWithTickets.length,
|
||||
action: 'complete' as const
|
||||
});
|
||||
}
|
||||
|
||||
if (constraints.length > 0) {
|
||||
throw new DeleteOperationException('Coach', coach.number, constraints);
|
||||
}
|
||||
|
||||
// Delete related seats first (now safe to do)
|
||||
await this.prisma.seat.deleteMany({ where: { coachId: id } });
|
||||
|
||||
return this.prisma.coach.delete({ where: { id } });
|
||||
|
||||
@@ -280,7 +280,7 @@ export class NotificationsService {
|
||||
seats: { include: { seat: { include: { coach: { include: { coachType: true } } } } } },
|
||||
},
|
||||
});
|
||||
const ticket = await this.prisma.ticket.findUnique({ where: { bookingId } });
|
||||
const ticket = await this.prisma.ticket.findFirst({ where: { bookingId } });
|
||||
|
||||
const ref = booking?.bookingRef ?? payload.booking.bookingRef;
|
||||
const amount = this.formatAmount(booking ?? payload.booking);
|
||||
|
||||
@@ -21,22 +21,152 @@ export class PassengersController {
|
||||
@Get()
|
||||
@SetMetadata('isPublic', true)
|
||||
@ApiOperation({
|
||||
summary: 'List all passengers with filters (Admin/Agent)',
|
||||
description: 'Returns paginated list of passengers with search filters'
|
||||
summary: 'List all travelers with filters (Admin/Agent)',
|
||||
description: `**Returns paginated list of all travelers in the system**
|
||||
|
||||
---
|
||||
|
||||
### Data Source
|
||||
- Fetches from **TravelerProfile** table (created during booking)
|
||||
- Shows ALL passengers from ALL bookings (including guest bookings)
|
||||
- Each row represents a unique traveler, not a user account
|
||||
|
||||
---
|
||||
|
||||
### Features
|
||||
- Search by name, email, phone
|
||||
- Filter by gender
|
||||
- Date range filtering (createdAt)
|
||||
- Pagination support (page, pageSize)
|
||||
- Includes loyalty and wallet info if linked to user account
|
||||
- Shows booking count per traveler
|
||||
|
||||
---
|
||||
|
||||
### Response Fields
|
||||
- **id**: TravelerProfile ID
|
||||
- **fullName**: Passenger name
|
||||
- **email/phone**: Contact info (from linked user or booking)
|
||||
- **gender**: Male/Female/Other (from Verifayda or manual entry)
|
||||
- **dateOfBirth**: Birth date in YYYY-MM-DD format
|
||||
- **nationality**: Passenger nationality
|
||||
- **faydaVerified**: Whether verified via Verifayda
|
||||
- **loyaltyTier/loyaltyPoints**: If linked to user account
|
||||
- **totalBookings**: Number of bookings
|
||||
- **createdAt**: When traveler was first added to system`
|
||||
})
|
||||
@ApiQuery({ name: 'search', required: false, description: 'Search by name, email, or phone' })
|
||||
@ApiQuery({ name: 'gender', required: false, description: 'Filter by gender (Male, Female, Other)' })
|
||||
@ApiQuery({ name: 'dateFrom', required: false, description: 'Filter by creation date from (YYYY-MM-DD)' })
|
||||
@ApiQuery({ name: 'dateTo', required: false, description: 'Filter by creation date to (YYYY-MM-DD)' })
|
||||
@ApiQuery({ name: 'page', required: false, description: 'Page number (default: 1)' })
|
||||
@ApiQuery({ name: 'pageSize', required: false, description: 'Items per page (default: 20)' })
|
||||
@ApiResponse({
|
||||
status: 200,
|
||||
description: 'Travelers retrieved successfully',
|
||||
schema: {
|
||||
example: {
|
||||
items: [
|
||||
{
|
||||
id: 'uuid-123',
|
||||
fullName: 'Abebe Kebede',
|
||||
email: 'abebe@example.com',
|
||||
phone: '+251911234567',
|
||||
gender: 'Male',
|
||||
dateOfBirth: '1985-03-15',
|
||||
nationality: 'Ethiopian',
|
||||
faydaVerified: true,
|
||||
loyaltyTier: 'SILVER',
|
||||
loyaltyPoints: 1500,
|
||||
totalBookings: 5,
|
||||
createdAt: '2024-01-10T12:00:00.000Z'
|
||||
}
|
||||
],
|
||||
meta: {
|
||||
page: 1,
|
||||
pageSize: 20,
|
||||
total: 150,
|
||||
totalPages: 8
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
@ApiResponse({
|
||||
status: 200,
|
||||
description: 'Travelers retrieved successfully',
|
||||
schema: {
|
||||
example: {
|
||||
items: [
|
||||
{
|
||||
id: 'uuid-123',
|
||||
fullName: 'Abebe Kebede',
|
||||
email: 'abebe@example.com',
|
||||
phone: '+251911234567',
|
||||
gender: 'Male',
|
||||
dateOfBirth: '1985-03-15',
|
||||
nationality: 'Ethiopian',
|
||||
nationalityCode: 'ET',
|
||||
faydaVerified: true,
|
||||
faydaVerifiedAt: '2024-01-15T10:30:00.000Z',
|
||||
passportNumber: null,
|
||||
passportCountry: null,
|
||||
passportExpiryDate: null,
|
||||
idDocumentType: 'NATIONAL_ID',
|
||||
verified: true,
|
||||
lastLoginAt: '2024-01-20T08:15:00.000Z',
|
||||
role: 'PASSENGER',
|
||||
loyalty: {
|
||||
tier: 'SILVER',
|
||||
pointsBalance: 1500,
|
||||
lifetimePoints: 3000
|
||||
},
|
||||
wallet: {
|
||||
balanceMinor: 50000,
|
||||
currency: 'ETB'
|
||||
},
|
||||
loyaltyTier: 'SILVER',
|
||||
loyaltyPoints: 1500,
|
||||
totalBookings: 5,
|
||||
createdAt: '2024-01-10T12:00:00.000Z'
|
||||
},
|
||||
{
|
||||
id: 'uuid-456',
|
||||
fullName: 'Sara Ketsela',
|
||||
email: null,
|
||||
phone: null,
|
||||
gender: 'Female',
|
||||
dateOfBirth: '1990-08-22',
|
||||
nationality: 'Ethiopian',
|
||||
nationalityCode: null,
|
||||
faydaVerified: false,
|
||||
faydaVerifiedAt: null,
|
||||
passportNumber: null,
|
||||
passportCountry: null,
|
||||
passportExpiryDate: null,
|
||||
idDocumentType: null,
|
||||
verified: false,
|
||||
lastLoginAt: null,
|
||||
role: null,
|
||||
loyalty: null,
|
||||
wallet: null,
|
||||
loyaltyTier: 'BRONZE',
|
||||
loyaltyPoints: 0,
|
||||
totalBookings: 1,
|
||||
createdAt: '2024-01-18T14:30:00.000Z'
|
||||
}
|
||||
],
|
||||
meta: {
|
||||
page: 1,
|
||||
pageSize: 20,
|
||||
total: 150,
|
||||
totalPages: 8
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
@ApiQuery({ name: 'search', required: false })
|
||||
@ApiQuery({ name: 'verified', required: false })
|
||||
@ApiQuery({ name: 'gender', required: false })
|
||||
@ApiQuery({ name: 'nationality', required: false })
|
||||
@ApiQuery({ name: 'dateFrom', required: false })
|
||||
@ApiQuery({ name: 'dateTo', required: false })
|
||||
@ApiQuery({ name: 'page', required: false })
|
||||
@ApiQuery({ name: 'pageSize', required: false })
|
||||
findAll(
|
||||
@Query('search') search?: string,
|
||||
@Query('verified') verified?: string,
|
||||
@Query('gender') gender?: string,
|
||||
@Query('nationality') nationality?: string,
|
||||
@Query('dateFrom') dateFrom?: string,
|
||||
@Query('dateTo') dateTo?: string,
|
||||
@Query('page') page?: string,
|
||||
@@ -44,9 +174,7 @@ export class PassengersController {
|
||||
) {
|
||||
return this.service.findAll({
|
||||
search,
|
||||
verified: verified ? verified === 'true' : undefined,
|
||||
gender,
|
||||
nationality,
|
||||
dateFrom,
|
||||
dateTo,
|
||||
page: page ? parseInt(page) : 1,
|
||||
|
||||
@@ -8,6 +8,7 @@ export class CreateTravelerProfileDto {
|
||||
@ApiProperty({ example: 'SPOUSE' }) @IsString() relationship: string;
|
||||
@ApiPropertyOptional({ example: '1998-04-01' }) @IsOptional() @IsDateString() dateOfBirth?: string;
|
||||
@ApiPropertyOptional({ example: 'ET-1234-5678' }) @IsOptional() @IsString() nationalId?: string;
|
||||
@ApiPropertyOptional({ example: 'Female' }) @IsOptional() @IsString() gender?: string;
|
||||
@ApiPropertyOptional() @IsOptional() @IsString() notes?: string;
|
||||
}
|
||||
|
||||
|
||||
@@ -4,12 +4,11 @@ import { DataSource } from 'typeorm';
|
||||
import { PrismaService } from '../../common/prisma.service';
|
||||
import { CreateTravelerProfileDto, CreateSavedRouteDto, RegisterPassengerDto } from './passengers.dto';
|
||||
import { VerifaydaService } from '../verifayda/verifayda.service';
|
||||
import { DeleteOperationException } from '../../common/exceptions/delete-operation.exception';
|
||||
|
||||
interface PassengerFilters {
|
||||
search?: string;
|
||||
verified?: boolean;
|
||||
gender?: string;
|
||||
nationality?: string;
|
||||
dateFrom?: string;
|
||||
dateTo?: string;
|
||||
page?: number;
|
||||
@@ -33,31 +32,21 @@ export class PassengersService {
|
||||
) {}
|
||||
|
||||
async findAll(filters: PassengerFilters = {}) {
|
||||
const { search, verified, gender, nationality, dateFrom, dateTo, page = 1, pageSize = 20 } = filters;
|
||||
const { search, gender, dateFrom, dateTo, page = 1, pageSize = 20 } = filters;
|
||||
const skip = (page - 1) * pageSize;
|
||||
|
||||
const where: any = {};
|
||||
|
||||
if (search) {
|
||||
where.user = {
|
||||
OR: [
|
||||
{ email: { contains: search, mode: 'insensitive' } },
|
||||
{ phone: { contains: search, mode: 'insensitive' } },
|
||||
{ fullName: { contains: search, mode: 'insensitive' } },
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (verified !== undefined) {
|
||||
where.user = { ...(where.user ?? {}), faydaVerified: verified };
|
||||
where.OR = [
|
||||
{ fullName: { contains: search, mode: 'insensitive' } },
|
||||
{ passenger: { user: { email: { contains: search, mode: 'insensitive' } } } },
|
||||
{ passenger: { user: { phone: { contains: search, mode: 'insensitive' } } } },
|
||||
];
|
||||
}
|
||||
|
||||
if (gender) {
|
||||
where.user = { ...(where.user ?? {}), gender };
|
||||
}
|
||||
|
||||
if (nationality) {
|
||||
where.user = { ...(where.user ?? {}), nationality: { contains: nationality, mode: 'insensitive' } };
|
||||
where.gender = gender;
|
||||
}
|
||||
|
||||
if (dateFrom || dateTo) {
|
||||
@@ -68,34 +57,43 @@ export class PassengersService {
|
||||
}
|
||||
|
||||
const [items, total] = await Promise.all([
|
||||
this.prisma.passenger.findMany({
|
||||
this.prisma.travelerProfile.findMany({
|
||||
where,
|
||||
skip,
|
||||
take: pageSize,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
include: {
|
||||
user: true,
|
||||
loyalty: true,
|
||||
wallet: true,
|
||||
_count: { select: { bookings: true } },
|
||||
bookings: {
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take: 1,
|
||||
select: {
|
||||
contactEmail: true,
|
||||
contactPhone: true,
|
||||
seats: { take: 1, orderBy: { id: 'asc' }, select: {
|
||||
passengerName: true, dateOfBirth: true, passportNumber: true,
|
||||
passportCountry: true, idDocumentType: true, verifaydaVerified: true, faydaVerifiedAt: true,
|
||||
}},
|
||||
passenger: {
|
||||
include: {
|
||||
user: true,
|
||||
loyalty: true,
|
||||
wallet: true,
|
||||
_count: { select: { bookings: true } },
|
||||
bookings: {
|
||||
take: 1,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
select: {
|
||||
contactPhone: true,
|
||||
contactEmail: true,
|
||||
seats: {
|
||||
take: 1,
|
||||
orderBy: { id: 'asc' },
|
||||
select: {
|
||||
passengerName: true,
|
||||
passportNumber: true,
|
||||
passportCountry: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
this.prisma.passenger.count({ where }),
|
||||
this.prisma.travelerProfile.count({ where }),
|
||||
]);
|
||||
|
||||
const iamUserIds = items.map(p => p.iamUserId).filter(Boolean) as string[];
|
||||
const iamUserIds = items.map(p => p.passenger?.iamUserId).filter(Boolean) as string[];
|
||||
const iamRows = iamUserIds.length > 0
|
||||
? await this.dataSource.query<IamUserRow[]>(
|
||||
`SELECT id, email, name, phone_number, metadata FROM iam.users WHERE id = ANY($1)`,
|
||||
@@ -104,72 +102,51 @@ export class PassengersService {
|
||||
: [];
|
||||
const iamMap = new Map(iamRows.map(r => [r.id, r]));
|
||||
|
||||
// Collect guest contact details for bulk SavedPassengerProfile lookup
|
||||
const guestContacts = items
|
||||
.filter(p => !(p as any).user && !p.iamUserId)
|
||||
.map(p => (p as any).bookings?.[0])
|
||||
.filter(Boolean);
|
||||
const guestEmails = guestContacts.map((b: any) => b.contactEmail).filter(Boolean) as string[];
|
||||
const guestPhones = guestContacts.map((b: any) => b.contactPhone).filter(Boolean) as string[];
|
||||
|
||||
const savedProfiles = (guestEmails.length || guestPhones.length)
|
||||
? await this.prisma.savedPassengerProfile.findMany({
|
||||
where: { OR: [
|
||||
...(guestEmails.length ? [{ email: { in: guestEmails } }] : []),
|
||||
...(guestPhones.length ? [{ phone: { in: guestPhones } }] : []),
|
||||
]},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
})
|
||||
: [];
|
||||
|
||||
// Index by email then phone for O(1) lookup
|
||||
const profileByEmail = new Map(savedProfiles.filter(s => s.email).map(s => [s.email!, s]));
|
||||
const profileByPhone = new Map(savedProfiles.filter(s => s.phone).map(s => [s.phone!, s]));
|
||||
|
||||
return {
|
||||
items: items.map(passenger => {
|
||||
const localUser = (passenger as any).user ?? null;
|
||||
const iam = passenger.iamUserId ? iamMap.get(passenger.iamUserId) : undefined;
|
||||
items: items.map(profile => {
|
||||
const passenger = profile.passenger;
|
||||
const localUser = (passenger as any)?.user ?? null;
|
||||
const iam = passenger?.iamUserId ? iamMap.get(passenger.iamUserId) : undefined;
|
||||
const faydaVerified = localUser?.faydaVerified === true
|
||||
|| iam?.metadata?.faydaVerified === true
|
||||
|| iam?.metadata?.faydaVerified === 'true';
|
||||
const guestBooking = !localUser && !iam ? (passenger as any).bookings?.[0] : null;
|
||||
|
||||
// Get additional data from bookings for guest passengers
|
||||
const guestBooking = (passenger as any)?.bookings?.[0] ?? null;
|
||||
const guestSeat = guestBooking?.seats?.[0] ?? null;
|
||||
const savedProfile = guestBooking
|
||||
? (profileByEmail.get(guestBooking.contactEmail) ?? profileByPhone.get(guestBooking.contactPhone) ?? null)
|
||||
: null;
|
||||
|
||||
return {
|
||||
id: passenger.id,
|
||||
fullName: localUser?.fullName ?? iam?.name?.en ?? iam?.name?.am ?? savedProfile?.passengerName ?? guestSeat?.passengerName ?? null,
|
||||
email: localUser?.email ?? iam?.email ?? savedProfile?.email ?? guestBooking?.contactEmail ?? null,
|
||||
phone: localUser?.phone ?? iam?.phone_number ?? savedProfile?.phone ?? guestBooking?.contactPhone ?? null,
|
||||
gender: localUser?.gender ?? iam?.metadata?.gender ?? null,
|
||||
dateOfBirth: localUser?.dateOfBirth
|
||||
? (localUser.dateOfBirth instanceof Date ? localUser.dateOfBirth.toISOString().split('T')[0] : localUser.dateOfBirth)
|
||||
: (iam?.metadata?.dateOfBirth ?? (savedProfile?.dateOfBirth
|
||||
? new Date(savedProfile.dateOfBirth).toISOString().split('T')[0]
|
||||
: (guestSeat?.dateOfBirth ? new Date(guestSeat.dateOfBirth).toISOString().split('T')[0] : null))),
|
||||
nationality: localUser?.nationality ?? iam?.metadata?.nationality ?? savedProfile?.nationality ?? null,
|
||||
id: profile.id,
|
||||
fullName: profile.fullName,
|
||||
email: localUser?.email ?? iam?.email ?? guestBooking?.contactEmail ?? null,
|
||||
phone: localUser?.phone ?? iam?.phone_number ?? guestBooking?.contactPhone ?? null,
|
||||
gender: profile.gender ?? localUser?.gender ?? iam?.metadata?.gender ?? null,
|
||||
dateOfBirth: profile.dateOfBirth
|
||||
? new Date(profile.dateOfBirth).toISOString().split('T')[0]
|
||||
: (localUser?.dateOfBirth
|
||||
? (localUser.dateOfBirth instanceof Date ? localUser.dateOfBirth.toISOString().split('T')[0] : localUser.dateOfBirth)
|
||||
: iam?.metadata?.dateOfBirth ?? null),
|
||||
nationality: localUser?.nationality ?? iam?.metadata?.nationality ?? (guestSeat?.passportCountry ? (guestSeat.passportCountry === 'Ethiopia' ? 'Ethiopian' : guestSeat.passportCountry) : null),
|
||||
nationalityCode: localUser?.nationalityCode ?? iam?.metadata?.nationalityCode ?? null,
|
||||
faydaVerified,
|
||||
faydaVerifiedAt: localUser?.faydaVerifiedAt ?? iam?.metadata?.faydaVerifiedAt ?? guestSeat?.faydaVerifiedAt ?? null,
|
||||
passportNumber: localUser?.passportNumber ?? iam?.metadata?.passportNumber ?? savedProfile?.passportNumber ?? guestSeat?.passportNumber ?? null,
|
||||
passportCountry: localUser?.passportCountry ?? iam?.metadata?.passportCountry ?? savedProfile?.passportCountry ?? guestSeat?.passportCountry ?? null,
|
||||
faydaVerifiedAt: localUser?.faydaVerifiedAt ?? iam?.metadata?.faydaVerifiedAt ?? null,
|
||||
passportNumber: localUser?.passportNumber ?? iam?.metadata?.passportNumber ?? guestSeat?.passportNumber ?? null,
|
||||
passportCountry: localUser?.passportCountry ?? iam?.metadata?.passportCountry ?? guestSeat?.passportCountry ?? null,
|
||||
passportExpiryDate: localUser?.passportExpiryDate ?? iam?.metadata?.passportExpiryDate ?? null,
|
||||
idDocumentType: savedProfile?.idDocumentType ?? guestSeat?.idDocumentType ?? null,
|
||||
idDocumentType: profile.nationalId ? 'NATIONAL_ID' : null,
|
||||
verified: faydaVerified,
|
||||
lastLoginAt: localUser?.lastLoginAt ?? null,
|
||||
role: localUser?.role ?? null,
|
||||
loyalty: passenger.loyalty
|
||||
loyalty: passenger?.loyalty
|
||||
? { tier: passenger.loyalty.tier, pointsBalance: passenger.loyalty.pointsBalance, lifetimePoints: (passenger.loyalty as any).lifetimePoints ?? 0 }
|
||||
: null,
|
||||
wallet: (passenger as any).wallet
|
||||
wallet: (passenger as any)?.wallet
|
||||
? { balanceMinor: (passenger as any).wallet.balanceMinor, currency: (passenger as any).wallet.currency ?? 'ETB' }
|
||||
: null,
|
||||
loyaltyTier: passenger.loyalty?.tier || 'BRONZE',
|
||||
loyaltyPoints: passenger.loyalty?.pointsBalance || 0,
|
||||
totalBookings: passenger._count.bookings,
|
||||
createdAt: passenger.createdAt,
|
||||
loyaltyTier: passenger?.loyalty?.tier || 'BRONZE',
|
||||
loyaltyPoints: passenger?.loyalty?.pointsBalance || 0,
|
||||
totalBookings: passenger?._count?.bookings || 0,
|
||||
createdAt: profile.createdAt,
|
||||
};
|
||||
}),
|
||||
meta: {
|
||||
@@ -299,8 +276,13 @@ export class PassengersService {
|
||||
createTravelerProfile(dto: CreateTravelerProfileDto) {
|
||||
return this.prisma.travelerProfile.create({
|
||||
data: {
|
||||
...dto,
|
||||
dateOfBirth: dto.dateOfBirth ? new Date(dto.dateOfBirth) : null
|
||||
passengerId: dto.passengerId,
|
||||
fullName: dto.fullName,
|
||||
relationship: dto.relationship,
|
||||
dateOfBirth: dto.dateOfBirth ? new Date(dto.dateOfBirth) : null,
|
||||
nationalId: dto.nationalId || null,
|
||||
gender: dto.gender || null,
|
||||
notes: dto.notes || null,
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -440,9 +422,21 @@ export class PassengersService {
|
||||
}
|
||||
|
||||
async deletePassenger(id: string) {
|
||||
const passenger = await this.prisma.passenger.findUnique({ where: { id } });
|
||||
const passenger = await this.prisma.passenger.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
user: true
|
||||
}
|
||||
});
|
||||
if (!passenger) throw new NotFoundException('Passenger not found');
|
||||
|
||||
// Check usage before allowing deletion
|
||||
const usage = await this.checkPassengerUsage(id);
|
||||
if (usage.isInUse && usage.constraints) {
|
||||
const passengerName = (passenger as any).user?.fullName || `Passenger ${id.slice(-8)}`;
|
||||
throw new DeleteOperationException('Passenger', passengerName, usage.constraints);
|
||||
}
|
||||
|
||||
await this.prisma.$transaction([
|
||||
this.prisma.loyaltyLedgerEntry.deleteMany({ where: { account: { passengerId: id } } }),
|
||||
this.prisma.loyaltyAccount.deleteMany({ where: { passengerId: id } }),
|
||||
@@ -470,14 +464,15 @@ export class PassengersService {
|
||||
this.prisma.walletAccount.findUnique({ where: { passengerId: id } }),
|
||||
]);
|
||||
|
||||
const usage = [];
|
||||
if (bookingCount > 0) usage.push(`${bookingCount} booking(s)`);
|
||||
if (loyaltyAccount) usage.push('Loyalty account');
|
||||
if (walletAccount) usage.push('Wallet account');
|
||||
const constraints = [];
|
||||
if (bookingCount > 0) constraints.push({ entityName: 'booking', count: bookingCount, action: 'complete' as const });
|
||||
if (loyaltyAccount) constraints.push({ entityName: 'loyalty account', count: 1, action: 'delete' as const });
|
||||
if (walletAccount) constraints.push({ entityName: 'wallet account', count: 1, action: 'delete' as const });
|
||||
|
||||
return {
|
||||
isInUse: usage.length > 0,
|
||||
affectedModules: usage,
|
||||
isInUse: constraints.length > 0,
|
||||
affectedModules: constraints.map(c => `${c.count} ${c.entityName}${c.count > 1 ? 's' : ''}`),
|
||||
constraints
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
Get,
|
||||
HttpStatus,
|
||||
Param,
|
||||
Patch,
|
||||
Post,
|
||||
Query,
|
||||
Res,
|
||||
@@ -123,6 +124,16 @@ export class PaymentsController {
|
||||
return this.service.addPaymentMethod(dto);
|
||||
}
|
||||
|
||||
@Patch("methods/:id")
|
||||
@PassengerStaff([PASSENGER_PERMS.payments.manageMethods, PASSENGER_PERMS.admin])
|
||||
@ApiBearerAuth("IAM-auth")
|
||||
@ApiOperation({
|
||||
summary: "Update a payment method configuration (admin only)",
|
||||
})
|
||||
updateMethod(@Param("id") id: string, @Body() dto: Partial<AddPaymentMethodDto>) {
|
||||
return this.service.updatePaymentMethod(id, dto);
|
||||
}
|
||||
|
||||
@Get("methods")
|
||||
@SetMetadata('isPublic', true)
|
||||
@ApiOperation({
|
||||
|
||||
@@ -473,6 +473,24 @@ export class PaymentsService {
|
||||
});
|
||||
}
|
||||
|
||||
async updatePaymentMethod(id: string, dto: Partial<AddPaymentMethodDto>) {
|
||||
const existing = await this.prisma.paymentMethod.findUnique({ where: { id } });
|
||||
if (!existing) throw new NotFoundException('Payment method not found');
|
||||
|
||||
const updateData: any = {};
|
||||
if (dto.displayName !== undefined) updateData.displayName = dto.displayName;
|
||||
if (dto.region !== undefined) updateData.region = dto.region as unknown as PaymentRegion;
|
||||
if (dto.currency !== undefined) updateData.currency = dto.currency;
|
||||
if (dto.providerId !== undefined) updateData.providerId = dto.providerId;
|
||||
if (dto.enabled !== undefined) updateData.enabled = dto.enabled;
|
||||
if (dto.sortOrder !== undefined) updateData.sortOrder = dto.sortOrder;
|
||||
|
||||
return this.prisma.paymentMethod.update({
|
||||
where: { id },
|
||||
data: updateData,
|
||||
});
|
||||
}
|
||||
|
||||
getSupportedPaymentMethods(region?: PaymentRegionEnum, currency?: string) {
|
||||
return this.prisma.paymentMethod.findMany({
|
||||
where: {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Injectable, NotFoundException, ConflictException, BadRequestException } from '@nestjs/common';
|
||||
import { PrismaService } from '../../common/prisma.service';
|
||||
import { CreateRouteDto, AddRouteStopDto, UpdateRouteDto } from './routes.dto';
|
||||
import { DeleteOperationException } from '../../common/exceptions/delete-operation.exception';
|
||||
|
||||
@Injectable()
|
||||
export class RoutesService {
|
||||
@@ -93,8 +94,28 @@ export class RoutesService {
|
||||
}
|
||||
|
||||
async deleteRoute(id: string) {
|
||||
const route = await this.prisma.route.findUnique({ where: { id } });
|
||||
const route = await this.prisma.route.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
schedules: true,
|
||||
stops: true
|
||||
}
|
||||
});
|
||||
if (!route) throw new NotFoundException('Route not found');
|
||||
|
||||
const constraints = [];
|
||||
if (route.schedules.length > 0) {
|
||||
constraints.push({
|
||||
entityName: 'schedule',
|
||||
count: route.schedules.length,
|
||||
action: 'delete' as const
|
||||
});
|
||||
}
|
||||
|
||||
if (constraints.length > 0) {
|
||||
throw new DeleteOperationException('Route', `${route.code} (${route.name})`, constraints);
|
||||
}
|
||||
|
||||
await this.prisma.route.delete({ where: { id } });
|
||||
return { deleted: true, id };
|
||||
}
|
||||
|
||||
@@ -3,6 +3,8 @@ import { PrismaService } from '../../common/prisma.service';
|
||||
import { RoutesService } from './routes.service';
|
||||
import { FareEngineService } from '../fare-engine/fare-engine.service';
|
||||
import { CreateScheduleDto, UpdateScheduleDto, CreateFareRuleDto, UpdateScheduleStatusDto, UpdateStopTimeDto, ListSchedulesDto, BulkCreateSchedulesDto } from './schedules.dto';
|
||||
import { DeleteOperationException } from '../../common/exceptions/delete-operation.exception';
|
||||
import { parseEthiopianTime, startOfDayEAT, startOfNextDayEAT } from '../../common/utils/timezone.utils';
|
||||
|
||||
@Injectable()
|
||||
export class SchedulesService {
|
||||
@@ -13,7 +15,7 @@ export class SchedulesService {
|
||||
) { }
|
||||
|
||||
async bulkGenerateSchedules(dto: BulkCreateSchedulesDto) {
|
||||
const startDate = new Date(dto.startDateTime);
|
||||
const startDate = parseEthiopianTime(dto.startDateTime);
|
||||
const endDate = new Date(startDate.getTime() + dto.forNextDays * 24 * 60 * 60 * 1000);
|
||||
const errors: string[] = [];
|
||||
const scheduleIds: string[] = [];
|
||||
@@ -66,8 +68,8 @@ export class SchedulesService {
|
||||
const where: any = {};
|
||||
|
||||
if (dto.date) {
|
||||
const date = new Date(dto.date);
|
||||
const nextDay = new Date(date.getTime() + 86_400_000);
|
||||
const date = parseEthiopianTime(dto.date);
|
||||
const nextDay = startOfNextDayEAT(date);
|
||||
where.departureAt = { gte: date, lt: nextDay };
|
||||
}
|
||||
if (dto.routeId) where.routeId = dto.routeId;
|
||||
@@ -93,8 +95,9 @@ export class SchedulesService {
|
||||
}
|
||||
|
||||
async createSchedule(dto: CreateScheduleDto) {
|
||||
const dep = new Date(dto.departureAt);
|
||||
const arr = new Date(dto.arrivalAt);
|
||||
// Parse dates in local Ethiopian time (EAT - UTC+3)
|
||||
const dep = parseEthiopianTime(dto.departureAt);
|
||||
const arr = parseEthiopianTime(dto.arrivalAt);
|
||||
if (arr <= dep) throw new BadRequestException('arrivalAt must be after departureAt');
|
||||
|
||||
const route = await this.prisma.route.findUnique({
|
||||
@@ -105,10 +108,9 @@ export class SchedulesService {
|
||||
if (!route.active) throw new BadRequestException('Route is not active');
|
||||
if (route.stops.length < 2) throw new BadRequestException('Route must have at least 2 stops');
|
||||
|
||||
const depDate = new Date(dep);
|
||||
depDate.setHours(0, 0, 0, 0);
|
||||
const nextDay = new Date(depDate);
|
||||
nextDay.setDate(nextDay.getDate() + 1);
|
||||
// Check for existing schedule on the same day (local Ethiopian time)
|
||||
const depDate = startOfDayEAT(dep);
|
||||
const nextDay = startOfNextDayEAT(dep);
|
||||
|
||||
const existingSchedule = await this.prisma.trainSchedule.findFirst({
|
||||
where: { trainId: dto.trainId, routeId: dto.routeId, departureAt: { gte: depDate, lt: nextDay } },
|
||||
@@ -240,8 +242,9 @@ export class SchedulesService {
|
||||
const schedule = await this.prisma.trainSchedule.findUnique({ where: { id } });
|
||||
if (!schedule) throw new NotFoundException('Schedule not found');
|
||||
|
||||
const dep = new Date(dto.departureAt);
|
||||
const arr = new Date(dto.arrivalAt);
|
||||
// Parse dates in local Ethiopian time (EAT - UTC+3)
|
||||
const dep = parseEthiopianTime(dto.departureAt);
|
||||
const arr = parseEthiopianTime(dto.arrivalAt);
|
||||
if (arr <= dep) throw new BadRequestException('arrivalAt must be after departureAt');
|
||||
|
||||
const route = await this.prisma.route.findUnique({
|
||||
@@ -308,16 +311,59 @@ export class SchedulesService {
|
||||
async deleteSchedule(id: string) {
|
||||
const schedule = await this.prisma.trainSchedule.findUnique({
|
||||
where: { id },
|
||||
include: { _count: { select: { bookings: true } } },
|
||||
include: {
|
||||
_count: { select: { bookings: true } },
|
||||
train: true,
|
||||
originStation: true,
|
||||
destinationStation: true
|
||||
},
|
||||
});
|
||||
if (!schedule) throw new NotFoundException('Schedule not found');
|
||||
|
||||
const constraints = [];
|
||||
if ((schedule as any)._count.bookings > 0) {
|
||||
throw new BadRequestException(
|
||||
`Cannot delete schedule. It has ${(schedule as any)._count.bookings} booking(s). Cancel all bookings before deleting.`,
|
||||
);
|
||||
constraints.push({
|
||||
entityName: 'booking',
|
||||
count: (schedule as any)._count.bookings,
|
||||
action: 'cancel' as const
|
||||
});
|
||||
}
|
||||
|
||||
if (constraints.length > 0) {
|
||||
const scheduleName = `${schedule.train.number} (${schedule.originStation.name} → ${schedule.destinationStation.name})`;
|
||||
throw new DeleteOperationException('Schedule', scheduleName, constraints);
|
||||
}
|
||||
|
||||
await this.prisma.tripStopTime.deleteMany({ where: { scheduleId: id } });
|
||||
await this.prisma.coachAssignment.deleteMany({ where: { scheduleId: id } });
|
||||
await this.prisma.tripLiveStatus.deleteMany({ where: { scheduleId: id } });
|
||||
await this.prisma.menuItem.deleteMany({ where: { scheduleId: id } });
|
||||
await this.prisma.journeySegment.deleteMany({ where: { scheduleId: id } });
|
||||
|
||||
// Delete travel packages that reference this schedule (required fields cannot be nulled)
|
||||
// First get packages that reference this schedule
|
||||
const packagesToDelete = await this.prisma.travelPackage.findMany({
|
||||
where: {
|
||||
OR: [
|
||||
{ outboundScheduleId: id },
|
||||
{ returnScheduleId: id }
|
||||
]
|
||||
},
|
||||
select: { id: true }
|
||||
});
|
||||
|
||||
// Delete price tiers first (they have foreign key to packages)
|
||||
if (packagesToDelete.length > 0) {
|
||||
const packageIds = packagesToDelete.map(p => p.id);
|
||||
await this.prisma.packagePriceTier.deleteMany({
|
||||
where: { packageId: { in: packageIds } }
|
||||
});
|
||||
|
||||
// Now delete the packages
|
||||
await this.prisma.travelPackage.deleteMany({
|
||||
where: { id: { in: packageIds } }
|
||||
});
|
||||
}
|
||||
return this.prisma.trainSchedule.delete({ where: { id } });
|
||||
}
|
||||
|
||||
@@ -338,8 +384,8 @@ export class SchedulesService {
|
||||
return this.prisma.tripStopTime.update({
|
||||
where: { scheduleId_sequence: { scheduleId, sequence } },
|
||||
data: {
|
||||
plannedArrivalAt: dto.plannedArrivalAt ? new Date(dto.plannedArrivalAt) : undefined,
|
||||
plannedDepartureAt: dto.plannedDepartureAt ? new Date(dto.plannedDepartureAt) : undefined,
|
||||
plannedArrivalAt: dto.plannedArrivalAt ? parseEthiopianTime(dto.plannedArrivalAt) : undefined,
|
||||
plannedDepartureAt: dto.plannedDepartureAt ? parseEthiopianTime(dto.plannedDepartureAt) : undefined,
|
||||
status: dto.status,
|
||||
},
|
||||
include: { station: true },
|
||||
@@ -353,8 +399,8 @@ export class SchedulesService {
|
||||
...rest,
|
||||
tripId: scheduleId,
|
||||
nationality,
|
||||
validFrom: new Date(validFrom),
|
||||
validUntil: validUntil ? new Date(validUntil) : null,
|
||||
validFrom: parseEthiopianTime(validFrom),
|
||||
validUntil: validUntil ? parseEthiopianTime(validUntil) : null,
|
||||
},
|
||||
include: { seatClass: true },
|
||||
});
|
||||
@@ -371,8 +417,8 @@ export class SchedulesService {
|
||||
...rest,
|
||||
...(scheduleId !== undefined && { tripId: scheduleId }),
|
||||
...(nationality !== undefined && { nationality }),
|
||||
...(validFrom && { validFrom: new Date(validFrom) }),
|
||||
...(validUntil !== undefined && { validUntil: validUntil ? new Date(validUntil) : null }),
|
||||
...(validFrom && { validFrom: parseEthiopianTime(validFrom) }),
|
||||
...(validUntil !== undefined && { validUntil: validUntil ? parseEthiopianTime(validUntil) : null }),
|
||||
},
|
||||
include: { seatClass: true },
|
||||
});
|
||||
@@ -390,8 +436,8 @@ export class SchedulesService {
|
||||
return this.prisma.segmentFareRule.create({
|
||||
data: {
|
||||
...rest,
|
||||
validFrom: new Date(validFrom),
|
||||
validUntil: validUntil ? new Date(validUntil) : null,
|
||||
validFrom: parseEthiopianTime(validFrom),
|
||||
validUntil: validUntil ? parseEthiopianTime(validUntil) : null,
|
||||
},
|
||||
include: { seatClass: true, route: true },
|
||||
});
|
||||
@@ -415,8 +461,8 @@ export class SchedulesService {
|
||||
where: { id },
|
||||
data: {
|
||||
...rest,
|
||||
validFrom: validFrom ? new Date(validFrom) : undefined,
|
||||
validUntil: validUntil ? new Date(validUntil) : null,
|
||||
validFrom: validFrom ? parseEthiopianTime(validFrom) : undefined,
|
||||
validUntil: validUntil ? parseEthiopianTime(validUntil) : null,
|
||||
},
|
||||
include: { seatClass: true, route: true },
|
||||
});
|
||||
@@ -523,8 +569,8 @@ export class SchedulesService {
|
||||
const updateData: any = {};
|
||||
|
||||
if (dto.departureAt || dto.arrivalAt) {
|
||||
const dep = dto.departureAt ? new Date(dto.departureAt) : new Date(schedule.departureAt);
|
||||
const arr = dto.arrivalAt ? new Date(dto.arrivalAt) : new Date(schedule.arrivalAt);
|
||||
const dep = dto.departureAt ? parseEthiopianTime(dto.departureAt) : new Date(schedule.departureAt);
|
||||
const arr = dto.arrivalAt ? parseEthiopianTime(dto.arrivalAt) : new Date(schedule.arrivalAt);
|
||||
if (arr <= dep) throw new BadRequestException('Arrival time must be after departure time');
|
||||
updateData.departureAt = dep;
|
||||
updateData.arrivalAt = arr;
|
||||
|
||||
@@ -33,7 +33,7 @@ export class SeatsController {
|
||||
@SetMetadata('isPublic', true)
|
||||
@ApiOperation({
|
||||
summary: "Get seat map filtered by coach type",
|
||||
description: `Returns all coaches of the given coachTypeId assigned to the schedule, each with their full seat list and real-time availability. Origin and destination are derived from the schedule. Omit coachTypeId to get all coaches.`,
|
||||
description: `Returns all coaches of the given coachTypeId assigned to the schedule, each with their full seat list and real-time availability. Origin and destination are derived from the schedule. Omit coachTypeId to get all coaches. Use journeyDirection to filter seat holds (OUTBOUND vs RETURN for round-trip bookings).`,
|
||||
})
|
||||
@ApiParam({ name: "scheduleId", description: "TrainSchedule UUID" })
|
||||
@ApiQuery({
|
||||
@@ -42,6 +42,23 @@ export class SeatsController {
|
||||
description:
|
||||
"Filter by CoachType UUID — returns all coaches of that type (e.g. all Economy coaches)",
|
||||
})
|
||||
@ApiQuery({
|
||||
name: "journeyDirection",
|
||||
required: false,
|
||||
enum: ['ONE_WAY', 'OUTBOUND', 'RETURN'],
|
||||
description:
|
||||
"Journey direction for round-trip bookings. Filters seat holds to show only conflicting holds. Use OUTBOUND for outbound leg, RETURN for return leg. Defaults to ONE_WAY (shows all holds).",
|
||||
})
|
||||
@ApiQuery({
|
||||
name: "originStationId",
|
||||
required: false,
|
||||
description: "Origin station UUID for segment-specific seat availability",
|
||||
})
|
||||
@ApiQuery({
|
||||
name: "destinationStationId",
|
||||
required: false,
|
||||
description: "Destination station UUID for segment-specific seat availability",
|
||||
})
|
||||
@ApiResponse({
|
||||
status: 200,
|
||||
description:
|
||||
@@ -50,8 +67,17 @@ export class SeatsController {
|
||||
getSeatMap(
|
||||
@Param("scheduleId") scheduleId: string,
|
||||
@Query("coachTypeId") coachTypeId?: string,
|
||||
@Query("journeyDirection") journeyDirection?: string,
|
||||
@Query("originStationId") originStationId?: string,
|
||||
@Query("destinationStationId") destinationStationId?: string,
|
||||
) {
|
||||
return this.service.getSeatMap(scheduleId, coachTypeId);
|
||||
return this.service.getSeatMap(
|
||||
scheduleId,
|
||||
coachTypeId,
|
||||
journeyDirection as any,
|
||||
originStationId,
|
||||
destinationStationId
|
||||
);
|
||||
}
|
||||
|
||||
// ── Hold / Release ────────────────────────────────────────────────────────
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
import { IsString, IsArray, ValidateNested } from 'class-validator';
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsString, IsArray, ValidateNested, IsOptional, IsEnum } from 'class-validator';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { Type } from 'class-transformer';
|
||||
|
||||
export enum JourneyDirection {
|
||||
ONE_WAY = 'ONE_WAY',
|
||||
OUTBOUND = 'OUTBOUND',
|
||||
RETURN = 'RETURN'
|
||||
}
|
||||
|
||||
export class PassengerSeatDto {
|
||||
@ApiProperty({ example: 'passenger-uuid', description: 'Passenger UUID' })
|
||||
@IsString() passengerId: string;
|
||||
@@ -20,6 +26,15 @@ export class HoldSeatsDto {
|
||||
@ApiProperty({ example: 'station-uuid', description: 'Destination station UUID for this leg' })
|
||||
@IsString() destinationStationId: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
enum: JourneyDirection,
|
||||
example: JourneyDirection.OUTBOUND,
|
||||
description: 'Journey direction for round-trip bookings. ONE_WAY for single journeys, OUTBOUND/RETURN for round-trip legs. Allows same seats to be held for different directions.'
|
||||
})
|
||||
@IsOptional()
|
||||
@IsEnum(JourneyDirection)
|
||||
journeyDirection?: JourneyDirection;
|
||||
|
||||
@ApiProperty({
|
||||
type: [PassengerSeatDto],
|
||||
description: 'One entry per passenger. Each passenger is assigned exactly one seat. Duplicate passengerId or seatId within the same request is rejected.',
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Injectable, ConflictException, NotFoundException, BadRequestException } from '@nestjs/common';
|
||||
import { PrismaService } from '../../common/prisma.service';
|
||||
import { HoldSeatsDto } from './seats.dto';
|
||||
import { HoldSeatsDto, JourneyDirection } 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';
|
||||
@@ -13,7 +13,7 @@ export class SeatsService {
|
||||
private systemConfig: SystemConfigService,
|
||||
) {}
|
||||
|
||||
async getSeatMap(scheduleId: string, coachTypeId?: string) {
|
||||
async getSeatMap(scheduleId: string, coachTypeId?: string, journeyDirection?: JourneyDirection, originStationId?: string, destinationStationId?: string) {
|
||||
const schedule = await this.prisma.trainSchedule.findUnique({
|
||||
where: { id: scheduleId },
|
||||
select: { originStationId: true, destinationStationId: true },
|
||||
@@ -37,7 +37,13 @@ export class SeatsService {
|
||||
});
|
||||
|
||||
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);
|
||||
const effectiveStatuses = await this.resolveEffectiveStatuses(
|
||||
scheduleId,
|
||||
allSeatIds,
|
||||
originStationId ?? schedule.originStationId,
|
||||
destinationStationId ?? schedule.destinationStationId,
|
||||
journeyDirection
|
||||
);
|
||||
|
||||
return {
|
||||
coaches: assignments.map((a) => {
|
||||
@@ -179,6 +185,7 @@ export class SeatsService {
|
||||
seatIds: string[],
|
||||
originStationId?: string,
|
||||
destinationStationId?: string,
|
||||
journeyDirection?: JourneyDirection,
|
||||
): Promise<Map<string, string>> {
|
||||
const statusMap = new Map<string, string>();
|
||||
if (seatIds.length === 0) return statusMap;
|
||||
@@ -211,9 +218,13 @@ export class SeatsService {
|
||||
select: { seatIds: true, createdBy: true },
|
||||
});
|
||||
|
||||
const reqDirection = journeyDirection || JourneyDirection.ONE_WAY;
|
||||
|
||||
for (const hold of activeHolds) {
|
||||
let holdFrom: number | undefined;
|
||||
let holdTo: number | undefined;
|
||||
let holdDirection = JourneyDirection.ONE_WAY;
|
||||
|
||||
try {
|
||||
if (hold.createdBy?.trimStart().startsWith('{')) {
|
||||
const meta = JSON.parse(hold.createdBy);
|
||||
@@ -221,16 +232,26 @@ export class SeatsService {
|
||||
const seqOf = (id: string) => stops.find(s => s.stationId === id)?.sequence;
|
||||
holdFrom = seqOf(meta.originStationId);
|
||||
holdTo = seqOf(meta.destinationStationId);
|
||||
holdDirection = meta.journeyDirection || JourneyDirection.ONE_WAY;
|
||||
}
|
||||
} 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');
|
||||
}
|
||||
|
||||
// Check leg overlap
|
||||
const legsOverlap =
|
||||
reqFrom === undefined || reqTo === undefined ||
|
||||
holdFrom === undefined || holdTo === undefined ||
|
||||
(holdFrom < reqTo && reqFrom < holdTo);
|
||||
|
||||
if (!legsOverlap) continue;
|
||||
|
||||
// Check direction conflict
|
||||
const directionsConflict = this.checkDirectionConflict(reqDirection, holdDirection);
|
||||
if (!directionsConflict) continue;
|
||||
|
||||
statusMap.set(seatId, 'HELD');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -266,6 +287,36 @@ export class SeatsService {
|
||||
return statusMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if two journey directions conflict (should not be allowed simultaneously)
|
||||
* For round-trip bookings: OUTBOUND and RETURN should NOT conflict on same schedule
|
||||
*/
|
||||
private checkDirectionConflict(current: JourneyDirection, existing: JourneyDirection): boolean {
|
||||
// OUTBOUND and RETURN are allowed simultaneously (round-trip on different schedules)
|
||||
if ((current === JourneyDirection.OUTBOUND && existing === JourneyDirection.RETURN) ||
|
||||
(current === JourneyDirection.RETURN && existing === JourneyDirection.OUTBOUND)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Same directions conflict (e.g., two OUTBOUND or two RETURN bookings)
|
||||
if (current === existing) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// ONE_WAY conflicts with other ONE_WAY bookings only
|
||||
if (current === JourneyDirection.ONE_WAY && existing === JourneyDirection.ONE_WAY) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// ONE_WAY with OUTBOUND/RETURN: conflict (to maintain safety for legacy bookings)
|
||||
if (current === JourneyDirection.ONE_WAY || existing === JourneyDirection.ONE_WAY) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Default: no conflict
|
||||
return false;
|
||||
}
|
||||
|
||||
async holdSeats(dto: HoldSeatsDto) {
|
||||
const passengerIds = dto.passengers.map(p => p.passengerId);
|
||||
const seatIds = dto.passengers.map(p => p.seatId);
|
||||
@@ -307,19 +358,16 @@ export class SeatsService {
|
||||
throw new NotFoundException(`Seat(s) not found: ${missing.join(', ')}`);
|
||||
}
|
||||
|
||||
const blocked = seats.filter(s => s.status === 'BLOCKED' || s.status === 'BOOKED' || s.status === 'HELD');
|
||||
const blocked = seats.filter(s => s.status === 'BLOCKED' || s.status === 'BOOKED');
|
||||
if (blocked.length > 0)
|
||||
throw new ConflictException(`Seat(s) ${blocked.map(s => s.seatNumber).join(', ')} are already taken`);
|
||||
|
||||
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 seqOf = (stationId: string) => stopTimes.find(s => s.stationId === stationId)?.sequence;
|
||||
const reqFrom = seqOf(dto.originStationId);
|
||||
const reqTo = seqOf(dto.destinationStationId);
|
||||
|
||||
@@ -328,57 +376,46 @@ export class SeatsService {
|
||||
if (reqFrom >= reqTo)
|
||||
throw new BadRequestException('Origin must come before destination');
|
||||
|
||||
// ── Check existing holds for overlap ────────────────────────────────────
|
||||
const currentDirection = dto.journeyDirection || JourneyDirection.ONE_WAY;
|
||||
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[]; legUnknown: boolean }[] = [];
|
||||
for (const h of activeHolds) {
|
||||
const rawSeatIds = h.seatIds as string[];
|
||||
let holdDirection = JourneyDirection.ONE_WAY;
|
||||
let holdFrom = 0, holdTo = Number.MAX_SAFE_INTEGER;
|
||||
let passengerIds: string[] = [];
|
||||
let legUnknown = true;
|
||||
|
||||
try {
|
||||
if (h.createdBy?.trimStart().startsWith('{')) {
|
||||
const meta = JSON.parse(h.createdBy);
|
||||
const holdFrom = seqOf(meta.originStationId);
|
||||
const holdTo = seqOf(meta.destinationStationId);
|
||||
parsedHolds.push({
|
||||
seatIds: rawSeatIds,
|
||||
from: holdFrom ?? 0,
|
||||
to: holdTo ?? Number.MAX_SAFE_INTEGER,
|
||||
passengerIds: (meta.passengers ?? []).map((p: any) => p.passengerId),
|
||||
legUnknown: holdFrom === undefined || holdTo === undefined,
|
||||
});
|
||||
} else {
|
||||
// Legacy plain-string createdBy — can't determine leg; block conservatively.
|
||||
parsedHolds.push({ seatIds: rawSeatIds, from: 0, to: Number.MAX_SAFE_INTEGER, passengerIds: [], legUnknown: true });
|
||||
holdFrom = seqOf(meta.originStationId) ?? 0;
|
||||
holdTo = seqOf(meta.destinationStationId) ?? Number.MAX_SAFE_INTEGER;
|
||||
holdDirection = meta.journeyDirection || JourneyDirection.ONE_WAY;
|
||||
passengerIds = (meta.passengers ?? []).map((p: any) => p.passengerId);
|
||||
legUnknown = !meta.originStationId || !meta.destinationStationId;
|
||||
}
|
||||
} catch {
|
||||
// Malformed JSON — block conservatively.
|
||||
parsedHolds.push({ seatIds: rawSeatIds, from: 0, to: Number.MAX_SAFE_INTEGER, passengerIds: [], legUnknown: true });
|
||||
}
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
|
||||
for (const { passengerId, seatId } of dto.passengers) {
|
||||
for (const hold of parsedHolds) {
|
||||
const legsOverlap = hold.legUnknown || (hold.from < reqTo && reqFrom < hold.to);
|
||||
if (!legsOverlap) continue;
|
||||
const legsOverlap = legUnknown || (holdFrom < reqTo && reqFrom < holdTo);
|
||||
if (!legsOverlap) continue;
|
||||
|
||||
if (hold.seatIds.includes(seatId)) {
|
||||
throw new ConflictException(
|
||||
`Seat ${seatLabelById[seatId]} is already held for this leg`,
|
||||
);
|
||||
const directionsConflict = this.checkDirectionConflict(currentDirection, holdDirection);
|
||||
if (!directionsConflict) continue;
|
||||
|
||||
for (const { passengerId, seatId } of dto.passengers) {
|
||||
if (rawSeatIds.includes(seatId)) {
|
||||
throw new ConflictException(`Seat ${seatLabelById[seatId]} is already held for this leg`);
|
||||
}
|
||||
|
||||
if (!hold.legUnknown && hold.passengerIds.includes(passengerId)) {
|
||||
throw new ConflictException(
|
||||
`Passenger already holds a seat on this journey leg`,
|
||||
);
|
||||
if (!legUnknown && 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,
|
||||
@@ -392,25 +429,19 @@ export class SeatsService {
|
||||
if (!seg.seatId) continue;
|
||||
const segFrom = seqOf(seg.departureStationId);
|
||||
const segTo = seqOf(seg.arrivalStationId);
|
||||
// If stations can't be resolved, assume overlap (conservative) to prevent double-booking.
|
||||
const overlaps = (segFrom === undefined || segTo === undefined)
|
||||
? true
|
||||
: segFrom < reqTo && reqFrom < segTo;
|
||||
const overlaps = (segFrom === undefined || segTo === undefined) ? true : segFrom < reqTo && reqFrom < segTo;
|
||||
if (overlaps) {
|
||||
throw new ConflictException(
|
||||
`Seat ${seatLabelById[seg.seatId]} is already booked for this leg`,
|
||||
);
|
||||
throw new ConflictException(`Seat ${seatLabelById[seg.seatId]} is already booked for this leg`);
|
||||
}
|
||||
}
|
||||
|
||||
const holdMeta = {
|
||||
originStationId: dto.originStationId,
|
||||
originStationId: dto.originStationId,
|
||||
destinationStationId: dto.destinationStationId,
|
||||
journeyDirection: currentDirection,
|
||||
passengers: dto.passengers.map(p => ({ passengerId: p.passengerId, seatId: p.seatId })),
|
||||
};
|
||||
|
||||
// Mark seats as HELD so the status check catches them immediately on any
|
||||
// subsequent hold attempt (avoids relying solely on the SeatHold table scan).
|
||||
await tx.seat.updateMany({
|
||||
where: { id: { in: seatIds } },
|
||||
data: { status: 'HELD' },
|
||||
@@ -418,10 +449,10 @@ export class SeatsService {
|
||||
|
||||
return tx.seatHold.create({
|
||||
data: {
|
||||
scheduleId: dto.scheduleId,
|
||||
scheduleId: dto.scheduleId,
|
||||
passengerId: dto.passengers[0].passengerId,
|
||||
seatIds,
|
||||
createdBy: JSON.stringify(holdMeta),
|
||||
createdBy: JSON.stringify(holdMeta),
|
||||
expiresAt,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -5,7 +5,6 @@ export class CreateStationDto {
|
||||
@ApiProperty({ example: 'ADD' }) @IsString() code: string;
|
||||
@ApiProperty({ example: 'Addis Ababa' }) @IsString() name: string;
|
||||
@ApiProperty({ example: 'Addis Ababa' }) @IsString() city: string;
|
||||
@ApiPropertyOptional() @IsOptional() @IsString() timezone?: string;
|
||||
@ApiPropertyOptional() @IsOptional() @IsString() countryCode?: string;
|
||||
@ApiPropertyOptional({ example: 9.0054 }) @IsOptional() @IsNumber() lat?: number;
|
||||
@ApiPropertyOptional({ example: 38.7636 }) @IsOptional() @IsNumber() lng?: number;
|
||||
|
||||
@@ -68,8 +68,8 @@ export class StationsService {
|
||||
|
||||
async update(id: string, dto: Partial<CreateStationDto>) {
|
||||
const oldStation = await this.findOne(id);
|
||||
const { code, name, city, timezone, lat, lng } = dto;
|
||||
const data: any = { code, name, city, timezone, lat, lng };
|
||||
const { code, name, city, lat, lng } = dto;
|
||||
const data: any = { code, name, city, lat, lng };
|
||||
if ('countryCode' in dto) data.countryCode = (dto as any).countryCode;
|
||||
if ('sequence' in dto) data.sequence = (dto as any).sequence;
|
||||
if ('isOperational' in dto) data.isOperational = (dto as any).isOperational;
|
||||
|
||||
@@ -39,6 +39,7 @@ export class TicketsController {
|
||||
@ApiQuery({ name: 'arrivalDate', required: false })
|
||||
@ApiQuery({ name: 'dateFrom', required: false })
|
||||
@ApiQuery({ name: 'dateTo', required: false })
|
||||
@ApiQuery({ name: 'coachId', required: false })
|
||||
@ApiQuery({ name: 'skip', required: false })
|
||||
@ApiQuery({ name: 'take', required: false })
|
||||
listTickets(
|
||||
@@ -49,6 +50,7 @@ export class TicketsController {
|
||||
@Query('arrivalDate') arrivalDate?: string,
|
||||
@Query('dateFrom') dateFrom?: string,
|
||||
@Query('dateTo') dateTo?: string,
|
||||
@Query('coachId') coachId?: string,
|
||||
@Query('skip') skip?: string,
|
||||
@Query('take') take?: string,
|
||||
) {
|
||||
@@ -60,6 +62,7 @@ export class TicketsController {
|
||||
arrivalDate,
|
||||
dateFrom,
|
||||
dateTo,
|
||||
coachId,
|
||||
skip: skip ? parseInt(skip) : 0,
|
||||
take: take ? parseInt(take) : 50,
|
||||
});
|
||||
@@ -83,6 +86,31 @@ export class TicketsController {
|
||||
return this.service.getByRef(ref);
|
||||
}
|
||||
|
||||
@Post('scan-board/:qrCodeOrRef')
|
||||
@UseGuards(JwtGuard)
|
||||
@ApiBearerAuth('JWT-auth')
|
||||
@ApiOperation({
|
||||
summary: 'Scan QR code or booking ref and automatically board ticket',
|
||||
description: 'Scans ticket QR code or booking reference and automatically boards the passenger. Handles errors like expired tickets, already used tickets, etc. Designed for mobile boarding interface.'
|
||||
})
|
||||
@ApiBody({
|
||||
schema: {
|
||||
type: 'object',
|
||||
required: ['validatorId'],
|
||||
properties: {
|
||||
validatorId: { type: 'string', example: 'agent-uuid' },
|
||||
gateId: { type: 'string', example: 'gate-01' },
|
||||
},
|
||||
},
|
||||
})
|
||||
scanAndBoard(
|
||||
@Param('qrCodeOrRef') qrCodeOrRef: string,
|
||||
@Body('validatorId') validatorId: string,
|
||||
@Body('gateId') gateId?: string,
|
||||
) {
|
||||
return this.service.scanAndBoard(qrCodeOrRef, validatorId, gateId);
|
||||
}
|
||||
|
||||
@Post(':bookingRef/validate')
|
||||
@UseGuards(JwtGuard)
|
||||
@ApiBearerAuth('JWT-auth')
|
||||
|
||||
@@ -23,12 +23,13 @@ export class TicketsService {
|
||||
@InjectDataSource() private readonly dataSource: DataSource,
|
||||
) {}
|
||||
|
||||
async listTickets(filters: { search?: string; status?: string; originStationId?: string; destinationStationId?: string; arrivalDate?: string; dateFrom?: string; dateTo?: string; skip: number; take: number }) {
|
||||
async listTickets(filters: { search?: string; status?: string; originStationId?: string; destinationStationId?: string; arrivalDate?: string; dateFrom?: string; dateTo?: string; coachId?: string; skip: number; take: number }) {
|
||||
const where: any = {};
|
||||
if (filters.search) {
|
||||
where.OR = [
|
||||
{ bookingRef: { contains: filters.search, mode: 'insensitive' } },
|
||||
{ barcodePayload: { contains: filters.search, mode: 'insensitive' } },
|
||||
{ passengerName: { contains: filters.search, mode: 'insensitive' } },
|
||||
{ booking: { bookingRef: { contains: filters.search, mode: 'insensitive' } } },
|
||||
];
|
||||
}
|
||||
@@ -53,6 +54,12 @@ export class TicketsService {
|
||||
...(filters.dateTo ? { lte: new Date(new Date(filters.dateTo).setHours(23, 59, 59, 999)) } : {}),
|
||||
};
|
||||
}
|
||||
// if (filters.coachId) {
|
||||
// where.seat = {
|
||||
// coachId: filters.coachId
|
||||
// };
|
||||
// }
|
||||
|
||||
const [tickets, total] = await Promise.all([
|
||||
this.prisma.ticket.findMany({
|
||||
where,
|
||||
@@ -61,19 +68,20 @@ export class TicketsService {
|
||||
include: {
|
||||
schedule: { include: { originStation: true, destinationStation: true, train: true } },
|
||||
returnSchedule: { select: { departureAt: true, arrivalAt: true, originStation: true, destinationStation: true } },
|
||||
seats: { include: { seat: { include: { coach: { include: { coachType: true } } } } } },
|
||||
passenger: { select: { id: true, iamUserId: true } },
|
||||
seats: { include: { seat: { include: { coach: true } } } },
|
||||
},
|
||||
},
|
||||
},
|
||||
seat: { include: { coach: { include: { coachType: true } } } },
|
||||
} as any,
|
||||
skip: filters.skip,
|
||||
take: filters.take,
|
||||
orderBy: { issuedAt: 'desc' },
|
||||
}),
|
||||
}) as any,
|
||||
this.prisma.ticket.count({ where }),
|
||||
]);
|
||||
|
||||
const iamUserIds = tickets.map(t => t.booking.passenger?.iamUserId).filter(Boolean) as string[];
|
||||
const iamUserIds = tickets.map((t: any) => t.booking?.passenger?.iamUserId).filter(Boolean) as string[];
|
||||
const iamRows = iamUserIds.length > 0
|
||||
? await this.dataSource.query<{ id: string; email: string; name: any; phone_number: string | null }[]>(
|
||||
`SELECT id, email, name, phone_number FROM iam.users WHERE id = ANY($1)`,
|
||||
@@ -83,34 +91,49 @@ export class TicketsService {
|
||||
const iamMap = new Map(iamRows.map(r => [r.id, r]));
|
||||
|
||||
return {
|
||||
items: tickets.map((t) => {
|
||||
const iam = t.booking.passenger?.iamUserId ? iamMap.get(t.booking.passenger.iamUserId) : undefined;
|
||||
items: tickets.map((t: any) => {
|
||||
const iam = t.booking?.passenger?.iamUserId ? iamMap.get(t.booking.passenger.iamUserId) : undefined;
|
||||
const passengerInfo = iam
|
||||
? { fullName: iam.name?.en ?? iam.name?.am ?? null, email: iam.email, phone: iam.phone_number }
|
||||
: { fullName: 'Guest', email: t.booking.contactEmail, phone: null };
|
||||
: { fullName: 'Guest', email: t.booking?.contactEmail, phone: null };
|
||||
return {
|
||||
id: t.id,
|
||||
ticketNumber: t.barcodePayload,
|
||||
bookingRef: t.bookingRef,
|
||||
passengerName: t.passengerName,
|
||||
leg: t.leg,
|
||||
booking: {
|
||||
id: t.booking.id,
|
||||
bookingRef: t.booking.bookingRef,
|
||||
status: t.booking.status,
|
||||
bookingType: t.booking.bookingType,
|
||||
returnLegStatus: (t.booking as any).returnLegStatus ?? null,
|
||||
outboundBoardedAt: (t.booking as any).outboundBoardedAt ?? null,
|
||||
returnBoardedAt: (t.booking as any).returnBoardedAt ?? null,
|
||||
totalMinor: t.booking.totalMinor,
|
||||
currency: t.booking.currency,
|
||||
displayCurrency: t.booking.displayCurrency,
|
||||
displayTotalMinor: t.booking.displayTotalMinor,
|
||||
id: t.booking?.id,
|
||||
bookingRef: t.booking?.bookingRef,
|
||||
status: t.booking?.status,
|
||||
bookingType: t.booking?.bookingType,
|
||||
returnLegStatus: t.booking?.returnLegStatus ?? null,
|
||||
outboundBoardedAt: t.booking?.outboundBoardedAt ?? null,
|
||||
returnBoardedAt: t.booking?.returnBoardedAt ?? null,
|
||||
totalMinor: t.booking?.totalMinor,
|
||||
currency: t.booking?.currency,
|
||||
displayCurrency: t.booking?.displayCurrency,
|
||||
displayTotalMinor: t.booking?.displayTotalMinor,
|
||||
passenger: passengerInfo,
|
||||
contactEmail: t.booking.contactEmail,
|
||||
contactPhone: t.booking.contactPhone,
|
||||
returnSchedule: (t.booking as any).returnSchedule ?? null,
|
||||
contactEmail: t.booking?.contactEmail,
|
||||
contactPhone: t.booking?.contactPhone,
|
||||
returnSchedule: t.booking?.returnSchedule ?? null,
|
||||
seats: t.booking?.seats ?? [],
|
||||
},
|
||||
schedule: t.booking.schedule,
|
||||
seat: t.booking.seats[0]?.seat,
|
||||
schedule: t.booking?.schedule,
|
||||
seat: t.seat ? {
|
||||
id: t.seat.id,
|
||||
seatNumber: t.seat.seatNumber,
|
||||
coach: t.seat.coach ? {
|
||||
id: t.seat.coach.id,
|
||||
number: t.seat.coach.number,
|
||||
coachType: t.seat.coach.coachType ? {
|
||||
id: t.seat.coach.coachType.id,
|
||||
name: t.seat.coach.coachType.name,
|
||||
type: t.seat.coach.coachType.type,
|
||||
} : null,
|
||||
} : null,
|
||||
} : null,
|
||||
status: t.status,
|
||||
validatedAt: t.validatedAt,
|
||||
createdAt: t.issuedAt,
|
||||
@@ -136,7 +159,7 @@ export class TicketsService {
|
||||
if (!booking) throw new NotFoundException(`Booking ${bookingId} not found`);
|
||||
|
||||
// No payment intent record at all
|
||||
if (!booking.paymentIntent) {
|
||||
if (!(booking as any).paymentIntent) {
|
||||
throw new HttpException(
|
||||
{ status: 'error', message: 'Payment not completed', code: 400 },
|
||||
HttpStatus.BAD_REQUEST,
|
||||
@@ -144,21 +167,19 @@ export class TicketsService {
|
||||
}
|
||||
|
||||
// Payment intent exists but not yet succeeded
|
||||
if (booking.paymentIntent.status !== 'SUCCEEDED') {
|
||||
if ((booking as any).paymentIntent.status !== 'SUCCEEDED') {
|
||||
throw new HttpException(
|
||||
{
|
||||
status: 'error',
|
||||
message: 'Payment not completed',
|
||||
code: 400,
|
||||
detail: `Payment status: ${booking.paymentIntent.status}`,
|
||||
detail: `Payment status: ${(booking as any).paymentIntent.status}`,
|
||||
},
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
|
||||
// Booking not in CONFIRMED state — could be a webhook delivery failure.
|
||||
// If the intent already SUCCEEDED but the booking is still PENDING_PAYMENT,
|
||||
// self-heal here rather than rejecting a legitimately paid booking.
|
||||
if (booking.status !== 'CONFIRMED') {
|
||||
if (booking.status === 'PENDING_PAYMENT') {
|
||||
this.logger.warn(
|
||||
@@ -181,154 +202,282 @@ export class TicketsService {
|
||||
}
|
||||
}
|
||||
|
||||
// Build a compact multi-leg payload for the QR so gate scanners see all legs
|
||||
const legSummary = this.buildLegSummary(booking);
|
||||
const qrData = JSON.stringify({
|
||||
ref: booking.bookingRef,
|
||||
type: booking.bookingType,
|
||||
legs: legSummary,
|
||||
});
|
||||
const qrPayload = await QRCode.toDataURL(qrData);
|
||||
const barcodePayload = `${booking.bookingRef}${booking.id.substring(0, 8).toUpperCase()}`;
|
||||
// Delete existing tickets if any
|
||||
await this.prisma.ticket.deleteMany({ where: { bookingId } });
|
||||
|
||||
const ticket = await this.prisma.ticket.upsert({
|
||||
where: { bookingId },
|
||||
update: { qrPayload, barcodePayload },
|
||||
create: { bookingId, bookingRef: booking.bookingRef, qrPayload, barcodePayload },
|
||||
});
|
||||
// Generate one ticket per unique passenger (grouped by passengerName)
|
||||
const tickets = [];
|
||||
const seatIds = (booking as any).seats.map((bs: any) => bs.seatId);
|
||||
|
||||
// Group seats by passenger
|
||||
const passengerSeatsMap = new Map<string, any[]>();
|
||||
for (const bookingSeat of (booking as any).seats) {
|
||||
const key = bookingSeat.passengerName;
|
||||
if (!passengerSeatsMap.has(key)) {
|
||||
passengerSeatsMap.set(key, []);
|
||||
}
|
||||
passengerSeatsMap.get(key)!.push(bookingSeat);
|
||||
}
|
||||
|
||||
// Create one ticket per passenger
|
||||
for (const [passengerName, passengerSeats] of passengerSeatsMap.entries()) {
|
||||
// Use first seat for primary data
|
||||
const primarySeat = passengerSeats[0];
|
||||
|
||||
// Build passenger QR data with all legs included
|
||||
const qrData = JSON.stringify({
|
||||
ref: booking.bookingRef,
|
||||
type: booking.bookingType,
|
||||
passenger: passengerName,
|
||||
seats: passengerSeats.map(ps => ({
|
||||
seat: ps.seat.seatNumber,
|
||||
coach: ps.seat.coach.number,
|
||||
leg: ps.leg || 1,
|
||||
scheduleId: ps.scheduleId || booking.scheduleId,
|
||||
})),
|
||||
});
|
||||
const qrPayload = await QRCode.toDataURL(qrData);
|
||||
const barcodePayload = `${booking.bookingRef}${primarySeat.seatId.substring(0, 8).toUpperCase()}`;
|
||||
|
||||
const ticket = await this.prisma.ticket.create({
|
||||
data: {
|
||||
bookingId,
|
||||
bookingRef: booking.bookingRef,
|
||||
passengerName,
|
||||
seatId: primarySeat.seatId,
|
||||
leg: primarySeat.leg || 1,
|
||||
scheduleId: primarySeat.scheduleId || booking.scheduleId,
|
||||
qrPayload,
|
||||
barcodePayload,
|
||||
} as any,
|
||||
});
|
||||
tickets.push(ticket);
|
||||
}
|
||||
|
||||
// Block all seats across all legs
|
||||
const seatIds = booking.seats.map(bs => bs.seatId);
|
||||
for (const seatId of seatIds) {
|
||||
await this.prisma.seat.update({ where: { id: seatId }, data: { status: 'BOOKED' } });
|
||||
await this.prisma.seatBlock.create({
|
||||
data: { seatId, reason: `Booked in ticket ${ticket.id}`, blockedBy: 'SYSTEM', approvedBy: 'SYSTEM' },
|
||||
data: { seatId, reason: `Booked in tickets ${tickets.map(t => t.id).join(', ')}`, blockedBy: 'SYSTEM', approvedBy: 'SYSTEM' },
|
||||
}).catch(() => null);
|
||||
}
|
||||
|
||||
return { ...ticket, legs: legSummary };
|
||||
return { tickets, totalTickets: tickets.length };
|
||||
}
|
||||
|
||||
private buildLegSummary(booking: any) {
|
||||
const seatsByLeg = new Map<number, any[]>();
|
||||
for (const bs of booking.seats) {
|
||||
const leg = bs.leg ?? 1;
|
||||
if (!seatsByLeg.has(leg)) seatsByLeg.set(leg, []);
|
||||
seatsByLeg.get(leg)!.push(bs);
|
||||
}
|
||||
return Array.from(seatsByLeg.entries())
|
||||
.sort(([a], [b]) => a - b)
|
||||
.map(([leg, seats]) => ({
|
||||
leg,
|
||||
scheduleId: (seats[0] as any).scheduleId ?? booking.scheduleId,
|
||||
passengers: seats.map(bs => ({
|
||||
name: bs.passengerName,
|
||||
category: bs.passengerCategory,
|
||||
coach: bs.seat?.coach?.number,
|
||||
seat: bs.seat?.seatNumber,
|
||||
fareMinor: bs.fareMinor,
|
||||
})),
|
||||
}));
|
||||
}
|
||||
|
||||
async updateSeats(bookingId: string, newSeatIds: string[]) {
|
||||
async updateSeats(bookingId: string, seatIds: string[]) {
|
||||
const booking = await this.prisma.booking.findUnique({
|
||||
where: { id: bookingId },
|
||||
include: { seats: true, ticket: true },
|
||||
include: { tickets: true, seats: true } as any
|
||||
});
|
||||
if (!booking) throw new NotFoundException(`Booking ${bookingId} not found`);
|
||||
if (!booking.ticket) throw new BadRequestException('No ticket found for this booking');
|
||||
|
||||
// Remove old seat blocks
|
||||
const oldSeatIds = booking.seats.map(bs => bs.seatId);
|
||||
for (const seatId of oldSeatIds) {
|
||||
for (const ticket of (booking as any).tickets) {
|
||||
await this.prisma.seatBlock.deleteMany({
|
||||
where: {
|
||||
seatId,
|
||||
reason: { contains: booking.ticket.id }
|
||||
}
|
||||
where: { reason: { contains: ticket.id } }
|
||||
});
|
||||
}
|
||||
|
||||
// Remove old booking seats
|
||||
// Delete existing tickets
|
||||
await this.prisma.ticket.deleteMany({ where: { bookingId } });
|
||||
|
||||
// Update booking seats
|
||||
await this.prisma.bookingSeat.deleteMany({ where: { bookingId } });
|
||||
|
||||
// Create new seat blocks
|
||||
for (const seatId of newSeatIds) {
|
||||
await this.prisma.seatBlock.create({
|
||||
data: {
|
||||
seatId,
|
||||
reason: `Permanently booked in ticket ${booking.ticket.id}`,
|
||||
blockedBy: 'SYSTEM',
|
||||
approvedBy: 'SYSTEM',
|
||||
}
|
||||
}).catch(() => null);
|
||||
}
|
||||
|
||||
// Create new booking seats (placeholder with minimal data)
|
||||
for (let i = 0; i < newSeatIds.length; i++) {
|
||||
|
||||
// Create new seat assignments (simplified)
|
||||
for (let i = 0; i < seatIds.length; i++) {
|
||||
await this.prisma.bookingSeat.create({
|
||||
data: {
|
||||
bookingId,
|
||||
seatId: newSeatIds[i],
|
||||
seatId: seatIds[i],
|
||||
passengerName: `Passenger ${i + 1}`,
|
||||
}
|
||||
leg: 1
|
||||
} as any
|
||||
});
|
||||
}
|
||||
|
||||
return { success: true, updatedSeats: newSeatIds.length };
|
||||
// Generate new tickets
|
||||
return this.generate(bookingId);
|
||||
}
|
||||
|
||||
async getByMerchantOrderId(merchantOrderId: string) {
|
||||
const intent = await this.prisma.paymentIntent.findUnique({
|
||||
const paymentIntent = await this.prisma.paymentIntent.findUnique({
|
||||
where: { merchantOrderId },
|
||||
select: { bookingId: true },
|
||||
include: { booking: { include: { tickets: true } as any } } as any
|
||||
});
|
||||
if (!intent) throw new NotFoundException(`No payment intent found for order ${merchantOrderId}`);
|
||||
if (!paymentIntent) throw new NotFoundException('Payment not found');
|
||||
|
||||
const booking = (paymentIntent as any).booking;
|
||||
if (!booking) throw new NotFoundException('Booking not found');
|
||||
|
||||
return this.getByRef(booking.bookingRef);
|
||||
}
|
||||
|
||||
async getByRef(ref: string) {
|
||||
const booking = await this.prisma.booking.findUnique({
|
||||
where: { id: intent.bookingId },
|
||||
include: { schedule: { include: { originStation: true, destinationStation: true, train: true } }, seats: { include: { seat: { include: { coach: true } } } }, ticket: true },
|
||||
where: { bookingRef: ref },
|
||||
include: {
|
||||
tickets: true,
|
||||
schedule: { include: { originStation: true, destinationStation: true } },
|
||||
returnSchedule: { include: { originStation: true, destinationStation: true } },
|
||||
seats: { include: { seat: { include: { coach: true } } } }
|
||||
} as any
|
||||
});
|
||||
if (!booking?.ticket) throw new NotFoundException('Ticket not found');
|
||||
const seat = booking.seats[0];
|
||||
if (!booking) throw new NotFoundException('Booking not found');
|
||||
|
||||
return {
|
||||
id: booking.ticket.id, bookingId: booking.id, bookingRef: booking.bookingRef, status: booking.status,
|
||||
fromStationName: booking.schedule.originStation.name, toStationName: booking.schedule.destinationStation.name,
|
||||
departureAt: booking.schedule.departureAt, trainName: booking.schedule.train.name,
|
||||
coachLabel: seat?.seat.coach.number, seatLabel: seat?.seat.seatNumber, passengerName: seat?.passengerName,
|
||||
priceMinor: booking.totalMinor, currency: booking.currency, qrPayload: booking.ticket.qrPayload,
|
||||
barcodePayload: booking.ticket.barcodePayload,
|
||||
booking: {
|
||||
id: booking.id,
|
||||
bookingRef: booking.bookingRef,
|
||||
status: booking.status,
|
||||
bookingType: booking.bookingType,
|
||||
totalMinor: booking.totalMinor,
|
||||
currency: booking.currency
|
||||
},
|
||||
tickets: (booking as any).tickets,
|
||||
schedule: (booking as any).schedule,
|
||||
returnSchedule: (booking as any).returnSchedule,
|
||||
seats: (booking as any).seats
|
||||
};
|
||||
}
|
||||
|
||||
async getByRef(bookingRef: string) {
|
||||
const booking = await this.prisma.booking.findUnique({
|
||||
where: { bookingRef },
|
||||
include: {
|
||||
schedule: { include: { originStation: true, destinationStation: true, train: true } },
|
||||
seats: { include: { seat: { include: { coach: true } } } },
|
||||
ticket: true
|
||||
},
|
||||
});
|
||||
if (!booking?.ticket) throw new NotFoundException('Ticket not found');
|
||||
const seat = booking.seats[0];
|
||||
return {
|
||||
id: booking.ticket.id,
|
||||
bookingId: booking.id,
|
||||
bookingRef: booking.bookingRef,
|
||||
status: booking.status,
|
||||
fromStationName: booking.schedule.originStation.name,
|
||||
toStationName: booking.schedule.destinationStation.name,
|
||||
departureAt: booking.schedule.departureAt,
|
||||
trainName: booking.schedule.train.name,
|
||||
coachLabel: seat?.seat.coach.number,
|
||||
seatLabel: seat?.seat.seatNumber,
|
||||
passengerName: seat?.passengerName,
|
||||
priceMinor: booking.totalMinor,
|
||||
currency: booking.currency,
|
||||
qrPayload: booking.ticket.qrPayload,
|
||||
barcodePayload: booking.ticket.barcodePayload
|
||||
};
|
||||
async scanAndBoard(qrCodeOrRef: string, validatorId: string, gateId?: string) {
|
||||
try {
|
||||
// Extract booking reference from QR code if it's JSON
|
||||
let bookingRef = qrCodeOrRef;
|
||||
try {
|
||||
const qrData = JSON.parse(qrCodeOrRef);
|
||||
if (qrData.ref) {
|
||||
bookingRef = qrData.ref;
|
||||
}
|
||||
} catch {
|
||||
// Not JSON, treat as booking reference
|
||||
}
|
||||
|
||||
// Get booking and ticket info
|
||||
const booking = await this.prisma.booking.findUnique({
|
||||
where: { bookingRef },
|
||||
include: {
|
||||
schedule: { include: { originStation: true, destinationStation: true, train: true } },
|
||||
returnSchedule: { include: { originStation: true, destinationStation: true } },
|
||||
tickets: true,
|
||||
seats: { include: { seat: { include: { coach: true } } } },
|
||||
},
|
||||
});
|
||||
|
||||
if (!booking) {
|
||||
throw new NotFoundException('Ticket not found');
|
||||
}
|
||||
|
||||
if (booking.status !== 'CONFIRMED') {
|
||||
throw new BadRequestException('Ticket is not confirmed');
|
||||
}
|
||||
|
||||
const ticket = (booking as any).tickets[0];
|
||||
if (!ticket) {
|
||||
throw new NotFoundException('No ticket found for this booking');
|
||||
}
|
||||
|
||||
// Check if ticket date matches today
|
||||
const today = new Date();
|
||||
const todayDateStr = today.toISOString().split('T')[0]; // YYYY-MM-DD format
|
||||
|
||||
if ((booking as any).schedule?.departureAt) {
|
||||
const departureDate = new Date((booking as any).schedule.departureAt);
|
||||
const departureDateStr = departureDate.toISOString().split('T')[0];
|
||||
|
||||
// Check if ticket is for today
|
||||
if (departureDateStr !== todayDateStr) {
|
||||
if (departureDateStr < todayDateStr) {
|
||||
throw new BadRequestException('Ticket has expired - departure date has passed');
|
||||
} else {
|
||||
throw new BadRequestException('Ticket is for a future date - cannot board early');
|
||||
}
|
||||
}
|
||||
|
||||
// Additional check: ticket expires 4 hours after departure time
|
||||
const departureTime = new Date((booking as any).schedule.departureAt);
|
||||
const expiryTime = new Date(departureTime.getTime() + 4 * 60 * 60 * 1000); // 4 hours after departure
|
||||
if (today > expiryTime) {
|
||||
throw new BadRequestException('Ticket has expired - boarding window closed');
|
||||
}
|
||||
}
|
||||
|
||||
// Use existing validation logic to handle round trips properly
|
||||
const result = await this.validate(bookingRef, validatorId, gateId);
|
||||
|
||||
// Get seat information
|
||||
const seatInfo = (booking as any).seats[0];
|
||||
const seatNumber = seatInfo?.seat?.seatNumber || 'N/A';
|
||||
const coachNumber = seatInfo?.seat?.coach?.number || 'N/A';
|
||||
|
||||
// Send notifications after successful boarding
|
||||
await this.sendBoardingNotifications(booking, ticket, result.leg || 'OUTBOUND');
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: `Passenger boarded successfully (${result.leg || 'OUTBOUND'} leg)`,
|
||||
boarding: {
|
||||
ticketId: ticket.id,
|
||||
bookingRef: booking.bookingRef,
|
||||
passengerName: seatInfo?.passengerName || ticket.passengerName || 'N/A',
|
||||
route: `${(booking as any).schedule?.originStation?.name || 'N/A'} → ${(booking as any).schedule?.destinationStation?.name || 'N/A'}`,
|
||||
seat: seatNumber,
|
||||
coach: coachNumber,
|
||||
trainName: (booking as any).schedule?.train?.name || (booking as any).schedule?.train?.number || 'N/A',
|
||||
departureTime: (booking as any).schedule?.departureAt,
|
||||
boardedAt: result.validatedAt,
|
||||
leg: result.leg || 'OUTBOUND',
|
||||
bookingType: booking.bookingType,
|
||||
isRoundTrip: booking.bookingType === 'ROUND_TRIP' || booking.bookingType === 'ROUND_TRIP_TRANSIT',
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
// Return structured error for the UI
|
||||
const errorMessage = error instanceof Error ? error.message : 'Boarding failed';
|
||||
const errorCode = error instanceof BadRequestException ? 'VALIDATION_ERROR'
|
||||
: error instanceof NotFoundException ? 'NOT_FOUND'
|
||||
: 'SYSTEM_ERROR';
|
||||
|
||||
return {
|
||||
success: false,
|
||||
error: errorMessage,
|
||||
errorCode,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private async sendBoardingNotifications(booking: any, ticket: any, leg: string) {
|
||||
try {
|
||||
const passengerName = booking.seats?.[0]?.passengerName || ticket.passengerName || 'Passenger';
|
||||
const contactEmail = booking.contactEmail;
|
||||
const contactPhone = booking.contactPhone;
|
||||
|
||||
if (!contactEmail && !contactPhone) {
|
||||
this.logger.warn(`No contact details found for booking ${booking.bookingRef}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const routeInfo = `${booking.schedule?.originStation?.name} → ${booking.schedule?.destinationStation?.name}`;
|
||||
const trainName = booking.schedule?.train?.name || booking.schedule?.train?.number;
|
||||
const departureTime = booking.schedule?.departureAt ? new Date(booking.schedule.departureAt).toLocaleString() : 'N/A';
|
||||
const legText = leg === 'RETURN' ? 'Return' : 'Outbound';
|
||||
|
||||
// Use the existing sendBoardingPassNotification method
|
||||
await this.notifications.sendBoardingPassNotification({
|
||||
passengerId: booking.passengerId || null,
|
||||
contactEmail,
|
||||
contactPhone,
|
||||
bookingRef: booking.bookingRef,
|
||||
leg,
|
||||
booking,
|
||||
ticket,
|
||||
});
|
||||
|
||||
} catch (error: any) {
|
||||
this.logger.error('Error sending boarding notifications:', error);
|
||||
}
|
||||
}
|
||||
|
||||
async validate(ticketIdOrRef: string, validatorId: string, gateId?: string, leg?: string) {
|
||||
@@ -343,11 +492,11 @@ export class TicketsService {
|
||||
const resolvedValidatorId = validatorId || 'BACKOFFICE';
|
||||
const booking = await this.prisma.booking.findUnique({ where: { bookingRef } });
|
||||
if (!booking) throw new NotFoundException('Booking not found');
|
||||
const ticket = await this.prisma.ticket.findUnique({ where: { bookingId: booking.id } });
|
||||
const ticket = await this.prisma.ticket.findFirst({ where: { bookingId: booking.id } });
|
||||
if (!ticket) throw new NotFoundException('Ticket not found');
|
||||
|
||||
const type = booking.bookingType;
|
||||
const now = new Date();
|
||||
const now = new Date();
|
||||
|
||||
// ── ONE_WAY / TRANSIT (single scan) ───────────────────────────────────
|
||||
if (type === 'ONE_WAY') {
|
||||
@@ -389,92 +538,34 @@ export class TicketsService {
|
||||
if (resolvedLeg === 'OUTBOUND') {
|
||||
if ((booking as any).outboundBoardedAt) {
|
||||
await this.prisma.gateValidationLog.create({ data: { ticketId: ticket.id, validatorId: resolvedValidatorId, gateId, leg: resolvedLeg, status: 'REJECTED', reason: 'OUTBOUND_ALREADY_USED' } as any });
|
||||
throw new BadRequestException('Outbound leg already used');
|
||||
throw new BadRequestException('Outbound leg already validated');
|
||||
}
|
||||
bookingData.outboundBoardedAt = now;
|
||||
if (!ticket.validatedAt) await this.prisma.ticket.update({ where: { id: ticket.id }, data: { validatedAt: now, validatorId: resolvedValidatorId } });
|
||||
} else if (resolvedLeg === 'RETURN') {
|
||||
if ((booking as any).returnBoardedAt) {
|
||||
await this.prisma.gateValidationLog.create({ data: { ticketId: ticket.id, validatorId: resolvedValidatorId, gateId, leg: resolvedLeg, status: 'REJECTED', reason: 'RETURN_ALREADY_USED' } as any });
|
||||
throw new BadRequestException('Return leg already used');
|
||||
throw new BadRequestException('Return leg already validated');
|
||||
}
|
||||
bookingData.returnBoardedAt = now;
|
||||
} else {
|
||||
throw new BadRequestException('For ROUND_TRIP bookings supply leg=OUTBOUND or leg=RETURN');
|
||||
}
|
||||
const outboundUsed = resolvedLeg === 'OUTBOUND' ? true : !!(booking as any).outboundBoardedAt;
|
||||
const returnUsed = resolvedLeg === 'RETURN' ? true : !!(booking as any).returnBoardedAt;
|
||||
if (outboundUsed && returnUsed) bookingData.returnLegStatus = 'BOTH_USED';
|
||||
else if (outboundUsed && !returnUsed) bookingData.returnLegStatus = 'OUTBOUND_ONLY';
|
||||
else if (!outboundUsed && returnUsed) bookingData.returnLegStatus = 'INBOUND_ONLY';
|
||||
|
||||
await this.prisma.booking.update({ where: { id: booking.id }, data: bookingData });
|
||||
if (!ticket.validatedAt) {
|
||||
await this.prisma.ticket.update({ where: { id: ticket.id }, data: { validatedAt: now, validatorId: resolvedValidatorId } });
|
||||
}
|
||||
await this.prisma.gateValidationLog.create({ data: { ticketId: ticket.id, validatorId: resolvedValidatorId, gateId, leg: resolvedLeg, status: 'APPROVED' } as any });
|
||||
this.fireBoardingPassNotification(booking, ticket, resolvedLeg);
|
||||
return { validated: true, ticketId: ticket.id, leg: resolvedLeg, validatedAt: now };
|
||||
}
|
||||
|
||||
// ── ROUND_TRIP_TRANSIT — leg=OUTBOUND_LEG1|OUTBOUND_LEG2|RETURN_LEG1|RETURN_LEG2
|
||||
if (type === 'ROUND_TRIP_TRANSIT') {
|
||||
const validLegs = ['OUTBOUND_LEG1', 'OUTBOUND_LEG2', 'RETURN_LEG1', 'RETURN_LEG2'];
|
||||
const resolvedLeg = (leg ?? '').toUpperCase();
|
||||
if (!validLegs.includes(resolvedLeg)) {
|
||||
throw new BadRequestException(`For ROUND_TRIP_TRANSIT supply leg=${validLegs.join('|')}`);
|
||||
}
|
||||
const logs = await this.prisma.gateValidationLog.findMany({ where: { ticketId: ticket.id, status: 'APPROVED' } }) as any[];
|
||||
if (logs.some(l => l.leg === resolvedLeg)) {
|
||||
await this.prisma.gateValidationLog.create({ data: { ticketId: ticket.id, validatorId: resolvedValidatorId, gateId, leg: resolvedLeg, status: 'REJECTED', reason: `${resolvedLeg}_ALREADY_USED` } as any });
|
||||
throw new BadRequestException(`${resolvedLeg} already validated`);
|
||||
}
|
||||
const bookingData: Record<string, any> = {};
|
||||
if (resolvedLeg.startsWith('OUTBOUND') && !logs.some(l => l.leg?.startsWith('OUTBOUND') && l.status === 'APPROVED')) {
|
||||
bookingData.outboundBoardedAt = now;
|
||||
}
|
||||
if (resolvedLeg.startsWith('RETURN') && !logs.some(l => l.leg?.startsWith('RETURN') && l.status === 'APPROVED')) {
|
||||
bookingData.returnBoardedAt = now;
|
||||
}
|
||||
const allOutboundDone = ['OUTBOUND_LEG1','OUTBOUND_LEG2'].every(l => l === resolvedLeg || logs.some(x => x.leg === l && x.status === 'APPROVED'));
|
||||
const allReturnDone = ['RETURN_LEG1','RETURN_LEG2'].every(l => l === resolvedLeg || logs.some(x => x.leg === l && x.status === 'APPROVED'));
|
||||
if (allOutboundDone && allReturnDone) bookingData.returnLegStatus = 'BOTH_USED';
|
||||
else if (allOutboundDone && !allReturnDone) bookingData.returnLegStatus = 'OUTBOUND_ONLY';
|
||||
else if (!allOutboundDone && allReturnDone) bookingData.returnLegStatus = 'INBOUND_ONLY';
|
||||
if (Object.keys(bookingData).length) await this.prisma.booking.update({ where: { id: booking.id }, data: bookingData });
|
||||
if (!ticket.validatedAt) await this.prisma.ticket.update({ where: { id: ticket.id }, data: { validatedAt: now, validatorId: resolvedValidatorId } });
|
||||
await this.prisma.gateValidationLog.create({ data: { ticketId: ticket.id, validatorId: resolvedValidatorId, gateId, leg: resolvedLeg, status: 'APPROVED' } as any });
|
||||
this.fireBoardingPassNotification(booking, ticket, resolvedLeg);
|
||||
return { validated: true, ticketId: ticket.id, leg: resolvedLeg, validatedAt: now };
|
||||
}
|
||||
|
||||
// Fallback for unknown booking types — single scan
|
||||
if (ticket.validatedAt) {
|
||||
return { validated: true, ticketId: ticket.id, validatedAt: ticket.validatedAt, alreadyValidated: true };
|
||||
}
|
||||
await this.prisma.ticket.update({ where: { id: ticket.id }, data: { validatedAt: now, validatorId: resolvedValidatorId } });
|
||||
await this.prisma.gateValidationLog.create({ data: { ticketId: ticket.id, validatorId: resolvedValidatorId, gateId, status: 'APPROVED' } });
|
||||
this.fireBoardingPassNotification(booking, ticket, null);
|
||||
return { validated: true, ticketId: ticket.id, validatedAt: now };
|
||||
throw new BadRequestException(`Unsupported booking type: ${type}`);
|
||||
}
|
||||
|
||||
/** Fire-and-forget — enriches booking with schedule+seats then sends email+SMS boarding pass. */
|
||||
private fireBoardingPassNotification(booking: any, ticket: any, leg: string | null): void {
|
||||
this.prisma.booking.findUnique({
|
||||
where: { id: booking.id },
|
||||
include: {
|
||||
schedule: { include: { originStation: true, destinationStation: true, train: true } },
|
||||
seats: { include: { seat: { include: { coach: { include: { coachType: true } } } } } },
|
||||
passenger: { select: { id: true, iamUserId: true } },
|
||||
},
|
||||
}).then((enriched) => {
|
||||
if (!enriched) return;
|
||||
this.notifications.sendBoardingPassNotification({
|
||||
passengerId: enriched.passenger?.iamUserId ?? enriched.passenger?.id ?? null,
|
||||
contactEmail: (enriched as any).contactEmail ?? null,
|
||||
contactPhone: (enriched as any).contactPhone ?? null,
|
||||
bookingRef: enriched.bookingRef,
|
||||
leg,
|
||||
booking: enriched,
|
||||
ticket,
|
||||
}).catch(() => null);
|
||||
}).catch(() => null);
|
||||
private async fireBoardingPassNotification(booking: any, ticket: any, leg: string | null) {
|
||||
// TODO: Implement notification logic
|
||||
console.log(`Boarding pass notification for booking ${booking.bookingRef}, leg: ${leg}`);
|
||||
}
|
||||
|
||||
async getValidationLogs(ticketId: string) {
|
||||
@@ -488,111 +579,57 @@ export class TicketsService {
|
||||
const bookings = await this.prisma.booking.findMany({
|
||||
where: { scheduleId: tripId, status: 'CONFIRMED' },
|
||||
include: {
|
||||
ticket: true,
|
||||
tickets: true,
|
||||
seats: { include: { seat: { include: { coach: true } } } },
|
||||
passenger: { select: { id: true, iamUserId: true } },
|
||||
},
|
||||
} as any,
|
||||
});
|
||||
|
||||
return bookings.map((b) => ({
|
||||
bookingRef: b.bookingRef,
|
||||
ticketId: b.ticket?.id,
|
||||
passengerName: b.seats[0]?.passengerName,
|
||||
seatLabel: b.seats[0]?.seat.seatNumber,
|
||||
coachLabel: b.seats[0]?.seat.coach.number,
|
||||
qrPayload: b.ticket?.qrPayload,
|
||||
ticketId: (b as any).tickets?.[0]?.id,
|
||||
passengerName: (b as any).seats[0]?.passengerName,
|
||||
seatLabel: (b as any).seats[0]?.seat.seatNumber,
|
||||
coachLabel: (b as any).seats[0]?.seat.coach.number,
|
||||
qrPayload: (b as any).tickets?.[0]?.qrPayload,
|
||||
status: b.status,
|
||||
bookingType: b.bookingType,
|
||||
returnLegStatus: (b as any).returnLegStatus ?? null,
|
||||
validatedAt: b.ticket?.validatedAt,
|
||||
validatedAt: (b as any).tickets?.[0]?.validatedAt,
|
||||
}));
|
||||
}
|
||||
|
||||
async validateOfflineBatch(validations: OfflineValidation[]) {
|
||||
const results = { success: 0, failed: 0, duplicate: 0, errors: [] as string[] };
|
||||
const processedRefs = new Set<string>();
|
||||
|
||||
for (const v of validations) {
|
||||
const offlineLeg = v.leg;
|
||||
const dedupKey = offlineLeg ? `${v.bookingRef}:${offlineLeg}` : v.bookingRef;
|
||||
if (processedRefs.has(dedupKey)) {
|
||||
results.duplicate++;
|
||||
continue;
|
||||
}
|
||||
processedRefs.add(dedupKey);
|
||||
|
||||
const results = [];
|
||||
|
||||
for (const validation of validations) {
|
||||
try {
|
||||
const booking = await this.prisma.booking.findUnique({ where: { bookingRef: v.bookingRef } });
|
||||
if (!booking) {
|
||||
results.failed++;
|
||||
results.errors.push(`Booking ${v.bookingRef} not found`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const ticket = await this.prisma.ticket.findUnique({ where: { bookingId: booking.id } });
|
||||
if (!ticket) {
|
||||
results.failed++;
|
||||
results.errors.push(`Ticket for ${v.bookingRef} not found`);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ticket.validatedAt && booking.bookingType !== 'ROUND_TRIP' &&
|
||||
booking.bookingType !== 'TRANSIT' && booking.bookingType !== 'ROUND_TRIP_TRANSIT') {
|
||||
results.duplicate++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// For multi-leg bookings, check per-leg duplication
|
||||
const isMultiLeg = booking.bookingType === 'ROUND_TRIP' ||
|
||||
booking.bookingType === 'TRANSIT' ||
|
||||
booking.bookingType === 'ROUND_TRIP_TRANSIT';
|
||||
if (isMultiLeg && offlineLeg) {
|
||||
const existingLogs = await this.prisma.gateValidationLog.findMany({ where: { ticketId: ticket.id, status: 'APPROVED' } }) as any[];
|
||||
if (existingLogs.some(l => l.leg === offlineLeg)) {
|
||||
results.duplicate++;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
await this.prisma.ticket.update({
|
||||
where: { id: ticket.id },
|
||||
data: { validatedAt: new Date(v.validatedAt), validatorId: v.validatorId },
|
||||
const result = await this.validate(
|
||||
validation.bookingRef,
|
||||
validation.validatorId,
|
||||
validation.gateId,
|
||||
validation.leg
|
||||
);
|
||||
results.push({
|
||||
bookingRef: validation.bookingRef,
|
||||
success: true,
|
||||
result
|
||||
});
|
||||
|
||||
await this.prisma.gateValidationLog.create({
|
||||
data: {
|
||||
ticketId: ticket.id,
|
||||
validatorId: v.validatorId,
|
||||
gateId: v.gateId,
|
||||
leg: v.leg ?? null,
|
||||
status: 'APPROVED',
|
||||
validatedAt: new Date(v.validatedAt),
|
||||
} as any,
|
||||
} catch (error) {
|
||||
results.push({
|
||||
bookingRef: validation.bookingRef,
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Validation failed'
|
||||
});
|
||||
|
||||
// update boarding timestamps for multi-leg bookings
|
||||
const isMultiLegBooking = booking.bookingType === 'ROUND_TRIP' ||
|
||||
booking.bookingType === 'TRANSIT' ||
|
||||
booking.bookingType === 'ROUND_TRIP_TRANSIT';
|
||||
if (isMultiLegBooking && offlineLeg) {
|
||||
const bookingData: Record<string, any> = {};
|
||||
const isOutbound = (offlineLeg as string) === 'OUTBOUND' || (offlineLeg as string) === 'OUTBOUND_LEG1' || (offlineLeg as string) === 'LEG1';
|
||||
const isReturn = (offlineLeg as string) === 'RETURN' || (offlineLeg as string) === 'RETURN_LEG1' || (offlineLeg as string) === 'RETURN_LEG2';
|
||||
if (isOutbound && !(booking as any).outboundBoardedAt) bookingData.outboundBoardedAt = new Date(v.validatedAt);
|
||||
if (isReturn && !(booking as any).returnBoardedAt) bookingData.returnBoardedAt = new Date(v.validatedAt);
|
||||
if (Object.keys(bookingData).length) {
|
||||
await this.prisma.booking.update({ where: { id: booking.id }, data: bookingData });
|
||||
}
|
||||
}
|
||||
|
||||
results.success++;
|
||||
} catch (err) {
|
||||
results.failed++;
|
||||
results.errors.push(`Error processing ${v.bookingRef}: ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
|
||||
return {
|
||||
processed: results.length,
|
||||
successful: results.filter(r => r.success).length,
|
||||
failed: results.filter(r => !r.success).length,
|
||||
results
|
||||
};
|
||||
}
|
||||
|
||||
async delete(id: string) {
|
||||
@@ -618,4 +655,4 @@ export class TicketsService {
|
||||
if (!ticket) throw new NotFoundException('Ticket not found');
|
||||
return this.prisma.ticket.update({ where: { id }, data: { status: 'ACTIVE' } });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,14 @@ The Passenger Backoffice Application is a comprehensive management system for th
|
||||
- **Live Tracking**: Monitor trip status and real-time updates
|
||||
- **Security Monitoring**: Fraud detection and audit logging
|
||||
- **Comprehensive Analytics**: Revenue, occupancy, and performance reports
|
||||
- **🆕 Excess Baggage Management**: Handle boarding baggage charges with agent tools
|
||||
- **🆕 Travel Packages**: Manage pilgrimage and group travel packages with tiered pricing
|
||||
- **🆕 System Health Monitoring**: Real-time API health checks and system status
|
||||
- **🆕 Advanced Fare Configuration**: Dynamic pricing with segment-based rules
|
||||
- **🆕 Boarding Management**: Gate operations and passenger processing
|
||||
- **🆕 Payment Methods Configuration**: Multi-provider payment setup
|
||||
- **🆕 Package Inquiries**: Lead management for travel package bookings
|
||||
- **🆕 Centralized Configuration**: Feature flags and operational controls
|
||||
|
||||
### Supported Roles
|
||||
- **Agent**: Counter booking and basic operations
|
||||
@@ -83,7 +91,16 @@ The application is organized into 8 main sections:
|
||||
└── System
|
||||
├── Agent Operations
|
||||
├── User Management
|
||||
├── System Config
|
||||
└── Settings
|
||||
└── Enhanced Features
|
||||
├── Excess Baggage
|
||||
├── Travel Packages
|
||||
├── Package Inquiries
|
||||
├── Health Monitoring
|
||||
├── Boarding Management
|
||||
├── Advanced Fare Config
|
||||
└── Payment Methods
|
||||
```
|
||||
|
||||
### Theme & Personalization
|
||||
@@ -2843,14 +2860,21 @@ Action: Block user
|
||||
|
||||
## Change Log
|
||||
|
||||
### Version 1.0.0 (June 15, 2026)
|
||||
- Initial release
|
||||
- All core modules implemented
|
||||
- Multi-currency support added
|
||||
- Verifayda 2.0 integration complete
|
||||
- Premium and insurance fees added to fares
|
||||
- Age-based pricing fully functional
|
||||
- Segment fare rules implemented
|
||||
### Version 1.0.0 (January 15, 2026)
|
||||
- **Complete Platform Release** - Full-featured passenger management system
|
||||
- **Excess Baggage Management** - Complete boarding baggage handling with agent tools and passenger self-pay options
|
||||
- **Travel Packages** - Pilgrimage and group travel packages with tiered pricing, capacity management, and inquiry handling
|
||||
- **System Health Monitoring** - Real-time API health checks with liveness, readiness, and performance metrics
|
||||
- **System Configuration** - Centralized config management with feature flags, rate limiting, and operational controls
|
||||
- **Package Inquiries** - Dedicated management for package booking inquiries with status tracking
|
||||
- **Boarding Management** - Gate operations, passenger processing, and boarding workflow tools
|
||||
- **Advanced Fare Configuration** - Dynamic fare management with complex pricing rules and segment-based pricing
|
||||
- **Payment Methods Configuration** - Multi-provider payment setup and management interface
|
||||
- **Enhanced Settings** - Improved settings interface with tabbed sections and live configuration updates
|
||||
- **Multi-currency support** - ETB, DJF, USD with real-time exchange rates
|
||||
- **Verifayda 2.0 integration** - Ethiopian national ID verification
|
||||
- **Age-based pricing** - ADULT/CHILD categories with free first child policy
|
||||
- **Segment fare rules** - Complex pricing with nationality-specific rates
|
||||
|
||||
---
|
||||
|
||||
@@ -2892,6 +2916,902 @@ Action: Block user
|
||||
|
||||
**For more information or feedback, please contact the development team or visit the support portal.**
|
||||
|
||||
**Last Updated**: January 15, 2026
|
||||
**Document Version**: 1.0.0
|
||||
**Maintained By**: EDR Development Team
|
||||
---
|
||||
|
||||
## Enhanced Features
|
||||
|
||||
### Excess Baggage
|
||||
|
||||
**Purpose**: Manage excess baggage charges at boarding with agent tools and passenger self-pay
|
||||
**Access Level**: Agent, Supervisor, Admin
|
||||
**Icon**: Package
|
||||
|
||||
#### Features Overview
|
||||
|
||||
```
|
||||
┌──────────────────────────────┐
|
||||
│ EXCESS BAGGAGE MANAGEMENT │
|
||||
├──────────────────────────────┤
|
||||
│ ✓ View Excess Charges │
|
||||
│ ✓ Search by Booking Ref │
|
||||
│ ✓ Track Payment Status │
|
||||
│ ✓ Waive Charges │
|
||||
│ ✓ Resend Payment Links │
|
||||
│ ✓ Agent Cash Collection │
|
||||
└──────────────────────────────┘
|
||||
```
|
||||
|
||||
#### Excess Baggage Process
|
||||
|
||||
1. **At Boarding**: Agent weighs passenger baggage
|
||||
2. **If Excess**: Agent creates charge in system
|
||||
3. **Payment Options**:
|
||||
- Passenger self-pay via mobile link
|
||||
- Agent collects cash on-the-spot
|
||||
4. **Completion**: Passenger boards after payment
|
||||
|
||||
#### Charge Statuses
|
||||
|
||||
- **PENDING**: Awaiting passenger payment (5-minute link expiry)
|
||||
- **PAID**: Successfully paid via mobile payment
|
||||
- **CASH_COLLECTED**: Agent collected cash payment
|
||||
- **EXPIRED**: Payment link expired
|
||||
- **WAIVED**: Supervisor waived the charge
|
||||
|
||||
#### CRUD Operations
|
||||
|
||||
##### READ (List Charges)
|
||||
|
||||
1. **Access Excess Baggage Page**:
|
||||
- Click **Excess Baggage** in Enhanced Features section
|
||||
- Shows all baggage charges
|
||||
|
||||
2. **Search & Filter**:
|
||||
- **Search Box**: Filter by booking reference
|
||||
- **Status Filter**: PENDING, PAID, CASH_COLLECTED, EXPIRED, WAIVED
|
||||
- **Date Range**: Filter by creation date
|
||||
|
||||
3. **Charge Information**:
|
||||
- Booking Reference
|
||||
- Excess Weight (kg)
|
||||
- Fee per kg
|
||||
- Total Amount (ETB)
|
||||
- Payment Status
|
||||
- Contact Information
|
||||
- Expiry Time
|
||||
|
||||
##### MANAGE CHARGES
|
||||
|
||||
**Resend Payment Link**:
|
||||
1. **For PENDING charges**: Click "Resend Link"
|
||||
2. **New SMS/Email**: Sent to passenger
|
||||
3. **Fresh 5-minute**: New expiry timer
|
||||
|
||||
**Waive Charge**:
|
||||
1. **Click "Waive"** on pending/expired charge
|
||||
2. **Enter Reason**: Medical exemption, scale error, etc.
|
||||
3. **Confirm**: Charge marked as waived
|
||||
4. **Audit**: Action logged for compliance
|
||||
|
||||
**Delete Charge**:
|
||||
1. **Only for EXPIRED/WAIVED**: Click "Delete"
|
||||
2. **Confirm**: Permanent removal from system
|
||||
3. **Note**: Cannot delete active or paid charges
|
||||
|
||||
#### Agent Workflow
|
||||
|
||||
1. **Weigh Baggage**: Use station scales
|
||||
2. **Check Allowance**: Compare to passenger's seat class allowance
|
||||
3. **Create Charge**: If excess weight found
|
||||
4. **Offer Payment Options**:
|
||||
- Mobile payment link (passenger's phone)
|
||||
- Cash payment (agent collection)
|
||||
5. **Process Boarding**: After payment completed
|
||||
|
||||
---
|
||||
|
||||
### Travel Packages
|
||||
|
||||
**Purpose**: Manage pilgrimage and group travel packages with tiered pricing
|
||||
**Access Level**: Supervisor, Admin
|
||||
**Icon**: Package
|
||||
|
||||
#### Features Overview
|
||||
|
||||
```
|
||||
┌──────────────────────────────┐
|
||||
│ TRAVEL PACKAGES MANAGEMENT │
|
||||
├──────────────────────────────┤
|
||||
│ ✓ Create Packages │
|
||||
│ ✓ Multi-tier Pricing │
|
||||
│ ✓ Capacity Management │
|
||||
│ ✓ Schedule Integration │
|
||||
│ ✓ Bus Transfer Coordination │
|
||||
│ ✓ Package Status Control │
|
||||
└──────────────────────────────┘
|
||||
```
|
||||
|
||||
#### Package Information
|
||||
|
||||
- **Code**: Unique package identifier (e.g., "KULUBBI-2025")
|
||||
- **Name**: Package display name
|
||||
- **Origin/Destination**: Station pairs
|
||||
- **Schedules**: Outbound and return train schedules
|
||||
- **Capacity**: Total seats available
|
||||
- **Coach Configuration**: Train composition
|
||||
- **Included Services**: List of package inclusions
|
||||
- **Bus Transfer**: Optional bus coordination
|
||||
- **Validity Period**: Package booking window
|
||||
|
||||
#### Package Statuses
|
||||
|
||||
- **DRAFT**: Created but not yet active
|
||||
- **ACTIVE**: Available for booking
|
||||
- **SOLD_OUT**: All seats booked
|
||||
- **EXPIRED**: Past validity period
|
||||
- **CANCELLED**: No longer offered
|
||||
|
||||
#### CRUD Operations
|
||||
|
||||
##### CREATE
|
||||
|
||||
1. **Click "New Package"** button
|
||||
2. **Fill Package Form**:
|
||||
- **Code** (required): Unique identifier
|
||||
- **Name** (required): Display name
|
||||
- **Description**: Optional details
|
||||
- **Origin/Destination Stations**: Select from dropdown
|
||||
- **Outbound/Return Schedules**: Link to existing schedules
|
||||
- **Boarding/Departure/Arrival Times**: Package timeline
|
||||
- **Total Capacity**: Available seats
|
||||
- **Coach Configuration**: Train setup description
|
||||
- **Included Services**: One service per line
|
||||
- **Bus Transfer**: Enable and specify route
|
||||
- **Valid From/Until**: Booking window
|
||||
3. **Save**: Click "Create Package"
|
||||
4. **Next Step**: Add price tiers
|
||||
|
||||
##### READ (List Packages)
|
||||
|
||||
1. **View Packages**:
|
||||
- Table shows all packages
|
||||
- Search by name or code
|
||||
- Filter by status
|
||||
- Filter by validity dates
|
||||
|
||||
2. **Package Details**:
|
||||
- Click "View" to see full information
|
||||
- Shows all configuration details
|
||||
- Lists price tiers with booking status
|
||||
- Displays included services
|
||||
|
||||
##### UPDATE
|
||||
|
||||
1. **Click "Edit"** on package
|
||||
2. **Modify Details**:
|
||||
- Update package information
|
||||
- Change validity periods
|
||||
- Adjust capacity (if no bookings)
|
||||
3. **Save**: Click "Update Package"
|
||||
|
||||
##### MANAGE PRICE TIERS
|
||||
|
||||
1. **Click "Tiers"** on package
|
||||
2. **View Existing Tiers**:
|
||||
- Shows seat type, label, price, capacity
|
||||
- Displays booking progress
|
||||
3. **Add New Tier**:
|
||||
- **Seat Type**: HSC, VIP, etc.
|
||||
- **Label**: Display name (e.g., "Regular Seat (HSC)")
|
||||
- **Price (minor)**: Amount in cents/minor units
|
||||
- **Available Seats**: Tier capacity
|
||||
4. **Edit Existing Tier**:
|
||||
- Click "Edit" on tier
|
||||
- Modify details (limited if bookings exist)
|
||||
5. **Delete Tier**:
|
||||
- Click "Delete" (only if no bookings)
|
||||
|
||||
##### ACTIVATE/DEACTIVATE
|
||||
|
||||
**Activate Package**:
|
||||
1. **For DRAFT packages**: Click "Activate"
|
||||
2. **Confirmation**: Package becomes publicly bookable
|
||||
3. **Status Change**: DRAFT → ACTIVE
|
||||
|
||||
**Deactivate Package**:
|
||||
1. **For ACTIVE packages**: Click "Deactivate"
|
||||
2. **Confirmation**: Removes from public booking
|
||||
3. **Existing Bookings**: Remain valid
|
||||
|
||||
##### DELETE
|
||||
|
||||
1. **Click "Delete"** on package
|
||||
2. **Warning**: Shows impact on existing bookings
|
||||
3. **Confirm**: Permanent removal
|
||||
4. **Cascade**: Also removes price tiers
|
||||
|
||||
#### Example Package
|
||||
|
||||
```
|
||||
Code: KULUBBI-2025
|
||||
Name: Kulubbi Pilgrimage Package
|
||||
Route: Addis Ababa → Awash (return)
|
||||
Capacity: 912 passengers
|
||||
Includes:
|
||||
- Round trip train ticket
|
||||
- Bus transfer to Kulubbi site
|
||||
- Meal on board
|
||||
- Guided tour
|
||||
|
||||
Price Tiers:
|
||||
- Regular Seat (HSC): 10,232 ETB
|
||||
- Premium Seat (VIP): 15,348 ETB
|
||||
- Sleeper Bed (BED): 20,464 ETB
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Package Inquiries
|
||||
|
||||
**Purpose**: Manage incoming package booking inquiries and lead conversion
|
||||
**Access Level**: Agent, Supervisor, Admin
|
||||
**Icon**: MessageSquare
|
||||
|
||||
#### Features Overview
|
||||
|
||||
```
|
||||
┌──────────────────────────────┐
|
||||
│ PACKAGE INQUIRIES MANAGEMENT │
|
||||
├──────────────────────────────┤
|
||||
│ ✓ View All Inquiries │
|
||||
│ ✓ Filter by Package │
|
||||
│ ✓ Track Inquiry Status │
|
||||
│ ✓ Contact Information │
|
||||
│ ✓ Lead Conversion │
|
||||
│ ✓ Delete Inquiries │
|
||||
└──────────────────────────────┘
|
||||
```
|
||||
|
||||
#### Inquiry Information
|
||||
|
||||
- **Contact Name**: Inquirer's name
|
||||
- **Contact Email/Phone**: Contact details
|
||||
- **Package**: Requested package
|
||||
- **Price Tier**: Selected tier (if specified)
|
||||
- **Traveler Count**: Number of passengers
|
||||
- **Inquiry Date**: When submitted
|
||||
- **Notes**: Additional comments
|
||||
- **Status**: Current inquiry status
|
||||
|
||||
#### Inquiry Statuses
|
||||
|
||||
- **NEW**: Just received, not yet contacted
|
||||
- **CONTACTED**: Agent has reached out
|
||||
- **CONVERTED**: Successfully converted to booking
|
||||
- **CLOSED**: Not converted, inquiry closed
|
||||
|
||||
#### CRUD Operations
|
||||
|
||||
##### READ (List Inquiries)
|
||||
|
||||
1. **Access Package Inquiries**:
|
||||
- Click **Package Inquiries** in Enhanced Features
|
||||
- Shows all inquiries
|
||||
|
||||
2. **Filter Options**:
|
||||
- **Package Filter**: Select specific package
|
||||
- **Status Filter**: NEW, CONTACTED, CONVERTED, CLOSED
|
||||
|
||||
3. **Inquiry Details**:
|
||||
- Contact information
|
||||
- Requested package and tier
|
||||
- Traveler count
|
||||
- Price information
|
||||
- Inquiry notes
|
||||
|
||||
##### UPDATE STATUS
|
||||
|
||||
1. **Status Dropdown**: In each inquiry row
|
||||
2. **Change Status**: Select new status
|
||||
3. **Auto-save**: Updates immediately
|
||||
4. **Track Progress**: Monitor conversion funnel
|
||||
|
||||
**Status Workflow**:
|
||||
```
|
||||
NEW → CONTACTED → CONVERTED/CLOSED
|
||||
```
|
||||
|
||||
##### DELETE
|
||||
|
||||
1. **Click "Delete"** on inquiry
|
||||
2. **Confirmation**: Cannot be undone
|
||||
3. **Use Case**: Remove spam or duplicate inquiries
|
||||
|
||||
#### Lead Management
|
||||
|
||||
**Best Practices**:
|
||||
1. **Respond Quickly**: Contact NEW inquiries within 24 hours
|
||||
2. **Follow Up**: Move to CONTACTED after first contact
|
||||
3. **Track Conversion**: Mark as CONVERTED when booked
|
||||
4. **Close Non-converts**: Mark as CLOSED if not interested
|
||||
|
||||
---
|
||||
|
||||
### Health Monitoring
|
||||
|
||||
**Purpose**: Monitor EDR Passenger API health and system performance
|
||||
**Access Level**: Admin, Supervisor
|
||||
**Icon**: Activity
|
||||
|
||||
#### Features Overview
|
||||
|
||||
```
|
||||
┌──────────────────────────────┐
|
||||
│ HEALTH MONITORING MGMT │
|
||||
├──────────────────────────────┤
|
||||
│ ✓ Liveness Checks │
|
||||
│ ✓ Readiness Probes │
|
||||
│ ✓ Database Health │
|
||||
│ ✓ Application Info │
|
||||
│ ✓ Real-time Status │
|
||||
│ ✓ Rate Limit Overview │
|
||||
└──────────────────────────────┘
|
||||
```
|
||||
|
||||
#### Health Check Types
|
||||
|
||||
**Liveness Probe** (`GET /health`):
|
||||
- Confirms API process is alive
|
||||
- Quick response check
|
||||
- Auto-refreshes every 30 seconds
|
||||
|
||||
**Readiness Probe** (`GET /health/ready`):
|
||||
- Database connectivity test
|
||||
- Live database ping with latency
|
||||
- Indicates if API can serve traffic
|
||||
|
||||
**Application Info** (`GET /health/info`):
|
||||
- App version and environment
|
||||
- System uptime
|
||||
- Refreshes every 60 seconds
|
||||
|
||||
#### Health Status Indicators
|
||||
|
||||
**Overall Status Banner**:
|
||||
- **Green**: All systems operational
|
||||
- **Red**: Service degraded
|
||||
- **Gray**: Checking status...
|
||||
|
||||
**Individual Probe Cards**:
|
||||
- Status dot (green/red/gray)
|
||||
- Health badge (Healthy/Degraded/Checking...)
|
||||
- Last check timestamp
|
||||
- Error details (if failed)
|
||||
|
||||
#### CRUD Operations
|
||||
|
||||
##### READ (Monitor Health)
|
||||
|
||||
1. **Access Health Page**:
|
||||
- Click **Health Monitoring** in Enhanced Features
|
||||
- Auto-refreshing dashboard
|
||||
|
||||
2. **System Overview**:
|
||||
- Overall health banner
|
||||
- Individual probe status
|
||||
- Real-time updates
|
||||
|
||||
3. **Detailed Metrics**:
|
||||
- Database latency (ms)
|
||||
- Application uptime
|
||||
- Version information
|
||||
- Environment details
|
||||
|
||||
##### REFRESH STATUS
|
||||
|
||||
1. **Manual Refresh**: Click "Refresh" button
|
||||
2. **Auto-refresh**:
|
||||
- Health probes: 30 seconds
|
||||
- App info: 60 seconds
|
||||
3. **Loading States**: Shows during refresh
|
||||
|
||||
#### Rate Limits Reference
|
||||
|
||||
The health page includes a rate limits table:
|
||||
|
||||
| Tier | Limit | Applied to |
|
||||
|------|-------|------------|
|
||||
| **auth** | 5 req/min | `/auth`, `/fayda/verification` |
|
||||
| **strict** | 20 req/min | `/bookings`, `/passengers`, `/payments`, `/wallet` |
|
||||
| **default** | 100 req/min | All other endpoints |
|
||||
| **exempt** | No limit | `/health/*`, payment webhooks |
|
||||
|
||||
#### Troubleshooting
|
||||
|
||||
**Common Issues**:
|
||||
|
||||
1. **Database Connectivity**:
|
||||
- Check network connection
|
||||
- Verify database server status
|
||||
- Review connection string
|
||||
|
||||
2. **High Latency**:
|
||||
- Monitor database performance
|
||||
- Check server resources
|
||||
- Review query optimization
|
||||
|
||||
3. **Failed Health Checks**:
|
||||
- Review API server logs
|
||||
- Check system resources
|
||||
- Verify service configuration
|
||||
|
||||
---
|
||||
|
||||
### System Config
|
||||
|
||||
**Purpose**: Centralized system configuration management with feature flags
|
||||
**Access Level**: Admin
|
||||
**Icon**: Settings
|
||||
|
||||
#### Features Overview
|
||||
|
||||
```
|
||||
┌──────────────────────────────┐
|
||||
│ SYSTEM CONFIG MANAGEMENT │
|
||||
├──────────────────────────────┤
|
||||
│ ✓ Rate Limit Configuration │
|
||||
│ ✓ Seat Booking Settings │
|
||||
│ ✓ Feature Flags │
|
||||
│ ✓ Operational Controls │
|
||||
│ ✓ Live Configuration Updates │
|
||||
│ ✓ Validation & Saving │
|
||||
└──────────────────────────────┘
|
||||
```
|
||||
|
||||
#### Configuration Categories
|
||||
|
||||
**Rate Limiting** (requests per minute per IP):
|
||||
- **Auth endpoints**: Login, register, OTP (default: 5)
|
||||
- **Strict endpoints**: Sensitive operations (default: 20)
|
||||
- **Default endpoints**: All other endpoints (default: 100)
|
||||
|
||||
**Seat Booking**:
|
||||
- **Hold Duration**: How long seats stay held (default: 5 minutes)
|
||||
- **Hold Cutoff**: Stop accepting holds X hours before departure (default: 2 hours)
|
||||
|
||||
#### CRUD Operations
|
||||
|
||||
##### READ (View Configuration)
|
||||
|
||||
1. **Access System Config**:
|
||||
- Click **System Config** in System section
|
||||
- Loads current configuration values
|
||||
|
||||
2. **Configuration Display**:
|
||||
- Rate limiting settings with descriptions
|
||||
- Seat booking parameters
|
||||
- Current values shown
|
||||
|
||||
##### UPDATE CONFIGURATION
|
||||
|
||||
1. **Modify Settings**:
|
||||
- **Auth Limit**: Adjust authentication rate limit
|
||||
- **Strict Limit**: Change sensitive operations limit
|
||||
- **Default Limit**: Update general rate limit
|
||||
- **Hold Duration**: Set seat hold time in minutes
|
||||
- **Hold Cutoff**: Set cutoff hours before departure
|
||||
|
||||
2. **Validation**:
|
||||
- Minimum values enforced
|
||||
- Reasonable maximums suggested
|
||||
- Input validation on save
|
||||
|
||||
3. **Save Changes**:
|
||||
- Click "Save Changes" button
|
||||
- Configuration applied immediately
|
||||
- Success/error feedback shown
|
||||
|
||||
#### Configuration Examples
|
||||
|
||||
**Rate Limiting Tiers**:
|
||||
```
|
||||
Auth endpoints (5/min):
|
||||
- /auth/login
|
||||
- /auth/register
|
||||
- /fayda/verification
|
||||
|
||||
Strict endpoints (20/min):
|
||||
- /bookings/*
|
||||
- /passengers/*
|
||||
- /payments/*
|
||||
- /wallet/*
|
||||
|
||||
Default endpoints (100/min):
|
||||
- /search/*
|
||||
- /stations/*
|
||||
- All other public endpoints
|
||||
```
|
||||
|
||||
**Seat Management**:
|
||||
```
|
||||
Hold Duration: 5 minutes
|
||||
- Passenger has 5 minutes to complete booking
|
||||
- After expiry, seats released automatically
|
||||
|
||||
Hold Cutoff: 2 hours
|
||||
- No new holds accepted within 2 hours of departure
|
||||
- Prevents last-minute booking complications
|
||||
```
|
||||
|
||||
#### System Impact
|
||||
|
||||
**Rate Limit Changes**:
|
||||
- Applied immediately to new requests
|
||||
- Existing connections not affected
|
||||
- Monitor for performance impact
|
||||
|
||||
**Seat Booking Changes**:
|
||||
- New holds use updated duration
|
||||
- Existing holds retain original expiry
|
||||
- Cutoff affects future booking attempts
|
||||
|
||||
#### Best Practices
|
||||
|
||||
1. **Monitor Impact**: Watch system performance after changes
|
||||
2. **Conservative Adjustments**: Make incremental changes
|
||||
3. **Peak Periods**: Consider higher limits during busy times
|
||||
4. **Security Balance**: Balance usability with abuse prevention
|
||||
5. **Documentation**: Document reasons for configuration changes
|
||||
|
||||
---
|
||||
|
||||
### Boarding Management
|
||||
|
||||
**Purpose**: Manage gate operations and passenger boarding processes
|
||||
**Access Level**: Agent, Supervisor, Admin
|
||||
**Icon**: Users
|
||||
|
||||
#### Features Overview
|
||||
|
||||
```
|
||||
┌──────────────────────────────┐
|
||||
│ BOARDING MANAGEMENT MGMT │
|
||||
├──────────────────────────────┤
|
||||
│ ✓ Gate Operations │
|
||||
│ ✓ Passenger Check-in │
|
||||
│ ✓ Boarding Pass Validation │
|
||||
│ ✓ Seat Assignment Verification│
|
||||
│ ✓ Boarding Status Tracking │
|
||||
│ ✓ Real-time Updates │
|
||||
└──────────────────────────────┘
|
||||
```
|
||||
|
||||
#### CRUD Operations
|
||||
|
||||
##### READ (Monitor Boarding)
|
||||
|
||||
1. **Access Boarding Page**:
|
||||
- Click **Boarding Management** in Enhanced Features
|
||||
- Select active trip/schedule
|
||||
- View real-time boarding status
|
||||
|
||||
2. **Boarding Dashboard**:
|
||||
- Total passengers expected
|
||||
- Passengers boarded
|
||||
- Boarding progress tracking
|
||||
|
||||
---
|
||||
|
||||
### Advanced Fare Configuration
|
||||
|
||||
**Purpose**: Manage complex fare rules and dynamic pricing strategies
|
||||
**Access Level**: Admin, Supervisor
|
||||
**Icon**: Calculator
|
||||
|
||||
#### Features Overview
|
||||
|
||||
```
|
||||
┌──────────────────────────────┐
|
||||
│ ADVANCED FARE CONFIG MGMT │
|
||||
├──────────────────────────────┤
|
||||
│ ✓ Dynamic Fare Rules │
|
||||
│ ✓ Segment-based Pricing │
|
||||
│ ✓ Nationality-specific Rates │
|
||||
│ ✓ Seasonal Adjustments │
|
||||
│ ✓ Fare Engine Integration │
|
||||
│ ✓ Real-time Calculations │
|
||||
└──────────────────────────────┘
|
||||
```
|
||||
|
||||
#### CRUD Operations
|
||||
|
||||
##### CREATE FARE RULES
|
||||
|
||||
1. **Access Fare Management**:
|
||||
- Click **Advanced Fare Config** in Enhanced Features
|
||||
- Choose between Schedule Fares or Segment Fares
|
||||
|
||||
2. **Configure Rules**:
|
||||
- Set fare amounts and validity periods
|
||||
- Define passenger categories and nationalities
|
||||
- Apply to specific routes or schedules
|
||||
|
||||
---
|
||||
|
||||
### Payment Methods Configuration
|
||||
|
||||
**Purpose**: Configure and manage payment provider integrations
|
||||
**Access Level**: Admin
|
||||
**Icon**: CreditCard
|
||||
|
||||
#### Features Overview
|
||||
|
||||
```
|
||||
┌──────────────────────────────┐
|
||||
│ PAYMENT METHODS CONFIG MGMT │
|
||||
├──────────────────────────────┤
|
||||
│ ✓ Provider Setup │
|
||||
│ ✓ API Configuration │
|
||||
│ ✓ Enable/Disable Methods │
|
||||
│ ✓ Webhook Management │
|
||||
│ ✓ Test Transactions │
|
||||
│ ✓ Fee Configuration │
|
||||
└──────────────────────────────┘
|
||||
```
|
||||
|
||||
#### Supported Providers
|
||||
|
||||
- **Telebirr**: Ethiopian mobile payment
|
||||
- **CBE Birr**: Commercial Bank of Ethiopia
|
||||
- **eBirr**: Electronic wallet service
|
||||
- **Card Payments**: VISA, Mastercard
|
||||
- **WAAFI**: Money transfer service
|
||||
- **Agent Cash**: Counter collection
|
||||
|
||||
#### CRUD Operations
|
||||
|
||||
##### UPDATE CONFIGURATION
|
||||
|
||||
1. **Provider Setup**:
|
||||
- Configure API credentials
|
||||
- Set transaction fees and limits
|
||||
- Enable/disable providers
|
||||
|
||||
2. **Test & Validate**:
|
||||
- Run test transactions
|
||||
- Validate webhook endpoints
|
||||
- Monitor connectivity
|
||||
|
||||
---
|
||||
|
||||
### Boarding Management
|
||||
|
||||
**Purpose**: Manage gate operations and passenger boarding processes
|
||||
**Access Level**: Agent, Supervisor, Admin
|
||||
**Icon**: Users
|
||||
|
||||
#### Features Overview
|
||||
|
||||
```
|
||||
┌──────────────────────────────┐
|
||||
│ BOARDING MANAGEMENT MGMT │
|
||||
├──────────────────────────────┤
|
||||
│ ✓ Gate Operations │
|
||||
│ ✓ Passenger Check-in │
|
||||
│ ✓ Boarding Pass Validation │
|
||||
│ ✓ Seat Assignment Verification│
|
||||
│ ✓ Boarding Status Tracking │
|
||||
│ ✓ Real-time Updates │
|
||||
└──────────────────────────────┘
|
||||
```
|
||||
|
||||
#### Boarding Process
|
||||
|
||||
1. **Pre-boarding Setup**: Configure gates and boarding times
|
||||
2. **Passenger Check-in**: Validate tickets and documents
|
||||
3. **Boarding Queue**: Manage passenger flow and priority boarding
|
||||
4. **Seat Verification**: Confirm seat assignments and resolve conflicts
|
||||
5. **Boarding Completion**: Final passenger count and departure clearance
|
||||
|
||||
#### CRUD Operations
|
||||
|
||||
##### READ (Monitor Boarding)
|
||||
|
||||
1. **Access Boarding Page**:
|
||||
- Click **Boarding Management** in Enhanced Features
|
||||
- Select active trip/schedule
|
||||
- View real-time boarding status
|
||||
|
||||
2. **Boarding Dashboard**:
|
||||
- Total passengers expected
|
||||
- Passengers boarded
|
||||
- Remaining passengers
|
||||
- Boarding progress percentage
|
||||
- Gate status and alerts
|
||||
|
||||
##### MANAGE BOARDING PROCESS
|
||||
|
||||
**Start Boarding**:
|
||||
1. **Select Trip**: Choose scheduled departure
|
||||
2. **Open Gates**: Activate boarding process
|
||||
3. **Scan Tickets**: Validate passenger tickets and documents
|
||||
4. **Update Status**: Track boarding progress in real-time
|
||||
|
||||
**Handle Issues**:
|
||||
1. **Seat Conflicts**: Resolve duplicate seat assignments
|
||||
2. **Missing Passengers**: Mark no-shows
|
||||
3. **Late Arrivals**: Process last-minute passengers
|
||||
4. **Special Assistance**: Handle wheelchair, elderly, child passengers
|
||||
|
||||
---
|
||||
|
||||
### Advanced Fare Configuration
|
||||
|
||||
**Purpose**: Manage complex fare rules and dynamic pricing strategies
|
||||
**Access Level**: Admin, Supervisor
|
||||
**Icon**: Calculator
|
||||
|
||||
#### Features Overview
|
||||
|
||||
```
|
||||
┌──────────────────────────────┐
|
||||
│ ADVANCED FARE CONFIG MGMT │
|
||||
├──────────────────────────────┤
|
||||
│ ✓ Dynamic Fare Rules │
|
||||
│ ✓ Segment-based Pricing │
|
||||
│ ✓ Nationality-specific Rates │
|
||||
│ ✓ Seasonal Adjustments │
|
||||
│ ✓ Fare Engine Integration │
|
||||
│ ✓ Real-time Calculations │
|
||||
└──────────────────────────────┘
|
||||
```
|
||||
|
||||
#### Fare Rule Types
|
||||
|
||||
**Schedule-specific Fares**:
|
||||
- Fixed rates for specific train schedules
|
||||
- Override default fare calculations
|
||||
- Temporary promotional pricing
|
||||
|
||||
**Route Segment Fares**:
|
||||
- Different pricing for route segments
|
||||
- Origin-destination specific rates
|
||||
- Distance-based calculations
|
||||
|
||||
**Passenger Category Fares**:
|
||||
- ADULT vs CHILD pricing
|
||||
- Nationality-based rates (Ethiopian, Djiboutian, Other)
|
||||
- Group discounts
|
||||
|
||||
#### CRUD Operations
|
||||
|
||||
##### CREATE FARE RULES
|
||||
|
||||
1. **Access Fare Management**:
|
||||
- Click **Advanced Fare Config** in Enhanced Features
|
||||
- Choose between Schedule Fares or Segment Fares
|
||||
|
||||
2. **Schedule Fare Rule**:
|
||||
- **Schedule**: Select specific trip
|
||||
- **Seat Class**: Choose class (Economy, VIP, etc.)
|
||||
- **Fare Amount**: Set price in ETB
|
||||
- **Passenger Type**: ADULT or CHILD (optional)
|
||||
- **Nationality**: Specific nationality or All
|
||||
- **Valid Period**: Start and end dates
|
||||
|
||||
3. **Segment Fare Rule**:
|
||||
- **Route**: Select route
|
||||
- **Origin/Destination**: Choose station pair
|
||||
- **Seat Class**: Select class
|
||||
- **Fare Amount**: Set segment price
|
||||
- **Passenger Type**: ADULT/CHILD filter
|
||||
- **Valid Period**: Effective dates
|
||||
|
||||
##### READ (View Fare Rules)
|
||||
|
||||
1. **Schedule Fares Tab**:
|
||||
- Select schedule to view calculated fares
|
||||
- See all active seat classes
|
||||
- View fare breakdown by category
|
||||
|
||||
2. **Segment Fares Tab**:
|
||||
- Select route to view segment rules
|
||||
- See origin-destination combinations
|
||||
- Filter by fare rule criteria
|
||||
|
||||
##### UPDATE/DELETE FARE RULES
|
||||
|
||||
1. **Edit Rules**: Click "Edit" on existing fare rule
|
||||
2. **Delete Rules**: Click "Delete" to remove rule
|
||||
3. **Validation**: Changes affect future bookings only
|
||||
|
||||
#### Fare Calculation Priority
|
||||
|
||||
```
|
||||
1. Segment Fare (nationality-specific)
|
||||
2. Segment Fare (generic)
|
||||
3. Schedule Fare (nationality-specific)
|
||||
4. Schedule Fare (generic)
|
||||
5. Default Class Base Fare
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Payment Methods Configuration
|
||||
|
||||
**Purpose**: Configure and manage payment provider integrations
|
||||
**Access Level**: Admin
|
||||
**Icon**: CreditCard
|
||||
|
||||
#### Features Overview
|
||||
|
||||
```
|
||||
┌──────────────────────────────┐
|
||||
│ PAYMENT METHODS CONFIG MGMT │
|
||||
├──────────────────────────────┤
|
||||
│ ✓ Provider Setup │
|
||||
│ ✓ API Configuration │
|
||||
│ ✓ Enable/Disable Methods │
|
||||
│ ✓ Webhook Management │
|
||||
│ ✓ Test Transactions │
|
||||
│ ✓ Fee Configuration │
|
||||
└──────────────────────────────┘
|
||||
```
|
||||
|
||||
#### Supported Payment Providers
|
||||
|
||||
- **Telebirr**: Ethiopian mobile payment
|
||||
- **CBE Birr**: Commercial Bank of Ethiopia
|
||||
- **eBirr**: Electronic wallet service
|
||||
- **Card Payments**: VISA, Mastercard via gateway
|
||||
- **WAAFI**: Money transfer service
|
||||
- **Agent Cash**: Counter cash collection
|
||||
|
||||
#### CRUD Operations
|
||||
|
||||
##### READ (View Payment Methods)
|
||||
|
||||
1. **Access Payment Methods**:
|
||||
- Click **Payment Methods** in Enhanced Features
|
||||
- View all configured providers
|
||||
- See status and configuration
|
||||
|
||||
2. **Provider Status**:
|
||||
- Enabled/Disabled toggle
|
||||
- Configuration status
|
||||
- Last transaction test
|
||||
- Error logs (if any)
|
||||
|
||||
##### UPDATE CONFIGURATION
|
||||
|
||||
**Provider Setup**:
|
||||
1. **API Credentials**:
|
||||
- Base URL
|
||||
- API Key/Secret
|
||||
- Merchant ID
|
||||
- Webhook endpoints
|
||||
|
||||
2. **Settings**:
|
||||
- Enable/disable provider
|
||||
- Transaction fees
|
||||
- Minimum/maximum amounts
|
||||
- Currency support
|
||||
|
||||
3. **Test Configuration**:
|
||||
- Run test transactions
|
||||
- Validate webhook endpoints
|
||||
- Check API connectivity
|
||||
|
||||
**Webhook Management**:
|
||||
1. **Endpoint URLs**: Configure callback URLs
|
||||
2. **Security**: Set webhook secrets
|
||||
3. **Event Types**: Select events to receive
|
||||
4. **Retry Logic**: Configure retry attempts
|
||||
|
||||
##### TROUBLESHOOTING
|
||||
|
||||
**Common Issues**:
|
||||
1. **API Connectivity**: Check network and credentials
|
||||
2. **Webhook Failures**: Verify endpoint accessibility
|
||||
3. **Transaction Failures**: Review provider logs
|
||||
4. **Configuration Errors**: Validate API settings
|
||||
|
||||
452
apps/edr-passenger-web/backoffice/src/app/boarding/page.tsx
Normal file
452
apps/edr-passenger-web/backoffice/src/app/boarding/page.tsx
Normal file
@@ -0,0 +1,452 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useRef, useEffect, useCallback } from 'react';
|
||||
import { useMutation, useQuery } from '@tanstack/react-query';
|
||||
import { QrCode, Camera, RotateCcw, CheckCircle, XCircle, User, MapPin, Clock, Train, CameraOff } from 'lucide-react';
|
||||
import { ticketsApi, apiClient } from '@/lib/api';
|
||||
import { useAuthStore } from '@/lib/auth-store';
|
||||
import { formatDateTime } from '@/lib/utils';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import Header from '@/components/layout/Header';
|
||||
|
||||
// Add QR Scanner component
|
||||
function QRScanner({ onScan, onError }: { onScan: (data: string) => void; onError: (error: string) => void }) {
|
||||
const videoRef = useRef<HTMLVideoElement>(null);
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null);
|
||||
const [isScanning, setIsScanning] = useState(false);
|
||||
const [stream, setStream] = useState<MediaStream | null>(null);
|
||||
const [cameraError, setCameraError] = useState<string | null>(null);
|
||||
const scanIntervalRef = useRef<number | null>(null);
|
||||
|
||||
const startCamera = async () => {
|
||||
try {
|
||||
setCameraError(null);
|
||||
const mediaStream = await navigator.mediaDevices.getUserMedia({
|
||||
video: {
|
||||
facingMode: 'environment', // Use back camera
|
||||
width: { ideal: 1280 },
|
||||
height: { ideal: 720 }
|
||||
}
|
||||
});
|
||||
|
||||
if (videoRef.current) {
|
||||
videoRef.current.srcObject = mediaStream;
|
||||
await videoRef.current.play();
|
||||
setStream(mediaStream);
|
||||
setIsScanning(true);
|
||||
}
|
||||
} catch (error: any) {
|
||||
const errorMsg = 'Camera access denied. Please enable camera permissions in browser settings.';
|
||||
setCameraError(errorMsg);
|
||||
onError(errorMsg);
|
||||
console.error('Camera error:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const stopCamera = useCallback(() => {
|
||||
if (scanIntervalRef.current) {
|
||||
clearInterval(scanIntervalRef.current);
|
||||
scanIntervalRef.current = null;
|
||||
}
|
||||
if (stream) {
|
||||
stream.getTracks().forEach(track => track.stop());
|
||||
setStream(null);
|
||||
}
|
||||
if (videoRef.current) {
|
||||
videoRef.current.srcObject = null;
|
||||
}
|
||||
setIsScanning(false);
|
||||
setCameraError(null);
|
||||
}, [stream]);
|
||||
|
||||
// QR code scanning with jsqr
|
||||
const scanFrame = useCallback(() => {
|
||||
if (!videoRef.current || !canvasRef.current || !isScanning) return;
|
||||
|
||||
const video = videoRef.current;
|
||||
const canvas = canvasRef.current;
|
||||
const ctx = canvas.getContext('2d', { willReadFrequently: true });
|
||||
|
||||
if (ctx && video.readyState === video.HAVE_ENOUGH_DATA) {
|
||||
canvas.width = video.videoWidth;
|
||||
canvas.height = video.videoHeight;
|
||||
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
|
||||
|
||||
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
|
||||
|
||||
try {
|
||||
// Try to use jsqr if available
|
||||
const jsQR = (window as any).jsQR;
|
||||
if (jsQR) {
|
||||
const code = jsQR(imageData.data, imageData.width, imageData.height, {
|
||||
inversionAttempts: 'dontInvert',
|
||||
});
|
||||
|
||||
if (code) {
|
||||
onScan(code.data);
|
||||
stopCamera();
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('QR scan error:', err);
|
||||
}
|
||||
}
|
||||
}, [isScanning, onScan, stopCamera]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isScanning) {
|
||||
scanIntervalRef.current = window.setInterval(scanFrame, 100); // Scan every 100ms
|
||||
}
|
||||
return () => {
|
||||
if (scanIntervalRef.current) {
|
||||
clearInterval(scanIntervalRef.current);
|
||||
}
|
||||
stopCamera();
|
||||
};
|
||||
}, [isScanning, scanFrame, stopCamera]);
|
||||
|
||||
// Load jsqr from CDN
|
||||
useEffect(() => {
|
||||
if (!(window as any).jsQR) {
|
||||
const script = document.createElement('script');
|
||||
script.src = 'https://cdn.jsdelivr.net/npm/jsqr@1.4.0/dist/jsQR.min.js';
|
||||
script.async = true;
|
||||
document.body.appendChild(script);
|
||||
return () => {
|
||||
document.body.removeChild(script);
|
||||
};
|
||||
}
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{!isScanning ? (
|
||||
<div className="space-y-3">
|
||||
<button
|
||||
onClick={startCamera}
|
||||
className="w-full bg-blue-600 hover:bg-blue-700 text-white font-semibold py-4 px-6 rounded-xl transition-colors flex items-center justify-center gap-2"
|
||||
>
|
||||
<Camera className="w-5 h-5" />
|
||||
Scan QR Code
|
||||
</button>
|
||||
{cameraError && (
|
||||
<div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-3">
|
||||
<p className="text-red-700 dark:text-red-300 text-sm">{cameraError}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
<div className="relative bg-black rounded-xl overflow-hidden">
|
||||
<video
|
||||
ref={videoRef}
|
||||
autoPlay
|
||||
playsInline
|
||||
muted
|
||||
className="w-full h-64 object-cover"
|
||||
/>
|
||||
<div className="absolute inset-0 flex items-center justify-center">
|
||||
<div className="relative w-48 h-48">
|
||||
<div className="absolute inset-0 border-2 border-white border-dashed rounded-lg"></div>
|
||||
<div className="absolute top-0 left-0 w-6 h-6 border-t-4 border-l-4 border-blue-400 rounded-tl-lg"></div>
|
||||
<div className="absolute top-0 right-0 w-6 h-6 border-t-4 border-r-4 border-blue-400 rounded-tr-lg"></div>
|
||||
<div className="absolute bottom-0 left-0 w-6 h-6 border-b-4 border-l-4 border-blue-400 rounded-bl-lg"></div>
|
||||
<div className="absolute bottom-0 right-0 w-6 h-6 border-b-4 border-r-4 border-blue-400 rounded-br-lg"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/70 to-transparent p-4">
|
||||
<p className="text-white text-center text-sm font-medium">Position QR code within frame</p>
|
||||
</div>
|
||||
</div>
|
||||
<canvas ref={canvasRef} className="hidden" />
|
||||
<button
|
||||
onClick={stopCamera}
|
||||
className="w-full bg-gray-600 hover:bg-gray-700 text-white font-semibold py-3 px-6 rounded-xl transition-colors flex items-center justify-center gap-2"
|
||||
>
|
||||
<CameraOff className="w-5 h-5" />
|
||||
Stop Camera
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function BoardingPage() {
|
||||
const [qrInput, setQrInput] = useState('');
|
||||
const [lastScanned, setLastScanned] = useState<any>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [success, setSuccess] = useState<string | null>(null);
|
||||
const [isScanning, setIsScanning] = useState(false);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const { user, isAuthenticated } = useAuthStore();
|
||||
const router = useRouter();
|
||||
|
||||
// Check authentication on mount
|
||||
useEffect(() => {
|
||||
if (!isAuthenticated) {
|
||||
router.push('/login');
|
||||
return;
|
||||
}
|
||||
}, [isAuthenticated, router]);
|
||||
|
||||
// Get current agent data
|
||||
const { data: agentData } = useQuery({
|
||||
queryKey: ['agent-me'],
|
||||
queryFn: () => apiClient.get<any>('/agents/me'),
|
||||
enabled: !!user,
|
||||
retry: false,
|
||||
});
|
||||
|
||||
const boardingMutation = useMutation({
|
||||
mutationFn: (qrCodeOrRef: string) =>
|
||||
ticketsApi.scanAndBoard(qrCodeOrRef, {
|
||||
validatorId: agentData?.id || user?.id || 'BACKOFFICE',
|
||||
gateId: 'MOBILE-GATE',
|
||||
}),
|
||||
onSuccess: (result) => {
|
||||
setError(null);
|
||||
if (result.success) {
|
||||
setSuccess('Passenger boarded successfully!');
|
||||
setLastScanned(result.boarding);
|
||||
setQrInput('');
|
||||
// Auto-focus for next scan
|
||||
setTimeout(() => inputRef.current?.focus(), 1000);
|
||||
} else {
|
||||
setError(result.error || 'Boarding failed');
|
||||
setLastScanned(null);
|
||||
}
|
||||
},
|
||||
onError: (error: any) => {
|
||||
setError(error?.response?.data?.message || error.message || 'Boarding failed');
|
||||
setSuccess(null);
|
||||
setLastScanned(null);
|
||||
},
|
||||
});
|
||||
|
||||
const handleScan = (inputValue?: string) => {
|
||||
const valueToScan = inputValue || qrInput.trim();
|
||||
if (!valueToScan) {
|
||||
setError('Please enter QR code or booking reference');
|
||||
return;
|
||||
}
|
||||
|
||||
setError(null);
|
||||
setSuccess(null);
|
||||
boardingMutation.mutate(valueToScan);
|
||||
};
|
||||
|
||||
const handleButtonClick = () => {
|
||||
handleScan();
|
||||
};
|
||||
|
||||
const handleKeyPress = (e: React.KeyboardEvent) => {
|
||||
if (e.key === 'Enter') {
|
||||
handleButtonClick();
|
||||
}
|
||||
};
|
||||
|
||||
const clearAll = () => {
|
||||
setQrInput('');
|
||||
setError(null);
|
||||
setSuccess(null);
|
||||
setLastScanned(null);
|
||||
inputRef.current?.focus();
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
// Auto-focus on mount for mobile scanning (only if authenticated)
|
||||
if (isAuthenticated) {
|
||||
inputRef.current?.focus();
|
||||
}
|
||||
}, [isAuthenticated]);
|
||||
|
||||
// Show loading or redirect if not authenticated
|
||||
if (!isAuthenticated) {
|
||||
return (
|
||||
<div className="flex h-screen items-center justify-center bg-gray-50 dark:bg-slate-950">
|
||||
<div className="text-center">
|
||||
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-edr-green-600 mx-auto"></div>
|
||||
<p className="mt-4 text-gray-600 dark:text-gray-400">Redirecting to login...</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-screen overflow-hidden bg-gray-50 dark:bg-slate-950">
|
||||
<div className="flex flex-1 flex-col overflow-hidden">
|
||||
<Header />
|
||||
<main className="flex-1 overflow-y-auto bg-gray-50 dark:bg-slate-950">
|
||||
<div className="min-h-full bg-gradient-to-br from-emerald-50 to-blue-50 dark:from-slate-900 dark:to-slate-800 p-4">
|
||||
{/* Mobile-optimized container */}
|
||||
<div className="max-w-md mx-auto space-y-6">
|
||||
|
||||
{/* Header */}
|
||||
<div className="text-center py-6">
|
||||
<div className="inline-flex items-center justify-center w-16 h-16 bg-emerald-600 rounded-full mb-4">
|
||||
<QrCode className="w-8 h-8 text-white" />
|
||||
</div>
|
||||
<h1 className="text-2xl font-bold text-gray-900 dark:text-white">Boarding</h1>
|
||||
<p className="text-gray-600 dark:text-gray-400 mt-1">Scan ticket QR codes to board passengers</p>
|
||||
{agentData && (
|
||||
<div className="text-sm text-emerald-600 dark:text-emerald-400 mt-2">
|
||||
Agent: {agentData.agentCode || agentData.name}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Scanner Input */}
|
||||
<div className="bg-white dark:bg-slate-800 rounded-2xl shadow-xl p-6 border border-gray-100 dark:border-slate-700">
|
||||
<div className="space-y-4">
|
||||
|
||||
{/* Camera Scanner */}
|
||||
<QRScanner
|
||||
onScan={(data) => {
|
||||
setQrInput(data);
|
||||
handleScan(data);
|
||||
}}
|
||||
onError={setError}
|
||||
/>
|
||||
|
||||
{/* Manual Input */}
|
||||
<div className="text-center text-gray-500 dark:text-gray-400 text-sm">OR</div>
|
||||
|
||||
<div className="relative">
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="text"
|
||||
value={qrInput}
|
||||
onChange={(e) => setQrInput(e.target.value)}
|
||||
onKeyPress={handleKeyPress}
|
||||
placeholder="Type ticket number"
|
||||
className="w-full px-4 py-4 text-lg border border-gray-300 dark:border-slate-600 rounded-xl
|
||||
focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500
|
||||
dark:bg-slate-700 dark:text-white dark:placeholder-slate-400
|
||||
font-mono tracking-wide"
|
||||
autoCapitalize="characters"
|
||||
autoComplete="off"
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-3">
|
||||
<button
|
||||
onClick={handleButtonClick}
|
||||
disabled={boardingMutation.isPending || !qrInput.trim()}
|
||||
className="flex-1 bg-emerald-600 hover:bg-emerald-700 disabled:bg-gray-300
|
||||
text-white font-semibold py-4 px-6 rounded-xl transition-colors
|
||||
disabled:cursor-not-allowed text-lg"
|
||||
>
|
||||
{boardingMutation.isPending ? 'Boarding...' : 'Board Passenger'}
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={clearAll}
|
||||
className="bg-gray-500 hover:bg-gray-600 text-white font-semibold py-4 px-6 rounded-xl transition-colors"
|
||||
>
|
||||
<RotateCcw className="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Success Message */}
|
||||
{success && (
|
||||
<div className="bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-2xl p-6">
|
||||
<div className="flex items-center gap-3 mb-3">
|
||||
<CheckCircle className="w-6 h-6 text-green-600 dark:text-green-400" />
|
||||
<span className="text-green-800 dark:text-green-200 font-semibold text-lg">{success}</span>
|
||||
</div>
|
||||
|
||||
{lastScanned && (
|
||||
<div className="mt-4 space-y-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<User className="w-4 h-4 text-green-600 dark:text-green-400" />
|
||||
<span className="text-green-700 dark:text-green-300 font-medium">
|
||||
{lastScanned.passengerName}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<MapPin className="w-4 h-4 text-green-600 dark:text-green-400" />
|
||||
<span className="text-green-700 dark:text-green-300">
|
||||
{lastScanned.route}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<Train className="w-4 h-4 text-green-600 dark:text-green-400" />
|
||||
<span className="text-green-700 dark:text-green-300">
|
||||
{lastScanned.trainName} - Coach {lastScanned.coach}, Seat {lastScanned.seat}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<Clock className="w-4 h-4 text-green-600 dark:text-green-400" />
|
||||
<span className="text-green-700 dark:text-green-300">
|
||||
Boarded: {formatDateTime(lastScanned.boardedAt)} ({lastScanned.leg})
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{lastScanned.isRoundTrip && (
|
||||
<div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-3 mt-3">
|
||||
<p className="text-blue-700 dark:text-blue-300 text-sm">
|
||||
ℹ️ Round-trip ticket: Scan again for return journey
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="text-sm text-green-600 dark:text-green-400 font-mono mt-2">
|
||||
Booking: {lastScanned.bookingRef} | Ticket: {lastScanned.ticketId}
|
||||
</div>
|
||||
|
||||
<div className="text-xs text-green-600 dark:text-green-400 mt-2">
|
||||
📧 Email & SMS notifications sent to passenger
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Error Message */}
|
||||
{error && (
|
||||
<div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-2xl p-6">
|
||||
<div className="flex items-center gap-3">
|
||||
<XCircle className="w-6 h-6 text-red-600 dark:text-red-400" />
|
||||
<span className="text-red-800 dark:text-red-200 font-semibold">{error}</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Instructions */}
|
||||
<div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-2xl p-6">
|
||||
<h3 className="text-blue-800 dark:text-blue-200 font-semibold mb-3">How to scan:</h3>
|
||||
<ul className="text-blue-700 dark:text-blue-300 space-y-2 text-sm">
|
||||
<li>• Tap "Scan QR Code" and point at ticket QR code</li>
|
||||
<li>• For manual option, type or paste booking reference</li>
|
||||
<li>• Tickets can only be boarded on their departure date</li>
|
||||
<li>• First scan boards outbound leg for round trips</li>
|
||||
<li>• Email & SMS sent automatically to passenger contacts</li>
|
||||
<li>• Red error shows validation issues</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
{/* Quick Stats */}
|
||||
<div className="bg-white dark:bg-slate-800 rounded-2xl shadow-xl p-6 border border-gray-100 dark:border-slate-700">
|
||||
<h3 className="text-gray-900 dark:text-white font-semibold mb-3">Session Summary</h3>
|
||||
<div className="flex justify-between items-center text-sm">
|
||||
<span className="text-gray-600 dark:text-gray-400">Status:</span>
|
||||
<span className="text-emerald-600 dark:text-emerald-400 font-semibold">
|
||||
Ready to scan
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { Download, Eye, XCircle, Trash2 } from 'lucide-react';
|
||||
import { Download, Eye, Trash2 } from 'lucide-react';
|
||||
import DataTable from '@/components/ui/DataTable';
|
||||
import Badge from '@/components/ui/Badge';
|
||||
import Pagination from '@/components/ui/Pagination';
|
||||
@@ -31,7 +31,6 @@ const SectionHeader = ({ title }: { title: string }) => (
|
||||
|
||||
function BookingsPageContent() {
|
||||
const canManage = usePermission(PERMS.bookings.manage);
|
||||
const canCancel = usePermission(PERMS.bookings.cancel);
|
||||
const [filters, setFilters] = useState<BookingFilters>({ page: 1, pageSize: 20, search: '', status: '' });
|
||||
const [extraFilters, setExtraFilters] = useState({ bookingType: '', dateFrom: '', dateTo: '', paymentStatus: '' });
|
||||
const [showExtraFilters, setShowExtraFilters] = useState(false);
|
||||
@@ -62,16 +61,6 @@ function BookingsPageContent() {
|
||||
}),
|
||||
});
|
||||
|
||||
const cancelMutation = useMutation({
|
||||
mutationFn: ({ id, reason }: { id: string; reason?: string }) => bookingsApi.cancel(id, reason),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['bookings'] });
|
||||
setSuccessMessage('Booking cancelled successfully');
|
||||
setTimeout(() => setSuccessMessage(''), 3000);
|
||||
},
|
||||
onError: (error: any) => alert(`Error: ${error.message || 'Failed to cancel booking'}`),
|
||||
});
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (id: string) => apiClient.delete(`/bookings/${id}`),
|
||||
onSuccess: () => {
|
||||
@@ -87,12 +76,6 @@ function BookingsPageContent() {
|
||||
},
|
||||
});
|
||||
|
||||
const handleCancel = async (booking: any) => {
|
||||
if (window.confirm(`Cancel booking ${booking.bookingRef}? This will process a refund.`)) {
|
||||
await cancelMutation.mutateAsync({ id: booking.id, reason: 'Cancelled by admin' });
|
||||
}
|
||||
};
|
||||
|
||||
const BOOKING_COLS = [
|
||||
{ key: 'bookingRef', label: 'Booking Reference' }, { key: 'journeyType', label: 'Journey Type' },
|
||||
{ key: 'passengerNames', label: 'Passenger Names' }, { key: 'contactPhone', label: 'Contact Phone' },
|
||||
@@ -167,9 +150,38 @@ function BookingsPageContent() {
|
||||
{
|
||||
key: 'passengerNames', label: 'Names',
|
||||
render: (booking: any) => {
|
||||
const names: string[] = booking.passengerNames || [];
|
||||
if (!names.length) return <span className="text-muted-foreground">—</span>;
|
||||
return <div className="flex flex-col gap-0.5">{names.map((n, i) => <span key={i} className="text-sm">{n}</span>)}</div>;
|
||||
const passengers = booking.passengers || [];
|
||||
if (!passengers.length) {
|
||||
// Fallback to old logic if passengers array not available
|
||||
const names: string[] = booking.passengerNames || [];
|
||||
const adultCount = booking.adultCount || 0;
|
||||
if (!names.length) return <span className="text-muted-foreground">—</span>;
|
||||
return (
|
||||
<div className="flex flex-col gap-0.5">
|
||||
{names.map((name, i) => {
|
||||
const isAdult = i < adultCount;
|
||||
const passengerType = isAdult ? 'A' : 'C';
|
||||
return (
|
||||
<span key={i} className="text-sm">
|
||||
{name} ({passengerType})
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className="flex flex-col gap-0.5">
|
||||
{passengers.map((p: any, i: number) => {
|
||||
const passengerType = p.category === 'ADULT' ? 'A' : 'C';
|
||||
return (
|
||||
<span key={i} className="text-sm">
|
||||
{p.name} ({passengerType})
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -206,10 +218,6 @@ function BookingsPageContent() {
|
||||
|
||||
const actions = [
|
||||
{ label: 'View Details', onClick: (b: any) => setSelectedBooking(b), variant: 'secondary' as const, icon: Eye },
|
||||
{
|
||||
label: 'Cancel Booking', onClick: handleCancel, variant: 'danger' as const, icon: XCircle,
|
||||
show: (b: any) => b.status !== 'CANCELLED' && b.status !== 'BOARDED',
|
||||
},
|
||||
{ label: 'Delete', onClick: (b: any) => { setDeleteError(null); setBookingToDelete(b); setDeleteConfirmOpen(true); }, variant: 'danger' as const, icon: Trash2 },
|
||||
];
|
||||
|
||||
|
||||
@@ -144,8 +144,11 @@ export default function CoachesPage() {
|
||||
const [activeTab, setActiveTab] = useState<Tab>('coaches');
|
||||
const [search, setSearch] = useState('');
|
||||
const [showModal, setShowModal] = useState(false);
|
||||
const [showPreviewModal, setShowPreviewModal] = useState(false);
|
||||
const [seatMapPreview, setSeatMapPreview] = useState<any>(null);
|
||||
const [editingItem, setEditingItem] = useState<any>(null);
|
||||
const [deleteConfirm, setDeleteConfirm] = useState<{ isOpen: boolean; item: any | null; error?: string }>({ isOpen: false, item: null });
|
||||
const [selectedCoachTypeId, setSelectedCoachTypeId] = useState<string>('');
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
// Coach Types Queries
|
||||
@@ -212,6 +215,14 @@ export default function CoachesPage() {
|
||||
},
|
||||
});
|
||||
|
||||
const generateSeatMapMutation = useMutation({
|
||||
mutationFn: fleetApi.generateSeatMap,
|
||||
onSuccess: (data) => {
|
||||
setSeatMapPreview(data);
|
||||
setShowPreviewModal(true);
|
||||
},
|
||||
});
|
||||
|
||||
const handleCoachTypeSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
const formData = new FormData(e.currentTarget);
|
||||
@@ -231,7 +242,8 @@ export default function CoachesPage() {
|
||||
const handleCoachSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
const formData = new FormData(e.currentTarget);
|
||||
const data = {
|
||||
|
||||
const data: any = {
|
||||
number: formData.get('number') as string,
|
||||
coachTypeId: formData.get('coachTypeId') as string,
|
||||
arrangement: formData.get('arrangement') as string,
|
||||
@@ -240,6 +252,16 @@ export default function CoachesPage() {
|
||||
status: formData.get('status') as string,
|
||||
};
|
||||
|
||||
// Add bed-specific fields if bed coach is selected
|
||||
const bedCategory = formData.get('bedCategory') as string;
|
||||
if (bedCategory) {
|
||||
data.bedCategory = bedCategory as 'ECONOMY_BED' | 'VIP_BED';
|
||||
const bedsPerRoom = formData.get('bedsPerRoom') as string;
|
||||
if (bedsPerRoom) {
|
||||
data.bedsPerRoom = parseInt(bedsPerRoom);
|
||||
}
|
||||
}
|
||||
|
||||
if (editingItem?.isCoach) {
|
||||
await updateCoachMutation.mutateAsync({ id: editingItem.id, data });
|
||||
} else {
|
||||
@@ -247,6 +269,27 @@ export default function CoachesPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const handlePreviewSeatMap = async () => {
|
||||
const form = document.querySelector('form') as HTMLFormElement;
|
||||
const formData = new FormData(form);
|
||||
const bedCategory = formData.get('bedCategory') as string;
|
||||
const capacity = parseInt(formData.get('capacity') as string);
|
||||
|
||||
if (!bedCategory || !capacity) {
|
||||
alert('Please select a bed category and enter capacity to preview seat map');
|
||||
return;
|
||||
}
|
||||
|
||||
const bedsPerRoom = bedCategory === 'VIP_BED' ? 4 : 6;
|
||||
const roomsPerCoach = Math.ceil(capacity / bedsPerRoom);
|
||||
|
||||
await generateSeatMapMutation.mutateAsync({
|
||||
coachCount: 1,
|
||||
roomsPerCoach,
|
||||
roomType: bedCategory,
|
||||
});
|
||||
};
|
||||
|
||||
const handleDelete = (item: any, isCoachType: boolean) => {
|
||||
setDeleteConfirm({ isOpen: true, item: { ...item, isCoachType } });
|
||||
};
|
||||
@@ -298,7 +341,6 @@ export default function CoachesPage() {
|
||||
|
||||
const statusMap: Record<string, string> = {
|
||||
ACTIVE: 'edr-badge-success',
|
||||
MAINTENANCE: 'edr-badge-warning',
|
||||
INACTIVE: 'edr-badge-danger',
|
||||
};
|
||||
|
||||
@@ -373,10 +415,30 @@ export default function CoachesPage() {
|
||||
},
|
||||
{
|
||||
key: 'arrangement',
|
||||
label: 'Arrangement',
|
||||
render: (coach: any) => (
|
||||
<span className="text-sm font-mono">{coach.arrangement || 'N/A'}</span>
|
||||
),
|
||||
label: 'Type/Arrangement',
|
||||
render: (coach: any) => {
|
||||
// Check if this is a bed coach based on coach type name containing 'bed'
|
||||
const coachTypeName = coach.coachType?.name?.toLowerCase() || '';
|
||||
const isBedCoach = coachTypeName.includes('bed') || coachTypeName.includes('sleeper') || coachTypeName.includes('berth');
|
||||
|
||||
if (isBedCoach) {
|
||||
// Determine if it's VIP or Economy based on coach type name
|
||||
const isVIP = coachTypeName.includes('vip');
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<Bed className="h-4 w-4 text-blue-600" />
|
||||
<span className="text-sm font-mono">{coach.arrangement || 'N/A'}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<Armchair className="h-4 w-4 text-green-600" />
|
||||
<span className="text-sm font-mono">{coach.arrangement || 'N/A'}</span>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'capacity',
|
||||
@@ -422,6 +484,7 @@ export default function CoachesPage() {
|
||||
label: 'Edit',
|
||||
onClick: (item: any) => {
|
||||
setEditingItem({ ...item, isCoach: true });
|
||||
setSelectedCoachTypeId(item.coachTypeId || '');
|
||||
setShowModal(true);
|
||||
},
|
||||
variant: 'secondary' as const,
|
||||
@@ -446,6 +509,7 @@ export default function CoachesPage() {
|
||||
icon={Plus}
|
||||
onClick={() => {
|
||||
setEditingItem(null);
|
||||
setSelectedCoachTypeId('');
|
||||
setSearch('');
|
||||
setShowModal(true);
|
||||
}}
|
||||
@@ -556,6 +620,7 @@ export default function CoachesPage() {
|
||||
onClose={() => {
|
||||
setShowModal(false);
|
||||
setEditingItem(null);
|
||||
setSelectedCoachTypeId('');
|
||||
}}
|
||||
title={
|
||||
activeTab === 'types'
|
||||
@@ -636,12 +701,13 @@ export default function CoachesPage() {
|
||||
name="coachTypeId"
|
||||
className="input"
|
||||
defaultValue={editingItem?.coachTypeId || ''}
|
||||
onChange={(e) => setSelectedCoachTypeId(e.target.value)}
|
||||
required
|
||||
>
|
||||
<option value="">Select Coach Type</option>
|
||||
{coachTypesArray.map((ct: any) => (
|
||||
<option key={ct.id} value={ct.id}>
|
||||
{ct.code} - {ct.name} - {ct.type}
|
||||
{ct.code} - {ct.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
@@ -659,17 +725,66 @@ export default function CoachesPage() {
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Conditionally show bed fields only for Economy and Regular coach types */}
|
||||
{(() => {
|
||||
const selectedCoachType = coachTypesArray.find((ct: any) => ct.id === (selectedCoachTypeId || editingItem?.coachTypeId));
|
||||
const isEconomyOrRegular = selectedCoachType &&
|
||||
(selectedCoachType.name?.toLowerCase().includes('economy') ||
|
||||
selectedCoachType.name?.toLowerCase().includes('regular') ||
|
||||
selectedCoachType.type?.toLowerCase().includes('economy') ||
|
||||
selectedCoachType.type?.toLowerCase().includes('regular'));
|
||||
|
||||
return isEconomyOrRegular ? (
|
||||
<>
|
||||
<div>
|
||||
<label className="label">Bed Category</label>
|
||||
<select
|
||||
name="bedCategory"
|
||||
className="input"
|
||||
defaultValue={editingItem?.bedCategory || ''}
|
||||
>
|
||||
<option value="">Select bed category</option>
|
||||
<option value="ECONOMY_BED">Economy Bed</option>
|
||||
<option value="VIP_BED">VIP Bed</option>
|
||||
</select>
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
Select if this is a bed coach
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="label">Beds Per Room</label>
|
||||
<select
|
||||
name="bedsPerRoom"
|
||||
className="input"
|
||||
defaultValue={editingItem?.bedsPerRoom || ''}
|
||||
>
|
||||
<option value="">Auto (VIP: 4, Economy: 6)</option>
|
||||
<option value="2">2 beds per room</option>
|
||||
<option value="4">4 beds per room</option>
|
||||
<option value="6">6 beds per room</option>
|
||||
</select>
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
Only applies to bed coaches
|
||||
</p>
|
||||
</div>
|
||||
</>
|
||||
) : null;
|
||||
})()}
|
||||
|
||||
<div>
|
||||
<label className="label">Arrangement *</label>
|
||||
<input
|
||||
type="text"
|
||||
name="arrangement"
|
||||
className="input"
|
||||
defaultValue={editingItem?.arrangement || editingItem?.seatArrangement }
|
||||
defaultValue={editingItem?.arrangement || editingItem?.seatArrangement || '2+2'}
|
||||
required
|
||||
placeholder="e.g., 3+2, 3+0, 2+0"
|
||||
placeholder="e.g., 2+2, 3+2"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground mt-1">Format: separate columns with +</p>
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
For regular seats: columns separated by +
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
@@ -691,12 +806,14 @@ export default function CoachesPage() {
|
||||
type="number"
|
||||
name="sequence"
|
||||
className="input"
|
||||
defaultValue={editingItem?.sequence || 0}
|
||||
min="0"
|
||||
defaultValue={editingItem?.sequence || 1}
|
||||
min="1"
|
||||
required
|
||||
placeholder="e.g., 1"
|
||||
placeholder="1"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground mt-1">Used for ordering coaches in trains</p>
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
Position in train consist
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
@@ -708,19 +825,27 @@ export default function CoachesPage() {
|
||||
required
|
||||
>
|
||||
<option value="ACTIVE">Active</option>
|
||||
<option value="MAINTENANCE">Maintenance</option>
|
||||
<option value="INACTIVE">Inactive</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-2 pt-4">
|
||||
<ActionButton
|
||||
type="button"
|
||||
variant="secondary"
|
||||
onClick={handlePreviewSeatMap}
|
||||
loading={generateSeatMapMutation.isPending}
|
||||
>
|
||||
Preview Bed Layout
|
||||
</ActionButton>
|
||||
<ActionButton
|
||||
type="button"
|
||||
variant="secondary"
|
||||
onClick={() => {
|
||||
setShowModal(false);
|
||||
setEditingItem(null);
|
||||
setSelectedCoachTypeId('');
|
||||
}}
|
||||
>
|
||||
Cancel
|
||||
@@ -735,6 +860,58 @@ export default function CoachesPage() {
|
||||
</form>
|
||||
)}
|
||||
</Modal>
|
||||
|
||||
{/* Seat Map Preview Modal */}
|
||||
<Modal
|
||||
isOpen={showPreviewModal}
|
||||
onClose={() => {
|
||||
setShowPreviewModal(false);
|
||||
setSeatMapPreview(null);
|
||||
}}
|
||||
title="Bed Layout Preview"
|
||||
size="lg"
|
||||
>
|
||||
{seatMapPreview && (
|
||||
<div className="space-y-4">
|
||||
<div className="bg-muted/50 p-4 rounded-lg">
|
||||
<h4 className="font-semibold mb-2">Configuration</h4>
|
||||
<div className="grid grid-cols-2 gap-4 text-sm">
|
||||
<div>Room Type: <span className="font-medium">{seatMapPreview.roomType}</span></div>
|
||||
<div>Rooms per Coach: <span className="font-medium">{seatMapPreview.roomsPerCoach}</span></div>
|
||||
<div>Beds per Room: <span className="font-medium">{seatMapPreview.bedsPerRoom}</span></div>
|
||||
<div>Total Beds: <span className="font-medium">{seatMapPreview.totalBeds}</span></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<h4 className="font-semibold">Bed Layout Sample (First Few Rooms)</h4>
|
||||
<div className="bg-gray-50 p-4 rounded border max-h-64 overflow-y-auto">
|
||||
{seatMapPreview.seats?.slice(0, 24).map((seat: any, idx: number) => (
|
||||
<div key={idx} className="text-xs mb-1 font-mono">
|
||||
{seat.seat_id} - Room: {seat.room_id} - {seat.position} {seat.bed_type}
|
||||
</div>
|
||||
))}
|
||||
{seatMapPreview.seats?.length > 24 && (
|
||||
<div className="text-xs text-muted-foreground mt-2">
|
||||
... and {seatMapPreview.seats.length - 24} more beds
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end">
|
||||
<ActionButton
|
||||
onClick={() => {
|
||||
setShowPreviewModal(false);
|
||||
setSeatMapPreview(null);
|
||||
}}
|
||||
>
|
||||
Close
|
||||
</ActionButton>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { PermissionGuard } from '@/components/layout/PermissionGuard';
|
||||
import { PERMS } from '@/lib/permissions';
|
||||
import { Ticket, Users, DollarSign, Percent } from 'lucide-react';
|
||||
import { Ticket, Users, DollarSign, Percent, AlertCircle, TrendingUp, Calendar } from 'lucide-react';
|
||||
import StatCard from '@/components/dashboard/StatCard';
|
||||
import DataTable from '@/components/ui/DataTable';
|
||||
import Badge from '@/components/ui/Badge';
|
||||
@@ -13,43 +13,83 @@ import { LineChart, Line, BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, R
|
||||
|
||||
const COLORS = ['#2563eb', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6'];
|
||||
|
||||
// Mock data for fallback when API fails
|
||||
const MOCK_STATS = {
|
||||
totalBookings: 1247,
|
||||
totalRevenue: 892450,
|
||||
totalPassengers: 2156,
|
||||
occupancyRate: 78
|
||||
};
|
||||
|
||||
const MOCK_RECENT_BOOKINGS = [
|
||||
{
|
||||
id: '1',
|
||||
bookingRef: 'BK-2024-001',
|
||||
passenger: { fullName: 'John Doe' },
|
||||
totalMinor: 125000,
|
||||
currency: 'ETB',
|
||||
status: 'CONFIRMED',
|
||||
createdAt: new Date().toISOString()
|
||||
},
|
||||
{
|
||||
id: '2',
|
||||
bookingRef: 'BK-2024-002',
|
||||
passenger: { fullName: 'Jane Smith' },
|
||||
totalMinor: 85000,
|
||||
currency: 'ETB',
|
||||
status: 'PENDING',
|
||||
createdAt: new Date().toISOString()
|
||||
}
|
||||
];
|
||||
|
||||
function DashboardPageContent() {
|
||||
const { data: stats, isLoading: statsLoading } = useQuery({
|
||||
const { data: stats, isLoading: statsLoading, error: statsError } = useQuery({
|
||||
queryKey: ['dashboard-stats'],
|
||||
queryFn: dashboardApi.getStats,
|
||||
retry: 1,
|
||||
staleTime: 60000, // 1 minute
|
||||
});
|
||||
|
||||
const { data: revenueData, isLoading: revenueLoading } = useQuery({
|
||||
queryKey: ['revenue-chart'],
|
||||
queryFn: () => dashboardApi.getRevenueChart(30),
|
||||
retry: 1,
|
||||
});
|
||||
|
||||
const { data: recentBookingsData, isLoading: bookingsLoading } = useQuery<any[]>({
|
||||
const { data: recentBookingsData, isLoading: bookingsLoading, error: bookingsError } = useQuery<any[]>({
|
||||
queryKey: ['recent-bookings'],
|
||||
queryFn: () => dashboardApi.getRecentBookings(10),
|
||||
retry: 1,
|
||||
});
|
||||
|
||||
const { data: topAgents, isLoading: agentsLoading } = useQuery({
|
||||
queryKey: ['top-agents'],
|
||||
queryFn: () => dashboardApi.getTopAgents(5),
|
||||
retry: 1,
|
||||
});
|
||||
|
||||
const { data: occupancyTrend, isLoading: occupancyLoading } = useQuery({
|
||||
queryKey: ['occupancy-trend'],
|
||||
queryFn: () => dashboardApi.getOccupancyTrend(7),
|
||||
retry: 1,
|
||||
});
|
||||
|
||||
const { data: upcomingTrips, isLoading: tripsLoading } = useQuery({
|
||||
queryKey: ['upcoming-trips'],
|
||||
queryFn: () => dashboardApi.getUpcomingTrips(5),
|
||||
retry: 1,
|
||||
});
|
||||
|
||||
const { data: paymentMethods } = useQuery({
|
||||
queryKey: ['payment-methods'],
|
||||
queryFn: dashboardApi.getPaymentMethods,
|
||||
retry: 1,
|
||||
});
|
||||
|
||||
const recentBookings = Array.isArray(recentBookingsData) ? recentBookingsData : [];
|
||||
// Use actual data or fallback to mock/empty states
|
||||
const displayStats = stats || (statsError ? MOCK_STATS : null);
|
||||
const recentBookings = Array.isArray(recentBookingsData) ? recentBookingsData :
|
||||
(bookingsError ? MOCK_RECENT_BOOKINGS : []);
|
||||
|
||||
const bookingColumns = [
|
||||
{ key: 'reference', label: 'Reference', render: (item: any) => item.bookingRef || item.reference },
|
||||
@@ -106,35 +146,52 @@ function DashboardPageContent() {
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="space-y-6 p-6">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-foreground">Dashboard</h1>
|
||||
<p className="text-muted-foreground mt-1">Welcome back! Here's your operational summary.</p>
|
||||
</div>
|
||||
|
||||
{/* Error Alert */}
|
||||
{(statsError || bookingsError) && (
|
||||
<div className="rounded-lg border border-orange-200 bg-orange-50 dark:border-orange-800 dark:bg-orange-950/30 p-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<AlertCircle className="h-5 w-5 text-orange-600 dark:text-orange-400" />
|
||||
<div>
|
||||
<h3 className="font-semibold text-orange-800 dark:text-orange-200">
|
||||
Some data may be outdated
|
||||
</h3>
|
||||
<p className="text-sm text-orange-700 dark:text-orange-300">
|
||||
Unable to fetch live data. Showing cached or sample information.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Primary Metrics */}
|
||||
<div className="grid grid-cols-1 gap-6 md:grid-cols-2 lg:grid-cols-4">
|
||||
<div className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-4">
|
||||
<StatCard
|
||||
title="Total Bookings"
|
||||
value={statsLoading ? '...' : (stats?.totalBookings || 0).toLocaleString()}
|
||||
value={statsLoading ? '...' : (displayStats?.totalBookings || 0).toLocaleString()}
|
||||
icon={Ticket}
|
||||
color="blue"
|
||||
/>
|
||||
<StatCard
|
||||
title="Total Revenue"
|
||||
value={statsLoading ? '...' : formatCurrency(stats?.totalRevenue || 0, 'ETB')}
|
||||
value={statsLoading ? '...' : formatCurrency(displayStats?.totalRevenue || 0, 'ETB')}
|
||||
icon={DollarSign}
|
||||
color="green"
|
||||
/>
|
||||
<StatCard
|
||||
title="Total Passengers"
|
||||
value={statsLoading ? '...' : (stats?.totalPassengers || 0).toLocaleString()}
|
||||
value={statsLoading ? '...' : (displayStats?.totalPassengers || 0).toLocaleString()}
|
||||
icon={Users}
|
||||
color="purple"
|
||||
/>
|
||||
<StatCard
|
||||
title="Occupancy Rate"
|
||||
value={statsLoading ? '...' : `${stats?.occupancyRate || 0}%`}
|
||||
value={statsLoading ? '...' : `${displayStats?.occupancyRate || 0}%`}
|
||||
icon={Percent}
|
||||
color="orange"
|
||||
/>
|
||||
@@ -143,9 +200,16 @@ function DashboardPageContent() {
|
||||
{/* Charts Row */}
|
||||
<div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
|
||||
{/* Revenue Trend */}
|
||||
{!revenueLoading && revenueData && revenueData.length > 0 && (
|
||||
<div className="card">
|
||||
<h2 className="mb-4 text-lg font-semibold text-foreground">Revenue Trend (Last 30 Days)</h2>
|
||||
<div className="card">
|
||||
<h2 className="mb-4 text-lg font-semibold text-foreground flex items-center gap-2">
|
||||
<TrendingUp className="h-5 w-5" />
|
||||
Revenue Trend (Last 30 Days)
|
||||
</h2>
|
||||
{revenueLoading ? (
|
||||
<div className="flex h-[300px] items-center justify-center">
|
||||
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
|
||||
</div>
|
||||
) : revenueData && revenueData.length > 0 ? (
|
||||
<ResponsiveContainer width="100%" height={300}>
|
||||
<LineChart data={revenueData}>
|
||||
<CartesianGrid strokeDasharray="3 3" className="stroke-border" />
|
||||
@@ -155,13 +219,27 @@ function DashboardPageContent() {
|
||||
<Line type="monotone" dataKey="revenue" stroke="#2563eb" strokeWidth={2} />
|
||||
</LineChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
)}
|
||||
) : (
|
||||
<div className="flex h-[300px] items-center justify-center text-muted-foreground">
|
||||
<div className="text-center">
|
||||
<TrendingUp className="h-12 w-12 mx-auto mb-2 opacity-50" />
|
||||
<p>No revenue data available</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Occupancy Trend */}
|
||||
{!occupancyLoading && occupancyTrend && occupancyTrend.length > 0 && (
|
||||
<div className="card">
|
||||
<h2 className="mb-4 text-lg font-semibold text-foreground">Occupancy Trend (Last 7 Days)</h2>
|
||||
<div className="card">
|
||||
<h2 className="mb-4 text-lg font-semibold text-foreground flex items-center gap-2">
|
||||
<Percent className="h-5 w-5" />
|
||||
Occupancy Trend (Last 7 Days)
|
||||
</h2>
|
||||
{occupancyLoading ? (
|
||||
<div className="flex h-[300px] items-center justify-center">
|
||||
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-green-600"></div>
|
||||
</div>
|
||||
) : occupancyTrend && occupancyTrend.length > 0 ? (
|
||||
<ResponsiveContainer width="100%" height={300}>
|
||||
<BarChart data={occupancyTrend}>
|
||||
<CartesianGrid strokeDasharray="3 3" className="stroke-border" />
|
||||
@@ -171,8 +249,15 @@ function DashboardPageContent() {
|
||||
<Bar dataKey="occupancyRate" fill="#10b981" radius={[8, 8, 0, 0]} />
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
)}
|
||||
) : (
|
||||
<div className="flex h-[300px] items-center justify-center text-muted-foreground">
|
||||
<div className="text-center">
|
||||
<Percent className="h-12 w-12 mx-auto mb-2 opacity-50" />
|
||||
<p>No occupancy data available</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Payment Methods Distribution */}
|
||||
@@ -202,40 +287,45 @@ function DashboardPageContent() {
|
||||
|
||||
{/* Recent Bookings */}
|
||||
<div className="card">
|
||||
<h2 className="mb-4 text-lg font-semibold text-foreground">Recent Bookings</h2>
|
||||
<h2 className="mb-4 text-lg font-semibold text-foreground flex items-center gap-2">
|
||||
<Ticket className="h-5 w-5" />
|
||||
Recent Bookings
|
||||
</h2>
|
||||
<DataTable
|
||||
data={recentBookings}
|
||||
columns={bookingColumns}
|
||||
loading={bookingsLoading}
|
||||
emptyMessage="No recent bookings"
|
||||
emptyMessage="No recent bookings found"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Upcoming Trips */}
|
||||
{upcomingTrips && upcomingTrips.length > 0 && (
|
||||
<div className="card">
|
||||
<h2 className="mb-4 text-lg font-semibold text-foreground">Upcoming Trips</h2>
|
||||
<DataTable
|
||||
data={upcomingTrips}
|
||||
columns={tripColumns}
|
||||
loading={tripsLoading}
|
||||
emptyMessage="No upcoming trips"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<div className="card">
|
||||
<h2 className="mb-4 text-lg font-semibold text-foreground flex items-center gap-2">
|
||||
<Calendar className="h-5 w-5" />
|
||||
Upcoming Trips
|
||||
</h2>
|
||||
<DataTable
|
||||
data={upcomingTrips || []}
|
||||
columns={tripColumns}
|
||||
loading={tripsLoading}
|
||||
emptyMessage="No upcoming trips scheduled"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Top Agents */}
|
||||
{topAgents && topAgents.length > 0 && (
|
||||
<div className="card">
|
||||
<h2 className="mb-4 text-lg font-semibold text-foreground">Top Performing Agents</h2>
|
||||
<DataTable
|
||||
data={topAgents}
|
||||
columns={agentColumns}
|
||||
loading={agentsLoading}
|
||||
emptyMessage="No agent data"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<div className="card">
|
||||
<h2 className="mb-4 text-lg font-semibold text-foreground flex items-center gap-2">
|
||||
<Users className="h-5 w-5" />
|
||||
Top Performing Agents
|
||||
</h2>
|
||||
<DataTable
|
||||
data={topAgents || []}
|
||||
columns={agentColumns}
|
||||
loading={agentsLoading}
|
||||
emptyMessage="No agent performance data available"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -246,4 +336,4 @@ export default function DashboardPage() {
|
||||
<DashboardPageContent />
|
||||
</PermissionGuard>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ const DocPage = () => {
|
||||
security: false,
|
||||
analytics: false,
|
||||
system: false,
|
||||
enhanced: false,
|
||||
});
|
||||
|
||||
const toggleSection = (section: string) => {
|
||||
@@ -133,10 +134,32 @@ const DocPage = () => {
|
||||
{ id: 'agents-how', label: '→ How-To' },
|
||||
{ id: 'users', label: 'Users' },
|
||||
{ id: 'users-how', label: '→ How-To' },
|
||||
{ id: 'system-config', label: 'System Config' },
|
||||
{ id: 'system-config-how', label: '→ How-To' },
|
||||
{ id: 'settings', label: 'Settings' },
|
||||
{ id: 'settings-how', label: '→ How-To' },
|
||||
]
|
||||
},
|
||||
{
|
||||
id: 'enhanced',
|
||||
title: '✨ Enhanced Features',
|
||||
items: [
|
||||
{ id: 'excess-baggage', label: 'Excess Baggage' },
|
||||
{ id: 'excess-baggage-how', label: '→ How-To' },
|
||||
{ id: 'packages', label: 'Travel Packages' },
|
||||
{ id: 'packages-how', label: '→ How-To' },
|
||||
{ id: 'package-inquiries', label: 'Package Inquiries' },
|
||||
{ id: 'package-inquiries-how', label: '→ How-To' },
|
||||
{ id: 'health', label: 'Health Monitoring' },
|
||||
{ id: 'health-how', label: '→ How-To' },
|
||||
{ id: 'boarding', label: 'Boarding Management' },
|
||||
{ id: 'boarding-how', label: '→ How-To' },
|
||||
{ id: 'fare-config', label: 'Advanced Fare Config' },
|
||||
{ id: 'fare-config-how', label: '→ How-To' },
|
||||
{ id: 'payment-methods', label: 'Payment Methods' },
|
||||
{ id: 'payment-methods-how', label: '→ How-To' },
|
||||
]
|
||||
},
|
||||
];
|
||||
|
||||
const HowToStep = ({ number, title, children }: { number: number; title: string; children: React.ReactNode }) => (
|
||||
@@ -203,7 +226,18 @@ const DocPage = () => {
|
||||
|
||||
<div id="about">
|
||||
<h2 className="text-3xl font-bold text-slate-900 dark:text-white mb-4">Welcome to EDR Passenger Backoffice</h2>
|
||||
<p className="text-slate-600 dark:text-slate-300">Comprehensive management system for the Ethio-Djibouti Railway passenger platform. This documentation provides complete guidance on all features, operations, and best practices.</p>
|
||||
<p className="text-slate-600 dark:text-slate-300 mb-4">Comprehensive management system for the Ethio-Djibouti Railway passenger platform. This documentation provides complete guidance on all features, operations, and best practices.</p>
|
||||
<div className="bg-emerald-50 dark:bg-emerald-900/20 p-6 rounded-lg border border-emerald-200 dark:border-emerald-800">
|
||||
<h3 className="text-lg font-semibold text-emerald-900 dark:text-emerald-100 mb-2">🎆 Version 1.0.0 - Complete Platform Release</h3>
|
||||
<ul className="text-emerald-800 dark:text-emerald-200 space-y-1">
|
||||
<li>• <strong>Excess Baggage:</strong> Complete baggage handling with agent tools and passenger self-pay</li>
|
||||
<li>• <strong>Travel Packages:</strong> Bundled offerings with tiered pricing and inquiry management</li>
|
||||
<li>• <strong>Health Monitoring:</strong> Comprehensive system status and performance tracking</li>
|
||||
<li>• <strong>Boarding Management:</strong> Gate operations and passenger processing workflows</li>
|
||||
<li>• <strong>Advanced Fare Config:</strong> Dynamic pricing with segment-based rules</li>
|
||||
<li>• <strong>Payment Methods:</strong> Multi-provider payment configuration and management</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="features" className="border-t pt-8">
|
||||
@@ -222,7 +256,7 @@ const DocPage = () => {
|
||||
<div className="space-y-4">
|
||||
<HowToStep number={1} title="Access Bookings">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click {`"Bookings"`} in Operations section</li>
|
||||
<li>Click "Bookings" in Operations section</li>
|
||||
<li>View all bookings in table format</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
@@ -234,704 +268,278 @@ const DocPage = () => {
|
||||
</HowToStep>
|
||||
<HowToStep number={3} title="Manage Bookings">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click {`"View Details"`} for full information</li>
|
||||
<li>Click {`"Cancel Booking"`} to process refunds</li>
|
||||
<li>Click "View Details" for full information</li>
|
||||
<li>Click "Cancel Booking" to process refunds</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* PASSENGERS */}
|
||||
<div id="passengers" className="border-t pt-8">
|
||||
<h2 className="text-2xl font-bold text-slate-900 dark:text-white mb-4">👥 Passengers</h2>
|
||||
<p className="text-slate-600 dark:text-slate-300">Manage passenger profiles, loyalty, and verification status.</p>
|
||||
<div id="system-config" className="border-t pt-8">
|
||||
<h2 className="text-2xl font-bold text-slate-900 dark:text-white mb-4">⚙️ System Config</h2>
|
||||
<p className="text-slate-600 dark:text-slate-300">Centralized system configuration management with feature flags and operational controls.</p>
|
||||
</div>
|
||||
|
||||
<div id="passengers-how" className="border-t pt-8">
|
||||
<h3 className="text-2xl font-bold text-slate-900 dark:text-white mb-2">👥 How-To: Manage Passengers</h3>
|
||||
<div id="system-config-how" className="border-t pt-8">
|
||||
<h3 className="text-2xl font-bold text-slate-900 dark:text-white mb-2">⚙️ How-To: Manage System Configuration</h3>
|
||||
<div className="space-y-4">
|
||||
<HowToStep number={1} title="Access Passengers">
|
||||
<HowToStep number={1} title="Access System Config">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click {`"Passengers"`} in Operations</li>
|
||||
<li>View all profiles with pagination</li>
|
||||
<li>Click "System Config" in System section</li>
|
||||
<li>View all configuration categories</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
<HowToStep number={2} title="Rate Limiting">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Adjust auth endpoints limit (default: 5 req/min)</li>
|
||||
<li>Set strict endpoints limit (default: 20 req/min)</li>
|
||||
<li>Configure default endpoints limit (default: 100 req/min)</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
<HowToStep number={3} title="Seat Booking Settings">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Set seat hold duration (default: 5 minutes)</li>
|
||||
<li>Configure hold cutoff before departure (default: 2 hours)</li>
|
||||
<li>Click "Save Changes" to apply</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* EXCESS BAGGAGE */}
|
||||
<div id="excess-baggage" className="border-t pt-8">
|
||||
<h2 className="text-2xl font-bold text-slate-900 dark:text-white mb-4">📦 Excess Baggage</h2>
|
||||
<p className="text-slate-600 dark:text-slate-300">Manage excess baggage charges at boarding with agent tools and passenger self-pay options.</p>
|
||||
</div>
|
||||
|
||||
<div id="excess-baggage-how" className="border-t pt-8">
|
||||
<h3 className="text-2xl font-bold text-slate-900 dark:text-white mb-2">📦 How-To: Handle Excess Baggage</h3>
|
||||
<div className="space-y-4">
|
||||
<HowToStep number={1} title="Access Excess Baggage">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click "Excess Baggage" in Enhanced Features</li>
|
||||
<li>View all baggage charges and their status</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
<HowToStep number={2} title="Search & Filter">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Search by name, email, phone, ID</li>
|
||||
<li>Filter by nationality, verification, loyalty tier</li>
|
||||
<li>Search by booking reference</li>
|
||||
<li>Filter by status: PENDING, PAID, CASH_COLLECTED, EXPIRED, WAIVED</li>
|
||||
<li>Use date filters for specific periods</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
<HowToStep number={3} title="View Profile">
|
||||
<HowToStep number={3} title="Manage Charges">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click passenger row to open modal</li>
|
||||
<li>View account, loyalty, wallet, booking history</li>
|
||||
<li>"Resend Link" for pending charges to passenger</li>
|
||||
<li>"Waive" charges with reason (supervisor authority)</li>
|
||||
<li>"Delete" expired or waived charges</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* TICKETS */}
|
||||
<div id="tickets" className="border-t pt-8">
|
||||
<h2 className="text-2xl font-bold text-slate-900 dark:text-white mb-4">🎫 Tickets</h2>
|
||||
<p className="text-slate-600 dark:text-slate-300">Manage ticket generation, tracking, and validation.</p>
|
||||
{/* TRAVEL PACKAGES */}
|
||||
<div id="packages" className="border-t pt-8">
|
||||
<h2 className="text-2xl font-bold text-slate-900 dark:text-white mb-4">🎒 Travel Packages</h2>
|
||||
<p className="text-slate-600 dark:text-slate-300">Manage pilgrimage and group travel packages with tiered pricing and capacity management.</p>
|
||||
</div>
|
||||
|
||||
<div id="tickets-how" className="border-t pt-8">
|
||||
<h3 className="text-2xl font-bold text-slate-900 dark:text-white mb-2">🎫 How-To: Manage Tickets</h3>
|
||||
<div id="packages-how" className="border-t pt-8">
|
||||
<h3 className="text-2xl font-bold text-slate-900 dark:text-white mb-2">🎒 How-To: Manage Travel Packages</h3>
|
||||
<div className="space-y-4">
|
||||
<HowToStep number={1} title="View Tickets">
|
||||
<HowToStep number={1} title="Create Package">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click {`"Tickets"`} in Operations</li>
|
||||
<li>View all issued tickets with status</li>
|
||||
<li>Click "New Package" button</li>
|
||||
<li>Fill package details: code, name, stations, schedules</li>
|
||||
<li>Set capacity, validity period, and included services</li>
|
||||
<li>Save package (starts in DRAFT status)</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
<HowToStep number={2} title="Search Tickets">
|
||||
<HowToStep number={2} title="Configure Price Tiers">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Search by booking reference or ticket number</li>
|
||||
<li>Filter by validation status</li>
|
||||
<li>Click "Tiers" on package to manage pricing</li>
|
||||
<li>Add tiers: seat type, label, price, capacity</li>
|
||||
<li>Edit existing tiers (limited if bookings exist)</li>
|
||||
<li>Delete unused tiers</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
<HowToStep number={3} title="Download PDF">
|
||||
<HowToStep number={3} title="Activate & Manage">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click ticket to view details</li>
|
||||
<li>Click {`"Download PDF"`} for printable version</li>
|
||||
<li>"Activate" draft packages to make bookable</li>
|
||||
<li>"Deactivate" active packages to stop new bookings</li>
|
||||
<li>"Delete" packages with no bookings if needed</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* STATIONS */}
|
||||
<div id="stations" className="border-t pt-8">
|
||||
<h2 className="text-2xl font-bold text-slate-900 dark:text-white mb-4">🏢 Stations</h2>
|
||||
<p className="text-slate-600 dark:text-slate-300">Configure railway stations with locations and timezones.</p>
|
||||
{/* PACKAGE INQUIRIES */}
|
||||
<div id="package-inquiries" className="border-t pt-8">
|
||||
<h2 className="text-2xl font-bold text-slate-900 dark:text-white mb-4">📝 Package Inquiries</h2>
|
||||
<p className="text-slate-600 dark:text-slate-300">Manage incoming package booking inquiries and track lead conversion.</p>
|
||||
</div>
|
||||
|
||||
<div id="stations-how" className="border-t pt-8">
|
||||
<h3 className="text-2xl font-bold text-slate-900 dark:text-white mb-2">🏢 How-To: Manage Stations</h3>
|
||||
<div id="package-inquiries-how" className="border-t pt-8">
|
||||
<h3 className="text-2xl font-bold text-slate-900 dark:text-white mb-2">📝 How-To: Handle Package Inquiries</h3>
|
||||
<div className="space-y-4">
|
||||
<HowToStep number={1} title="Access Stations">
|
||||
<HowToStep number={1} title="View Inquiries">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click {`"Stations"`} in Master Data</li>
|
||||
<li>View all configured stations</li>
|
||||
<li>Click "Package Inquiries" in Enhanced Features</li>
|
||||
<li>Filter by package or inquiry status</li>
|
||||
<li>View contact details, package interest, traveler count</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
<HowToStep number={2} title="Create Station">
|
||||
<HowToStep number={2} title="Update Status">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click {`"Add Station"`}</li>
|
||||
<li>Enter code, name, city, timezone, coordinates</li>
|
||||
<li>Use status dropdown: NEW → CONTACTED → CONVERTED/CLOSED</li>
|
||||
<li>Mark as CONTACTED after first customer contact</li>
|
||||
<li>Mark as CONVERTED when inquiry becomes booking</li>
|
||||
<li>Mark as CLOSED if customer not interested</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
<HowToStep number={3} title="Edit Station">
|
||||
<HowToStep number={3} title="Lead Management">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click station to open details</li>
|
||||
<li>Update information and save</li>
|
||||
<li>Respond to NEW inquiries within 24 hours</li>
|
||||
<li>Follow up on CONTACTED inquiries regularly</li>
|
||||
<li>Delete spam or duplicate inquiries as needed</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* TRAINS */}
|
||||
<div id="trains" className="border-t pt-8">
|
||||
<h2 className="text-2xl font-bold text-slate-900 dark:text-white mb-4">🚂 Trains</h2>
|
||||
<p className="text-slate-600 dark:text-slate-300">Manage train fleet with coach assignments.</p>
|
||||
{/* HEALTH MONITORING */}
|
||||
<div id="health" className="border-t pt-8">
|
||||
<h2 className="text-2xl font-bold text-slate-900 dark:text-white mb-4">🏥 Health Monitoring</h2>
|
||||
<p className="text-slate-600 dark:text-slate-300">Monitor EDR Passenger API health with real-time system status and performance metrics.</p>
|
||||
</div>
|
||||
|
||||
<div id="trains-how" className="border-t pt-8">
|
||||
<h3 className="text-2xl font-bold text-slate-900 dark:text-white mb-2">🚂 How-To: Manage Trains</h3>
|
||||
<div id="health-how" className="border-t pt-8">
|
||||
<h3 className="text-2xl font-bold text-slate-900 dark:text-white mb-2">🏥 How-To: Monitor System Health</h3>
|
||||
<div className="space-y-4">
|
||||
<HowToStep number={1} title="Access Trains">
|
||||
<HowToStep number={1} title="Access Health Dashboard">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click {`"Trains"`} in Master Data</li>
|
||||
<li>View all trains and coaches</li>
|
||||
<li>Click "Health Monitoring" in Enhanced Features</li>
|
||||
<li>View overall system status banner</li>
|
||||
<li>Check individual probe cards (auto-refreshing)</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
<HowToStep number={2} title="Create Train">
|
||||
<HowToStep number={2} title="Interpret Health Checks">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click {`"Add Train"`}</li>
|
||||
<li>Enter code and select coaches</li>
|
||||
<li>Liveness: API process alive (30s refresh)</li>
|
||||
<li>Readiness: Database connectivity + latency (30s refresh)</li>
|
||||
<li>App Info: Version, uptime, environment (60s refresh)</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
<HowToStep number={3} title="Assign Coaches">
|
||||
<HowToStep number={3} title="Troubleshoot Issues">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click train to edit</li>
|
||||
<li>Add/remove coaches with position numbers</li>
|
||||
<li>Red status: Check error details and system logs</li>
|
||||
<li>High DB latency: Monitor database performance</li>
|
||||
<li>Failed checks: Verify API server and connections</li>
|
||||
<li>Use "Refresh" button for manual status update</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* COACHES */}
|
||||
<div id="coaches" className="border-t pt-8">
|
||||
<h2 className="text-2xl font-bold text-slate-900 dark:text-white mb-4">🚃 Coaches</h2>
|
||||
<p className="text-slate-600 dark:text-slate-300">Manage coach inventory with seat configurations.</p>
|
||||
{/* BOARDING MANAGEMENT */}
|
||||
<div id="boarding" className="border-t pt-8">
|
||||
<h2 className="text-2xl font-bold text-slate-900 dark:text-white mb-4">🚆 Boarding Management</h2>
|
||||
<p className="text-slate-600 dark:text-slate-300">Manage gate operations and passenger boarding processes with real-time tracking.</p>
|
||||
</div>
|
||||
|
||||
<div id="coaches-how" className="border-t pt-8">
|
||||
<h3 className="text-2xl font-bold text-slate-900 dark:text-white mb-2">🚃 How-To: Manage Coaches</h3>
|
||||
<div id="boarding-how" className="border-t pt-8">
|
||||
<h3 className="text-2xl font-bold text-slate-900 dark:text-white mb-2">🚆 How-To: Manage Boarding Operations</h3>
|
||||
<div className="space-y-4">
|
||||
<HowToStep number={1} title="Access Coaches">
|
||||
<HowToStep number={1} title="Access Boarding Management">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click "Coaches" in Master Data</li>
|
||||
<li>View all coaches and assignments</li>
|
||||
<li>Click "Boarding" in Enhanced Features</li>
|
||||
<li>Select active trip/schedule for boarding</li>
|
||||
<li>View real-time boarding dashboard</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
<HowToStep number={2} title="Create Coach">
|
||||
<HowToStep number={2} title="Monitor Boarding Process">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click "Add Coach"</li>
|
||||
<li>Enter code, select train, define seat layout</li>
|
||||
<li>Track total passengers expected vs boarded</li>
|
||||
<li>Monitor boarding progress percentage</li>
|
||||
<li>View gate status and any alerts</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
<HowToStep number={3} title="Configure Seats">
|
||||
<HowToStep number={3} title="Handle Boarding Operations">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click coach to edit</li>
|
||||
<li>Add seats and assign classes</li>
|
||||
<li>Validate passenger tickets and documents</li>
|
||||
<li>Resolve seat conflicts or issues</li>
|
||||
<li>Process last-minute passengers and no-shows</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* SEATS */}
|
||||
<div id="seats" className="border-t pt-8">
|
||||
<h2 className="text-2xl font-bold text-slate-900 dark:text-white mb-4">💺 Seats</h2>
|
||||
<p className="text-slate-600 dark:text-slate-300">Manage seat inventory with visual maps.</p>
|
||||
{/* ADVANCED FARE CONFIG */}
|
||||
<div id="fare-config" className="border-t pt-8">
|
||||
<h2 className="text-2xl font-bold text-slate-900 dark:text-white mb-4">📊 Advanced Fare Config</h2>
|
||||
<p className="text-slate-600 dark:text-slate-300">Configure complex fare rules and dynamic pricing strategies with segment-based pricing.</p>
|
||||
</div>
|
||||
|
||||
<div id="seats-how" className="border-t pt-8">
|
||||
<h3 className="text-2xl font-bold text-slate-900 dark:text-white mb-2">💺 How-To: Manage Seats</h3>
|
||||
<div id="fare-config-how" className="border-t pt-8">
|
||||
<h3 className="text-2xl font-bold text-slate-900 dark:text-white mb-2">📊 How-To: Configure Advanced Fares</h3>
|
||||
<div className="space-y-4">
|
||||
<HowToStep number={1} title="View Seat Map">
|
||||
<HowToStep number={1} title="Access Fare Configuration">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Go to "Seats" in Master Data</li>
|
||||
<li>Select coach from dropdown</li>
|
||||
<li>Visual map shows: Green=Available, Red=Blocked</li>
|
||||
<li>Click "Advanced Fare Config" in Enhanced Features</li>
|
||||
<li>Choose between Schedule Fares or Segment Fares</li>
|
||||
<li>View existing fare rules and calculations</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
<HowToStep number={2} title="Block Seat">
|
||||
<HowToStep number={2} title="Create Fare Rules">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click available seat</li>
|
||||
<li>Click "Block" and select reason</li>
|
||||
<li>Set fare amounts for specific schedules or segments</li>
|
||||
<li>Define passenger categories (ADULT/CHILD) and nationalities</li>
|
||||
<li>Configure validity periods and seasonal adjustments</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
<HowToStep number={3} title="Unblock Seat">
|
||||
<HowToStep number={3} title="Manage Dynamic Pricing">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click blocked seat</li>
|
||||
<li>Click "Unblock" to restore</li>
|
||||
<li>Apply route segment-specific pricing</li>
|
||||
<li>Set nationality-based rate variations</li>
|
||||
<li>Monitor fare engine integration and real-time calculations</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* SEAT CLASSES */}
|
||||
<div id="classes" className="border-t pt-8">
|
||||
<h2 className="text-2xl font-bold text-slate-900 dark:text-white mb-4">🎯 Seat Classes</h2>
|
||||
<p className="text-slate-600 dark:text-slate-300">Define seat class types with pricing.</p>
|
||||
{/* PAYMENT METHODS */}
|
||||
<div id="payment-methods" className="border-t pt-8">
|
||||
<h2 className="text-2xl font-bold text-slate-900 dark:text-white mb-4">💳 Payment Methods</h2>
|
||||
<p className="text-slate-600 dark:text-slate-300">Configure and manage payment provider integrations with multi-provider support.</p>
|
||||
</div>
|
||||
|
||||
<div id="classes-how" className="border-t pt-8">
|
||||
<h3 className="text-2xl font-bold text-slate-900 dark:text-white mb-2">🎯 How-To: Manage Seat Classes</h3>
|
||||
<div id="payment-methods-how" className="border-t pt-8">
|
||||
<h3 className="text-2xl font-bold text-slate-900 dark:text-white mb-2">💳 How-To: Configure Payment Methods</h3>
|
||||
<div className="space-y-4">
|
||||
<HowToStep number={1} title="Access Classes">
|
||||
<HowToStep number={1} title="Access Payment Configuration">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click "Seat Classes" in Master Data</li>
|
||||
<li>View all class types</li>
|
||||
<li>Click "Payment Methods" in Enhanced Features</li>
|
||||
<li>View all configured payment providers</li>
|
||||
<li>Check provider status and connectivity</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
<HowToStep number={2} title="Create Class">
|
||||
<HowToStep number={2} title="Configure Providers">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click "Add Class"</li>
|
||||
<li>Enter name, base fare, premium, insurance</li>
|
||||
<li>Set up API credentials (URLs, keys, merchant IDs)</li>
|
||||
<li>Configure transaction fees and limits</li>
|
||||
<li>Enable/disable specific payment methods</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
<HowToStep number={3} title="Update Pricing">
|
||||
<HowToStep number={3} title="Test & Validate">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click class to edit</li>
|
||||
<li>Update fares and save</li>
|
||||
<li>Run test transactions for each provider</li>
|
||||
<li>Validate webhook endpoints and security</li>
|
||||
<li>Monitor API connectivity and error logs</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ROUTES */}
|
||||
<div id="routes" className="border-t pt-8">
|
||||
<h2 className="text-2xl font-bold text-slate-900 dark:text-white mb-4">🛤️ Routes</h2>
|
||||
<p className="text-slate-600 dark:text-slate-300">Define railway routes with ordered stops.</p>
|
||||
</div>
|
||||
|
||||
<div id="routes-how" className="border-t pt-8">
|
||||
<h3 className="text-2xl font-bold text-slate-900 dark:text-white mb-2">🛤️ How-To: Manage Routes</h3>
|
||||
<div className="space-y-4">
|
||||
<HowToStep number={1} title="Access Routes">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click "Routes" in Master Data</li>
|
||||
<li>View all routes and stops</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
<HowToStep number={2} title="Create Route">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click "Add Route"</li>
|
||||
<li>Enter code and description</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
<HowToStep number={3} title="Add Stops">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click route to edit</li>
|
||||
<li>Click "Add Stop" and select station</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* SCHEDULES */}
|
||||
<div id="schedules" className="border-t pt-8">
|
||||
<h2 className="text-2xl font-bold text-slate-900 dark:text-white mb-4">📅 Schedules</h2>
|
||||
<p className="text-slate-600 dark:text-slate-300">Create and manage train schedules.</p>
|
||||
</div>
|
||||
|
||||
<div id="schedules-how" className="border-t pt-8">
|
||||
<h3 className="text-2xl font-bold text-slate-900 dark:text-white mb-2">📅 How-To: Create Schedules</h3>
|
||||
<div className="space-y-4">
|
||||
<HowToStep number={1} title="Create Single">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Go to "Schedules" in Master Data</li>
|
||||
<li>Click "Create Schedule"</li>
|
||||
<li>Fill train, route, departure/arrival times</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
<HowToStep number={2} title="Bulk Generate">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click "Bulk Generate"</li>
|
||||
<li>Set recurring parameters and generate</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
<HowToStep number={3} title="Manage Status">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click schedule to edit</li>
|
||||
<li>Update times and view fares</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* PRICING */}
|
||||
<div id="pricing" className="border-t pt-8">
|
||||
<h2 className="text-2xl font-bold text-slate-900 dark:text-white mb-4">💰 Pricing & Fares</h2>
|
||||
<p className="text-slate-600 dark:text-slate-300">Configure dynamic pricing with segments.</p>
|
||||
</div>
|
||||
|
||||
<div id="pricing-how" className="border-t pt-8">
|
||||
<h3 className="text-2xl font-bold text-slate-900 dark:text-white mb-2">💰 How-To: Configure Pricing</h3>
|
||||
<div className="space-y-4">
|
||||
<HowToStep number={1} title="Access Pricing">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click "Pricing & Fares" in Financial</li>
|
||||
<li>Two tabs: Schedule Fares, Segment Fares</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
<HowToStep number={2} title="Schedule Fares">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click "Add Fare Rule"</li>
|
||||
<li>Fill schedule, seat class, fare, nationality</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
<HowToStep number={3} title="Segment Fares">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Switch to "Segment Fares" tab</li>
|
||||
<li>Select route and add origin/destination fare</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* CURRENCIES */}
|
||||
<div id="currencies" className="border-t pt-8">
|
||||
<h2 className="text-2xl font-bold text-slate-900 dark:text-white mb-4">💵 Currencies</h2>
|
||||
<p className="text-slate-600 dark:text-slate-300">Manage exchange rates for multiple currencies.</p>
|
||||
</div>
|
||||
|
||||
<div id="currencies-how" className="border-t pt-8">
|
||||
<h3 className="text-2xl font-bold text-slate-900 dark:text-white mb-2">💵 How-To: Manage Currencies</h3>
|
||||
<div className="space-y-4">
|
||||
<HowToStep number={1} title="View Rates">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click "Currencies" in Financial</li>
|
||||
<li>View all configured rates</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
<HowToStep number={2} title="Add Rate">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click "Add Rate"</li>
|
||||
<li>Select currency and enter exchange rate</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
<HowToStep number={3} title="Sync Rates">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click rate to edit</li>
|
||||
<li>Click "Sync" to update from provider</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* PAYMENTS */}
|
||||
<div id="payments" className="border-t pt-8">
|
||||
<h2 className="text-2xl font-bold text-slate-900 dark:text-white mb-4">💳 Payments</h2>
|
||||
<p className="text-slate-600 dark:text-slate-300">Monitor and process transactions.</p>
|
||||
</div>
|
||||
|
||||
<div id="payments-how" className="border-t pt-8">
|
||||
<h3 className="text-2xl font-bold text-slate-900 dark:text-white mb-2">💳 How-To: Manage Payments</h3>
|
||||
<div className="space-y-4">
|
||||
<HowToStep number={1} title="View Transactions">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click "Payments" in Financial</li>
|
||||
<li>View all transactions</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
<HowToStep number={2} title="Search & Filter">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Search by booking or transaction ID</li>
|
||||
<li>Filter by status and payment method</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
<HowToStep number={3} title="Process Refunds">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click transaction</li>
|
||||
<li>Click "Refund" if eligible</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* PROMOS */}
|
||||
<div id="promos" className="border-t pt-8">
|
||||
<h2 className="text-2xl font-bold text-slate-900 dark:text-white mb-4">🎁 Promo Codes</h2>
|
||||
<p className="text-slate-600 dark:text-slate-300">Create and manage promotional campaigns.</p>
|
||||
</div>
|
||||
|
||||
<div id="promos-how" className="border-t pt-8">
|
||||
<h3 className="text-2xl font-bold text-slate-900 dark:text-white mb-2">🎁 How-To: Manage Promo Codes</h3>
|
||||
<div className="space-y-4">
|
||||
<HowToStep number={1} title="Access Promos">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click "Promo Codes" in Financial</li>
|
||||
<li>View all active codes</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
<HowToStep number={2} title="Create Code">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click "Add Promo Code"</li>
|
||||
<li>Enter code, discount type, validity dates</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
<HowToStep number={3} title="Track Usage">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click code to view analytics</li>
|
||||
<li>View usage count and savings</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* LOYALTY */}
|
||||
<div id="loyalty" className="border-t pt-8">
|
||||
<h2 className="text-2xl font-bold text-slate-900 dark:text-white mb-4">🏆 Loyalty</h2>
|
||||
<p className="text-slate-600 dark:text-slate-300">Manage loyalty program and rewards.</p>
|
||||
</div>
|
||||
|
||||
<div id="loyalty-how" className="border-t pt-8">
|
||||
<h3 className="text-2xl font-bold text-slate-900 dark:text-white mb-2">🏆 How-To: Manage Loyalty</h3>
|
||||
<div className="space-y-4">
|
||||
<HowToStep number={1} title="View Accounts">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click "Loyalty Program" in Services</li>
|
||||
<li>View all loyalty accounts</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
<HowToStep number={2} title="Adjust Points">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click account</li>
|
||||
<li>Click "Adjust Points" and enter amount</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
<HowToStep number={3} title="Award Rewards">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click account</li>
|
||||
<li>Click "Grant Reward" and select reward</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* SUPPORT */}
|
||||
<div id="support" className="border-t pt-8">
|
||||
<h2 className="text-2xl font-bold text-slate-900 dark:text-white mb-4">💬 Support</h2>
|
||||
<p className="text-slate-600 dark:text-slate-300">Manage support tickets and conversations.</p>
|
||||
</div>
|
||||
|
||||
<div id="support-how" className="border-t pt-8">
|
||||
<h3 className="text-2xl font-bold text-slate-900 dark:text-white mb-2">💬 How-To: Manage Support</h3>
|
||||
<div className="space-y-4">
|
||||
<HowToStep number={1} title="View Tickets">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click "Support Center" in Services</li>
|
||||
<li>View all support tickets</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
<HowToStep number={2} title="Manage Ticket">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click ticket to open conversation</li>
|
||||
<li>Add replies and update status</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
<HowToStep number={3} title="Manage FAQ">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Go to FAQ management</li>
|
||||
<li>Add or edit FAQ articles</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* NOTIFICATIONS */}
|
||||
<div id="notifications" className="border-t pt-8">
|
||||
<h2 className="text-2xl font-bold text-slate-900 dark:text-white mb-4">🔔 Notifications</h2>
|
||||
<p className="text-slate-600 dark:text-slate-300">Send notifications via multiple channels.</p>
|
||||
</div>
|
||||
|
||||
<div id="notifications-how" className="border-t pt-8">
|
||||
<h3 className="text-2xl font-bold text-slate-900 dark:text-white mb-2">🔔 How-To: Manage Notifications</h3>
|
||||
<div className="space-y-4">
|
||||
<HowToStep number={1} title="View Notifications">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click "Notifications" in Services</li>
|
||||
<li>View notification history</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
<HowToStep number={2} title="Send Notification">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click "Send Notification"</li>
|
||||
<li>Select channel and message</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
<HowToStep number={3} title="Manage Templates">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Go to Templates section</li>
|
||||
<li>Create or edit templates with variables</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* AUDIT */}
|
||||
<div id="audit" className="border-t pt-8">
|
||||
<h2 className="text-2xl font-bold text-slate-900 dark:text-white mb-4">📋 Audit Logs</h2>
|
||||
<p className="text-slate-600 dark:text-slate-300">Monitor system activities and user actions.</p>
|
||||
</div>
|
||||
|
||||
<div id="audit-how" className="border-t pt-8">
|
||||
<h3 className="text-2xl font-bold text-slate-900 dark:text-white mb-2">📋 How-To: View Audit Logs</h3>
|
||||
<div className="space-y-4">
|
||||
<HowToStep number={1} title="Access Logs">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click "Audit Logs" in Security</li>
|
||||
<li>View all recorded activities</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
<HowToStep number={2} title="Filter Logs">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Filter by user, action, or date</li>
|
||||
<li>Search by entity ID</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
<HowToStep number={3} title="Export Logs">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click log entry for details</li>
|
||||
<li>Click "Export" to download CSV</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* FRAUD */}
|
||||
<div id="fraud" className="border-t pt-8">
|
||||
<h2 className="text-2xl font-bold text-slate-900 dark:text-white mb-4">🛡️ Fraud Detection</h2>
|
||||
<p className="text-slate-600 dark:text-slate-300">Monitor and manage fraud alerts.</p>
|
||||
</div>
|
||||
|
||||
<div id="fraud-how" className="border-t pt-8">
|
||||
<h3 className="text-2xl font-bold text-slate-900 dark:text-white mb-2">🛡️ How-To: Manage Fraud Detection</h3>
|
||||
<div className="space-y-4">
|
||||
<HowToStep number={1} title="View Alerts">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click "Fraud Detection" in Security</li>
|
||||
<li>View all fraud alerts</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
<HowToStep number={2} title="Investigate">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click alert to view details</li>
|
||||
<li>Review triggered rules and patterns</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
<HowToStep number={3} title="Take Action">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click "Allow" or "Block" with notes</li>
|
||||
<li>Update user status</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* VERIFAYDA */}
|
||||
<div id="verifayda" className="border-t pt-8">
|
||||
<h2 className="text-2xl font-bold text-slate-900 dark:text-white mb-4">✅ Verifayda</h2>
|
||||
<p className="text-slate-600 dark:text-slate-300">Verify passenger identities against government database.</p>
|
||||
</div>
|
||||
|
||||
<div id="verifayda-how" className="border-t pt-8">
|
||||
<h3 className="text-2xl font-bold text-slate-900 dark:text-white mb-2">✅ How-To: Manage Verifayda</h3>
|
||||
<div className="space-y-4">
|
||||
<HowToStep number={1} title="Access Verification">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click "Verifayda Integration" in Security</li>
|
||||
<li>View verification history</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
<HowToStep number={2} title="Verify Passenger">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Enter national ID or passport number</li>
|
||||
<li>Click "Verify" to check database</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
<HowToStep number={3} title="Review Results">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>View verified passenger data</li>
|
||||
<li>Match with booking details</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* REPORTS */}
|
||||
<div id="reports" className="border-t pt-8">
|
||||
<h2 className="text-2xl font-bold text-slate-900 dark:text-white mb-4">📊 Reports</h2>
|
||||
<p className="text-slate-600 dark:text-slate-300">Generate business analytics and reports.</p>
|
||||
</div>
|
||||
|
||||
<div id="reports-how" className="border-t pt-8">
|
||||
<h3 className="text-2xl font-bold text-slate-900 dark:text-white mb-2">📊 How-To: Generate Reports</h3>
|
||||
<div className="space-y-4">
|
||||
<HowToStep number={1} title="Access Reports">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click "Reports" in Analytics</li>
|
||||
<li>View available report types</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
<HowToStep number={2} title="Generate Report">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click report type</li>
|
||||
<li>Select date range and parameters</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
<HowToStep number={3} title="Export Report">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>View report with charts</li>
|
||||
<li>Click "Export" for PDF or CSV</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* AGENTS */}
|
||||
<div id="agents" className="border-t pt-8">
|
||||
<h2 className="text-2xl font-bold text-slate-900 dark:text-white mb-4">👤 Agents</h2>
|
||||
<p className="text-slate-600 dark:text-slate-300">Manage booking agents and commissions.</p>
|
||||
</div>
|
||||
|
||||
<div id="agents-how" className="border-t pt-8">
|
||||
<h3 className="text-2xl font-bold text-slate-900 dark:text-white mb-2">👤 How-To: Manage Agents</h3>
|
||||
<div className="space-y-4">
|
||||
<HowToStep number={1} title="View Agents">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click "Agents" in System</li>
|
||||
<li>View all agents</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
<HowToStep number={2} title="Create Agent">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click "Add Agent"</li>
|
||||
<li>Enter name, email, commission rate</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
<HowToStep number={3} title="Create Shift">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click agent to edit</li>
|
||||
<li>Click "Create Shift" to assign schedule</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* USERS */}
|
||||
<div id="users" className="border-t pt-8">
|
||||
<h2 className="text-2xl font-bold text-slate-900 dark:text-white mb-4">👥 Users</h2>
|
||||
<p className="text-slate-600 dark:text-slate-300">Manage backoffice user accounts and permissions.</p>
|
||||
</div>
|
||||
|
||||
<div id="users-how" className="border-t pt-8">
|
||||
<h3 className="text-2xl font-bold text-slate-900 dark:text-white mb-2">👥 How-To: Manage Users</h3>
|
||||
<div className="space-y-4">
|
||||
<HowToStep number={1} title="View Users">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click "Users" in System</li>
|
||||
<li>View all user accounts</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
<HowToStep number={2} title="Create User">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click "Add User"</li>
|
||||
<li>Enter email, name, select role</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
<HowToStep number={3} title="Manage Permissions">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click user to edit</li>
|
||||
<li>Adjust roles and permissions</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* SETTINGS */}
|
||||
<div id="settings" className="border-t pt-8">
|
||||
<h2 className="text-2xl font-bold text-slate-900 dark:text-white mb-4">⚙️ Settings</h2>
|
||||
<p className="text-slate-600 dark:text-slate-300">Configure system-wide settings and integrations.</p>
|
||||
</div>
|
||||
|
||||
<div id="settings-how" className="border-t pt-8">
|
||||
<h3 className="text-2xl font-bold text-slate-900 dark:text-white mb-2">⚙️ How-To: Configure Settings</h3>
|
||||
<div className="space-y-4">
|
||||
<HowToStep number={1} title="Access Settings">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Click "Settings" in System</li>
|
||||
<li>View configuration options</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
<HowToStep number={2} title="Configure Email">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Go to Email tab</li>
|
||||
<li>Enter SendGrid API key and email</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
<HowToStep number={3} title="Configure API Keys">
|
||||
<ol className="list-decimal pl-5 space-y-1 text-sm text-slate-700 dark:text-slate-300">
|
||||
<li>Go to API tab</li>
|
||||
<li>Add payment and Verifayda keys</li>
|
||||
</ol>
|
||||
</HowToStep>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -939,11 +547,11 @@ const DocPage = () => {
|
||||
|
||||
<div className="mt-12 bg-slate-900 text-white py-8">
|
||||
<div className="max-w-7xl mx-auto px-4 text-center text-slate-400">
|
||||
<p>© 2026 Ethio-Djibouti Railway | Passenger Backoffice Documentation v1.0</p>
|
||||
<p>© 2026 Ethio-Djibouti Railway | Passenger Backoffice Documentation v1.0.0</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default DocPage;
|
||||
export default DocPage;
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { RefreshCw, Send } from 'lucide-react';
|
||||
import { RefreshCw, Send, Trash2 } from 'lucide-react';
|
||||
import DataTable from '@/components/ui/DataTable';
|
||||
import Badge from '@/components/ui/Badge';
|
||||
import ActionButton from '@/components/ui/ActionButton';
|
||||
@@ -54,6 +54,11 @@ export default function ExcessBaggagePage() {
|
||||
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['excess-baggage'] }),
|
||||
});
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (id: string) => excessBaggageApi.delete(id),
|
||||
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['excess-baggage'] }),
|
||||
});
|
||||
|
||||
const columns = [
|
||||
{
|
||||
key: 'booking', label: 'Booking',
|
||||
@@ -120,14 +125,25 @@ export default function ExcessBaggagePage() {
|
||||
onClick: (c: any) => { setWaiveModal(c); setWaiveReason(''); setWaiveError(null); },
|
||||
show: (c: any) => !['PAID', 'CASH_COLLECTED', 'WAIVED'].includes(c.status),
|
||||
},
|
||||
{
|
||||
label: 'Delete',
|
||||
icon: Trash2,
|
||||
variant: 'danger' as const,
|
||||
onClick: (c: any) => {
|
||||
if (confirm('Are you sure you want to delete this charge?')) {
|
||||
deleteMutation.mutate(c.id);
|
||||
}
|
||||
},
|
||||
show: (c: any) => ['EXPIRED', 'WAIVED'].includes(c.status),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-foreground">Excess Baggage</h1>
|
||||
<p className="text-muted-foreground">Track and manage excess baggage charges at boarding</p>
|
||||
<h1 className="text-2xl font-bold text-foreground">Excess Lugagge</h1>
|
||||
<p className="text-muted-foreground">Track and manage excess luggage charges at boarding</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import Sidebar from '@/components/layout/Sidebar';
|
||||
import Header from '@/components/layout/Header';
|
||||
import { useAuthStore } from '@/lib/auth-store';
|
||||
|
||||
export default function FareManagementLayout({ children }: { children: React.ReactNode }) {
|
||||
const router = useRouter();
|
||||
const { isAuthenticated } = useAuthStore();
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => {
|
||||
setIsLoading(false);
|
||||
}, 100);
|
||||
|
||||
return () => clearTimeout(timer);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isLoading && !isAuthenticated) {
|
||||
router.push('/login');
|
||||
}
|
||||
}, [isAuthenticated, router, isLoading]);
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex h-screen items-center justify-center bg-gray-50 dark:bg-slate-950">
|
||||
<div className="text-center">
|
||||
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-edr-green-600 mx-auto"></div>
|
||||
<p className="mt-4 text-gray-600 dark:text-gray-400">Loading...</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!isAuthenticated) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-screen overflow-hidden bg-gray-50 dark:bg-slate-950">
|
||||
<Sidebar />
|
||||
<div className="flex flex-1 flex-col overflow-hidden">
|
||||
<Header />
|
||||
<main className="flex-1 overflow-y-auto bg-gray-50 dark:bg-slate-950 p-6">
|
||||
{children}
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,535 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { Plus, Settings, Play, Square, Trash2, TestTube, History, Download } from 'lucide-react';
|
||||
import DataTable from '@/components/ui/DataTable';
|
||||
import Badge from '@/components/ui/Badge';
|
||||
import ActionButton from '@/components/ui/ActionButton';
|
||||
import Modal from '@/components/ui/Modal';
|
||||
import ConfirmDialog from '@/components/ui/ConfirmDialog';
|
||||
import { apiClient } from '@/lib/api-client';
|
||||
|
||||
interface FareConfiguration {
|
||||
id: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
effective_date: string;
|
||||
expiry_date?: string;
|
||||
is_active: boolean;
|
||||
is_default: boolean;
|
||||
created_by?: string;
|
||||
approved_by?: string;
|
||||
approved_at?: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
rate_rules_count: number;
|
||||
components_count: number;
|
||||
age_rules_count: number;
|
||||
}
|
||||
|
||||
interface SystemStatus {
|
||||
configurableFaresEnabled: boolean;
|
||||
rolloutPercentage: number;
|
||||
totalConfigurations: number;
|
||||
activeConfiguration: string | null;
|
||||
activeConfigurationName: string | null;
|
||||
systemReady: boolean;
|
||||
}
|
||||
|
||||
interface FareTestResult {
|
||||
baseFareMinor: number;
|
||||
componentsTotal: number;
|
||||
finalTotalMinor: number;
|
||||
breakdown?: Array<{
|
||||
description: string;
|
||||
runningTotal: number;
|
||||
}>;
|
||||
}
|
||||
|
||||
export default function ConfigurableFarePage() {
|
||||
const [showCreateModal, setShowCreateModal] = useState(false);
|
||||
const [showTestModal, setShowTestModal] = useState(false);
|
||||
const [selectedConfig, setSelectedConfig] = useState<FareConfiguration | null>(null);
|
||||
const [deleteConfirm, setDeleteConfirm] = useState<{ isOpen: boolean; config: FareConfiguration | null }>({ isOpen: false, config: null });
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
// Queries
|
||||
const { data: configurations = [], isLoading: configsLoading } = useQuery<FareConfiguration[]>({
|
||||
queryKey: ['fare-configurations'],
|
||||
queryFn: () => apiClient.get('/admin/fare-configurations'),
|
||||
});
|
||||
|
||||
const { data: systemStatus } = useQuery<SystemStatus>({
|
||||
queryKey: ['fare-system-status'],
|
||||
queryFn: () => apiClient.get('/admin/fare-migration/status'),
|
||||
});
|
||||
|
||||
// Mutations
|
||||
const activateMutation = useMutation({
|
||||
mutationFn: (id: string) => apiClient.post(`/admin/fare-configurations/${id}/activate`),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['fare-configurations'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['fare-system-status'] });
|
||||
},
|
||||
});
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (id: string) => apiClient.delete(`/admin/fare-configurations/${id}`),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['fare-configurations'] });
|
||||
setDeleteConfirm({ isOpen: false, config: null });
|
||||
},
|
||||
});
|
||||
|
||||
const toggleSystemMutation = useMutation({
|
||||
mutationFn: (enabled: boolean) =>
|
||||
enabled
|
||||
? apiClient.post('/admin/fare-configurations/system/enable-configurable-fares', { rolloutPercentage: 100 })
|
||||
: apiClient.post('/admin/fare-configurations/system/disable-configurable-fares'),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['fare-system-status'] });
|
||||
},
|
||||
});
|
||||
|
||||
const setupSystemMutation = useMutation({
|
||||
mutationFn: () => apiClient.post('/admin/fare-migration/complete-setup', {
|
||||
activateNewFormula: true,
|
||||
enableFeature: true
|
||||
}),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['fare-configurations'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['fare-system-status'] });
|
||||
},
|
||||
});
|
||||
|
||||
const handleActivate = async (config: FareConfiguration) => {
|
||||
await activateMutation.mutateAsync(config.id);
|
||||
};
|
||||
|
||||
const handleDelete = (config: FareConfiguration) => {
|
||||
setDeleteConfirm({ isOpen: true, config });
|
||||
};
|
||||
|
||||
const confirmDelete = async () => {
|
||||
if (deleteConfirm.config) {
|
||||
await deleteMutation.mutateAsync(deleteConfirm.config.id);
|
||||
}
|
||||
};
|
||||
|
||||
const handleTest = (config: FareConfiguration) => {
|
||||
setSelectedConfig(config);
|
||||
setShowTestModal(true);
|
||||
};
|
||||
|
||||
const columns = [
|
||||
{
|
||||
key: 'name',
|
||||
label: 'Configuration Name',
|
||||
sortable: true,
|
||||
render: (config: FareConfiguration) => (
|
||||
<div>
|
||||
<div className="font-medium">{config.name}</div>
|
||||
{config.description && (
|
||||
<div className="text-sm text-muted-foreground">{config.description}</div>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'status',
|
||||
label: 'Status',
|
||||
render: (config: FareConfiguration) => (
|
||||
<div className="space-y-1">
|
||||
<Badge variant="status" status={config.is_active ? 'CONFIRMED' : 'PENDING'}>
|
||||
{config.is_active ? 'Active' : 'Inactive'}
|
||||
</Badge>
|
||||
{config.is_default && (
|
||||
<Badge variant="status" status="INFO">Default</Badge>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'rules',
|
||||
label: 'Rules Count',
|
||||
render: (config: FareConfiguration) => (
|
||||
<div className="text-sm">
|
||||
<div>{config.rate_rules_count} rate rules</div>
|
||||
<div>{config.components_count} components</div>
|
||||
<div>{config.age_rules_count} age rules</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'dates',
|
||||
label: 'Validity Period',
|
||||
render: (config: FareConfiguration) => (
|
||||
<div className="text-sm">
|
||||
<div>From: {new Date(config.effective_date).toLocaleDateString()}</div>
|
||||
{config.expiry_date && (
|
||||
<div>Until: {new Date(config.expiry_date).toLocaleDateString()}</div>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'created_at',
|
||||
label: 'Created',
|
||||
sortable: true,
|
||||
render: (config: FareConfiguration) => (
|
||||
<div className="text-sm">
|
||||
<div>{new Date(config.created_at).toLocaleDateString()}</div>
|
||||
{config.created_by && (
|
||||
<div className="text-muted-foreground">by {config.created_by}</div>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
const actions = [
|
||||
{
|
||||
label: 'Activate',
|
||||
onClick: handleActivate,
|
||||
variant: 'secondary' as const,
|
||||
icon: Play,
|
||||
show: (config: FareConfiguration) => !config.is_active,
|
||||
},
|
||||
{
|
||||
label: 'Test',
|
||||
onClick: handleTest,
|
||||
variant: 'secondary' as const,
|
||||
icon: TestTube,
|
||||
},
|
||||
{
|
||||
label: 'Delete',
|
||||
onClick: handleDelete,
|
||||
variant: 'danger' as const,
|
||||
icon: Trash2,
|
||||
show: (config: FareConfiguration) => !config.is_active,
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-foreground">Configurable Fare Management</h1>
|
||||
<p className="text-muted-foreground mt-1">
|
||||
Manage dynamic fare configurations with flexible rules, components, and pricing
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<ActionButton
|
||||
icon={Settings}
|
||||
variant="secondary"
|
||||
onClick={() => setupSystemMutation.mutate()}
|
||||
loading={setupSystemMutation.isPending}
|
||||
disabled={systemStatus?.systemReady}
|
||||
>
|
||||
{systemStatus?.systemReady ? 'System Ready' : 'Setup System'}
|
||||
</ActionButton>
|
||||
<ActionButton
|
||||
icon={Plus}
|
||||
onClick={() => setShowCreateModal(true)}
|
||||
>
|
||||
New Configuration
|
||||
</ActionButton>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* System Status */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-4 gap-4">
|
||||
<div className="card">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<div className="text-sm text-muted-foreground">System Status</div>
|
||||
<div className={`font-semibold ${systemStatus?.systemReady ? 'text-green-600' : 'text-yellow-600'}`}>
|
||||
{systemStatus?.systemReady ? 'Ready' : 'Setup Required'}
|
||||
</div>
|
||||
</div>
|
||||
<Badge variant="status" status={systemStatus?.configurableFaresEnabled ? 'CONFIRMED' : 'CANCELLED'}>
|
||||
{systemStatus?.configurableFaresEnabled ? 'Enabled' : 'Disabled'}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="card">
|
||||
<div className="text-sm text-muted-foreground">Total Configurations</div>
|
||||
<div className="text-2xl font-bold">{systemStatus?.totalConfigurations || 0}</div>
|
||||
</div>
|
||||
|
||||
<div className="card">
|
||||
<div className="text-sm text-muted-foreground">Rollout Percentage</div>
|
||||
<div className="text-2xl font-bold">{systemStatus?.rolloutPercentage || 0}%</div>
|
||||
</div>
|
||||
|
||||
<div className="card">
|
||||
<div className="text-sm text-muted-foreground">Active Configuration</div>
|
||||
<div className="font-medium">
|
||||
{systemStatus?.activeConfigurationName || 'None'}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* System Controls */}
|
||||
<div className="card">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h3 className="font-semibold">System Control</h3>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
Enable or disable the configurable fare system globally
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-4">
|
||||
<span className="text-sm">
|
||||
{systemStatus?.configurableFaresEnabled ? 'System Enabled' : 'Using Legacy System'}
|
||||
</span>
|
||||
<ActionButton
|
||||
variant={systemStatus?.configurableFaresEnabled ? 'danger' : 'secondary'}
|
||||
onClick={() => toggleSystemMutation.mutate(!systemStatus?.configurableFaresEnabled)}
|
||||
loading={toggleSystemMutation.isPending}
|
||||
icon={systemStatus?.configurableFaresEnabled ? Square : Play}
|
||||
>
|
||||
{systemStatus?.configurableFaresEnabled ? 'Disable' : 'Enable'}
|
||||
</ActionButton>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Configurations Table */}
|
||||
<div className="card">
|
||||
<div className="mb-6">
|
||||
<h3 className="text-lg font-semibold">Fare Configurations</h3>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
Manage fare calculation configurations with custom rates, components, and age-based pricing
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<DataTable
|
||||
data={configurations}
|
||||
columns={columns}
|
||||
actions={actions}
|
||||
loading={configsLoading}
|
||||
emptyMessage="No fare configurations found. Create your first configuration to get started."
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Delete Confirmation */}
|
||||
<ConfirmDialog
|
||||
isOpen={deleteConfirm.isOpen}
|
||||
onClose={() => setDeleteConfirm({ isOpen: false, config: null })}
|
||||
onConfirm={confirmDelete}
|
||||
title="Delete Configuration"
|
||||
message={`Are you sure you want to delete "${deleteConfirm.config?.name}"? This action cannot be undone.`}
|
||||
confirmText="Delete"
|
||||
isDanger={true}
|
||||
isLoading={deleteMutation.isPending}
|
||||
warning="Active configurations cannot be deleted. Deactivate first if needed."
|
||||
/>
|
||||
|
||||
{/* Test Modal */}
|
||||
{showTestModal && selectedConfig && (
|
||||
<FareTestModal
|
||||
configuration={selectedConfig}
|
||||
isOpen={showTestModal}
|
||||
onClose={() => {
|
||||
setShowTestModal(false);
|
||||
setSelectedConfig(null);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Create/Edit Modal */}
|
||||
{showCreateModal && (
|
||||
<ConfigurationFormModal
|
||||
isOpen={showCreateModal}
|
||||
onClose={() => setShowCreateModal(false)}
|
||||
onSuccess={() => {
|
||||
setShowCreateModal(false);
|
||||
queryClient.invalidateQueries({ queryKey: ['fare-configurations'] });
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Test Modal Component
|
||||
function FareTestModal({
|
||||
configuration,
|
||||
isOpen,
|
||||
onClose
|
||||
}: {
|
||||
configuration: FareConfiguration;
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const [testData, setTestData] = useState({
|
||||
distanceKm: 100,
|
||||
nationality: 'Ethiopian',
|
||||
coachType: 'REGULAR_SEAT',
|
||||
bedPosition: '',
|
||||
adultCount: 2,
|
||||
childCount: 1,
|
||||
});
|
||||
|
||||
const testMutation = useMutation<FareTestResult>({
|
||||
mutationFn: () => apiClient.post(`/admin/fare-configurations/${configuration.id}/test`, testData),
|
||||
});
|
||||
|
||||
const handleTest = () => {
|
||||
testMutation.mutate();
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal isOpen={isOpen} onClose={onClose} title={`Test Configuration: ${configuration.name}`} size="lg">
|
||||
<div className="space-y-4">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="label">Distance (km) *</label>
|
||||
<input
|
||||
type="number"
|
||||
className="input"
|
||||
value={testData.distanceKm}
|
||||
onChange={(e) => setTestData({ ...testData, distanceKm: +e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Nationality *</label>
|
||||
<select
|
||||
className="input"
|
||||
value={testData.nationality}
|
||||
onChange={(e) => setTestData({ ...testData, nationality: e.target.value })}
|
||||
>
|
||||
<option value="Ethiopian">Ethiopian</option>
|
||||
<option value="Djiboutian">Djiboutian</option>
|
||||
<option value="Other">International</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Coach Type *</label>
|
||||
<select
|
||||
className="input"
|
||||
value={testData.coachType}
|
||||
onChange={(e) => setTestData({ ...testData, coachType: e.target.value })}
|
||||
>
|
||||
<option value="REGULAR_SEAT">Regular Seat</option>
|
||||
<option value="ECONOMY_BED">Economy Bed</option>
|
||||
<option value="VIP_BED">VIP Bed</option>
|
||||
</select>
|
||||
</div>
|
||||
{(testData.coachType === 'ECONOMY_BED' || testData.coachType === 'VIP_BED') && (
|
||||
<div>
|
||||
<label className="label">Bed Position</label>
|
||||
<select
|
||||
className="input"
|
||||
value={testData.bedPosition}
|
||||
onChange={(e) => setTestData({ ...testData, bedPosition: e.target.value })}
|
||||
>
|
||||
<option value="">Select position</option>
|
||||
<option value="UPPER">Upper</option>
|
||||
<option value="MIDDLE">Middle</option>
|
||||
<option value="LOWER">Lower</option>
|
||||
</select>
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<label className="label">Adults *</label>
|
||||
<input
|
||||
type="number"
|
||||
min="1"
|
||||
className="input"
|
||||
value={testData.adultCount}
|
||||
onChange={(e) => setTestData({ ...testData, adultCount: +e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Children</label>
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
className="input"
|
||||
value={testData.childCount}
|
||||
onChange={(e) => setTestData({ ...testData, childCount: +e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ActionButton
|
||||
onClick={handleTest}
|
||||
loading={testMutation.isPending}
|
||||
className="w-full"
|
||||
>
|
||||
Calculate Fare
|
||||
</ActionButton>
|
||||
|
||||
{testMutation.data && (
|
||||
<div className="mt-6 p-4 bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-lg">
|
||||
<h4 className="font-semibold text-green-900 dark:text-green-200 mb-3">Calculation Result</h4>
|
||||
<div className="space-y-2 text-sm">
|
||||
<div className="flex justify-between">
|
||||
<span>Base Fare:</span>
|
||||
<span className="font-mono">{(testMutation.data.baseFareMinor / 100).toFixed(2)} ETB</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span>Components:</span>
|
||||
<span className="font-mono">{(testMutation.data.componentsTotal / 100).toFixed(2)} ETB</span>
|
||||
</div>
|
||||
<div className="flex justify-between font-semibold border-t pt-2">
|
||||
<span>Total:</span>
|
||||
<span className="font-mono">{(testMutation.data.finalTotalMinor / 100).toFixed(2)} ETB</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{testMutation.data.breakdown && (
|
||||
<div className="mt-4">
|
||||
<h5 className="font-medium mb-2">Calculation Breakdown:</h5>
|
||||
<div className="space-y-1 text-xs">
|
||||
{testMutation.data.breakdown.map((step: any, index: number) => (
|
||||
<div key={index} className="flex justify-between">
|
||||
<span>{step.description}</span>
|
||||
<span className="font-mono">{(step.runningTotal / 100).toFixed(2)} ETB</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{testMutation.error && (
|
||||
<div className="p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg text-red-800 dark:text-red-200 text-sm">
|
||||
{(testMutation.error as any)?.response?.data?.message || 'Test failed'}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
// Create Configuration Form Modal
|
||||
function ConfigurationFormModal({
|
||||
isOpen,
|
||||
onClose,
|
||||
onSuccess
|
||||
}: {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
onSuccess: () => void;
|
||||
}) {
|
||||
return (
|
||||
<Modal isOpen={isOpen} onClose={onClose} title="Create Configuration" size="xl">
|
||||
<div className="p-8 text-center">
|
||||
<h3 className="text-lg font-semibold mb-2">Configuration Form</h3>
|
||||
<p className="text-muted-foreground mb-4">
|
||||
This would contain a comprehensive form for creating fare configurations with rate rules, components, and age pricing.
|
||||
</p>
|
||||
<ActionButton onClick={onSuccess} variant="secondary">
|
||||
Close for Now
|
||||
</ActionButton>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -143,17 +143,9 @@ export default function LoginPage() {
|
||||
|
||||
{/* Password field */}
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<label className="block text-xs font-semibold text-gray-600 dark:text-gray-400 uppercase tracking-wider">
|
||||
Password
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
className="text-xs text-[rgb(20,113,76)] hover:text-[rgb(16,90,61)] font-medium transition-colors"
|
||||
>
|
||||
Forgot password?
|
||||
</button>
|
||||
</div>
|
||||
<label className="block text-xs font-semibold text-gray-600 dark:text-gray-400 uppercase tracking-wider mb-2">
|
||||
Password
|
||||
</label>
|
||||
<div className={`relative rounded-xl transition-all duration-200 ${
|
||||
passwordFocused
|
||||
? 'ring-2 ring-[rgb(20,113,76)] ring-offset-0'
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import Sidebar from '@/components/layout/Sidebar';
|
||||
import Header from '@/components/layout/Header';
|
||||
import { useAuthStore } from '@/lib/auth-store';
|
||||
import { useTheme } from '@/lib/theme-store';
|
||||
import type { Metadata } from 'next';
|
||||
|
||||
export default function PaymentMethodsLayout({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const { isAuthenticated, user } = useAuthStore();
|
||||
const { setTheme } = useTheme();
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
// Auth is already initialized in root providers
|
||||
// Just wait a tick for hydration
|
||||
const timer = setTimeout(() => {
|
||||
setIsLoading(false);
|
||||
}, 100);
|
||||
|
||||
return () => clearTimeout(timer);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isLoading && !isAuthenticated) {
|
||||
router.push('/login');
|
||||
}
|
||||
}, [isAuthenticated, router, isLoading]);
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex h-screen items-center justify-center bg-gray-50 dark:bg-slate-950">
|
||||
<div className="text-center">
|
||||
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-edr-green-600 mx-auto"></div>
|
||||
<p className="mt-4 text-gray-600 dark:text-gray-400">Loading...</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!isAuthenticated) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-screen overflow-hidden bg-gray-50 dark:bg-slate-950">
|
||||
<Sidebar />
|
||||
<div className="flex flex-1 flex-col overflow-hidden">
|
||||
<Header />
|
||||
<main className="flex-1 overflow-y-auto bg-gray-50 dark:bg-slate-950 p-6">
|
||||
{children}
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,421 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { Plus, Edit2, Trash2 } from 'lucide-react';
|
||||
import DataTable from '@/components/ui/DataTable';
|
||||
import Badge from '@/components/ui/Badge';
|
||||
import ActionButton from '@/components/ui/ActionButton';
|
||||
import Modal from '@/components/ui/Modal';
|
||||
import ConfirmDialog from '@/components/ui/ConfirmDialog';
|
||||
import { apiClient, paymentsApi } from '@/lib/api';
|
||||
import { PermissionGuard } from '@/components/layout/PermissionGuard';
|
||||
import { usePermission } from '@/lib/use-permission';
|
||||
import { PERMS } from '@/lib/permissions';
|
||||
|
||||
export default function PaymentMethodsPage() {
|
||||
const canManagePayments = usePermission(PERMS.payments.manage);
|
||||
const canManageAdmin = usePermission(PERMS.admin);
|
||||
const canManage = canManagePayments || canManageAdmin;
|
||||
const [createModalOpen, setCreateModalOpen] = useState(false);
|
||||
const [editModalOpen, setEditModalOpen] = useState(false);
|
||||
const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
|
||||
const [selectedMethod, setSelectedMethod] = useState<any>(null);
|
||||
const [successMessage, setSuccessMessage] = useState('');
|
||||
const [formData, setFormData] = useState({
|
||||
name: '',
|
||||
type: 'TELEBIRR',
|
||||
region: 'ETHIOPIA',
|
||||
currency: 'ETB',
|
||||
isEnabled: true,
|
||||
displayOrder: 1,
|
||||
description: '',
|
||||
fees: '',
|
||||
processingTime: ''
|
||||
});
|
||||
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const { data, isLoading, error } = useQuery({
|
||||
queryKey: ['payment-methods'],
|
||||
queryFn: () => paymentsApi.getMethods(),
|
||||
});
|
||||
|
||||
const createMutation = useMutation({
|
||||
mutationFn: (data: any) => paymentsApi.addMethod(data),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['payment-methods'] });
|
||||
setCreateModalOpen(false);
|
||||
resetForm();
|
||||
setSuccessMessage('Payment method added successfully');
|
||||
setTimeout(() => setSuccessMessage(''), 3000);
|
||||
},
|
||||
});
|
||||
|
||||
const updateMutation = useMutation({
|
||||
mutationFn: ({ id, ...data }: any) => paymentsApi.updateMethod(id, data),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['payment-methods'] });
|
||||
queryClient.refetchQueries({ queryKey: ['payment-methods'] });
|
||||
setEditModalOpen(false);
|
||||
setSelectedMethod(null);
|
||||
resetForm();
|
||||
setSuccessMessage('Payment method updated successfully');
|
||||
setTimeout(() => setSuccessMessage(''), 3000);
|
||||
},
|
||||
onError: (error) => {
|
||||
console.error('Update failed:', error);
|
||||
setSuccessMessage('Failed to update payment method');
|
||||
setTimeout(() => setSuccessMessage(''), 3000);
|
||||
},
|
||||
});
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (id: string) => paymentsApi.deleteMethod(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['payment-methods'] });
|
||||
setDeleteConfirmOpen(false);
|
||||
setSelectedMethod(null);
|
||||
setSuccessMessage('Payment method deleted successfully');
|
||||
setTimeout(() => setSuccessMessage(''), 3000);
|
||||
},
|
||||
});
|
||||
|
||||
const resetForm = () => {
|
||||
setFormData({
|
||||
name: '',
|
||||
type: 'TELEBIRR',
|
||||
region: 'ETHIOPIA',
|
||||
currency: 'ETB',
|
||||
isEnabled: true,
|
||||
displayOrder: 1,
|
||||
description: '',
|
||||
fees: '',
|
||||
processingTime: ''
|
||||
});
|
||||
};
|
||||
|
||||
const handleEdit = (method: any) => {
|
||||
setSelectedMethod(method);
|
||||
setFormData({
|
||||
name: method.displayName || method.name || '',
|
||||
type: method.type || 'TELEBIRR',
|
||||
region: method.region || 'ETHIOPIA',
|
||||
currency: method.currency || 'ETB',
|
||||
isEnabled: method.enabled ?? method.isEnabled ?? true,
|
||||
displayOrder: method.sortOrder ?? method.displayOrder ?? 1,
|
||||
description: method.description || '',
|
||||
fees: method.fees || '',
|
||||
processingTime: method.processingTime || ''
|
||||
});
|
||||
setEditModalOpen(true);
|
||||
};
|
||||
|
||||
const handleDelete = (method: any) => {
|
||||
setSelectedMethod(method);
|
||||
setDeleteConfirmOpen(true);
|
||||
};
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
const submitData = {
|
||||
displayName: formData.name,
|
||||
type: formData.type,
|
||||
region: formData.region,
|
||||
currency: formData.currency,
|
||||
enabled: formData.isEnabled,
|
||||
sortOrder: formData.displayOrder,
|
||||
// Additional fields that might be expected
|
||||
description: formData.description,
|
||||
fees: formData.fees,
|
||||
processingTime: formData.processingTime,
|
||||
};
|
||||
|
||||
console.log('Submitting data:', submitData);
|
||||
|
||||
if (selectedMethod) {
|
||||
updateMutation.mutate({ id: selectedMethod.id, ...submitData });
|
||||
} else {
|
||||
createMutation.mutate(submitData);
|
||||
}
|
||||
};
|
||||
|
||||
const columns = [
|
||||
{
|
||||
key: 'displayName',
|
||||
label: 'Name',
|
||||
sortable: true,
|
||||
render: (method: any) => (
|
||||
<div>
|
||||
<div className="font-semibold">{method.displayName || method.name}</div>
|
||||
<div className="text-sm text-muted-foreground">{method.type}</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'region',
|
||||
label: 'Region',
|
||||
render: (method: any) => (
|
||||
<Badge>{method.region}</Badge>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'currency',
|
||||
label: 'Currency',
|
||||
render: (method: any) => (
|
||||
<span className="font-mono text-sm">{method.currency}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'enabled',
|
||||
label: 'Status',
|
||||
render: (method: any) => (
|
||||
<Badge variant="status" status={(method.enabled ?? method.isEnabled) ? 'CONFIRMED' : 'CANCELLED'}>
|
||||
{(method.enabled ?? method.isEnabled) ? 'Enabled' : 'Disabled'}
|
||||
</Badge>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'sortOrder',
|
||||
label: 'Order',
|
||||
render: (method: any) => (
|
||||
<span className="text-sm">{method.sortOrder ?? method.displayOrder}</span>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
const actions = [
|
||||
{
|
||||
label: 'Edit',
|
||||
onClick: handleEdit,
|
||||
variant: 'secondary' as const,
|
||||
icon: Edit2,
|
||||
show: () => canManage,
|
||||
},
|
||||
{
|
||||
label: 'Delete',
|
||||
onClick: handleDelete,
|
||||
variant: 'danger' as const,
|
||||
icon: Trash2,
|
||||
show: () => canManage,
|
||||
},
|
||||
];
|
||||
|
||||
const paymentTypes = [
|
||||
{ value: 'TELEBIRR', label: 'Telebirr' },
|
||||
{ value: 'CBE_BIRR', label: 'CBE Birr' },
|
||||
{ value: 'EBIRR', label: 'eBirr' },
|
||||
{ value: 'WAAFI', label: 'Waafi' },
|
||||
{ value: 'CARD', label: 'Card Payment' },
|
||||
{ value: 'WALLET', label: 'Internal Wallet' },
|
||||
];
|
||||
|
||||
const regions = [
|
||||
{ value: 'ETHIOPIA', label: 'Ethiopia' },
|
||||
{ value: 'DJIBOUTI', label: 'Djibouti' },
|
||||
{ value: 'INTERNATIONAL', label: 'International' },
|
||||
];
|
||||
|
||||
const currencies = [
|
||||
{ value: 'ETB', label: 'Ethiopian Birr (ETB)' },
|
||||
{ value: 'DJF', label: 'Djiboutian Franc (DJF)' },
|
||||
{ value: 'USD', label: 'US Dollar (USD)' },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-foreground">Payment Methods</h1>
|
||||
<p className="text-muted-foreground">Manage supported payment systems</p>
|
||||
</div>
|
||||
<PermissionGuard permission={PERMS.admin}>
|
||||
<ActionButton icon={Plus} onClick={() => setCreateModalOpen(true)}>
|
||||
Add Method
|
||||
</ActionButton>
|
||||
</PermissionGuard>
|
||||
</div>
|
||||
|
||||
{successMessage && (
|
||||
<div className="rounded-lg bg-green-50 dark:bg-green-900/20 p-4 text-sm text-green-800 dark:text-green-200">
|
||||
✓ {successMessage}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div className="rounded-lg bg-red-50 dark:bg-red-900/20 p-4 text-sm text-red-800 dark:text-red-200">
|
||||
Error loading payment methods: {error instanceof Error ? error.message : 'Unknown error'}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<DataTable
|
||||
data={data || []}
|
||||
columns={columns}
|
||||
actions={actions}
|
||||
loading={isLoading}
|
||||
emptyMessage="No payment methods found"
|
||||
/>
|
||||
|
||||
<Modal
|
||||
isOpen={createModalOpen || editModalOpen}
|
||||
onClose={() => {
|
||||
setCreateModalOpen(false);
|
||||
setEditModalOpen(false);
|
||||
setSelectedMethod(null);
|
||||
resetForm();
|
||||
}}
|
||||
title={selectedMethod ? 'Edit Payment Method' : 'Add Payment Method'}
|
||||
size="md"
|
||||
>
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="label">Name *</label>
|
||||
<input
|
||||
type="text"
|
||||
className="input"
|
||||
value={formData.name}
|
||||
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
|
||||
placeholder="e.g., Telebirr Mobile Money"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Type *</label>
|
||||
<select
|
||||
className="input"
|
||||
value={formData.type}
|
||||
onChange={(e) => setFormData({ ...formData, type: e.target.value })}
|
||||
required
|
||||
>
|
||||
{paymentTypes.map((type) => (
|
||||
<option key={type.value} value={type.value}>{type.label}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
<div>
|
||||
<label className="label">Region *</label>
|
||||
<select
|
||||
className="input"
|
||||
value={formData.region}
|
||||
onChange={(e) => setFormData({ ...formData, region: e.target.value })}
|
||||
required
|
||||
>
|
||||
{regions.map((region) => (
|
||||
<option key={region.value} value={region.value}>{region.label}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Currency *</label>
|
||||
<select
|
||||
className="input"
|
||||
value={formData.currency}
|
||||
onChange={(e) => setFormData({ ...formData, currency: e.target.value })}
|
||||
required
|
||||
>
|
||||
{currencies.map((currency) => (
|
||||
<option key={currency.value} value={currency.value}>{currency.label}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Display Order</label>
|
||||
<input
|
||||
type="number"
|
||||
className="input"
|
||||
value={formData.displayOrder}
|
||||
onChange={(e) => setFormData({ ...formData, displayOrder: parseInt(e.target.value) || 1 })}
|
||||
min="1"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="label">Description</label>
|
||||
<textarea
|
||||
className="input"
|
||||
rows={3}
|
||||
value={formData.description}
|
||||
onChange={(e) => setFormData({ ...formData, description: e.target.value })}
|
||||
placeholder="Brief description of the payment method..."
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="label">Fees</label>
|
||||
<input
|
||||
type="text"
|
||||
className="input"
|
||||
value={formData.fees}
|
||||
onChange={(e) => setFormData({ ...formData, fees: e.target.value })}
|
||||
placeholder="e.g., 2.5% + 5 ETB"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Processing Time</label>
|
||||
<input
|
||||
type="text"
|
||||
className="input"
|
||||
value={formData.processingTime}
|
||||
onChange={(e) => setFormData({ ...formData, processingTime: e.target.value })}
|
||||
placeholder="e.g., Instant, 1-3 business days"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="flex items-center gap-3 cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={formData.isEnabled}
|
||||
onChange={(e) => setFormData({ ...formData, isEnabled: e.target.checked })}
|
||||
className="w-4 h-4 rounded border-gray-300"
|
||||
/>
|
||||
<span className="text-sm">Enable this payment method</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-2 pt-4 border-t">
|
||||
<ActionButton
|
||||
variant="secondary"
|
||||
onClick={() => {
|
||||
setCreateModalOpen(false);
|
||||
setEditModalOpen(false);
|
||||
setSelectedMethod(null);
|
||||
resetForm();
|
||||
}}
|
||||
>
|
||||
Cancel
|
||||
</ActionButton>
|
||||
<ActionButton
|
||||
type="submit"
|
||||
loading={createMutation.isPending || updateMutation.isPending}
|
||||
>
|
||||
{selectedMethod ? 'Update' : 'Add'} Method
|
||||
</ActionButton>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
|
||||
<ConfirmDialog
|
||||
isOpen={deleteConfirmOpen}
|
||||
onClose={() => {
|
||||
setDeleteConfirmOpen(false);
|
||||
setSelectedMethod(null);
|
||||
}}
|
||||
onConfirm={() => selectedMethod && deleteMutation.mutate(selectedMethod.id)}
|
||||
title="Delete Payment Method"
|
||||
message={`Are you sure you want to delete "${selectedMethod?.name}"? This action cannot be undone.`}
|
||||
confirmText="Delete"
|
||||
cancelText="Cancel"
|
||||
isLoading={deleteMutation.isPending}
|
||||
isDanger={true}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -192,17 +192,18 @@ export default function SchedulesPage() {
|
||||
|
||||
if (!editingSchedule) return;
|
||||
|
||||
const depDate = new Date(editForm.departureAt);
|
||||
const arrDate = new Date(editForm.arrivalAt);
|
||||
|
||||
if (arrDate <= depDate) {
|
||||
// Convert local datetime-local values to UTC for API
|
||||
const depLocal = new Date(editForm.departureAt);
|
||||
const arrLocal = new Date(editForm.arrivalAt);
|
||||
|
||||
if (arrLocal <= depLocal) {
|
||||
setError('Arrival time must be after departure time');
|
||||
return;
|
||||
}
|
||||
|
||||
const payload: any = {
|
||||
departureAt: editForm.departureAt,
|
||||
arrivalAt: editForm.arrivalAt,
|
||||
departureAt: depLocal.toISOString(),
|
||||
arrivalAt: arrLocal.toISOString(),
|
||||
status: editForm.status,
|
||||
coaches: editForm.coachIds.map((coachId: string, idx: number) => ({
|
||||
coachId,
|
||||
@@ -238,15 +239,22 @@ export default function SchedulesPage() {
|
||||
const handleEditClick = (schedule: Schedule) => {
|
||||
setEditingSchedule(schedule);
|
||||
|
||||
// Convert UTC dates to local time for datetime-local input
|
||||
// datetime-local expects local time (no timezone info)
|
||||
const dep = new Date(schedule.departureAt);
|
||||
const arr = new Date(schedule.arrivalAt);
|
||||
|
||||
const depLocal = new Date(dep.getTime() - dep.getTimezoneOffset() * 60000).toISOString().slice(0, 16);
|
||||
const arrLocal = new Date(arr.getTime() - arr.getTimezoneOffset() * 60000).toISOString().slice(0, 16);
|
||||
// Convert to local time by adding the timezone offset
|
||||
const depLocal = new Date(dep.getTime() + dep.getTimezoneOffset() * 60000);
|
||||
const arrLocal = new Date(arr.getTime() + arr.getTimezoneOffset() * 60000);
|
||||
|
||||
// Format for datetime-local input (YYYY-MM-DDTHH:mm)
|
||||
const depStr = depLocal.toISOString().slice(0, 16);
|
||||
const arrStr = arrLocal.toISOString().slice(0, 16);
|
||||
|
||||
setEditForm({
|
||||
departureAt: depLocal,
|
||||
arrivalAt: arrLocal,
|
||||
departureAt: depStr,
|
||||
arrivalAt: arrStr,
|
||||
status: schedule.status,
|
||||
coachIds: schedule.coachAssignments?.map((ca: any) => ca.coachId) || [],
|
||||
});
|
||||
@@ -675,7 +683,7 @@ export default function SchedulesPage() {
|
||||
className="rounded"
|
||||
/>
|
||||
<span className="text-sm">
|
||||
Seq {coach.sequence || 'N/A'} - {coach.number || coach.coachNumber} - {coach.coachType?.name} (Cap: {coach.capacity})
|
||||
{coach.sequence || 'N/A'} - {coach.number || coach.coachNumber} - {coach.coachType?.name} (Cap: {coach.capacity})
|
||||
</span>
|
||||
</label>
|
||||
))
|
||||
@@ -825,7 +833,7 @@ export default function SchedulesPage() {
|
||||
className="rounded"
|
||||
/>
|
||||
<span className="text-sm">
|
||||
Seq {coach.sequence || 'N/A'} - {coach.number || coach.coachNumber} - {coach.coachType?.name} (Cap: {coach.capacity})
|
||||
{coach.sequence || 'N/A'} - {coach.number || coach.coachNumber} - {coach.coachType?.name} (Cap: {coach.capacity})
|
||||
</span>
|
||||
</label>
|
||||
))
|
||||
|
||||
@@ -9,16 +9,6 @@ import ActionButton from '@/components/ui/ActionButton';
|
||||
import Modal from '@/components/ui/Modal';
|
||||
import ConfirmDialog from '@/components/ui/ConfirmDialog';
|
||||
import { stationsApi } from '@/lib/api';
|
||||
import { Station } from '@/types';
|
||||
|
||||
const TIMEZONES = [
|
||||
'Africa/Addis_Ababa',
|
||||
'Africa/Johannesburg',
|
||||
'Africa/Cairo',
|
||||
'Africa/Lagos',
|
||||
'Asia/Kolkata',
|
||||
'UTC',
|
||||
];
|
||||
|
||||
export default function StationsPage() {
|
||||
const [filters, setFilters] = useState({ search: '', country: '', operational: '' });
|
||||
@@ -317,19 +307,6 @@ export default function StationsPage() {
|
||||
<option value="DJ">Djibouti (DJ)</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Timezone *</label>
|
||||
<select
|
||||
name="timezone"
|
||||
className="input"
|
||||
defaultValue={editingStation?.timezone || 'Africa/Addis_Ababa'}
|
||||
required
|
||||
>
|
||||
{TIMEZONES.map((tz) => (
|
||||
<option key={tz} value={tz}>{tz}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Sequence Number *</label>
|
||||
<input
|
||||
|
||||
@@ -14,7 +14,7 @@ import { formatDateTime, formatCurrency, formatDateTimeShort } from '@/lib/utils
|
||||
import { useAuthStore } from '@/lib/auth-store';
|
||||
|
||||
export default function TicketsPage() {
|
||||
const [filters, setFilters] = useState({ search: '', status: '', originStationId: '', destinationStationId: '', arrivalDate: '', dateFrom: '', dateTo: '' });
|
||||
const [filters, setFilters] = useState({ search: '', status: '', originStationId: '', destinationStationId: '', arrivalDate: '', dateFrom: '', dateTo: '', coachId: '' });
|
||||
const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
|
||||
const [ticketToDelete, setTicketToDelete] = useState<any>(null);
|
||||
const [deleteError, setDeleteError] = useState<string | null>(null);
|
||||
@@ -80,6 +80,7 @@ export default function TicketsPage() {
|
||||
arrivalDate: filters.arrivalDate || undefined,
|
||||
dateFrom: filters.dateFrom || undefined,
|
||||
dateTo: filters.dateTo || undefined,
|
||||
coachId: filters.coachId || undefined,
|
||||
skip: 0,
|
||||
take: 50,
|
||||
}),
|
||||
@@ -90,6 +91,11 @@ export default function TicketsPage() {
|
||||
queryFn: () => stationsApi.getAll(),
|
||||
});
|
||||
|
||||
const { data: coachesData } = useQuery({
|
||||
queryKey: ['coaches'],
|
||||
queryFn: () => apiClient.get('/fleet/coaches'),
|
||||
});
|
||||
|
||||
const boardMutation = useMutation({
|
||||
mutationFn: ({ ticketId, leg }: { ticketId: string; leg?: 'outbound' | 'inbound' }) =>
|
||||
ticketsApi.validate(ticketId, { status: 'USED', boardedAt: new Date().toISOString(), leg: leg === 'inbound' ? 'RETURN' : 'OUTBOUND' }),
|
||||
@@ -283,7 +289,7 @@ export default function TicketsPage() {
|
||||
switch (key) {
|
||||
case 'ticketNumber': return ticket.ticketNumber || 'N/A';
|
||||
case 'booking': return ticket.booking?.bookingRef || 'N/A';
|
||||
case 'passenger': return ticket.booking?.passenger?.fullName || ticket.booking?.contactEmail || 'N/A';
|
||||
case 'passenger': return ticket.passengerName || ticket.booking?.seats?.[0]?.passengerName || ticket.booking?.passenger?.fullName || ticket.booking?.contactEmail || 'Guest';
|
||||
case 'trip': return (ticket.schedule?.originStation?.name || 'N/A') + ' - ' + (ticket.schedule?.destinationStation?.name || 'N/A');
|
||||
case 'coach': return ticket.seat?.coach?.number || 'N/A';
|
||||
case 'seat': return ticket.seat?.seatNumber || 'N/A';
|
||||
@@ -322,26 +328,44 @@ export default function TicketsPage() {
|
||||
key: 'ticketNumber',
|
||||
label: 'Ticket Number',
|
||||
sortable: true,
|
||||
render: (ticket: any) => (
|
||||
<div>
|
||||
<div className="font-mono font-semibold">{ticket.ticketNumber || 'N/A'}</div>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
{ticket.booking?.passenger?.fullName || 'N/A'}
|
||||
render: (ticket: any) => {
|
||||
const passengerName = ticket.passengerName ||
|
||||
ticket.booking?.seats?.[0]?.passengerName ||
|
||||
ticket.booking?.passenger?.fullName ||
|
||||
ticket.booking?.contactEmail ||
|
||||
'Guest';
|
||||
return (
|
||||
<div>
|
||||
<div className="font-mono font-semibold">{ticket.ticketNumber || 'N/A'}</div>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
{passengerName}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'contact',
|
||||
label: 'Contact',
|
||||
render: (ticket: any) => (
|
||||
<div>
|
||||
<div className="font-medium">{ticket.booking?.contactPhone || ticket.booking?.passenger?.phone || 'N/A'}</div>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
<div className="text-xs text-muted-foreground">{ticket.booking?.contactEmail || ticket.booking?.passenger?.email || 'N/A'}</div>
|
||||
render: (ticket: any) => {
|
||||
// Find the booking seat that matches this ticket's passenger
|
||||
const matchingSeat = ticket.booking?.seats?.find((s: any) =>
|
||||
s.passengerName === ticket.passengerName && s.leg === ticket.leg
|
||||
);
|
||||
|
||||
// Try to get phone from BookingSeat first, then fall back to booking contact
|
||||
const phone = matchingSeat?.phone || ticket.booking?.contactPhone || ticket.booking?.passenger?.phone || 'N/A';
|
||||
const email = matchingSeat?.email || ticket.booking?.contactEmail || ticket.booking?.passenger?.email || 'N/A';
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="font-medium">{phone}</div>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
<div className="text-xs text-muted-foreground truncate" title={email}>{email}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'trip',
|
||||
@@ -368,12 +392,35 @@ export default function TicketsPage() {
|
||||
key: 'seat',
|
||||
label: 'Seat/Bed',
|
||||
sortable: true,
|
||||
render: (ticket: any) => (
|
||||
<div>
|
||||
<div className="font-mono font-semibold">{ticket.seat?.coach?.number || 'N/A'}: {ticket.seat?.seatNumber || 'N/A'}</div>
|
||||
<div className="text-xs text-muted-foreground">{ticket.seat?.coach?.coachType?.type || 'N/A'}</div>
|
||||
</div>
|
||||
),
|
||||
render: (ticket: any) => {
|
||||
const isRoundTrip = ticket.booking?.bookingType === 'ROUND_TRIP' || ticket.booking?.bookingType === 'ROUND_TRIP_TRANSIT';
|
||||
|
||||
if (isRoundTrip) {
|
||||
// Find seats for THIS specific passenger based on passengerName
|
||||
const passengerSeats = ticket.booking?.seats?.filter((s: any) => s.passengerName === ticket.passengerName) || [];
|
||||
const outboundSeat = passengerSeats.find((s: any) => s.leg === 1);
|
||||
const returnSeat = passengerSeats.find((s: any) => s.leg === 2);
|
||||
|
||||
return (
|
||||
<div className="space-y-1">
|
||||
<div className="font-mono font-semibold text-sm">
|
||||
➡ {outboundSeat?.seat?.coach?.number || 'N/A'}: {outboundSeat?.seat?.seatNumber || 'N/A'}
|
||||
</div>
|
||||
<div className="font-mono text-sm text-muted-foreground">
|
||||
⬅ {returnSeat?.seat?.coach?.number || 'N/A'}: {returnSeat?.seat?.seatNumber || 'N/A'}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// For one-way, show the ticket's primary seat
|
||||
return (
|
||||
<div>
|
||||
<div className="font-mono font-semibold">{ticket.seat?.coach?.number || 'N/A'}: {ticket.seat?.seatNumber || 'N/A'}</div>
|
||||
<div className="text-xs text-muted-foreground">{ticket.seat?.coach?.coachType?.type || 'N/A'}</div>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'arrivalDate',
|
||||
@@ -386,8 +433,20 @@ export default function TicketsPage() {
|
||||
key: 'boardingTimes',
|
||||
label: 'Boarding Times',
|
||||
render: (ticket: any) => {
|
||||
const outbound = ticket.booking?.outboundBoardedAt;
|
||||
const isRoundTrip = ticket.booking?.bookingType === 'ROUND_TRIP' || ticket.booking?.bookingType === 'ROUND_TRIP_TRANSIT';
|
||||
const outbound = ticket.booking?.outboundBoardedAt || ticket.validatedAt;
|
||||
const inbound = ticket.booking?.returnBoardedAt;
|
||||
|
||||
if (!isRoundTrip) {
|
||||
// One-way tickets: only show outbound status
|
||||
return (
|
||||
<span className={`text-sm ${outbound ? 'text-green-600 dark:text-green-400' : 'text-muted-foreground'}`}>
|
||||
{outbound ? formatDateTimeShort(outbound) : 'Not boarded'}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
// Round-trip tickets: show both legs
|
||||
const hasAny = outbound || inbound;
|
||||
if (!hasAny) return <span className="text-sm text-muted-foreground">Not boarded</span>;
|
||||
return (
|
||||
@@ -539,7 +598,7 @@ export default function TicketsPage() {
|
||||
</div>
|
||||
</div>
|
||||
{showExtraFilters && (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-3 mt-3">
|
||||
<div className="grid grid-cols-1 sm:grid-cols-4 gap-3 mt-3">
|
||||
<div>
|
||||
<label className="label">Status</label>
|
||||
<select
|
||||
@@ -553,6 +612,19 @@ export default function TicketsPage() {
|
||||
<option value="CANCELLED">Cancelled</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Coach</label>
|
||||
<select
|
||||
className="input"
|
||||
value={filters.coachId}
|
||||
onChange={(e) => setFilters({ ...filters, coachId: e.target.value })}
|
||||
>
|
||||
<option value="">All Coaches</option>
|
||||
{(Array.isArray(coachesData) ? coachesData : (coachesData as any)?.data || []).map((coach: any) => (
|
||||
<option key={coach.id} value={coach.id}>{coach.number}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Issued From</label>
|
||||
<input type="date" className="input" value={filters.dateFrom}
|
||||
@@ -663,7 +735,7 @@ export default function TicketsPage() {
|
||||
const t = selectedTicket;
|
||||
const b = t.booking;
|
||||
const isRoundTrip = b?.bookingType === 'ROUND_TRIP' || b?.bookingType === 'ROUND_TRIP_TRANSIT';
|
||||
const passengerName = b?.passenger?.fullName || b?.contactEmail || 'Guest';
|
||||
const passengerName = b?.seats?.[0]?.passengerName || b?.passenger?.fullName || b?.contactEmail || 'Guest';
|
||||
return (
|
||||
<div>
|
||||
{/* Gradient header */}
|
||||
|
||||
@@ -40,7 +40,7 @@ export default function Header() {
|
||||
</button>
|
||||
|
||||
{showNotifications && (
|
||||
<div className="absolute right-0 mt-2 w-80 rounded-lg border border-gray-200 dark:border-slate-700 bg-white dark:bg-slate-900 shadow-xl z-50">
|
||||
<div className="fixed inset-x-2 top-20 z-50 rounded-lg border border-gray-200 dark:border-slate-700 bg-white dark:bg-slate-900 shadow-xl sm:absolute sm:inset-x-auto sm:right-0 sm:top-full sm:mt-2 sm:w-80 md:w-96">
|
||||
<div className="p-4 border-b border-gray-200 dark:border-slate-700">
|
||||
<h3 className="font-semibold text-foreground">Notifications</h3>
|
||||
</div>
|
||||
@@ -96,7 +96,7 @@ export default function Header() {
|
||||
</button>
|
||||
|
||||
{showUserMenu && (
|
||||
<div className="absolute right-0 mt-2 w-56 rounded-lg border border-gray-200 dark:border-slate-700 bg-white dark:bg-slate-900 shadow-xl z-50">
|
||||
<div className="fixed inset-x-2 top-20 z-50 rounded-lg border border-gray-200 dark:border-slate-700 bg-white dark:bg-slate-900 shadow-xl sm:absolute sm:inset-x-auto sm:right-0 sm:top-full sm:mt-2 sm:w-56">
|
||||
<div className="p-3 border-b border-gray-200 dark:border-slate-700">
|
||||
<p className="text-sm font-medium text-foreground">{user?.fullName || 'Full Name'}</p>
|
||||
<p className="text-xs text-muted-foreground">{user?.email || 'user@email.com'}</p>
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import Link from 'next/link';
|
||||
import { usePathname } from 'next/navigation';
|
||||
import { useState } from 'react';
|
||||
import { useState, useEffect } from 'react';
|
||||
import {
|
||||
LayoutDashboard,
|
||||
Ticket,
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
BarChart3,
|
||||
Settings,
|
||||
LogOut,
|
||||
LogIn,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
Train,
|
||||
@@ -61,6 +62,7 @@ const navigationSections: { title: string; items: NavItem[] }[] = [
|
||||
{ name: 'Bookings', href: '/bookings', icon: Ticket, permission: PERMS.bookings.view },
|
||||
{ name: 'Passengers', href: '/passengers', icon: Users, permission: PERMS.passengers.view },
|
||||
{ name: 'Tickets', href: '/tickets', icon: FileText, permission: PERMS.tickets.view },
|
||||
{ name: 'Boarding', href: '/boarding', icon: LogIn, permission: PERMS.tickets.view },
|
||||
{ name: 'Luggage', href: '/excess-baggage', icon: Banknote, permission: PERMS.bookings.view },
|
||||
]
|
||||
},
|
||||
@@ -86,10 +88,11 @@ const navigationSections: { title: string; items: NavItem[] }[] = [
|
||||
{
|
||||
title: 'Financial',
|
||||
items: [
|
||||
{ name: 'Pricing & Fares', href: '/pricing', icon: DollarSign, permission: PERMS.admin },
|
||||
{ name: 'Currencies', href: '/currencies', icon: Banknote, permission: PERMS.currencies.manage },
|
||||
{ name: 'Payments', href: '/payments', icon: CreditCard, permission: PERMS.payments.view },
|
||||
{ name: 'Promo Codes', href: '/promos', icon: Gift, permission: PERMS.admin },
|
||||
{ name: 'Pricing & Fares', href: '/pricing', icon: DollarSign, permission: PERMS.admin },
|
||||
// { name: 'Configurable Fares', href: '/fare-management', icon: Settings, permission: PERMS.admin },
|
||||
{ name: 'Currencies', href: '/currencies', icon: Banknote, permission: PERMS.currencies.manage },
|
||||
{ name: 'Payment Methods', href: '/payment-methods', icon: CreditCard, permission: PERMS.payments.view },
|
||||
{ name: 'Promo Codes', href: '/promos', icon: Gift, permission: PERMS.admin },
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -134,12 +137,40 @@ const navigationSections: { title: string; items: NavItem[] }[] = [
|
||||
}
|
||||
];
|
||||
|
||||
// Hook to detect mobile devices
|
||||
function useIsMobile() {
|
||||
const [isMobile, setIsMobile] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const checkIsMobile = () => {
|
||||
setIsMobile(window.innerWidth < 768); // md breakpoint
|
||||
};
|
||||
|
||||
// Check on mount
|
||||
checkIsMobile();
|
||||
|
||||
// Listen for resize events
|
||||
window.addEventListener('resize', checkIsMobile);
|
||||
return () => window.removeEventListener('resize', checkIsMobile);
|
||||
}, []);
|
||||
|
||||
return isMobile;
|
||||
}
|
||||
|
||||
export default function Sidebar() {
|
||||
const pathname = usePathname();
|
||||
const { user, logout, hasPermission } = useAuthStore();
|
||||
const { isDark, toggleTheme } = useTheme();
|
||||
const isMobile = useIsMobile();
|
||||
|
||||
// Initialize collapsed state based on mobile detection
|
||||
const [isCollapsed, setIsCollapsed] = useState(false);
|
||||
|
||||
// Update collapsed state when mobile status changes
|
||||
useEffect(() => {
|
||||
setIsCollapsed(isMobile);
|
||||
}, [isMobile]);
|
||||
|
||||
return (
|
||||
<div className={cn(
|
||||
'flex h-screen flex-col transition-all duration-300',
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
import { apiClient } from '@/lib/api-client';
|
||||
|
||||
export interface FareConfiguration {
|
||||
id: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
effective_date: string;
|
||||
expiry_date?: string;
|
||||
is_active: boolean;
|
||||
is_default: boolean;
|
||||
created_by?: string;
|
||||
approved_by?: string;
|
||||
approved_at?: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
rate_rules_count: number;
|
||||
components_count: number;
|
||||
age_rules_count: number;
|
||||
rateRules?: any[];
|
||||
components?: any[];
|
||||
ageRules?: any[];
|
||||
}
|
||||
|
||||
export interface CreateFareConfigurationRequest {
|
||||
name: string;
|
||||
description?: string;
|
||||
effectiveDate: string;
|
||||
expiryDate?: string;
|
||||
rateRules: RateRule[];
|
||||
components: FareComponent[];
|
||||
ageRules: AgeRule[];
|
||||
isDefault?: boolean;
|
||||
}
|
||||
|
||||
export interface RateRule {
|
||||
nationalityType: 'LOCAL' | 'INTERNATIONAL';
|
||||
coachType: 'REGULAR_SEAT' | 'ECONOMY_BED' | 'VIP_BED';
|
||||
bedPosition?: 'UPPER' | 'MIDDLE' | 'LOWER';
|
||||
ratePerKmMinor: number;
|
||||
isActive?: boolean;
|
||||
}
|
||||
|
||||
export interface FareComponent {
|
||||
componentType: 'INSURANCE' | 'PREMIUM' | 'SERVICE_CHARGE' | 'TAX' | 'DEMAND';
|
||||
componentName: string;
|
||||
calculationMethod: 'MULTIPLIER' | 'PERCENTAGE' | 'FIXED_AMOUNT';
|
||||
valueMinor?: number;
|
||||
percentageValue?: number;
|
||||
appliesTo: 'BASE_FARE' | 'SUBTOTAL' | 'TOTAL';
|
||||
applyOrder: number;
|
||||
isActive?: boolean;
|
||||
}
|
||||
|
||||
export interface AgeRule {
|
||||
ruleName: string;
|
||||
minAge: number;
|
||||
maxAge?: number;
|
||||
pricingType: 'FREE' | 'FULL_FARE' | 'DISCOUNTED';
|
||||
discountPercentage?: number;
|
||||
maxFreePassengers?: number;
|
||||
appliesToComponents?: boolean;
|
||||
isActive?: boolean;
|
||||
}
|
||||
|
||||
export interface TestScenario {
|
||||
distanceKm: number;
|
||||
nationality: string;
|
||||
coachType: 'REGULAR_SEAT' | 'ECONOMY_BED' | 'VIP_BED';
|
||||
bedPosition?: 'UPPER' | 'MIDDLE' | 'LOWER';
|
||||
adultCount: number;
|
||||
childCount?: number;
|
||||
promoCode?: string;
|
||||
loyaltyPoints?: number;
|
||||
}
|
||||
|
||||
export interface CalculationResult {
|
||||
baseFareMinor: number;
|
||||
componentsTotal: number;
|
||||
totalBeforeDiscounts: number;
|
||||
discountsTotal: number;
|
||||
finalTotalMinor: number;
|
||||
breakdown: Array<{
|
||||
step: string;
|
||||
description: string;
|
||||
amount: number;
|
||||
runningTotal: number;
|
||||
}>;
|
||||
currency: string;
|
||||
calculationTimestamp: string;
|
||||
}
|
||||
|
||||
export interface SystemStatus {
|
||||
configurableFaresEnabled: boolean;
|
||||
rolloutPercentage: number;
|
||||
totalConfigurations: number;
|
||||
activeConfiguration: string | null;
|
||||
activeConfigurationName: string | null;
|
||||
systemReady: boolean;
|
||||
}
|
||||
|
||||
export const configurableFareApi = {
|
||||
// Configuration Management
|
||||
getAllConfigurations: (): Promise<FareConfiguration[]> =>
|
||||
apiClient.get('/admin/fare-configurations'),
|
||||
|
||||
getConfigurationById: (id: string): Promise<FareConfiguration> =>
|
||||
apiClient.get(`/admin/fare-configurations/${id}`),
|
||||
|
||||
createConfiguration: (data: CreateFareConfigurationRequest): Promise<FareConfiguration> =>
|
||||
apiClient.post('/admin/fare-configurations', data),
|
||||
|
||||
updateConfiguration: (id: string, data: Partial<CreateFareConfigurationRequest>): Promise<FareConfiguration> =>
|
||||
apiClient.put(`/admin/fare-configurations/${id}`, data),
|
||||
|
||||
activateConfiguration: (id: string): Promise<{ success: boolean; message: string }> =>
|
||||
apiClient.post(`/admin/fare-configurations/${id}/activate`),
|
||||
|
||||
deleteConfiguration: (id: string): Promise<{ success: boolean; message: string }> =>
|
||||
apiClient.delete(`/admin/fare-configurations/${id}`),
|
||||
|
||||
testConfiguration: (id: string, scenario: TestScenario): Promise<CalculationResult> =>
|
||||
apiClient.post(`/admin/fare-configurations/${id}/test`, scenario),
|
||||
|
||||
getAuditTrail: (id: string): Promise<any[]> =>
|
||||
apiClient.get(`/admin/fare-configurations/${id}/audit`),
|
||||
|
||||
// Migration & Setup
|
||||
migrateLegacySystem: (dryRun: boolean = false): Promise<{
|
||||
scheduleFareRules: number;
|
||||
segmentFareRules: number;
|
||||
configurationsCreated: number;
|
||||
dryRun: boolean;
|
||||
}> =>
|
||||
apiClient.post('/admin/fare-migration/migrate-legacy', { dryRun }),
|
||||
|
||||
createNewFormulaConfiguration: (data: {
|
||||
name: string;
|
||||
description?: string;
|
||||
activateImmediately?: boolean;
|
||||
}): Promise<FareConfiguration> =>
|
||||
apiClient.post('/admin/fare-migration/create-new-formula', data),
|
||||
|
||||
completeSetup: (options: {
|
||||
activateNewFormula?: boolean;
|
||||
enableFeature?: boolean;
|
||||
} = {}): Promise<{
|
||||
migration: any;
|
||||
newConfiguration: FareConfiguration;
|
||||
featureEnabled: boolean;
|
||||
message: string;
|
||||
}> =>
|
||||
apiClient.post('/admin/fare-migration/complete-setup', options),
|
||||
|
||||
getSystemStatus: (): Promise<SystemStatus> =>
|
||||
apiClient.get('/admin/fare-migration/status'),
|
||||
|
||||
// System Control
|
||||
getFeatureStatus: (featureName: string = 'USE_CONFIGURABLE_FARES'): Promise<{
|
||||
enabled: boolean;
|
||||
config: Record<string, any>;
|
||||
}> =>
|
||||
apiClient.get(`/admin/fare-configurations/system/feature-status?feature=${featureName}`),
|
||||
|
||||
toggleFeature: (data: {
|
||||
featureName: string;
|
||||
enabled: boolean;
|
||||
config?: Record<string, any>;
|
||||
}): Promise<{ success: boolean; message: string }> =>
|
||||
apiClient.post('/admin/fare-configurations/system/toggle-feature', data),
|
||||
|
||||
enableConfigurableFares: (rolloutPercentage: number = 100): Promise<{ success: boolean; message: string }> =>
|
||||
apiClient.post('/admin/fare-configurations/system/enable-configurable-fares', { rolloutPercentage }),
|
||||
|
||||
disableConfigurableFares: (): Promise<{ success: boolean; message: string }> =>
|
||||
apiClient.post('/admin/fare-configurations/system/disable-configurable-fares'),
|
||||
};
|
||||
|
||||
export default configurableFareApi;
|
||||
@@ -113,6 +113,7 @@ export const fleetApi = {
|
||||
createCoach: (data: any) => apiClient.post<any>('/fleet/coaches', data),
|
||||
updateCoach: (id: string, data: any) => apiClient.patch<any>(`/fleet/coaches/${id}`, data),
|
||||
deleteCoach: (id: string) => apiClient.delete(`/fleet/coaches/${id}`),
|
||||
generateSeatMap: (data: any) => apiClient.post<any>('/fleet/seatmap/generate', data),
|
||||
};
|
||||
|
||||
// Schedules API
|
||||
@@ -165,6 +166,13 @@ export const paymentsApi = {
|
||||
getById: (id: string) => apiClient.get<any>(`/payments/${id}`),
|
||||
refund: (id: string, data: any) => apiClient.post<any>(`/payments/${id}/refund`, data),
|
||||
getProviders: () => apiClient.get<any[]>('/payments/providers'),
|
||||
getMethods: async () => {
|
||||
const response = await apiClient.get('/payments/methods');
|
||||
return (response as any)?.data || response || [];
|
||||
},
|
||||
addMethod: (data: any) => apiClient.post('/payments/methods', data),
|
||||
updateMethod: (id: string, data: any) => apiClient.patch(`/payments/methods/${id}`, data),
|
||||
deleteMethod: (id: string) => apiClient.delete(`/payments/methods/${id}`),
|
||||
};
|
||||
|
||||
// Tickets API
|
||||
@@ -182,6 +190,7 @@ export const ticketsApi = {
|
||||
},
|
||||
getById: (id: string) => apiClient.get<any>(`/tickets/${id}`),
|
||||
validate: (ticketId: string, data: any) => apiClient.post<any>(`/tickets/${ticketId}/validate`, data),
|
||||
scanAndBoard: (qrCodeOrRef: string, data: any) => apiClient.post<any>(`/tickets/scan-board/${encodeURIComponent(qrCodeOrRef)}`, data),
|
||||
regenerate: (ticketId: string) => apiClient.post<any>(`/tickets/${ticketId}/regenerate`),
|
||||
};
|
||||
|
||||
@@ -371,7 +380,7 @@ export const reportsApi = {
|
||||
const query = reportType ? `?type=${reportType}` : '';
|
||||
const response = await apiClient.get<any>(`/reports${query}`);
|
||||
if (Array.isArray(response)) return { items: response };
|
||||
return response?.data ? (Array.isArray(response.data) ? { items: response.data } : response) : { items: [] };
|
||||
return (response as any)?.data ? (Array.isArray((response as any).data) ? { items: (response as any).data } : response) : { items: [] };
|
||||
},
|
||||
};
|
||||
|
||||
@@ -383,7 +392,7 @@ export const packagesApi = {
|
||||
) as Record<string, string>;
|
||||
const query = new URLSearchParams(cleanParams).toString();
|
||||
const response = await apiClient.get<any>(`/packages/all${query ? `?${query}` : ''}`);
|
||||
if (response?.data) return Array.isArray(response.data) ? { items: response.data } : response;
|
||||
if ((response as any)?.data) return Array.isArray((response as any).data) ? { items: (response as any).data } : response;
|
||||
return Array.isArray(response) ? { items: response } : response;
|
||||
},
|
||||
getById: (id: string) => apiClient.get<any>(`/packages/${id}`),
|
||||
@@ -405,7 +414,7 @@ export const packageInquiriesApi = {
|
||||
) as Record<string, string>;
|
||||
const query = new URLSearchParams(cleanParams).toString();
|
||||
const response = await apiClient.get<any>(`/packages/inquiries${query ? `?${query}` : ''}`);
|
||||
if (response?.data) return Array.isArray(response.data) ? { items: response.data } : response;
|
||||
if ((response as any)?.data) return Array.isArray((response as any).data) ? { items: (response as any).data } : response;
|
||||
return Array.isArray(response) ? { items: response } : response;
|
||||
},
|
||||
create: (data: any) => apiClient.post<any>('/packages/inquiries', data),
|
||||
@@ -423,11 +432,12 @@ export const excessBaggageApi = {
|
||||
) as Record<string, string>;
|
||||
const query = new URLSearchParams(cleanParams).toString();
|
||||
const response = await apiClient.get<any>(`/agents/excess-baggage${query ? `?${query}` : ''}`);
|
||||
if (response?.data) return Array.isArray(response.data) ? { items: response.data } : response;
|
||||
if ((response as any)?.data) return Array.isArray((response as any).data) ? { items: (response as any).data } : response;
|
||||
return Array.isArray(response) ? { items: response } : response;
|
||||
},
|
||||
resendLink: (id: string) => apiClient.post<any>(`/agents/excess-baggage/${id}/resend`, {}),
|
||||
waive: (id: string, data: any) => apiClient.patch<any>(`/agents/excess-baggage/${id}/waive`, data),
|
||||
delete: (id: string) => apiClient.delete(`/agents/excess-baggage/${id}`),
|
||||
};
|
||||
|
||||
// System Config API
|
||||
|
||||
@@ -8,6 +8,7 @@ import { apiClient } from '@/lib/api-client';
|
||||
import { format } from 'date-fns';
|
||||
import { useState, useEffect } from 'react';
|
||||
import { ChevronLeft } from 'lucide-react';
|
||||
import { calculatePassengerFare, isChild, isFirstChild, formatFare } from '@/utils/fare-utils';
|
||||
|
||||
// Helper function to decode JWT token and extract passengerId
|
||||
function getPassengerIdFromToken(token: string): string | null {
|
||||
@@ -373,11 +374,17 @@ export default function ReviewPage() {
|
||||
}
|
||||
|
||||
|
||||
const outboundBaseFare = isRoundTrip && outboundSchedule ? passengers.reduce((sum) => sum + (outboundSchedule.baseFareAdult || 0), 0) : 0;
|
||||
const inboundBaseFare = isRoundTrip && inboundSchedule ? passengers.reduce((sum) => sum + (inboundSchedule.baseFareAdult || 0), 0) : 0;
|
||||
const baseFare = isRoundTrip ? (outboundBaseFare + inboundBaseFare) : passengers.reduce((sum) => {
|
||||
const outboundBaseFare = isRoundTrip && outboundSchedule ? passengers.reduce((sum, _, i) => {
|
||||
return sum + calculatePassengerFare(passengers, i, outboundSchedule.baseFareAdult || 0);
|
||||
}, 0) : 0;
|
||||
|
||||
const inboundBaseFare = isRoundTrip && inboundSchedule ? passengers.reduce((sum, _, i) => {
|
||||
return sum + calculatePassengerFare(passengers, i, inboundSchedule.baseFareAdult || 0);
|
||||
}, 0) : 0;
|
||||
|
||||
const baseFare = isRoundTrip ? (outboundBaseFare + inboundBaseFare) : passengers.reduce((sum, _, i) => {
|
||||
const farePerPassenger = selectedSchedule?.baseFareAdult || (selectedSchedule as any)?.fareAdult || (selectedSchedule as any)?.price || 0;
|
||||
return sum + farePerPassenger;
|
||||
return sum + calculatePassengerFare(passengers, i, farePerPassenger);
|
||||
}, 0);
|
||||
const total = baseFare;
|
||||
|
||||
@@ -391,26 +398,42 @@ export default function ReviewPage() {
|
||||
const outFare = outboundSchedule?.baseFareAdult || 0;
|
||||
const inFare = inboundSchedule?.baseFareAdult || 0;
|
||||
const onewayFare = selectedSchedule?.baseFareAdult || 0;
|
||||
const passengerTotal = isRoundTrip ? outFare + inFare : onewayFare;
|
||||
|
||||
// Apply first child free logic using utility functions
|
||||
const outboundFare = calculatePassengerFare(passengers, i, outFare);
|
||||
const inboundFare = calculatePassengerFare(passengers, i, inFare);
|
||||
const oneWayFare = calculatePassengerFare(passengers, i, onewayFare);
|
||||
|
||||
const passengerTotal = isRoundTrip ? outboundFare + inboundFare : oneWayFare;
|
||||
const isChildPassenger = isChild(p);
|
||||
const isFreeChild = isChildPassenger && isFirstChild(passengers, i);
|
||||
|
||||
return (
|
||||
<div key={i} className="border-b border-gray-100 dark:border-gray-800 pb-2 last:border-0">
|
||||
<div className="flex justify-between mb-0.5">
|
||||
<span className="text-sm font-medium text-gray-900 dark:text-gray-100 truncate max-w-[60%]">
|
||||
{p.name || `Passenger ${i + 1}`}
|
||||
{p.name || `Passenger ${i + 1}`}
|
||||
{isChildPassenger && (
|
||||
<span className={`text-xs font-semibold ml-1 ${
|
||||
isFreeChild ? 'text-green-600' : 'text-blue-600'
|
||||
}`}>
|
||||
({isFreeChild ? 'CHILD - FREE' : 'CHILD'})
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
<span className="text-sm font-semibold text-gray-900 dark:text-gray-100">
|
||||
{displayCurrency} {(passengerTotal / 100).toFixed(2)}
|
||||
{formatFare(passengerTotal, displayCurrency)}
|
||||
</span>
|
||||
</div>
|
||||
{isRoundTrip && (
|
||||
<div className="pl-3 space-y-0.5 text-xs text-gray-500 dark:text-gray-400">
|
||||
<div className="flex justify-between">
|
||||
<span>Outbound</span>
|
||||
<span>{displayCurrency} {(outFare / 100).toFixed(2)}</span>
|
||||
<span>Outbound {isFreeChild ? '(Free)' : ''}</span>
|
||||
<span>{formatFare(outboundFare, displayCurrency)}</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span>Return</span>
|
||||
<span>{displayCurrency} {(inFare / 100).toFixed(2)}</span>
|
||||
<span>Return {isFreeChild ? '(Free)' : ''}</span>
|
||||
<span>{formatFare(inboundFare, displayCurrency)}</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -32,6 +32,13 @@ export interface PassengerDetail {
|
||||
phone?: string;
|
||||
email?: string;
|
||||
gender?: string;
|
||||
// Round-trip specific seat assignments
|
||||
outboundSeatId?: string;
|
||||
outboundSeatNumber?: string;
|
||||
inboundSeatId?: string;
|
||||
inboundSeatNumber?: string;
|
||||
returnSeatId?: string;
|
||||
returnSeatNumber?: string;
|
||||
}
|
||||
|
||||
export interface SelectedSchedule {
|
||||
|
||||
108
apps/edr-passenger-web/portal/src/utils/fare-utils.ts
Normal file
108
apps/edr-passenger-web/portal/src/utils/fare-utils.ts
Normal file
@@ -0,0 +1,108 @@
|
||||
/**
|
||||
* Utility functions for age-based fare calculations
|
||||
* Implements the "first child free" pricing policy
|
||||
*/
|
||||
|
||||
export interface PassengerWithAge {
|
||||
dateOfBirth?: string;
|
||||
name?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate age from date of birth
|
||||
*/
|
||||
export function calculateAge(dateOfBirth: string | Date): number {
|
||||
const today = new Date();
|
||||
const birth = new Date(dateOfBirth);
|
||||
let age = today.getFullYear() - birth.getFullYear();
|
||||
const monthDiff = today.getMonth() - birth.getMonth();
|
||||
|
||||
if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
|
||||
age--;
|
||||
}
|
||||
|
||||
return Math.max(0, age);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if passenger is a child (under 5 years old)
|
||||
*/
|
||||
export function isChild(passenger: PassengerWithAge): boolean {
|
||||
if (!passenger.dateOfBirth) return false;
|
||||
return calculateAge(passenger.dateOfBirth) < 5;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if this child gets the free fare (first child in the list)
|
||||
*/
|
||||
export function isFirstChild(passengers: PassengerWithAge[], currentIndex: number): boolean {
|
||||
const currentPassenger = passengers[currentIndex];
|
||||
if (!isChild(currentPassenger)) return false;
|
||||
|
||||
// Count children before this passenger
|
||||
const childrenBefore = passengers.slice(0, currentIndex).filter(p => isChild(p));
|
||||
return childrenBefore.length === 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate fare for a single passenger with first child free logic
|
||||
*/
|
||||
export function calculatePassengerFare(
|
||||
passengers: PassengerWithAge[],
|
||||
passengerIndex: number,
|
||||
baseFare: number
|
||||
): number {
|
||||
const passenger = passengers[passengerIndex];
|
||||
|
||||
if (isChild(passenger) && isFirstChild(passengers, passengerIndex)) {
|
||||
return 0; // First child travels free
|
||||
}
|
||||
|
||||
return baseFare;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate total fare for all passengers with first child free logic
|
||||
*/
|
||||
export function calculateTotalFare(
|
||||
passengers: PassengerWithAge[],
|
||||
baseFare: number
|
||||
): number {
|
||||
return passengers.reduce((total, _, index) => {
|
||||
return total + calculatePassengerFare(passengers, index, baseFare);
|
||||
}, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get passenger category for display purposes
|
||||
*/
|
||||
export function getPassengerCategory(passenger: PassengerWithAge): 'ADULT' | 'CHILD' {
|
||||
return isChild(passenger) ? 'CHILD' : 'ADULT';
|
||||
}
|
||||
|
||||
/**
|
||||
* Format fare amount for display
|
||||
*/
|
||||
export function formatFare(amountMinor: number, currency: string = 'ETB'): string {
|
||||
return `${currency} ${(amountMinor / 100).toFixed(2)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get pricing summary for a list of passengers
|
||||
*/
|
||||
export function getPricingSummary(passengers: PassengerWithAge[], baseFare: number) {
|
||||
const adults = passengers.filter(p => !isChild(p));
|
||||
const children = passengers.filter(p => isChild(p));
|
||||
const freeChildren = Math.min(children.length, 1);
|
||||
const paidChildren = Math.max(0, children.length - 1);
|
||||
|
||||
return {
|
||||
adultCount: adults.length,
|
||||
childCount: children.length,
|
||||
freeChildrenCount: freeChildren,
|
||||
paidChildrenCount: paidChildren,
|
||||
adultFare: adults.length * baseFare,
|
||||
paidChildFare: paidChildren * baseFare,
|
||||
totalFare: calculateTotalFare(passengers, baseFare)
|
||||
};
|
||||
}
|
||||
@@ -176,7 +176,7 @@ const DashboardLayout = ({
|
||||
{isUserMenuOpen ? (
|
||||
<div
|
||||
role="menu"
|
||||
className="absolute right-0 top-full z-50 mt-2 w-52 overflow-hidden rounded-xl border border-border bg-card py-1 shadow-lg"
|
||||
className="absolute right-0 top-full z-50 mt-2 w-52 max-w-[calc(100vw-2rem)] overflow-hidden rounded-xl border border-border bg-card py-1 shadow-lg -translate-x-4 sm:translate-x-0"
|
||||
>
|
||||
<div className="border-b border-border px-4 py-3">
|
||||
<p className="text-sm font-semibold text-card-foreground">
|
||||
|
||||
Reference in New Issue
Block a user