Merge pull request #1156 from Tria-plc/freight_feature/usermanagement

Freight feature/usermanagement
This commit is contained in:
marshal
2026-08-07 11:49:04 +03:00
committed by GitHub
92 changed files with 6630 additions and 486 deletions

View File

@@ -31,6 +31,18 @@ export const BookingView = () => BookingStaff(FREIGHT_PERMS.bookings.view);
export const BookingDocReviewAlert = () =>
BookingStaff(FREIGHT_PERMS.bookings.docReviewAlert);
/** Staff wagon-cancellation history list (admin side). */
export const WagonCancellationView = () =>
BookingStaff(FREIGHT_PERMS.bookings.wagonCancellationView);
/** Staff void of a customer's pending (fee-unpaid) wagon cancellation. */
export const WagonCancellationVoid = () =>
BookingStaff(FREIGHT_PERMS.bookings.wagonCancellationVoid);
/** Staff rebook of a customer's wagon-cancellation credit on their behalf. */
export const WagonCancellationRebook = () =>
BookingStaff(FREIGHT_PERMS.bookings.wagonCancellationRebook);
export const TrainSchedulingView = () =>
BookingStaff(FREIGHT_PERMS.trainScheduling.view);

View File

@@ -85,6 +85,48 @@ describe('computeLastMileCharge', () => {
expect(charge).toMatchObject({ mode: 'BULK', total: 60 * 26 * 25, currency: 'ETB' });
});
it('picks the bulk rate whose distance band holds the km (half-open boundary)', () => {
const bulkNear = rate({ rateUnit: 'PER_TON_KM', rateValue: 30, minKm: 0, maxKm: 30 });
const bulkFar = rate({ rateUnit: 'PER_TON_KM', rateValue: 22, minKm: 30, maxKm: null });
const near = computeLastMileCharge({
freightType: 'BULK',
tons: 10,
km: 12,
containers: [],
liveRates: [bulkNear, bulkFar],
});
expect(near).toMatchObject({ mode: 'BULK', total: 10 * 12 * 30 });
const boundary = computeLastMileCharge({
freightType: 'BULK',
tons: 10,
km: 30,
containers: [],
liveRates: [bulkNear, bulkFar],
});
expect(boundary).toMatchObject({ total: 10 * 30 * 22 });
});
it('bulk falls back to the legacy bandless rate when no band holds the km, null when nothing covers it', () => {
const bulkNear = rate({ rateUnit: 'PER_TON_KM', rateValue: 30, minKm: 0, maxKm: 30 });
const fallback = computeLastMileCharge({
freightType: 'BULK',
tons: 10,
km: 50,
containers: [],
liveRates: [bulkNear, bulkRate], // bulkRate has no band
});
expect(fallback).toMatchObject({ total: 10 * 50 * 25 });
expect(
computeLastMileCharge({
freightType: 'BULK',
tons: 10,
km: 50,
containers: [],
liveRates: [bulkNear],
}),
).toBeNull();
});
it('returns null on mixed currencies, unknown km, and uncovered freight types', () => {
const usd40 = rate({ ...band40a, currency: 'USD' });
expect(

View File

@@ -30,10 +30,12 @@ const round2 = (n: number): number => Math.round(n * 100) / 100;
/**
* Price a last-mile leg off the LIVE rate rules. Pure — pass the live rates in.
*
* BULK: one PER_TON_KM rate → price = tons × km × rate.
* BULK: the PER_TON_KM rate whose distance band holds the km (a legacy
* bandless row — NULL minKm — is the fallback and prices every distance) →
* price = tons × km × rate.
* CONTAINER: per container size, the PER_KM rate whose distance band holds the
* km (bands are half-open [minKm, maxKm), NULL maxKm = open-ended) → price =
* km × rate × quantity, summed across sizes.
* km → price = km × rate × quantity, summed across sizes.
* Bands are half-open [minKm, maxKm), NULL maxKm = open-ended.
*
* Returns null whenever the rules don't fully cover the shipment (no rate, a
* container size without a matching band, mixed currencies, km/tons unknown) —
@@ -56,7 +58,15 @@ export function computeLastMileCharge(input: {
if (freightType === 'BULK') {
if (!tons || tons <= 0) return null;
const rate = candidates.find((r) => r.rateUnit === 'PER_TON_KM');
const bulkRates = candidates.filter((r) => r.rateUnit === 'PER_TON_KM');
const rate =
bulkRates.find(
(r) =>
r.minKm !== null &&
r.minKm !== undefined &&
Number(r.minKm) <= km &&
(r.maxKm === null || r.maxKm === undefined || km < Number(r.maxKm)),
) ?? bulkRates.find((r) => r.minKm === null || r.minKm === undefined);
if (!rate) return null;
const unitRate = Number(rate.rateValue);
const amount = round2(tons * km * unitRate);

View File

@@ -0,0 +1,65 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
/**
* Partial wagon cancellation with rebooking credit.
*
* One row per cancellation cycle on a PAID booking: the customer asks to drop
* N wagons, pays a per-wagon cancellation fee (rates row
* rate_type = 'CANCELLATION_FEE', rate_unit = 'PER_WAGON'), and the dropped cargo becomes a
* rebookable credit. The credit is redeemed by creating a fresh booking
* through the normal under-contract create path (which re-checks contract
* validity and caps), immediately marked PAID — the freight was already paid
* on the original booking, only the fee is new money.
*
* cancelled_quantities carries what was cut, in the booking's own terms:
* `{ bulkTons }` for bulk, `{ bySize: { "20": 4, "40": 3 } }` for container.
* Container numbers are NOT stored here — they are recovered at rebook time
* from the unit rows the reduction soft-deleted (same hybrid pattern as
* RemainderPlacementService).
*/
export class BookingWagonCancellations3300000000000 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`
CREATE TABLE IF NOT EXISTS freight.booking_wagon_cancellations (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
booking_id uuid NOT NULL REFERENCES freight.bookings(id),
rebooked_booking_id uuid REFERENCES freight.bookings(id),
wagons_cancelled numeric(6,2) NOT NULL CHECK (wagons_cancelled > 0),
weight_tons numeric(12,3) NOT NULL DEFAULT 0,
cancelled_quantities jsonb NOT NULL,
credit_amount numeric(14,2) NOT NULL DEFAULT 0,
fee_rate_id uuid REFERENCES freight.rates(id),
fee_amount numeric(14,2) NOT NULL CHECK (fee_amount >= 0),
fee_currency varchar(8) NOT NULL DEFAULT 'ETB',
fee_invoice_id uuid REFERENCES freight.invoices(id),
fee_paid_at timestamptz,
status varchar(30) NOT NULL DEFAULT 'FEE_PENDING',
reason text,
requested_by_user_id uuid,
rebooked_at timestamptz,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz
)
`);
// One open (fee-unpaid) cancellation per booking — closes the double-click
// race without app-level locking.
await queryRunner.query(`
CREATE UNIQUE INDEX IF NOT EXISTS uq_open_wagon_cancellation_per_booking
ON freight.booking_wagon_cancellations (booking_id)
WHERE status = 'FEE_PENDING' AND deleted_at IS NULL
`);
await queryRunner.query(`
CREATE INDEX IF NOT EXISTS idx_bwc_booking
ON freight.booking_wagon_cancellations (booking_id)
`);
await queryRunner.query(`
CREATE INDEX IF NOT EXISTS idx_bwc_status
ON freight.booking_wagon_cancellations (status)
`);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`DROP TABLE IF EXISTS freight.booking_wagon_cancellations`);
}
}

View File

@@ -668,3 +668,66 @@ describe("BillingService — CAC Bank (OTP debit)", () => {
expect(confirmOtp).toHaveBeenCalledWith("intent-1", "123456");
});
});
describe("BillingService — CBE bill amounts round UP to whole birr", () => {
// CBE bills whole birr. Ceil, never Math.round: a .40 balance rounded down
// settles 0.40 short while markInvoiceAsPaid still writes paidAmount =
// totalAmount — money missing from the bank with the books saying paid.
// payInvoice and billQuery must agree, or /cbe/payment sees a mismatch.
const invoice = {
id: "inv-1",
status: Freight.InvoiceStatus.Pending,
source: Freight.InvoiceSource.Booking,
sourceId: "booking-1",
type: "PREPAID",
invoiceNumber: "INV-20260101-00001",
currency: "ETB",
// .40 — the case Math.round gets wrong (rounds down, underpays).
balanceAmount: 12345.4,
totalAmount: 12345.4,
company: { name: "Acme PLC" },
paymentId: null,
dueAt: null,
};
const build = (payment: Record<string, unknown> = {}) => {
const repo = {
findOne: jest.fn().mockResolvedValue(invoice),
update: jest.fn().mockResolvedValue(undefined),
};
const service = new BillingService(
{ getRepository: () => repo } as never,
{} as never,
{} as never,
makeEvents() as never,
payment as never,
{} as never,
{} as never,
);
return { service, repo };
};
it("opens the intent for the ceiled balance, never below it", async () => {
const initiate = jest.fn().mockResolvedValue({
intentId: "intent-1",
immediateSuccess: false,
response: { intentId: "intent-1", status: "REQUIRES_ACTION" },
});
const { service } = build({ initiate });
await service.payInvoice("inv-1", { method: "CBE_BILL" });
expect(initiate).toHaveBeenCalledWith(
expect.objectContaining({ amountMinor: 12346 }),
);
});
it("quotes the same ceiled amount on bill-query as payInvoice opened", async () => {
const { service } = build();
await expect(service.billQuery("booking-1")).resolves.toMatchObject({
stillPayable: true,
currentAmountMinor: 12346,
});
});
});

View File

@@ -1191,7 +1191,11 @@ export class BillingService {
// service branches on a domain-specific reference type.
referenceType: PaymentReferenceType.SHIPMENT,
orderRef: invoice.invoiceNumber.replace(/-/g, "_"),
amountMinor: Math.round(Number(invoice.balanceAmount)),
// Whole birr, always UP. CBE bills this amount verbatim, so it must never
// land below the outstanding balance — Math.round would let a .40 balance
// settle 0.40 short. Ceil overcharges by <1 birr instead, and the same
// ceil in billQuery keeps the quoted and debited amounts identical.
amountMinor: Math.ceil(Number(invoice.balanceAmount)),
currency: invoice.currency,
reason: `Payment for invoice ${invoice.invoiceNumber}`,
method: opts.method ?? "TELEBIRR",
@@ -1336,7 +1340,9 @@ export class BillingService {
});
if (open) {
const balance = Math.round(Number(open.balanceAmount ?? open.totalAmount));
// Ceil, matching payInvoice — the amount CBE quotes at the counter has to
// be the amount the intent was opened for, or /cbe/payment sees a mismatch.
const balance = Math.ceil(Number(open.balanceAmount ?? open.totalAmount));
const expired = open.dueAt && open.dueAt.getTime() < Date.now();
return {
stillPayable: balance > 0 && !expired,
@@ -1371,7 +1377,7 @@ export class BillingService {
return {
stillPayable: false,
payerName: latest.company?.name ?? null,
currentAmountMinor: Math.round(Number(latest.totalAmount)),
currentAmountMinor: Math.ceil(Number(latest.totalAmount)),
currency: latest.currency,
paymentReason: `Freight invoice ${latest.invoiceNumber}`,
reason: closedInvoiceReason(latest.status),

View File

@@ -20,6 +20,10 @@ import { FirstMileService } from "../first-mile/first-mile.service";
import { BookingBatchService } from "../train-scheduling/booking-batch.service";
import { PriceLineItemDto } from "./dto/generate-price-response.dto";
import { BookingsRepository } from "./bookings.repository";
import {
BookingWagonCancellationService,
WAGON_CANCEL_FEE_INVOICE_TYPE,
} from "./booking-wagon-cancellation.service";
import { Booking } from "./entities/booking.entity";
/** Snapshot written onto `booking.pricingBreakdown` by the pricing service. */
@@ -58,6 +62,8 @@ export class BookingInvoiceService {
private readonly firstMile: FirstMileService,
@Inject(forwardRef(() => BookingBatchService))
private readonly bookingBatch: BookingBatchService,
@Inject(forwardRef(() => BookingWagonCancellationService))
private readonly wagonCancellations: BookingWagonCancellationService,
) { }
/**
@@ -123,6 +129,11 @@ export class BookingInvoiceService {
await this.bookingBatch.reviveOfferForInvoice(payload.invoiceId);
await this.advanceBookingOnPayment(payload.sourceId);
break;
case WAGON_CANCEL_FEE_INVOICE_TYPE:
// Partial wagon cancellation: the fee settled — reduce the booking and
// release the cancelled wagons (T2 of the cancellation cycle).
await this.wagonCancellations.onFeePaid(payload.invoiceId);
break;
default:
this.logger.warn(
`Unhandled booking invoice type "${payload.type}" paid (${payload.invoiceId})`,

View File

@@ -8,6 +8,9 @@ import {
Optional,
} from "@nestjs/common";
import { EventEmitter2, OnEvent } from "@nestjs/event-emitter";
import { DataSource } from "typeorm";
import { TrainSchedule } from '../train-schedules/entities/train-schedule.entity';
import {
BookingBatchService,
@@ -56,11 +59,18 @@ export class BookingTransitionService {
private readonly bookingClearanceService: BookingClearanceService,
@Inject(forwardRef(() => ClearanceWorkflowService))
private readonly workflowService: ClearanceWorkflowService,
private readonly invoiceService: BookingInvoiceService,
// forwardRef: booking-invoice.service now pulls in the wagon-cancellation
// service, whose cross-module imports close a require cycle through this
// file — without it the class is undefined at decorator time.
@Inject(forwardRef(() => BookingInvoiceService))
private readonly invoiceService: BookingInvoiceService,
private readonly containerValidationService: ContainerValidationService,
private readonly notifier: BookingLifecycleNotifierService,
private readonly events: EventEmitter2,
@Optional() private readonly milestoneService?: ClearanceMilestoneService,
// Optional + last so the hand-constructed service in *.spec.ts files keeps
// compiling; Nest injects it normally at runtime.
@Optional() private readonly dataSource?: DataSource,
) {}
private isPhasedCustoms(booking: Booking): boolean {
@@ -429,6 +439,20 @@ export class BookingTransitionService {
return fresh;
}
/**
* Customer self-service cancel, allowed only before payment — no fee.
* SELECTED_FOR_BATCH releases the wagon hold immediately; earlier statuses
* take the plain cancel path (open invoices expired, nothing reserved yet).
* Anything past payment falls through to cancel()'s status assertion.
*/
async customerCancel(bookingId: string, reason?: string): Promise<Booking> {
const booking = await this.bookingsService.findById(bookingId);
if (booking.status === "SELECTED_FOR_BATCH") {
return this.cancelHold(bookingId, reason);
}
return this.cancel(bookingId, reason ?? "Customer cancelled before payment");
}
async cancel(bookingId: string, reason: string): Promise<Booking> {
const booking = await this.bookingsService.findById(bookingId);
assertBookingStatus(booking, [
@@ -978,6 +1002,15 @@ export class BookingTransitionService {
// booking through the space checks below AND is persisted so the accept /
// reserve path locks onto that train (pickExportSchedule honors it).
const requestedId = isExportTrain ? (requestedTrainScheduleId ?? null) : null;
// Export rail rides the exact train the customer picked — never an
// auto-assigned one. Both portal flows (clearance + contract completion)
// surface a picker, so a missing id is an invalid submission, not a
// legitimate "let the system choose".
if (isExportTrain && !requestedId) {
throw new BadRequestException(
"Select a train for the chosen shipment day.",
);
}
const scheduledBooking = {
...booking,
scheduledDate: date,
@@ -1244,6 +1277,12 @@ export class BookingTransitionService {
/** Flat list of physical container numbers on this booking (for the
* customer truck-assignment container picker). */
containerNumbers: string[];
/** The allocated train, when the booking is placed on a schedule. */
trainSchedule?: {
trainNumber: string | null;
reference: string | null;
scheduledDepartureDate: Date | null;
} | null;
}
> {
// This enrichment runs AFTER the transition has committed. A failure here
@@ -1296,6 +1335,32 @@ export class BookingTransitionService {
`enrichBookingResponse: batch-offer lookup failed for ${booking.id}: ${(err as Error).message}`,
);
}
// Allocated train: number + schedule reference for the detail headers
// (portal and backoffice). Degrades to null like every fragile field here.
let trainSchedule: {
trainNumber: string | null;
reference: string | null;
scheduledDepartureDate: Date | null;
} | null = null;
if (booking.trainScheduleId && this.dataSource) {
try {
const s = await this.dataSource.getRepository(TrainSchedule).findOne({
where: { id: booking.trainScheduleId },
});
if (s) {
trainSchedule = {
trainNumber: s.trainNumber ?? null,
reference: s.reference ?? null,
scheduledDepartureDate: s.scheduledDepartureDate ?? null,
};
}
} catch (err) {
this.logger.warn(
`enrichBookingResponse: train-schedule lookup failed for ${booking.id}: ${(err as Error).message}`,
);
}
}
// Physical container numbers entered at booking time (booking_container
// units), flattened for the customer truck-assignment container picker.
const containerNumbers = (booking.bookingContainers ?? [])
@@ -1310,6 +1375,7 @@ export class BookingTransitionService {
nextStep,
activeBatchOffer,
containerNumbers,
trainSchedule,
};
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,85 @@
import { BaseRepository } from '@edr/api-common';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, SelectQueryBuilder } from 'typeorm';
import { BookingWagonCancellation } from './entities/booking-wagon-cancellation.entity';
export interface WagonCancellationListFilter {
status?: string[];
/** Booking reference / company name search (staff list). */
search?: string;
companyId?: string;
bookingId?: string;
from?: Date;
to?: Date;
page?: number;
pageSize?: number;
}
@Injectable()
export class BookingWagonCancellationsRepository extends BaseRepository<BookingWagonCancellation> {
constructor(
@InjectRepository(BookingWagonCancellation)
repository: Repository<BookingWagonCancellation>,
) {
super(repository);
}
/** The one open (fee-unpaid) cancellation of a booking, if any. */
findOpenForBooking(bookingId: string): Promise<BookingWagonCancellation | null> {
return this.repository.findOne({
where: { bookingId, status: 'FEE_PENDING' },
});
}
findByFeeInvoiceId(feeInvoiceId: string): Promise<BookingWagonCancellation | null> {
return this.repository.findOne({ where: { feeInvoiceId } });
}
/** Paged history — staff see everything, customers are scoped by companyId. */
async list(
filter: WagonCancellationListFilter,
): Promise<{ items: BookingWagonCancellation[]; total: number }> {
const page = Math.max(1, filter.page ?? 1);
const pageSize = Math.min(100, Math.max(1, filter.pageSize ?? 10));
const qb = this.baseQuery();
if (filter.bookingId) {
qb.andWhere('(bwc.booking_id = :bookingId OR bwc.rebooked_booking_id = :bookingId)', {
bookingId: filter.bookingId,
});
}
if (filter.companyId) {
qb.andWhere('booking.company_id = :companyId', { companyId: filter.companyId });
}
if (filter.status?.length) {
qb.andWhere('bwc.status IN (:...statuses)', { statuses: filter.status });
}
if (filter.search) {
qb.andWhere('(booking.reference ILIKE :search OR company.name ILIKE :search)', {
search: `%${filter.search}%`,
});
}
if (filter.from) qb.andWhere('bwc.created_at >= :from', { from: filter.from });
if (filter.to) qb.andWhere('bwc.created_at <= :to', { to: filter.to });
// Property path (not raw column): skip/take builds a distinct-id subquery
// and the ORDER BY must resolve inside it.
const [items, total] = await qb
.orderBy('bwc.createdAt', 'DESC')
.skip((page - 1) * pageSize)
.take(pageSize)
.getManyAndCount();
return { items, total };
}
private baseQuery(): SelectQueryBuilder<BookingWagonCancellation> {
return this.repository
.createQueryBuilder('bwc')
.leftJoinAndSelect('bwc.booking', 'booking')
.leftJoinAndSelect('booking.company', 'company')
.leftJoinAndSelect('bwc.rebookedBooking', 'rebookedBooking')
.leftJoinAndSelect('bwc.feeInvoice', 'feeInvoice');
}
}

View File

@@ -21,7 +21,11 @@ import {
import { CurrentUser } from '@edr/api-common';
import type { TCurrentUser } from '@tria-plc/api-common/modules/auth/types/current-user.type';
import { JwtGuard } from '@tria-plc/api-common/modules/auth/services/jwt.guard';
import { BookingStaff, BookingView } from '../../common/booking-guards';
import {
BookingStaff,
BookingView,
WagonCancellationView,
} from '../../common/booking-guards';
import { FREIGHT_PERMS } from '../../seed/freight-permissions.registry';
import { AnyFilesInterceptor, FileInterceptor } from '@nestjs/platform-express';
import {
@@ -74,6 +78,12 @@ import { GenerateGrnDto } from './dto/generate-grn.dto';
import { ContainerReceiptService } from './container-receipt.service';
import { SignContractDto } from './dto/sign-contract.dto';
import { UpdateBookingDto } from './dto/update-booking.dto';
import { BookingWagonCancellationService } from './booking-wagon-cancellation.service';
import {
FilterWagonCancellationsDto,
RebookCancelledWagonsDto,
RequestWagonCancellationDto,
} from './dto/wagon-cancellation.dto';
import {
type AuthUserPayload,
resolveAuthUserId,
@@ -153,6 +163,7 @@ export class BookingsController {
private readonly firstMileService: FirstMileService,
private readonly lastMileService: LastMileService,
private readonly userTradeAccessService: UserTradeAccessService,
private readonly wagonCancellationService: BookingWagonCancellationService,
) {}
@Post()
@@ -496,6 +507,150 @@ export class BookingsController {
res.send(buffer);
}
@Get(':id/wagons')
@ApiOperation({
summary:
'Allocated wagons for a booking (JSON) — empty until the paid booking is placed on a train',
})
async wagonAllocations(
@Param('id', ParseUUIDPipe) id: string,
@CurrentUser() user: TCurrentUser,
) {
const booking = await this.bookingsService.findById(id);
if (!hasFreightPermission(user, FREIGHT_PERMS.bookings.view)) {
await this.bookingsService.assertCustomerCanAccessBooking(user?.id, booking);
}
return this.bookingsService.wagonAllocations(id);
}
// ── Partial wagon cancellation (paid bookings) ────────────────────────────
// Customer endpoints are ownership-scoped (no portal permission keys); the
// staff history/void/rebook variants are permission-gated below.
@Post(':id/wagon-cancellations/preview')
@ApiOperation({ summary: 'Preview the fee/credit of a partial wagon cancellation (no writes)' })
async previewWagonCancellation(
@Param('id', ParseUUIDPipe) id: string,
@Body() dto: RequestWagonCancellationDto,
@CurrentUser() user: TCurrentUser,
) {
const booking = await this.bookingsService.findById(id);
if (!hasFreightPermission(user, FREIGHT_PERMS.bookings.view)) {
await this.bookingsService.assertCustomerCanAccessBooking(user?.id, booking);
}
return this.wagonCancellationService.previewCancellation(id, dto);
}
@Post(':id/wagon-cancellations')
@ApiOperation({
summary:
'Request a partial wagon cancellation on a PAID booking — opens the cancellation-fee invoice; wagons are released only once the fee settles',
})
async requestWagonCancellation(
@Param('id', ParseUUIDPipe) id: string,
@Body() dto: RequestWagonCancellationDto,
@CurrentUser() user: TCurrentUser,
) {
const booking = await this.bookingsService.findById(id);
if (!hasFreightPermission(user, FREIGHT_PERMS.bookings.view)) {
await this.bookingsService.assertCustomerCanAccessBooking(user?.id, booking);
}
return this.wagonCancellationService.requestCancellation(id, dto, user?.id);
}
@Get(':id/wagon-cancellations')
@ApiOperation({ summary: 'Wagon-cancellation history of one booking (owner or staff)' })
async listBookingWagonCancellations(
@Param('id', ParseUUIDPipe) id: string,
@CurrentUser() user: TCurrentUser,
) {
const booking = await this.bookingsService.findById(id);
const staff =
hasFreightPermission(user, FREIGHT_PERMS.bookings.view) ||
hasFreightPermission(user, FREIGHT_PERMS.bookings.wagonCancellationView);
if (!staff) {
await this.bookingsService.assertCustomerCanAccessBooking(user?.id, booking);
}
return this.wagonCancellationService.list({ bookingId: id, pageSize: 100 });
}
@Get('wagon-cancellations/my')
@ApiOperation({ summary: 'Wagon-cancellation history of the calling customer (paginated, filterable)' })
async listMyWagonCancellations(
@Query() filter: FilterWagonCancellationsDto,
@CurrentUser() user: TCurrentUser,
) {
const companyId = await this.bookingsService.resolveCustomerCompanyId(user?.id ?? '');
if (!companyId) throw new ForbiddenException('No customer company for this user.');
return this.wagonCancellationService.list({
companyId,
status: filter.statuses,
search: filter.search,
from: filter.from ? new Date(filter.from) : undefined,
to: filter.to ? new Date(filter.to) : undefined,
page: filter.page,
pageSize: filter.pageSize,
});
}
@Get('wagon-cancellations/history')
@WagonCancellationView()
@ApiOperation({ summary: 'All wagon cancellations (staff, paginated, filterable)' })
async listAllWagonCancellations(@Query() filter: FilterWagonCancellationsDto) {
return this.wagonCancellationService.list({
status: filter.statuses,
search: filter.search,
from: filter.from ? new Date(filter.from) : undefined,
to: filter.to ? new Date(filter.to) : undefined,
page: filter.page,
pageSize: filter.pageSize,
});
}
@Post('wagon-cancellations/:cancellationId/withdraw')
@ApiOperation({ summary: 'Withdraw a fee-pending wagon cancellation (owner, or staff with the void permission)' })
async withdrawWagonCancellation(
@Param('cancellationId', ParseUUIDPipe) cancellationId: string,
@CurrentUser() user: TCurrentUser,
) {
await this.assertWagonCancellationActor(
cancellationId,
user,
FREIGHT_PERMS.bookings.wagonCancellationVoid,
);
return this.wagonCancellationService.withdraw(cancellationId);
}
@Post('wagon-cancellations/:cancellationId/rebook')
@ApiOperation({
summary:
'Rebook a wagon-cancellation credit: pick a shipment day only — the new booking is created under the contract and marked PAID (freight already paid; contract must still be valid)',
})
async rebookWagonCancellation(
@Param('cancellationId', ParseUUIDPipe) cancellationId: string,
@Body() dto: RebookCancelledWagonsDto,
@CurrentUser() user: TCurrentUser,
) {
await this.assertWagonCancellationActor(
cancellationId,
user,
FREIGHT_PERMS.bookings.wagonCancellationRebook,
);
return this.wagonCancellationService.rebook(cancellationId, dto, user?.id);
}
/** Owner-or-staff gate shared by the per-cancellation actions. */
private async assertWagonCancellationActor(
cancellationId: string,
user: TCurrentUser,
staffPermission: string,
): Promise<void> {
if (hasFreightPermission(user, staffPermission)) return;
const row = await this.wagonCancellationService.findById(cancellationId);
const booking = await this.bookingsService.findById(row.bookingId);
await this.bookingsService.assertCustomerCanAccessBooking(user?.id, booking);
}
@Get(':id/customer-trucks')
@ApiOperation({ summary: 'List customer self-haul trucks (multi-truck) for a booking' })
async listCustomerTrucks(
@@ -1335,6 +1490,19 @@ export class BookingsController {
return this.transitionService.enrichBookingResponse(booking);
}
@Post(":id/customer-cancel")
@ApiOperation({
summary:
"Customer cancels their own booking before payment — no cancellation fee",
})
async customerCancel(
@Param("id", ParseUUIDPipe) id: string,
@Body() dto: RejectBookingDto,
) {
const booking = await this.transitionService.customerCancel(id, dto.reason);
return this.transitionService.enrichBookingResponse(booking);
}
@Post(":id/cancel-hold")
@ApiOperation({
summary:

View File

@@ -38,6 +38,9 @@ import { BookingRateSnapshot } from './entities/booking-rate-snapshot.entity';
import { BookingContractSignature } from './entities/booking-contract-signature.entity';
import { BookingReviewNote } from './entities/booking-review-note.entity';
import { Booking } from './entities/booking.entity';
import { BookingWagonCancellation } from './entities/booking-wagon-cancellation.entity';
import { BookingWagonCancellationsRepository } from './booking-wagon-cancellations.repository';
import { BookingWagonCancellationService } from './booking-wagon-cancellation.service';
import { CustomerTruckAssignment } from './entities/customer-truck-assignment.entity';
import { CustomerTruckContainer } from './entities/customer-truck-container.entity';
import { CustomerTruckAssignmentsRepository } from './customer-truck-assignments.repository';
@@ -65,6 +68,7 @@ import { VehiclesModule } from "../vehicles/vehicles.module";
BookingReviewNote,
BookingContractSignature,
BookingContainerAllocation,
BookingWagonCancellation,
CustomerTruckAssignment,
CustomerTruckContainer,
]),
@@ -109,6 +113,8 @@ import { VehiclesModule } from "../vehicles/vehicles.module";
CustomerTruckAssignmentsRepository,
CustomerTruckService,
ContainerReceiptService,
BookingWagonCancellationsRepository,
BookingWagonCancellationService,
],
exports: [
BookingsService,
@@ -120,6 +126,7 @@ import { VehiclesModule } from "../vehicles/vehicles.module";
ConsolidationService,
CustomerTruckService,
ContainerReceiptService,
BookingWagonCancellationService,
],
})
export class BookingsModule { }

View File

@@ -339,6 +339,64 @@ export class BookingsService {
};
}
/**
* Allocated wagons of a booking as JSON — the portal's "Wagons" tab. Same
* join chain as the carriage acceptance sheet, but structured (containers as
* an array per wagon, bulk load description when the wagon carries bulk).
* Empty array until the booking has been allocated onto a train.
*/
async wagonAllocations(bookingId: string): Promise<unknown[]> {
return this.dataSource.query(
`SELECT a.id AS "allocationId",
tsw.sequence_no AS "sequenceNo",
w.wagon_number AS "wagonNumber",
COALESCE(wt.name, wt.code) AS "wagonType",
wt.code AS "wagonTypeCode",
wt.tare_weight_tons AS "tareWeightTons",
tsw.capacity_tons AS "capacityTons",
tsw.length_meters AS "lengthMeters",
a.allocated_weight_tons AS "allocatedWeightTons",
a.load_type AS "loadType",
a.status AS "status",
s.train_number AS "trainNumber",
s.scheduled_departure_date AS "departureAt",
so.label AS "originStation",
sd.label AS "destinationStation",
bl.cargo_description AS "bulkCargoDescription",
bl.quantity AS "bulkQuantity",
COALESCE(
json_agg(
json_build_object(
'containerNumber', ci.container_number,
'sealNumber', ci.seal_number,
'positionOnWagon', ci.position_on_wagon,
'grossWeightTons', ci.gross_weight_tons
) ORDER BY ci.position_on_wagon, ci.container_number
) FILTER (WHERE ci.id IS NOT NULL),
'[]'
) AS "containers"
FROM freight.wagon_booking_allocations a
JOIN freight.train_set_wagons tsw
ON tsw.id = a.train_set_wagon_id AND tsw.deleted_at IS NULL
LEFT JOIN freight.wagon_types wt ON wt.id = tsw.wagon_type_id
LEFT JOIN freight.wagons w ON w.id = tsw.physical_wagon_id
LEFT JOIN freight.train_schedules s
ON s.train_set_id = tsw.train_set_id AND s.deleted_at IS NULL
LEFT JOIN freight.yards so ON so.id = s.origin_station_id
LEFT JOIN freight.yards sd ON sd.id = s.destination_station_id
LEFT JOIN freight.wagon_allocation_container_items ci
ON ci.wagon_booking_allocation_id = a.id AND ci.deleted_at IS NULL
LEFT JOIN freight.wagon_allocation_bulk_loads bl
ON bl.wagon_booking_allocation_id = a.id AND bl.deleted_at IS NULL
WHERE a.booking_id = $1 AND a.deleted_at IS NULL
GROUP BY tsw.id, a.id, w.wagon_number, wt.name, wt.code, wt.tare_weight_tons,
s.train_number, s.scheduled_departure_date, so.label, sd.label,
bl.cargo_description, bl.quantity
ORDER BY tsw.sequence_no`,
[bookingId],
);
}
/**
* Split the booking amount across its wagons, proportional to allocated weight
* (equal shares when no weights are recorded). The last row absorbs the rounding
@@ -1425,7 +1483,46 @@ export class BookingsService {
tradeDirection,
);
}
if (dto.scheduledDate) updates.scheduledDate = new Date(dto.scheduledDate);
// Re-pinning the departure day on an edit (e.g. fixing a CHANGES_REQUESTED
// booking) must obey the same gate as creation: the route needs an OPEN
// departure on that EAT day that can carry the cargo. Skipped when the day
// didn't change, for general contracts (period-based, no pinned day) and
// for intercity (staff assign a passing train later).
if (dto.scheduledDate) {
const day = eatDay(new Date(dto.scheduledDate));
const dayChanged =
!existing.scheduledDate || eatDay(existing.scheduledDate) !== day;
if (
dayChanged &&
existing.bookingType !== 'GENERAL_CONTRACT' &&
tradeDirection !== 'DOMESTIC'
) {
const { hasDeparture, hasCompatible } =
await this.trainSchedulingService.checkDayCargoCompatibility(
originYardId,
destinationYardId,
day,
{
freightType: freightType as 'CONTAINER' | 'BULK',
cargoTypeId,
containerTypeIds: containers
.map((c) => c.containerTypeId)
.filter((cid): cid is string => Boolean(cid)),
},
);
if (!hasDeparture) {
throw new BadRequestException(
'No departures available on the selected day for this route',
);
}
if (!hasCompatible) {
throw new BadRequestException(
'No wagon on the selected day can carry this cargo type — please choose another day',
);
}
}
updates.scheduledDate = new Date(dto.scheduledDate);
}
if (dto.estimatedShipmentDate)
updates.estimatedShipmentDate = new Date(dto.estimatedShipmentDate);
if (dto.startDate) updates.startDate = new Date(dto.startDate);

View File

@@ -0,0 +1,112 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { Type } from 'class-transformer';
import {
ArrayNotEmpty,
IsArray,
IsDateString,
IsIn,
IsInt,
IsNumber,
IsOptional,
IsString,
IsUUID,
MaxLength,
Min,
ValidateNested,
} from 'class-validator';
import { WAGON_CANCELLATION_STATUSES } from '../entities/booking-wagon-cancellation.entity';
export class CancelContainerLineDto {
@ApiProperty({ description: 'Container size (ft) as stored on the booking line, e.g. "20", "40"' })
@IsString()
containerSize!: string;
@ApiProperty({ description: 'How many units of this size to cancel' })
@IsInt()
@Min(1)
quantity!: number;
}
export class RequestWagonCancellationDto {
@ApiPropertyOptional({
description:
'Cancel SPECIFIC allocated wagons: wagon_booking_allocation ids from GET /bookings/:id/wagons. ' +
'When set, wagons/containers are derived from the selected wagons and the other fields are ignored.',
type: [String],
})
@IsOptional()
@IsArray()
@ArrayNotEmpty()
@IsUUID('4', { each: true })
wagonAllocationIds?: string[];
@ApiPropertyOptional({
description: 'BULK bookings: number of wagons to cancel (tons derived proportionally)',
})
@IsOptional()
@IsNumber()
@Min(0.5)
wagons?: number;
@ApiPropertyOptional({
description: 'CONTAINER bookings: units to cancel per size (wagons derived per size)',
type: [CancelContainerLineDto],
})
@IsOptional()
@IsArray()
@ArrayNotEmpty()
@ValidateNested({ each: true })
@Type(() => CancelContainerLineDto)
containers?: CancelContainerLineDto[];
@ApiPropertyOptional({ description: 'Customer reason for the cancellation' })
@IsOptional()
@IsString()
@MaxLength(1000)
reason?: string;
}
export class RebookCancelledWagonsDto {
@ApiProperty({ description: 'Shipment day the credit is rebooked onto (ISO date)' })
@IsDateString()
scheduledDate!: string;
}
export class FilterWagonCancellationsDto {
@ApiPropertyOptional({ enum: WAGON_CANCELLATION_STATUSES, isArray: true })
@IsOptional()
@IsArray()
@IsIn(WAGON_CANCELLATION_STATUSES as readonly string[], { each: true })
statuses?: string[];
@ApiPropertyOptional({ description: 'Booking reference / company name search' })
@IsOptional()
@IsString()
@MaxLength(120)
search?: string;
@ApiPropertyOptional()
@IsOptional()
@IsDateString()
from?: string;
@ApiPropertyOptional()
@IsOptional()
@IsDateString()
to?: string;
@ApiPropertyOptional({ default: 1 })
@IsOptional()
@Type(() => Number)
@IsInt()
@Min(1)
page?: number;
@ApiPropertyOptional({ default: 10 })
@IsOptional()
@Type(() => Number)
@IsInt()
@Min(1)
pageSize?: number;
}

View File

@@ -0,0 +1,137 @@
import { BaseEntity } from '@edr/api-common';
import { Column, Entity, Index, JoinColumn, ManyToOne } from 'typeorm';
import { Invoice } from '../../billing/entities/invoice.entity';
import { Rate } from '../../rule-engine/entities/rate.entity';
import { Booking } from './booking.entity';
export const WAGON_CANCELLATION_STATUSES = [
// Requested; fee invoice open; wagons still allocated to the customer.
'FEE_PENDING',
// Fee settled; booking reduced, wagons freed; credit waiting for a rebook.
'CREDIT_AVAILABLE',
// Credit redeemed into a new PAID booking (rebookedBookingId).
'REBOOKED',
// Customer/staff voided the request before paying the fee. Nothing changed.
'WITHDRAWN',
// Reserved for a future expiry policy; not set by code today.
'EXPIRED',
] as const;
export type WagonCancellationStatus = (typeof WAGON_CANCELLATION_STATUSES)[number];
/** Snapshot of one physical container unit cut by the cancellation. */
export interface CancelledUnitSnapshot {
containerSize: string;
containerNumber: string;
sealNumber?: string | null;
vgmTons: number;
isHazardous: boolean;
isReefer: boolean;
}
/** What the cancellation cut, in the booking's own quantity terms. */
export interface CancelledQuantities {
/** Bulk bookings: tons cut (PER_ITEM cargo: item count, matching cargoTotalWeightVgm). */
bulkTons?: number;
/** Container bookings: units cut per container size. */
bySize?: Record<string, number>;
/**
* Container bookings: the exact physical units cut. Snapshotted at request
* time when the customer picked specific wagons, otherwise at fee settlement
* (LIFO trim). The rebook reconstructs the new booking from THESE — never
* from a soft-deleted-row scan, which could pick up units dropped by an
* unrelated batch split on the same booking.
*/
units?: CancelledUnitSnapshot[];
/**
* Specific-wagon cancellation: the wagon_booking_allocation ids the customer
* picked in the Wagons tab. T2 releases exactly these (fallback to
* newest-first for any id that no longer exists, e.g. after a re-batch).
*/
allocationIds?: string[];
/**
* The wagon allocations were already released from the schedule at REQUEST
* time (policy: wagons free up immediately; the fee is still owed before the
* credit can be rebooked). Tells T2 to skip its release step so it never
* deletes wagons the batch engine re-assigned in between.
*/
releasedAtRequest?: boolean;
}
/**
* One partial-wagon-cancellation cycle on a PAID booking — the audit trail and
* the state machine. The credit itself is not a wallet balance: redeeming it
* creates a real booking through the under-contract create path and marks it
* PAID (see BookingWagonCancellationService).
*/
@Entity({ schema: 'freight', name: 'booking_wagon_cancellations' })
@Index(['bookingId'])
@Index(['status'])
export class BookingWagonCancellation extends BaseEntity {
@Column({ name: 'booking_id', type: 'uuid' })
bookingId!: string;
@ManyToOne(() => Booking)
@JoinColumn({ name: 'booking_id' })
booking?: Booking;
@Column({ name: 'rebooked_booking_id', type: 'uuid', nullable: true })
rebookedBookingId?: string | null;
@ManyToOne(() => Booking, { nullable: true })
@JoinColumn({ name: 'rebooked_booking_id' })
rebookedBooking?: Booking | null;
@Column({ name: 'wagons_cancelled', type: 'numeric', precision: 6, scale: 2 })
wagonsCancelled!: number;
@Column({ name: 'weight_tons', type: 'numeric', precision: 12, scale: 3, default: 0 })
weightTons!: number;
@Column({ name: 'cancelled_quantities', type: 'jsonb' })
cancelledQuantities!: CancelledQuantities;
/**
* The freight value of the cancelled part at the ORIGINAL booking's price —
* informational (shown to the customer as "credit worth"); no refund is ever
* issued from it, the credit is redeemed by rebooking.
*/
@Column({ name: 'credit_amount', type: 'numeric', precision: 14, scale: 2, default: 0 })
creditAmount!: number;
@Column({ name: 'fee_rate_id', type: 'uuid', nullable: true })
feeRateId?: string | null;
@ManyToOne(() => Rate, { nullable: true })
@JoinColumn({ name: 'fee_rate_id' })
feeRate?: Rate | null;
@Column({ name: 'fee_amount', type: 'numeric', precision: 14, scale: 2 })
feeAmount!: number;
@Column({ name: 'fee_currency', type: 'varchar', length: 8, default: 'ETB' })
feeCurrency!: string;
@Column({ name: 'fee_invoice_id', type: 'uuid', nullable: true })
feeInvoiceId?: string | null;
@ManyToOne(() => Invoice, { nullable: true })
@JoinColumn({ name: 'fee_invoice_id' })
feeInvoice?: Invoice | null;
@Column({ name: 'fee_paid_at', type: 'timestamptz', nullable: true })
feePaidAt?: Date | null;
@Column({ name: 'status', type: 'varchar', length: 30, default: 'FEE_PENDING' })
status!: string;
@Column({ name: 'reason', type: 'text', nullable: true })
reason?: string | null;
@Column({ name: 'requested_by_user_id', type: 'uuid', nullable: true })
requestedByUserId?: string | null;
@Column({ name: 'rebooked_at', type: 'timestamptz', nullable: true })
rebookedAt?: Date | null;
}

View File

@@ -2057,6 +2057,11 @@ export class CompaniesService {
// replace it before the application counts as complete.
const flaggedDelegation = delegationDue && delegation.flagged;
// Mirrors `poaProven` in buildCompanyIdentityState — see the note there.
const poaProven = identity.faydaRequired
? identity.poa.verified
: identity.poa.verified || Boolean(identity.poa.name?.trim());
const outstanding = [
...missingInfo.map((f) => `Add your ${f.label.toLowerCase()}`),
...missingDocs.map((d) => `Upload your ${d.fileLabel}`),
@@ -2074,8 +2079,19 @@ export class CompaniesService {
...(identity.faydaRequired && !identity.owner.verified
? ["Verify the company owner's identity with Fayda"]
: []),
...((poaRequired || poaProvided) && !identity.poa.verified
? ["Verify your Power of Attorney's identity with Fayda"]
// Nationality-aware, exactly like `poaProven` in
// buildCompanyIdentityState and the check in `assertIdentityVerified`:
// Fayda is an Ethiopian national ID, so a foreign company's typed
// representative has to count. Demanding a verification here regardless
// made this list disagree with the rule actually enforced, and left a
// foreign freight forwarder unable to submit — asked for a Fayda
// verification its representative may have no way to obtain.
...((poaRequired || poaProvided) && !poaProven
? [
identity.faydaRequired
? "Verify your Power of Attorney's identity with Fayda"
: "Name your Power of Attorney, or verify them with Fayda",
]
: []),
...(identity.passportRequired && !identity.owner.passportNumber
? ["Add the company owner's passport number"]
@@ -2089,7 +2105,10 @@ export class CompaniesService {
const poaItemCount = delegationDue ? 1 : 0;
// One item per identity credential the company has to prove: the owner
// always (Fayda for Ethiopian, passport for foreign), plus the PoA once
// there is one — that one is Fayda whatever the nationality.
// there is one — Fayda for an Ethiopian company, a named representative
// for a foreign one, same rule as `poaProven` above. Counting a foreign
// company's typed PoA as unproven here left the progress bar permanently
// short of 100% on an item it had already satisfied.
const ownerCredentialDue =
identity.faydaRequired || identity.passportRequired;
const ownerCredentialProven = identity.faydaRequired
@@ -2099,7 +2118,7 @@ export class CompaniesService {
(ownerCredentialDue ? 1 : 0) + (delegationDue ? 1 : 0);
const missingIdentityCount =
(ownerCredentialDue && !ownerCredentialProven ? 1 : 0) +
(delegationDue && !identity.poa.verified ? 1 : 0);
(delegationDue && !poaProven ? 1 : 0);
const total =
requiredInfo.length +
requiredDocCount +
@@ -2767,7 +2786,13 @@ export class CompaniesService {
// The verified payload owns the person's details from here on.
...(result.fullName ? { [`${prefix}Name`]: result.fullName } : {}),
...(result.email ? { [`${prefix}Email`]: result.email } : {}),
...(result.phoneNumber ? { [`${prefix}Phone`]: result.phoneNumber } : {}),
// Fayda returns whatever the national registry holds, which is routinely a
// local number ("0911223344"). Every typed phone in this service is stored
// E.164, and `@IsValidPhone()` rejects anything else — so a raw claim here
// becomes a value the portal reads back and cannot resubmit.
...(result.phoneNumber
? { [`${prefix}Phone`]: normalizeE164(result.phoneNumber) }
: {}),
...(result.address ? { [`${prefix}Address`]: result.address } : {}),
};

View File

@@ -1,4 +1,12 @@
import { IsString, IsOptional, IsEmail, MaxLength, IsEnum, IsIn } from 'class-validator';
import {
IsString,
IsOptional,
IsEmail,
MaxLength,
IsEnum,
IsIn,
Matches,
} from 'class-validator';
import { ETHIOPIAN_REGIONS, type EthiopianRegion } from '@edr/types';
import { CompanyNationality } from '../entities/company.entity';
import { IsValidPhone } from '../../../common/validators/is-phone-number.validator';
@@ -39,9 +47,13 @@ export class UpdateProfileDto {
@IsTin({ message: 'TIN must be exactly 10 digits' })
tin?: string;
// Ethiopian VAT registration numbers are 10 digits, the same shape as the
// TIN. Both portal forms enforce that; without it here the API happily stored
// whatever a stale client sent, and the two layers disagreed about what the
// column may hold.
@IsOptional()
@IsString()
@MaxLength(50)
@Matches(/^\d{10}$/, { message: 'VAT number must be exactly 10 digits' })
vatNumber?: string;
// `fanNumber` is deliberately absent: the FAN is the Fayda number of the

View File

@@ -98,6 +98,9 @@ export class ContractBookingService {
private readonly containerTypesService: ContainerTypesService,
private readonly ruleEngineService: RuleEngineService,
private readonly milestoneService: ClearanceMilestoneService,
// forwardRef: part of the booking-invoice ⇄ wagon-cancellation ⇄ contracts
// require cycle (see BookingTransitionService).
@Inject(forwardRef(() => BookingInvoiceService))
private readonly invoiceService: BookingInvoiceService,
private readonly bookingNotifier: BookingLifecycleNotifierService,
private readonly dataSource: DataSource,
@@ -1882,6 +1885,9 @@ export class ContractBookingService {
async validateShipment(
contractId: string,
dto: CreateBookingUnderContractDto,
// Completion/resubmit preview: the booking being completed must not clash
// with its own persisted containers.
excludeBookingId?: string,
): Promise<{
overweightLines: Array<{
containerTypeCode: string;
@@ -2043,6 +2049,7 @@ export class ContractBookingService {
originYardId: route?.originYardId,
destinationYardId: route?.destinationYardId,
},
excludeBookingId,
);
containerClashErrors = clashes.map(
(c) =>

View File

@@ -1124,8 +1124,11 @@ export class ContractsController {
validateShipment(
@Param('id', ParseUUIDPipe) id: string,
@Body() dto: CreateBookingUnderContractDto,
// Completion/resubmit preview: exclude this booking's own persisted
// containers from the same-train clash check.
@Query('bookingId') bookingId?: string,
) {
return this.contractBookingService.validateShipment(id, dto);
return this.contractBookingService.validateShipment(id, dto, bookingId);
}
@Get(':id/capacity')

View File

@@ -460,8 +460,21 @@ export class LastMileService {
@OnEvent("last_mile.invoice.paid")
async onBookingInvoicePaid(payload: InvoiceEventPayload): Promise<void> {
try {
// Invoice paid → the delivery is complete. Route through update() so it
// also frees the trucks + records history (same as "Mark Delivered").
if (payload.type === 'LAST_MILE_ADVANCE') {
// Advance paid → the leg becomes dispatchable, not delivered.
await this.update(payload.sourceId, {
status: 'READY_TO_TRANSIT',
advancedPayment: payload.totalAmount,
} as unknown as UpdateLastMileDto);
this.logger.log(
`Last-mile ${payload.sourceId} READY_TO_TRANSIT on advance invoice ${payload.invoiceId} payment`,
);
return;
}
if (payload.type !== 'DELIVERY_FEE') return;
// Delivery-fee invoice paid → the delivery is complete. Route through
// update() so it also frees the trucks + records history (same as
// "Mark Delivered").
await this.update(payload.sourceId, { status: 'DELIVERED', paid: true } as unknown as UpdateLastMileDto);
this.logger.log(`Last-mile ${payload.sourceId} marked DELIVERED on invoice ${payload.invoiceId} payment`);
} catch (err) {

View File

@@ -1,8 +1,8 @@
import {
IsEnum,
IsIn,
IsInt,
IsISO8601,
IsNumber,
IsOptional,
IsPositive,
IsString,
@@ -37,7 +37,9 @@ export class PaymentEventDto {
@ApiProperty() @IsString() referenceId!: string;
@ApiProperty() @IsString() merchantOrderId!: string;
@ApiProperty({ enum: ProviderMethod }) @IsEnum(ProviderMethod) provider!: string;
@ApiProperty() @IsInt() @IsPositive() amountMinor!: number;
// Major units, fractional (payment-api stores it as double precision) — an
// invoice of 12345.67 must not be rejected by an integer-only validator.
@ApiProperty() @IsNumber() @IsPositive() amountMinor!: number;
@ApiProperty() @IsString() currency!: string;
@ApiPropertyOptional() @IsOptional() @IsString() providerTxnId?: string;

View File

@@ -43,6 +43,12 @@ export class YardsRepository implements IYardsRepository {
findPaged(query: ListYardsQueryDto): Promise<PaginatedResponse<Yard>> {
const qb = this.repo
.createQueryBuilder('yard')
// createQueryBuilder does NOT auto-apply the soft-delete filter that
// repo.find()/findOne() get for free — without this, a renamed/replaced
// yard (e.g. an old "DMP" superseded by a new one) still shows up
// alongside the live one in every picker built off this endpoint, and a
// route picked against the dead yard id never matches any LIVE rate.
.where('yard.deleted_at IS NULL')
.orderBy(`yard.${query.sortBy ?? 'displayOrder'}`, query.sortOrder ?? 'ASC')
.addOrderBy('yard.label', 'ASC');

View File

@@ -7,7 +7,7 @@ import {
NotFoundException,
} from '@nestjs/common';
import { PaginatedResponse, YardCountry } from '@edr/types';
import { Not } from 'typeorm';
import { IsNull, Not } from 'typeorm';
import { CreateRateDto } from '../dto/create-rate.dto';
import { ListRatesQueryDto } from '../dto/list-rule-engine-query.dto';
import { UpdateRateDto } from '../dto/update-rate.dto';
@@ -344,11 +344,12 @@ export class RatesService {
/**
* Validate and normalise the last-mile band fields for a rate shape.
*
* Last-mile rates come in two calculation modes: bulk (PER_TON_KM — price =
* tons × km × rate, one row, no scope) and container (PER_KM — one row per
* container type per distance band, price = km × rate × quantity). Every
* other rate shape has its band fields cleared, mirroring how yard scope is
* cleared for non-route rates.
* Last-mile rates come in two calculation modes: bulk (PER_TON_KM — one row
* per distance band, price = tons × km × rate) and container (PER_KM — one
* row per container type per distance band, price = km × rate × quantity).
* A bandless bulk row (NULL minKm) is the legacy pre-band shape and still
* prices every distance. Every other rate shape has its band fields cleared,
* mirroring how yard scope is cleared for non-route rates.
*/
private resolveLastMileBand(input: {
appliesTo: Rate['appliesTo'];
@@ -366,7 +367,21 @@ export class RatesService {
'A bulk last-mile rate (per ton per km) cannot be scoped to a container type.',
);
}
return { minKm: null, maxKm: null };
const minKm = input.minKm ?? null;
const maxKm = input.maxKm ?? null;
if (minKm === null) {
if (maxKm !== null) {
throw new BadRequestException(
'"To km" needs a "From km" — set the band start (0 for the first tier).',
);
}
// Legacy bandless bulk rate — prices every distance.
return { minKm: null, maxKm: null };
}
if (maxKm !== null && maxKm <= minKm) {
throw new BadRequestException('"To km" must be greater than "From km".');
}
return { minKm, maxKm };
}
if (rateUnit === 'PER_KM') {
@@ -393,14 +408,16 @@ export class RatesService {
}
/**
* Reject a container last-mile band that overlaps an existing band for the
* same container type. Bands are half-open [minKm, maxKm) with NULL maxKm =
* open-ended, so 030 and 30∞ tile cleanly. Checked across every
* non-superseded row (DRAFT included) — two drafts with colliding bands would
* only defer the conflict to approval.
* Reject a last-mile band that overlaps an existing band for the same scope —
* container bands collide per container type (PER_KM), bulk bands collide
* with each other (PER_TON_KM, no container scope). Bands are half-open
* [minKm, maxKm) with NULL maxKm = open-ended, so 030 and 30∞ tile
* cleanly. Checked across every non-superseded row (DRAFT included) — two
* drafts with colliding bands would only defer the conflict to approval.
*/
private async assertNoBandOverlap(input: {
containerTypeId: string;
rateUnit: 'PER_KM' | 'PER_TON_KM';
containerTypeId: string | null;
minKm: number;
maxKm: number | null;
ignoreId?: string;
@@ -408,8 +425,8 @@ export class RatesService {
const siblings = await this.repository.findAll({
where: {
rateType: 'LAST_MILE',
rateUnit: 'PER_KM',
containerTypeId: input.containerTypeId,
rateUnit: input.rateUnit,
containerTypeId: input.containerTypeId ?? IsNull(),
status: Not('SUPERSEDED'),
},
});
@@ -425,7 +442,7 @@ export class RatesService {
if (input.minKm < sibMax && sibMin < newMax) {
const sibLabel = `${sibMin}${sibMax === Number.POSITIVE_INFINITY ? 'open' : sibMax} km`;
throw new ConflictException(
`This distance band overlaps the existing ${sibLabel} band for this container type. Adjust the ranges so each distance falls in exactly one band.`,
`This distance band overlaps the existing ${sibLabel} band for ${input.rateUnit === 'PER_TON_KM' ? 'bulk last-mile' : 'this container type'}. Adjust the ranges so each distance falls in exactly one band.`,
);
}
}
@@ -538,8 +555,12 @@ export class RatesService {
minKm: dto.minKm,
maxKm: dto.maxKm,
});
if (appliesTo === 'LAST_MILE' && rateUnit === 'PER_KM' && containerTypeId && minKm !== null) {
await this.assertNoBandOverlap({ containerTypeId, minKm, maxKm });
if (
appliesTo === 'LAST_MILE' &&
(rateUnit === 'PER_KM' || rateUnit === 'PER_TON_KM') &&
minKm !== null
) {
await this.assertNoBandOverlap({ rateUnit, containerTypeId, minKm, maxKm });
}
await this.assertNoDuplicatePattern({
@@ -742,12 +763,12 @@ export class RatesService {
updates.maxKm = maxKm;
if (
appliesTo === 'LAST_MILE' &&
rateUnit === 'PER_KM' &&
updates.containerTypeId &&
(rateUnit === 'PER_KM' || rateUnit === 'PER_TON_KM') &&
minKm !== null
) {
await this.assertNoBandOverlap({
containerTypeId: updates.containerTypeId,
rateUnit,
containerTypeId: updates.containerTypeId ?? null,
minKm,
maxKm,
ignoreId: id,

View File

@@ -31,6 +31,19 @@ export function paymentDrainMs(): number {
);
}
/**
* ISO timestamp of the end of a pay window's drain tail, for client display
* (the "payment processing" countdown). Null in ⇒ null out.
*/
export function paymentDrainEndsAtIso(
deadline: Date | string | null | undefined,
): string | null {
if (deadline == null) return null;
const ms = new Date(deadline).getTime();
if (!Number.isFinite(ms)) return null;
return new Date(ms + paymentDrainMs()).toISOString();
}
/**
* A pay window AND its drain tail have closed.
*

View File

@@ -14,6 +14,7 @@ import { Server, Socket } from 'socket.io';
import { WsAuthService } from '../notification-inbox/ws-auth.service';
import { TrainSchedule } from '../train-schedules/entities/train-schedule.entity';
import { paymentDrainEndsAtIso } from './booking-batch.constants';
/**
* Server → client push for booking-window state changes. Same handshake model
@@ -61,6 +62,7 @@ export class BookingWindowGateway implements OnGatewayConnection {
windowClosesAt: schedule.windowClosesAt?.toISOString() ?? null,
docReviewEndsAt: schedule.docReviewEndsAt?.toISOString() ?? null,
paymentPhaseEndsAt: schedule.paymentPhaseEndsAt?.toISOString() ?? null,
paymentDrainEndsAt: paymentDrainEndsAtIso(schedule.paymentPhaseEndsAt),
scheduledDepartureDate: schedule.scheduledDepartureDate?.toISOString() ?? null,
};
this.server.emit(BOOKING_WINDOW_WS_EVENTS.PHASE, payload);

View File

@@ -1,5 +1,6 @@
import {
DEFAULT_PAYMENT_DRAIN_MINUTES,
paymentDrainEndsAtIso,
paymentDrainMs,
payWindowLapsed,
} from "./booking-batch.constants";
@@ -64,4 +65,16 @@ describe("payWindowLapsed — pay-window drain tail", () => {
expect(paymentDrainMs()).toBe(DEFAULT_PAYMENT_DRAIN_MINUTES * MIN);
}
});
it("paymentDrainEndsAtIso reports deadline + drain, null/garbage-safe", () => {
expect(paymentDrainEndsAtIso(deadline)).toBe(
new Date(at(DEFAULT_PAYMENT_DRAIN_MINUTES * MIN)).toISOString(),
);
expect(paymentDrainEndsAtIso(deadline.toISOString())).toBe(
new Date(at(DEFAULT_PAYMENT_DRAIN_MINUTES * MIN)).toISOString(),
);
expect(paymentDrainEndsAtIso(null)).toBeNull();
expect(paymentDrainEndsAtIso(undefined)).toBeNull();
expect(paymentDrainEndsAtIso("not-a-date")).toBeNull();
});
});

View File

@@ -153,6 +153,7 @@ import {
DEFAULT_CONTAINER_WAGON_CAPACITY_TONS,
DEFAULT_CONTAINER_WAGON_LENGTH_METERS,
DEFAULT_CONTAINER_WAGON_TARE_TONS,
paymentDrainEndsAtIso,
} from './booking-batch.constants';
import { orderConsistWagons } from './consist-order.util';
import {
@@ -1546,23 +1547,10 @@ export class TrainSchedulingService {
}
: globalCfg;
// Staff cannot schedule inside the lead window — there must be room for a
// booking window before departure. IMPORT/DOMESTIC lead is in whole EAT
// days (lead 3, today 11th → first allowed departure is the 14th); EXPORT
// lead is in hours (24h = 1 day ahead). Checked against the schedule's OWN
// lead, so a custom lead is honoured rather than rejected by the global one.
const earliest = earliestSchedulableDeparture(direction, windowCfg, new Date());
if (departure.getTime() < earliest.getTime()) {
const detail =
direction === 'EXPORT'
? `at least ${windowCfg.exportBookingLeadHours} hour(s) ahead`
: `at least ${windowCfg.importWindowLeadDays} day(s) ahead`;
throw new BadRequestException(
`Departure ${departure.toISOString()} is inside the booking lead window; ` +
`${direction === 'EXPORT' ? 'export' : 'import'} trains must be scheduled ${detail} ` +
`(earliest ${earliest.toISOString()})`,
);
}
// Short-notice trains are allowed: a departure inside the booking lead
// window is NOT rejected — the window just opens immediately (opensAt is
// clamped to `now` below) instead of waiting out a lead that has already
// passed. Only `updateScheduleDate` still enforces the lead floor.
// Freeze the rule this schedule is born with. A later global-rules edit
// only re-derives NOT-YET-OPEN schedules (see restampPendingWindows); an
@@ -1577,6 +1565,11 @@ export class TrainSchedulingService {
...ruleSnapshot,
...computeImportWindowTimes(departure, windowCfg, new Date()),
};
// Inside-lead departure (e.g. a huge configured lead): the raw open lands
// in the past — clamp it to `now` so the window tick opens it immediately.
if (computedTimes.windowOpensAt.getTime() < Date.now()) {
computedTimes.windowOpensAt = new Date();
}
if (
computedTimes.windowOpensAt.getTime() >= computedTimes.windowClosesAt.getTime()
) {
@@ -6948,6 +6941,7 @@ export class TrainSchedulingService {
windowClosesAt: r.window_closes_at,
docReviewEndsAt: r.doc_review_ends_at,
paymentPhaseEndsAt: r.payment_phase_ends_at,
paymentDrainEndsAt: paymentDrainEndsAtIso(r.payment_phase_ends_at),
bookingWindowStatus: r.booking_window_status,
bookingCycleNo: r.booking_cycle_no,
departureDate: r.scheduled_departure_date,

View File

@@ -68,6 +68,11 @@ export const BOOKING_PERMISSIONS: FreightPermissionSeed[] = [
// Header alarm for the document-review deadline: its own key so only the
// position types that actually decide operation requests are alerted.
perm('a1000001-0001-4000-8000-000000000025', 'edr_freight_app:bookings:doc_review_alert', 'See document-review deadline alarm'),
// Partial wagon cancellation (paid bookings): staff-side keys. The customer
// portal needs none — customer actions are ownership-scoped on the API.
perm('a1000001-0001-4000-8000-000000000026', 'edr_freight_app:bookings:wagon_cancellation_view', 'View wagon cancellation history'),
perm('a1000001-0001-4000-8000-000000000027', 'edr_freight_app:bookings:wagon_cancellation_void', 'Void a pending wagon cancellation'),
perm('a1000001-0001-4000-8000-000000000028', 'edr_freight_app:bookings:wagon_cancellation_rebook', 'Rebook cancelled wagons for a customer'),
];
/**
@@ -431,6 +436,9 @@ export const FREIGHT_PERMS = {
uploadClearanceOutput: 'edr_freight_app:bookings:upload_clearance_output',
finalizeClearance: 'edr_freight_app:bookings:finalize_clearance',
docReviewAlert: 'edr_freight_app:bookings:doc_review_alert',
wagonCancellationView: 'edr_freight_app:bookings:wagon_cancellation_view',
wagonCancellationVoid: 'edr_freight_app:bookings:wagon_cancellation_void',
wagonCancellationRebook: 'edr_freight_app:bookings:wagon_cancellation_rebook',
},
contracts: {
view: 'edr_freight_app:contracts:view',
@@ -825,6 +833,8 @@ export const ROLE_PERMISSION_PRESETS = {
FREIGHT_PERMS.bookings.approveLineStaff,
FREIGHT_PERMS.bookings.rejectApproval,
FREIGHT_PERMS.bookings.cancel,
FREIGHT_PERMS.bookings.wagonCancellationView,
FREIGHT_PERMS.bookings.wagonCancellationVoid,
FREIGHT_PERMS.contracts.view,
...bothFreightTypes(FREIGHT_PERMS.contracts.staffAccept),
...bothFreightTypes(FREIGHT_PERMS.contracts.requestChanges),
@@ -837,6 +847,7 @@ export const ROLE_PERMISSION_PRESETS = {
operationsOfficer: [
FREIGHT_PERMS.bookings.view,
FREIGHT_PERMS.bookings.operations,
FREIGHT_PERMS.bookings.wagonCancellationView,
// They are the ones who accept/reject operation requests, so they are the
// ones the doc-review countdown is for.
FREIGHT_PERMS.bookings.docReviewAlert,
@@ -877,7 +888,7 @@ export const ROLE_PERMISSION_PRESETS = {
FREIGHT_PERMS.contracts.approveCeo,
...allRuleEngineViewKeys(),
],
finance: [FREIGHT_PERMS.bookings.view],
finance: [FREIGHT_PERMS.bookings.view, FREIGHT_PERMS.bookings.wagonCancellationView],
// Global Logistics: manages ONLY the customs-clearance queue. Scoped out of
// the general booking-request list (no bookings:view) — instead a dedicated
// clearance:view permission lists the clearance bookings. Reviews customer
@@ -920,6 +931,9 @@ export const ROLE_PERMISSION_PRESETS = {
FREIGHT_PERMS.bookings.approveLineStaff,
FREIGHT_PERMS.bookings.rejectApproval,
FREIGHT_PERMS.bookings.cancel,
FREIGHT_PERMS.bookings.wagonCancellationView,
FREIGHT_PERMS.bookings.wagonCancellationVoid,
FREIGHT_PERMS.bookings.wagonCancellationRebook,
FREIGHT_PERMS.bookings.generateContract,
FREIGHT_PERMS.bookings.signStaff,
FREIGHT_PERMS.bookings.reviewDocuments,

View File

@@ -29,6 +29,7 @@ import {
Wallet,
LifeBuoy,
TrainFront,
XCircle,
} from "lucide-react";
import { useEffect } from "react";
import {
@@ -54,6 +55,7 @@ import BookingContractPage from "./pages/bookings/BookingContractPage";
import BookingRequestDetailPage from "./pages/bookings/BookingRequestDetailPage";
import BookingRequestsPage from "./pages/bookings/BookingRequestsPage";
import NewBookingPage from "./pages/bookings/NewBookingPage";
import WagonCancellationsPage from "./pages/bookings/WagonCancellationsPage";
import ContractRequestsPage from "./pages/contracts/ContractRequestsPage";
import ContractRequestDetailPage from "./pages/contracts/ContractRequestDetailPage";
import ContractViewPage from "./pages/contracts/ContractViewPage";
@@ -184,6 +186,12 @@ const buildSidebarSections = (demoItems: SidebarItem[]): SidebarSection[] => [
icon: <FileText />,
permission: FREIGHT_PERMS.bookings.view,
},
{
label: "Wagon cancellations",
href: "/dashboard/wagon-cancellations",
icon: <XCircle />,
permission: FREIGHT_PERMS.bookings.wagonCancellationView,
},
// Operations hub: per-shipment clearance-document review for services
// WITHOUT customs clearing (self-clearance) — bookings only.
{
@@ -647,6 +655,8 @@ const DJ_CLEARANCE_HREF = "/dashboard/gl-djibouti/clearance";
const GL_WORKFLOW_PATH_PATTERNS: RegExp[] = [
/^\/dashboard\/contracts\/[^/]+\/create-booking(\/|$)/,
/^\/dashboard\/bookings\/[^/]+\/clearance(\/|$)/,
// The ET hub's rows open the shipment clearance detail at this URL.
/^\/dashboard\/clearance\/[^/]+(\/|$)/,
];
const isEtClearanceItem = (item: SidebarItem): boolean =>
@@ -895,6 +905,16 @@ const App = () => {
}
/>
<Route path="booking-requests/new" element={<NewBookingPage />} />
<Route
path="wagon-cancellations"
element={
<RequirePermission
permission={FREIGHT_PERMS.bookings.wagonCancellationView}
>
<WagonCancellationsPage />
</RequirePermission>
}
/>
<Route
path="booking-requests/:id"
element={<BookingRequestDetailPage />}

View File

@@ -1,6 +1,6 @@
import type { LucideIcon } from "lucide-react";
import type { ReactNode } from "react";
import { Hash, Package, Ship, Weight, Clock } from "lucide-react";
import { Hash, Package, Ship, Weight, Clock, TrainFront } from "lucide-react";
import { Group, Stack, Text, Divider } from "@mantine/core";
import { cargoTonsAndItems } from "@/utils/cargoWeight";
@@ -50,6 +50,21 @@ export function BookingFactsCard({ booking }: BookingFactsCardProps) {
},
{ icon: Clock, label: "Last Updated", value: formatDate(booking.updatedAt) },
];
// Allocated train facts — only once the booking rides a schedule.
if (booking.trainSchedule?.trainNumber || booking.trainSchedule?.reference) {
facts.splice(1, 0, {
icon: TrainFront,
label: "Allocated Train",
value: [
booking.trainSchedule.trainNumber
? `Train ${booking.trainSchedule.trainNumber}`
: null,
booking.trainSchedule.reference ?? null,
]
.filter(Boolean)
.join(" · "),
});
}
return (
<SectionCard icon={Hash} title="Booking Details" accent="cyan">

View File

@@ -144,4 +144,10 @@ export interface BookingDetailView {
bookingContainers?: BookingContainerView[];
reviewNotes?: BookingReviewNoteView[];
files?: BookingFileView[];
/** The allocated train, present once the booking is placed on a schedule. */
trainSchedule?: {
trainNumber: string | null;
reference: string | null;
scheduledDepartureDate: string | null;
} | null;
}

View File

@@ -225,7 +225,13 @@ export function ExportClearanceStepper({
<Stepper.Step
label="Request transit assignee"
description="Ask GL Djibouti to name the officer handling this shipment"
// Description is the only part of a passed step that stays visible,
// so it carries the assigned officer's name for GL Ethiopia.
description={
clearance.transitAssignee?.name
? `Transit assignee: ${clearance.transitAssignee.name}`
: "Ask GL Djibouti to name the officer handling this shipment"
}
icon={
clearance.transitAssignee?.name ? (
<CheckCircle2 size={14} />

View File

@@ -961,7 +961,7 @@ export default function GlCreateBookingForm() {
// modal falls back to the contract unit-rate estimate while it loads.
const validateShipmentMutation = useMutation({
mutationFn: (dto: Freight.CreateBookingUnderContractDto) =>
contractsService.validateShipment(id ?? "", dto),
contractsService.validateShipment(id ?? "", dto, completeBookingId),
});
const validation = validateShipmentMutation.data ?? null;

View File

@@ -39,6 +39,8 @@ interface WindowRow {
windowClosesAt: string | null;
docReviewEndsAt: string | null;
paymentPhaseEndsAt: string | null;
/** End of the payment drain tail — pending payments may settle until then. */
paymentDrainEndsAt?: string | null;
bookingWindowStatus: string;
bookingCycleNo: number;
departureDate: string;
@@ -94,16 +96,29 @@ const COUNTDOWN_TEXT: Partial<
PRE_WINDOW: { label: "Opens in", expiredText: "Opening now…" },
OPEN: { label: "Closes in", expiredText: "Review starting…" },
DOC_REVIEW: { label: "Doc review ends in", expiredText: "Payment starting…" },
PAYMENT: { label: "Payment ends in", expiredText: "Closing…" },
PAYMENT: { label: "Payment ends in", expiredText: "Finalizing…" },
};
function phaseCountdown(
w: WindowRow,
): { label: string; deadline: string; expiredText: string } | null {
function phaseCountdown(w: WindowRow): {
label: string;
deadline: string;
expiredText: string;
graceDeadline?: string | null;
graceLabel?: string;
} | null {
const state = bookingWindowUiState(w);
const text = COUNTDOWN_TEXT[state.kind];
if (!state.countdownTo || !text) return null;
return { ...text, deadline: state.countdownTo };
// Once the pay deadline lapses, pending payments still settle during the
// drain tail — count it down as "processing" instead of a stale "closing".
const grace =
state.kind === "PAYMENT" && w.paymentDrainEndsAt
? {
graceDeadline: w.paymentDrainEndsAt,
graceLabel: "Processing payments — closes in",
}
: undefined;
return { ...text, deadline: state.countdownTo, ...grace };
}
/** Badge label + Mantine color per UI state — same state the countdown uses. */
@@ -225,6 +240,8 @@ function WindowCard({ w }: { w: WindowRow }) {
deadline={cd.deadline}
label={cd.label}
expiredText={cd.expiredText}
graceDeadline={cd.graceDeadline}
graceLabel={cd.graceLabel}
size="xs"
/>
</Box>

View File

@@ -357,7 +357,14 @@ export function PhasedClearanceActionPanel({
<Stepper.Step
label="Request transit assignee"
description="Ask GL Djibouti to name the officer handling this shipment"
// Once the flow moves past this step its content collapses — the
// description is the only slot that stays visible, so it carries
// the assigned officer's name for GL Ethiopia.
description={
clearance.transitAssignee?.name
? `Transit assignee: ${clearance.transitAssignee.name}`
: "Ask GL Djibouti to name the officer handling this shipment"
}
icon={
clearance.transitAssignee?.name ? (
<CheckCircle2 size={14} />

View File

@@ -234,7 +234,7 @@ const RuleEngineCardGrid = ({
{col.header}:
</Text>
<div style={{ textAlign: "right", flex: 1 }}>
{formatCell(displayValue, col.format)}
{formatCell(displayValue, col.format, record)}
</div>
</Group>
);

View File

@@ -127,6 +127,8 @@ const buildInitialValues = (
} else {
values[field.name] = raw;
}
} else if (field.defaultValue !== undefined) {
values[field.name] = field.defaultValue;
} else if (field.type === "boolean") {
values[field.name] = false;
} else if (field.type === "number") {

View File

@@ -17,7 +17,13 @@ const extractLabel = (value: unknown): string | null => {
);
};
export const formatCell = (value: unknown, format?: ColumnFormat): ReactNode => {
export const formatCell = (
value: unknown,
format?: ColumnFormat,
// The row the cell came from — currency amounts read their code off it so a
// last-mile rate priced in birr does not render as USD.
row?: Record<string, unknown>,
): ReactNode => {
if (value === null || value === undefined || value === "") {
return <Text size="sm" c="dimmed"></Text>;
}
@@ -109,9 +115,10 @@ export const formatCell = (value: unknown, format?: ColumnFormat): ReactNode =>
if (format === "currency") {
const num = Number(value);
const code = typeof row?.currency === "string" ? row.currency : "USD";
return (
<Text size="sm" fw={500}>
{Number.isNaN(num) ? String(value) : `USD ${num.toLocaleString()}`}
{Number.isNaN(num) ? String(value) : `${code} ${num.toLocaleString()}`}
</Text>
);
}

View File

@@ -30,6 +30,7 @@ interface WindowRow {
windowClosesAt: string | null;
docReviewEndsAt: string | null;
paymentPhaseEndsAt: string | null;
paymentDrainEndsAt?: string | null;
bookingWindowStatus: string;
bookingCycleNo: number;
departureDate: string;
@@ -55,6 +56,7 @@ function applyEvent<T extends WindowRow>(row: T, event: BookingWindowPhaseEvent)
windowClosesAt: event.windowClosesAt,
docReviewEndsAt: event.docReviewEndsAt,
paymentPhaseEndsAt: event.paymentPhaseEndsAt,
paymentDrainEndsAt: event.paymentDrainEndsAt,
departureDate: event.scheduledDepartureDate ?? row.departureDate,
};
}

View File

@@ -27,6 +27,10 @@ export const FREIGHT_PERMS = {
uploadClearanceOutput: "edr_freight_app:bookings:upload_clearance_output",
finalizeClearance: "edr_freight_app:bookings:finalize_clearance",
docReviewAlert: "edr_freight_app:bookings:doc_review_alert",
wagonCancellationView: "edr_freight_app:bookings:wagon_cancellation_view",
wagonCancellationVoid: "edr_freight_app:bookings:wagon_cancellation_void",
wagonCancellationRebook:
"edr_freight_app:bookings:wagon_cancellation_rebook",
},
contracts: {
view: "edr_freight_app:contracts:view",

View File

@@ -0,0 +1,420 @@
import {
Anchor,
Badge,
Box,
Button,
Card,
Group,
Modal,
Select,
Stack,
Text,
TextInput,
} from "@mantine/core";
import { DateInput } from "@mantine/dates";
import { useDebouncedValue } from "@mantine/hooks";
import { useMutation, useQuery } from "@tanstack/react-query";
import { Search, XCircle } from "lucide-react";
import { useMemo, useState } from "react";
import toast from "react-hot-toast";
import { Link } from "react-router-dom";
import { api } from "@/auth/http";
import { useAuth } from "@/auth/useAuth";
import { PageContainer, PageHeader } from "@/components/page";
import { toDayString } from "@/hooks/useListControls";
import { FREIGHT_PERMS, hasPermission } from "@/lib/permissions";
import {
DataTable,
DataTableFooter,
usePagination,
type ColumnDef,
} from "@edr/ui-common";
type WagonCancellationStatus =
| "FEE_PENDING"
| "CREDIT_AVAILABLE"
| "REBOOKED"
| "WITHDRAWN"
| "EXPIRED";
interface WagonCancellation {
id: string;
bookingId: string;
rebookedBookingId?: string | null;
wagonsCancelled: number;
weightTons: number;
creditAmount: number;
feeAmount: number;
feeCurrency: string;
feeInvoiceId?: string | null;
feePaidAt?: string | null;
status: WagonCancellationStatus;
reason?: string | null;
rebookedAt?: string | null;
createdAt: string;
booking?: { id: string; reference: string; company?: { name: string } };
rebookedBooking?: { id: string; reference: string };
feeInvoice?: { invoiceNumber: string; status: string };
}
interface WagonCancellationListResponse {
items: WagonCancellation[];
total: number;
}
const STATUS_CHIP: Record<
WagonCancellationStatus,
{ label: string; color: string }
> = {
FEE_PENDING: { label: "Fee pending", color: "yellow" },
CREDIT_AVAILABLE: { label: "Credit available", color: "edr-green" },
REBOOKED: { label: "Rebooked", color: "indigo" },
WITHDRAWN: { label: "Withdrawn", color: "gray" },
EXPIRED: { label: "Expired", color: "red" },
};
const STATUS_FILTER_OPTIONS = (
Object.keys(STATUS_CHIP) as WagonCancellationStatus[]
).map((s) => ({ value: s, label: STATUS_CHIP[s].label }));
function StatusChip({ status }: { status: WagonCancellationStatus }) {
const chip = STATUS_CHIP[status] ?? { label: status, color: "gray" };
return (
<Badge
color={chip.color}
variant="light"
size="sm"
radius="md"
tt="uppercase"
fw={600}
style={{ fontSize: "0.7rem", letterSpacing: "0.05em" }}
>
{chip.label}
</Badge>
);
}
function formatDate(iso: string | null | undefined): string {
if (!iso) return "—";
const d = new Date(iso);
return Number.isNaN(d.getTime())
? "—"
: d.toLocaleDateString(undefined, {
year: "numeric",
month: "short",
day: "numeric",
});
}
function formatAmount(amount: number, currency: string): string {
return `${currency} ${Number(amount).toLocaleString(undefined, {
minimumFractionDigits: 2,
})}`;
}
/**
* Staff view of partial wagon cancellations: every slice of capacity a
* customer gave back, its cancellation fee, and where the credit went
* (rebooked, still available, expired, or the request was voided).
*/
export default function WagonCancellationsPage() {
const { user } = useAuth();
const canVoid = hasPermission(
user,
FREIGHT_PERMS.bookings.wagonCancellationVoid,
);
const { pagination, setPagination } = usePagination({ pageSize: 10 });
const [status, setStatus] = useState<string | null>(null);
const [search, setSearch] = useState("");
const [debouncedSearch] = useDebouncedValue(search, 300);
const [from, setFrom] = useState<Date | null>(null);
const [to, setTo] = useState<Date | null>(null);
const [voiding, setVoiding] = useState<WagonCancellation | null>(null);
const resetPage = () =>
setPagination({ pageIndex: 0, pageSize: pagination.pageSize });
const filter = useMemo(
() => ({
page: pagination.pageIndex + 1,
pageSize: pagination.pageSize,
...(status ? { statuses: status } : {}),
...(debouncedSearch.trim() ? { search: debouncedSearch.trim() } : {}),
...(from ? { from: toDayString(from) } : {}),
...(to ? { to: toDayString(to) } : {}),
}),
[pagination.pageIndex, pagination.pageSize, status, debouncedSearch, from, to],
);
const { data, isLoading, isError, refetch } = useQuery({
queryKey: ["bookings", "wagon-cancellations", filter],
queryFn: async () => {
const res = await api.get<WagonCancellationListResponse>(
"/bookings/wagon-cancellations/history",
{ params: filter },
);
return res.data;
},
});
const rows = data?.items ?? [];
const total = data?.total ?? 0;
const pageCount = Math.max(1, Math.ceil(total / pagination.pageSize));
const withdraw = useMutation({
mutationFn: (id: string) =>
api.post(`/bookings/wagon-cancellations/${id}/withdraw`),
});
const columns: ColumnDef<WagonCancellation>[] = [
{
id: "requested",
header: () => <span>Requested</span>,
cell: ({ row }) => (
<Text size="xs" c="dimmed">
{formatDate(row.original.createdAt)}
</Text>
),
},
{
id: "booking",
header: () => <span>Booking</span>,
cell: ({ row }) => (
<Anchor
component={Link}
to={`/dashboard/booking-requests/${row.original.bookingId}`}
size="sm"
fw={600}
>
{row.original.booking?.reference ?? row.original.bookingId}
</Anchor>
),
},
{
id: "company",
header: () => <span>Company</span>,
cell: ({ row }) => (
<Text size="sm">{row.original.booking?.company?.name ?? "—"}</Text>
),
},
{
id: "wagons",
header: () => <span>Wagons</span>,
cell: ({ row }) => <Text size="sm">{row.original.wagonsCancelled}</Text>,
},
{
id: "fee",
header: () => <span>Fee</span>,
cell: ({ row }) => (
<Text size="sm" style={{ fontVariantNumeric: "tabular-nums" }}>
{formatAmount(row.original.feeAmount, row.original.feeCurrency)}
</Text>
),
},
{
id: "credit",
header: () => <span>Credit</span>,
cell: ({ row }) => (
<Text size="sm" style={{ fontVariantNumeric: "tabular-nums" }}>
{formatAmount(row.original.creditAmount, row.original.feeCurrency)}
</Text>
),
},
{
id: "status",
header: () => <span>Status</span>,
cell: ({ row }) => <StatusChip status={row.original.status} />,
},
{
id: "rebookedAs",
header: () => <span>Rebooked as</span>,
cell: ({ row }) => {
const r = row.original;
if (!r.rebookedBookingId) return <Text size="sm"></Text>;
return (
<Anchor
component={Link}
to={`/dashboard/booking-requests/${r.rebookedBookingId}`}
size="sm"
>
{r.rebookedBooking?.reference ?? r.rebookedBookingId}
</Anchor>
);
},
},
{
id: "actions",
header: () => <span />,
cell: ({ row }) => {
const r = row.original;
if (r.status !== "FEE_PENDING" || !canVoid) return null;
return (
<Group justify="flex-end" wrap="nowrap">
<Button
size="xs"
radius="md"
variant="subtle"
color="red"
onClick={() => setVoiding(r)}
>
Void
</Button>
</Group>
);
},
},
];
return (
<PageContainer>
<Stack gap="lg">
<PageHeader
title="Wagon cancellations"
subtitle="Partial wagon cancellations — fees charged, credits held, and where each credit was rebooked"
breadcrumbs={[
{ label: "Bookings", href: "/dashboard/booking-requests" },
{ label: "Wagon cancellations" },
]}
/>
<Card withBorder radius="md" p="md">
<Stack gap="md">
<Group gap="sm" wrap="wrap">
<TextInput
placeholder="Search booking ref or company…"
leftSection={<Search size={15} />}
value={search}
onChange={(e) => {
setSearch(e.currentTarget.value);
resetPage();
}}
w={260}
radius="md"
/>
<Select
placeholder="Status"
data={STATUS_FILTER_OPTIONS}
value={status}
onChange={(v) => {
setStatus(v);
resetPage();
}}
clearable
w={190}
radius="md"
/>
<DateInput
placeholder="From"
value={from}
onChange={(v) => {
setFrom(v ? new Date(v) : null);
resetPage();
}}
maxDate={to ?? undefined}
clearable
radius="md"
style={{ minWidth: 140 }}
/>
<DateInput
placeholder="To"
value={to}
onChange={(v) => {
setTo(v ? new Date(v) : null);
resetPage();
}}
minDate={from ?? undefined}
clearable
radius="md"
style={{ minWidth: 140 }}
/>
<Button
variant="subtle"
radius="md"
onClick={() => {
setStatus(null);
setSearch("");
setFrom(null);
setTo(null);
resetPage();
}}
>
Clear
</Button>
</Group>
<Box style={{ overflowX: "auto" }} w="100%">
<DataTable
columns={columns}
data={rows}
status={isLoading ? "loading" : isError ? "error" : "success"}
pagination={{
pageIndex: pagination.pageIndex,
pageSize: pagination.pageSize,
pageCount,
totalCount: total,
}}
tableOptions={{
state: { pagination },
onPaginationChange: setPagination,
manualPagination: true,
pageCount,
}}
containerClassName="border-0 shadow-none bg-transparent"
footer={DataTableFooter}
/>
</Box>
</Stack>
</Card>
</Stack>
<Modal
opened={Boolean(voiding)}
onClose={() => setVoiding(null)}
radius="md"
title="Void this cancellation?"
>
{!voiding ? null : (
<Stack gap="sm">
<Text size="sm">
{voiding.booking?.reference ?? voiding.bookingId} ·{" "}
{voiding.wagonsCancelled} wagon(s) · fee{" "}
{formatAmount(voiding.feeAmount, voiding.feeCurrency)}
</Text>
<Text size="sm" c="dimmed">
The pending fee is dropped and the wagons stay on the booking.
Voiding can't be undone.
</Text>
<Group justify="flex-end" gap="sm">
<Button
variant="default"
radius="md"
onClick={() => setVoiding(null)}
>
Keep it
</Button>
<Button
color="red"
radius="md"
leftSection={<XCircle size={15} />}
loading={withdraw.isPending}
onClick={async () => {
try {
await withdraw.mutateAsync(voiding.id);
toast.success("Cancellation voided");
setVoiding(null);
void refetch();
} catch {
// interceptor surfaces the reason
}
}}
>
Void
</Button>
</Group>
</Stack>
)}
</Modal>
</PageContainer>
);
}

View File

@@ -161,10 +161,10 @@ export default function ClearanceDocumentsPage() {
<User className="size-4" strokeWidth={1.75} />
</div>
<div className="min-w-0">
<p className="truncate font-medium text-foreground">
<p className="font-medium text-foreground">
{customer}
</p>
<p className="mt-0.5 flex items-center gap-1 truncate text-xs text-muted-foreground">
<p className="mt-0.5 flex items-center gap-1 text-xs text-muted-foreground">
<FileText className="size-3 shrink-0 opacity-70" />
{b.reference}
</p>
@@ -182,7 +182,7 @@ export default function ClearanceDocumentsPage() {
<ContractReferenceLink
contractId={b.contractId}
contractReference={b.contractReference}
className="block truncate text-sm text-foreground underline underline-offset-2 hover:text-muted-foreground"
className="block text-sm text-foreground underline underline-offset-2 hover:text-muted-foreground"
/>
) : (
<Text size="sm"></Text>
@@ -409,7 +409,7 @@ export default function ClearanceDocumentsPage() {
manualPagination: true,
pageCount,
}}
containerClassName="border-0 shadow-none bg-transparent"
containerClassName="border-0 shadow-none bg-transparent [&_th]:max-w-[100px] [&_td]:max-w-[100px] [&_td]:break-words"
footer={DataTableFooter}
/>
</Box>

View File

@@ -393,10 +393,10 @@ function ShipmentBookingsTable({
<PackageCheck className="size-4" strokeWidth={1.75} />
</div>
<div className="min-w-0">
<p className="truncate font-medium text-foreground">
<p className="font-medium text-foreground">
{row.original.reference}
</p>
<p className="mt-0.5 flex items-center gap-1 truncate text-xs text-muted-foreground">
<p className="mt-0.5 flex items-center gap-1 text-xs text-muted-foreground">
<User className="size-3 shrink-0 opacity-70" />
{row.original.customerLabel}
</p>
@@ -413,7 +413,7 @@ function ShipmentBookingsTable({
<Stack gap={4} py={2}>
<Group gap={6} wrap="nowrap">
<FileText size={13} className="shrink-0 text-muted-foreground" />
<Text size="sm" fw={500} truncate maw={150}>
<Text size="sm" fw={500}>
{r.contractReference ?? "—"}
</Text>
</Group>
@@ -431,13 +431,9 @@ function ShipmentBookingsTable({
header: () => <span className={bookingTable.headerCell}>Route</span>,
cell: ({ row }) => (
<Group gap={6} wrap="nowrap">
<Text size="sm" className="truncate">
{row.original.originLabel}
</Text>
<Text size="sm">{row.original.originLabel}</Text>
<ArrowRight size={13} className="shrink-0 text-muted-foreground" />
<Text size="sm" className="truncate">
{row.original.destinationLabel}
</Text>
<Text size="sm">{row.original.destinationLabel}</Text>
</Group>
),
},
@@ -610,7 +606,7 @@ function ShipmentBookingsTable({
data={rows}
status={loading ? "loading" : error ? "error" : "success"}
onRowClick={(row) => onOpen(row.id)}
containerClassName="border-0 shadow-none bg-transparent"
containerClassName="border-0 shadow-none bg-transparent [&_th]:max-w-[100px] [&_td]:max-w-[100px] [&_td]:break-words"
/>
</Box>
);

View File

@@ -450,6 +450,35 @@ export default function ContractRequestDetailPage() {
description={statusMeta.description}
/>
{/* A contract resting in APPROVED means the automatic PDF generation on
final approval failed — on success it moves straight to
CONTRACT_READY. Offer the manual retry. */}
{contract.status === "APPROVED" ? (
<Alert
color="orange"
radius="md"
icon={<AlertTriangle size={18} />}
title="Contract document was not generated"
>
<Stack gap="sm" align="flex-start">
<Text size="sm">
All approvals are complete, but generating the contract PDF
failed. Retry the generation below.
</Text>
<Button
color="edr-green"
size="compact-sm"
radius="lg"
leftSection={<RefreshCw size={15} />}
loading={mutations.generateContract.isPending}
onClick={() => mutations.generateContract.mutate()}
>
Regenerate contract
</Button>
</Stack>
</Alert>
) : null}
{contract.status === "REJECTED" && contract.latestRejectionNote ? (
<Alert
color="red"

View File

@@ -226,11 +226,11 @@ function RouteCell({
return (
<Stack gap={4} py={2}>
<Group gap={6} wrap="nowrap">
<Text size="sm" fw={500} truncate maw={120}>
<Text size="sm" fw={500}>
{origin}
</Text>
<ArrowRight size={14} className="shrink-0 text-muted-foreground" />
<Text size="sm" fw={500} truncate maw={120}>
<Text size="sm" fw={500}>
{destination}
</Text>
</Group>
@@ -385,10 +385,10 @@ export default function GlDjiboutiClearanceListPage() {
<PackageCheck className="size-4" strokeWidth={1.75} />
</div>
<div className="min-w-0">
<p className="truncate font-medium text-foreground">
<p className="font-medium text-foreground">
{r.reference}
</p>
<p className="mt-0.5 flex items-center gap-1 truncate text-xs text-muted-foreground">
<p className="mt-0.5 flex items-center gap-1 text-xs text-muted-foreground">
<User className="size-3 shrink-0 opacity-70" />
{r.customerLabel}
</p>
@@ -403,9 +403,7 @@ export default function GlDjiboutiClearanceListPage() {
cell: ({ row }) => (
<Group gap={6} wrap="nowrap">
<FileText size={13} className="shrink-0 text-muted-foreground" />
<Text size="sm" truncate maw={140}>
{row.original.contractReference}
</Text>
<Text size="sm">{row.original.contractReference}</Text>
</Group>
),
},
@@ -710,7 +708,7 @@ export default function GlDjiboutiClearanceListPage() {
manualPagination: true,
pageCount,
}}
containerClassName="border-0 shadow-none bg-transparent"
containerClassName="border-0 shadow-none bg-transparent [&_th]:max-w-[100px] [&_td]:max-w-[100px] [&_td]:break-words"
footer={DataTableFooter}
/>
</Box>

View File

@@ -306,34 +306,27 @@ const RuleEngineResourcePage = () => {
const formFields = useMemo(() => {
if (!config) return [];
// Last-mile container bands: creating uses the multi-row tier list (one
// rate per tier); editing an existing band row keeps the single
// From/To/value fields (a rate row IS one band).
// Last-mile bands (both modes): creating uses the multi-row tier list (one
// rate per tier, each tier carrying its own rate value); editing an
// existing band row keeps the single From/To/value fields (a rate row IS
// one band).
const bandFields = config.formFields.filter((field) => {
if (config.slug !== "rates") return true;
if (field.type === "tierList") return !editing;
if (editing) return true;
return field.name !== "minKm" && field.name !== "maxKm";
});
return bandFields.map((field) => {
// On create, the tier rows carry the per-band rate values — the single
// last-mile "Rate value" field then only applies to bulk mode.
// On create the tier rows carry From/To/value — drop the single fields,
// including the last-mile "Rate value" (the non-last-mile one keeps its
// own showIf).
if (
config.slug === "rates" &&
!editing &&
field.name === "rateValue" &&
field.showWhen?.field === "appliesTo" &&
field.showWhen.equals.includes("LAST_MILE")
) {
return {
...field,
showWhen: undefined,
showIf: (values: Record<string, unknown>) =>
values.appliesTo === "LAST_MILE" && values.lastMileMode === "BULK",
};
return false;
}
return field;
}).map((field) => {
return field.name !== "minKm" && field.name !== "maxKm";
});
return bandFields.map((field) => {
if (isPriorityRules && field.name === "minWagonCount") {
return {
...field,
@@ -501,7 +494,7 @@ const RuleEngineResourcePage = () => {
header: col.header,
meta: { headerClassName, cellClassName },
cell: ({ row }) => {
const cell = formatCell(row.original[col.accessorKey], col.format);
const cell = formatCell(row.original[col.accessorKey], col.format, row.original);
// On the rate column, show the proposed value under the live one — the
// live value stays the headline because it is what still gets charged.
if (!isRates || col.accessorKey !== "rateValue") return cell;
@@ -621,19 +614,15 @@ const RuleEngineResourcePage = () => {
currency: isLastMile ? (values.currency ?? "ETB") : "USD",
trigger: isSurcharge ? values.trigger : "ALWAYS",
...(isLastMile
? lastMileMode === "BULK"
? {
rateUnit: "PER_TON_KM",
containerTypeId: undefined,
minKm: undefined,
maxKm: undefined,
}
: {
rateUnit: "PER_KM",
// Empty "To km" means an open-ended band — send null so an
// edit can clear a previously-set ceiling.
maxKm: values.maxKm ?? null,
}
? {
// Empty "To km" means an open-ended band — send null so an
// edit can clear a previously-set ceiling. On create the tier
// spread below overrides the band fields per tier.
maxKm: values.maxKm ?? null,
...(lastMileMode === "BULK"
? { rateUnit: "PER_TON_KM", containerTypeId: undefined }
: { rateUnit: "PER_KM" }),
}
: {}),
};
// Editing a LIVE rate files a change request — the rate keeps charging

View File

@@ -70,6 +70,8 @@ export interface FormFieldDef {
* relation list (`wagonTypeIds` read from `record.wagonTypes`).
*/
getInitialValue?: (record: Record<string, unknown>) => unknown;
/** Pre-selected value on create (no record yet) — e.g. last-mile currency = ETB. */
defaultValue?: string;
/**
* Fully derived field: its value is computed from the live form values on
* every render and the input is locked. Used for the priority-rule min
@@ -297,8 +299,8 @@ export const rateUnitOptions = (
};
const CURRENCIES = [
{ label: "ETB (Birr)", value: "ETB" },
{ label: "USD", value: "USD" },
{ label: "ETB", value: "ETB" },
];
const PRIORITY_CONFIG_TYPES = [
@@ -1001,7 +1003,8 @@ export const RULE_ENGINE_RESOURCES: RuleEngineResourceConfig[] = [
placeholder: "0",
description: "Band start (inclusive). Use 0 for the first band.",
showIf: (v) =>
v.appliesTo === "LAST_MILE" && v.lastMileMode === "CONTAINER",
v.appliesTo === "LAST_MILE" &&
(v.lastMileMode === "CONTAINER" || v.lastMileMode === "BULK"),
},
{
name: "maxKm",
@@ -1011,7 +1014,8 @@ export const RULE_ENGINE_RESOURCES: RuleEngineResourceConfig[] = [
placeholder: "Leave empty for no upper limit",
description: "Band end (exclusive) — a 030 band covers up to but not including 30 km.",
showIf: (v) =>
v.appliesTo === "LAST_MILE" && v.lastMileMode === "CONTAINER",
v.appliesTo === "LAST_MILE" &&
(v.lastMileMode === "CONTAINER" || v.lastMileMode === "BULK"),
},
{
name: "currency",
@@ -1020,6 +1024,8 @@ export const RULE_ENGINE_RESOURCES: RuleEngineResourceConfig[] = [
required: true,
options: CURRENCIES,
showWhen: { field: "appliesTo", equals: ["LAST_MILE"] },
// Birr is the norm for domestic trucking; USD stays selectable.
defaultValue: "ETB",
getInitialValue: (record) => String(record.currency ?? "ETB"),
},
// ── Distance tiers (create only — the page swaps this for the single
@@ -1031,9 +1037,10 @@ export const RULE_ENGINE_RESOURCES: RuleEngineResourceConfig[] = [
type: "tierList",
required: true,
description:
"One rate per distance range. To km is exclusive (030 then 30+); leave the last tier's To km empty for no upper limit.",
"One rate per distance range — the rate value is per km (container mode) or per ton per km (bulk mode). To km is exclusive (030 then 30+); leave the last tier's To km empty for no upper limit.",
showIf: (v) =>
v.appliesTo === "LAST_MILE" && v.lastMileMode === "CONTAINER",
v.appliesTo === "LAST_MILE" &&
(v.lastMileMode === "CONTAINER" || v.lastMileMode === "BULK"),
},
// ── Container type — Container freight, container-kind intercity, and
// the empty-container return surcharge (20ft vs 40ft price differently) ─

View File

@@ -916,6 +916,11 @@ export default function TrainScheduleV2DetailPage() {
<Title order={2} fw={700} style={{ color: "#0f172a" }}>
{schedule.route?.name ?? "Train schedule"}
</Title>
{schedule.train?.trainName ? (
<Text fw={700} style={{ color: "#0f172a" }}>
{schedule.train.trainName}
</Text>
) : null}
{schedule.train ? (
<Text size="xs" c="dimmed" ff="monospace">
Train {schedule.train.code}

View File

@@ -673,8 +673,16 @@ export const contractsService = {
validateShipment: (
id: string,
payload: Freight.CreateBookingUnderContractDto,
// Completion/resubmit preview: exclude this booking's own containers from
// the same-train clash check.
excludeBookingId?: string,
) =>
postContract<ShipmentValidation>(C.VALIDATE_SHIPMENT(id), payload),
postContract<ShipmentValidation>(
excludeBookingId
? `${C.VALIDATE_SHIPMENT(id)}?bookingId=${excludeBookingId}`
: C.VALIDATE_SHIPMENT(id),
payload,
),
/** Remaining bookable quantity per cargo line (GENERAL draw-down cap). */
getCapacity: async (id: string): Promise<Freight.ContractCapacityLine[]> => {

View File

@@ -3,6 +3,7 @@ import { useDisclosure } from "@mantine/hooks";
import {
Home,
Layers,
LifeBuoy,
Loader2,
// MapPin,
Package,
@@ -58,6 +59,10 @@ import CheckPaymentPage from "./pages/payments/CheckPaymentPage";
import PaymentFailurePage from "./pages/payments/PaymentFailurePage";
import FaydaCallbackPage from "./pages/FaydaCallbackPage";
import PaymentSuccessPage from "./pages/payments/PaymentSuccessPage";
import FaqPage from "./pages/support/FaqPage";
import HelpPage from "./pages/support/HelpPage";
import PrivacyPolicyPage from "./pages/support/PrivacyPolicyPage";
import TermsPage from "./pages/support/TermsPage";
import TrackingPage from "./pages/tracking/TrackingPage";
function FullScreenSpinner() {
@@ -217,6 +222,12 @@ const sidebarItems: SidebarItem[] = [
href: "/settings",
icon: <Settings size={18} />,
},
{
section: "Account",
label: "Help & Support",
href: "/help",
icon: <LifeBuoy size={18} />,
},
];
const App = () => {
@@ -273,6 +284,14 @@ const App = () => {
<Route path="/payment/success" element={<PaymentSuccessPage />} />
<Route path="/payment/failure" element={<PaymentFailurePage />} />
{/* Help and legal pages. Public on purpose: the auth screens link to
them before a session exists, so they carry their own chrome rather
than sitting inside the authenticated app layout. */}
<Route path="/help" element={<HelpPage />} />
<Route path="/faq" element={<FaqPage />} />
<Route path="/privacy" element={<PrivacyPolicyPage />} />
<Route path="/terms" element={<TermsPage />} />
{/* Auth pages — inaccessible once logged in */}
<Route element={<RedirectIfAuthed />}>
<Route path="/login" element={<LoginPage />} />

View File

@@ -129,19 +129,19 @@ const FormFooter = () => (
<span className="shrink-0">© 2026 EDR Freight</span>
<div className="flex flex-wrap items-center justify-center gap-3 sm:justify-end sm:gap-6">
<Link
to="#"
to="/terms"
className="font-semibold text-gray-700 transition-colors hover:text-primary"
>
Terms &amp; Conditions
</Link>
<Link
to="#"
to="/privacy"
className="font-semibold text-gray-700 transition-colors hover:text-primary"
>
Privacy Policy
</Link>
<Link
to="#"
to="/help"
className="font-semibold text-gray-700 transition-colors hover:text-primary"
>
Help &amp; Support

View File

@@ -26,9 +26,22 @@ interface ETradeInfoProps {
onStatusChange?: (status: ETradeStatus) => void;
/** Called when the TIN changes away from the last fetched value — clear whatever it filled in. */
onReset?: () => void;
/**
* This TIN already passed eTrade in an earlier session (the saved profile
* carries its registration details), so adopt it on arrival instead of
* re-querying. Rehydration lands the TIN after the first render, which used
* to look exactly like the customer typing a new one: every reopen fired a
* live lookup that could fail on an outage, and re-marked eTrade's fields as
* freshly verified so they were resubmitted on the next save. "Get Data"
* stays available for a deliberate re-verify.
*/
alreadyVerified?: boolean;
}
const isValidTin = (tin: string) => tin.length === 10;
// Digits, not just length: a 10-character non-numeric TIN used to fire a lookup
// that could only fail, and the failure was then reported as "this TIN isn't
// registered with eTrade" instead of "that isn't a TIN".
const isValidTin = (tin: string) => /^\d{10}$/.test(tin);
export default function ETradeInfo({
tin,
@@ -37,6 +50,7 @@ export default function ETradeInfo({
onDataLoaded,
onStatusChange,
onReset,
alreadyVerified,
}: ETradeInfoProps) {
const mutation = useETradeData();
const isLoading = mutation.isPending;
@@ -63,6 +77,13 @@ export default function ETradeInfo({
// doesn't refire the lookup the moment this mounts.
const lastFetchedTin = useRef<string | null>(tin || null);
useEffect(() => {
// A rehydrated TIN that eTrade already accepted: adopt it silently. Doing
// this before the change-detection below also keeps `onReset` from firing,
// which would wipe the very registration details that prove it passed.
if (alreadyVerified && lastFetchedTin.current === null && isValidTin(tin)) {
lastFetchedTin.current = tin;
return;
}
if (tin !== lastFetchedTin.current) {
// TIN moved away from whatever we last fetched — that result (verified
// data, "taken", or an error) no longer describes this TIN. Drop it so
@@ -82,12 +103,17 @@ export default function ETradeInfo({
const apiError =
mutation.isError && mutation.error ? extractApiError(mutation.error) : null;
// A 400 here means eTrade simply has no record for this TIN.
const notFound = apiError?.statusCode === 400;
// A 400 here usually means eTrade has no record for this TIN — but the API
// also wraps its own transport failures as a 400 ("Failed to fetch company
// info from eTrade: …"), and reporting an outage as "this TIN isn't
// registered" sends the customer off to re-check a number that was fine.
const unreachable = /failed to fetch/i.test(apiError?.message ?? "");
const notFound = apiError?.statusCode === 400 && !unreachable;
const errorMessage =
apiError && !notFound
? apiError.message ||
"We couldn't reach eTrade to fetch your company information. Please try again."
? unreachable || !apiError.message
? "We couldn't reach eTrade to fetch your company information. Please try again in a moment."
: apiError.message
: null;
const status: ETradeStatus = isLoading

View File

@@ -47,6 +47,7 @@ function applyEvent(
windowClosesAt: event.windowClosesAt,
docReviewEndsAt: event.docReviewEndsAt,
paymentPhaseEndsAt: event.paymentPhaseEndsAt,
paymentDrainEndsAt: event.paymentDrainEndsAt,
departureDate: event.scheduledDepartureDate ?? row.departureDate,
};
}

View File

@@ -584,7 +584,35 @@ export default function EDRFreightLandingPage() {
</div>
</div>
<div>© 2026 EDR Freight. All rights reserved.</div>
<div className="flex flex-col items-center gap-4 md:items-end">
<nav className="flex flex-wrap items-center justify-center gap-x-6 gap-y-2">
<Link
to="/help"
className="font-semibold text-foreground transition-colors hover:text-primary"
>
Help &amp; Support
</Link>
<Link
to="/faq"
className="font-semibold text-foreground transition-colors hover:text-primary"
>
FAQ
</Link>
<Link
to="/privacy"
className="font-semibold text-foreground transition-colors hover:text-primary"
>
Privacy Policy
</Link>
<Link
to="/terms"
className="font-semibold text-foreground transition-colors hover:text-primary"
>
Terms of Service
</Link>
</nav>
<div>© 2026 EDR Freight. All rights reserved.</div>
</div>
</div>
</footer>
</div>

View File

@@ -68,16 +68,29 @@ const COUNTDOWN_TEXT: Partial<
PRE_WINDOW: { label: "Booking opens in", expiredText: "Booking opening now…" },
OPEN: { label: "Window closes in", expiredText: "Document review starting…" },
DOC_REVIEW: { label: "Document review ends in", expiredText: "Payment starting…" },
PAYMENT: { label: "Payment due in", expiredText: "Payment window closing…" },
PAYMENT: { label: "Payment due in", expiredText: "Finalizing payments…" },
};
function phaseCountdown(
w: MyBookingWindow,
): { label: string; deadline: string; expiredText: string } | null {
function phaseCountdown(w: MyBookingWindow): {
label: string;
deadline: string;
expiredText: string;
graceDeadline?: string | null;
graceLabel?: string;
} | null {
const state = bookingWindowUiState(w);
const text = COUNTDOWN_TEXT[state.kind];
if (!state.countdownTo || !text) return null;
return { ...text, deadline: state.countdownTo };
// Once the pay deadline lapses, pending payments still settle during the
// drain tail — count it down as "processing" instead of a stale "closing".
const grace =
state.kind === "PAYMENT" && w.paymentDrainEndsAt
? {
graceDeadline: w.paymentDrainEndsAt,
graceLabel: "Payment processing — closes in",
}
: undefined;
return { ...text, deadline: state.countdownTo, ...grace };
}
function Pill({
@@ -336,6 +349,8 @@ export const UpcomingWindowsSection = memo(function UpcomingWindowsSection({
deadline={cd.deadline}
label={cd.label}
expiredText={cd.expiredText}
graceDeadline={cd.graceDeadline}
graceLabel={cd.graceLabel}
size="xs"
/>
</Box>

View File

@@ -38,6 +38,10 @@ import {
} from "./companyProfileForm/schema";
import {
buildPayload,
firstPresent,
firstValidEmail,
firstValidPhone,
normalizeIdentityPhones,
stepPayload,
toFormValues,
} from "./companyProfileForm/helpers";
@@ -45,6 +49,7 @@ import FaydaVerifyPanel from "@/components/FaydaVerifyPanel";
import { verifaydaService } from "@/services/verifayda.service";
import type { CompanyIdentityState } from "@/services/verifayda.service";
import { LinkCheckboxCard } from "./companyProfileForm/LinkCheckboxCard";
import { ReadOnlyField } from "./companyProfileForm/ReadOnlyField";
import ETradeCompanyCard from "./companyProfileForm/ETradeCompanyCard";
import StepSection from "./companyProfileForm/StepSection";
@@ -67,7 +72,7 @@ export default function CompanyProfileForm({
submitError,
uploadedDocumentKeys,
onUploadDocuments,
identity,
identity: rawIdentity,
onIdentityChange,
}: {
documentSettingCode: string;
@@ -115,6 +120,15 @@ export default function CompanyProfileForm({
*/
onIdentityChange?: () => void;
}) {
// A Fayda claim carries the phone as the national registry holds it, which is
// often a local number the form's E.164 validation (and the API's
// `@IsValidPhone()`) would reject — for a value the customer never typed and
// has no field to correct. Normalize once, here, so every read below is safe.
const identity = useMemo(
() => normalizeIdentityPhones(rawIdentity),
[rawIdentity],
);
const [step, setStep] = useState<CompanyStep>(initialStep ?? "company");
const [saving, setSaving] = useState(false);
const [saveError, setSaveError] = useState<string | null>(null);
@@ -188,15 +202,20 @@ export default function CompanyProfileForm({
const {
register,
control,
handleSubmit,
trigger,
watch,
setValue,
formState: { errors },
getValues,
formState: { errors, dirtyFields },
} = useForm<FormData>({
resolver: zodResolver(
buildOnboardingSchema(identity?.passportRequired === true),
),
// `values` below re-seeds the form whenever the profile is refetched — and
// an in-page identity action (ticking "same as owner") refetches it. Without
// this, that reset silently throws away whatever the customer was part-way
// through typing on the current step.
resetOptions: { keepDirtyValues: true, keepErrors: true },
defaultValues: {
companyName: "",
companyEmail: "",
@@ -266,21 +285,28 @@ export default function CompanyProfileForm({
phone: string;
} | null>(null);
// `shouldDirty` is what marks the eTrade bundle as "re-verified this session";
// `stepPayload` sends those keys only when dirty, so an unchanged record is
// never echoed back to the API (which would make it re-query eTrade).
const handleETradeDataLoaded = (data: CompanyRegistrationData) => {
const dirty = { shouldDirty: true } as const;
if (data.companyName) {
setValue("companyName", data.companyName, { shouldValidate: true });
setValue("companyName", data.companyName, {
shouldValidate: true,
...dirty,
});
}
setValue("licenceNumber", data.licenceNumber);
setValue("statusDescription", data.statusDescription);
setValue("dateRegistered", data.dateRegistered);
setValue("renewedFrom", data.renewedFrom);
setValue("renewalDate", data.renewalDate);
setValue("renewedTo", data.renewedTo);
setValue("region", data.region);
setValue("zone", data.zone);
setValue("woreda", data.woreda);
setValue("kebele", data.kebele);
setValue("houseNo", data.houseNo);
setValue("licenceNumber", data.licenceNumber, dirty);
setValue("statusDescription", data.statusDescription, dirty);
setValue("dateRegistered", data.dateRegistered, dirty);
setValue("renewedFrom", data.renewedFrom, dirty);
setValue("renewalDate", data.renewalDate, dirty);
setValue("renewedTo", data.renewedTo, dirty);
setValue("region", data.region, dirty);
setValue("zone", data.zone, dirty);
setValue("woreda", data.woreda, dirty);
setValue("kebele", data.kebele, dirty);
setValue("houseNo", data.houseNo, dirty);
// companyAddress is composed reactively from the address fields below, so
// setting region/zone/woreda/kebele/houseNo above is enough — no need to
// compose it here. companyPhone is derived below (identity → eTrade →
@@ -292,6 +318,7 @@ export default function CompanyProfileForm({
setValue(
"etradePhone",
data.managerPhone || data.regularPhone || data.mobilePhone,
dirty,
);
setEtradeOwner({
@@ -321,28 +348,37 @@ export default function CompanyProfileForm({
setEtradeOwner(null);
};
// companyEmail/companyPhone are no longer typed — the Fayda-verified owner
// companyEmail/companyPhone are derived, not typed — the Fayda-verified owner
// is the highest-trust source (that's the whole point of verifying), eTrade's
// registered number and the account email/phone are the fallbacks used
// before verification happens.
//
// `firstValid*`, not `??`: these sources are optional AND unreliable. Fayda's
// email/phone claims can come back empty, and eTrade's registered phone is
// free text that arrives as things like "09 " (→ "+2519"). `??` stops
// at the first non-null, so a junk value became a field with no input and a
// 400 from the API on a value the customer never typed. Skip anything that
// isn't usable and fall through.
//
// When every source really is unusable the fields become editable below
// rather than blocking — the API requires a company email and phone at
// submit (REQUIRED_COMPANY_INFO), so leaving no way to supply them is a dead
// end.
const derivedEmail = firstValidEmail(identity?.owner.email, user.email);
const derivedPhone = firstValidPhone(
identity?.owner.phone,
etradeOwner?.phone,
user.phoneNumber,
);
useEffect(() => {
setValue("companyEmail", identity?.owner.email ?? user.email ?? "", {
shouldValidate: true,
});
if (derivedEmail) setValue("companyEmail", derivedEmail);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [identity?.owner.email, user.email, rehydrate]);
}, [derivedEmail, rehydrate]);
useEffect(() => {
setValue(
"companyPhone",
identity?.owner.phone ??
etradeOwner?.phone ??
toEthiopianE164(user.phoneNumber) ??
"",
{ shouldValidate: true },
);
if (derivedPhone) setValue("companyPhone", derivedPhone);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [identity?.owner.phone, etradeOwner?.phone, user.phoneNumber, rehydrate]);
}, [derivedPhone, rehydrate]);
// "Same as …" links. A checked card prefills the target step's fields from the
// source step and disables them (kept mirrored while linked); unchecking clears
@@ -352,6 +388,16 @@ export default function CompanyProfileForm({
const [gmSameAsOwner, setGmSameAsOwner] = useState(
identity?.gmSameAsOwner ?? false,
);
// `identity` is undefined on the first render (the requirements query is still
// in flight), so the initial state above freezes at `false` — adopt the
// server's declaration the moment it lands, or a resumed draft shows an
// unticked box over a GM that is linked server-side.
const identityLoaded = useRef(false);
useEffect(() => {
if (!identity || identityLoaded.current) return;
identityLoaded.current = true;
setGmSameAsOwner(identity.gmSameAsOwner);
}, [identity]);
const [contactSameAsGm, setContactSameAsGm] = useState(false);
// General Manager source. The company step's email/phone are seeded from
@@ -365,16 +411,26 @@ export default function CompanyProfileForm({
// A Fayda-verified owner outranks eTrade's registered owner — it's the
// higher-trust source, and the whole point of proving identity is to stop
// trusting typed/looked-up data for this.
const gmSourceName =
identity?.owner.name ?? etradeOwner?.name ?? user.name?.en ?? "";
const gmSourceEmail =
identity?.owner.email ?? (companyEmail || user.email || "");
const gmSourcePhone =
identity?.owner.phone ??
companyPhone ??
etradeOwner?.phone ??
toEthiopianE164(user.phoneNumber) ??
"";
const gmSourceName = firstPresent(
identity?.owner.name,
etradeOwner?.name,
user.name?.en,
);
const gmSourceEmail = firstValidEmail(
identity?.owner.email,
companyEmail,
user.email,
);
// Same reason as `derivedPhone`: this value is written into
// `generalManagerPhone`, which the API validates with `@IsValidPhone()`, so an
// unusable eTrade number here 400s the personnel step instead.
const gmSourcePhone = firstValidPhone(
identity?.owner.phone,
companyPhone,
etradeOwner?.phone,
user.phoneNumber,
);
useEffect(() => {
if (!gmSameAsOwner) return;
@@ -458,10 +514,24 @@ export default function CompanyProfileForm({
const gmEstablished =
gmVerified || (identity ? !identity.faydaRequired && gmTyped : gmTyped);
/** Same rule for the representative: verified, or typed where Fayda is optional. */
/**
* Same rule for the representative: verified, or entered where Fayda is
* optional.
*
* Matches the API's own rule (`REQUIRED_POA_FIELDS`): a typed representative
* counts once they have a name, an email and a phone. The step now renders
* inputs for all three, so this is something the customer can actually
* satisfy — previously it gated on `poaName`, for which no input existed
* anywhere, leaving a foreign freight forwarder permanently stuck.
*/
const poaTyped = Boolean(
watch("poaName")?.trim() &&
watch("poaEmail")?.trim() &&
watch("poaPhone")?.trim(),
);
const poaEstablished =
(identity?.poa.verified ?? false) ||
(identity ? !identity.faydaRequired && Boolean(watch("poaName")?.trim()) : false);
(identity ? !identity.faydaRequired && poaTyped : false);
// While linked, mirror the source values into the (disabled) target fields so
// the copy stays current even if the user goes back and edits the source.
@@ -616,8 +686,12 @@ export default function CompanyProfileForm({
// Until then the upload is hidden: there is no representative for the paper
// to authorise, and a freight forwarder is held on the verification gate
// below rather than on a file field it cannot yet fill.
const poaProvided = identity?.poa.verified ?? false;
const delegationRequired = poaProvided;
const poaProvided = (identity?.poa.verified ?? false) || poaTyped;
// A freight forwarder owes the paper whether or not its representative could
// verify with Fayda — the API demands it at completion either way. Keying
// this on the verification alone hid the upload from a foreign forwarder and
// then failed them on submit for a file they were never shown.
const delegationRequired = poaProvided || requirePoa;
const delegationPresent =
(uploadedDocumentKeys ?? []).includes(POA_DELEGATION_FILE_KEY) ||
(() => {
@@ -625,15 +699,63 @@ export default function CompanyProfileForm({
return Array.isArray(v) ? v.length > 0 : v != null;
})();
/**
* Collect the messages for a set of fields into one sentence.
*
* A failed `trigger()` used to return silently, so Continue simply did
* nothing — and every field whose input is conditionally rendered (or derived
* and never rendered at all) turned into an invisible dead end. Naming the
* failures is the whole point: the ones worth reporting are exactly the ones
* with no error text on screen to read.
*/
const describeErrors = (fields: (keyof FormData)[]): string => {
// Re-parse rather than read `errors`: that's the render-time snapshot, and
// this runs immediately after an `await trigger()` that has not re-rendered
// yet, so the closure would still be holding the previous attempt's state.
const parsed = buildOnboardingSchema(
identity?.passportRequired === true,
).safeParse(getValues());
const wanted = new Set<string>(fields as string[]);
const messages = parsed.success
? []
: parsed.error.issues
.filter((i) => wanted.has(String(i.path[0])))
.map((i) => i.message);
return messages.length > 0
? `Please fix: ${[...new Set(messages)].join(", ")}.`
: "Some details on this step are incomplete. Please review the fields above.";
};
/**
* The fields this step actually validates. `stepFields` covers what the step
* always renders; the company step additionally exposes company email/phone
* as inputs when nothing could be derived for them, and a field is validated
* exactly when the customer can see and fix it.
*/
const fieldsForStep = (s: CompanyStep): (keyof FormData)[] => {
if (s !== "company" || !identity) return stepFields[s];
return [
...stepFields.company,
...(derivedEmail ? [] : (["companyEmail"] as const)),
...(derivedPhone ? [] : (["companyPhone"] as const)),
];
};
/** Validate + persist the current step, returning whether we may advance. */
const saveCurrentStep = async (): Promise<boolean> => {
setSaveError(null);
const isValid = await trigger(stepFields[step]);
if (!isValid) return false;
const fields = fieldsForStep(step);
const isValid = await trigger(fields);
if (!isValid) {
setSaveError(describeErrors(fields));
return false;
}
if (!onSaveStep) return true;
setSaving(true);
try {
const res = await onSaveStep(stepPayload(step, watch()));
const res = await onSaveStep(
stepPayload(step, getValues(), dirtyFields),
);
if (!res.ok) {
setSaveError(res.error);
return false;
@@ -676,7 +798,14 @@ export default function CompanyProfileForm({
}
setSaveError(null);
handleSubmit((data) => onSubmit(buildPayload(data, user)))();
// Deliberately NOT `handleSubmit`: that re-validated all 34 schema fields
// — including every field belonging to a step that isn't on screen — and
// on failure did nothing at all, no alert and no navigation, which is the
// "Submit for review" button that appears dead. Each step has already
// validated and saved its own fields, and the API's `markOnboardingComplete`
// is the authority on what is still outstanding; its message reaches the
// customer through `submitError`.
onSubmit(buildPayload(getValues(), user));
return;
}
// The TIN must resolve to a real eTrade record before anything else on
@@ -728,15 +857,40 @@ export default function CompanyProfileForm({
setDocumentFieldErrors({
[POA_DELEGATION_FILE_KEY]: "DARS delegation paper is required",
});
// Validate the text fields too, so every problem shows at once.
const fieldsOk = await trigger(stepFields.poa);
setSaveError(
requirePoa
? "Freight forwarders must provide Power of Attorney details and the DARS delegation paper."
: "Upload the DARS delegation paper for the Power of Attorney you entered, or clear the PoA details to skip.",
[
requirePoa
? "Freight forwarders must provide Power of Attorney details and the DARS delegation paper."
: "Upload the DARS delegation paper for the Power of Attorney you entered, or clear the PoA details to skip.",
fieldsOk ? null : describeErrors(stepFields.poa),
]
.filter(Boolean)
.join(" "),
);
// Fall through to validate the text fields too, so every problem shows at once.
await trigger(stepFields.poa);
return;
}
// The API will not accept the PoA's details until the paper evidencing the
// delegation is actually on file, so the selection made on this step has to
// be uploaded before the save — not held back until the documents step,
// which is unreachable while this save keeps failing.
if (step === "poa" && delegationRequired && onUploadDocuments) {
const pending = documentFiles[POA_DELEGATION_FILE_KEY];
const hasPending = Array.isArray(pending) ? pending.length > 0 : pending != null;
if (hasPending) {
setSaving(true);
try {
const res = await onUploadDocuments();
if (!res.ok) {
setSaveError(res.error);
return;
}
} finally {
setSaving(false);
}
}
}
// Field steps validate + save before advancing.
const ok = await saveCurrentStep();
if (!ok) return;
@@ -812,6 +966,42 @@ export default function CompanyProfileForm({
{...register("ownerPassportNumber")}
/>
)}
{/* Normally derived from the verified owner (falling back
to eTrade and the account), and shown read-only. Fayda's
email and phone claims are optional though, so when
every source comes up empty these become typeable —
the API requires both at submit, and having no input
for them is otherwise an unrecoverable dead end. */}
<SimpleGrid cols={2} spacing="md">
{derivedEmail ? (
<ReadOnlyField
label="Company email"
value={derivedEmail}
/>
) : (
<TextInput
label="Company Email"
type="email"
description="We couldn't find one on your verified identity or account — please enter it."
placeholder="company@example.com"
error={errors.companyEmail?.message}
{...register("companyEmail")}
/>
)}
{derivedPhone ? (
<ReadOnlyField
label="Company phone"
value={derivedPhone}
/>
) : (
<ControlledPhoneField
control={control}
name="companyPhone"
label="Company Phone"
required
/>
)}
</SimpleGrid>
</>
)}
</StepSection>
@@ -835,6 +1025,7 @@ export default function CompanyProfileForm({
onDataLoaded={handleETradeDataLoaded}
onStatusChange={setTinStatus}
onReset={handleETradeReset}
alreadyVerified={hasRegistrationDetails}
/>
{tinVerified && (
<ETradeCompanyCard
@@ -924,7 +1115,10 @@ export default function CompanyProfileForm({
<Text fw={600} size="sm" c="edr-text">
Contact Person
</Text>
{watch("generalManagerName") && (
{/* `gmName`, not the raw form field: a Fayda-verified GM never
fills `generalManagerName`, so gating on it hid this card from
every Ethiopian company — the majority case. */}
{gmName && (
<LinkCheckboxCard
checked={contactSameAsGm}
onToggle={toggleContactSameAsGm}
@@ -983,21 +1177,51 @@ export default function CompanyProfileForm({
required={requirePoa}
/>
)}
{/* The address comes from the Fayda claim along with the name,
so it is shown on the panel rather than typed. Only a company
whose representative may hold no Fayda ID still types it. */}
{/* A verified representative's details come from the Fayda claim
and are shown on the panel above. Where Fayda cannot be
required — a foreign company whose representative may hold no
Fayda ID — they are typed here instead. They have to be: the
API refuses to save a freight forwarder's PoA without a name,
email and phone (`REQUIRED_POA_FIELDS`), and before this the
step rendered no input for any of them, so the customer was
told to "add the poa name, poa email, poa phone" with nowhere
to add them. */}
{!identity?.poa.verified && !identity?.faydaRequired && (
<TextInput
label="PoA Location"
placeholder="City, Country"
error={errors.poaLocation?.message}
{...register("poaLocation")}
/>
<>
<TextInput
label="Representative's Name"
placeholder="Abebe Bikila"
error={errors.poaName?.message}
{...register("poaName")}
/>
<SimpleGrid cols={2} spacing="md">
<TextInput
label="Representative's Email"
type="email"
placeholder="poa@company.com"
error={errors.poaEmail?.message}
{...register("poaEmail")}
/>
<ControlledPhoneField
control={control}
name="poaPhone"
label="Representative's Phone"
/>
</SimpleGrid>
<TextInput
label="PoA Location"
placeholder="City, Country"
error={errors.poaLocation?.message}
{...register("poaLocation")}
/>
</>
)}
{/* The paper authorises the representative the verification
named, so it only has meaning once one exists. */}
{poaProvided && poaDocumentSetting && (
{/* The paper authorises the representative, so it shows once one
exists — or straight away for a freight forwarder, who owes it
either way and must not be failed on submit for a file the
step never offered. */}
{delegationRequired && poaDocumentSetting && (
<>
<Divider my="sm" />
<SmartFileInput

View File

@@ -17,6 +17,11 @@ import { ReadOnlyField } from "./ReadOnlyField";
* supplied a value, but falls back to an editable input when eTrade left it
* blank — otherwise a gap in eTrade's own data would leave the field
* permanently empty and the user stuck (zod requires all of these).
*
* A value that fails validation unlocks the same way. eTrade (or a row saved
* before the current rules) can supply something the schema rejects, and a
* rejected value rendered read-only is a step that can never be completed and
* never says why.
*/
function LockedField({
label,
@@ -32,7 +37,7 @@ function LockedField({
errors: FieldErrors<FormData>;
}) {
const value = watch(name) as string | undefined;
if (value && value.trim()) {
if (value && value.trim() && !errors[name]) {
return <ReadOnlyField label={label} value={value} />;
}
return (
@@ -96,7 +101,12 @@ export default function ETradeCompanyCard({
<ReadOnlyField label="Renewal Date" value={watch("renewalDate")} />
<ReadOnlyField label="Renewed From" value={watch("renewedFrom")} />
<ReadOnlyField label="Renewed To" value={watch("renewedTo")} />
{region && region.trim() ? (
{/* Membership of the catalog, not mere presence: eTrade's normalizer
returns null for a region it doesn't recognise, and older rows can
hold a spelling that isn't in the list. Showing such a value
read-only left the customer with a required field they could not
correct. */}
{(ETHIOPIAN_REGIONS as readonly string[]).includes(region ?? "") ? (
<ReadOnlyField label="Region" value={region} />
) : (
<Controller

View File

@@ -1,8 +1,72 @@
import type { AuthUser } from "@/types/auth";
import type { CreateCompanyPayload } from "@/services/companies.service";
import type { ProfileResponse, UpdateProfilePayload } from "@/types/profile";
import type { CompanyIdentityState } from "@/services/verifayda.service";
import { isValidPhone, toEthiopianE164 } from "@/components/PhoneField";
import type { CompanyStep, FormData } from "./schema";
import { ETRADE_BUNDLE_FIELDS, type CompanyStep, type FormData } from "./schema";
/**
* First value that is actually present.
*
* `??` is wrong for these: an identity claim Fayda returned as an empty string
* is not a value, but it isn't null either, so `??` would stop there and hand
* the form a blank it has no input to fix.
*/
export const firstPresent = (...values: (string | null | undefined)[]): string =>
values.find((v) => v && v.trim())?.trim() ?? "";
/**
* First candidate that is actually a usable phone number, normalized to E.164.
*
* Presence is not enough here. eTrade's registered phone is free text and comes
* back as things like `"09 "`, which normalizes to `+2519` — non-empty,
* so a "first present" pick would take it, hand it to a field with no input,
* and have the API reject the whole save with
* "companyPhone must be a valid international phone number" for something the
* customer never typed. Skip a source that cannot produce a valid number and
* fall through to the next one.
*/
export const firstValidPhone = (
...values: (string | null | undefined)[]
): string => {
for (const raw of values) {
if (!raw || !raw.trim()) continue;
const e164 = toEthiopianE164(raw);
if (e164 && isValidPhone(e164)) return e164;
}
return "";
};
/** Same idea for email: a malformed claim must not become an unfixable field. */
export const firstValidEmail = (
...values: (string | null | undefined)[]
): string => {
const ok = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return values.find((v) => v && ok.test(v.trim()))?.trim() ?? "";
};
/**
* Fayda reports a person's phone as the national registry holds it, which is
* routinely a local number ("0911223344"). Every phone the forms validate and
* submit is E.164, so normalize on the way in — the API now stores new
* verifications normalized, but rows verified before that still hold raw claims.
*/
export function normalizeIdentityPhones(
identity?: CompanyIdentityState,
): CompanyIdentityState | undefined {
if (!identity) return identity;
const fix = <T extends { phone: string | null }>(person: T): T => ({
...person,
phone: person.phone ? toEthiopianE164(person.phone) : person.phone,
});
return {
...identity,
owner: fix(identity.owner),
poa: fix(identity.poa),
gm: fix(identity.gm),
};
}
/** Last 9 digits (Ethiopian national significant number) for tolerant compare. */
export const phoneDigits = (p?: string | null) =>
@@ -44,34 +108,35 @@ export function buildPayload(
};
}
/** Map one wizard step's form values to the profile-update payload it saves. */
/**
* Map one wizard step's form values to the profile-update payload it saves.
*
* `dirty` is react-hook-form's `dirtyFields`. The eTrade-owned keys (and the
* TIN) ride along only when the customer actually changed them this session —
* see `ETRADE_BUNDLE_FIELDS`. Everything else is unconditional: the API treats
* an absent key as "untouched", so omitting a field never clears it.
*/
export function stepPayload(
step: CompanyStep,
d: FormData,
dirty: Partial<Record<keyof FormData, unknown>> = {},
): Partial<UpdateProfilePayload> {
switch (step) {
case "company":
case "company": {
const etrade: Partial<UpdateProfilePayload> = {};
for (const key of ETRADE_BUNDLE_FIELDS) {
if (dirty[key]) (etrade as Record<string, unknown>)[key] = d[key];
}
if (dirty.tinNumber) etrade.tin = d.tinNumber;
return {
companyName: d.companyName,
companyEmail: d.companyEmail,
companyPhone: d.companyPhone,
companyAddress: d.companyAddress,
tin: d.tinNumber,
vatNumber: d.vatNumber,
ownerPassportNumber: d.ownerPassportNumber || undefined,
licenceNumber: d.licenceNumber,
statusDescription: d.statusDescription,
dateRegistered: d.dateRegistered,
renewedFrom: d.renewedFrom,
renewalDate: d.renewalDate,
renewedTo: d.renewedTo,
region: d.region,
zone: d.zone,
woreda: d.woreda,
kebele: d.kebele,
houseNo: d.houseNo,
etradePhone: d.etradePhone,
...etrade,
};
}
case "personnel":
return {
generalManagerName: d.generalManagerName,
@@ -86,7 +151,12 @@ export function stepPayload(
contactPersonPhone: d.contactPersonPhone,
};
case "poa":
return { poaLocation: d.poaLocation || undefined };
return {
poaName: d.poaName || undefined,
poaEmail: d.poaEmail || undefined,
poaPhone: d.poaPhone || undefined,
poaLocation: d.poaLocation || undefined,
};
default:
return {};
}

View File

@@ -0,0 +1,180 @@
import { describe, expect, it } from "vitest";
import { onboardingSchema, stepFields } from "./schema";
import {
firstPresent,
firstValidEmail,
firstValidPhone,
normalizeIdentityPhones,
stepPayload,
} from "./helpers";
import type { FormData } from "./schema";
import type { CompanyIdentityState } from "@/services/verifayda.service";
/** A minimally-valid form, so each case can vary one field at a time. */
const values = (over: Partial<FormData> = {}): FormData =>
({
companyName: "Acme PLC",
companyEmail: "acme@example.com",
companyPhone: "+251911223344",
companyAddress: "1, Bole, Bole, Addis Ababa",
etradePhone: "+251911223344",
tinNumber: "0012345678",
vatNumber: "0012345678",
ownerPassportNumber: "",
licenceNumber: "LIC-1",
statusDescription: "Active",
dateRegistered: "2020-01-01",
renewedFrom: "",
renewalDate: "",
renewedTo: "",
region: "Addis Ababa",
zone: "Bole",
woreda: "03",
kebele: "07",
houseNo: "1",
contactPersonName: "Jane Smith",
contactPersonPosition: "",
contactPersonEmail: "",
contactPersonPhone: "+251911223344",
generalManagerName: "",
generalManagerEmail: "",
generalManagerPhone: "",
poaName: "",
poaPhone: "",
poaAddress: "",
poaEmail: "",
poaLocation: "",
...over,
}) as FormData;
const errorFor = (data: FormData, field: keyof FormData) => {
const parsed = onboardingSchema.safeParse(data);
if (parsed.success) return undefined;
return parsed.error.issues.find((i) => i.path[0] === field)?.message;
};
describe("VAT number", () => {
it("accepts exactly ten digits", () => {
expect(errorFor(values({ vatNumber: "0012345678" }), "vatNumber")).toBeUndefined();
});
// `.length(10)` used to pass this, so a ten-letter string reached the API.
it("rejects ten non-digits", () => {
expect(errorFor(values({ vatNumber: "ABCDEFGHIJ" }), "vatNumber")).toBe(
"VAT number must be exactly 10 digits",
);
});
it("rejects blank", () => {
expect(errorFor(values({ vatNumber: "" }), "vatNumber")).toBe(
"VAT number is required",
);
});
});
describe("region", () => {
it("rejects a spelling outside the catalog", () => {
expect(errorFor(values({ region: "Addis Abeba City" }), "region")).toBe(
"Region is required",
);
});
});
describe("stepFields", () => {
// The regression this whole change exists to prevent: a step must not gate on
// a field it renders no input for, or Continue fails with the error attached
// to nothing on screen.
it("never gates the company step on a derived or read-only field", () => {
const unreachable = [
"companyEmail",
"companyPhone",
"companyAddress",
"etradePhone",
"licenceNumber",
"statusDescription",
"dateRegistered",
"renewedFrom",
"renewalDate",
"renewedTo",
];
expect(
stepFields.company.filter((f) => unreachable.includes(f)),
).toEqual([]);
});
});
describe("stepPayload (company)", () => {
it("omits the eTrade bundle when nothing was re-verified", () => {
const payload = stepPayload("company", values(), {});
expect(payload.tin).toBeUndefined();
expect(payload.region).toBeUndefined();
expect(payload.licenceNumber).toBeUndefined();
// The customer's own fields still save.
expect(payload.vatNumber).toBe("0012345678");
});
it("includes the bundle and the TIN once they are dirty", () => {
const payload = stepPayload("company", values(), {
tinNumber: true,
region: true,
});
expect(payload.tin).toBe("0012345678");
expect(payload.region).toBe("Addis Ababa");
// Still only the dirty ones.
expect(payload.licenceNumber).toBeUndefined();
});
});
describe("firstPresent", () => {
it("skips empty strings rather than stopping at them", () => {
expect(firstPresent("", " ", "second@example.com")).toBe(
"second@example.com",
);
expect(firstPresent(null, undefined, "")).toBe("");
});
});
describe("firstValidPhone", () => {
// Observed live: eTrade returned "09 " for a real TIN. It normalizes to
// "+2519", which is non-empty — so a presence check took it, put it in a field
// with no input, and the API rejected the whole step.
it("skips an eTrade number that cannot make a valid E.164", () => {
expect(firstValidPhone("09 ", "+251911223344")).toBe("+251911223344");
});
it("normalizes a local number it can use", () => {
expect(firstValidPhone("0911223344")).toBe("+251911223344");
});
it("returns empty when no source is usable, so the field falls back to an input", () => {
expect(firstValidPhone("09 ", "", null)).toBe("");
});
});
describe("firstValidEmail", () => {
it("skips a malformed claim", () => {
expect(firstValidEmail("not-an-email", "real@example.com")).toBe(
"real@example.com",
);
});
});
describe("normalizeIdentityPhones", () => {
it("converts a local Fayda phone claim to E.164", () => {
const identity = {
faydaRequired: true,
passportRequired: false,
owner: { verified: true, name: "A", phone: "0911223344", email: null, address: null, verifiedAt: null, passportNumber: null },
poa: { verified: false, name: null, phone: null, email: null, address: null, verifiedAt: null },
gm: { verified: false, name: null, phone: "251911223344", email: null, address: null, verifiedAt: null },
gmSameAsOwner: false,
complete: false,
} as CompanyIdentityState;
const fixed = normalizeIdentityPhones(identity)!;
expect(fixed.owner.phone).toBe("+251911223344");
expect(fixed.gm.phone).toBe("+251911223344");
expect(fixed.poa.phone).toBeNull();
});
});

View File

@@ -26,10 +26,11 @@ export const onboardingSchema = z.object({
// can diverge without the backend's eTrade-authenticity check misfiring.
etradePhone: z.string().optional(),
tinNumber: z.string().regex(/^\d{10}$/, "TIN must be exactly 10 digits"),
// `.length(10)` alone accepted "ABCDEFGHIJ" — the check has to be on digits.
vatNumber: z
.string()
.min(1, "VAT number is required")
.length(10, "VAT number must be exactly 10 digits"),
.regex(/^\d{10}$/, "VAT number must be exactly 10 digits"),
// The owner's passport number — the foreign-company identity credential
// (Fayda is an Ethiopian national ID). Required only for a foreign company;
// enforced in buildOnboardingSchema since that depends on `nationality`.
@@ -134,22 +135,47 @@ export function buildOnboardingSchema(
});
}
/**
* The keys eTrade owns. They are only resent when the customer actually
* re-verified the TIN this session: the API reacts to *any* of them by issuing
* a live eTrade lookup (`applyEtradeSourcedFields`) whose transport failures
* come back as a 400, so echoing unchanged values back would let an eTrade
* outage block a save the customer never made.
*/
export const ETRADE_BUNDLE_FIELDS = [
"companyName",
"licenceNumber",
"statusDescription",
"dateRegistered",
"renewedFrom",
"renewalDate",
"renewedTo",
"region",
"zone",
"woreda",
"kebele",
"houseNo",
"etradePhone",
] as const satisfies readonly (keyof FormData)[];
/**
* What each step validates before it may advance.
*
* Hard rule: a key belongs here only if that step renders an input the customer
* can actually correct it in. `companyEmail`/`companyPhone` are derived from the
* Fayda identity / eTrade / the account and have no input of their own, and the
* read-only eTrade fields cannot be edited at all — listing them meant a value
* the customer never typed could fail zod with its error message attached to
* nothing on screen, which reads as a Continue button that silently does
* nothing. The server still enforces its own required-field list at submit
* (`REQUIRED_COMPANY_INFO`), and reports it with a message.
*/
export const stepFields: Record<CompanyStep, (keyof FormData)[]> = {
company: [
"companyName",
"companyEmail",
"companyPhone",
"companyAddress",
"etradePhone",
"tinNumber",
"vatNumber",
"ownerPassportNumber",
"licenceNumber",
"statusDescription",
"dateRegistered",
"renewedFrom",
"renewalDate",
"renewedTo",
"region",
"zone",
"woreda",
@@ -167,7 +193,11 @@ export const stepFields: Record<CompanyStep, (keyof FormData)[]> = {
"contactPersonEmail",
"contactPersonPhone",
],
poa: ["poaLocation"],
// The API requires poaName/poaEmail/poaPhone from a freight forwarder
// (`REQUIRED_POA_FIELDS`), so the step has to offer them wherever the
// representative isn't proven by Fayda — otherwise the save is rejected
// naming fields the form never rendered.
poa: ["poaName", "poaEmail", "poaPhone", "poaLocation"],
documents: [],
additional: [],
};

View File

@@ -1,18 +1,30 @@
import {
Alert,
Box,
Button,
Group,
Modal,
Stack,
Text,
TextInput,
UnstyledButton,
} from "@mantine/core";
import { useMutation, useQuery } from "@tanstack/react-query";
import { AlertCircle, Pencil, Send, XCircle } from "lucide-react";
import {
AlertCircle,
CalendarDays,
ChevronRight,
Package,
Pencil,
Send,
XCircle,
} from "lucide-react";
import type { ReactNode } from "react";
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { api } from "@/services/api";
import { bookingsService } from "@/services/bookings.service";
import type { Freight } from "@edr/types";
import { PriceChangeModal } from "@/pages/bookings/resubmit/PriceChangeModal";
@@ -25,13 +37,55 @@ import { CompanyInfoCard } from "./components/CompanyInfoCard";
import { ContainersCard } from "./components/ContainersCard";
import { ContractInfoCard } from "./components/ContractInfoCard";
import { ActionRequiredBanner, MutationErrors } from "./components/Notices";
import { PageHeader } from "./components/PageHeader";
import { HeaderButton, PageHeader } from "./components/PageHeader";
import { EstimateCard } from "./components/pricing";
import { ScheduleCard } from "./components/ScheduleCard";
import { ShipmentDetailsCard } from "./components/ShipmentDetailsCard";
import { StatusHero } from "./components/StatusHero";
import { SupportCard } from "./components/SupportCard";
/** Row linking straight to one section of the edit-booking form. */
function EditLink({
icon,
title,
description,
onClick,
}: {
icon: ReactNode;
title: string;
description: string;
onClick: () => void;
}) {
return (
<UnstyledButton
onClick={onClick}
p="sm"
style={{
border: "1px solid #E6ECF2",
borderRadius: 12,
width: "100%",
}}
>
<Group gap="sm" wrap="nowrap" align="flex-start">
<Box mt={2} c="#0A6F4D">
{icon}
</Box>
<Box style={{ flex: 1, minWidth: 0 }}>
<Text fz={13.5} fw={700} c="#10202F">
{title}
</Text>
<Text fz={12} c="#6B7C8E" mt={2}>
{description}
</Text>
</Box>
<Box mt={2} c="#9AA8B5">
<ChevronRight size={16} />
</Box>
</Group>
</UnstyledButton>
);
}
/**
* Detail-page view for a booking staff returned with CHANGES_REQUESTED.
*
@@ -64,8 +118,9 @@ export function ChangesRequestedView({
null) as Freight.PricingBreakdown | null;
const cancelMutation = useMutation({
// Customer-facing cancel endpoint — the plain /cancel route is staff-only.
mutationFn: (reason: string) =>
api.bookings.cancel.call({ id: booking.id, reason }),
bookingsService.customerCancel(booking.id, reason),
onSuccess: () => {
setCancelDialogOpen(false);
onBookingUpdated();
@@ -76,10 +131,14 @@ export function ChangesRequestedView({
<PageShell>
<PageHeader
booking={booking}
menuActions={{
onCancel: () => setCancelDialogOpen(true),
onSupport: () => navigate("/support"),
}}
actions={
<HeaderButton
red
icon={<XCircle size={16} />}
label="Cancel booking"
onClick={() => setCancelDialogOpen(true)}
/>
}
/>
<MutationErrors mutations={[...flow.mutations, cancelMutation]} />
@@ -101,6 +160,41 @@ export function ChangesRequestedView({
<ContractInfoCard booking={booking} />
<SectionCard>
<CardTitle>Fix your booking</CardTitle>
<Text fz="12.5px" c="#6B7C8E" mt={4} mb="md">
Staff asked for changes on this booking. Update whatever needs
fixing below, then resubmit for review the booking stays in
place, no need to start over.
</Text>
<Stack gap={8}>
<EditLink
icon={<Package size={16} />}
title="Cargo & containers"
description="Add or remove containers, change container type, quantity or VGM — or for bulk cargo, change the commodity and tonnage."
onClick={() =>
navigate(`/bookings/${booking.id}/edit?section=cargo`)
}
/>
<EditLink
icon={<CalendarDays size={16} />}
title="Schedule date"
description="Pick a different departure day — only days with an open schedule on your route can be selected."
onClick={() =>
navigate(`/bookings/${booking.id}/edit?section=schedule`)
}
/>
<EditLink
icon={<Pencil size={16} />}
title="Route, service & other details"
description="Change the origin or destination yard, service type, trucking options or notes."
onClick={() =>
navigate(`/bookings/${booking.id}/edit?section=service`)
}
/>
</Stack>
</SectionCard>
<SectionCard>
<Group justify="space-between" align="center" mb="md">
<CardTitle>Your documents</CardTitle>
@@ -108,25 +202,8 @@ export function ChangesRequestedView({
<Text fz="12.5px" c="#6B7C8E" mb="sm">
Update the documents for this booking, then resubmit for review.
Replace any that changed and attach any that are still required.
Need to change the cargo itself containers, route, schedule or
other details? Edit the booking first, then come back and
resubmit.
</Text>
<Button
fullWidth
radius={10}
variant="default"
leftSection={<Pencil size={16} />}
onClick={() => navigate(`/bookings/${booking.id}/edit`)}
styles={{
root: { height: 46 },
label: { fontSize: 14, fontWeight: 700 },
}}
>
Edit booking details
</Button>
<ResubmitDocuments flow={flow} />
{flow.validationError && (

View File

@@ -24,7 +24,10 @@ import { useNavigate } from "react-router-dom";
import { api } from "@/services/api";
import { downloadStoredFile } from "@/services/files.service";
import type { SubmitBookingResponse } from "@/services/bookings.service";
import {
bookingsService,
type SubmitBookingResponse,
} from "@/services/bookings.service";
import type { Freight } from "@edr/types";
import { REQUIRED_DOC_FIELDS } from "./constants";
@@ -116,8 +119,9 @@ export function DraftBookingView({
});
const cancelMutation = useMutation({
// Customer-facing cancel endpoint — the plain /cancel route is staff-only.
mutationFn: (reason: string) =>
api.bookings.cancel.call({ id: booking.id, reason }),
bookingsService.customerCancel(booking.id, reason),
onSuccess: () => {
setCancelDialogOpen(false);
onBookingUpdated();
@@ -157,17 +161,21 @@ export function DraftBookingView({
<PageHeader
booking={booking}
actions={
<HeaderButton
dark
icon={<Pencil size={16} />}
label="Continue editing"
onClick={() => navigate(`/bookings/${booking.id}/edit`)}
/>
<Group gap={8} wrap="nowrap">
<HeaderButton
dark
icon={<Pencil size={16} />}
label="Continue editing"
onClick={() => navigate(`/bookings/${booking.id}/edit`)}
/>
<HeaderButton
red
icon={<XCircle size={16} />}
label="Cancel"
onClick={() => setCancelDialogOpen(true)}
/>
</Group>
}
menuActions={{
onCancel: () => setCancelDialogOpen(true),
onSupport: () => navigate("/support"),
}}
/>
<MutationErrors

View File

@@ -1,15 +1,21 @@
import { Group, Tabs } from "@mantine/core";
import { Button, Group, Modal, Stack, Tabs, Text } from "@mantine/core";
import { useMutation } from "@tanstack/react-query";
import {
Clock,
CreditCard,
FileText,
LayoutGrid,
Package,
TrainFront,
Truck,
XCircle,
} from "lucide-react";
import { useState } from "react";
import toast from "react-hot-toast";
import { useNavigate } from "react-router-dom";
import { useFileViewer } from "@/hooks/useFileViewer";
import { bookingsService } from "@/services/bookings.service";
import type { Freight } from "@edr/types";
import { ApproveDeliveryButton } from "../delivery/ApproveDeliveryButton";
@@ -28,6 +34,7 @@ import { MileSummaryCard } from "./components/MileSummaryCard";
import { BodyGrid, PageShell } from "./components/layout";
import {
CancelledBanner,
ActionRequiredBanner,
ConsolidationPairedNotice,
ConsolidationWaitingBanner,
} from "./components/Notices";
@@ -41,10 +48,33 @@ import { ShipmentDetailsCard } from "./components/ShipmentDetailsCard";
import { ShipmentTrackingCard } from "./components/ShipmentTrackingCard";
import { StatusHero } from "./components/StatusHero";
import { SupportCard } from "./components/SupportCard";
import { WagonCancellationCard } from "./components/WagonCancellationCard";
import { WagonsTab } from "./components/WagonsTab";
import { fmtDate, isNegative, priceTotal } from "./utils";
import { useScrollToHash } from "@/hooks/useScrollToHash";
import { useBookingPayment } from "@/pages/bookings/payments/useBookingPayment";
// Pre-payment statuses the customer may self-cancel from this view (free of
// charge). DRAFT / CHANGES_REQUESTED render their own views and drafts can
// simply be deleted; anything at or past payment must go through support.
const CUSTOMER_CANCELLABLE_STATUSES = [
"SUBMITTED",
"PRICE_CHANGED_PENDING_CONFIRM",
"PENDING_APPROVAL",
"CONTRACT_READY",
"OPERATION_REQUEST_PENDING",
"SELECTED_FOR_BATCH",
];
const cancelErrorMessage = (error: unknown) => {
const data = (
error as { response?: { data?: { message?: string | string[] } } }
)?.response?.data;
if (Array.isArray(data?.message)) return data.message.join(", ");
if (data?.message) return data.message;
return "Could not cancel the booking. Please try again.";
};
export function ReadonlyBookingView({
booking,
onBookingUpdated,
@@ -71,6 +101,23 @@ export function ReadonlyBookingView({
// and handles redirect vs CAC Bank OTP.
const pay = useBookingPayment(booking.id);
const [cancelOpen, setCancelOpen] = useState(false);
const cancelMutation = useMutation({
mutationFn: () => bookingsService.customerCancel(booking.id),
onSuccess: () => {
setCancelOpen(false);
toast.success(
"Your booking has been cancelled — no cancellation fee was charged.",
{ duration: 6000 },
);
onBookingUpdated?.();
},
onError: (e) => toast.error(cancelErrorMessage(e)),
});
const canCancel =
booking.paymentStatus !== "PAID" &&
CUSTOMER_CANCELLABLE_STATUSES.includes(status);
const pricing = booking.pricingBreakdown;
// A general contract is paid once it's FULLY_EXECUTED (signed) — it never
// enters batch selection. A one-time booking can only pay once it's been
@@ -117,6 +164,9 @@ export function ReadonlyBookingView({
"DOCUMENTS_UNDER_REVIEW",
"CLEARANCE_READY",
"OPERATION_REQUESTED",
// Operations returned the order — same card hosts the pick-a-new-day +
// resubmit flow.
"OPERATION_CHANGES_REQUESTED",
].includes(status);
// Paired: a consolidation partner was found and the booking resumed the normal
// flow. Surface the "partner found" reassurance only in the early stages,
@@ -124,13 +174,16 @@ export function ReadonlyBookingView({
const showPairedNotice =
!!booking.consolidationPartnerId &&
["SUBMITTED", "PENDING_APPROVAL", "CHANGES_REQUESTED"].includes(status);
// Wagons exist only after payment puts the booking on a train; before that
// the tab would always be an empty state, so it stays hidden.
const showWagonsTab = booking.paymentStatus === "PAID" && !isNegative(status);
return (
<PageShell>
<PageHeader
booking={booking}
actions={
(canApproveDelivery || (canPay && !showCountdown)) && (
(canApproveDelivery || (canPay && !showCountdown) || canCancel) && (
<Group gap={8} wrap="nowrap">
{canApproveDelivery && (
<ApproveDeliveryButton bookingId={booking.id} />
@@ -143,13 +196,17 @@ export function ReadonlyBookingView({
onClick={pay.open}
/>
)}
{canCancel && (
<HeaderButton
red
icon={<XCircle size={16} />}
label="Cancel booking"
onClick={() => setCancelOpen(true)}
/>
)}
</Group>
)
}
menuActions={{
onRebook: canSelfRebook ? onRebook : undefined,
onSupport: () => navigate("/support"),
}}
/>
{isNegative(status) ? (
@@ -182,7 +239,14 @@ export function ReadonlyBookingView({
priceLabel={pricing ? priceTotal(pricing) : undefined}
/>
) : (
<StatusHero booking={booking} />
<StatusHero booking={booking}>
{status === "OPERATION_CHANGES_REQUESTED" &&
booking.latestChangeRequestNote ? (
<ActionRequiredBanner title="Operations requested changes — pick a new shipment day and resubmit.">
{booking.latestChangeRequestNote}
</ActionRequiredBanner>
) : undefined}
</StatusHero>
)}
{showPairedNotice && <ConsolidationPairedNotice />}
@@ -210,6 +274,11 @@ export function ReadonlyBookingView({
<Tabs.Tab value="cargo" leftSection={<Package size={15} />}>
Cargo
</Tabs.Tab>
{showWagonsTab && (
<Tabs.Tab value="wagons" leftSection={<TrainFront size={15} />}>
Wagons
</Tabs.Tab>
)}
<Tabs.Tab value="logistics" leftSection={<Truck size={15} />}>
Logistics
</Tabs.Tab>
@@ -257,6 +326,11 @@ export function ReadonlyBookingView({
title="Consignment & Schedule"
consignment
/>
{/* Renders only on PAID + paid + contract-backed bookings. */}
<WagonCancellationCard
booking={booking}
onBookingUpdated={onBookingUpdated}
/>
<CompanyInfoCard booking={booking} />
<SupportCard />
</>
@@ -269,6 +343,20 @@ export function ReadonlyBookingView({
<CargoTab booking={booking} />
</Tabs.Panel>
{showWagonsTab && (
<Tabs.Panel value="wagons">
<WagonsTab
bookingId={booking.id}
cancellable={
booking.status === "PAID" &&
booking.paymentStatus === "PAID" &&
Boolean(booking.contractId)
}
onCancellationRequested={onBookingUpdated}
/>
</Tabs.Panel>
)}
<Tabs.Panel value="logistics">
<div className="flex flex-col gap-6">
<BodyGrid
@@ -313,6 +401,52 @@ export function ReadonlyBookingView({
bill={pay.bill}
onConfirm={pay.confirm}
/>
<Modal
opened={cancelOpen}
onClose={() => setCancelOpen(false)}
title={
<Text fw={800} fz={18} c="#10202F">
Cancel this booking?
</Text>
}
centered
radius={16}
>
<Stack gap="md">
<Text size="sm" c="#475569">
You&apos;re about to cancel booking{" "}
<Text span fw={700} c="#10202F">
{booking.reference}
</Text>
. Since you haven&apos;t paid yet,{" "}
<Text span fw={700}>
no cancellation fee
</Text>{" "}
will be charged
{status === "SELECTED_FOR_BATCH"
? ", and your reserved wagon space will be released immediately"
: ""}
. This cannot be undone.
</Text>
<Group justify="flex-end" gap={8}>
<Button
variant="default"
radius={10}
onClick={() => setCancelOpen(false)}
>
Keep booking
</Button>
<Button
color="red"
radius={10}
loading={cancelMutation.isPending}
onClick={() => cancelMutation.mutate()}
>
Cancel booking
</Button>
</Group>
</Stack>
</Modal>
{viewer}
</PageShell>
);

View File

@@ -35,6 +35,8 @@ export interface BookingContainerLineDetail {
isOverweight?: boolean;
overweightExcessTons?: number | string | null;
containerNumber?: string | null;
/** Size (ft) as stored on the line ("20"/"40") — the wagon-cancellation key. */
containerSize?: string | null;
containerType?: {
code: string;
label?: string | null;
@@ -75,6 +77,12 @@ export type BookingDetail = Freight.IBooking & {
reference: string;
status: string;
} | null;
/** The allocated train, present once the booking is placed on a schedule. */
trainSchedule?: {
trainNumber: string | null;
reference: string | null;
scheduledDepartureDate: string | null;
} | null;
};
/**

View File

@@ -51,7 +51,12 @@ export function ClearanceCard({ booking }: { booking: Freight.IBooking }) {
}
const summary =
status === "CLEARANCE_READY" ? (
status === "OPERATION_CHANGES_REQUESTED" ? (
<Alert color="yellow" radius="md" icon={<Clock size={18} />}>
Operations returned this order for changes. Update the booking details,
pick a new shipment day and resubmit.
</Alert>
) : status === "CLEARANCE_READY" ? (
<Alert color="teal" radius="md" icon={<CheckCircle2 size={18} />}>
{`${
booking.customsClearingEnabled
@@ -103,9 +108,11 @@ export function ClearanceCard({ booking }: { booking: Freight.IBooking }) {
{summary}
<Text fz="12.5px" c="dimmed" mt="sm">
{isBookAction
? "Use “Book” to enter the cargo details and schedule your shipment."
: `Use “${action?.label ?? "the action button"}” to manage your ${docNoun}.`}
{status === "OPERATION_CHANGES_REQUESTED"
? "Use “Change booking” to update the details and pick a new shipment day."
: isBookAction
? "Use “Book” to enter the cargo details and schedule your shipment."
: `Use “${action?.label ?? "the action button"}” to manage your ${docNoun}.`}
</Text>
{!isBookAction && (

View File

@@ -1,14 +1,5 @@
import { ActionIcon, Button, Group, Menu, Stack, Text } from "@mantine/core";
import {
ArrowDownLeft,
ArrowUpRight,
Edit2,
FileText,
HelpCircle,
MoreHorizontal,
RefreshCw,
XCircle,
} from "lucide-react";
import { Button, Group, Stack, Text } from "@mantine/core";
import { ArrowDownLeft, ArrowUpRight } from "lucide-react";
import type { ReactNode } from "react";
import type { Freight } from "@edr/types";
@@ -20,22 +11,12 @@ import {
import { bookingSubtitle, isDraftLike, isNegative } from "../utils";
export interface PageHeaderMenuActions {
onViewContract?: () => void;
onCancel?: () => void;
onEdit?: () => void;
onSupport?: () => void;
onRebook?: () => void;
}
export function PageHeader({
booking,
actions,
menuActions,
}: {
booking: Freight.IBooking;
actions?: ReactNode;
menuActions?: PageHeaderMenuActions;
}) {
const status = booking.status as string;
const negative = isNegative(status);
@@ -47,8 +28,6 @@ export function PageHeader({
const pillText = negative ? "#A93226" : draft ? "#475569" : "#0A6F4D";
const isExport = booking.tradeDirection === "EXPORT";
const hasMenu = menuActions && Object.values(menuActions).some(Boolean);
return (
<Group justify="space-between" align="flex-start" wrap="wrap" gap="md">
<Stack gap={8} miw={0}>
@@ -83,66 +62,6 @@ export function PageHeader({
<Group gap={8} wrap="nowrap" align="center">
{actions}
{hasMenu && (
<Menu shadow="md" radius={12} position="bottom-end">
<Menu.Target>
<ActionIcon
variant="default"
size={42}
radius={10}
aria-label="More options"
>
<MoreHorizontal size={18} />
</ActionIcon>
</Menu.Target>
<Menu.Dropdown miw={210}>
{menuActions!.onViewContract && (
<Menu.Item
leftSection={<FileText size={15} />}
onClick={menuActions!.onViewContract}
>
View contract
</Menu.Item>
)}
{menuActions!.onEdit && (
<Menu.Item
leftSection={<Edit2 size={15} />}
onClick={menuActions!.onEdit}
>
Edit
</Menu.Item>
)}
{menuActions!.onSupport && (
<Menu.Item
leftSection={<HelpCircle size={15} />}
onClick={menuActions!.onSupport}
>
Contact customer support
</Menu.Item>
)}
{menuActions!.onRebook && (
<Menu.Item
leftSection={<RefreshCw size={15} />}
onClick={menuActions!.onRebook}
>
Rebook similar schedule
</Menu.Item>
)}
{menuActions!.onCancel && (
<>
<Menu.Divider />
<Menu.Item
color="red"
leftSection={<XCircle size={15} />}
onClick={menuActions!.onCancel}
>
Cancel booking
</Menu.Item>
</>
)}
</Menu.Dropdown>
</Menu>
)}
</Group>
</Group>
);
@@ -154,6 +73,7 @@ export function HeaderButton({
onClick,
dark,
green,
red,
disabled,
}: {
label: string;
@@ -161,6 +81,7 @@ export function HeaderButton({
onClick?: () => void;
dark?: boolean;
green?: boolean;
red?: boolean;
disabled?: boolean;
}) {
return (
@@ -169,14 +90,14 @@ export function HeaderButton({
disabled={disabled}
leftSection={icon}
radius={10}
variant={green || dark ? "filled" : "default"}
color={green ? "edr-green" : dark ? "#0C1A2B" : undefined}
variant={green || dark ? "filled" : red ? "outline" : "default"}
color={green ? "edr-green" : dark ? "#0C1A2B" : red ? "red" : undefined}
styles={{
root: { height: 42, paddingInline: 16 },
label: {
fontSize: 13,
fontWeight: 700,
color: green || dark ? "#fff" : "#10202F",
color: green || dark ? "#fff" : red ? undefined : "#10202F",
},
}}
>

View File

@@ -65,6 +65,12 @@ export function ScheduleCard({
const service = serviceTypeLabel(booking);
const equipmentReturn =
booking.equipmentReturn === "WITH_RETURN" ? "With return" : "Without return";
const schedule = booking.trainSchedule;
const trainLabel = schedule?.trainNumber
? `Train ${schedule.trainNumber}${schedule.reference ? ` · ${schedule.reference}` : ""}`
: schedule?.reference
? `Schedule ${schedule.reference}`
: "Track shipment";
const assignedTrain: Row = booking.trainScheduleId
? {
label: "Assigned train",
@@ -85,7 +91,7 @@ export function ScheduleCard({
fontSize: 13,
}}
>
<MapPin size={13} /> Track shipment
<MapPin size={13} /> {trainLabel}
</button>
),
}

View File

@@ -0,0 +1,496 @@
import {
Alert,
Box,
Button,
Group,
Modal,
NumberInput,
Stack,
Table,
Text,
Textarea,
} from "@mantine/core";
import { useMutation, useQuery } from "@tanstack/react-query";
import { CheckCircle2, Clock, CreditCard, TrainTrack } from "lucide-react";
import { useMemo, useState } from "react";
import toast from "react-hot-toast";
import { Link, useNavigate } from "react-router-dom";
import type { Freight } from "@edr/types";
import { api } from "@/services/api";
import {
bookingsService,
type RequestWagonCancellationPayload,
type WagonCancellation,
type WagonCancellationPreview,
} from "@/services/bookings.service";
import { OperationDatePicker } from "@/pages/bookings/clearance";
import { useFeeInvoicePayment } from "@/pages/bookings/payments/useBookingPayment";
import type { BookingDetail } from "../booking-detail-types";
import { fmtDate } from "../utils";
import { CardTitle, SectionCard } from "./layout";
import { PaymentMethodModal } from "./PaymentMethodModal";
// Same pill treatment as WagonsTab's STATUS_TONES so the page reads as one.
const STATUS_TONES: Record<
WagonCancellation["status"],
{ bg: string; color: string; label: string }
> = {
FEE_PENDING: { bg: "#FFFBEB", color: "#92400E", label: "Fee pending" },
CREDIT_AVAILABLE: { bg: "#EAF1FE", color: "#1E40AF", label: "Credit available" },
REBOOKED: { bg: "#E8F5EF", color: "#0A6F4D", label: "Rebooked" },
WITHDRAWN: { bg: "#F1F4F7", color: "#475569", label: "Withdrawn" },
EXPIRED: { bg: "#FEF2F2", color: "#B91C1C", label: "Expired" },
};
function StatusPill({ status }: { status: WagonCancellation["status"] }) {
const tone = STATUS_TONES[status] ?? STATUS_TONES.WITHDRAWN;
return (
<Text
component="span"
fz={11}
fw={700}
px={9}
py={3}
style={{ borderRadius: 999, backgroundColor: tone.bg, color: tone.color }}
>
{tone.label}
</Text>
);
}
const fmtMoney = (amount: number | string, currency: string) =>
`${Number(amount).toLocaleString()} ${currency}`;
const apiErrorMessage = (error: unknown, fallback: string) => {
const data = (
error as { response?: { data?: { message?: string | string[] } } }
)?.response?.data;
if (Array.isArray(data?.message)) return data.message.join(", ");
if (data?.message) return data.message;
return fallback;
};
const th = { color: "#9AA8B5", fontSize: 11 } as const;
/**
* Partial wagon cancellation on a PAID contract booking: request a cut (fee
* previewed first), pay the cancellation fee, then rebook the freed credit
* onto another shipment day — plus the booking's cancellation history.
* Wagons leave the schedule at request time; the fee settles the credit.
*/
export function WagonCancellationCard({
booking,
onBookingUpdated,
}: {
booking: Freight.IBooking;
onBookingUpdated?: () => void;
}) {
const navigate = useNavigate();
const status = booking.status as string;
const eligible =
status === "PAID" &&
(booking.paymentStatus as string) === "PAID" &&
!!booking.contractId;
const isBulk = booking.freightType === "BULK";
const detail = booking as BookingDetail;
// The entity field the API serializes on the detail read; not on the DTO type.
const wagonsRequired = Number(
(booking as { wagonsRequired?: number | string | null }).wagonsRequired ?? 0,
);
// Live units per container size ("20"/"40"), summed across lines.
const containerLines = useMemo(() => {
const bySize = new Map<string, number>();
for (const line of detail.bookingContainers ?? []) {
const size =
line.containerSize ??
(line.containerType?.sizeFt != null
? String(line.containerType.sizeFt)
: null);
if (!size) continue;
bySize.set(size, (bySize.get(size) ?? 0) + Number(line.quantity ?? 0));
}
return [...bySize.entries()].map(([containerSize, quantity]) => ({
containerSize,
quantity,
}));
}, [detail.bookingContainers]);
const { data, refetch } = useQuery({
...api.bookings.listWagonCancellations.queryOptions({
input: { bookingId: booking.id },
}),
enabled: eligible,
});
// History includes rows where this booking is the rebooked TARGET — only
// rows this booking opened itself can be paid/withdrawn/rebooked from here.
const rows = data?.items ?? [];
const ownRows = rows.filter((r) => r.bookingId === booking.id);
const openRow = ownRows.find((r) => r.status === "FEE_PENDING");
const creditRow = ownRows.find((r) => r.status === "CREDIT_AVAILABLE");
const feePay = useFeeInvoicePayment(booking.id);
// ── Request modal state ──
const [modalOpen, setModalOpen] = useState(false);
const [wagons, setWagons] = useState<number | string>(1);
const [cancelBySize, setCancelBySize] = useState<Record<string, number>>({});
const [reason, setReason] = useState("");
const [preview, setPreview] = useState<WagonCancellationPreview | null>(null);
const closeModal = () => {
setModalOpen(false);
setWagons(1);
setCancelBySize({});
setReason("");
setPreview(null);
};
const requestPayload = (): RequestWagonCancellationPayload | null => {
const trimmedReason = reason.trim();
if (isBulk) {
const n = Number(wagons);
if (!n || n <= 0) return null;
return { wagons: n, ...(trimmedReason ? { reason: trimmedReason } : {}) };
}
const containers = containerLines
.map((l) => ({
containerSize: l.containerSize,
quantity: cancelBySize[l.containerSize] ?? 0,
}))
.filter((c) => c.quantity > 0);
if (!containers.length) return null;
return { containers, ...(trimmedReason ? { reason: trimmedReason } : {}) };
};
const payload = requestPayload();
const previewMutation = useMutation({
mutationFn: (body: RequestWagonCancellationPayload) =>
bookingsService.previewWagonCancellation(booking.id, body),
onSuccess: setPreview,
onError: (e) => {
setPreview(null);
toast.error(apiErrorMessage(e, "Could not calculate the fee. Please try again."));
},
});
const requestMutation = useMutation({
mutationFn: (body: RequestWagonCancellationPayload) =>
bookingsService.requestWagonCancellation(booking.id, body),
onSuccess: () => {
closeModal();
toast.success(
"Cancellation requested — pay the fee to release the wagons.",
{ duration: 6000 },
);
void refetch();
onBookingUpdated?.();
},
onError: (e) =>
toast.error(
apiErrorMessage(e, "Could not request the cancellation. Please try again."),
),
});
const withdrawMutation = useMutation({
mutationFn: () => bookingsService.withdrawWagonCancellation(openRow!.id),
onSuccess: () => {
toast.success("Cancellation withdrawn — the fee invoice was voided.");
void refetch();
onBookingUpdated?.();
},
onError: (e) =>
toast.error(
apiErrorMessage(e, "Could not withdraw the cancellation. Please try again."),
),
});
const [rebookDate, setRebookDate] = useState("");
const rebookMutation = useMutation({
mutationFn: () =>
bookingsService.rebookWagonCancellation(creditRow!.id, {
scheduledDate: rebookDate,
}),
onSuccess: ({ bookingId }) => {
toast.success("Wagons rebooked — taking you to the new booking.", {
duration: 6000,
});
navigate(`/bookings/${bookingId}`);
},
onError: (e) =>
toast.error(apiErrorMessage(e, "Could not rebook the wagons. Please try again.")),
});
if (!eligible) return null;
return (
<SectionCard>
<Group justify="space-between" align="center" mb="sm">
<CardTitle>Wagon Cancellation</CardTitle>
{!openRow && !creditRow && (
<Button
variant="default"
radius="md"
leftSection={<TrainTrack size={16} />}
onClick={() => setModalOpen(true)}
>
Cancel wagons
</Button>
)}
</Group>
{openRow ? (
<Stack gap="sm">
<Alert color="yellow" radius="md" icon={<Clock size={18} />}>
A cancellation of {Number(openRow.wagonsCancelled)} wagon(s) is
awaiting its fee of{" "}
<Text span fw={700}>
{fmtMoney(openRow.feeAmount, openRow.feeCurrency)}
</Text>
. The cancelled wagons have left the train. Pay the fee to unlock
the rebooking credit, or withdraw the request to get the wagons
back withdrawing works only while the train still has free space
for them.
</Alert>
<Group gap={8}>
<Button
color="edr-green"
radius="md"
leftSection={<CreditCard size={16} />}
onClick={feePay.open}
>
Pay cancellation fee
</Button>
<Button
variant="default"
radius="md"
loading={withdrawMutation.isPending}
onClick={() => withdrawMutation.mutate()}
>
Withdraw request
</Button>
</Group>
</Stack>
) : creditRow ? (
<Stack gap="sm">
<Alert color="teal" radius="md" icon={<CheckCircle2 size={18} />}>
{Number(creditRow.wagonsCancelled)} wagon(s) were released a
credit of{" "}
<Text span fw={700}>
{fmtMoney(creditRow.creditAmount, booking.paymentCurrency)}
</Text>{" "}
is available. Pick a shipment day to rebook them as a new paid
booking (no further payment needed).
</Alert>
<OperationDatePicker
bookingId={booking.id}
value={rebookDate}
onChange={setRebookDate}
/>
<Group justify="flex-end">
<Button
color="edr-green"
radius="md"
disabled={!rebookDate}
loading={rebookMutation.isPending}
onClick={() => rebookMutation.mutate()}
>
Rebook wagons
</Button>
</Group>
</Stack>
) : (
<Text fz={13} c="#475569">
Need fewer wagons than you paid for? Cancel part of this booking for
a per-wagon fee the freed freight amount becomes a credit you can
rebook onto another shipment day.
</Text>
)}
{rows.length > 0 && (
<Box style={{ overflowX: "auto" }} mt="md">
<Table verticalSpacing={6} horizontalSpacing="sm">
<Table.Thead>
<Table.Tr>
<Table.Th style={th}>Date</Table.Th>
<Table.Th style={th}>Wagons</Table.Th>
<Table.Th style={th}>Fee</Table.Th>
<Table.Th style={th}>Status</Table.Th>
<Table.Th style={th}>Rebooked as</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{rows.map((r) => (
<Table.Tr key={r.id}>
<Table.Td>
<Text fz={12.5} c="#475569">
{fmtDate(r.createdAt)}
</Text>
</Table.Td>
<Table.Td>
<Text fz={12.5} fw={700} c="#10202F">
{Number(r.wagonsCancelled)}
</Text>
</Table.Td>
<Table.Td>
<Text fz={12.5} c="#475569">
{fmtMoney(r.feeAmount, r.feeCurrency)}
</Text>
</Table.Td>
<Table.Td>
<StatusPill status={r.status} />
</Table.Td>
<Table.Td>
{r.rebookedBookingId ? (
<Text
component={Link}
to={`/bookings/${r.rebookedBookingId}`}
fz={12.5}
fw={700}
c="#0A6F4D"
style={{ textDecoration: "underline" }}
>
{r.rebookedBooking?.reference ?? "View booking"}
</Text>
) : (
<Text fz={12.5} c="#9AA8B5">
</Text>
)}
</Table.Td>
</Table.Tr>
))}
</Table.Tbody>
</Table>
</Box>
)}
<PaymentMethodModal
opened={feePay.modalOpen}
onClose={feePay.close}
amountLabel={
openRow ? fmtMoney(openRow.feeAmount, openRow.feeCurrency) : undefined
}
currency={openRow?.feeCurrency}
processing={feePay.processing}
error={feePay.error}
otp={feePay.otp}
bill={feePay.bill}
onConfirm={feePay.confirm}
/>
<Modal
opened={modalOpen}
onClose={closeModal}
title={
<Text fw={800} fz={18} c="#10202F">
Cancel wagons
</Text>
}
centered
radius={16}
>
<Stack gap="md">
<Text size="sm" c="#475569">
Choose how much of booking{" "}
<Text span fw={700} c="#10202F">
{booking.reference}
</Text>{" "}
to cancel. A per-wagon fee applies; once it&apos;s paid the wagons
are released and the freed amount becomes a rebooking credit. At
least one wagon must remain to cancel everything, cancel the
whole booking instead.
</Text>
{isBulk ? (
<NumberInput
label="Wagons to cancel"
min={1}
max={wagonsRequired > 1 ? wagonsRequired - 1 : undefined}
allowDecimal={false}
value={wagons}
onChange={(v) => {
setWagons(v);
setPreview(null);
}}
/>
) : (
containerLines.map((line) => (
<NumberInput
key={line.containerSize}
label={`${line.containerSize}ft containers to cancel`}
description={`${line.quantity} on this booking`}
min={0}
max={line.quantity}
allowDecimal={false}
value={cancelBySize[line.containerSize] ?? 0}
onChange={(v) => {
setCancelBySize((prev) => ({
...prev,
[line.containerSize]: Number(v) || 0,
}));
setPreview(null);
}}
/>
))
)}
<Textarea
label="Reason (optional)"
placeholder="Why are these wagons no longer needed?"
autosize
minRows={2}
value={reason}
onChange={(e) => setReason(e.currentTarget.value)}
/>
{preview && (
<Alert color="blue" radius="md">
<Text fz={13}>
Cancelling{" "}
<Text span fw={700}>
{preview.wagons} wagon(s)
</Text>{" "}
(~{preview.weightTons} t) costs a fee of{" "}
<Text span fw={700}>
{fmtMoney(preview.feeAmount, preview.feeCurrency)}
</Text>{" "}
({fmtMoney(preview.feePerWagon, preview.feeCurrency)} per
wagon) and frees a rebooking credit of{" "}
<Text span fw={700}>
{fmtMoney(preview.creditAmount, booking.paymentCurrency)}
</Text>
.
</Text>
</Alert>
)}
<Group justify="flex-end" gap={8}>
<Button
variant="default"
radius={10}
disabled={!payload}
loading={previewMutation.isPending}
onClick={() => payload && previewMutation.mutate(payload)}
>
Calculate fee
</Button>
<Button
color="red"
radius={10}
disabled={!payload}
loading={requestMutation.isPending}
onClick={() => payload && requestMutation.mutate(payload)}
>
Request cancellation
</Button>
</Group>
</Stack>
</Modal>
</SectionCard>
);
}

View File

@@ -0,0 +1,792 @@
import {
Alert,
Box,
Button,
Checkbox,
Group,
Modal,
SimpleGrid,
Skeleton,
Stack,
Table,
Text,
Textarea,
Tooltip,
} from "@mantine/core";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
Container,
Gauge,
MapPin,
Package,
Route,
Scale,
TrainFront,
TrainTrack,
} from "lucide-react";
import { useState, type ReactNode } from "react";
import toast from "react-hot-toast";
import {
bookingsService,
type BookingWagonAllocation,
type WagonCancellation,
type WagonCancellationPreview,
} from "@/services/bookings.service";
import { api } from "@/services/api";
import { fmtDate, fmtWeight } from "../utils";
import { CardTitle, SectionCard } from "./layout";
const CANCEL_TONES: Record<
string,
{ bg: string; color: string; border: string; label: string; hint: string }
> = {
FEE_PENDING: {
bg: "#FFFBEB",
color: "#92400E",
border: "#FDE68A",
label: "Cancelled — fee unpaid",
hint: "These wagons left the train. Pay the cancellation fee to turn them into a rebooking credit, or withdraw to get them back (needs free space).",
},
CREDIT_AVAILABLE: {
bg: "#E6F7F2",
color: "#0A6F4D",
border: "#B7E6D6",
label: "Cancelled — credit ready",
hint: "Fee paid. Pick a new shipment day in the wagon cancellation card to rebook these — no new freight charge.",
},
REBOOKED: {
bg: "#E8F5EF",
color: "#0A6F4D",
border: "#B7E6D6",
label: "Rebooked",
hint: "These wagons ride again on the rebooked shipment.",
},
};
/** Cancelled wagons + their cargo, categorized by cancellation state. */
function CancelledWagonsSection({ rows }: { rows: WagonCancellation[] }) {
const visible = rows.filter((r) => CANCEL_TONES[r.status]);
if (!visible.length) return null;
return (
<SectionCard>
<CardTitle>Cancelled wagons</CardTitle>
<Stack gap="sm" mt="sm">
{visible.map((r) => {
const tone = CANCEL_TONES[r.status];
const units = r.cancelledQuantities.units ?? [];
return (
<Box
key={r.id}
p={12}
style={{
borderRadius: 10,
backgroundColor: tone.bg,
border: `1px solid ${tone.border}`,
}}
>
<Group justify="space-between" align="center" wrap="wrap" gap={6}>
<Text fz={13.5} fw={800} style={{ color: tone.color }}>
{Number(r.wagonsCancelled)} wagon(s) {tone.label}
</Text>
<Text fz={12} c="#6B7C8E">
{fmtDate(r.createdAt)}
{r.rebookedBooking
? ` · new booking ${r.rebookedBooking.reference}`
: ""}
</Text>
</Group>
{units.length > 0 && (
<Group gap={6} mt={6} wrap="wrap">
{units.map((u) => (
<Text
key={u.containerNumber}
component="span"
fz={11.5}
fw={700}
px={8}
py={2}
style={{
borderRadius: 6,
backgroundColor: "white",
border: `1px solid ${tone.border}`,
color: tone.color,
fontFamily: "monospace",
}}
>
{u.containerNumber} · {u.containerSize}ft
</Text>
))}
</Group>
)}
{!units.length && r.cancelledQuantities.bulkTons != null && (
<Text fz={12.5} mt={4} style={{ color: tone.color }}>
{Number(r.cancelledQuantities.bulkTons).toLocaleString()} tons of
bulk cargo
</Text>
)}
<Text fz={12} c="#6B7C8E" mt={6}>
{tone.hint}
</Text>
</Box>
);
})}
</Stack>
</SectionCard>
);
}
const apiErrorMessage = (error: unknown, fallback: string) => {
const data = (
error as { response?: { data?: { message?: string | string[] } } }
)?.response?.data;
if (Array.isArray(data?.message)) return data.message.join(", ");
if (data?.message) return data.message;
return fallback;
};
// Mirrors CargoTab's local Flag/StatTile look so the two tabs read as one page.
const STATUS_TONES: Record<
BookingWagonAllocation["status"],
{ bg: string; color: string; label: string }
> = {
PLANNED: { bg: "#F1F4F7", color: "#475569", label: "Planned" },
RESERVED: { bg: "#FFFBEB", color: "#92400E", label: "Reserved" },
LOADED: { bg: "#E8F5EF", color: "#0A6F4D", label: "Loaded" },
DEPARTED: { bg: "#EAF1FE", color: "#1E40AF", label: "Departed" },
};
function StatusPill({ status }: { status: BookingWagonAllocation["status"] }) {
const tone = STATUS_TONES[status] ?? STATUS_TONES.PLANNED;
return (
<Text
component="span"
fz={11}
fw={700}
px={9}
py={3}
style={{ borderRadius: 999, backgroundColor: tone.bg, color: tone.color }}
>
{tone.label}
</Text>
);
}
function StatTile({
icon,
label,
value,
sub,
}: {
icon: ReactNode;
label: string;
value: string;
sub?: string;
}) {
return (
<Box
p={14}
style={{
borderRadius: 12,
border: "1px solid #E6ECF2",
backgroundColor: "#FAFCFE",
}}
>
<Group gap={6} align="center" mb={6} c="#6B7C8E">
{icon}
<Text fz="11px" fw={700} tt="uppercase" style={{ letterSpacing: "0.05em" }}>
{label}
</Text>
</Group>
<Text fz={18} fw={800} c="#10202F" truncate>
{value}
</Text>
{sub && (
<Text fz={12} c="#9AA8B5" mt={2}>
{sub}
</Text>
)}
</Box>
);
}
/** Little consist strip: locomotive + one box per wagon, in marshalling order. */
function ConsistStrip({ wagons }: { wagons: BookingWagonAllocation[] }) {
return (
<Box style={{ overflowX: "auto" }} pb={4}>
<Group gap={5} wrap="nowrap" align="flex-end">
<Box
px={10}
py={8}
style={{
borderRadius: "10px 4px 4px 10px",
backgroundColor: "#10202F",
color: "white",
display: "flex",
alignItems: "center",
gap: 6,
flexShrink: 0,
}}
>
<TrainFront size={16} />
<Text fz={11} fw={800}>
LOCO
</Text>
</Box>
{wagons.map((w) => (
<Tooltip
key={w.sequenceNo}
label={`${w.wagonNumber ?? "Unassigned"} · ${w.wagonType ?? "—"} · ${
STATUS_TONES[w.status]?.label ?? w.status
}`}
withArrow
>
<Box
px={10}
py={8}
ta="center"
style={{
borderRadius: 6,
border: "1.5px solid #C9D6E2",
backgroundColor: STATUS_TONES[w.status]?.bg ?? "#F1F4F7",
flexShrink: 0,
minWidth: 64,
cursor: "default",
}}
>
<Text fz={10} fw={700} c="#6B7C8E">
W{w.sequenceNo}
</Text>
<Text fz={11.5} fw={800} c="#10202F" style={{ fontFamily: "monospace" }}>
{w.wagonNumber ?? "—"}
</Text>
</Box>
</Tooltip>
))}
</Group>
</Box>
);
}
function LoadBar({ allocated, capacity }: { allocated: number; capacity: number }) {
const pct = capacity > 0 ? Math.min(100, Math.round((allocated / capacity) * 100)) : 0;
return (
<Box>
<Group justify="space-between" mb={4}>
<Text fz={11.5} fw={700} c="#6B7C8E">
Load
</Text>
<Text fz={11.5} fw={800} c="#10202F">
{fmtWeight(allocated)}
{capacity > 0 ? ` / ${fmtWeight(capacity)} · ${pct}%` : ""}
</Text>
</Group>
<Box style={{ height: 6, borderRadius: 999, backgroundColor: "#EDF2F7" }}>
<Box
style={{
height: 6,
width: `${pct}%`,
borderRadius: 999,
backgroundColor: pct >= 95 ? "#B45309" : "#0A6F4D",
transition: "width 300ms ease",
}}
/>
</Box>
</Box>
);
}
const th = { color: "#9AA8B5", fontSize: 11 } as const;
function WagonCard({
wagon,
selectable,
selected,
onToggle,
}: {
wagon: BookingWagonAllocation;
selectable?: boolean;
selected?: boolean;
onToggle?: () => void;
}) {
const allocated = Number(wagon.allocatedWeightTons || 0);
const capacity = Number(wagon.capacityTons || 0);
const containers = wagon.containers ?? [];
return (
<SectionCard
style={
selected
? { outline: "2px solid #B45309", outlineOffset: -2, borderRadius: 16 }
: undefined
}
>
<Group justify="space-between" align="flex-start" wrap="nowrap" mb="sm">
<Group gap={10} align="center" wrap="nowrap">
{selectable && (
<Checkbox
checked={!!selected}
onChange={onToggle}
color="orange"
aria-label={`Select wagon ${wagon.sequenceNo} for cancellation`}
/>
)}
<Box
style={{
width: 40,
height: 40,
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
borderRadius: 10,
backgroundColor: "#10202F",
color: "white",
flexShrink: 0,
}}
>
<Text fz={9} fw={700} c="#9AA8B5" lh={1}>
WAGON
</Text>
<Text fz={15} fw={800} lh={1.2}>
{wagon.sequenceNo}
</Text>
</Box>
<Box>
<Text fz={16} fw={800} c="#10202F" style={{ fontFamily: "monospace" }}>
{wagon.wagonNumber ?? "Not yet assigned"}
</Text>
<Text fz={12} c="#9AA8B5">
{wagon.wagonType ?? "Wagon type pending"}
{wagon.wagonTypeCode && wagon.wagonType !== wagon.wagonTypeCode
? ` · ${wagon.wagonTypeCode}`
: ""}
</Text>
</Box>
</Group>
<StatusPill status={wagon.status} />
</Group>
<LoadBar allocated={allocated} capacity={capacity} />
<Group gap={16} mt="sm" mb={containers.length || wagon.loadType === "BULK" ? "sm" : 0}>
{Number(wagon.tareWeightTons) > 0 && (
<Group gap={5}>
<Scale size={12} color="#9AA8B5" />
<Text fz={12} c="#475569">
Tare {fmtWeight(Number(wagon.tareWeightTons))}
</Text>
</Group>
)}
{Number(wagon.lengthMeters) > 0 && (
<Group gap={5}>
<Route size={12} color="#9AA8B5" />
<Text fz={12} c="#475569">
{Number(wagon.lengthMeters)} m
</Text>
</Group>
)}
<Group gap={5}>
{wagon.loadType === "BULK" ? (
<Package size={12} color="#9AA8B5" />
) : (
<Container size={12} color="#9AA8B5" />
)}
<Text fz={12} c="#475569">
{wagon.loadType === "BULK" ? "Bulk load" : "Container load"}
</Text>
</Group>
</Group>
{wagon.loadType === "BULK" && (wagon.bulkCargoDescription || wagon.bulkQuantity) && (
<Box
p={10}
style={{ borderRadius: 10, backgroundColor: "#FAFCFE", border: "1px solid #EDF2F7" }}
>
<Text fz={12.5} fw={700} c="#10202F">
{wagon.bulkCargoDescription ?? "Bulk cargo"}
</Text>
{Number(wagon.bulkQuantity) > 0 && (
<Text fz={12} c="#9AA8B5">
Quantity: {Number(wagon.bulkQuantity).toLocaleString()}
</Text>
)}
</Box>
)}
{containers.length > 0 && (
<Box style={{ overflowX: "auto" }}>
<Table verticalSpacing={6} horizontalSpacing="sm">
<Table.Thead>
<Table.Tr>
<Table.Th style={th}>Container no.</Table.Th>
<Table.Th style={th}>Seal no.</Table.Th>
<Table.Th style={th}>Gross wt.</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{containers.map((c, i) => (
<Table.Tr key={c.containerNumber ?? i}>
<Table.Td>
<Text fz={12.5} fw={700} c="#10202F" style={{ fontFamily: "monospace" }}>
{c.containerNumber ?? "—"}
</Text>
</Table.Td>
<Table.Td>
<Text fz={12.5} c="#475569">
{c.sealNumber ?? "—"}
</Text>
</Table.Td>
<Table.Td>
<Text fz={12.5} c="#475569">
{Number(c.grossWeightTons) > 0
? fmtWeight(Number(c.grossWeightTons))
: "—"}
</Text>
</Table.Td>
</Table.Tr>
))}
</Table.Tbody>
</Table>
</Box>
)}
</SectionCard>
);
}
/**
* "Wagons" tab: the customer's view of their allocated wagons once the paid
* booking has been placed on a train — consist strip in marshalling order,
* per-wagon load/containers, and the train's route summary.
*/
export function WagonsTab({
bookingId,
cancellable,
onCancellationRequested,
}: {
bookingId: string;
/** PAID contract booking — specific wagons may be selected for cancellation. */
cancellable?: boolean;
onCancellationRequested?: () => void;
}) {
const queryClient = useQueryClient();
const { data: wagons, isLoading } = useQuery({
queryKey: ["booking-wagons", bookingId],
queryFn: () => bookingsService.getWagons(bookingId),
enabled: !!bookingId,
});
// Cancellation history: feeds the "Cancelled wagons" section and blocks a
// second request while one is awaiting its fee.
const { data: history } = useQuery({
...api.bookings.listWagonCancellations.queryOptions({ input: { bookingId } }),
enabled: !!bookingId,
});
const ownCancellations = (history?.items ?? []).filter(
(r) => r.bookingId === bookingId,
);
const hasOpenCancellation = ownCancellations.some(
(r) => r.status === "FEE_PENDING",
);
const [selected, setSelected] = useState<Set<string>>(new Set());
const [confirmOpen, setConfirmOpen] = useState(false);
const [reason, setReason] = useState("");
const [preview, setPreview] = useState<WagonCancellationPreview | null>(null);
const toggle = (allocationId: string) =>
setSelected((prev) => {
const next = new Set(prev);
if (next.has(allocationId)) next.delete(allocationId);
else next.add(allocationId);
return next;
});
const previewMutation = useMutation({
mutationFn: () =>
bookingsService.previewWagonCancellation(bookingId, {
wagonAllocationIds: [...selected],
}),
onSuccess: setPreview,
onError: (e) => {
setPreview(null);
toast.error(apiErrorMessage(e, "Could not calculate the fee. Please try again."));
},
});
const requestMutation = useMutation({
mutationFn: () =>
bookingsService.requestWagonCancellation(bookingId, {
wagonAllocationIds: [...selected],
...(reason.trim() ? { reason: reason.trim() } : {}),
}),
onSuccess: () => {
setConfirmOpen(false);
setSelected(new Set());
setReason("");
setPreview(null);
toast.success(
"Cancellation requested — pay the fee in the wagon cancellation card to release these wagons.",
{ duration: 7000 },
);
void queryClient.invalidateQueries({ queryKey: ["booking-wagons", bookingId] });
void queryClient.invalidateQueries({
queryKey: api.bookings.listWagonCancellations.queryKey({ bookingId }),
});
onCancellationRequested?.();
},
onError: (e) =>
toast.error(apiErrorMessage(e, "Could not request the cancellation. Please try again.")),
});
const openConfirm = () => {
setPreview(null);
setConfirmOpen(true);
previewMutation.mutate();
};
if (isLoading) {
return (
<div className="flex flex-col gap-6" style={{ maxWidth: 980 }}>
<Skeleton height={140} radius={16} />
<SimpleGrid cols={{ base: 1, md: 2 }} spacing={24}>
<Skeleton height={220} radius={16} />
<Skeleton height={220} radius={16} />
</SimpleGrid>
</div>
);
}
if (!wagons?.length) {
return (
<div className="flex flex-col gap-6" style={{ maxWidth: 980 }}>
<CancelledWagonsSection rows={ownCancellations} />
<SectionCard>
<Group gap={12} align="center">
<Box
style={{
width: 44,
height: 44,
display: "flex",
alignItems: "center",
justifyContent: "center",
borderRadius: 12,
backgroundColor: "#F1F4F7",
color: "#6B7C8E",
}}
>
<TrainTrack size={22} />
</Box>
<Box>
<Text fz={15} fw={800} c="#10202F">
No wagons allocated yet
</Text>
<Text fz={13} c="#9AA8B5">
Your wagons will appear here once the shipment is placed on a
train after payment.
</Text>
</Box>
</Group>
</SectionCard>
</div>
);
}
const canSelect = !!cancellable && !hasOpenCancellation;
const first = wagons[0];
const totalAllocated = wagons.reduce(
(s, w) => s + Number(w.allocatedWeightTons || 0),
0,
);
const totalCapacity = wagons.reduce((s, w) => s + Number(w.capacityTons || 0), 0);
const containerCount = wagons.reduce((s, w) => s + (w.containers?.length ?? 0), 0);
const utilization =
totalCapacity > 0 ? Math.round((totalAllocated / totalCapacity) * 100) : null;
return (
<div className="flex flex-col gap-6" style={{ maxWidth: 980 }}>
<SectionCard>
<Group justify="space-between" align="flex-start" mb="md" wrap="wrap">
<Group gap={10} align="center">
<Box
style={{
width: 36,
height: 36,
display: "flex",
alignItems: "center",
justifyContent: "center",
borderRadius: 10,
backgroundColor: "#E8F5EF",
color: "#0A6F4D",
}}
>
<TrainFront size={18} />
</Box>
<Box>
<Text fz={15} fw={800} c="#10202F">
{first.trainNumber ? `Train ${first.trainNumber}` : "Your train"}
</Text>
<Group gap={5} align="center">
<MapPin size={11} color="#9AA8B5" />
<Text fz={12} c="#9AA8B5">
{first.originStation ?? "—"} {first.destinationStation ?? "—"}
{first.departureAt ? ` · departs ${fmtDate(first.departureAt)}` : ""}
</Text>
</Group>
</Box>
</Group>
<CardTitle>Your wagons on this train</CardTitle>
</Group>
<ConsistStrip wagons={wagons} />
<SimpleGrid cols={{ base: 2, sm: 4 }} spacing={10} mt="md">
<StatTile
icon={<TrainTrack size={13} />}
label="Wagons"
value={`${wagons.length}`}
sub="allocated to you"
/>
<StatTile
icon={<Scale size={13} />}
label="Allocated weight"
value={fmtWeight(totalAllocated)}
/>
<StatTile
icon={<Container size={13} />}
label="Containers"
value={containerCount ? `${containerCount}` : "—"}
sub={containerCount ? "loaded on wagons" : undefined}
/>
<StatTile
icon={<Gauge size={13} />}
label="Utilization"
value={utilization != null ? `${utilization}%` : "—"}
sub="of wagon capacity"
/>
</SimpleGrid>
</SectionCard>
{canSelect && (
<SectionCard>
<Group justify="space-between" align="center" wrap="wrap" gap="sm">
<Box>
<Text fz={14} fw={800} c="#10202F">
Cancel specific wagons
</Text>
<Text fz={12.5} c="#9AA8B5">
Tick the wagons you want to cancel. They leave this train
immediately; after you pay the per-wagon cancellation fee, the
freight you paid for them becomes a credit you can rebook on
another day.
</Text>
</Box>
<Button
color="orange"
disabled={selected.size === 0 || selected.size >= wagons.length}
onClick={openConfirm}
>
Cancel selected ({selected.size})
</Button>
</Group>
{selected.size >= wagons.length && selected.size > 0 && (
<Text fz={12} c="#B3362C" mt={6}>
You cannot cancel every wagon here to cancel the whole booking,
use the booking cancellation instead.
</Text>
)}
</SectionCard>
)}
{cancellable && hasOpenCancellation && (
<Alert color="yellow" variant="light">
A wagon cancellation is already awaiting its fee pay or withdraw it
in the wagon cancellation card before requesting another.
</Alert>
)}
<CancelledWagonsSection rows={ownCancellations} />
<SimpleGrid cols={{ base: 1, md: 2 }} spacing={24}>
{wagons.map((w) => (
<WagonCard
key={w.allocationId ?? w.sequenceNo}
wagon={w}
selectable={
canSelect &&
!!w.allocationId &&
(w.status === "PLANNED" || w.status === "RESERVED")
}
selected={!!w.allocationId && selected.has(w.allocationId)}
onToggle={() => w.allocationId && toggle(w.allocationId)}
/>
))}
</SimpleGrid>
<Modal
opened={confirmOpen}
onClose={() => setConfirmOpen(false)}
title="Cancel selected wagons"
centered
>
<Stack gap="sm">
<Text fz={13.5} c="#475569">
You are cancelling <b>{selected.size}</b> wagon(s). They stay
allocated to you until the cancellation fee is paid; after that the
paid freight for them becomes a credit you can rebook on another
day while your contract is valid.
</Text>
{previewMutation.isPending && <Skeleton height={64} radius={10} />}
{preview && (
<Box
p={12}
style={{
borderRadius: 10,
backgroundColor: "#FFFBEB",
border: "1px solid #FDE68A",
}}
>
<Group justify="space-between">
<Text fz={13} c="#92400E">
Cancellation fee ({preview.wagons} × {Number(preview.feePerWagon).toLocaleString()})
</Text>
<Text fz={14} fw={800} c="#92400E">
{Number(preview.feeAmount).toLocaleString()} {preview.feeCurrency}
</Text>
</Group>
<Group justify="space-between" mt={4}>
<Text fz={13} c="#0A6F4D">
Rebooking credit kept
</Text>
<Text fz={14} fw={800} c="#0A6F4D">
{Number(preview.creditAmount).toLocaleString()}
</Text>
</Group>
</Box>
)}
<Textarea
label="Reason (optional)"
placeholder="Why are you cancelling these wagons?"
value={reason}
onChange={(e) => setReason(e.currentTarget.value)}
autosize
minRows={2}
/>
<Group justify="flex-end" gap="sm">
<Button variant="default" onClick={() => setConfirmOpen(false)}>
Keep wagons
</Button>
<Button
color="orange"
loading={requestMutation.isPending}
disabled={!preview}
onClick={() => requestMutation.mutate()}
>
Request cancellation
</Button>
</Group>
</Stack>
</Modal>
</div>
);
}

View File

@@ -85,7 +85,12 @@ export function ClearanceFlow({ booking, flow, footer }: ClearanceFlowProps) {
return (
<Stack gap={0}>
{isReady ? (
{status === "OPERATION_CHANGES_REQUESTED" ? (
<Alert color="yellow" radius="md" icon={<Clock size={18} />} mb="md">
Operations returned this order for changes. Review their note, pick a
new shipment day below and resubmit.
</Alert>
) : isReady ? (
<Alert color="teal" radius="md" icon={<CheckCircle2 size={18} />} mb="md">
{needsCompletion
? "Clearance is finalized. Complete your booking now — enter the cargo details and pick a shipment day inside an open booking window."

View File

@@ -89,6 +89,22 @@ function actionByStatus(booking: ActionBooking): BookingNextAction | null {
label: "Schedule & proceed",
title: "Schedule your shipment",
};
case "OPERATION_CHANGES_REQUESTED":
// Contract bookings reopen the full completion form (cargo + shipment
// day, prefilled from the booking) — same page as the initial booking.
// Contract-less bookings keep the in-place day-picker modal.
return booking.contractId
? {
kind: "BOOK",
label: "Change booking",
title: "Change your booking",
to: `/contracts/${booking.contractId}/bookings/${booking.id}/complete`,
}
: {
kind: "SCHEDULE_OPERATION",
label: "Choose day & resubmit",
title: "Resubmit your shipment",
};
default:
return null;
}

View File

@@ -98,7 +98,10 @@ export function useClearanceFlow(booking: Freight.IBooking) {
[clearance],
);
const isReady = status === "CLEARANCE_READY";
// OPERATION_CHANGES_REQUESTED re-opens the same pick-a-day flow: the
// customer resubmits via the same clearance/proceed endpoint.
const isReady =
status === "CLEARANCE_READY" || status === "OPERATION_CHANGES_REQUESTED";
// Bare initiated instance: created with no cargo and no price; completion
// (cargo + shipment day + window check) happens on the full booking form.
const isBareInstance =

View File

@@ -3,18 +3,22 @@ import { useState } from "react";
import { useInvoicePayment } from "@/hooks/useInvoicePayment";
import { type PaymentMethod } from "@/services/payments.service";
import { invoicesService } from "@/services/invoices.service";
import { invoicesService, type PortalInvoice } from "@/services/invoices.service";
import { isPayable } from "@/pages/billing/invoice-ui";
/** Fee invoice opened by a partial wagon cancellation (see WagonCancellationCard). */
export const WAGON_CANCEL_FEE_INVOICE_TYPE = "WAGON_CANCEL_FEE";
/**
* Shared payment flow for a single booking: opens the method modal, fires
* POST /billing/my-invoices/:id/pay for the booking's currently payable
* invoice, and redirects the browser to the provider (or, for CAC Bank, an
* OTP debit with no redirect, collects the SMS'd code in the modal). Reused by
* the booking detail page, the booking list, and the home page so "Pay now"
* behaves identically everywhere.
* Core of the booking payment flows: resolves the booking's invoices (shared
* query/key with BookingPaymentPanel, so they share that cache), picks the one
* matching `match`, and charges it through the ownership-checked portal route —
* redirect vs CAC Bank OTP handled by `useInvoicePayment`.
*/
export function useBookingPayment(bookingId: string) {
function useBookingInvoicePayment(
bookingId: string,
match: (invoice: PortalInvoice) => boolean,
) {
const [modalOpen, setModalOpen] = useState(false);
const [noInvoice, setNoInvoice] = useState(false);
@@ -22,7 +26,7 @@ export function useBookingPayment(bookingId: string) {
queryKey: ["booking-invoices", bookingId],
queryFn: () => invoicesService.listForSource("booking", bookingId),
});
const payableInvoiceId = invoices.find((inv) => isPayable(inv.status))?.id;
const payableInvoiceId = invoices.find(match)?.id;
const flow = useInvoicePayment();
@@ -56,3 +60,28 @@ export function useBookingPayment(bookingId: string) {
},
};
}
/**
* Shared payment flow for a single booking: opens the method modal, fires
* POST /billing/my-invoices/:id/pay for the booking's currently payable
* invoice, and redirects the browser to the provider (or, for CAC Bank, an
* OTP debit with no redirect, collects the SMS'd code in the modal). Reused by
* the booking detail page, the booking list, and the home page so "Pay now"
* behaves identically everywhere.
*/
export function useBookingPayment(bookingId: string) {
return useBookingInvoicePayment(bookingId, (inv) => isPayable(inv.status));
}
/**
* Same flow, but targets the booking's payable wagon-cancellation FEE invoice
* (type WAGON_CANCEL_FEE) — the freight invoice is already paid on these
* bookings, so the generic "first payable" pick would work today, but pinning
* the type keeps the two buttons from ever racing over the same invoice.
*/
export function useFeeInvoicePayment(bookingId: string) {
return useBookingInvoicePayment(
bookingId,
(inv) => inv.type === WAGON_CANCEL_FEE_INVOICE_TYPE && isPayable(inv.status),
);
}

View File

@@ -104,16 +104,29 @@ const COUNTDOWN_TEXT: Partial<
PRE_WINDOW: { label: "Booking opens in", expiredText: "Booking opening now…" },
OPEN: { label: "Window closes in", expiredText: "Document review starting…" },
DOC_REVIEW: { label: "Document review ends in", expiredText: "Payment starting…" },
PAYMENT: { label: "Payment due in", expiredText: "Payment window closing…" },
PAYMENT: { label: "Payment due in", expiredText: "Finalizing payments…" },
};
function phaseCountdown(
w: MyBookingWindow,
): { label: string; deadline: string; expiredText: string } | null {
function phaseCountdown(w: MyBookingWindow): {
label: string;
deadline: string;
expiredText: string;
graceDeadline?: string | null;
graceLabel?: string;
} | null {
const state = bookingWindowUiState(w);
const text = COUNTDOWN_TEXT[state.kind];
if (!state.countdownTo || !text) return null;
return { ...text, deadline: state.countdownTo };
// Once the pay deadline lapses, pending payments still settle during the
// drain tail — count it down as "processing" instead of a stale "closing".
const grace =
state.kind === "PAYMENT" && w.paymentDrainEndsAt
? {
graceDeadline: w.paymentDrainEndsAt,
graceLabel: "Payment processing — closes in",
}
: undefined;
return { ...text, deadline: state.countdownTo, ...grace };
}
/**
@@ -226,6 +239,8 @@ function WindowCard({ w }: { w: MyBookingWindow }) {
deadline={cd.deadline}
label={cd.label}
expiredText={cd.expiredText}
graceDeadline={cd.graceDeadline}
graceLabel={cd.graceLabel}
size="xs"
/>
</Box>

View File

@@ -38,6 +38,7 @@ import {
CheckCircle2,
ChevronLeft,
FileDown,
FileText,
FileUp,
Flame,
MapPin,
@@ -59,6 +60,7 @@ import {
contractsService,
type ShipmentValidation,
} from "@/services/contracts.service";
import { downloadStoredFile } from "@/services/files.service";
import {
SelectField,
StepCard,
@@ -245,6 +247,127 @@ function bulkUnitOfMeasure(
return hasPerItem ? "PER_ITEM" : "PER_TON";
}
/**
* Prefill for a changes-requested resubmit: the booking's persisted cargo,
* currency and route become the form's starting values so the customer edits
* what exists instead of retyping it. The shipment day is deliberately left
* empty — a new day must be picked.
*/
function mapBookingToShipmentValues(
booking: Freight.IBooking,
contract: Freight.IContract,
): Partial<ShipmentFormInputValues> {
const b = booking as unknown as {
cargoFreeText?: string | null;
contractRouteId?: string | null;
cargoTotalWeightVgm?: number | string | null;
bulkTotalWeightTons?: number | string | null;
bulkHazardousQuantity?: number | string | null;
bulkReeferQuantity?: number | string | null;
bookingContainers?: Array<{
quantity?: number;
hazardousQuantity?: number | string | null;
reeferQuantity?: number | string | null;
returnQuantity?: number | string | null;
containerType?: { sizeFt?: number | null } | null;
units?: Array<{
containerNumber?: string;
sealNumber?: string | null;
vgmTons?: number | string;
isHazardous?: boolean;
isReefer?: boolean;
isReturn?: boolean;
}>;
}>;
};
const values: Partial<ShipmentFormInputValues> = {
paymentCurrency: booking.paymentCurrency === "ETB" ? "ETB" : "USD",
withReturn: booking.equipmentReturn === "WITH_RETURN",
cargoDescription: b.cargoFreeText ?? "",
...(b.contractRouteId ? { contractRouteId: b.contractRouteId } : {}),
};
if (contract.freightType === "CONTAINER") {
const rows = b.bookingContainers ?? [];
const lineFor = (size: "20ft" | "40ft") => {
const bc = rows.find(
(r) => (r.containerType?.sizeFt === 40 ? "40ft" : "20ft") === size,
);
return {
containerSize: size,
quantity: String(bc?.quantity ?? 0),
hazardousQuantity: String(Number(bc?.hazardousQuantity ?? 0)),
reeferQuantity: String(Number(bc?.reeferQuantity ?? 0)),
returnQuantity: String(Number(bc?.returnQuantity ?? 0)),
units: (bc?.units ?? []).map((u) => ({
containerNumber: u.containerNumber ?? "",
sealNumber: u.sealNumber ?? "",
vgmTons: String(Number(u.vgmTons ?? 0)),
isHazardous: Boolean(u.isHazardous),
isReefer: Boolean(u.isReefer),
isReturn: Boolean(u.isReturn),
})),
};
};
const sizes = (contract.cargoScope ?? [])
.map((s) => s.containerSize)
.filter((s): s is "20ft" | "40ft" => s === "20ft" || s === "40ft");
values.containers = (sizes.length ? sizes : (["20ft", "40ft"] as const)).map(lineFor);
} else {
const perItem = bulkUnitOfMeasure(contract) === "PER_ITEM";
const amount = Number(b.cargoTotalWeightVgm ?? 0);
if (perItem) {
values.itemCount = amount ? String(amount) : "";
values.cargoWeightTons =
b.bulkTotalWeightTons != null
? String(Number(b.bulkTotalWeightTons))
: "";
} else {
values.cargoWeightTons = amount ? String(amount) : "";
}
values.bulkHazardousQuantity = String(Number(b.bulkHazardousQuantity ?? 0));
values.bulkReeferQuantity = String(Number(b.bulkReeferQuantity ?? 0));
}
return values;
}
/** Read-only list of the booking's already-uploaded documents (resubmit view). */
function UploadedDocumentsCard({ booking }: { booking: Freight.IBooking }) {
const files =
(booking as unknown as { files?: Array<{ id: string; name: string }> })
.files ?? [];
if (!files.length) return null;
return (
<Paper withBorder radius="lg" p="lg">
<Group gap={8} mb={4}>
<FileText size={16} />
<Text fw={700} fz="sm">
Your uploaded documents
</Text>
</Group>
<Text fz={12.5} c="dimmed" mb="sm">
These stay attached to the booking no need to upload them again.
</Text>
<Stack gap={6}>
{files.map((f) => (
<Group key={f.id} justify="space-between" wrap="nowrap">
<Text fz={13} truncate>
{f.name}
</Text>
<ActionIcon
variant="default"
radius="md"
onClick={() => void downloadStoredFile(f.id, f.name)}
aria-label={`Download ${f.name}`}
>
<FileDown size={15} />
</ActionIcon>
</Group>
))}
</Stack>
</Paper>
);
}
function NewShipmentBookingForm({
contract,
contractId,
@@ -284,6 +407,10 @@ function NewShipmentBookingForm({
unitOfMeasure: bulkUnitOfMeasure(contract),
// Intercity rides a passing train staff pick later — no date to choose.
requiresDate: contract.tradeDirection !== "DOMESTIC",
// Export completion locks onto a specific train — the pick is required
// (mirrors the ScheduleStep picker's visibility).
requiresTrain:
contract.tradeDirection === "EXPORT" && Boolean(completeBookingId),
}),
),
mode: "onChange",
@@ -302,6 +429,34 @@ function NewShipmentBookingForm({
: 0;
const hasOdd20ft = ft20Total % 2 === 1;
// COMPLETION mode: fetch the booking — a changes-requested resubmit prefills
// the form from it and shows the operations note + uploaded documents.
const { data: completeBooking } = useQuery(
api.bookings.get.queryOptions({
input: { id: completeBookingId! },
enabled: Boolean(completeBookingId),
}),
);
const isResubmit = Boolean(
completeBooking &&
["OPERATION_CHANGES_REQUESTED", "EXPIRED"].includes(
completeBooking.status as string,
) &&
(((completeBooking as unknown as { bookingContainers?: unknown[] })
.bookingContainers?.length ?? 0) > 0 ||
Number(completeBooking.cargoTotalWeightVgm ?? 0) > 0),
);
const prefilledRef = useRef(false);
useEffect(() => {
if (!isResubmit || prefilledRef.current || !completeBooking) return;
prefilledRef.current = true;
form.reset({
...form.getValues(),
...mapBookingToShipmentValues(completeBooking, contract),
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isResubmit]);
const submitMutation = useMutation({
mutationFn: (dto: Freight.CreateBookingUnderContractDto) =>
completeBookingId
@@ -328,7 +483,12 @@ function NewShipmentBookingForm({
// price modal opens so re-reviewing after an edit re-checks.
const validateMutation = useMutation({
mutationFn: (dto: Freight.CreateBookingUnderContractDto) =>
api.contracts.validateShipment.call({ id: contractId, dto }),
api.contracts.validateShipment.call({
id: contractId,
dto,
// Resubmit preview must not clash with this booking's own containers.
excludeBookingId: completeBookingId,
}),
});
function buildDto(
@@ -484,12 +644,16 @@ function NewShipmentBookingForm({
style={{ letterSpacing: "-0.01em" }}
>
{completeBookingId
? "Complete Your Booking"
? isResubmit
? "Change Your Booking"
: "Complete Your Booking"
: "New Shipment Booking"}
</Title>
<Text size="sm" c="edr-muted" mt={4}>
{completeBookingId
? `Clearance is finalized — enter the cargo details and shipment day to complete your booking under contract ${contract.reference}.`
? isResubmit
? `Update the details below and pick a new shipment day, then resubmit your booking under contract ${contract.reference}.`
: `Clearance is finalized — enter the cargo details and shipment day to complete your booking under contract ${contract.reference}.`
: `Book a shipment against contract ${contract.reference}.`}
</Text>
</Box>
@@ -531,6 +695,16 @@ function NewShipmentBookingForm({
{/* Single-step form — all sections on one page. */}
<Stack gap="lg" className="mx-auto max-w-4xl">
{isResubmit && completeBooking?.latestChangeRequestNote && (
<Alert
color="yellow"
icon={<AlertCircle size={16} />}
radius="md"
title="Operations requested changes"
>
<Text size="sm">{completeBooking.latestChangeRequestNote}</Text>
</Alert>
)}
<RouteStep form={form} contract={contract} routes={routes} />
<CargoStep form={form} contract={contract} />
{/* Legacy contracts only — WITH_RETURN contracts capture per-line
@@ -543,6 +717,9 @@ function NewShipmentBookingForm({
routes={routes}
completeBookingId={completeBookingId ?? null}
/>
{isResubmit && completeBooking && (
<UploadedDocumentsCard booking={completeBooking} />
)}
{/* Notes are captured when the booking is initiated — completing
a bare booking does not re-ask for them. */}
{!completeBookingId && <NotesSection form={form} />}
@@ -590,7 +767,7 @@ function NewShipmentBookingForm({
onClick={handleReview}
disabled={hasOdd20ft}
>
Review price &amp; book
{isResubmit ? "Change booking" : "Review price & book"}
</Button>
</Box>
</Tooltip>
@@ -1179,12 +1356,23 @@ function ScheduleStep({
</Text>
)}
{isExportPick && scheduledDate ? (
<ExportTrainPicker
options={exportTrainsQuery.data ?? []}
loading={exportTrainsQuery.isLoading}
value={selectedTrainId ?? ""}
onChange={(id) => form.setValue("trainScheduleId", id)}
/>
<>
<ExportTrainPicker
options={exportTrainsQuery.data ?? []}
loading={exportTrainsQuery.isLoading}
value={selectedTrainId ?? ""}
onChange={(id) =>
form.setValue("trainScheduleId", id, {
shouldValidate: true,
})
}
/>
{form.formState.errors.trainScheduleId?.message && (
<Text fz="xs" c="red" mt={6}>
{String(form.formState.errors.trainScheduleId.message)}
</Text>
)}
</>
) : null}
</Box>
)}

View File

@@ -30,6 +30,11 @@ export interface ShipmentValidationContext {
* staff pick later, so no shipment day is chosen. Defaults to true.
*/
requiresDate?: boolean;
/**
* EXPORT rail completion: the shipment must ride a specific train the
* customer picks for the chosen day. Defaults to false.
*/
requiresTrain?: boolean;
}
// ISO 6346: 3-letter owner code + category id (U/J/Z) + 6-digit serial + check digit.
@@ -102,6 +107,20 @@ export function createShipmentFormSchema(ctx: ShipmentValidationContext) {
});
}
// Train is only pickable once a day is chosen — the day error covers the
// no-date case, so don't stack a second error on an invisible field.
if (
ctx.requiresTrain &&
data.scheduledDate.trim() &&
!data.trainScheduleId.trim()
) {
refineCtx.addIssue({
code: "custom",
path: ["trainScheduleId"],
message: "Select a train for your shipment day.",
});
}
// No default currency — the customer must pick one before submitting.
if (!data.paymentCurrency) {
refineCtx.addIssue({

View File

@@ -0,0 +1,52 @@
import { describe, expect, it } from "vitest";
import { createShipmentFormSchema, initialShipmentFormValues } from "./schema";
const schema = createShipmentFormSchema({
isContainer: false,
isHazardous: false,
isReefer: false,
requiresTrain: true,
});
const values = (over: Record<string, unknown> = {}) => ({
...initialShipmentFormValues,
cargoWeightTons: "10",
paymentCurrency: "USD",
scheduledDate: "2026-08-10",
...over,
});
const trainIssue = (input: Record<string, unknown>) => {
const result = schema.safeParse(input);
return result.success
? undefined
: result.error.issues.find((i) => i.path[0] === "trainScheduleId");
};
describe("requiresTrain", () => {
it("rejects a dated export completion without a train pick", () => {
expect(trainIssue(values())?.message).toMatch(/select a train/i);
});
it("passes once a train is picked", () => {
expect(trainIssue(values({ trainScheduleId: "sched-1" }))).toBeUndefined();
});
it("stays silent while no date is chosen (day error covers it)", () => {
expect(trainIssue(values({ scheduledDate: "" }))).toBeUndefined();
});
it("is off by default (non-completion flows)", () => {
const plain = createShipmentFormSchema({
isContainer: false,
isHazardous: false,
isReefer: false,
});
const result = plain.safeParse(values());
expect(
result.success ||
result.error.issues.every((i) => i.path[0] !== "trainScheduleId"),
).toBe(true);
});
});

View File

@@ -1,4 +1,4 @@
import { isValidPhone, toEthiopianE164 } from "@/components/PhoneField";
import { ControlledPhoneField, isValidPhone } from "@/components/PhoneField";
import { api } from "@/services/api";
import type {
CompanyProfileInput,
@@ -30,6 +30,12 @@ import FaydaVerifyPanel from "@/components/FaydaVerifyPanel";
import ETradeInfo, { type ETradeStatus } from "@/components/onboarding/ETradeInfo";
import { ReadOnlyField } from "@/pages/accounts/companyProfileForm/ReadOnlyField";
import StepSection from "@/pages/accounts/companyProfileForm/StepSection";
import { ETRADE_BUNDLE_FIELDS as SHARED_ETRADE_FIELDS } from "@/pages/accounts/companyProfileForm/schema";
import {
firstValidEmail,
firstValidPhone,
normalizeIdentityPhones,
} from "@/pages/accounts/companyProfileForm/helpers";
export const COMPANY_PROFILE_SCHEMA = z.object({
companyName: z.string().min(1, "Company name is required"),
@@ -43,12 +49,12 @@ export const COMPANY_PROFILE_SCHEMA = z.object({
// no standalone input.
companyAddress: z.string().optional(),
tinNumber: z.string().regex(/^\d{10}$/, "TIN must be exactly 10 digits"),
// Same rule as onboarding — the two forms write the same column, so they must
// not disagree about what is acceptable in it.
vatNumber: z
.string()
.trim()
.max(20, "VAT number is too long")
.optional()
.or(z.literal("")),
.min(1, "VAT number is required")
.regex(/^\d{10}$/, "VAT number must be exactly 10 digits"),
ownerPassportNumber: z.string().optional(),
// Registration/address fields are eTrade-sourced — locked once eTrade
// supplies a value, editable only as an escape hatch when it doesn't
@@ -72,21 +78,13 @@ export const COMPANY_PROFILE_SCHEMA = z.object({
export type CompanyProfileFormData = z.infer<typeof COMPANY_PROFILE_SCHEMA>;
/** UpdateProfilePayload keys eTrade owns — only resent when the customer re-verified them this session. */
const ETRADE_BUNDLE_FIELDS = [
"companyName",
"licenceNumber",
"statusDescription",
"dateRegistered",
"renewedFrom",
"renewalDate",
"renewedTo",
"region",
"zone",
"woreda",
"kebele",
"houseNo",
] as const satisfies readonly (keyof CompanyProfileFormData)[];
/**
* `etradePhone` is not on this form, so the shared list is filtered down to the
* keys it actually holds. Source of truth: `companyProfileForm/schema.ts`.
*/
const ETRADE_FIELDS = SHARED_ETRADE_FIELDS.filter(
(k): k is Exclude<typeof k, "etradePhone"> => k !== "etradePhone",
);
interface TabCompanyProfileProps {
profile?: ProfileResponse;
@@ -166,32 +164,39 @@ export default function TabCompanyProfile({
values: defaultValues,
});
const identity = profile?.identity;
// Fayda stores the phone as the national registry holds it (often a local
// number), which neither this form's E.164 validation nor the API's
// `@IsValidPhone()` accepts. Normalize on read — same as the wizard.
const identity = useMemo(
() => normalizeIdentityPhones(profile?.identity),
[profile?.identity],
);
const verifiedIdentity = identity?.faydaRequired === true;
// companyEmail/companyPhone are the owner's verified contact details, never
// typed — same derivation as the onboarding wizard, just fed from the saved
// profile instead of an in-progress form.
useEffect(() => {
if (!user) return;
setValue("companyEmail", identity?.owner.email ?? user.email ?? "", {
shouldValidate: true,
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [identity?.owner.email, user?.email]);
// profile instead of an in-progress form. `firstValid*` rather than `??`:
// these claims are optional AND unreliable — eTrade's registered phone is
// free text that arrives as things like "09 " — and `??` stops at the
// first non-null, so junk became a read-only field the customer could not
// fix and a 400 on save. When nothing usable can be derived the fields below
// become editable instead of blocking.
const derivedEmail = firstValidEmail(identity?.owner.email, user?.email);
const derivedPhone = firstValidPhone(
identity?.owner.phone,
profile?.etradePhone,
user?.phoneNumber,
);
useEffect(() => {
if (!user) return;
setValue(
"companyPhone",
identity?.owner.phone ??
profile?.etradePhone ??
toEthiopianE164(user.phoneNumber) ??
"",
{ shouldValidate: true },
);
if (derivedEmail) setValue("companyEmail", derivedEmail);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [identity?.owner.phone, profile?.etradePhone, user?.phoneNumber]);
}, [derivedEmail]);
useEffect(() => {
if (derivedPhone) setValue("companyPhone", derivedPhone);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [derivedPhone]);
// companyAddress is composed from the (locked) eTrade address parts, not
// typed directly.
@@ -249,7 +254,7 @@ export default function TabCompanyProfile({
// on every save would otherwise trigger the server's eTrade
// authenticity re-check for no reason.
const etradeBundle: Record<string, string | undefined> = {};
for (const key of ETRADE_BUNDLE_FIELDS) {
for (const key of ETRADE_FIELDS) {
if (dirtyFields[key]) etradeBundle[key] = data[key];
}
if (dirtyFields.tinNumber) etradeBundle.tin = data.tinNumber;
@@ -296,13 +301,32 @@ export default function TabCompanyProfile({
});
const onSubmit = (data: CompanyProfileFormData) => {
setValidationError(null);
if (isCreate && selectedRoles.length === 0) return;
mutation.mutate(data);
};
const saveErrorMessage = mutation.isError
? extractApiError(mutation.error).message
: null;
/**
* Without this, a failed validation made "Save Changes" a no-op: the fields
* the schema requires are largely eTrade-sourced and rendered read-only, so
* their error messages had nowhere to appear and the button simply did
* nothing. Name them instead.
*/
const [validationError, setValidationError] = useState<string | null>(null);
const onInvalid = (formErrors: typeof errors) => {
const messages = Object.values(formErrors)
.map((e) => e?.message)
.filter((m): m is string => Boolean(m));
setValidationError(
messages.length > 0
? `Please fix: ${[...new Set(messages)].join(", ")}.`
: "Some details are incomplete. Please review the fields above.",
);
};
const saveErrorMessage =
validationError ??
(mutation.isError ? extractApiError(mutation.error).message : null);
const pendingOwnerReview = Boolean(
(profile?.pendingChanges as { faydaIdentity?: Record<string, unknown> } | null)
@@ -333,7 +357,7 @@ export default function TabCompanyProfile({
: "Your registration and identity come from eTrade and Fayda — re-verify to refresh them."}
</Text>
<form onSubmit={handleSubmit(onSubmit)}>
<form onSubmit={handleSubmit(onSubmit, onInvalid)}>
<Stack gap="xl">
<StepSection
index={1}
@@ -341,9 +365,9 @@ export default function TabCompanyProfile({
status={watch("vatNumber") ? "done" : "todo"}
>
<TextInput
label="VAT Number (optional)"
label="VAT Number"
placeholder="e.g. 0012345678"
maxLength={20}
maxLength={10}
error={errors.vatNumber?.message}
{...register("vatNumber")}
/>
@@ -389,9 +413,33 @@ export default function TabCompanyProfile({
{...register("ownerPassportNumber")}
/>
)}
{/* Read-only while the verified owner (or eTrade, or the account)
supplies them. Fayda's email/phone claims are optional, so
when nothing can be derived these become typeable — the API
requires both, and showing an empty read-only field is a save
that can never succeed. */}
<SimpleGrid cols={2} spacing="md">
<ReadOnlyField label="Company email" value={watch("companyEmail")} />
<ReadOnlyField label="Company phone" value={watch("companyPhone")} />
{derivedEmail ? (
<ReadOnlyField label="Company email" value={derivedEmail} />
) : (
<TextInput
label="Company Email"
type="email"
description="We couldn't find one on your verified identity or account — please enter it."
error={errors.companyEmail?.message}
{...register("companyEmail")}
/>
)}
{derivedPhone ? (
<ReadOnlyField label="Company phone" value={derivedPhone} />
) : (
<ControlledPhoneField
control={control}
name="companyPhone"
label="Company Phone"
required
/>
)}
</SimpleGrid>
</StepSection>
)}
@@ -410,6 +458,7 @@ export default function TabCompanyProfile({
error={errors.tinNumber?.message}
onDataLoaded={handleETradeDataLoaded}
onStatusChange={setTinStatus}
alreadyVerified={hasRegistrationDetails}
/>
{tinVerified && (
<EtradeLockedCard
@@ -520,7 +569,9 @@ function EtradeLockedCard({
<ReadOnlyField label="Renewal Date" value={watch("renewalDate")} />
<ReadOnlyField label="Renewed From" value={watch("renewedFrom")} />
<ReadOnlyField label="Renewed To" value={watch("renewedTo")} />
{region?.trim() ? (
{/* Membership of the catalog, not mere presence — a stored spelling
outside the list is otherwise uncorrectable. */}
{(ETHIOPIAN_REGIONS as readonly string[]).includes(region ?? "") ? (
<ReadOnlyField label="Region" value={region} />
) : (
<RegionSelect control={control} error={errors.region?.message} />
@@ -548,7 +599,9 @@ function LockedField({
errors: ReturnType<typeof useForm<CompanyProfileFormData>>["formState"]["errors"];
}) {
const value = watch(name) as string | undefined;
if (value?.trim()) {
// A value that fails validation unlocks too — rendering a rejected value
// read-only is a save that can never succeed and never says why.
if (value?.trim() && !errors[name]) {
return <ReadOnlyField label={label} value={value} />;
}
return (

View File

@@ -0,0 +1,122 @@
import { ArrowLeft, Train } from "lucide-react";
import type { ReactNode } from "react";
import { Link } from "react-router-dom";
import type { Section } from "./content";
/** Public pages reachable from every doc page's header and footer. */
const DOC_LINKS = [
{ to: "/help", label: "Help & Support" },
{ to: "/faq", label: "FAQ" },
{ to: "/privacy", label: "Privacy Policy" },
{ to: "/terms", label: "Terms of Service" },
];
interface DocShellProps {
title: string;
subtitle: string;
/** Rendered under the title, e.g. "Last updated 6 August 2026". */
meta?: string;
/** Path of the current page, so it is not linked to itself. */
current: string;
children: ReactNode;
}
/**
* Chrome shared by the help, FAQ and legal pages. These routes are public —
* the auth screens link to them before a session exists — so the shell carries
* its own header instead of relying on the authenticated app layout.
*/
export function DocShell({
title,
subtitle,
meta,
current,
children,
}: DocShellProps) {
return (
<div className="min-h-screen bg-background text-foreground">
<header className="sticky top-0 z-50 border-b border-border bg-background/80 backdrop-blur-xl">
<div className="mx-auto flex max-w-4xl items-center justify-between gap-4 px-6 py-4">
<Link to="/" className="flex items-center gap-3">
<div className="flex size-10 items-center justify-center rounded-2xl bg-primary text-primary-foreground">
<Train className="size-5" />
</div>
<span className="font-bold">EDR Freight</span>
</Link>
<Link
to="/portal"
className="inline-flex items-center gap-2 rounded-2xl border border-border px-4 py-2 text-sm font-semibold transition hover:bg-accent"
>
<ArrowLeft className="size-4" />
Back to portal
</Link>
</div>
</header>
<main className="mx-auto max-w-4xl px-6 py-12">
<h1 className="text-4xl font-black tracking-tight">{title}</h1>
<p className="mt-4 text-lg leading-8 text-muted-foreground">
{subtitle}
</p>
{meta && (
<p className="mt-2 text-sm text-muted-foreground">{meta}</p>
)}
<div className="mt-10">{children}</div>
</main>
<footer className="border-t border-border py-8">
<div className="mx-auto flex max-w-4xl flex-col items-center justify-between gap-4 px-6 text-sm text-muted-foreground md:flex-row">
<span>© 2026 EDR Freight. All rights reserved.</span>
<nav className="flex flex-wrap items-center justify-center gap-x-6 gap-y-2">
{DOC_LINKS.filter((l) => l.to !== current).map((link) => (
<Link
key={link.to}
to={link.to}
className="font-semibold text-foreground transition-colors hover:text-primary"
>
{link.label}
</Link>
))}
</nav>
</div>
</footer>
</div>
);
}
/** Renders a legal document's numbered sections. */
export function DocSections({ sections }: { sections: Section[] }) {
return (
<div className="space-y-10">
{sections.map((section) => (
<section key={section.heading}>
<h2 className="text-xl font-bold tracking-tight">
{section.heading}
</h2>
{section.body?.map((paragraph) => (
<p
key={paragraph}
className="mt-4 leading-7 text-muted-foreground"
>
{paragraph}
</p>
))}
{section.bullets && (
<ul className="mt-4 list-disc space-y-2 pl-5 leading-7 text-muted-foreground">
{section.bullets.map((bullet) => (
<li key={bullet}>{bullet}</li>
))}
</ul>
)}
</section>
))}
</div>
);
}
export default DocShell;

View File

@@ -0,0 +1,59 @@
import { ChevronDown } from "lucide-react";
import { Link } from "react-router-dom";
import { DocShell } from "./DocShell";
import { FAQ_GROUPS, SUPPORT_CONTACT } from "./content";
export default function FaqPage() {
return (
<DocShell
current="/faq"
title="Frequently Asked Questions"
subtitle="Answers to the questions customers ask most about registering, booking cargo and settling invoices on EDR Freight."
>
<div className="space-y-10">
{FAQ_GROUPS.map((group) => (
<section key={group.title}>
<h2 className="text-xl font-bold tracking-tight">{group.title}</h2>
<div className="mt-4 space-y-3">
{group.items.map((item) => (
// Native disclosure: keyboard- and screen-reader-accessible
// without any state of our own.
<details
key={item.question}
className="group rounded-2xl border border-border bg-card px-5 py-4 transition hover:border-primary/40"
>
<summary className="flex cursor-pointer list-none items-center justify-between gap-4 font-semibold">
{item.question}
<ChevronDown className="size-5 shrink-0 text-muted-foreground transition-transform group-open:rotate-180" />
</summary>
<p className="mt-3 leading-7 text-muted-foreground">
{item.answer}
</p>
</details>
))}
</div>
</section>
))}
</div>
<div className="mt-12 rounded-[32px] border border-border bg-card p-8">
<h2 className="text-xl font-bold tracking-tight">
Still need a hand?
</h2>
<p className="mt-2 leading-7 text-muted-foreground">
Our team is on {SUPPORT_CONTACT.email} and {SUPPORT_CONTACT.phone}, or
you can start a chat from the support button inside the portal.
</p>
<Link
to="/help"
className="mt-6 inline-flex rounded-2xl bg-primary px-6 py-3 font-semibold text-primary-foreground transition hover:opacity-90"
>
Go to Help &amp; Support
</Link>
</div>
</DocShell>
);
}

View File

@@ -0,0 +1,183 @@
import {
Clock3,
FileText,
HelpCircle,
Mail,
MapPin,
MessageSquare,
Package,
Phone,
Receipt,
ShieldCheck,
} from "lucide-react";
import { Link } from "react-router-dom";
import { DocShell } from "./DocShell";
import { SUPPORT_CONTACT } from "./content";
const channels = [
{
icon: Mail,
title: "Email",
value: SUPPORT_CONTACT.email,
href: `mailto:${SUPPORT_CONTACT.email}`,
note: "Best for document issues and anything needing an attachment.",
},
{
icon: Phone,
title: "Phone",
value: SUPPORT_CONTACT.phone,
href: `tel:${SUPPORT_CONTACT.phone.replace(/\s/g, "")}`,
note: "Best for urgent problems with cargo already in transit.",
},
{
icon: MapPin,
title: "Head office",
value: SUPPORT_CONTACT.office,
note: "Walk-in support during working hours.",
},
{
icon: Clock3,
title: "Support hours",
value: SUPPORT_CONTACT.hours,
note: "Outside these hours, email us and we reply the next working day.",
},
];
const topics = [
{
icon: ShieldCheck,
title: "Account & onboarding",
body: "Registering your company, uploading your trade licence and TIN, and getting an operational profile approved.",
},
{
icon: FileText,
title: "Contracts",
body: "Requesting a freight contract, reviewing its terms and signing it with your saved signature and stamp.",
},
{
icon: Package,
title: "Bookings & tracking",
body: "Raising a booking against a contract, adding last-mile transport and following the consignment along the corridor.",
},
{
icon: Receipt,
title: "Invoices & payments",
body: "Finding invoices, paying through the bank channels and confirming a payment that has not yet settled.",
},
];
export default function HelpPage() {
return (
<DocShell
current="/help"
title="Help & Support"
subtitle="Get answers fast — browse the common topics, check the FAQ, or reach our team directly."
>
{/* Live chat is the fastest route, so lead with it. */}
<div className="rounded-[32px] border border-border bg-card p-8">
<div className="flex items-start gap-4">
<div className="rounded-2xl bg-accent p-3 text-primary">
<MessageSquare className="size-5" />
</div>
<div>
<h2 className="text-xl font-bold tracking-tight">
Chat with our team
</h2>
<p className="mt-2 leading-7 text-muted-foreground">
Signed-in customers can open a support conversation from the
headset button at the bottom right of every portal page. You can
send screenshots and documents in the chat, and replies appear
there and as a notification.
</p>
<Link
to="/portal"
className="mt-6 inline-flex rounded-2xl bg-primary px-6 py-3 font-semibold text-primary-foreground transition hover:opacity-90"
>
Open the portal
</Link>
</div>
</div>
</div>
<section className="mt-12">
<h2 className="text-xl font-bold tracking-tight">Contact us</h2>
<div className="mt-4 grid gap-4 sm:grid-cols-2">
{channels.map((channel) => (
<div
key={channel.title}
className="flex items-start gap-4 rounded-2xl border border-border bg-background p-5"
>
<div className="rounded-2xl bg-accent p-3 text-primary">
<channel.icon className="size-5" />
</div>
<div>
<p className="font-semibold">{channel.title}</p>
{channel.href ? (
<a
href={channel.href}
className="text-muted-foreground transition-colors hover:text-primary"
>
{channel.value}
</a>
) : (
<p className="text-muted-foreground">{channel.value}</p>
)}
<p className="mt-1 text-sm text-muted-foreground">
{channel.note}
</p>
</div>
</div>
))}
</div>
</section>
<section className="mt-12">
<h2 className="text-xl font-bold tracking-tight">Common topics</h2>
<div className="mt-4 grid gap-4 sm:grid-cols-2">
{topics.map((topic) => (
<Link
key={topic.title}
to="/faq"
className="rounded-2xl border border-border bg-background p-5 transition hover:border-primary/40"
>
<div className="inline-flex rounded-2xl bg-accent p-3 text-primary">
<topic.icon className="size-5" />
</div>
<p className="mt-4 font-semibold">{topic.title}</p>
<p className="mt-1 leading-7 text-muted-foreground">
{topic.body}
</p>
</Link>
))}
</div>
</section>
<section className="mt-12 rounded-[32px] border border-border bg-card p-8">
<div className="flex items-start gap-4">
<div className="rounded-2xl bg-accent p-3 text-primary">
<HelpCircle className="size-5" />
</div>
<div>
<h2 className="text-xl font-bold tracking-tight">
What to include when you contact us
</h2>
<ul className="mt-3 list-disc space-y-2 pl-5 leading-7 text-muted-foreground">
<li>Your company name and the email you sign in with.</li>
<li>
The reference of the contract, booking or invoice involved.
</li>
<li>What you expected to happen and what happened instead.</li>
<li>A screenshot of any error message the portal showed.</li>
</ul>
</div>
</div>
</section>
</DocShell>
);
}

View File

@@ -0,0 +1,15 @@
import { DocSections, DocShell } from "./DocShell";
import { LEGAL_LAST_UPDATED, PRIVACY_SECTIONS } from "./content";
export default function PrivacyPolicyPage() {
return (
<DocShell
current="/privacy"
title="Privacy Policy"
subtitle="How EDR Freight collects, uses, shares and protects the information you provide when you use the platform."
meta={`Last updated ${LEGAL_LAST_UPDATED}`}
>
<DocSections sections={PRIVACY_SECTIONS} />
</DocShell>
);
}

View File

@@ -0,0 +1,15 @@
import { DocSections, DocShell } from "./DocShell";
import { LEGAL_LAST_UPDATED, TERMS_SECTIONS } from "./content";
export default function TermsPage() {
return (
<DocShell
current="/terms"
title="Terms of Service"
subtitle="The terms on which EDR provides the EDR Freight platform and the freight services you request through it."
meta={`Last updated ${LEGAL_LAST_UPDATED}`}
>
<DocSections sections={TERMS_SECTIONS} />
</DocShell>
);
}

View File

@@ -0,0 +1,358 @@
/**
* Copy for the public help/FAQ/legal pages. Kept as data so the pages stay
* thin — the shell in `DocShell.tsx` renders any `Section[]` the same way.
*
* The privacy and terms text is the platform's working draft; legal counsel
* signs off on the final wording, and `LEGAL_LAST_UPDATED` is bumped with it.
*/
export const SUPPORT_CONTACT = {
email: "support@edrfreight.com",
phone: "+251 11 000 0000",
office: "Addis Ababa, Ethiopia",
hours: "Monday Saturday, 8:30 AM 5:30 PM (EAT)",
};
export const LEGAL_LAST_UPDATED = "6 August 2026";
export interface Section {
heading: string;
/** Paragraphs, rendered in order. */
body?: string[];
/** Optional bullet list, rendered after the paragraphs. */
bullets?: string[];
}
export interface FaqItem {
question: string;
answer: string;
}
export interface FaqGroup {
title: string;
items: FaqItem[];
}
export const FAQ_GROUPS: FaqGroup[] = [
{
title: "Getting started",
items: [
{
question: "How do I open an account on EDR Freight?",
answer:
"Sign up with your work email and verify the one-time code we send you. After you set a password, the onboarding wizard collects your company details, trade licence, TIN certificate and the operational services you need (importer, exporter, freight forwarder or transporter). Submit the wizard and our team reviews the application.",
},
{
question: "How long does account approval take?",
answer:
"Most complete applications are reviewed within two working days. You will see the status on your dashboard, and we email you when a profile is approved or when a document needs to be re-uploaded.",
},
{
question: "My profile was rejected. What now?",
answer:
"The rejection notice states the reason. Open Settings, correct the details or replace the document that was flagged, and re-apply — you do not need to create a new account.",
},
{
question: "Can one company hold several operational services?",
answer:
"Yes. A company can hold importer, exporter, freight forwarder and transporter profiles at the same time. Each is approved separately, and the header lets you switch between the ones you hold.",
},
],
},
{
title: "Contracts and bookings",
items: [
{
question: "What is the difference between a contract and a booking?",
answer:
"A contract is the commercial agreement covering a cargo movement — route, commodity, volume and rates. A booking is a single shipment executed under that contract. You create the contract once, then raise bookings against it for each consignment.",
},
{
question: "How do I create a booking?",
answer:
"Open the contract from the Contracts list and choose New Booking. Provide the consignment details, containers or tonnage, and the last-mile requirement if you need one. Bookings can also be started from the Bookings page, which routes you through contract selection first.",
},
{
question: "Why do I have to sign a contract before shipping?",
answer:
"The contract document is the binding agreement for the movement. You must scroll to the end, accept the terms, and sign it with your saved signature and stamp before EDR schedules any wagon against it.",
},
{
question: "Where do I set up my signature and stamp?",
answer:
"Under Signature & Stamp in the portal. It is saved once and reused for every contract you sign, so you do not have to upload it per document.",
},
{
question: "Can I change a booking after submitting it?",
answer:
"You can edit a booking while it is still pending review. Once EDR has confirmed it and allocated capacity, changes go through our operations team — contact support with the booking reference.",
},
{
question: "How do I track a consignment?",
answer:
"Open the booking and use the tracking panel, which shows the current milestone, the wagon or container assigned, and the timestamps recorded at each corridor point.",
},
],
},
{
title: "Invoices and payments",
items: [
{
question: "Where do I find my invoices?",
answer:
"The Invoices page lists every invoice raised against your company, with its status, due date and outstanding balance. Open any invoice to see its line items and download a PDF copy.",
},
{
question: "Which payment methods are supported?",
answer:
"Payments are made through the integrated bank channels shown at checkout. After you complete the payment on the bank's page you are returned to the portal, and the invoice status updates once the bank confirms the transaction.",
},
{
question: "My payment was deducted but the invoice still shows unpaid.",
answer:
"Bank confirmations can lag by a few minutes. Use the Check Payment Status page linked from your receipt; if it still has not settled after an hour, email support with the invoice number and the bank reference and we will reconcile it.",
},
{
question: "Why is my invoice amount rounded?",
answer:
"Some bank channels only accept whole-birr amounts, so invoices routed through them are rounded up to the nearest birr. The rounding is shown on the invoice detail page.",
},
],
},
{
title: "Account and security",
items: [
{
question: "How do I reset my password?",
answer:
"Use Forgot Password on the sign-in page. We email you a reset link that is valid for a limited time. If a member of our staff issued the link, it works the same way even if you are already signed in.",
},
{
question: "Can I add colleagues to my company account?",
answer:
"Yes. Company administrators can invite additional users from Settings. Each user signs in with their own credentials, and actions are recorded against the individual who performed them.",
},
{
question: "How do I update company details after approval?",
answer:
"Edit them in Settings. Changes to regulated fields — trade licence, TIN, legal name — are re-verified by our team before they take effect.",
},
],
},
];
export const PRIVACY_SECTIONS: Section[] = [
{
heading: "1. Introduction",
body: [
"The Ethio-Djibouti Standard Gauge Rail Share Company (\"EDR\", \"we\", \"us\") operates the EDR Freight platform, which lets customers register their business, agree freight contracts, raise bookings, track consignments and settle invoices online.",
"This policy explains what personal and business information we collect through the platform, why we collect it, how long we keep it and what rights you have over it. It applies to the EDR Freight customer portal and the services reached through it.",
],
},
{
heading: "2. Information we collect",
body: [
"We collect information you give us, information generated by your use of the platform, and information we receive from the regulators and financial institutions we work with.",
],
bullets: [
"Account details — name, work email address, phone number and the credentials used to sign in.",
"Company and compliance records — legal name, trade licence, TIN certificate, VAT registration, ownership and manager details, and the operational services you apply for.",
"Identity verification data — where you verify through a national identity service, the verification result and the attributes that service returns to us.",
"Operational data — contracts, bookings, consignment and cargo details, container and wagon assignments, tracking events and delivery confirmations.",
"Financial data — invoices, payment references, transaction status and settlement confirmations received from banks. We do not store your card numbers or online banking credentials.",
"Support data — the messages and files you send us through the in-app support chat or by email.",
"Technical data — IP address, device and browser information, and event logs generated when you use the platform.",
],
},
{
heading: "3. How we use your information",
bullets: [
"To create and administer your account and verify that your company is entitled to the services it applies for.",
"To perform the freight contracts and bookings you place, including allocating capacity and coordinating rail and last-mile movements.",
"To issue invoices, process payments and keep the accounting records the law requires us to keep.",
"To provide customer support and respond to the questions and complaints you raise.",
"To keep the platform secure, detect misuse and investigate incidents.",
"To meet our legal, tax, customs and regulatory obligations in Ethiopia and Djibouti.",
"To improve the platform — measuring which features are used and where users encounter errors, using aggregated and pseudonymised data wherever that is sufficient.",
],
},
{
heading: "4. Legal basis for processing",
body: [
"We process your information because it is necessary to perform the contract between you and EDR, because we have a legal obligation to do so (customs, tax and transport regulation), or because we have a legitimate interest in operating and securing the platform. Where we rely on your consent — for example, optional marketing messages — you can withdraw it at any time.",
],
},
{
heading: "5. Sharing your information",
body: [
"We do not sell your information. We share it only where it is necessary to deliver the service or where the law requires it.",
],
bullets: [
"Government and regulatory bodies — customs, revenue and transport authorities in Ethiopia and Djibouti, to the extent required for the movement of your cargo.",
"Ports, terminals and last-mile transporters involved in executing your bookings.",
"Banks and payment providers, to initiate and reconcile the payments you make.",
"Technology suppliers who host and maintain the platform on our behalf, under contracts that restrict them to processing data on our instructions.",
"Courts, law enforcement and other authorities where we are legally compelled to disclose.",
],
},
{
heading: "6. International transfers",
body: [
"Cross-border freight inherently involves parties in more than one country, so consignment and clearance information is shared with counterparties and authorities in Djibouti as well as Ethiopia. Where we transfer information outside Ethiopia, we do so only as far as the movement requires or the law permits, and we require recipients to protect it to a comparable standard.",
],
},
{
heading: "7. Data retention",
body: [
"We keep account and company records for as long as your account is active. Contract, booking, customs and financial records are kept for the period required by Ethiopian commercial, tax and customs law after the relevant transaction, because we are obliged to be able to produce them. Support conversations and technical logs are kept for a shorter period, sufficient to resolve disputes and investigate security incidents.",
],
},
{
heading: "8. Security",
body: [
"Access to the platform requires authentication, and staff access to customer records is limited to what each role needs. Data is transmitted over encrypted connections and stored on systems protected by access controls and logging. No system is perfectly secure, so please keep your credentials confidential and tell us immediately if you believe your account has been compromised.",
],
},
{
heading: "9. Your rights",
body: [
"Subject to Ethiopian law, you may ask us to give you a copy of the personal information we hold about you, correct it if it is inaccurate, restrict or object to certain processing, or delete it where we are not required to keep it. Requests are handled through the contact details below; we may need to verify your identity before acting.",
],
},
{
heading: "10. Cookies and similar technologies",
body: [
"The platform uses cookies and browser storage to keep you signed in, remember your interface preferences and measure how the product is used so we can fix problems. Essential cookies cannot be turned off without breaking sign-in. You can clear or block the rest through your browser settings.",
],
},
{
heading: "11. Children",
body: [
"The platform is a business service and is not directed at children. We do not knowingly collect information from anyone under 18.",
],
},
{
heading: "12. Changes to this policy",
body: [
"We may update this policy as the platform and the law change. Material changes are announced in the portal before they take effect, and the date at the top of this page always reflects the current version.",
],
},
{
heading: "13. Contact us",
body: [
`Questions about this policy or about how we handle your information can be sent to ${SUPPORT_CONTACT.email}, called in on ${SUPPORT_CONTACT.phone}, or addressed to our head office in ${SUPPORT_CONTACT.office}.`,
],
},
];
export const TERMS_SECTIONS: Section[] = [
{
heading: "1. These terms",
body: [
"These terms govern your use of the EDR Freight platform operated by the Ethio-Djibouti Standard Gauge Rail Share Company (\"EDR\"). By creating an account or using the platform, the company you represent agrees to them.",
"The platform is the channel through which you register, request and manage freight services. The commercial terms of each movement — routes, rates, volumes and payment terms — are set out in the freight contract you sign in the platform. Where a signed contract and these terms conflict, the signed contract governs that movement.",
],
},
{
heading: "2. Eligibility and accounts",
bullets: [
"The platform is for registered businesses. You confirm that you are authorised to act for the company you register and to bind it to these terms.",
"The information and documents you submit — trade licence, TIN, VAT registration, ownership details — must be accurate, current and genuine.",
"Accounts and operational profiles are activated only after EDR has reviewed and approved them, and approval may be refused or withdrawn.",
"You are responsible for keeping credentials confidential and for everything done under your account. Tell us at once if you suspect unauthorised use.",
],
},
{
heading: "3. Contracts and bookings",
bullets: [
"A freight contract takes effect when it is signed in the platform by you and countersigned by EDR.",
"A booking is a request for a specific movement under a contract. It becomes binding when EDR confirms it and allocates capacity — submission alone does not reserve a wagon or container.",
"You are responsible for the accuracy of consignment data: commodity description, weight, dimensions, container numbers, hazardous classification and consignee details.",
"Capacity is finite. EDR may decline, defer or reschedule a booking where capacity, safety, operating conditions or regulatory direction require it.",
],
},
{
heading: "4. Cargo, documents and compliance",
bullets: [
"You must obtain and provide every permit, customs declaration and clearance document the movement requires, and you warrant that the cargo may lawfully be carried.",
"Prohibited and restricted goods may not be tendered without EDR's prior written agreement and any licence the law requires.",
"Cargo must be packed, secured and, where applicable, labelled to the standard the mode of carriage requires. EDR may inspect, refuse or offload cargo that is misdeclared or unsafe.",
"You are liable for fines, demurrage, storage charges and losses arising from misdeclared cargo, missing documents or delays attributable to you.",
],
},
{
heading: "5. Rates, invoicing and payment",
bullets: [
"Charges are calculated from the rates in your contract, the tariffs published in the platform, and any accessorial services actually rendered.",
"Invoices are issued in the platform and are payable by the due date shown on them, through the payment channels the platform offers.",
"Payment is confirmed when the funds are confirmed by the bank, not when payment is initiated.",
"Overdue amounts may attract interest and may result in suspension of new bookings or of the account until the balance is cleared.",
"Taxes and statutory duties are your responsibility unless the contract expressly says otherwise.",
],
},
{
heading: "6. Delivery, delay and liability",
body: [
"Transit times shown in the platform are estimates based on planned schedules. They are not guarantees, and EDR is not liable for indirect or consequential loss, loss of profit or loss of market arising from delay.",
"EDR's liability for loss of or damage to cargo is limited to the extent set out in the applicable freight contract and in the transport law governing the carriage. Claims must be notified in writing within the period the contract specifies; late claims may be rejected.",
"Neither party is liable for failure to perform caused by events beyond its reasonable control, including natural disasters, industrial action, civil unrest, infrastructure failure, or acts of government and regulatory authorities.",
],
},
{
heading: "7. Acceptable use of the platform",
bullets: [
"Use the platform only for its intended purpose and in accordance with applicable law.",
"Do not attempt to gain unauthorised access, probe or disrupt the service, or interfere with other customers' data.",
"Do not scrape, resell or redistribute platform content, rates or data without written permission.",
"Do not upload malware or content that infringes the rights of others.",
],
},
{
heading: "8. Electronic signatures and records",
body: [
"You agree that contracts signed in the platform using your stored signature and stamp are validly executed, that the records the platform keeps of those signatures are admissible evidence of them, and that they carry the same effect as signatures on paper.",
],
},
{
heading: "9. Availability and changes to the service",
body: [
"We aim to keep the platform available, but it may be interrupted for maintenance, upgrades or reasons outside our control. We may add, change or withdraw features. Where a change materially affects how you use the platform, we will give reasonable notice in the portal.",
],
},
{
heading: "10. Suspension and termination",
body: [
"We may suspend or terminate access where these terms are breached, where documents prove to be false, where amounts remain unpaid, or where the law or a regulator requires it. You may stop using the platform at any time. Termination does not affect obligations already incurred — cargo in transit, invoices outstanding, or records we are required to retain.",
],
},
{
heading: "11. Intellectual property",
body: [
"The platform, its software, design and content belong to EDR or its licensors. You are granted a non-exclusive, non-transferable right to use it for your own freight operations. Your commercial and consignment data remains yours; you grant us the right to process it as needed to deliver the service and as described in the Privacy Policy.",
],
},
{
heading: "12. Confidentiality and data protection",
body: [
"Each party will keep the other's non-public commercial information confidential and use it only for the purposes of the services. Our handling of personal information is described in the Privacy Policy, which forms part of these terms.",
],
},
{
heading: "13. Governing law and disputes",
body: [
"These terms are governed by the laws of the Federal Democratic Republic of Ethiopia. The parties will first attempt to resolve any dispute amicably; failing that, the dispute is subject to the jurisdiction of the competent courts of Ethiopia, without prejudice to any arbitration clause agreed in a specific freight contract.",
],
},
{
heading: "14. Changes to these terms",
body: [
"We may update these terms as the service and the law change. Updates are published here and announced in the portal. Continuing to use the platform after an update takes effect means you accept the revised terms.",
],
},
{
heading: "15. Contact",
body: [
`For questions about these terms, write to ${SUPPORT_CONTACT.email} or call ${SUPPORT_CONTACT.phone}.`,
],
},
];

View File

@@ -15,6 +15,8 @@ import {
GeneratePriceResponse,
type MyBookingWindow,
SubmitBookingResponse,
type WagonCancellationListFilter,
type WagonCancellationListResponse,
} from "./bookings.service";
import {
contractsService,
@@ -483,6 +485,22 @@ export const api = {
bookingsService.getExportTrains(bookingId, date, cargo),
),
listWagonCancellations: endpoint<
{ bookingId: string },
WagonCancellationListResponse
>("bookings", "listWagonCancellations", ({ bookingId }) =>
bookingsService.listWagonCancellations(bookingId),
),
listMyWagonCancellations: endpoint<
WagonCancellationListFilter | void,
WagonCancellationListResponse
>(
"bookings",
"listMyWagonCancellations",
bookingsService.listMyWagonCancellations,
),
getMyBookingWindows: endpoint<void, MyBookingWindow[]>(
"train-scheduling",
"myBookingWindows",
@@ -610,10 +628,14 @@ export const api = {
),
validateShipment: endpoint<
{ id: string; dto: Freight.CreateBookingUnderContractDto },
{
id: string;
dto: Freight.CreateBookingUnderContractDto;
excludeBookingId?: string;
},
ShipmentValidation
>("contracts", "validateShipment", ({ id, dto }) =>
contractsService.validateShipment(id, dto),
>("contracts", "validateShipment", ({ id, dto, excludeBookingId }) =>
contractsService.validateShipment(id, dto, excludeBookingId),
),
getContractMilestones: endpoint<

View File

@@ -91,6 +91,8 @@ export interface MyBookingWindow {
windowClosesAt: string | null;
docReviewEndsAt: string | null;
paymentPhaseEndsAt: string | null;
/** End of the payment drain tail — pending payments may settle until then. */
paymentDrainEndsAt: string | null;
bookingWindowStatus: string;
bookingCycleNo: number;
departureDate: string;
@@ -193,6 +195,116 @@ export interface BookingListFilter {
sortOrder?: "ASC" | "DESC";
}
export interface BookingWagonContainer {
containerNumber: string | null;
sealNumber: string | null;
positionOnWagon: number | null;
grossWeightTons: string | null;
}
/** One allocated wagon of a booking, as returned by GET /bookings/:id/wagons. */
export interface BookingWagonAllocation {
/** wagon_booking_allocations id — the handle for cancelling this specific wagon. */
allocationId: string;
sequenceNo: number;
wagonNumber: string | null;
wagonType: string | null;
wagonTypeCode: string | null;
tareWeightTons: string | null;
capacityTons: string | null;
lengthMeters: string | null;
allocatedWeightTons: string | null;
loadType: "CONTAINER" | "BULK";
status: "PLANNED" | "RESERVED" | "LOADED" | "DEPARTED";
trainNumber: string | null;
departureAt: string | null;
originStation: string | null;
destinationStation: string | null;
bulkCargoDescription: string | null;
bulkQuantity: string | null;
containers: BookingWagonContainer[];
}
// ── Partial wagon cancellation (paid bookings) ──────────────────────────────
export type WagonCancellationStatus =
| "FEE_PENDING"
| "CREDIT_AVAILABLE"
| "REBOOKED"
| "WITHDRAWN"
| "EXPIRED";
/** One partial-cancellation ledger row of a paid booking. */
export interface WagonCancellation {
id: string;
bookingId: string;
rebookedBookingId?: string | null;
wagonsCancelled: number;
weightTons: number;
/** What was cut: bulk tons, or container units per size (ft). */
cancelledQuantities: {
bulkTons?: number;
bySize?: Record<string, number>;
/** Exact physical containers leaving with the cancelled wagons. */
units?: Array<{
containerSize: string;
containerNumber: string;
sealNumber?: string | null;
vgmTons: number;
isHazardous: boolean;
isReefer: boolean;
}>;
/** Wagons already left the schedule when the request was made. */
releasedAtRequest?: boolean;
};
/** Rebooking credit — the cancelled share of the original freight price. */
creditAmount: number;
feeAmount: number;
feeCurrency: string;
feeInvoiceId?: string | null;
feePaidAt?: string | null;
status: WagonCancellationStatus;
reason?: string | null;
rebookedAt?: string | null;
createdAt: string;
booking?: { id: string; reference: string } | null;
rebookedBooking?: { id: string; reference: string } | null;
}
/** Fee/credit preview of a partial wagon cancellation (no writes). */
export interface WagonCancellationPreview {
wagons: number;
weightTons: number;
feePerWagon: number;
feeAmount: number;
feeCurrency: string;
creditAmount: number;
}
export interface RequestWagonCancellationPayload {
/** Cancel SPECIFIC wagons: allocationIds from getWagons. Overrides the fields below. */
wagonAllocationIds?: string[];
/** BULK bookings: number of wagons to cancel (tons derived proportionally). */
wagons?: number;
/** CONTAINER bookings: units to cancel per size ("20"/"40", as stored on the line). */
containers?: Array<{ containerSize: string; quantity: number }>;
reason?: string;
}
export interface WagonCancellationListFilter {
statuses?: string[];
search?: string;
from?: string;
to?: string;
page?: number;
pageSize?: number;
}
export interface WagonCancellationListResponse {
items: WagonCancellation[];
total: number;
}
export const bookingsService = {
list: async (
filter: BookingListFilter | void = {},
@@ -315,6 +427,16 @@ export const bookingsService = {
return data.data;
},
customerCancel: async (
id: string,
reason?: string,
): Promise<Freight.IBooking> => {
const { data } = await client.post(`/api/bookings/${id}/customer-cancel`, {
reason,
});
return data.data;
},
reject: async (id: string, reason?: string): Promise<Freight.IBooking> => {
const { data } = await client.post(`/api/bookings/${id}/reject`, { reason });
return data.data;
@@ -548,6 +670,82 @@ export const bookingsService = {
return data.data as Freight.DayAvailabilityResponse;
},
/**
* Allocated wagons for a paid booking (empty until placed on a train).
* One row per wagon with its containers / bulk load.
*/
getWagons: async (bookingId: string): Promise<BookingWagonAllocation[]> => {
const { data } = await client.get(`/api/bookings/${bookingId}/wagons`);
return (data.data ?? data) as BookingWagonAllocation[];
},
// ── Partial wagon cancellation ──
/** Fee/credit preview for the confirm dialog — same math as the request, no writes. */
previewWagonCancellation: async (
id: string,
payload: RequestWagonCancellationPayload,
): Promise<WagonCancellationPreview> => {
const { data } = await client.post(
`/api/bookings/${id}/wagon-cancellations/preview`,
payload,
);
return data.data ?? data;
},
/** Open a cancellation: issues the fee invoice; wagons release once the fee settles. */
requestWagonCancellation: async (
id: string,
payload: RequestWagonCancellationPayload,
): Promise<WagonCancellation> => {
const { data } = await client.post(
`/api/bookings/${id}/wagon-cancellations`,
payload,
);
return data.data ?? data;
},
/** Cancellation history of one booking (as source and as rebooked target). */
listWagonCancellations: async (
bookingId: string,
): Promise<WagonCancellationListResponse> => {
const { data } = await client.get(
`/api/bookings/${bookingId}/wagon-cancellations`,
);
return data.data ?? data;
},
/** The signed-in customer's wagon cancellations (paginated, filterable). */
listMyWagonCancellations: async (
filter: WagonCancellationListFilter | void = {},
): Promise<WagonCancellationListResponse> => {
const { data } = await client.get("/api/bookings/wagon-cancellations/my", {
params: filter,
});
return data.data ?? data;
},
/** Void a FEE_PENDING request — the fee invoice is cancelled, nothing was released. */
withdrawWagonCancellation: async (
cancellationId: string,
): Promise<WagonCancellation> => {
const { data } = await client.post(
`/api/bookings/wagon-cancellations/${cancellationId}/withdraw`,
);
return data.data ?? data;
},
/** Rebook a CREDIT_AVAILABLE cancellation onto a shipment day → new PAID booking. */
rebookWagonCancellation: async (
cancellationId: string,
payload: { scheduledDate: string },
): Promise<{ cancellation: WagonCancellation; bookingId: string }> => {
const { data } = await client.post(
`/api/bookings/wagon-cancellations/${cancellationId}/rebook`,
payload,
);
return data.data ?? data;
},
/**
* Upcoming/open booking windows on the signed-in customer's active-contract
* lanes (import booking-day windows + export 24h pre-departure windows).

View File

@@ -400,8 +400,13 @@ export const contractsService = {
validateShipment: async (
id: string,
dto: Freight.CreateBookingUnderContractDto,
// Completion/resubmit: exclude this booking's own containers from the
// same-train clash check.
excludeBookingId?: string,
): Promise<ShipmentValidation> => {
const { data } = await client.post(C.VALIDATE_SHIPMENT(id), dto);
const { data } = await client.post(C.VALIDATE_SHIPMENT(id), dto, {
params: excludeBookingId ? { bookingId: excludeBookingId } : undefined,
});
return data.data ?? data;
},

View File

@@ -34,6 +34,16 @@ function humanizeApiMessage(raw: string): string {
return raw;
}
/**
* NestJS's ValidationPipe reports every failed constraint at once, so `message`
* arrives as a string[] rather than a string. Flatten it — passing the array
* through left the UI rendering its entries run together with no separator.
*/
function asMessage(value: unknown): string {
if (Array.isArray(value)) return value.filter(Boolean).join(". ");
return typeof value === "string" ? value : "";
}
export function extractApiError(err: unknown): ApiError {
if (err && typeof err === "object") {
const obj = err as Record<string, unknown>;
@@ -41,13 +51,10 @@ export function extractApiError(err: unknown): ApiError {
if (response) {
const statusCode = response.status as number | undefined;
const data = response.data as Record<string, unknown> | undefined;
const raw = asMessage(data?.message) || asMessage(data?.error);
return {
code: (data?.message as string) || (data?.error as string) || "api_error",
message: humanizeApiMessage(
(data?.message as string) ||
(data?.error as string) ||
"An unexpected error occurred",
),
code: raw || "api_error",
message: humanizeApiMessage(raw || "An unexpected error occurred"),
statusCode,
};
}

View File

@@ -0,0 +1,22 @@
import { amountsMatchToTheCent } from "./cbe-bill.service";
describe("amountsMatchToTheCent (CBE payment amount gate)", () => {
it("accepts the exact amount", () => {
expect(amountsMatchToTheCent(1234.34, 1234.34)).toBe(true);
});
it("rejects a cents-only difference (the 1234.89 vs 1234.34 bug)", () => {
expect(amountsMatchToTheCent(1234.89, 1234.34)).toBe(false);
expect(amountsMatchToTheCent(1234.35, 1234.34)).toBe(false);
});
it("rejects whole-unit differences", () => {
expect(amountsMatchToTheCent(1235.34, 1234.34)).toBe(false);
});
it("absorbs double-precision storage noise", () => {
expect(amountsMatchToTheCent(1234.34, 1234.3399999999999)).toBe(true);
// classic float artifact: 0.1 + 0.2 !== 0.3
expect(amountsMatchToTheCent(0.1 + 0.2, 0.3)).toBe(true);
});
});

View File

@@ -38,8 +38,15 @@ import {
/** Postgres unique_violation — the DB-level idempotency backstop firing on a concurrent duplicate. */
const PG_UNIQUE_VIOLATION = "23505";
/** Mirrors the short-pay tolerance already applied in handlePaymentEvent. */
const AMOUNT_TOLERANCE = 0.01;
/**
* CBE must pay the bill to the exact cent — compare in integer cents so
* double-precision storage noise (1234.34 stored as 1234.33999…) can neither
* mask nor fabricate a difference. A relative tolerance is wrong here: 1% of a
* 1234.34 bill would wave through anything up to ±12.34.
*/
export function amountsMatchToTheCent(a: number, b: number): boolean {
return Math.round(a * 100) === Math.round(b * 100);
}
/**
* Translate an intent's own terminal state into the same reason vocabulary the domain apps
@@ -268,8 +275,7 @@ export class CbeBillService {
const amount = Number(dto.Amount);
if (
!Number.isFinite(amount) ||
Math.abs(amount - intent.amountMinor) >
intent.amountMinor * AMOUNT_TOLERANCE
!amountsMatchToTheCent(amount, intent.amountMinor)
) {
throw new CbeBillError("Amount mismatch", "BUSINESS");
}

View File

@@ -29,6 +29,11 @@ export interface BookingWindowPhaseEvent {
windowClosesAt: string | null;
docReviewEndsAt: string | null;
paymentPhaseEndsAt: string | null;
/**
* When the payment drain tail ends (paymentPhaseEndsAt + server drain
* minutes) — pending payments may still settle until then. Display only.
*/
paymentDrainEndsAt: string | null;
scheduledDepartureDate: string | null;
}

View File

@@ -1,4 +1,4 @@
import { Group, Text } from "@mantine/core";
import { Group, Loader, Text } from "@mantine/core";
import { Clock } from "lucide-react";
import { useEffect, useState } from "react";
@@ -9,6 +9,14 @@ export interface CountdownTimerProps {
label?: string;
/** Text shown once the deadline has passed. */
expiredText?: string;
/**
* Optional grace stage: once `deadline` passes, count down to this later
* ISO timestamp instead (e.g. the payment drain tail). `expiredText` then
* only shows after the grace deadline has also passed.
*/
graceDeadline?: string | null;
/** Label shown while counting down the grace stage (e.g. "Payment processing — closes in"). */
graceLabel?: string;
/** Visual size of the time text. */
size?: "xs" | "sm" | "md" | "lg";
/** Colour once under this many seconds remain (urgency). Default 300 (5 min). */
@@ -35,37 +43,56 @@ function formatRemaining(ms: number): string {
/**
* Live countdown to an ISO deadline. Ticks once a second, shows the remaining
* time (d/h/m/s), turns red when under `urgentUnderSeconds`, and shows
* `expiredText` once the deadline is in the past. Display only — enforcement
* lives server-side.
* `expiredText` once the deadline is in the past. When `graceDeadline` is set,
* a lapsed main deadline rolls into a calm second-stage countdown (spinner,
* no urgency colours) toward it before `expiredText` takes over. Display only
* — enforcement lives server-side.
*/
export function CountdownTimer({
deadline,
label,
expiredText = "Expired",
graceDeadline,
graceLabel,
size = "sm",
urgentUnderSeconds = 300,
}: CountdownTimerProps) {
const [remaining, setRemaining] = useState<number | null>(() =>
deadline ? new Date(deadline).getTime() - Date.now() : null,
);
const [now, setNow] = useState(() => Date.now());
useEffect(() => {
if (!deadline) {
setRemaining(null);
return;
}
const target = new Date(deadline).getTime();
const tick = () => setRemaining(target - Date.now());
tick();
const id = setInterval(tick, 1000);
if (!deadline) return;
setNow(Date.now());
const id = setInterval(() => setNow(Date.now()), 1000);
return () => clearInterval(id);
}, [deadline]);
}, [deadline, graceDeadline]);
if (!deadline || remaining == null || Number.isNaN(remaining)) {
return null;
if (!deadline) return null;
const target = new Date(deadline).getTime();
if (Number.isNaN(target)) return null;
const remaining = target - now;
const expired = remaining <= 0;
const graceTarget = graceDeadline ? new Date(graceDeadline).getTime() : NaN;
const graceRemaining = Number.isNaN(graceTarget) ? 0 : graceTarget - now;
const inGrace = expired && graceRemaining > 0;
if (inGrace) {
return (
<Group gap={6} align="center" wrap="nowrap">
<Loader size={size === "lg" ? 18 : 14} color="blue.7" />
{graceLabel && (
<Text size={size} c="dimmed">
{graceLabel}
</Text>
)}
<Text size={size} fw={600} c="blue.7">
{formatRemaining(graceRemaining)}
</Text>
</Group>
);
}
const expired = remaining <= 0;
const urgent = !expired && remaining <= urgentUnderSeconds * 1000;
const color = expired ? "red.7" : urgent ? "orange.7" : "dimmed";