mirror of
https://github.com/Tria-plc/edr-platform.git
synced 2026-08-30 07:38:10 +00:00
Booking and pricing related updates
This commit is contained in:
@@ -1,28 +1,52 @@
|
|||||||
-- Fix missing columns from 20260617 migration (failed due to missing schema prefix)
|
-- Create passenger schema if it doesn't exist
|
||||||
|
CREATE SCHEMA IF NOT EXISTS passenger;
|
||||||
|
|
||||||
|
-- Move all enums from public to passenger schema
|
||||||
|
DO $$
|
||||||
|
DECLARE
|
||||||
|
e text;
|
||||||
|
BEGIN
|
||||||
|
FOR e IN
|
||||||
|
SELECT typname FROM pg_type
|
||||||
|
JOIN pg_namespace ON pg_namespace.oid = pg_type.typnamespace
|
||||||
|
WHERE pg_namespace.nspname = 'public' AND pg_type.typtype = 'e'
|
||||||
|
LOOP
|
||||||
|
EXECUTE format('ALTER TYPE public.%I SET SCHEMA passenger', e);
|
||||||
|
END LOOP;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
-- Move all tables from public to passenger schema
|
||||||
|
DO $$
|
||||||
|
DECLARE
|
||||||
|
t text;
|
||||||
|
BEGIN
|
||||||
|
FOR t IN
|
||||||
|
SELECT tablename FROM pg_tables
|
||||||
|
WHERE schemaname = 'public' AND tablename NOT IN ('_prisma_migrations')
|
||||||
|
LOOP
|
||||||
|
EXECUTE format('ALTER TABLE public.%I SET SCHEMA passenger', t);
|
||||||
|
END LOOP;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
-- Add missing columns to Booking
|
||||||
ALTER TABLE "passenger"."Booking"
|
ALTER TABLE "passenger"."Booking"
|
||||||
ADD COLUMN IF NOT EXISTS "returnScheduleId" TEXT,
|
ADD COLUMN IF NOT EXISTS "returnScheduleId" TEXT,
|
||||||
ADD COLUMN IF NOT EXISTS "returnOriginStationId" TEXT,
|
ADD COLUMN IF NOT EXISTS "returnOriginStationId" TEXT,
|
||||||
ADD COLUMN IF NOT EXISTS "returnDestinationStationId" TEXT,
|
ADD COLUMN IF NOT EXISTS "returnDestinationStationId" TEXT,
|
||||||
ADD COLUMN IF NOT EXISTS "returnHoldId" TEXT,
|
ADD COLUMN IF NOT EXISTS "returnHoldId" TEXT,
|
||||||
ADD COLUMN IF NOT EXISTS "returnSeatClassId" TEXT;
|
ADD COLUMN IF NOT EXISTS "returnSeatClassId" TEXT,
|
||||||
|
ADD COLUMN IF NOT EXISTS "leg2ScheduleId" TEXT,
|
||||||
|
ADD COLUMN IF NOT EXISTS "leg2OriginStationId" TEXT,
|
||||||
|
ADD COLUMN IF NOT EXISTS "leg2DestinationStationId" TEXT,
|
||||||
|
ADD COLUMN IF NOT EXISTS "leg2SeatClassId" TEXT,
|
||||||
|
ADD COLUMN IF NOT EXISTS "returnLeg2ScheduleId" TEXT,
|
||||||
|
ADD COLUMN IF NOT EXISTS "returnLeg2OriginStationId" TEXT,
|
||||||
|
ADD COLUMN IF NOT EXISTS "returnLeg2DestStationId" TEXT,
|
||||||
|
ADD COLUMN IF NOT EXISTS "returnLeg2SeatClassId" TEXT,
|
||||||
|
ADD COLUMN IF NOT EXISTS "outboundBoardedAt" TIMESTAMP(3),
|
||||||
|
ADD COLUMN IF NOT EXISTS "returnBoardedAt" TIMESTAMP(3);
|
||||||
|
|
||||||
ALTER TABLE "passenger"."SeatClass" ALTER COLUMN "baseFareMinor" SET DEFAULT 0;
|
-- Add ReturnLegStatus enum and column
|
||||||
ALTER TABLE "passenger"."Ticket" ALTER COLUMN "status" SET DEFAULT 'ACTIVE';
|
|
||||||
|
|
||||||
CREATE INDEX IF NOT EXISTS "Booking_bookingType_idx" ON "passenger"."Booking"("bookingType");
|
|
||||||
|
|
||||||
-- Transit leg-2 columns (never migrated)
|
|
||||||
ALTER TABLE "passenger"."Booking"
|
|
||||||
ADD COLUMN IF NOT EXISTS "leg2ScheduleId" TEXT,
|
|
||||||
ADD COLUMN IF NOT EXISTS "leg2OriginStationId" TEXT,
|
|
||||||
ADD COLUMN IF NOT EXISTS "leg2DestinationStationId" TEXT,
|
|
||||||
ADD COLUMN IF NOT EXISTS "leg2SeatClassId" TEXT,
|
|
||||||
ADD COLUMN IF NOT EXISTS "returnLeg2ScheduleId" TEXT,
|
|
||||||
ADD COLUMN IF NOT EXISTS "returnLeg2OriginStationId" TEXT,
|
|
||||||
ADD COLUMN IF NOT EXISTS "returnLeg2DestStationId" TEXT,
|
|
||||||
ADD COLUMN IF NOT EXISTS "returnLeg2SeatClassId" TEXT;
|
|
||||||
|
|
||||||
-- ReturnLegStatus enum + columns (from 20260625 migration, may have also failed)
|
|
||||||
DO $$ BEGIN
|
DO $$ BEGIN
|
||||||
CREATE TYPE "passenger"."ReturnLegStatus" AS ENUM (
|
CREATE TYPE "passenger"."ReturnLegStatus" AS ENUM (
|
||||||
'NOT_APPLICABLE', 'BOTH_USED', 'OUTBOUND_ONLY', 'INBOUND_ONLY', 'NEITHER_USED'
|
'NOT_APPLICABLE', 'BOTH_USED', 'OUTBOUND_ONLY', 'INBOUND_ONLY', 'NEITHER_USED'
|
||||||
@@ -30,9 +54,15 @@ DO $$ BEGIN
|
|||||||
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||||
|
|
||||||
ALTER TABLE "passenger"."Booking"
|
ALTER TABLE "passenger"."Booking"
|
||||||
ADD COLUMN IF NOT EXISTS "returnLegStatus" "passenger"."ReturnLegStatus" NOT NULL DEFAULT 'NOT_APPLICABLE',
|
ADD COLUMN IF NOT EXISTS "returnLegStatus" "passenger"."ReturnLegStatus" NOT NULL DEFAULT 'NOT_APPLICABLE';
|
||||||
ADD COLUMN IF NOT EXISTS "outboundBoardedAt" TIMESTAMP(3),
|
|
||||||
ADD COLUMN IF NOT EXISTS "returnBoardedAt" TIMESTAMP(3);
|
|
||||||
|
|
||||||
ALTER TABLE "passenger"."GateValidationLog"
|
-- Add missing columns to other tables
|
||||||
ADD COLUMN IF NOT EXISTS "leg" TEXT;
|
ALTER TABLE "passenger"."GateValidationLog" ADD COLUMN IF NOT EXISTS "leg" TEXT;
|
||||||
|
ALTER TABLE "passenger"."BookingSeat" ADD COLUMN IF NOT EXISTS "leg" INTEGER NOT NULL DEFAULT 1;
|
||||||
|
ALTER TABLE "passenger"."BookingSeat" ADD COLUMN IF NOT EXISTS "scheduleId" TEXT;
|
||||||
|
ALTER TABLE "passenger"."Ticket" ADD COLUMN IF NOT EXISTS "boardedAt" TIMESTAMP(3);
|
||||||
|
|
||||||
|
ALTER TABLE "passenger"."SeatClass" ALTER COLUMN "baseFareMinor" SET DEFAULT 0;
|
||||||
|
ALTER TABLE "passenger"."Ticket" ALTER COLUMN "status" SET DEFAULT 'ACTIVE';
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS "Booking_bookingType_idx" ON "passenger"."Booking"("bookingType");
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
generator client {
|
generator client {
|
||||||
provider = "prisma-client-js"
|
provider = "prisma-client-js"
|
||||||
|
previewFeatures = ["multiSchema"]
|
||||||
}
|
}
|
||||||
|
|
||||||
datasource db {
|
datasource db {
|
||||||
@@ -79,7 +80,6 @@ model CoachType {
|
|||||||
updatedAt DateTime @updatedAt
|
updatedAt DateTime @updatedAt
|
||||||
coaches Coach[]
|
coaches Coach[]
|
||||||
seatClasses SeatClass[]
|
seatClasses SeatClass[]
|
||||||
|
|
||||||
@@schema("passenger")
|
@@schema("passenger")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -116,11 +116,11 @@ enum BookingStatus {
|
|||||||
}
|
}
|
||||||
|
|
||||||
enum ReturnLegStatus {
|
enum ReturnLegStatus {
|
||||||
NOT_APPLICABLE // one-way booking
|
NOT_APPLICABLE
|
||||||
BOTH_USED // passenger used both legs
|
BOTH_USED
|
||||||
OUTBOUND_ONLY // return leg not used (no-show on return)
|
OUTBOUND_ONLY
|
||||||
INBOUND_ONLY // outbound leg not used, return leg used
|
INBOUND_ONLY
|
||||||
NEITHER_USED // neither leg boarded yet
|
NEITHER_USED
|
||||||
|
|
||||||
@@schema("passenger")
|
@@schema("passenger")
|
||||||
}
|
}
|
||||||
@@ -269,7 +269,6 @@ model User {
|
|||||||
fraudAlerts FraudAlert[]
|
fraudAlerts FraudAlert[]
|
||||||
|
|
||||||
faydaVerificationSessions FaydaVerificationSession[]
|
faydaVerificationSessions FaydaVerificationSession[]
|
||||||
|
|
||||||
@@schema("passenger")
|
@@schema("passenger")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -283,7 +282,6 @@ model Session {
|
|||||||
lastActivityAt DateTime @default(now())
|
lastActivityAt DateTime @default(now())
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||||
|
|
||||||
@@schema("passenger")
|
@@schema("passenger")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -315,7 +313,6 @@ model TravelerProfile {
|
|||||||
notes String?
|
notes String?
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
passenger Passenger @relation(fields: [passengerId], references: [id])
|
passenger Passenger @relation(fields: [passengerId], references: [id])
|
||||||
|
|
||||||
@@schema("passenger")
|
@@schema("passenger")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -350,7 +347,6 @@ model Train {
|
|||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
updatedAt DateTime @updatedAt
|
updatedAt DateTime @updatedAt
|
||||||
schedules TrainSchedule[]
|
schedules TrainSchedule[]
|
||||||
|
|
||||||
@@schema("passenger")
|
@@schema("passenger")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -412,7 +408,6 @@ model TripLiveStatus {
|
|||||||
platformLabel String?
|
platformLabel String?
|
||||||
updatedAt DateTime @updatedAt
|
updatedAt DateTime @updatedAt
|
||||||
schedule TrainSchedule @relation(fields: [scheduleId], references: [id])
|
schedule TrainSchedule @relation(fields: [scheduleId], references: [id])
|
||||||
|
|
||||||
@@schema("passenger")
|
@@schema("passenger")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -500,7 +495,6 @@ model FareRule {
|
|||||||
validFrom DateTime
|
validFrom DateTime
|
||||||
validUntil DateTime?
|
validUntil DateTime?
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
|
|
||||||
@@schema("passenger")
|
@@schema("passenger")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -584,7 +578,6 @@ model BookingSeat {
|
|||||||
displayFareMinor Int?
|
displayFareMinor Int?
|
||||||
booking Booking @relation(fields: [bookingId], references: [id])
|
booking Booking @relation(fields: [bookingId], references: [id])
|
||||||
seat Seat @relation(fields: [seatId], references: [id])
|
seat Seat @relation(fields: [seatId], references: [id])
|
||||||
|
|
||||||
@@schema("passenger")
|
@@schema("passenger")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -600,7 +593,6 @@ model PaymentMethod {
|
|||||||
sortOrder Int @default(0)
|
sortOrder Int @default(0)
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
updatedAt DateTime @updatedAt
|
updatedAt DateTime @updatedAt
|
||||||
|
|
||||||
@@schema("passenger")
|
@@schema("passenger")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -661,7 +653,6 @@ model PaymentRefund {
|
|||||||
status String
|
status String
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
paymentIntent PaymentIntent @relation(fields: [paymentIntentId], references: [id])
|
paymentIntent PaymentIntent @relation(fields: [paymentIntentId], references: [id])
|
||||||
|
|
||||||
@@schema("passenger")
|
@@schema("passenger")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -681,7 +672,6 @@ model Ticket {
|
|||||||
booking Booking @relation(fields: [bookingId], references: [id])
|
booking Booking @relation(fields: [bookingId], references: [id])
|
||||||
validationLogs GateValidationLog[]
|
validationLogs GateValidationLog[]
|
||||||
seats TicketSeat[]
|
seats TicketSeat[]
|
||||||
|
|
||||||
@@schema("passenger")
|
@@schema("passenger")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -709,7 +699,6 @@ model LoyaltyAccount {
|
|||||||
passenger Passenger @relation(fields: [passengerId], references: [id])
|
passenger Passenger @relation(fields: [passengerId], references: [id])
|
||||||
ledger LoyaltyLedgerEntry[]
|
ledger LoyaltyLedgerEntry[]
|
||||||
rewards LoyaltyReward[]
|
rewards LoyaltyReward[]
|
||||||
|
|
||||||
@@schema("passenger")
|
@@schema("passenger")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -722,7 +711,6 @@ model LoyaltyLedgerEntry {
|
|||||||
balanceAfter Int
|
balanceAfter Int
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
account LoyaltyAccount @relation(fields: [accountId], references: [id])
|
account LoyaltyAccount @relation(fields: [accountId], references: [id])
|
||||||
|
|
||||||
@@schema("passenger")
|
@@schema("passenger")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -734,7 +722,6 @@ model LoyaltyReward {
|
|||||||
available Boolean @default(true)
|
available Boolean @default(true)
|
||||||
description String?
|
description String?
|
||||||
account LoyaltyAccount @relation(fields: [accountId], references: [id])
|
account LoyaltyAccount @relation(fields: [accountId], references: [id])
|
||||||
|
|
||||||
@@schema("passenger")
|
@@schema("passenger")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -763,7 +750,6 @@ model WalletLedgerEntry {
|
|||||||
relatedBookingId String?
|
relatedBookingId String?
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
wallet WalletAccount @relation(fields: [walletId], references: [id])
|
wallet WalletAccount @relation(fields: [walletId], references: [id])
|
||||||
|
|
||||||
@@schema("passenger")
|
@@schema("passenger")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -778,7 +764,6 @@ model Notification {
|
|||||||
metadata Json?
|
metadata Json?
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
passenger Passenger @relation(fields: [passengerId], references: [id])
|
passenger Passenger @relation(fields: [passengerId], references: [id])
|
||||||
|
|
||||||
@@schema("passenger")
|
@@schema("passenger")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -794,7 +779,6 @@ model Promotion {
|
|||||||
deepLink String?
|
deepLink String?
|
||||||
active Boolean @default(true)
|
active Boolean @default(true)
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
|
|
||||||
@@schema("passenger")
|
@@schema("passenger")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -808,7 +792,6 @@ model StationCrowdSignal {
|
|||||||
observedAt DateTime?
|
observedAt DateTime?
|
||||||
updatedAt DateTime @updatedAt
|
updatedAt DateTime @updatedAt
|
||||||
station Station @relation(fields: [stationId], references: [id])
|
station Station @relation(fields: [stationId], references: [id])
|
||||||
|
|
||||||
@@schema("passenger")
|
@@schema("passenger")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -820,7 +803,6 @@ model WeatherAlert {
|
|||||||
message String
|
message String
|
||||||
validUntil DateTime
|
validUntil DateTime
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
|
|
||||||
@@schema("passenger")
|
@@schema("passenger")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -828,7 +810,6 @@ model MenuCategory {
|
|||||||
id String @id @default(uuid())
|
id String @id @default(uuid())
|
||||||
name String
|
name String
|
||||||
items MenuItem[]
|
items MenuItem[]
|
||||||
|
|
||||||
@@schema("passenger")
|
@@schema("passenger")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -843,7 +824,6 @@ model MenuItem {
|
|||||||
availableUntil DateTime?
|
availableUntil DateTime?
|
||||||
schedule TrainSchedule @relation(fields: [scheduleId], references: [id])
|
schedule TrainSchedule @relation(fields: [scheduleId], references: [id])
|
||||||
category MenuCategory @relation(fields: [categoryId], references: [id])
|
category MenuCategory @relation(fields: [categoryId], references: [id])
|
||||||
|
|
||||||
@@schema("passenger")
|
@@schema("passenger")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -858,7 +838,6 @@ model FoodOrder {
|
|||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
booking Booking @relation(fields: [bookingId], references: [id])
|
booking Booking @relation(fields: [bookingId], references: [id])
|
||||||
items FoodOrderItem[]
|
items FoodOrderItem[]
|
||||||
|
|
||||||
@@schema("passenger")
|
@@schema("passenger")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -871,7 +850,6 @@ model FoodOrderItem {
|
|||||||
unitPriceMinor Int?
|
unitPriceMinor Int?
|
||||||
lineTotalMinor Int
|
lineTotalMinor Int
|
||||||
order FoodOrder @relation(fields: [orderId], references: [id])
|
order FoodOrder @relation(fields: [orderId], references: [id])
|
||||||
|
|
||||||
@@schema("passenger")
|
@@schema("passenger")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -880,7 +858,6 @@ model FaqCategory {
|
|||||||
title String
|
title String
|
||||||
iconKey String?
|
iconKey String?
|
||||||
articles FaqArticle[]
|
articles FaqArticle[]
|
||||||
|
|
||||||
@@schema("passenger")
|
@@schema("passenger")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -891,7 +868,6 @@ model FaqArticle {
|
|||||||
answerMarkdown String
|
answerMarkdown String
|
||||||
rank Int @default(0)
|
rank Int @default(0)
|
||||||
category FaqCategory @relation(fields: [categoryId], references: [id])
|
category FaqCategory @relation(fields: [categoryId], references: [id])
|
||||||
|
|
||||||
@@schema("passenger")
|
@@schema("passenger")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -902,7 +878,6 @@ model SupportConversation {
|
|||||||
status SupportConversationStatus @default(OPEN)
|
status SupportConversationStatus @default(OPEN)
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
messages SupportMessage[]
|
messages SupportMessage[]
|
||||||
|
|
||||||
@@schema("passenger")
|
@@schema("passenger")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -914,7 +889,6 @@ model SupportMessage {
|
|||||||
attachments Json?
|
attachments Json?
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
conversation SupportConversation @relation(fields: [conversationId], references: [id])
|
conversation SupportConversation @relation(fields: [conversationId], references: [id])
|
||||||
|
|
||||||
@@schema("passenger")
|
@@schema("passenger")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -934,7 +908,6 @@ model UserPreferences {
|
|||||||
darkMode Boolean @default(false)
|
darkMode Boolean @default(false)
|
||||||
language String @default("en")
|
language String @default("en")
|
||||||
user User @relation(fields: [userId], references: [id])
|
user User @relation(fields: [userId], references: [id])
|
||||||
|
|
||||||
@@schema("passenger")
|
@@schema("passenger")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -947,7 +920,6 @@ model Device {
|
|||||||
trusted Boolean @default(false)
|
trusted Boolean @default(false)
|
||||||
lastSeenAt DateTime @default(now())
|
lastSeenAt DateTime @default(now())
|
||||||
user User @relation(fields: [userId], references: [id])
|
user User @relation(fields: [userId], references: [id])
|
||||||
|
|
||||||
@@schema("passenger")
|
@@schema("passenger")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -961,7 +933,6 @@ model SavedRoute {
|
|||||||
tripCount Int @default(0)
|
tripCount Int @default(0)
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
passenger Passenger @relation(fields: [passengerId], references: [id])
|
passenger Passenger @relation(fields: [passengerId], references: [id])
|
||||||
|
|
||||||
@@schema("passenger")
|
@@schema("passenger")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -973,7 +944,6 @@ model Journey {
|
|||||||
currency String @default("ETB")
|
currency String @default("ETB")
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
journeySegments JourneySegment[]
|
journeySegments JourneySegment[]
|
||||||
|
|
||||||
@@schema("passenger")
|
@@schema("passenger")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -988,7 +958,6 @@ model JourneySegment {
|
|||||||
arrivalStationId String
|
arrivalStationId String
|
||||||
journey Journey @relation(fields: [journeyId], references: [id])
|
journey Journey @relation(fields: [journeyId], references: [id])
|
||||||
schedule TrainSchedule @relation(fields: [scheduleId], references: [id])
|
schedule TrainSchedule @relation(fields: [scheduleId], references: [id])
|
||||||
|
|
||||||
@@schema("passenger")
|
@@schema("passenger")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1032,7 +1001,6 @@ model Route {
|
|||||||
fareRules RouteFareRule[]
|
fareRules RouteFareRule[]
|
||||||
segmentFares SegmentFareRule[]
|
segmentFares SegmentFareRule[]
|
||||||
schedules TrainSchedule[]
|
schedules TrainSchedule[]
|
||||||
|
|
||||||
@@schema("passenger")
|
@@schema("passenger")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1102,7 +1070,6 @@ model Agent {
|
|||||||
bookings AgentBooking[]
|
bookings AgentBooking[]
|
||||||
shifts AgentShift[]
|
shifts AgentShift[]
|
||||||
commissions AgentCommission[]
|
commissions AgentCommission[]
|
||||||
|
|
||||||
@@schema("passenger")
|
@@schema("passenger")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1117,7 +1084,6 @@ model AgentBooking {
|
|||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
agent Agent @relation(fields: [agentId], references: [id])
|
agent Agent @relation(fields: [agentId], references: [id])
|
||||||
booking Booking @relation(fields: [bookingId], references: [id])
|
booking Booking @relation(fields: [bookingId], references: [id])
|
||||||
|
|
||||||
@@schema("passenger")
|
@@schema("passenger")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1177,7 +1143,6 @@ model BookingCancellation {
|
|||||||
processedAt DateTime?
|
processedAt DateTime?
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
booking Booking @relation(fields: [bookingId], references: [id])
|
booking Booking @relation(fields: [bookingId], references: [id])
|
||||||
|
|
||||||
@@schema("passenger")
|
@@schema("passenger")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1205,7 +1170,6 @@ model BaggageAllowance {
|
|||||||
excessFeePerKg Int
|
excessFeePerKg Int
|
||||||
currency String @default("ETB")
|
currency String @default("ETB")
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
|
|
||||||
@@schema("passenger")
|
@@schema("passenger")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1249,7 +1213,6 @@ model NotificationTemplate {
|
|||||||
bodyTemplate String
|
bodyTemplate String
|
||||||
active Boolean @default(true)
|
active Boolean @default(true)
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
|
|
||||||
@@schema("passenger")
|
@@schema("passenger")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1288,7 +1251,6 @@ model FraudRule {
|
|||||||
config Json?
|
config Json?
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
updatedAt DateTime @updatedAt
|
updatedAt DateTime @updatedAt
|
||||||
|
|
||||||
@@schema("passenger")
|
@@schema("passenger")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -518,7 +518,7 @@ async function seedSegmentFares() {
|
|||||||
include: { stops: { orderBy: { sequence: 'asc' } } },
|
include: { stops: { orderBy: { sequence: 'asc' } } },
|
||||||
});
|
});
|
||||||
const seatClasses = await prisma.seatClass.findMany();
|
const seatClasses = await prisma.seatClass.findMany();
|
||||||
const validFrom = new Date('2024-01-01');
|
const validFrom = new Date('2026-01-01');
|
||||||
|
|
||||||
if (route && route.stops.length > 2) {
|
if (route && route.stops.length > 2) {
|
||||||
for (const sc of seatClasses) {
|
for (const sc of seatClasses) {
|
||||||
@@ -531,7 +531,7 @@ async function seedSegmentFares() {
|
|||||||
baseFareMinor: Math.floor(sc.baseFareMinor * 0.4),
|
baseFareMinor: Math.floor(sc.baseFareMinor * 0.4),
|
||||||
validFrom,
|
validFrom,
|
||||||
},
|
},
|
||||||
}).catch(() => {});
|
}).catch(() => { });
|
||||||
|
|
||||||
await prisma.segmentFareRule.create({
|
await prisma.segmentFareRule.create({
|
||||||
data: {
|
data: {
|
||||||
@@ -542,7 +542,7 @@ async function seedSegmentFares() {
|
|||||||
baseFareMinor: Math.floor(sc.baseFareMinor * 0.6),
|
baseFareMinor: Math.floor(sc.baseFareMinor * 0.6),
|
||||||
validFrom,
|
validFrom,
|
||||||
},
|
},
|
||||||
}).catch(() => {});
|
}).catch(() => { });
|
||||||
}
|
}
|
||||||
console.log(` ✅ ${seatClasses.length * 2} segment fare rules created`);
|
console.log(` ✅ ${seatClasses.length * 2} segment fare rules created`);
|
||||||
}
|
}
|
||||||
@@ -589,13 +589,13 @@ async function seedMenuAndFood() {
|
|||||||
|
|
||||||
await prisma.menuItem.create({
|
await prisma.menuItem.create({
|
||||||
data: { id: coffeeId, scheduleId: schedule.id, categoryId: beverages.id, name: 'Ethiopian Coffee', priceMinor: 50 },
|
data: { id: coffeeId, scheduleId: schedule.id, categoryId: beverages.id, name: 'Ethiopian Coffee', priceMinor: 50 },
|
||||||
}).catch(() => {}); // ignore if exists
|
}).catch(() => { }); // ignore if exists
|
||||||
await prisma.menuItem.create({
|
await prisma.menuItem.create({
|
||||||
data: { id: juiceId, scheduleId: schedule.id, categoryId: beverages.id, name: 'Fresh Juice', priceMinor: 35 },
|
data: { id: juiceId, scheduleId: schedule.id, categoryId: beverages.id, name: 'Fresh Juice', priceMinor: 35 },
|
||||||
}).catch(() => {}); // ignore if exists
|
}).catch(() => { }); // ignore if exists
|
||||||
await prisma.menuItem.create({
|
await prisma.menuItem.create({
|
||||||
data: { id: sandwichId, scheduleId: schedule.id, categoryId: snacks.id, name: 'Sandwich', priceMinor: 80 },
|
data: { id: sandwichId, scheduleId: schedule.id, categoryId: snacks.id, name: 'Sandwich', priceMinor: 80 },
|
||||||
}).catch(() => {}); // ignore if exists
|
}).catch(() => { }); // ignore if exists
|
||||||
}
|
}
|
||||||
console.log(` ✅ Menu categories and items created`);
|
console.log(` ✅ Menu categories and items created`);
|
||||||
}
|
}
|
||||||
@@ -682,6 +682,9 @@ async function main() {
|
|||||||
|
|
||||||
const steps: Array<[string, () => Promise<unknown>]> = [
|
const steps: Array<[string, () => Promise<unknown>]> = [
|
||||||
['system users', seedSystemUsers],
|
['system users', seedSystemUsers],
|
||||||
|
['fare rules', seedFareRules],
|
||||||
|
['segment fares', seedSegmentFares],
|
||||||
|
['currency', seedCurrency]
|
||||||
];
|
];
|
||||||
|
|
||||||
let failed = 0;
|
let failed = 0;
|
||||||
|
|||||||
@@ -47,6 +47,9 @@ export class FareCalculateDto {
|
|||||||
|
|
||||||
@ApiPropertyOptional({ example: 'WEEKEND15', description: 'Promo code for discount' })
|
@ApiPropertyOptional({ example: 'WEEKEND15', description: 'Promo code for discount' })
|
||||||
@IsOptional() @IsString() promoCode?: string;
|
@IsOptional() @IsString() promoCode?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ example: 'schedule-uuid', description: 'Schedule UUID — used to match schedule-scoped FareRules first' })
|
||||||
|
@IsOptional() @IsString() scheduleId?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class FareBreakdownDto {
|
export class FareBreakdownDto {
|
||||||
|
|||||||
@@ -32,20 +32,59 @@ export class FareEngineService {
|
|||||||
s => s.sequence > originStop.sequence && s.sequence <= destStop.sequence,
|
s => s.sequence > originStop.sequence && s.sequence <= destStop.sequence,
|
||||||
);
|
);
|
||||||
|
|
||||||
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(', ')}`,
|
|
||||||
);
|
|
||||||
|
|
||||||
const totalDistanceKm = legStops.reduce((sum, s) => sum + (s.distanceKm ?? 0), 0);
|
|
||||||
|
|
||||||
const seatClass = await this.prisma.seatClass.findUnique({ where: { id: dto.seatClassId } });
|
const seatClass = await this.prisma.seatClass.findUnique({ where: { id: dto.seatClassId } });
|
||||||
if (!seatClass) throw new NotFoundException('Seat class not found');
|
if (!seatClass) throw new NotFoundException('Seat class not found');
|
||||||
if (!seatClass.isActive) throw new BadRequestException('Seat class is not active');
|
if (!seatClass.isActive) throw new BadRequestException('Seat class is not active');
|
||||||
|
|
||||||
const ratePerKmMinor = seatClass.baseFareMinor;
|
// Resolve fare: FareRule (schedule-scoped → route-scoped) takes precedence over distance×rate
|
||||||
const baseFarePerPassengerMinor = totalDistanceKm * ratePerKmMinor;
|
const now = new Date();
|
||||||
|
const [originStation, destStation] = await Promise.all([
|
||||||
|
this.prisma.station.findUnique({ where: { id: dto.originStationId } }),
|
||||||
|
this.prisma.station.findUnique({ where: { id: dto.destinationStationId } }),
|
||||||
|
]);
|
||||||
|
const segmentRoute = originStation && destStation
|
||||||
|
? `${originStation.code}-${destStation.code}` : null;
|
||||||
|
const fullRoute = `${route.code}`;
|
||||||
|
|
||||||
|
const fareRuleCandidates = await this.prisma.fareRule.findMany({
|
||||||
|
where: {
|
||||||
|
seatClassId: dto.seatClassId,
|
||||||
|
validFrom: { lte: now },
|
||||||
|
OR: [{ validUntil: null }, { validUntil: { gte: now } }],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const fareRule = this.pickBestFareRule(
|
||||||
|
fareRuleCandidates,
|
||||||
|
dto.scheduleId,
|
||||||
|
segmentRoute,
|
||||||
|
fullRoute,
|
||||||
|
dto.nationality,
|
||||||
|
);
|
||||||
|
|
||||||
|
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';
|
||||||
|
}
|
||||||
|
|
||||||
// Premium and insurance fees applied per passenger
|
// Premium and insurance fees applied per passenger
|
||||||
const premiumPerPassenger = seatClass.premiumMinor ?? 0;
|
const premiumPerPassenger = seatClass.premiumMinor ?? 0;
|
||||||
@@ -84,11 +123,6 @@ export class FareEngineService {
|
|||||||
const exchangeRate = await this.currencyService.getExchangeRate(Currency.ETB, billingCurrency);
|
const exchangeRate = await this.currencyService.getExchangeRate(Currency.ETB, billingCurrency);
|
||||||
const totalInBillingCurrency = Math.round(totalEtbMinor * exchangeRate);
|
const totalInBillingCurrency = Math.round(totalEtbMinor * exchangeRate);
|
||||||
|
|
||||||
const [originStation, destStation] = await Promise.all([
|
|
||||||
this.prisma.station.findUnique({ where: { id: dto.originStationId } }),
|
|
||||||
this.prisma.station.findUnique({ where: { id: dto.destinationStationId } }),
|
|
||||||
]);
|
|
||||||
|
|
||||||
const calculation = [
|
const calculation = [
|
||||||
`Distance: ${totalDistanceKm} km (${originStation?.name} → ${destStation?.name})`,
|
`Distance: ${totalDistanceKm} km (${originStation?.name} → ${destStation?.name})`,
|
||||||
`Rate per km: ${ratePerKmMinor} ETB minor (${seatClass.name})`,
|
`Rate per km: ${ratePerKmMinor} ETB minor (${seatClass.name})`,
|
||||||
@@ -110,9 +144,11 @@ export class FareEngineService {
|
|||||||
`Nationality: ${dto.nationality ?? 'unspecified'} → ${billingCurrency}`,
|
`Nationality: ${dto.nationality ?? 'unspecified'} → ${billingCurrency}`,
|
||||||
`Exchange rate: 1 ETB = ${exchangeRate} ${billingCurrency}`,
|
`Exchange rate: 1 ETB = ${exchangeRate} ${billingCurrency}`,
|
||||||
`Total (${billingCurrency}): ${totalInBillingCurrency} ${billingCurrency} minor`,
|
`Total (${billingCurrency}): ${totalInBillingCurrency} ${billingCurrency} minor`,
|
||||||
|
`Fare source: ${fareSource}`,
|
||||||
].join('\n');
|
].join('\n');
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
fareSource,
|
||||||
routeCode: route.code,
|
routeCode: route.code,
|
||||||
originName: originStation?.name ?? dto.originStationId,
|
originName: originStation?.name ?? dto.originStationId,
|
||||||
destinationName: destStation?.name ?? dto.destinationStationId,
|
destinationName: destStation?.name ?? dto.destinationStationId,
|
||||||
@@ -161,6 +197,37 @@ export class FareEngineService {
|
|||||||
return results.filter(Boolean);
|
return results.filter(Boolean);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private pickBestFareRule(
|
||||||
|
candidates: any[],
|
||||||
|
scheduleId?: string,
|
||||||
|
segmentRoute?: string | null,
|
||||||
|
fullRoute?: string,
|
||||||
|
nationality?: string,
|
||||||
|
): any | null {
|
||||||
|
const nat = nationality ?? null;
|
||||||
|
const priorities = [
|
||||||
|
{ tripId: scheduleId, route: segmentRoute, nationality: nat },
|
||||||
|
{ tripId: scheduleId, route: segmentRoute, nationality: null },
|
||||||
|
{ tripId: scheduleId, route: fullRoute, nationality: nat },
|
||||||
|
{ tripId: scheduleId, route: fullRoute, nationality: null },
|
||||||
|
{ tripId: scheduleId, route: null, nationality: nat },
|
||||||
|
{ tripId: scheduleId, route: null, nationality: null },
|
||||||
|
{ tripId: null, route: segmentRoute, nationality: nat },
|
||||||
|
{ tripId: null, route: segmentRoute, nationality: null },
|
||||||
|
{ tripId: null, route: fullRoute, nationality: nat },
|
||||||
|
{ tripId: null, route: fullRoute, nationality: null },
|
||||||
|
{ tripId: null, route: null, nationality: nat },
|
||||||
|
{ tripId: null, route: null, nationality: null },
|
||||||
|
];
|
||||||
|
for (const p of priorities) {
|
||||||
|
const match = candidates.find(
|
||||||
|
c => c.tripId === p.tripId && c.route === p.route && c.nationality === p.nationality,
|
||||||
|
);
|
||||||
|
if (match) return match;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
async calculateForSchedule(scheduleId: string, seatClassId: string, nationality?: string) {
|
async calculateForSchedule(scheduleId: string, seatClassId: string, nationality?: string) {
|
||||||
const schedule = await this.prisma.trainSchedule.findUnique({
|
const schedule = await this.prisma.trainSchedule.findUnique({
|
||||||
where: { id: scheduleId },
|
where: { id: scheduleId },
|
||||||
@@ -175,6 +242,7 @@ export class FareEngineService {
|
|||||||
destinationStationId: schedule.destinationStationId,
|
destinationStationId: schedule.destinationStationId,
|
||||||
seatClassId,
|
seatClassId,
|
||||||
nationality,
|
nationality,
|
||||||
|
scheduleId,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -199,6 +267,7 @@ export class FareEngineService {
|
|||||||
destinationStationId: schedule.destinationStationId,
|
destinationStationId: schedule.destinationStationId,
|
||||||
seatClassId: sc.id,
|
seatClassId: sc.id,
|
||||||
nationality,
|
nationality,
|
||||||
|
scheduleId,
|
||||||
}).catch(() => null),
|
}).catch(() => null),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -12,34 +12,22 @@ export class SchedulesController {
|
|||||||
|
|
||||||
@Post('bulk-generate')
|
@Post('bulk-generate')
|
||||||
@UseGuards(JwtGuard) @ApiBearerAuth('JWT-auth')
|
@UseGuards(JwtGuard) @ApiBearerAuth('JWT-auth')
|
||||||
@ApiOperation({
|
@ApiOperation({ summary: 'Bulk generate repetitive schedules' })
|
||||||
summary: 'Bulk generate repetitive schedules',
|
|
||||||
description: 'Creates multiple schedules automatically by repeating every X days for the next Y days. Example: repeat every 2 days for 30 days = 15 schedules.',
|
|
||||||
})
|
|
||||||
@ApiResponse({ status: 201, description: 'Schedules generated successfully' })
|
|
||||||
@ApiResponse({ status: 400, description: 'Invalid parameters or route not found' })
|
|
||||||
bulkGenerateSchedules(@Body() dto: BulkCreateSchedulesDto) {
|
bulkGenerateSchedules(@Body() dto: BulkCreateSchedulesDto) {
|
||||||
return this.service.bulkGenerateSchedules(dto);
|
return this.service.bulkGenerateSchedules(dto);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Post()
|
@Post()
|
||||||
@UseGuards(JwtGuard) @ApiBearerAuth('JWT-auth')
|
@UseGuards(JwtGuard) @ApiBearerAuth('JWT-auth')
|
||||||
@ApiOperation({
|
@ApiOperation({ summary: 'Create a train schedule from a route template' })
|
||||||
summary: 'Create a train schedule from a route template',
|
|
||||||
description: `Creates a schedule by referencing a Route (routeId).\nStops are automatically copied from the route's RouteStop definitions.\nYou supply the actual planned arrival/departure times per stop sequence.\nOrigin and destination are derived from the first and last route stop — no need to specify them manually.`,
|
|
||||||
})
|
|
||||||
@ApiResponse({ status: 201, description: 'Schedule created with stops copied from route template' })
|
|
||||||
@ApiResponse({ status: 400, description: 'Invalid times, inactive route, or missing planned times for some stops' })
|
|
||||||
@ApiResponse({ status: 404, description: 'Train or route not found' })
|
|
||||||
createSchedule(@Body() dto: CreateScheduleDto) { return this.service.createSchedule(dto); }
|
createSchedule(@Body() dto: CreateScheduleDto) { return this.service.createSchedule(dto); }
|
||||||
|
|
||||||
@Get()
|
@Get()
|
||||||
@ApiOperation({ summary: 'List schedules with optional filters' })
|
@ApiOperation({ summary: 'List schedules with optional filters' })
|
||||||
@ApiQuery({ name: 'date', required: false, example: '2026-06-15', description: 'Departure date (YYYY-MM-DD). Returns all schedules departing on this calendar day.' })
|
@ApiQuery({ name: 'date', required: false })
|
||||||
@ApiQuery({ name: 'routeId', required: false, description: 'Filter by route UUID' })
|
@ApiQuery({ name: 'routeId', required: false })
|
||||||
@ApiQuery({ name: 'trainId', required: false, description: 'Filter by train UUID' })
|
@ApiQuery({ name: 'trainId', required: false })
|
||||||
@ApiQuery({ name: 'status', required: false, enum: TripStatus, description: 'Filter by schedule status' })
|
@ApiQuery({ name: 'status', required: false, enum: TripStatus })
|
||||||
@ApiResponse({ status: 200, description: 'Array of schedules ordered by departureAt, each with train, origin/destination, stops, and booking/assignment counts' })
|
|
||||||
listSchedules(
|
listSchedules(
|
||||||
@Query('date') date?: string,
|
@Query('date') date?: string,
|
||||||
@Query('routeId') routeId?: string,
|
@Query('routeId') routeId?: string,
|
||||||
@@ -57,57 +45,63 @@ export class SchedulesController {
|
|||||||
@ApiResponse({ status: 201, description: 'Fare rule created' })
|
@ApiResponse({ status: 201, description: 'Fare rule created' })
|
||||||
createFareRule(@Body() dto: CreateFareRuleDto) { return this.service.createFareRule(dto); }
|
createFareRule(@Body() dto: CreateFareRuleDto) { return this.service.createFareRule(dto); }
|
||||||
|
|
||||||
|
@Patch('fares/:id')
|
||||||
|
@UseGuards(JwtGuard) @ApiBearerAuth('JWT-auth')
|
||||||
|
@ApiOperation({ summary: 'Update a fare rule' })
|
||||||
|
@ApiParam({ name: 'id', description: 'FareRule UUID' })
|
||||||
|
@ApiResponse({ status: 200, description: 'Fare rule updated' })
|
||||||
|
updateFareRule(@Param('id') id: string, @Body() dto: Partial<CreateFareRuleDto>) {
|
||||||
|
return this.service.updateFareRule(id, dto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Delete('fares/:id')
|
||||||
|
@UseGuards(JwtGuard) @ApiBearerAuth('JWT-auth')
|
||||||
|
@ApiOperation({ summary: 'Delete a fare rule' })
|
||||||
|
@ApiParam({ name: 'id', description: 'FareRule UUID' })
|
||||||
|
@ApiResponse({ status: 200, description: 'Fare rule deleted' })
|
||||||
|
deleteFareRule(@Param('id') id: string) { return this.service.deleteFareRule(id); }
|
||||||
|
|
||||||
@Post('segment-fares')
|
@Post('segment-fares')
|
||||||
@UseGuards(JwtGuard) @ApiBearerAuth('JWT-auth')
|
@UseGuards(JwtGuard) @ApiBearerAuth('JWT-auth')
|
||||||
@ApiOperation({ summary: 'Create a segment fare rule (stop-to-stop pricing on a route)' })
|
@ApiOperation({ summary: 'Create a segment fare rule' })
|
||||||
@ApiResponse({ status: 201, description: 'Segment fare rule created' })
|
|
||||||
createSegmentFareRule(@Body() dto: any) { return this.service.createSegmentFareRule(dto); }
|
createSegmentFareRule(@Body() dto: any) { return this.service.createSegmentFareRule(dto); }
|
||||||
|
|
||||||
@Get('routes/:routeId/segment-fares')
|
@Get('routes/:routeId/segment-fares')
|
||||||
@ApiOperation({ summary: 'List all segment fare rules for a route' })
|
@ApiOperation({ summary: 'List all segment fare rules for a route' })
|
||||||
@ApiParam({ name: 'routeId', description: 'Route UUID' })
|
@ApiParam({ name: 'routeId', description: 'Route UUID' })
|
||||||
@ApiResponse({ status: 200, description: 'List of segment fare rules' })
|
|
||||||
getSegmentFares(@Param('routeId') routeId: string) { return this.service.getSegmentFares(routeId); }
|
getSegmentFares(@Param('routeId') routeId: string) { return this.service.getSegmentFares(routeId); }
|
||||||
|
|
||||||
@Patch('segment-fares/:id')
|
@Patch('segment-fares/:id')
|
||||||
@UseGuards(JwtGuard) @ApiBearerAuth('JWT-auth')
|
@UseGuards(JwtGuard) @ApiBearerAuth('JWT-auth')
|
||||||
@ApiOperation({ summary: 'Update a segment fare rule' })
|
@ApiOperation({ summary: 'Update a segment fare rule' })
|
||||||
@ApiParam({ name: 'id', description: 'SegmentFareRule UUID' })
|
@ApiParam({ name: 'id', description: 'SegmentFareRule UUID' })
|
||||||
@ApiResponse({ status: 200, description: 'Segment fare rule updated' })
|
|
||||||
updateSegmentFareRule(@Param('id') id: string, @Body() dto: any) { return this.service.updateSegmentFareRule(id, dto); }
|
updateSegmentFareRule(@Param('id') id: string, @Body() dto: any) { return this.service.updateSegmentFareRule(id, dto); }
|
||||||
|
|
||||||
@Delete('segment-fares/:id')
|
@Delete('segment-fares/:id')
|
||||||
@UseGuards(JwtGuard) @ApiBearerAuth('JWT-auth')
|
@UseGuards(JwtGuard) @ApiBearerAuth('JWT-auth')
|
||||||
@ApiOperation({ summary: 'Delete a segment fare rule' })
|
@ApiOperation({ summary: 'Delete a segment fare rule' })
|
||||||
@ApiParam({ name: 'id', description: 'SegmentFareRule UUID' })
|
@ApiParam({ name: 'id', description: 'SegmentFareRule UUID' })
|
||||||
@ApiResponse({ status: 200, description: 'Segment fare rule deleted' })
|
|
||||||
deleteSegmentFareRule(@Param('id') id: string) { return this.service.deleteSegmentFareRule(id); }
|
deleteSegmentFareRule(@Param('id') id: string) { return this.service.deleteSegmentFareRule(id); }
|
||||||
|
|
||||||
// ===== PARAMETRIZED ROUTES (generic :id routes come AFTER specific routes) =====
|
// ===== PARAMETRIZED ROUTES (generic :id routes come AFTER specific routes) =====
|
||||||
|
|
||||||
@Get(':id')
|
@Get(':id')
|
||||||
@ApiOperation({ summary: 'Get schedule with train, coaches, seats, and stop timeline' })
|
@ApiOperation({ summary: 'Get schedule detail' })
|
||||||
@ApiParam({ name: 'id', description: 'TrainSchedule UUID' })
|
@ApiParam({ name: 'id', description: 'TrainSchedule UUID' })
|
||||||
@ApiResponse({ status: 200, description: 'Full schedule detail including route stops with station info' })
|
|
||||||
@ApiResponse({ status: 404, description: 'Schedule not found' })
|
|
||||||
getSchedule(@Param('id') id: string) { return this.service.getSchedule(id); }
|
getSchedule(@Param('id') id: string) { return this.service.getSchedule(id); }
|
||||||
|
|
||||||
@Patch(':id')
|
@Patch(':id')
|
||||||
@UseGuards(JwtGuard) @ApiBearerAuth('JWT-auth')
|
@UseGuards(JwtGuard) @ApiBearerAuth('JWT-auth')
|
||||||
@ApiOperation({ summary: 'Update a schedule (partial update - times, status, coaches)' })
|
@ApiOperation({ summary: 'Update a schedule (partial)' })
|
||||||
@ApiParam({ name: 'id', description: 'TrainSchedule UUID' })
|
@ApiParam({ name: 'id', description: 'TrainSchedule UUID' })
|
||||||
@ApiResponse({ status: 200, description: 'Schedule updated' })
|
|
||||||
@ApiResponse({ status: 404, description: 'Schedule not found' })
|
|
||||||
updateSchedule(@Param('id') id: string, @Body() dto: UpdateScheduleDto) {
|
updateSchedule(@Param('id') id: string, @Body() dto: UpdateScheduleDto) {
|
||||||
return this.service.updateSchedulePartial(id, dto);
|
return this.service.updateSchedulePartial(id, dto);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Patch(':id/status')
|
@Patch(':id/status')
|
||||||
@UseGuards(JwtGuard) @ApiBearerAuth('JWT-auth')
|
@UseGuards(JwtGuard) @ApiBearerAuth('JWT-auth')
|
||||||
@ApiOperation({ summary: 'Update schedule status (SCHEDULED → BOARDING → EN_ROUTE → ARRIVED)' })
|
@ApiOperation({ summary: 'Update schedule status' })
|
||||||
@ApiParam({ name: 'id', description: 'TrainSchedule UUID' })
|
@ApiParam({ name: 'id', description: 'TrainSchedule UUID' })
|
||||||
@ApiResponse({ status: 200, description: 'Status updated' })
|
|
||||||
@ApiResponse({ status: 404, description: 'Schedule not found' })
|
|
||||||
updateStatus(@Param('id') id: string, @Body() dto: UpdateScheduleStatusDto) {
|
updateStatus(@Param('id') id: string, @Body() dto: UpdateScheduleStatusDto) {
|
||||||
return this.service.updateScheduleStatus(id, dto);
|
return this.service.updateScheduleStatus(id, dto);
|
||||||
}
|
}
|
||||||
@@ -116,26 +110,18 @@ export class SchedulesController {
|
|||||||
@UseGuards(JwtGuard) @ApiBearerAuth('JWT-auth')
|
@UseGuards(JwtGuard) @ApiBearerAuth('JWT-auth')
|
||||||
@ApiOperation({ summary: 'Delete a schedule' })
|
@ApiOperation({ summary: 'Delete a schedule' })
|
||||||
@ApiParam({ name: 'id', description: 'TrainSchedule UUID' })
|
@ApiParam({ name: 'id', description: 'TrainSchedule UUID' })
|
||||||
@ApiResponse({ status: 200, description: 'Schedule deleted' })
|
deleteSchedule(@Param('id') id: string) { return this.service.deleteSchedule(id); }
|
||||||
@ApiResponse({ status: 404, description: 'Schedule not found' })
|
|
||||||
deleteSchedule(@Param('id') id: string) {
|
|
||||||
return this.service.deleteSchedule(id);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Get(':id/stops')
|
@Get(':id/stops')
|
||||||
@ApiOperation({ summary: 'List all stops for a schedule ordered by sequence' })
|
@ApiOperation({ summary: 'List all stops for a schedule' })
|
||||||
@ApiParam({ name: 'id', description: 'TrainSchedule UUID' })
|
@ApiParam({ name: 'id', description: 'TrainSchedule UUID' })
|
||||||
@ApiResponse({ status: 200, description: 'Ordered stop list with station details and planned/actual times' })
|
|
||||||
@ApiResponse({ status: 404, description: 'Schedule not found' })
|
|
||||||
getStops(@Param('id') id: string) { return this.service.getStops(id); }
|
getStops(@Param('id') id: string) { return this.service.getStops(id); }
|
||||||
|
|
||||||
@Patch(':id/stops/:sequence')
|
@Patch(':id/stops/:sequence')
|
||||||
@UseGuards(JwtGuard) @ApiBearerAuth('JWT-auth')
|
@UseGuards(JwtGuard) @ApiBearerAuth('JWT-auth')
|
||||||
@ApiOperation({ summary: 'Update planned times or live status of a specific stop' })
|
@ApiOperation({ summary: 'Update a stop time' })
|
||||||
@ApiParam({ name: 'id', description: 'TrainSchedule UUID' })
|
@ApiParam({ name: 'id', description: 'TrainSchedule UUID' })
|
||||||
@ApiParam({ name: 'sequence', description: 'Stop sequence number' })
|
@ApiParam({ name: 'sequence', description: 'Stop sequence number' })
|
||||||
@ApiResponse({ status: 200, description: 'Stop updated' })
|
|
||||||
@ApiResponse({ status: 404, description: 'Stop not found on schedule' })
|
|
||||||
updateStop(
|
updateStop(
|
||||||
@Param('id') id: string,
|
@Param('id') id: string,
|
||||||
@Param('sequence', ParseIntPipe) sequence: number,
|
@Param('sequence', ParseIntPipe) sequence: number,
|
||||||
@@ -145,19 +131,26 @@ export class SchedulesController {
|
|||||||
@Get(':scheduleId/fares/stored')
|
@Get(':scheduleId/fares/stored')
|
||||||
@ApiOperation({ summary: 'Get stored fare rules for a schedule' })
|
@ApiOperation({ summary: 'Get stored fare rules for a schedule' })
|
||||||
@ApiParam({ name: 'scheduleId', description: 'TrainSchedule UUID' })
|
@ApiParam({ name: 'scheduleId', description: 'TrainSchedule UUID' })
|
||||||
@ApiResponse({ status: 200, description: 'List of stored fare rules with seat class info' })
|
|
||||||
getStoredFares(@Param('scheduleId') scheduleId: string) {
|
getStoredFares(@Param('scheduleId') scheduleId: string) {
|
||||||
return this.service.getFareRules(scheduleId);
|
return this.service.getFareRules(scheduleId);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get(':scheduleId/fares')
|
@Get(':scheduleId/fares/all')
|
||||||
@ApiOperation({ summary: 'Get fare for a schedule and seat class from the fare engine' })
|
@ApiOperation({ summary: 'Get fares for all active seat classes from the fare engine' })
|
||||||
@ApiParam({ name: 'scheduleId', description: 'TrainSchedule UUID' })
|
@ApiParam({ name: 'scheduleId', description: 'TrainSchedule UUID' })
|
||||||
@ApiQuery({ name: 'seatClassId', required: true, description: 'SeatClass UUID' })
|
@ApiQuery({ name: 'nationality', required: false })
|
||||||
@ApiQuery({ name: 'nationality', required: false, description: 'Passenger nationality — determines billing currency (Ethiopian→ETB, Djiboutian→DJF, other→USD)' })
|
getAllFares(
|
||||||
@ApiResponse({ status: 200, description: 'Live fare breakdown from fare engine' })
|
@Param('scheduleId') scheduleId: string,
|
||||||
@ApiResponse({ status: 400, description: 'Schedule has no route or missing distanceKm on stops' })
|
@Query('nationality') nationality?: string,
|
||||||
@ApiResponse({ status: 404, description: 'Schedule or seat class not found' })
|
) {
|
||||||
|
return this.service.getAllFaresFromEngine(scheduleId, nationality);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get(':scheduleId/fares')
|
||||||
|
@ApiOperation({ summary: 'Get fare for a specific seat class from the fare engine' })
|
||||||
|
@ApiParam({ name: 'scheduleId', description: 'TrainSchedule UUID' })
|
||||||
|
@ApiQuery({ name: 'seatClassId', required: true })
|
||||||
|
@ApiQuery({ name: 'nationality', required: false })
|
||||||
getFare(
|
getFare(
|
||||||
@Param('scheduleId') scheduleId: string,
|
@Param('scheduleId') scheduleId: string,
|
||||||
@Query('seatClassId') seatClassId: string,
|
@Query('seatClassId') seatClassId: string,
|
||||||
@@ -166,42 +159,15 @@ export class SchedulesController {
|
|||||||
return this.service.getFareFromEngine(scheduleId, seatClassId, nationality);
|
return this.service.getFareFromEngine(scheduleId, seatClassId, nationality);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get(':scheduleId/fares/all')
|
|
||||||
@ApiOperation({ summary: 'Get fares for all active seat classes on a schedule' })
|
|
||||||
@ApiParam({ name: 'scheduleId', description: 'TrainSchedule UUID' })
|
|
||||||
@ApiQuery({ name: 'nationality', required: false, description: 'Passenger nationality — determines billing currency' })
|
|
||||||
@ApiResponse({ status: 200, description: 'Array of fare breakdowns for every active seat class, ordered by price ascending' })
|
|
||||||
@ApiResponse({ status: 400, description: 'Schedule has no route or missing distanceKm on stops' })
|
|
||||||
@ApiResponse({ status: 404, description: 'Schedule not found' })
|
|
||||||
getAllFares(
|
|
||||||
@Param('scheduleId') scheduleId: string,
|
|
||||||
@Query('nationality') nationality?: string,
|
|
||||||
) {
|
|
||||||
return this.service.getAllFaresFromEngine(scheduleId, nationality);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Post(':id/fares/sync')
|
@Post(':id/fares/sync')
|
||||||
@ApiOperation({
|
@ApiOperation({ summary: 'Sync fares from fare engine' })
|
||||||
summary: 'Sync fares from fare engine',
|
|
||||||
description: 'Recalculates fares for all active seat classes using the fare engine (km × ratePerKm + tax) and upserts them as FareRule records scoped to this schedule. Previous active rules are expired.',
|
|
||||||
})
|
|
||||||
@ApiParam({ name: 'id', description: 'TrainSchedule UUID' })
|
@ApiParam({ name: 'id', description: 'TrainSchedule UUID' })
|
||||||
@ApiResponse({ status: 201, description: 'Fares synced — returns count of synced rules and any errors' })
|
syncFares(@Param('id') id: string) { return this.service.syncFaresFromEngine(id); }
|
||||||
@ApiResponse({ status: 400, description: 'Schedule has no associated route or missing distanceKm on stops' })
|
|
||||||
@ApiResponse({ status: 404, description: 'Schedule not found' })
|
|
||||||
syncFares(@Param('id') id: string) {
|
|
||||||
return this.service.syncFaresFromEngine(id);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Post(':id/coaches')
|
@Post(':id/coaches')
|
||||||
@UseGuards(JwtGuard) @ApiBearerAuth('JWT-auth')
|
@UseGuards(JwtGuard) @ApiBearerAuth('JWT-auth')
|
||||||
@ApiOperation({
|
@ApiOperation({ summary: 'Assign coaches to a schedule' })
|
||||||
summary: 'Assign coaches to a schedule',
|
|
||||||
description: 'Assigns selected coaches to a schedule with their position numbers. Replaces any existing coach assignments.'
|
|
||||||
})
|
|
||||||
@ApiParam({ name: 'id', description: 'TrainSchedule UUID' })
|
@ApiParam({ name: 'id', description: 'TrainSchedule UUID' })
|
||||||
@ApiResponse({ status: 201, description: 'Coaches assigned successfully' })
|
|
||||||
@ApiResponse({ status: 404, description: 'Schedule or coach not found' })
|
|
||||||
assignCoaches(
|
assignCoaches(
|
||||||
@Param('id') id: string,
|
@Param('id') id: string,
|
||||||
@Body() dto: { coaches: Array<{ coachId: string; positionNumber: number }> },
|
@Body() dto: { coaches: Array<{ coachId: string; positionNumber: number }> },
|
||||||
@@ -212,21 +178,14 @@ export class SchedulesController {
|
|||||||
@Get(':id/coaches')
|
@Get(':id/coaches')
|
||||||
@ApiOperation({ summary: 'Get assigned coaches for a schedule' })
|
@ApiOperation({ summary: 'Get assigned coaches for a schedule' })
|
||||||
@ApiParam({ name: 'id', description: 'TrainSchedule UUID' })
|
@ApiParam({ name: 'id', description: 'TrainSchedule UUID' })
|
||||||
@ApiResponse({ status: 200, description: 'List of assigned coaches with seat details' })
|
getAssignedCoaches(@Param('id') id: string) { return this.service.getAssignedCoaches(id); }
|
||||||
getAssignedCoaches(@Param('id') id: string) {
|
|
||||||
return this.service.getAssignedCoaches(id);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Delete(':id/coaches/:coachId')
|
@Delete(':id/coaches/:coachId')
|
||||||
@UseGuards(JwtGuard) @ApiBearerAuth('JWT-auth')
|
@UseGuards(JwtGuard) @ApiBearerAuth('JWT-auth')
|
||||||
@ApiOperation({ summary: 'Remove a coach assignment from a schedule' })
|
@ApiOperation({ summary: 'Remove a coach assignment' })
|
||||||
@ApiParam({ name: 'id', description: 'TrainSchedule UUID' })
|
@ApiParam({ name: 'id', description: 'TrainSchedule UUID' })
|
||||||
@ApiParam({ name: 'coachId', description: 'Coach UUID' })
|
@ApiParam({ name: 'coachId', description: 'Coach UUID' })
|
||||||
@ApiResponse({ status: 200, description: 'Coach assignment removed' })
|
removeCoachAssignment(@Param('id') id: string, @Param('coachId') coachId: string) {
|
||||||
removeCoachAssignment(
|
|
||||||
@Param('id') id: string,
|
|
||||||
@Param('coachId') coachId: string,
|
|
||||||
) {
|
|
||||||
return this.service.removeCoachAssignment(id, coachId);
|
return this.service.removeCoachAssignment(id, coachId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,7 +18,6 @@ export class SchedulesService {
|
|||||||
const errors: string[] = [];
|
const errors: string[] = [];
|
||||||
const scheduleIds: string[] = [];
|
const scheduleIds: string[] = [];
|
||||||
|
|
||||||
// Validate route and get stops for plannedTimes generation
|
|
||||||
const route = await this.prisma.route.findUnique({
|
const route = await this.prisma.route.findUnique({
|
||||||
where: { id: dto.routeId },
|
where: { id: dto.routeId },
|
||||||
include: { stops: { orderBy: { sequence: 'asc' } } },
|
include: { stops: { orderBy: { sequence: 'asc' } } },
|
||||||
@@ -45,7 +44,6 @@ export class SchedulesService {
|
|||||||
const schedule = await this.createSchedule(createDto);
|
const schedule = await this.createSchedule(createDto);
|
||||||
scheduleIds.push(schedule.id);
|
scheduleIds.push(schedule.id);
|
||||||
|
|
||||||
// Assign coaches if provided
|
|
||||||
if (dto.coachIds && dto.coachIds.length > 0) {
|
if (dto.coachIds && dto.coachIds.length > 0) {
|
||||||
await this.assignCoaches(
|
await this.assignCoaches(
|
||||||
schedule.id,
|
schedule.id,
|
||||||
@@ -58,15 +56,10 @@ export class SchedulesService {
|
|||||||
errors.push(`Failed to create schedule for ${currentDate.toISOString()}: ${error instanceof Error ? error.message : String(error)}`);
|
errors.push(`Failed to create schedule for ${currentDate.toISOString()}: ${error instanceof Error ? error.message : String(error)}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Move to next repetition
|
|
||||||
currentDate = new Date(currentDate.getTime() + dto.repeatEveryDays * 24 * 60 * 60 * 1000);
|
currentDate = new Date(currentDate.getTime() + dto.repeatEveryDays * 24 * 60 * 60 * 1000);
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return { schedulesCreated: scheduleCount, errors, scheduleIds };
|
||||||
schedulesCreated: scheduleCount,
|
|
||||||
errors,
|
|
||||||
scheduleIds,
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async listSchedules(dto: ListSchedulesDto) {
|
async listSchedules(dto: ListSchedulesDto) {
|
||||||
@@ -104,7 +97,6 @@ export class SchedulesService {
|
|||||||
const arr = new Date(dto.arrivalAt);
|
const arr = new Date(dto.arrivalAt);
|
||||||
if (arr <= dep) throw new BadRequestException('arrivalAt must be after departureAt');
|
if (arr <= dep) throw new BadRequestException('arrivalAt must be after departureAt');
|
||||||
|
|
||||||
// Validate route exists and has stops
|
|
||||||
const route = await this.prisma.route.findUnique({
|
const route = await this.prisma.route.findUnique({
|
||||||
where: { id: dto.routeId },
|
where: { id: dto.routeId },
|
||||||
include: { stops: { orderBy: { sequence: 'asc' } } },
|
include: { stops: { orderBy: { sequence: 'asc' } } },
|
||||||
@@ -113,21 +105,13 @@ export class SchedulesService {
|
|||||||
if (!route.active) throw new BadRequestException('Route is not active');
|
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');
|
if (route.stops.length < 2) throw new BadRequestException('Route must have at least 2 stops');
|
||||||
|
|
||||||
// Check for duplicate schedule with same train, route, and date
|
|
||||||
const depDate = new Date(dep);
|
const depDate = new Date(dep);
|
||||||
depDate.setHours(0, 0, 0, 0);
|
depDate.setHours(0, 0, 0, 0);
|
||||||
const nextDay = new Date(depDate);
|
const nextDay = new Date(depDate);
|
||||||
nextDay.setDate(nextDay.getDate() + 1);
|
nextDay.setDate(nextDay.getDate() + 1);
|
||||||
|
|
||||||
const existingSchedule = await this.prisma.trainSchedule.findFirst({
|
const existingSchedule = await this.prisma.trainSchedule.findFirst({
|
||||||
where: {
|
where: { trainId: dto.trainId, routeId: dto.routeId, departureAt: { gte: depDate, lt: nextDay } },
|
||||||
trainId: dto.trainId,
|
|
||||||
routeId: dto.routeId,
|
|
||||||
departureAt: {
|
|
||||||
gte: depDate,
|
|
||||||
lt: nextDay,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
|
||||||
if (existingSchedule) {
|
if (existingSchedule) {
|
||||||
@@ -136,7 +120,6 @@ export class SchedulesService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Auto-generate plannedTimes if not provided or empty
|
|
||||||
let plannedTimes = dto.plannedTimes;
|
let plannedTimes = dto.plannedTimes;
|
||||||
if (!plannedTimes || plannedTimes.length === 0) {
|
if (!plannedTimes || plannedTimes.length === 0) {
|
||||||
const totalDuration = arr.getTime() - dep.getTime();
|
const totalDuration = arr.getTime() - dep.getTime();
|
||||||
@@ -144,7 +127,6 @@ export class SchedulesService {
|
|||||||
|
|
||||||
plannedTimes = route.stops.map((stop, index) => {
|
plannedTimes = route.stops.map((stop, index) => {
|
||||||
let stopTime: Date;
|
let stopTime: Date;
|
||||||
|
|
||||||
if (index === 0) {
|
if (index === 0) {
|
||||||
stopTime = dep;
|
stopTime = dep;
|
||||||
} else if (index === route.stops.length - 1) {
|
} else if (index === route.stops.length - 1) {
|
||||||
@@ -154,7 +136,6 @@ export class SchedulesService {
|
|||||||
const progress = totalDistance > 0 ? stopDistance / totalDistance : index / (route.stops.length - 1);
|
const progress = totalDistance > 0 ? stopDistance / totalDistance : index / (route.stops.length - 1);
|
||||||
stopTime = new Date(dep.getTime() + totalDuration * progress);
|
stopTime = new Date(dep.getTime() + totalDuration * progress);
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
sequence: stop.sequence,
|
sequence: stop.sequence,
|
||||||
plannedArrivalAt: index === 0 ? undefined : stopTime.toISOString(),
|
plannedArrivalAt: index === 0 ? undefined : stopTime.toISOString(),
|
||||||
@@ -163,14 +144,12 @@ export class SchedulesService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validate all route stop sequences are covered by plannedTimes
|
|
||||||
const providedSeqs = new Set(plannedTimes.map(t => t.sequence));
|
const providedSeqs = new Set(plannedTimes.map(t => t.sequence));
|
||||||
const missingSeqs = route.stops.map(s => s.sequence).filter(seq => !providedSeqs.has(seq));
|
const missingSeqs = route.stops.map(s => s.sequence).filter(seq => !providedSeqs.has(seq));
|
||||||
if (missingSeqs.length > 0) {
|
if (missingSeqs.length > 0) {
|
||||||
throw new BadRequestException(`Missing planned times for stop sequences: ${missingSeqs.join(', ')}`);
|
throw new BadRequestException(`Missing planned times for stop sequences: ${missingSeqs.join(', ')}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Derive origin and destination from first and last route stop
|
|
||||||
const firstStop = route.stops[0];
|
const firstStop = route.stops[0];
|
||||||
const lastStop = route.stops[route.stops.length - 1];
|
const lastStop = route.stops[route.stops.length - 1];
|
||||||
|
|
||||||
@@ -188,9 +167,7 @@ export class SchedulesService {
|
|||||||
include: { train: true, originStation: true, destinationStation: true },
|
include: { train: true, originStation: true, destinationStation: true },
|
||||||
});
|
});
|
||||||
|
|
||||||
const plannedTimesMap = Object.fromEntries(
|
const plannedTimesMap = Object.fromEntries(plannedTimes.map(t => [t.sequence, t]));
|
||||||
plannedTimes.map(t => [t.sequence, t]),
|
|
||||||
);
|
|
||||||
await this.routesService.applyRouteToSchedule(dto.routeId, schedule.id, plannedTimesMap);
|
await this.routesService.applyRouteToSchedule(dto.routeId, schedule.id, plannedTimesMap);
|
||||||
|
|
||||||
return this.getSchedule(schedule.id);
|
return this.getSchedule(schedule.id);
|
||||||
@@ -230,10 +207,7 @@ export class SchedulesService {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private async resolveEffectiveStatuses(
|
private async resolveEffectiveStatuses(scheduleId: string, seatIds: string[]): Promise<Map<string, string>> {
|
||||||
scheduleId: string,
|
|
||||||
seatIds: string[],
|
|
||||||
): Promise<Map<string, string>> {
|
|
||||||
const statusMap = new Map<string, string>();
|
const statusMap = new Map<string, string>();
|
||||||
if (seatIds.length === 0) return statusMap;
|
if (seatIds.length === 0) return statusMap;
|
||||||
|
|
||||||
@@ -304,7 +278,6 @@ export class SchedulesService {
|
|||||||
|
|
||||||
plannedTimes = route.stops.map((stop, index) => {
|
plannedTimes = route.stops.map((stop, index) => {
|
||||||
let stopTime: Date;
|
let stopTime: Date;
|
||||||
|
|
||||||
if (index === 0) {
|
if (index === 0) {
|
||||||
stopTime = dep;
|
stopTime = dep;
|
||||||
} else if (index === route.stops.length - 1) {
|
} else if (index === route.stops.length - 1) {
|
||||||
@@ -314,7 +287,6 @@ export class SchedulesService {
|
|||||||
const progress = totalDistance > 0 ? stopDistance / totalDistance : index / (route.stops.length - 1);
|
const progress = totalDistance > 0 ? stopDistance / totalDistance : index / (route.stops.length - 1);
|
||||||
stopTime = new Date(dep.getTime() + totalDuration * progress);
|
stopTime = new Date(dep.getTime() + totalDuration * progress);
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
sequence: stop.sequence,
|
sequence: stop.sequence,
|
||||||
plannedArrivalAt: index === 0 ? undefined : stopTime.toISOString(),
|
plannedArrivalAt: index === 0 ? undefined : stopTime.toISOString(),
|
||||||
@@ -323,9 +295,7 @@ export class SchedulesService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const plannedTimesMap = Object.fromEntries(
|
const plannedTimesMap = Object.fromEntries(plannedTimes.map(t => [t.sequence, t]));
|
||||||
plannedTimes.map(t => [t.sequence, t]),
|
|
||||||
);
|
|
||||||
await this.routesService.applyRouteToSchedule(dto.routeId, id, plannedTimesMap);
|
await this.routesService.applyRouteToSchedule(dto.routeId, id, plannedTimesMap);
|
||||||
|
|
||||||
return this.getSchedule(id);
|
return this.getSchedule(id);
|
||||||
@@ -376,9 +346,35 @@ export class SchedulesService {
|
|||||||
validFrom: new Date(validFrom),
|
validFrom: new Date(validFrom),
|
||||||
validUntil: validUntil ? new Date(validUntil) : null,
|
validUntil: validUntil ? new Date(validUntil) : null,
|
||||||
},
|
},
|
||||||
|
include: { seatClass: true },
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async updateFareRule(id: string, dto: Partial<CreateFareRuleDto>) {
|
||||||
|
const existing = await this.prisma.fareRule.findUnique({ where: { id } });
|
||||||
|
if (!existing) throw new NotFoundException('Fare rule not found');
|
||||||
|
|
||||||
|
const { validFrom, validUntil, scheduleId, nationality, passengerCategory, ...rest } = dto;
|
||||||
|
return this.prisma.fareRule.update({
|
||||||
|
where: { id },
|
||||||
|
data: {
|
||||||
|
...rest,
|
||||||
|
...(scheduleId !== undefined && { tripId: scheduleId }),
|
||||||
|
...(nationality !== undefined && { nationality }),
|
||||||
|
...(validFrom && { validFrom: new Date(validFrom) }),
|
||||||
|
...(validUntil !== undefined && { validUntil: validUntil ? new Date(validUntil) : null }),
|
||||||
|
},
|
||||||
|
include: { seatClass: true },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteFareRule(id: string) {
|
||||||
|
const existing = await this.prisma.fareRule.findUnique({ where: { id } });
|
||||||
|
if (!existing) throw new NotFoundException('Fare rule not found');
|
||||||
|
await this.prisma.fareRule.delete({ where: { id } });
|
||||||
|
return { deleted: true, id };
|
||||||
|
}
|
||||||
|
|
||||||
createSegmentFareRule(dto: any) {
|
createSegmentFareRule(dto: any) {
|
||||||
const { validFrom, validUntil, passengerCategory, ...rest } = dto;
|
const { validFrom, validUntil, passengerCategory, ...rest } = dto;
|
||||||
return this.prisma.segmentFareRule.create({
|
return this.prisma.segmentFareRule.create({
|
||||||
@@ -419,7 +415,6 @@ export class SchedulesService {
|
|||||||
async getFareRules(scheduleId?: string) {
|
async getFareRules(scheduleId?: string) {
|
||||||
const where: any = {};
|
const where: any = {};
|
||||||
if (scheduleId) where.tripId = scheduleId;
|
if (scheduleId) where.tripId = scheduleId;
|
||||||
|
|
||||||
return this.prisma.fareRule.findMany({
|
return this.prisma.fareRule.findMany({
|
||||||
where,
|
where,
|
||||||
include: { seatClass: true },
|
include: { seatClass: true },
|
||||||
@@ -439,11 +434,10 @@ export class SchedulesService {
|
|||||||
});
|
});
|
||||||
if (!schedule) throw new NotFoundException('Schedule not found');
|
if (!schedule) throw new NotFoundException('Schedule not found');
|
||||||
if (!schedule.routeId) throw new BadRequestException('Schedule has no associated route');
|
if (!schedule.routeId) throw new BadRequestException('Schedule has no associated route');
|
||||||
|
|
||||||
return await this.fareEngine.calculateAllForSchedule(scheduleId, nationality);
|
return await this.fareEngine.calculateAllForSchedule(scheduleId, nationality);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw new BadRequestException(
|
throw new BadRequestException(
|
||||||
error instanceof Error ? error.message : 'Failed to calculate fares for schedule'
|
error instanceof Error ? error.message : 'Failed to calculate fares for schedule',
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -483,20 +477,13 @@ export class SchedulesService {
|
|||||||
return { synced, errors };
|
return { synced, errors };
|
||||||
}
|
}
|
||||||
|
|
||||||
async assignCoaches(
|
async assignCoaches(scheduleId: string, coaches: Array<{ coachId: string; positionNumber: number }>) {
|
||||||
scheduleId: string,
|
|
||||||
coaches: Array<{ coachId: string; positionNumber: number }>,
|
|
||||||
) {
|
|
||||||
const schedule = await this.prisma.trainSchedule.findUnique({ where: { id: scheduleId } });
|
const schedule = await this.prisma.trainSchedule.findUnique({ where: { id: scheduleId } });
|
||||||
if (!schedule) throw new NotFoundException('Schedule not found');
|
if (!schedule) throw new NotFoundException('Schedule not found');
|
||||||
|
|
||||||
const coachIds = coaches.map(c => c.coachId);
|
const coachIds = coaches.map(c => c.coachId);
|
||||||
const existingCoaches = await this.prisma.coach.findMany({
|
const existingCoaches = await this.prisma.coach.findMany({ where: { id: { in: coachIds } } });
|
||||||
where: { id: { in: coachIds } },
|
if (existingCoaches.length !== coachIds.length) throw new NotFoundException('One or more coaches not found');
|
||||||
});
|
|
||||||
if (existingCoaches.length !== coachIds.length) {
|
|
||||||
throw new NotFoundException('One or more coaches not found');
|
|
||||||
}
|
|
||||||
|
|
||||||
await this.prisma.coachAssignment.deleteMany({ where: { scheduleId } });
|
await this.prisma.coachAssignment.deleteMany({ where: { scheduleId } });
|
||||||
|
|
||||||
@@ -508,20 +495,13 @@ export class SchedulesService {
|
|||||||
}));
|
}));
|
||||||
|
|
||||||
await this.prisma.coachAssignment.createMany({ data });
|
await this.prisma.coachAssignment.createMany({ data });
|
||||||
|
|
||||||
return { message: 'Coaches assigned successfully', count: coaches.length };
|
return { message: 'Coaches assigned successfully', count: coaches.length };
|
||||||
}
|
}
|
||||||
|
|
||||||
async getAssignedCoaches(scheduleId: string) {
|
async getAssignedCoaches(scheduleId: string) {
|
||||||
return this.prisma.coachAssignment.findMany({
|
return this.prisma.coachAssignment.findMany({
|
||||||
where: { scheduleId },
|
where: { scheduleId },
|
||||||
include: {
|
include: { coach: { include: { seats: { orderBy: [{ row: 'asc' }, { col: 'asc' }] } } } },
|
||||||
coach: {
|
|
||||||
include: {
|
|
||||||
seats: { orderBy: [{ row: 'asc' }, { col: 'asc' }] },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
orderBy: { positionNumber: 'asc' },
|
orderBy: { positionNumber: 'asc' },
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -535,30 +515,22 @@ export class SchedulesService {
|
|||||||
if (dto.departureAt || dto.arrivalAt) {
|
if (dto.departureAt || dto.arrivalAt) {
|
||||||
const dep = dto.departureAt ? new Date(dto.departureAt) : new Date(schedule.departureAt);
|
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 arr = dto.arrivalAt ? new Date(dto.arrivalAt) : new Date(schedule.arrivalAt);
|
||||||
|
|
||||||
if (arr <= dep) throw new BadRequestException('Arrival time must be after departure time');
|
if (arr <= dep) throw new BadRequestException('Arrival time must be after departure time');
|
||||||
|
|
||||||
updateData.departureAt = dep;
|
updateData.departureAt = dep;
|
||||||
updateData.arrivalAt = arr;
|
updateData.arrivalAt = arr;
|
||||||
updateData.durationMinutes = Math.round((arr.getTime() - dep.getTime()) / 60_000);
|
updateData.durationMinutes = Math.round((arr.getTime() - dep.getTime()) / 60_000);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (dto.status) {
|
if (dto.status) updateData.status = dto.status;
|
||||||
updateData.status = dto.status;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (Object.keys(updateData).length > 0) {
|
if (Object.keys(updateData).length > 0) {
|
||||||
await this.prisma.trainSchedule.update({
|
await this.prisma.trainSchedule.update({ where: { id }, data: updateData });
|
||||||
where: { id },
|
|
||||||
data: updateData,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (dto.coaches !== undefined) {
|
if (dto.coaches !== undefined) {
|
||||||
if (dto.coaches.length > 0) {
|
if (dto.coaches.length > 0) {
|
||||||
await this.assignCoaches(id, dto.coaches);
|
await this.assignCoaches(id, dto.coaches);
|
||||||
} else {
|
} else {
|
||||||
// Remove all coach assignments when empty array is sent
|
|
||||||
await this.prisma.coachAssignment.deleteMany({ where: { scheduleId: id } });
|
await this.prisma.coachAssignment.deleteMany({ where: { scheduleId: id } });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -567,11 +539,8 @@ export class SchedulesService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async removeCoachAssignment(scheduleId: string, coachId: string) {
|
async removeCoachAssignment(scheduleId: string, coachId: string) {
|
||||||
const assignment = await this.prisma.coachAssignment.findFirst({
|
const assignment = await this.prisma.coachAssignment.findFirst({ where: { scheduleId, coachId } });
|
||||||
where: { scheduleId, coachId },
|
|
||||||
});
|
|
||||||
if (!assignment) throw new NotFoundException('Coach assignment not found');
|
if (!assignment) throw new NotFoundException('Coach assignment not found');
|
||||||
|
|
||||||
await this.prisma.coachAssignment.delete({ where: { id: assignment.id } });
|
await this.prisma.coachAssignment.delete({ where: { id: assignment.id } });
|
||||||
return { message: 'Coach assignment removed' };
|
return { message: 'Coach assignment removed' };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -441,6 +441,7 @@ export class SearchService {
|
|||||||
destinationStationId,
|
destinationStationId,
|
||||||
seatClassId: sc.id,
|
seatClassId: sc.id,
|
||||||
nationality,
|
nationality,
|
||||||
|
scheduleId: schedule.id,
|
||||||
});
|
});
|
||||||
return {
|
return {
|
||||||
seatClassName: fare.seatClassName,
|
seatClassName: fare.seatClassName,
|
||||||
|
|||||||
@@ -2,14 +2,13 @@
|
|||||||
|
|
||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||||
import { Plus, Trash2, Loader2, Edit, RefreshCw } from 'lucide-react';
|
import { Edit, Loader2, RefreshCw } from 'lucide-react';
|
||||||
import DataTable from '@/components/ui/DataTable';
|
import DataTable from '@/components/ui/DataTable';
|
||||||
import Modal from '@/components/ui/Modal';
|
import Modal from '@/components/ui/Modal';
|
||||||
import ActionButton from '@/components/ui/ActionButton';
|
import ActionButton from '@/components/ui/ActionButton';
|
||||||
import ConfirmDialog from '@/components/ui/ConfirmDialog';
|
|
||||||
import { apiClient } from '@/lib/api-client';
|
import { apiClient } from '@/lib/api-client';
|
||||||
|
|
||||||
interface Currency {
|
interface CurrencyRate {
|
||||||
id: string;
|
id: string;
|
||||||
code: string;
|
code: string;
|
||||||
name: string;
|
name: string;
|
||||||
@@ -18,203 +17,104 @@ interface Currency {
|
|||||||
exchangeRate: number;
|
exchangeRate: number;
|
||||||
isActive: boolean;
|
isActive: boolean;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
updatedAt: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const CURRENCY_META: Record<string, { name: string; symbol: string }> = {
|
||||||
|
ETB: { name: 'Ethiopian Birr', symbol: 'Br' },
|
||||||
|
DJF: { name: 'Djiboutian Franc', symbol: 'Fdj' },
|
||||||
|
USD: { name: 'US Dollar', symbol: '$' },
|
||||||
|
};
|
||||||
|
|
||||||
export default function CurrenciesPage() {
|
export default function CurrenciesPage() {
|
||||||
const [showModal, setShowModal] = useState(false);
|
const [editingRate, setEditingRate] = useState<CurrencyRate | null>(null);
|
||||||
const [editingCurrency, setEditingCurrency] = useState<Currency | null>(null);
|
const [rateInput, setRateInput] = useState('');
|
||||||
const [deleteConfirm, setDeleteConfirm] = useState<{ isOpen: boolean; id: string | null }>({
|
|
||||||
isOpen: false,
|
|
||||||
id: null,
|
|
||||||
});
|
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
const [currencyForm, setCurrencyForm] = useState({
|
const { data: currencies = [], isLoading } = useQuery<CurrencyRate[]>({
|
||||||
code: '',
|
|
||||||
name: '',
|
|
||||||
symbol: '',
|
|
||||||
baseCurrencyCode: 'ETB',
|
|
||||||
exchangeRate: '',
|
|
||||||
});
|
|
||||||
|
|
||||||
const { data: currencies = [], isLoading } = useQuery({
|
|
||||||
queryKey: ['currencies'],
|
queryKey: ['currencies'],
|
||||||
queryFn: () => apiClient.get('/currencies'),
|
queryFn: () => apiClient.get('/currencies'),
|
||||||
});
|
});
|
||||||
|
|
||||||
const createMutation = useMutation({
|
|
||||||
mutationFn: (data: any) => apiClient.post('/currencies', data),
|
|
||||||
onSuccess: () => {
|
|
||||||
queryClient.invalidateQueries({ queryKey: ['currencies'] });
|
|
||||||
resetForm();
|
|
||||||
setError(null);
|
|
||||||
},
|
|
||||||
onError: (err: any) => {
|
|
||||||
setError(err.response?.data?.message || 'Failed to create currency');
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const updateMutation = useMutation({
|
const updateMutation = useMutation({
|
||||||
mutationFn: (data: any) => apiClient.patch(`/currencies/${data.id}`, data),
|
mutationFn: ({ id, exchangeRate }: { id: string; exchangeRate: number }) =>
|
||||||
|
apiClient.patch(`/currencies/${id}`, { exchangeRate }),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: ['currencies'] });
|
queryClient.invalidateQueries({ queryKey: ['currencies'] });
|
||||||
setEditingCurrency(null);
|
setEditingRate(null);
|
||||||
resetForm();
|
|
||||||
setError(null);
|
setError(null);
|
||||||
},
|
},
|
||||||
onError: (err: any) => {
|
onError: (err: any) => {
|
||||||
setError(err.response?.data?.message || 'Failed to update currency');
|
setError(err.response?.data?.message || 'Failed to update exchange rate');
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const deleteMutation = useMutation({
|
const syncMutation = useMutation({
|
||||||
mutationFn: (id: string) => apiClient.delete(`/currencies/${id}`),
|
|
||||||
onSuccess: () => {
|
|
||||||
queryClient.invalidateQueries({ queryKey: ['currencies'] });
|
|
||||||
setDeleteConfirm({ isOpen: false, id: null });
|
|
||||||
},
|
|
||||||
onError: (err: any) => {
|
|
||||||
setError(err.response?.data?.message || 'Failed to delete currency');
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const syncRatesMutation = useMutation({
|
|
||||||
mutationFn: () => apiClient.post('/currencies/sync-rates', {}),
|
mutationFn: () => apiClient.post('/currencies/sync-rates', {}),
|
||||||
onSuccess: () => {
|
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['currencies'] }),
|
||||||
queryClient.invalidateQueries({ queryKey: ['currencies'] });
|
onError: (err: any) => setError(err.response?.data?.message || 'Failed to sync rates'),
|
||||||
setError(null);
|
|
||||||
},
|
|
||||||
onError: (err: any) => {
|
|
||||||
setError(err.response?.data?.message || 'Failed to sync exchange rates');
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const resetForm = () => {
|
const handleEdit = (currency: CurrencyRate) => {
|
||||||
setCurrencyForm({
|
setEditingRate(currency);
|
||||||
code: '',
|
setRateInput(currency.exchangeRate.toString());
|
||||||
name: '',
|
|
||||||
symbol: '',
|
|
||||||
baseCurrencyCode: 'ETB',
|
|
||||||
exchangeRate: '',
|
|
||||||
});
|
|
||||||
setEditingCurrency(null);
|
|
||||||
setShowModal(false);
|
|
||||||
setError(null);
|
setError(null);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleEditCurrency = (currency: Currency) => {
|
const handleSave = async () => {
|
||||||
setEditingCurrency(currency);
|
const rate = parseFloat(rateInput);
|
||||||
setCurrencyForm({
|
|
||||||
code: currency.code,
|
|
||||||
name: currency.name,
|
|
||||||
symbol: currency.symbol,
|
|
||||||
baseCurrencyCode: currency.baseCurrencyCode,
|
|
||||||
exchangeRate: currency.exchangeRate.toString(),
|
|
||||||
});
|
|
||||||
setError(null);
|
|
||||||
setShowModal(true);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleSaveCurrency = async () => {
|
|
||||||
setError(null);
|
|
||||||
if (!currencyForm.code || !currencyForm.name || !currencyForm.symbol || !currencyForm.exchangeRate) {
|
|
||||||
setError('All fields are required');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const rate = parseFloat(currencyForm.exchangeRate);
|
|
||||||
if (isNaN(rate) || rate <= 0) {
|
if (isNaN(rate) || rate <= 0) {
|
||||||
setError('Exchange rate must be a positive number');
|
setError('Exchange rate must be a positive number');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
await updateMutation.mutateAsync({ id: editingRate!.id, exchangeRate: rate });
|
||||||
const payload = {
|
|
||||||
code: currencyForm.code.toUpperCase(),
|
|
||||||
name: currencyForm.name,
|
|
||||||
symbol: currencyForm.symbol,
|
|
||||||
baseCurrencyCode: currencyForm.baseCurrencyCode,
|
|
||||||
exchangeRate: rate,
|
|
||||||
};
|
|
||||||
|
|
||||||
if (editingCurrency) {
|
|
||||||
await updateMutation.mutateAsync({ id: editingCurrency.id, ...payload });
|
|
||||||
} else {
|
|
||||||
await createMutation.mutateAsync(payload);
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const confirmDelete = async () => {
|
const currenciesArray = Array.isArray(currencies) ? currencies : (currencies as any)?.items ?? [];
|
||||||
if (deleteConfirm.id) {
|
|
||||||
await deleteMutation.mutateAsync(deleteConfirm.id);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const currenciesArray = Array.isArray(currencies) ? currencies : (currencies as any)?.items || [];
|
|
||||||
|
|
||||||
const columns = [
|
const columns = [
|
||||||
{
|
{
|
||||||
key: 'code',
|
key: 'code',
|
||||||
label: 'Code',
|
label: 'Currency',
|
||||||
render: (currency: Currency) => (
|
render: (c: CurrencyRate) => (
|
||||||
<span className="font-mono font-semibold text-primary">{currency.code}</span>
|
<div className="flex items-center gap-3">
|
||||||
),
|
<span className="text-2xl font-bold text-muted-foreground w-10 text-center">
|
||||||
},
|
{CURRENCY_META[c.code]?.symbol ?? c.symbol}
|
||||||
{
|
</span>
|
||||||
key: 'name',
|
<div>
|
||||||
label: 'Name',
|
<div className="font-semibold">{c.code}</div>
|
||||||
render: (currency: Currency) => (
|
<div className="text-xs text-muted-foreground">{CURRENCY_META[c.code]?.name ?? c.name}</div>
|
||||||
<span className="font-medium">{currency.name}</span>
|
|
||||||
),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: 'symbol',
|
|
||||||
label: 'Symbol',
|
|
||||||
render: (currency: Currency) => (
|
|
||||||
<span className="text-lg">{currency.symbol}</span>
|
|
||||||
),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: 'baseCurrencyCode',
|
|
||||||
label: 'Base Currency',
|
|
||||||
render: (currency: Currency) => (
|
|
||||||
<span className="font-mono text-sm">{currency.baseCurrencyCode}</span>
|
|
||||||
),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: 'exchangeRate',
|
|
||||||
label: 'Exchange Rate',
|
|
||||||
render: (currency: Currency) => (
|
|
||||||
<div className="space-y-1">
|
|
||||||
<div className="font-mono font-semibold">
|
|
||||||
1 {currency.baseCurrencyCode} = {currency.exchangeRate.toFixed(4)} {currency.code}
|
|
||||||
</div>
|
|
||||||
<div className="text-xs text-muted-foreground">
|
|
||||||
1 {currency.code} = {(1 / currency.exchangeRate).toFixed(6)} {currency.baseCurrencyCode}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'isActive',
|
key: 'baseCurrencyCode',
|
||||||
label: 'Status',
|
label: 'Base',
|
||||||
render: (currency: Currency) => (
|
render: (c: CurrencyRate) => (
|
||||||
<span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
|
<span className="font-mono text-sm text-muted-foreground">{c.baseCurrencyCode}</span>
|
||||||
currency.isActive
|
|
||||||
? 'bg-green-100 dark:bg-green-900/20 text-green-800 dark:text-green-300'
|
|
||||||
: 'bg-gray-100 dark:bg-gray-900/20 text-gray-800 dark:text-gray-300'
|
|
||||||
}`}>
|
|
||||||
{currency.isActive ? 'Active' : 'Inactive'}
|
|
||||||
</span>
|
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'updatedAt',
|
key: 'exchangeRate',
|
||||||
|
label: 'Exchange Rate',
|
||||||
|
render: (c: CurrencyRate) => (
|
||||||
|
<div>
|
||||||
|
<div className="font-mono font-semibold">
|
||||||
|
1 {c.baseCurrencyCode} = {c.exchangeRate} {c.code}
|
||||||
|
</div>
|
||||||
|
<div className="text-xs text-muted-foreground">
|
||||||
|
1 {c.code} = {(1 / c.exchangeRate).toFixed(6)} {c.baseCurrencyCode}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'createdAt',
|
||||||
label: 'Last Updated',
|
label: 'Last Updated',
|
||||||
render: (currency: Currency) => (
|
render: (c: CurrencyRate) => (
|
||||||
<span className="text-sm text-muted-foreground">
|
<span className="text-sm text-muted-foreground">
|
||||||
{new Date(currency.updatedAt).toLocaleDateString()}
|
{new Date(c.createdAt).toLocaleDateString()}
|
||||||
</span>
|
</span>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
@@ -222,140 +122,93 @@ export default function CurrenciesPage() {
|
|||||||
|
|
||||||
const actions = [
|
const actions = [
|
||||||
{
|
{
|
||||||
label: 'Edit',
|
label: 'Edit Rate',
|
||||||
onClick: handleEditCurrency,
|
onClick: handleEdit,
|
||||||
variant: 'secondary' as const,
|
variant: 'secondary' as const,
|
||||||
icon: Edit,
|
icon: Edit,
|
||||||
},
|
},
|
||||||
{
|
|
||||||
label: 'Delete',
|
|
||||||
onClick: (currency: Currency) => setDeleteConfirm({ isOpen: true, id: currency.id }),
|
|
||||||
variant: 'danger' as const,
|
|
||||||
icon: Trash2,
|
|
||||||
},
|
|
||||||
];
|
];
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-3xl font-bold text-foreground">Currencies</h1>
|
<h1 className="text-3xl font-bold text-foreground">Exchange Rates</h1>
|
||||||
<p className="text-muted-foreground mt-1">Manage exchange rates and display currencies</p>
|
<p className="text-muted-foreground mt-1">
|
||||||
</div>
|
Manage ETB exchange rates for display currencies (DJF, USD)
|
||||||
<div className="flex gap-3">
|
</p>
|
||||||
<ActionButton
|
|
||||||
icon={RefreshCw}
|
|
||||||
variant="secondary"
|
|
||||||
onClick={() => syncRatesMutation.mutate()}
|
|
||||||
loading={syncRatesMutation.isPending}
|
|
||||||
>
|
|
||||||
Sync Rates
|
|
||||||
</ActionButton>
|
|
||||||
<ActionButton
|
|
||||||
icon={Plus}
|
|
||||||
onClick={() => {
|
|
||||||
setError(null);
|
|
||||||
setEditingCurrency(null);
|
|
||||||
setCurrencyForm({
|
|
||||||
code: '',
|
|
||||||
name: '',
|
|
||||||
symbol: '',
|
|
||||||
baseCurrencyCode: 'ETB',
|
|
||||||
exchangeRate: '',
|
|
||||||
});
|
|
||||||
setShowModal(true);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
Add Currency
|
|
||||||
</ActionButton>
|
|
||||||
</div>
|
</div>
|
||||||
|
<ActionButton
|
||||||
|
icon={RefreshCw}
|
||||||
|
variant="secondary"
|
||||||
|
onClick={() => syncMutation.mutate()}
|
||||||
|
loading={syncMutation.isPending}
|
||||||
|
>
|
||||||
|
Sync Rates
|
||||||
|
</ActionButton>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{error && !editingRate && (
|
||||||
|
<div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 p-3 rounded-lg text-sm text-red-800 dark:text-red-200">
|
||||||
|
{error}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
<div className="card">
|
<div className="card">
|
||||||
<div className="space-y-6">
|
<div className="grid grid-cols-3 gap-4 mb-6">
|
||||||
<div className="grid grid-cols-1 md:grid-cols-4 gap-4">
|
{(['ETB', 'DJF', 'USD'] as const).map((code) => {
|
||||||
<div className="p-4 bg-gradient-to-br from-blue-50 to-blue-100 dark:from-blue-900/20 dark:to-blue-900/10 rounded-lg border border-blue-200 dark:border-blue-800">
|
const entry = currenciesArray.find((c: CurrencyRate) => c.code === code);
|
||||||
<div className="text-sm text-blue-600 dark:text-blue-400 font-medium">Total Currencies</div>
|
return (
|
||||||
<div className="text-2xl font-bold text-blue-900 dark:text-blue-200 mt-2">
|
<div
|
||||||
{currenciesArray.length}
|
key={code}
|
||||||
|
className="p-4 rounded-lg border bg-muted/30 flex items-center justify-between"
|
||||||
|
>
|
||||||
|
<div>
|
||||||
|
<div className="text-xs text-muted-foreground font-medium">{CURRENCY_META[code].name}</div>
|
||||||
|
<div className="text-2xl font-bold mt-1">{code}</div>
|
||||||
|
</div>
|
||||||
|
<div className="text-right">
|
||||||
|
{entry ? (
|
||||||
|
<>
|
||||||
|
<div className="font-mono font-semibold text-lg">{entry.exchangeRate}</div>
|
||||||
|
<div className="text-xs text-muted-foreground">per ETB</div>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<span className="text-xs text-muted-foreground">Not configured</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
);
|
||||||
<div className="p-4 bg-gradient-to-br from-green-50 to-green-100 dark:from-green-900/20 dark:to-green-900/10 rounded-lg border border-green-200 dark:border-green-800">
|
})}
|
||||||
<div className="text-sm text-green-600 dark:text-green-400 font-medium">Active</div>
|
|
||||||
<div className="text-2xl font-bold text-green-900 dark:text-green-200 mt-2">
|
|
||||||
{currenciesArray.filter((c: Currency) => c.isActive).length}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="p-4 bg-gradient-to-br from-purple-50 to-purple-100 dark:from-purple-900/20 dark:to-purple-900/10 rounded-lg border border-purple-200 dark:border-purple-800">
|
|
||||||
<div className="text-sm text-purple-600 dark:text-purple-400 font-medium">Base Currency</div>
|
|
||||||
<div className="text-2xl font-bold text-purple-900 dark:text-purple-200 mt-2">ETB</div>
|
|
||||||
</div>
|
|
||||||
<div className="p-4 bg-gradient-to-br from-orange-50 to-orange-100 dark:from-orange-900/20 dark:to-orange-900/10 rounded-lg border border-orange-200 dark:border-orange-800">
|
|
||||||
<div className="text-sm text-orange-600 dark:text-orange-400 font-medium">Last Sync</div>
|
|
||||||
<div className="text-lg font-bold text-orange-900 dark:text-orange-200 mt-2">
|
|
||||||
{currenciesArray.length > 0
|
|
||||||
? new Date(currenciesArray[0]?.updatedAt).toLocaleDateString()
|
|
||||||
: 'N/A'}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{isLoading ? (
|
|
||||||
<div className="flex items-center justify-center py-12">
|
|
||||||
<Loader2 className="h-8 w-8 animate-spin text-primary" />
|
|
||||||
</div>
|
|
||||||
) : currenciesArray.length === 0 ? (
|
|
||||||
<div className="text-center py-12 text-muted-foreground">
|
|
||||||
<p>No currencies configured. Click "Add Currency" to create one.</p>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<DataTable
|
|
||||||
data={currenciesArray}
|
|
||||||
columns={columns}
|
|
||||||
actions={actions}
|
|
||||||
loading={false}
|
|
||||||
emptyMessage="No currencies found."
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{isLoading ? (
|
||||||
|
<div className="flex items-center justify-center py-12">
|
||||||
|
<Loader2 className="h-8 w-8 animate-spin text-primary" />
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<DataTable
|
||||||
|
data={currenciesArray}
|
||||||
|
columns={columns}
|
||||||
|
actions={actions}
|
||||||
|
loading={false}
|
||||||
|
emptyMessage="No exchange rates configured."
|
||||||
|
/>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="card bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800">
|
<div className="card bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 text-sm text-blue-800 dark:text-blue-300 space-y-1">
|
||||||
<h3 className="font-semibold text-blue-900 dark:text-blue-200 mb-3">Currency Management</h3>
|
<p className="font-semibold text-blue-900 dark:text-blue-200 mb-2">How it works</p>
|
||||||
<ul className="text-sm text-blue-800 dark:text-blue-300 space-y-2">
|
<p>• ETB is the transaction currency — all fares are stored in ETB minor units (1 ETB = 100 minor)</p>
|
||||||
<li>
|
<p>• DJF and USD rates are used to display prices to passengers in their preferred currency</p>
|
||||||
• <strong>Base Currency:</strong> All exchange rates are calculated relative to this currency (typically ETB)
|
<p>• Rates apply globally; changes take effect immediately on the next booking or fare quote</p>
|
||||||
</li>
|
|
||||||
<li>
|
|
||||||
• <strong>Exchange Rate:</strong> How many units of the currency equal 1 unit of the base currency
|
|
||||||
</li>
|
|
||||||
<li>
|
|
||||||
• <strong>Display Currencies:</strong> Configure which currencies customers can view prices in
|
|
||||||
</li>
|
|
||||||
<li>
|
|
||||||
• <strong>Sync Rates:</strong> Automatically update exchange rates from external sources
|
|
||||||
</li>
|
|
||||||
</ul>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Delete Confirmation */}
|
|
||||||
<ConfirmDialog
|
|
||||||
isOpen={deleteConfirm.isOpen}
|
|
||||||
onClose={() => setDeleteConfirm({ isOpen: false, id: null })}
|
|
||||||
onConfirm={confirmDelete}
|
|
||||||
title="Delete Currency"
|
|
||||||
message="Are you sure you want to delete this currency? This action cannot be undone."
|
|
||||||
confirmText="Delete"
|
|
||||||
isDanger={true}
|
|
||||||
warning="This will remove the currency from the system."
|
|
||||||
/>
|
|
||||||
|
|
||||||
{/* Add/Edit Modal */}
|
|
||||||
<Modal
|
<Modal
|
||||||
isOpen={showModal}
|
isOpen={!!editingRate}
|
||||||
onClose={resetForm}
|
onClose={() => { setEditingRate(null); setError(null); }}
|
||||||
title={`${editingCurrency ? 'Edit' : 'Add'} Currency`}
|
title={`Update Rate — ${editingRate?.code}`}
|
||||||
size="lg"
|
size="sm"
|
||||||
>
|
>
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
{error && (
|
{error && (
|
||||||
@@ -364,108 +217,38 @@ export default function CurrenciesPage() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
<div className="p-3 bg-muted/40 rounded-lg text-sm">
|
||||||
<div>
|
<span className="text-muted-foreground">Currency: </span>
|
||||||
<label className="label">Currency Code *</label>
|
<span className="font-semibold">{editingRate?.code} — {CURRENCY_META[editingRate?.code ?? '']?.name}</span>
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
value={currencyForm.code}
|
|
||||||
onChange={(e) => setCurrencyForm({ ...currencyForm, code: e.target.value.toUpperCase() })}
|
|
||||||
className="input w-full"
|
|
||||||
placeholder="e.g., USD"
|
|
||||||
maxLength={3}
|
|
||||||
disabled={!!editingCurrency}
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
<p className="text-xs text-muted-foreground mt-1">3-letter ISO code (e.g., USD, DJF, GBP)</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<label className="label">Currency Name *</label>
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
value={currencyForm.name}
|
|
||||||
onChange={(e) => setCurrencyForm({ ...currencyForm, name: e.target.value })}
|
|
||||||
className="input w-full"
|
|
||||||
placeholder="e.g., United States Dollar"
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
|
||||||
<div>
|
|
||||||
<label className="label">Symbol *</label>
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
value={currencyForm.symbol}
|
|
||||||
onChange={(e) => setCurrencyForm({ ...currencyForm, symbol: e.target.value })}
|
|
||||||
className="input w-full"
|
|
||||||
placeholder="e.g., $"
|
|
||||||
maxLength={3}
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<label className="label">Base Currency *</label>
|
|
||||||
<select
|
|
||||||
value={currencyForm.baseCurrencyCode}
|
|
||||||
onChange={(e) => setCurrencyForm({ ...currencyForm, baseCurrencyCode: e.target.value })}
|
|
||||||
className="input w-full"
|
|
||||||
disabled
|
|
||||||
>
|
|
||||||
<option value="ETB">ETB (Ethiopian Birr)</option>
|
|
||||||
<option value="USD">USD (US Dollar)</option>
|
|
||||||
<option value="DJF">DJF (Djiboutian Franc)</option>
|
|
||||||
</select>
|
|
||||||
<p className="text-xs text-muted-foreground mt-1">All rates relative to this currency</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<label className="label">Exchange Rate *</label>
|
<label className="label">
|
||||||
<div className="flex items-center gap-2">
|
1 {editingRate?.baseCurrencyCode} = ? {editingRate?.code}
|
||||||
<input
|
</label>
|
||||||
type="number"
|
<input
|
||||||
min="0"
|
type="number"
|
||||||
step="0.0001"
|
min="0.0001"
|
||||||
value={currencyForm.exchangeRate}
|
step="0.0001"
|
||||||
onChange={(e) => setCurrencyForm({ ...currencyForm, exchangeRate: e.target.value })}
|
value={rateInput}
|
||||||
className="input w-full"
|
onChange={(e) => setRateInput(e.target.value)}
|
||||||
placeholder="e.g., 0.018"
|
className="input w-full"
|
||||||
required
|
placeholder="e.g., 3.25"
|
||||||
/>
|
autoFocus
|
||||||
<div className="text-sm text-muted-foreground whitespace-nowrap">
|
/>
|
||||||
1 {currencyForm.baseCurrencyCode} = ? {currencyForm.code}
|
{rateInput && parseFloat(rateInput) > 0 && (
|
||||||
</div>
|
<p className="text-xs text-muted-foreground mt-1">
|
||||||
</div>
|
≈ 1 {editingRate?.code} = {(1 / parseFloat(rateInput)).toFixed(6)} {editingRate?.baseCurrencyCode}
|
||||||
{currencyForm.exchangeRate && parseFloat(currencyForm.exchangeRate) > 0 && (
|
|
||||||
<p className="text-xs text-muted-foreground mt-2">
|
|
||||||
≈ 1 {currencyForm.code} = {(1 / parseFloat(currencyForm.exchangeRate)).toFixed(6)} {currencyForm.baseCurrencyCode}
|
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 p-3 rounded-lg text-xs text-blue-800 dark:text-blue-200">
|
<div className="flex gap-2 justify-end pt-2">
|
||||||
<p className="font-semibold mb-1">Exchange Rate Example:</p>
|
<ActionButton variant="secondary" onClick={() => { setEditingRate(null); setError(null); }}>
|
||||||
<p>If 1 ETB = 0.018 USD, enter 0.018</p>
|
|
||||||
<p>If 1 ETB = 3.25 DJF, enter 3.25</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex gap-2 justify-end pt-4">
|
|
||||||
<ActionButton
|
|
||||||
variant="secondary"
|
|
||||||
onClick={resetForm}
|
|
||||||
type="button"
|
|
||||||
>
|
|
||||||
Cancel
|
Cancel
|
||||||
</ActionButton>
|
</ActionButton>
|
||||||
<ActionButton
|
<ActionButton onClick={handleSave} loading={updateMutation.isPending}>
|
||||||
onClick={handleSaveCurrency}
|
Save Rate
|
||||||
loading={createMutation.isPending || updateMutation.isPending}
|
|
||||||
>
|
|
||||||
{editingCurrency ? 'Update Currency' : 'Add Currency'}
|
|
||||||
</ActionButton>
|
</ActionButton>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -731,14 +731,19 @@ export default function PricingPage() {
|
|||||||
|
|
||||||
<div>
|
<div>
|
||||||
<label className="label">Route Code (Optional)</label>
|
<label className="label">Route Code (Optional)</label>
|
||||||
<input
|
<select
|
||||||
type="text"
|
|
||||||
value={fareForm.route}
|
value={fareForm.route}
|
||||||
onChange={(e) => setFareForm({ ...fareForm, route: e.target.value })}
|
onChange={(e) => setFareForm({ ...fareForm, route: e.target.value })}
|
||||||
className="input w-full"
|
className="input w-full"
|
||||||
placeholder="e.g., ADD-DJI"
|
>
|
||||||
/>
|
<option value="">All routes</option>
|
||||||
<p className="text-xs text-muted-foreground mt-1">e.g., ADD-DJI for full route</p>
|
{routesArray.map((route: Route) => (
|
||||||
|
<option key={route.id} value={route.code}>
|
||||||
|
{route.code} — {route.name}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
<p className="text-xs text-muted-foreground mt-1">Scope this fare to a specific route</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user