finilize gl flow for export

This commit is contained in:
Marshal
2026-07-02 17:55:59 +00:00
parent f77e4d150b
commit dd47068a4b
24 changed files with 2462 additions and 598 deletions

View File

@@ -1,5 +1,10 @@
import { BadRequestException, Injectable } from '@nestjs/common';
import { ContractDocPhase, type ClearanceT1State } from '@edr/types';
import {
ContractDocPhase,
type ClearanceFinalInvoiceSummary,
type ClearanceT1State,
type ClearanceTrainState,
} from '@edr/types';
import { DropdownSettingsService } from '../dropdown-settings/dropdown-settings.service';
import { FileUploadSettingsService } from '../file-upload-settings/file-upload-settings.service';
@@ -66,6 +71,15 @@ export interface BookingClearanceView {
workflowFiles?: ReturnType<typeof buildWorkflowFiles>;
/** Import post-allocation T1 transit document state (null until wagon allocation). */
t1?: ClearanceT1State | null;
/** Train link state for the booking (both directions). */
train?: ClearanceTrainState | null;
gatepassGranted?: boolean;
gatepassAt?: string | null;
t1Closed?: boolean;
t1ClosedAt?: string | null;
offloaded?: boolean;
/** GL Djibouti post-offload final invoice (export). */
finalInvoice?: ClearanceFinalInvoiceSummary | null;
}
@Injectable()
@@ -175,6 +189,18 @@ export class BookingClearanceService {
}
}
let train: ClearanceTrainState | null = null;
try {
train = await this.glOperationsService.trainState(bookingId);
} catch {
train = null;
}
const finalInvoice = await this.glOperationsService.finalInvoiceSummary(bookingId);
const bookingMilestone = (code: string) =>
milestones.find((m) => m.milestoneCode === code);
const gatepassMilestone = bookingMilestone('GATEPASS_GRANTED');
const t1ClosedMilestone = bookingMilestone('T1_CLOSED');
return {
bookingId,
status: booking.status,
@@ -206,6 +232,22 @@ export class BookingClearanceService {
dutyAdvice,
workflowFiles,
t1,
train,
gatepassGranted: gatepassMilestone?.status === 'COMPLETED',
gatepassAt:
gatepassMilestone?.status === 'COMPLETED'
? (gatepassMilestone.metadata?.gatepassAt ??
(gatepassMilestone.triggeredAt
? gatepassMilestone.triggeredAt.toISOString()
: null))
: null,
t1Closed: t1ClosedMilestone?.status === 'COMPLETED',
t1ClosedAt:
t1ClosedMilestone?.status === 'COMPLETED' && t1ClosedMilestone.triggeredAt
? t1ClosedMilestone.triggeredAt.toISOString()
: null,
offloaded: bookingMilestone('OFFLOADED')?.status === 'COMPLETED',
finalInvoice,
};
}
@@ -302,6 +344,12 @@ export class BookingClearanceService {
: ContractDocPhase.CustomerDuty,
} as never);
// Export: the declaration is the last GL ET pre-operation action — release
// immediately so the customer can proceed without a separate confirm click.
if (tradeDirection === 'EXPORT') {
await this.workflowService.onExportReleasedForBooking(bookingId, userId);
}
return this.bookingsService.findById(bookingId);
}

View File

@@ -68,6 +68,7 @@ const EXPORT_DEFS: Record<string, Omit<MilestoneDef, 'code'>> = {
DEPARTED_TO_DJIBOUTI: { label: 'Departed to Djibouti', ownerRegion: 'OPS', triggeredByDoc: false },
ARRIVED_AT_DJIBOUTI: { label: 'Arrived at Djibouti', ownerRegion: 'DJ', triggeredByDoc: false },
GATEPASS_GRANTED: { label: 'Gatepass Granted', ownerRegion: 'DJ', triggeredByDoc: false },
T1_CLOSED: { label: 'T1 Closed', ownerRegion: 'DJ', triggeredByDoc: false },
OFFLOADED: { label: 'Offloaded', ownerRegion: 'DJ', triggeredByDoc: true },
};

View File

@@ -91,6 +91,39 @@ export class ClearanceMilestoneService {
});
}
/**
* Find-or-create a post-booking milestone row from the catalog. Needed for codes
* added to the catalog after a booking's rows were seeded (e.g. export T1_CLOSED).
*/
async ensureForBooking(
bookingId: string,
code: string,
tradeDirection: string,
): Promise<ClearanceMilestone> {
const existing = await this.repo.findOne({ where: { bookingId, milestoneCode: code } });
if (existing) return existing;
const { postBooking } = splitMilestones(tradeDirection);
const idx = postBooking.findIndex((d) => d.code === code);
if (idx < 0) {
throw new NotFoundException(
`Milestone ${code} is not a ${tradeDirection} post-booking milestone`,
);
}
const def = postBooking[idx]!;
return this.repo.save(
this.repo.create({
bookingId,
milestoneCode: def.code,
milestoneLabel: def.label,
ownerRegion: def.ownerRegion,
triggeredByDoc: def.triggeredByDoc,
status: 'PENDING',
sortOrder: idx,
}),
);
}
/** Mark a milestone complete (by code) on a booking. */
async completeForBooking(
bookingId: string,

View File

@@ -1,5 +1,10 @@
import { BadRequestException, ConflictException, Injectable } from '@nestjs/common';
import { ContractDocPhase, type ClearanceT1State } from '@edr/types';
import {
ContractDocPhase,
type ClearanceFinalInvoiceSummary,
type ClearanceT1State,
type ClearanceTrainState,
} from '@edr/types';
import { DropdownSettingsService } from '../dropdown-settings/dropdown-settings.service';
import { FileUploadSettingsService } from '../file-upload-settings/file-upload-settings.service';
@@ -80,6 +85,15 @@ export interface ContractClearanceView {
workflowFiles?: ReturnType<typeof buildWorkflowFiles>;
/** Import post-allocation T1 transit document state (null until a booking is linked). */
t1?: ClearanceT1State | null;
/** Train link state for the booking (both directions; null until a booking is linked). */
train?: ClearanceTrainState | null;
gatepassGranted?: boolean;
gatepassAt?: string | null;
t1Closed?: boolean;
t1ClosedAt?: string | null;
offloaded?: boolean;
/** GL Djibouti post-offload final invoice (export). */
finalInvoice?: ClearanceFinalInvoiceSummary | null;
}
@Injectable()
@@ -237,11 +251,27 @@ export class ContractClearanceService {
}
}
let nextAction = this.workflowService.computeNextAction(contract, cycle, milestones);
if (cycle?.bookingId && contract.tradeDirection === 'EXPORT') {
const bookingMilestones = await this.workflowService.listMilestonesForBooking(
let train: ClearanceTrainState | null = null;
let bookingMilestones: ClearanceMilestone[] = [];
let finalInvoice: ClearanceFinalInvoiceSummary | null = null;
if (cycle?.bookingId) {
try {
train = await this.glOperationsService.trainState(cycle.bookingId);
} catch {
train = null;
}
bookingMilestones = await this.workflowService.listMilestonesForBooking(
cycle.bookingId,
);
finalInvoice = await this.glOperationsService.finalInvoiceSummary(cycle.bookingId);
}
const bookingMilestone = (code: string) =>
bookingMilestones.find((m) => m.milestoneCode === code);
const gatepassMilestone = bookingMilestone('GATEPASS_GRANTED');
const t1ClosedMilestone = bookingMilestone('T1_CLOSED');
let nextAction = this.workflowService.computeNextAction(contract, cycle, milestones);
if (cycle?.bookingId && contract.tradeDirection === 'EXPORT') {
const booking = await this.bookingsService.findById(cycle.bookingId);
if (booking) {
nextAction = this.workflowService.computeNextActionForBooking(
@@ -286,6 +316,22 @@ export class ContractClearanceService {
dutyAdvice,
workflowFiles,
t1,
train,
gatepassGranted: gatepassMilestone?.status === 'COMPLETED',
gatepassAt:
gatepassMilestone?.status === 'COMPLETED'
? (gatepassMilestone.metadata?.gatepassAt ??
(gatepassMilestone.triggeredAt
? gatepassMilestone.triggeredAt.toISOString()
: null))
: null,
t1Closed: t1ClosedMilestone?.status === 'COMPLETED',
t1ClosedAt:
t1ClosedMilestone?.status === 'COMPLETED' && t1ClosedMilestone.triggeredAt
? t1ClosedMilestone.triggeredAt.toISOString()
: null,
offloaded: bookingMilestone('OFFLOADED')?.status === 'COMPLETED',
finalInvoice,
};
}
@@ -873,6 +919,12 @@ export class ContractClearanceService {
});
}
// Export: the declaration is the last GL ET pre-booking action — release
// immediately so booking creation unlocks without a separate confirm click.
if (contract.tradeDirection === 'EXPORT') {
await this.workflowService.onExportReleased(contractId, userId);
}
return this.contractsService.findById(contractId);
}

View File

@@ -77,6 +77,7 @@ import {
} from './dto/gl-operations.dto';
import {
AdviseContractDutyDto,
GatepassDto,
RoAmendmentDto,
} from './dto/phased-clearance.dto';
@@ -681,6 +682,30 @@ export class ContractsController {
return this.clearanceService.djQueue(filter);
}
@Get('clearance/dj-schedules')
@BookingStaff(FREIGHT_PERMS.contracts.clearanceDjActions)
@ApiOperation({ summary: 'Train schedules carrying customs bookings — GL DJ gate-pass table' })
djClearanceSchedules() {
return this.glOperationsService.djSchedules();
}
@Post('clearance/schedules/:scheduleId/gatepass')
@BookingStaff(FREIGHT_PERMS.contracts.clearanceDjActions)
@ApiOperation({
summary: 'GL DJ grants the gate pass for every customs booking on a train schedule',
})
grantScheduleGatepass(
@Param('scheduleId', ParseUUIDPipe) scheduleId: string,
@Body() dto: GatepassDto,
@CurrentUser() user: AuthUserPayload,
) {
return this.glOperationsService.grantScheduleGatepass(
scheduleId,
dto?.gatepassAt,
resolveAuthUserId(user),
);
}
// ── Path A self-clearance — Operations reviews the customer's own docs ───────
@Get('clearance/ops-queue')
@@ -889,9 +914,13 @@ export class ContractsController {
}
@Post('bookings/:bookingId/t1-close')
@BookingStaff(FREIGHT_PERMS.contracts.clearanceEtActions)
@BookingStaff([
FREIGHT_PERMS.contracts.clearanceEtActions,
FREIGHT_PERMS.contracts.clearanceDjActions,
])
@ApiOperation({
summary: 'GL Ethiopia closes (accepts) the T1 document set after the train arrives',
summary:
'Close (accept) the T1 set — GL ET after arrival (import) / GL DJ after gate pass (export)',
})
closeT1(
@Param('bookingId', ParseUUIDPipe) bookingId: string,
@@ -900,6 +929,75 @@ export class ContractsController {
return this.glOperationsService.closeT1(bookingId, resolveAuthUserId(user));
}
@Post('bookings/:bookingId/gatepass')
@BookingStaff(FREIGHT_PERMS.contracts.clearanceDjActions)
@ApiOperation({ summary: 'GL DJ grants the gate pass for a customs booking (captures time)' })
grantGatepass(
@Param('bookingId', ParseUUIDPipe) bookingId: string,
@Body() dto: GatepassDto,
@CurrentUser() user: AuthUserPayload,
) {
return this.glOperationsService.grantGatepass(
bookingId,
dto?.gatepassAt,
resolveAuthUserId(user),
);
}
@Post('bookings/:bookingId/final-invoice')
@BookingStaff(FREIGHT_PERMS.contracts.clearanceDjActions)
@UseInterceptors(FileInterceptor('file'))
@ApiConsumes('multipart/form-data')
@ApiOperation({
summary: 'GL DJ raises the post-offload final invoice (amount + invoice document)',
})
createFinalInvoice(
@Param('bookingId', ParseUUIDPipe) bookingId: string,
@Body('amount') amountRaw: string,
@Body('currency') currency: string | undefined,
@Body('description') description: string | undefined,
@UploadedFile() file: Express.Multer.File,
@CurrentUser() user: AuthUserPayload,
) {
return this.glOperationsService.createFinalInvoice(
bookingId,
{
amount: Number(amountRaw),
currency: currency?.trim() || 'ETB',
description,
},
file,
resolveAuthUserId(user),
);
}
@Post('bookings/:bookingId/final-invoice-slip')
@UseInterceptors(FileInterceptor('file'))
@ApiConsumes('multipart/form-data')
@ApiOperation({ summary: 'Customer attaches the payment slip for the final invoice' })
uploadFinalInvoiceSlip(
@Param('bookingId', ParseUUIDPipe) bookingId: string,
@UploadedFile() file: Express.Multer.File,
) {
return this.glOperationsService.uploadFinalInvoiceSlip(bookingId, file);
}
@Post('bookings/:bookingId/final-invoice/confirm')
@BookingStaff([
FREIGHT_PERMS.contracts.clearanceDjActions,
FREIGHT_PERMS.contracts.clearanceEtActions,
])
@ApiOperation({ summary: 'GL (ET or DJ) confirms the payment slip — settles the final invoice' })
confirmFinalInvoicePaid(
@Param('bookingId', ParseUUIDPipe) bookingId: string,
@CurrentUser() user: AuthUserPayload,
) {
return this.glOperationsService.confirmFinalInvoicePaid(
bookingId,
resolveAuthUserId(user),
);
}
@Post('bookings/:bookingId/documents')
@BookingStaff(FREIGHT_PERMS.bookings.uploadClearanceOutput)
@UseInterceptors(AnyFilesInterceptor())

View File

@@ -3,6 +3,7 @@ import { ConfigService } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ExchangeModule, ExchangeOptions } from '@edr/api-common';
import { BillingModule } from '../billing/billing.module';
import { CompaniesModule } from '../companies/companies.module';
import { FilesModule } from '../files/files.module';
import { MinioModule } from '../minio/minio.module';
@@ -64,6 +65,7 @@ import { ContractDocumentViewModelBuilder } from '../../contracts/contract-docum
Booking,
BookingContainerUnit,
]),
BillingModule,
RuleEngineModule,
FileUploadSettingsModule,
DropdownSettingsModule,

View File

@@ -35,3 +35,12 @@ export class RoAmendmentDto {
@IsString()
note?: string;
}
export class GatepassDto {
@ApiPropertyOptional({
description: 'When the gate pass was granted (ISO datetime; defaults to now)',
})
@IsOptional()
@IsString()
gatepassAt?: string;
}

View File

@@ -23,6 +23,8 @@ export interface MilestoneMetadata {
dutyAmount?: number;
dutyCurrency?: string;
declarationSerial?: string;
/** When the gate pass was physically granted (GL DJ captures the time). */
gatepassAt?: string;
}
/**

View File

@@ -1,14 +1,24 @@
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import { DataSource } from 'typeorm';
import { isT1TransportFileCode, type Freight } from '@edr/types';
import {
BadRequestException,
ConflictException,
Injectable,
NotFoundException,
} from '@nestjs/common';
import { DataSource, In, IsNull } from 'typeorm';
import { Freight, GL_FINAL_INVOICE_TYPE, isT1TransportFileCode } from '@edr/types';
import { BillingService } from '../billing/billing.service';
import { InvoiceLine } from '../billing/entities/invoice-line.entity';
import { FilesService } from '../files/files.service';
import { Booking } from '../bookings/entities/booking.entity';
import { TrainSchedule } from '../train-schedules/entities/train-schedule.entity';
import { ImportDjiboutiOperation } from '../train-scheduling/entities/import-djibouti-operation.entity';
import {
ClearanceIncident,
IncidentType,
} from './entities/clearance-incident.entity';
import { ClearanceMilestone } from './entities/clearance-milestone.entity';
import { ContractClearanceCycle } from './entities/contract-clearance-cycle.entity';
import { ClearanceMilestoneService } from './clearance-milestone.service';
import {
persistExportTransportUploads,
@@ -43,6 +53,7 @@ export class GlOperationsService {
private readonly dataSource: DataSource,
private readonly filesService: FilesService,
private readonly milestoneService: ClearanceMilestoneService,
private readonly billingService: BillingService,
) {}
private get bookings() {
@@ -167,12 +178,8 @@ export class GlOperationsService {
return { uploaded: files.length, completedMilestones };
}
/**
* T1 transit-document lifecycle state for an import shipment booking. Wagon
* allocation opens the upload window; train departure locks it; train arrival
* lets GL Ethiopia close (accept) the T1 set.
*/
async t1State(bookingId: string): Promise<Freight.ClearanceT1State> {
/** Wagon-allocation + train-schedule actuals for a booking (both directions). */
async trainState(bookingId: string): Promise<Freight.ClearanceTrainState> {
const booking = await this.getBooking(bookingId);
const milestones = await this.milestoneService.listForBooking(bookingId);
@@ -190,19 +197,35 @@ export class GlOperationsService {
.findOne({ where: { id: booking.trainScheduleId } });
}
return {
wagonAllocated,
departedAt: schedule?.actualDepartureAt
? new Date(schedule.actualDepartureAt).toISOString()
: null,
arrivedAt: schedule?.actualArrivalAt
? new Date(schedule.actualArrivalAt).toISOString()
: null,
};
}
/**
* T1 transit-document lifecycle state for an import shipment booking. Wagon
* allocation opens the upload window; train departure locks it; train arrival
* lets GL Ethiopia close (accept) the T1 set.
*/
async t1State(bookingId: string): Promise<Freight.ClearanceT1State> {
const train = await this.trainState(bookingId);
const milestones = await this.milestoneService.listForBooking(bookingId);
const closedMilestone = milestones.find(
(m) => m.milestoneCode === 'T1_CLOSED' && m.status === 'COMPLETED',
);
return {
bookingId,
wagonAllocated,
trainDepartedAt: schedule?.actualDepartureAt
? new Date(schedule.actualDepartureAt).toISOString()
: null,
trainArrivedAt: schedule?.actualArrivalAt
? new Date(schedule.actualArrivalAt).toISOString()
: null,
wagonAllocated: train.wagonAllocated,
trainDepartedAt: train.departedAt,
trainArrivedAt: train.arrivedAt,
closed: Boolean(closedMilestone),
closedAt: closedMilestone?.triggeredAt
? new Date(closedMilestone.triggeredAt).toISOString()
@@ -243,26 +266,26 @@ export class GlOperationsService {
}
/**
* GL Ethiopia closes (accepts) the T1 document set once the train has arrived.
* Completes the T1_CLOSED milestone; the document set becomes final.
* Close (accept) the T1/transport document set.
* Import: GL Ethiopia closes once the train has arrived (T1 files required).
* Export: GL Djibouti closes after the gate pass (transport document required).
*/
async closeT1(
bookingId: string,
userId?: string,
): Promise<Freight.ClearanceT1State> {
const booking = await this.getBooking(bookingId);
if (booking.tradeDirection !== 'IMPORT') {
throw new BadRequestException('T1 closure applies to import shipments only.');
}
const tradeDirection = booking.tradeDirection ?? 'IMPORT';
const state = await this.t1State(bookingId);
if (state.closed) return state;
if (tradeDirection === 'IMPORT') {
if (!state.trainArrivedAt) {
throw new BadRequestException(
'The train has not arrived yet — T1 can be closed only after arrival.',
);
}
const files = await this.filesService.findByResource(bookingId, 'bookings');
const hasT1 = files.some((f) => isT1TransportFileCode(f.code));
if (!hasT1) {
@@ -270,11 +293,391 @@ export class GlOperationsService {
'No T1 transport documents on file — GL Djibouti must upload them first.',
);
}
} else {
const milestones = await this.milestoneService.listForBooking(bookingId);
const done = (code: string) =>
milestones.find((m) => m.milestoneCode === code)?.status === 'COMPLETED';
if (!done('EXPORT_TRANSPORT_ISSUED')) {
throw new BadRequestException(
'The transport document must be uploaded before T1 can be closed.',
);
}
if (!done('GATEPASS_GRANTED')) {
throw new BadRequestException('Grant the gate pass before closing T1.');
}
// Export bookings seeded before T1_CLOSED joined the catalog lack the row.
await this.milestoneService.ensureForBooking(bookingId, 'T1_CLOSED', tradeDirection);
}
await this.milestoneService.completeForBooking(bookingId, 'T1_CLOSED', userId);
return this.t1State(bookingId);
}
/** Milestones GL DJ implicitly confirms when granting an export gate pass. */
private static readonly EXPORT_ARRIVAL_CHAIN = [
'CARGO_ARRIVED',
'READY_FOR_LOADING',
'LOADED',
'DEPARTED_TO_DJIBOUTI',
'ARRIVED_AT_DJIBOUTI',
];
/**
* GL Djibouti grants the gate pass for a customs booking, capturing the time.
* Export: requires the train to have arrived at Djibouti; back-fills the
* arrival-chain milestones. Import: requires wagon allocation (pre-loading).
*/
async grantGatepass(
bookingId: string,
gatepassAt?: string,
userId?: string,
): Promise<{ bookingId: string; gatepassAt: string }> {
const booking = await this.getBooking(bookingId);
if (!booking.customsClearingEnabled) {
throw new BadRequestException('Gate pass applies to customs bookings only.');
}
const tradeDirection = booking.tradeDirection ?? 'IMPORT';
const milestones = await this.milestoneService.listForBooking(bookingId);
const byCode = new Map(milestones.map((m) => [m.milestoneCode, m]));
const existing = byCode.get('GATEPASS_GRANTED');
if (existing?.status === 'COMPLETED') {
return {
bookingId,
gatepassAt:
existing.metadata?.gatepassAt ??
(existing.triggeredAt ? new Date(existing.triggeredAt).toISOString() : ''),
};
}
const train = await this.trainState(bookingId);
if (tradeDirection === 'EXPORT') {
if (!train.arrivedAt) {
throw new BadRequestException(
'The train has not arrived at Djibouti yet — gate pass can be granted after arrival.',
);
}
for (const code of GlOperationsService.EXPORT_ARRIVAL_CHAIN) {
if (byCode.get(code)?.status === 'PENDING') {
await this.milestoneService.completeForBooking(bookingId, code, userId);
}
}
} else if (!train.wagonAllocated) {
throw new BadRequestException(
'Wagons must be allocated before the gate pass can be granted.',
);
}
const at = gatepassAt?.trim() || new Date().toISOString();
await this.milestoneService.completeWithMetadataForBooking(
bookingId,
'GATEPASS_GRANTED',
{ gatepassAt: at },
userId,
);
return { bookingId, gatepassAt: at };
}
/** Train schedules carrying ≥1 customs booking — the GL Djibouti gate-pass table. */
async djSchedules(): Promise<Freight.DjClearanceSchedule[]> {
const schedules = await this.dataSource.getRepository(TrainSchedule).find({
relations: {
scheduleBookings: { booking: true },
originStation: true,
destinationStation: true,
},
order: { scheduledDepartureDate: 'DESC' },
});
const withCustoms = schedules
.filter((s) => s.status !== 'CANCELLED')
.map((s) => ({
schedule: s,
customs: (s.scheduleBookings ?? [])
.map((sb) => sb.booking)
.filter((b): b is Booking => Boolean(b?.customsClearingEnabled)),
}))
.filter((s) => s.customs.length > 0);
const bookingIds = withCustoms.flatMap((s) => s.customs.map((b) => b.id));
const gatepassRows = bookingIds.length
? await this.dataSource.getRepository(ClearanceMilestone).find({
where: { bookingId: In(bookingIds), milestoneCode: 'GATEPASS_GRANTED' },
})
: [];
const gatepassByBooking = new Map(gatepassRows.map((m) => [m.bookingId, m]));
return withCustoms.map(({ schedule, customs }) => {
const freightTypes = [...new Set(customs.map((b) => b.freightType).filter(Boolean))];
return {
id: schedule.id,
trainNumber: schedule.trainNumber ?? null,
routeName: null,
origin: schedule.originStation?.label ?? schedule.originStation?.code ?? null,
destination:
schedule.destinationStation?.label ?? schedule.destinationStation?.code ?? null,
status: schedule.status,
scheduledDepartureDate: schedule.scheduledDepartureDate
? new Date(schedule.scheduledDepartureDate).toISOString()
: null,
actualDepartureAt: schedule.actualDepartureAt
? new Date(schedule.actualDepartureAt).toISOString()
: null,
actualArrivalAt: schedule.actualArrivalAt
? new Date(schedule.actualArrivalAt).toISOString()
: null,
freightType:
freightTypes.length === 1 ? (freightTypes[0] as string) : freightTypes.length ? 'MIXED' : null,
customsBookings: customs.map((b) => {
const m = gatepassByBooking.get(b.id);
const granted = m?.status === 'COMPLETED';
return {
bookingId: b.id,
reference: b.reference ?? b.id,
tradeDirection: b.tradeDirection ?? 'IMPORT',
contractId: b.contractId ?? null,
gatepassGranted: granted,
gatepassAt: granted
? (m?.metadata?.gatepassAt ??
(m?.triggeredAt ? new Date(m.triggeredAt).toISOString() : null))
: null,
};
}),
};
});
}
/**
* One-click gate pass for every customs booking on a train schedule. Per-booking
* guard failures are collected, not fatal. Import schedules also get the
* schedule-level ImportDjiboutiOperation gate pass so loading unblocks.
*/
async grantScheduleGatepass(
scheduleId: string,
gatepassAt?: string,
userId?: string,
): Promise<{ granted: number; skipped: Array<{ bookingId: string; error: string }> }> {
const schedule = await this.dataSource.getRepository(TrainSchedule).findOne({
where: { id: scheduleId },
relations: { scheduleBookings: { booking: true } },
});
if (!schedule) throw new NotFoundException(`Train schedule ${scheduleId} not found`);
const customs = (schedule.scheduleBookings ?? [])
.map((sb) => sb.booking)
.filter((b): b is Booking => Boolean(b?.customsClearingEnabled));
if (customs.length === 0) {
throw new BadRequestException('No customs bookings ride this schedule.');
}
let granted = 0;
const skipped: Array<{ bookingId: string; error: string }> = [];
for (const booking of customs) {
try {
await this.grantGatepass(booking.id, gatepassAt, userId);
granted += 1;
} catch (e) {
skipped.push({
bookingId: booking.id,
error: e instanceof Error ? e.message : 'Failed',
});
}
}
if (granted > 0 && customs.some((b) => (b.tradeDirection ?? 'IMPORT') === 'IMPORT')) {
const opRepo = this.dataSource.getRepository(ImportDjiboutiOperation);
let operation = await opRepo.findOne({ where: { trainScheduleId: scheduleId } });
if (!operation) {
operation = opRepo.create({ trainScheduleId: scheduleId });
}
if (!operation.gatepassGrantedAt) {
operation.gatepassGrantedAt = gatepassAt ? new Date(gatepassAt) : new Date();
await opRepo.save(operation);
}
}
return { granted, skipped };
}
/**
* GL Djibouti raises the post-offload final invoice (export): manual amount +
* attached invoice document. The customer pays offline and attaches a slip;
* GL (ET or DJ) then confirms to settle it.
*/
async createFinalInvoice(
bookingId: string,
input: { amount: number; currency: string; description?: string },
file: Express.Multer.File,
userId?: string,
): Promise<Freight.ClearanceFinalInvoiceSummary> {
const booking = await this.getBooking(bookingId);
if (!booking.customsClearingEnabled) {
throw new BadRequestException('Final invoice applies to customs bookings only.');
}
if (!(input.amount > 0)) {
throw new BadRequestException('Invoice amount must be greater than zero.');
}
if (!file) throw new BadRequestException('Attach the invoice document.');
const milestones = await this.milestoneService.listForBooking(bookingId);
const offloaded = milestones.find(
(m) => m.milestoneCode === 'OFFLOADED' && m.status === 'COMPLETED',
);
if (!offloaded) {
throw new BadRequestException(
'Cargo must be offloaded before the final invoice can be raised.',
);
}
const existing = await this.billingService.findInvoice(
Freight.InvoiceSource.Booking,
bookingId,
GL_FINAL_INVOICE_TYPE,
);
if (
existing &&
existing.status !== Freight.InvoiceStatus.Cancelled &&
existing.status !== Freight.InvoiceStatus.Expired
) {
throw new ConflictException('A final invoice already exists for this shipment.');
}
const description = input.description?.trim() || 'Post-offload charges (Djibouti)';
await this.billingService.generateInvoice({
source: Freight.InvoiceSource.Booking,
sourceId: bookingId,
type: GL_FINAL_INVOICE_TYPE,
companyId: booking.companyId,
companyProfileId: booking.companyProfileId,
currency: input.currency,
lines: [
{
chargeType: GL_FINAL_INVOICE_TYPE,
description,
quantity: 1,
unitRate: input.amount,
amount: input.amount,
},
],
status: Freight.InvoiceStatus.Issued,
});
await this.filesService.upsertByCode({
resourceId: bookingId,
resource: 'bookings',
code: 'final_invoice',
file,
});
// Export clearance is administratively done once the final invoice goes out.
await this.dataSource
.getRepository(ContractClearanceCycle)
.update({ bookingId, completedAt: IsNull() }, { completedAt: new Date() });
void userId;
const summary = await this.finalInvoiceSummary(bookingId);
if (!summary) throw new NotFoundException('Final invoice could not be created.');
return summary;
}
/** Customer attaches the payment slip for the final invoice. */
async uploadFinalInvoiceSlip(
bookingId: string,
file: Express.Multer.File,
): Promise<{ uploaded: boolean }> {
await this.getBooking(bookingId);
if (!file) throw new BadRequestException('No payment slip uploaded');
const invoice = await this.billingService.findInvoice(
Freight.InvoiceSource.Booking,
bookingId,
GL_FINAL_INVOICE_TYPE,
);
if (!invoice) {
throw new BadRequestException('No final invoice has been issued for this shipment.');
}
if (invoice.status === Freight.InvoiceStatus.Paid) {
throw new BadRequestException('The final invoice is already paid.');
}
if (
invoice.status === Freight.InvoiceStatus.Cancelled ||
invoice.status === Freight.InvoiceStatus.Expired
) {
throw new BadRequestException('The final invoice is no longer payable.');
}
await this.filesService.upsertByCode({
resourceId: bookingId,
resource: 'bookings',
code: 'final_invoice_slip',
file,
});
return { uploaded: true };
}
/** GL (ET or DJ) confirms the customer's slip — settles the final invoice. */
async confirmFinalInvoicePaid(
bookingId: string,
userId?: string,
): Promise<Freight.ClearanceFinalInvoiceSummary> {
await this.getBooking(bookingId);
const invoice = await this.billingService.findInvoice(
Freight.InvoiceSource.Booking,
bookingId,
GL_FINAL_INVOICE_TYPE,
);
if (!invoice) {
throw new BadRequestException('No final invoice has been issued for this shipment.');
}
if (invoice.status !== Freight.InvoiceStatus.Paid) {
const files = await this.filesService.findByResource(bookingId, 'bookings');
if (!files.some((f) => f.code === 'final_invoice_slip')) {
throw new BadRequestException(
'The customer has not attached a payment slip yet.',
);
}
await this.billingService.markInvoiceAsPaid(invoice.id);
}
void userId;
const summary = await this.finalInvoiceSummary(bookingId);
if (!summary) throw new NotFoundException('Final invoice not found.');
return summary;
}
/** Final-invoice state joined with its document + slip files, for clearance views. */
async finalInvoiceSummary(
bookingId: string,
): Promise<Freight.ClearanceFinalInvoiceSummary | null> {
const invoice = await this.billingService.findInvoice(
Freight.InvoiceSource.Booking,
bookingId,
GL_FINAL_INVOICE_TYPE,
);
if (!invoice) return null;
const files = await this.filesService.findByResource(bookingId, 'bookings');
const toRef = (code: string) => {
const f = files.find((x) => x.code === code);
return f ? { id: f.id, name: f.name, url: f.url } : null;
};
const line = await this.dataSource
.getRepository(InvoiceLine)
.findOne({ where: { invoiceId: invoice.id } });
return {
id: invoice.id,
invoiceNumber: invoice.invoiceNumber,
status: invoice.status,
totalAmount: Number(invoice.totalAmount),
currency: invoice.currency,
description: line?.description ?? null,
invoiceFile: toRef('final_invoice'),
slipFile: toRef('final_invoice_slip'),
confirmedAt: invoice.paidAt ? new Date(invoice.paidAt).toISOString() : null,
};
}
/**
* GL ET uploads export transport document after wagon allocation (export ONE_TIME).
*/

View File

@@ -107,8 +107,12 @@ describe('belongsOnDjClearanceQueue', () => {
).toBe(true);
});
it('excludes import contracts still on Ethiopia-side clearance only', () => {
expect(belongsOnDjClearanceQueue('IMPORT', null, [])).toBe(false);
it('keeps import contracts from the start — DO upload is un-gated', () => {
expect(belongsOnDjClearanceQueue('IMPORT', null, [])).toBe(true);
});
it('excludes export contracts with no DJ activity or RO hold', () => {
expect(belongsOnDjClearanceQueue('EXPORT', null, [])).toBe(false);
});
});

View File

@@ -3,7 +3,6 @@ import {
Alert,
Badge,
Button,
FileInput,
Group,
NumberInput,
Paper,
@@ -19,7 +18,6 @@ import {
TransitPermitMultiUpload,
type TransitPermitUploadedRow,
} from "@/components/contracts/TransitPermitMultiUpload";
import { DateInput } from "@mantine/dates";
import {
AlertTriangle,
CheckCircle2,
@@ -35,6 +33,7 @@ import type { Freight } from "@edr/types";
import toast from "react-hot-toast";
import { SectionCard } from "@/components/bookings/detail/SectionCard";
import { ExportClearanceStepper } from "@/components/contracts/ExportClearanceStepper";
import { PhasedDocumentUploadField } from "@/components/contracts/PhasedDocumentUploadField";
import {
findWorkflowFile,
@@ -47,7 +46,7 @@ import { FREIGHT_PERMS, hasPermission } from "@/lib/permissions";
type RoleMode = "ET" | "DJ" | "ALL";
type ClearanceViewLike = Pick<
export type ClearanceViewLike = Pick<
Freight.ContractClearanceView,
| "nextAction"
| "dutyRequired"
@@ -60,11 +59,20 @@ type ClearanceViewLike = Pick<
| "exportClearanceFinalized"
| "allApproved"
| "t1"
| "train"
| "gatepassGranted"
| "gatepassAt"
| "t1Closed"
| "t1ClosedAt"
| "offloaded"
| "finalInvoice"
| "vesselDepartureDate"
| "linkedBookingId"
> & { operationReady?: boolean };
type MilestoneRow = NonNullable<ClearanceViewLike["milestones"]>[number];
export type MilestoneRow = NonNullable<ClearanceViewLike["milestones"]>[number];
function isMilestoneDone(
export function isMilestoneDone(
milestones: MilestoneRow[] | undefined,
code: string,
): boolean {
@@ -72,7 +80,7 @@ function isMilestoneDone(
return m?.status === "COMPLETED" || m?.status === "SKIPPED";
}
function isBookingMilestoneDone(
export function isBookingMilestoneDone(
milestones: MilestoneRow[] | undefined,
code: string,
): boolean {
@@ -524,91 +532,24 @@ export function PhasedClearanceActionPanel({
}
return (
<Stack gap="md">
{clearance.roHold && clearance.roHoldReason ? (
<Alert color="orange" icon={<AlertTriangle size={16} />} title="Release Order on hold">
{clearance.roHoldReason}
</Alert>
) : null}
{showDj && canDj ? (
useUploadModals ? (
<ReleaseOrderActions
entityId={entityId}
isBooking={isBooking}
clearance={clearance}
workflowFiles={workflowFiles}
onUploadRoRequest={onUploadRoRequest}
onChanged={onChanged}
onViewFile={onViewFile}
onDownloadFile={onDownloadFile}
/>
) : (
<ReleaseOrderCard
entityId={entityId}
isBooking={isBooking}
clearance={clearance}
onChanged={onChanged}
/>
)
) : null}
{showEt && canEt ? (
<DeclarationStep
entityId={entityId}
isBooking={isBooking}
workflowFiles={workflowFiles}
onChanged={onChanged}
onViewFile={onViewFile}
onDownloadFile={onDownloadFile}
/>
) : null}
{showEt && canEt ? (
<ExportReleaseCard
entityId={entityId}
isBooking={isBooking}
clearance={clearance}
onChanged={onChanged}
/>
) : null}
{(clearance.bookingReady || clearance.operationReady) &&
bookingCreateHref &&
!bookingCreated &&
showEt &&
canEt ? (
<SectionCard icon={Ship} title="Create booking" accent="edr-green">
<Text size="sm" c="dimmed" mb="sm">
Pre-booking clearance is complete. Create the shipment booking for the customer.
</Text>
<Button component="a" href={bookingCreateHref} color="edr-green">
Create shipment booking
</Button>
</SectionCard>
) : bookingCreated && showEt ? (
<SectionCard icon={Ship} title="Create booking" accent="edr-green">
<StepStatus
done
pendingLabel=""
doneLabel="Shipment booking has been created for this contract."
/>
</SectionCard>
) : null}
{bookingCreated && showEt && canEt && bookingId ? (
<ExportPostBookingSection
<ExportClearanceStepper
contractId={contractId}
bookingId={bookingId}
clearance={clearance}
bookingMilestones={bookingMilestones}
workflowFiles={workflowFiles}
showEt={showEt}
canEt={canEt}
showDj={showDj}
canDj={canDj}
onChanged={onChanged}
bookingCreateHref={bookingCreateHref}
onViewFile={onViewFile}
onDownloadFile={onDownloadFile}
useUploadModals={useUploadModals}
onUploadRoRequest={onUploadRoRequest}
bookingCreated={bookingCreated}
bookingMilestones={bookingMilestones}
/>
) : null}
</Stack>
);
}
@@ -776,7 +717,7 @@ function ImportT1Section({
);
}
function StepStatus({
export function StepStatus({
done,
pendingLabel,
doneLabel,
@@ -805,7 +746,7 @@ function StepStatus({
);
}
function DeclarationStep({
export function DeclarationStep({
entityId,
isBooking,
onChanged,
@@ -1171,411 +1112,3 @@ function DeliveryOrderStep({
);
}
function ReleaseOrderActions({
entityId,
isBooking,
clearance,
workflowFiles = [],
onUploadRoRequest,
onChanged,
onViewFile,
onDownloadFile,
}: {
entityId: string;
isBooking: boolean;
clearance: ClearanceViewLike & { vesselDepartureDate?: string | null };
workflowFiles?: Freight.ClearanceWorkflowFile[];
onUploadRoRequest?: () => void;
onChanged?: () => void;
onViewFile?: (file: { name: string; url: string }) => void;
onDownloadFile?: (file: { id: string; name: string }) => void;
}) {
const [amendLoading, setAmendLoading] = useState(false);
const roFile = findWorkflowFile(workflowFiles, "release_order");
return (
<Paper withBorder radius="md" p="md">
<Text fw={600} size="sm" mb="sm">
Release Order
</Text>
<Stack gap="sm">
{roFile ? (
<PhasedUploadedFileRow
label="Release Order"
file={roFile}
onView={onViewFile}
onDownload={onDownloadFile}
/>
) : null}
{clearance.vesselDepartureDate ? (
<Text size="sm" c="dimmed">
Vessel departure:{" "}
{new Date(clearance.vesselDepartureDate).toLocaleDateString()}
</Text>
) : null}
<Group>
{onUploadRoRequest ? (
<Button color="edr-green" leftSection={<Upload size={16} />} onClick={onUploadRoRequest}>
{roFile ? "Replace RO" : "Upload RO"}
</Button>
) : null}
<Button
variant="light"
color="orange"
loading={amendLoading}
onClick={async () => {
setAmendLoading(true);
try {
if (isBooking) {
await bookingsService.requestRoAmendment(
entityId,
"Port amendment requested — vessel window too short.",
);
} else {
await contractsService.requestRoAmendment(
entityId,
"Port amendment requested — vessel window too short.",
);
}
toast.success("Amendment request recorded");
onChanged?.();
} catch (e) {
toast.error(e instanceof Error ? e.message : "Failed");
} finally {
setAmendLoading(false);
}
}}
>
Request amendment
</Button>
</Group>
</Stack>
</Paper>
);
}
function ReleaseOrderCard({
entityId,
isBooking,
clearance,
onChanged,
}: {
entityId: string;
isBooking: boolean;
clearance: ClearanceViewLike & { vesselDepartureDate?: string | null };
onChanged?: () => void;
}) {
const [file, setFile] = useState<File | null>(null);
const [vesselDate, setVesselDate] = useState<Date | null>(
clearance.vesselDepartureDate ? new Date(clearance.vesselDepartureDate) : null,
);
const [loading, setLoading] = useState(false);
const [amendLoading, setAmendLoading] = useState(false);
return (
<Paper withBorder radius="md" p="md">
<Text fw={600} size="sm" mb="sm">
Release Order
</Text>
<Stack gap="sm">
<FileInput label="Release Order" value={file} onChange={setFile} size="sm" />
<DateInput
label="Vessel departure date"
value={vesselDate}
onChange={(v) => setVesselDate(v ? new Date(v) : null)}
size="sm"
/>
<Group>
<Button
color="edr-green"
loading={loading}
disabled={!file || !vesselDate}
onClick={async () => {
if (!file || !vesselDate) return;
setLoading(true);
try {
const iso = vesselDate.toISOString().slice(0, 10);
const result = isBooking
? await bookingsService.uploadReleaseOrder(entityId, file, iso)
: await contractsService.uploadReleaseOrder(entityId, file, iso);
if (result.hold) {
toast.error(result.holdReason ?? "Vessel date too soon");
} else {
toast.success("Release Order accepted");
}
onChanged?.();
} catch (e) {
toast.error(e instanceof Error ? e.message : "Upload failed");
} finally {
setLoading(false);
}
}}
>
Upload RO
</Button>
<Button
variant="light"
color="orange"
loading={amendLoading}
onClick={async () => {
setAmendLoading(true);
try {
if (isBooking) {
await bookingsService.requestRoAmendment(
entityId,
"Port amendment requested — vessel window too short.",
);
} else {
await contractsService.requestRoAmendment(
entityId,
"Port amendment requested — vessel window too short.",
);
}
toast.success("Amendment request recorded");
onChanged?.();
} catch (e) {
toast.error(e instanceof Error ? e.message : "Failed");
} finally {
setAmendLoading(false);
}
}}
>
Request amendment
</Button>
</Group>
</Stack>
</Paper>
);
}
function ExportReleaseCard({
entityId,
isBooking,
clearance,
onChanged,
}: {
entityId: string;
isBooking: boolean;
clearance: ClearanceViewLike;
onChanged?: () => void;
}) {
const [loading, setLoading] = useState(false);
const done = clearance.bookingReady || clearance.operationReady;
return (
<Paper withBorder radius="md" p="md">
<Text fw={600} size="sm" mb="sm">
Export release
</Text>
<Button
color="edr-green"
loading={loading}
disabled={Boolean(done)}
onClick={async () => {
setLoading(true);
try {
if (isBooking) {
await bookingsService.confirmExportRelease(entityId);
} else {
await contractsService.confirmExportRelease(entityId);
}
toast.success("Export released — ready for booking");
onChanged?.();
} catch (e) {
toast.error(e instanceof Error ? e.message : "Failed");
} finally {
setLoading(false);
}
}}
>
Confirm export release
</Button>
</Paper>
);
}
function ExportPostBookingSection({
contractId,
bookingId,
clearance,
bookingMilestones,
workflowFiles = [],
onChanged,
onViewFile,
onDownloadFile,
}: {
contractId?: string;
bookingId: string;
clearance: ClearanceViewLike;
bookingMilestones: MilestoneRow[];
workflowFiles?: Freight.ClearanceWorkflowFile[];
onChanged?: () => void;
onViewFile?: (file: { name: string; url: string }) => void;
onDownloadFile?: (file: { id: string; name: string }) => void;
}) {
const wagonAllocated = isBookingMilestoneDone(bookingMilestones, "WAGON_ALLOCATED");
const paymentSettled = isBookingMilestoneDone(bookingMilestones, "FREIGHT_PAYMENT_SETTLED");
const transitUploaded = isBookingMilestoneDone(bookingMilestones, "EXPORT_TRANSPORT_ISSUED");
const finalized = Boolean(clearance.exportClearanceFinalized);
return (
<SectionCard icon={Truck} title="Post-booking clearance" accent="edr-green">
<Stack gap="md">
<Text size="sm" c="dimmed">
After the customer pays and operations allocates wagons, upload the transit
permit and finalize export clearance.
</Text>
{!paymentSettled ? (
<Alert color="blue" variant="light" icon={<Clock size={16} />}>
Waiting for the customer to pay freight charges.
</Alert>
) : null}
{paymentSettled && !wagonAllocated ? (
<Alert color="yellow" variant="light" icon={<Clock size={16} />}>
Waiting for operations to allocate wagons before the transit permit can be
uploaded.
</Alert>
) : null}
{wagonAllocated && !transitUploaded ? (
<ExportTransitPermitStep
bookingId={bookingId}
workflowFiles={workflowFiles}
onChanged={onChanged}
onViewFile={onViewFile}
onDownloadFile={onDownloadFile}
/>
) : null}
{transitUploaded ? (
<StepStatus
done
pendingLabel=""
doneLabel="Transit permit uploaded."
/>
) : null}
{transitUploaded && !finalized && contractId ? (
<FinalizeExportClearanceStep contractId={contractId} onChanged={onChanged} />
) : null}
{finalized ? (
<StepStatus
done
pendingLabel=""
doneLabel="Export clearance finalized."
/>
) : null}
</Stack>
</SectionCard>
);
}
function exportTransitFilesFromWorkflow(
workflowFiles: Freight.ClearanceWorkflowFile[],
): TransitPermitUploadedRow[] {
return workflowFiles
.filter((f) => f.category === "transit" && f.file)
.map((f) => ({
code: f.code,
label: f.label,
file: f.file!,
}));
}
function ExportTransitPermitStep({
bookingId,
workflowFiles = [],
replaceMode = false,
onChanged,
onViewFile,
onDownloadFile,
}: {
bookingId: string;
workflowFiles?: Freight.ClearanceWorkflowFile[];
replaceMode?: boolean;
onChanged?: () => void;
onViewFile?: (file: { name: string; url: string }) => void;
onDownloadFile?: (file: { id: string; name: string }) => void;
}) {
const uploaded = exportTransitFilesFromWorkflow(workflowFiles);
const hasUploaded = uploaded.length > 0;
if (hasUploaded && !replaceMode) {
return (
<Stack gap="sm">
<Text size="sm" fw={700}>
Transit Permit
</Text>
{uploaded.map((row) => (
<PhasedUploadedFileRow
key={row.code}
label={row.label}
file={row.file}
onView={onViewFile}
onDownload={onDownloadFile}
/>
))}
</Stack>
);
}
return (
<TransitPermitMultiUpload
replaceMode={replaceMode || hasUploaded}
uploaded={uploaded}
fileFieldPrefix="export_transport_document"
onViewFile={onViewFile}
onDownloadFile={onDownloadFile}
onSubmit={async (payload) => {
try {
await contractsService.uploadTransportDocument(bookingId, payload);
toast.success(replaceMode ? "Transit permit updated" : "Transit permit uploaded");
onChanged?.();
} catch (e) {
toast.error(e instanceof Error ? e.message : "Upload failed");
throw e;
}
}}
/>
);
}
function FinalizeExportClearanceStep({
contractId,
onChanged,
}: {
contractId: string;
onChanged?: () => void;
}) {
const [loading, setLoading] = useState(false);
return (
<Stack gap="sm">
<Text size="sm" c="dimmed">
Confirm that export clearance is complete now that the transit permit is on file.
</Text>
<Button
color="edr-green"
loading={loading}
leftSection={<PackageCheck size={16} />}
onClick={async () => {
setLoading(true);
try {
await contractsService.finalizeExportClearance(contractId);
toast.success("Export clearance finalized");
onChanged?.();
} catch (e) {
toast.error(e instanceof Error ? e.message : "Failed");
} finally {
setLoading(false);
}
}}
>
Finalize clearance
</Button>
</Stack>
);
}

View File

@@ -60,6 +60,7 @@ export const QUERY_KEYS = {
["contracts", "clearance-queue", region ?? "ET"] as const,
clearanceHistory: (region?: string) =>
["contracts", "clearance-history", region ?? "ET"] as const,
djSchedules: ["contracts", "clearance-dj-schedules"] as const,
milestones: (id: string) => ["contracts", "milestones", id] as const,
capacity: (id: string) => ["contracts", "capacity", id] as const,
bookingMilestones: (bookingId: string) =>

View File

@@ -215,6 +215,15 @@ export const URL_CONSTANTS = {
`/contracts/bookings/${bookingId}/t1-documents`,
BOOKING_T1_CLOSE: (bookingId: string) =>
`/contracts/bookings/${bookingId}/t1-close`,
CLEARANCE_DJ_SCHEDULES: "/contracts/clearance/dj-schedules",
CLEARANCE_SCHEDULE_GATEPASS: (scheduleId: string) =>
`/contracts/clearance/schedules/${scheduleId}/gatepass`,
BOOKING_GATEPASS: (bookingId: string) =>
`/contracts/bookings/${bookingId}/gatepass`,
BOOKING_FINAL_INVOICE: (bookingId: string) =>
`/contracts/bookings/${bookingId}/final-invoice`,
BOOKING_FINAL_INVOICE_CONFIRM: (bookingId: string) =>
`/contracts/bookings/${bookingId}/final-invoice/confirm`,
BOOKING_INCIDENTS: (bookingId: string) =>
`/contracts/bookings/${bookingId}/incidents`,
},

View File

@@ -68,6 +68,15 @@ export function useDjClearanceQueue(enabled = true) {
});
}
/** Train schedules carrying customs bookings — GL DJ gate-pass table. */
export function useDjClearanceSchedules(enabled = true) {
return useQuery({
queryKey: QUERY_KEYS.CONTRACTS.djSchedules,
queryFn: () => contractsService.getDjClearanceSchedules(),
enabled,
});
}
/** Path A self-clearance queue (Operations reviews non-customs contracts). */
export function useOpsClearanceQueue(enabled = true) {
return useQuery({

View File

@@ -29,6 +29,7 @@ import {
import { PhasedClearanceActionPanel } from "@/components/contracts/PhasedClearanceActionPanel";
import { findWorkflowFile } from "@/components/contracts/PhasedUploadedFileRow";
import { useFileViewer } from "@/hooks/useFileViewer";
import { useBookingMilestones } from "@/hooks/contracts/useContracts";
import { contractsService } from "@/services/contracts.service";
import { bookingsService } from "@/services/bookings.service";
import { downloadBookingFile } from "@/services/files.service";
@@ -85,6 +86,11 @@ export default function GlClearanceDetailPage() {
enabled: Boolean(id),
});
const linkedBookingId =
data?.kind === "contract" ? (data.clearance.linkedBookingId ?? undefined) : undefined;
const { data: bookingMilestones, refetch: refetchBookingMilestones } =
useBookingMilestones(linkedBookingId);
if (isLoading) {
return (
<PageContainer>
@@ -197,7 +203,13 @@ export default function GlClearanceDetailPage() {
<Grid.Col span={{ base: 12, lg: 5 }}>
<PhasedClearanceActionPanel
contractId={data.kind === "contract" ? id : undefined}
bookingId={data.kind === "booking" ? id : undefined}
bookingId={data.kind === "booking" ? id : linkedBookingId}
bookingCreated={data.kind === "booking" || Boolean(linkedBookingId)}
bookingMilestones={
data.kind === "booking"
? (data.clearance.milestones ?? [])
: (bookingMilestones ?? [])
}
clearance={data.clearance}
tradeDirection={data.tradeDirection}
workflowFiles={workflowFiles}
@@ -205,7 +217,10 @@ export default function GlClearanceDetailPage() {
useUploadModals
onUploadDoRequest={() => setUploadKind("do")}
onUploadRoRequest={() => setUploadKind("ro")}
onChanged={() => void refetch()}
onChanged={() => {
void refetch();
void refetchBookingMilestones();
}}
onViewFile={view}
onDownloadFile={(f) => void downloadBookingFile(f.id, f.name)}
/>

View File

@@ -1,30 +1,172 @@
import { useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import { Badge, Card, Group, Loader, Stack, Tabs, Text } from "@mantine/core";
import { ChevronRight, Container, Ship } from "lucide-react";
import {
Badge,
Button,
Card,
Group,
Loader,
Modal,
Stack,
Tabs,
Text,
} from "@mantine/core";
import { DateTimePicker } from "@mantine/dates";
import { ChevronRight, Ship, Train, Truck } from "lucide-react";
import { DataTable, type ColumnDef } from "@edr/ui-common";
import type { Freight } from "@edr/types";
import toast from "react-hot-toast";
import { PageContainer } from "@/components/page/PageContainer";
import { PageHeader } from "@/components/page/PageHeader";
import { useDjClearanceQueue } from "@/hooks/contracts/useContracts";
import { useBookingDjClearanceQueue } from "@/hooks/bookings/useBookings";
import {
useDjClearanceQueue,
useDjClearanceSchedules,
} from "@/hooks/contracts/useContracts";
import { contractsService } from "@/services/contracts.service";
export default function GlDjiboutiClearanceListPage() {
const navigate = useNavigate();
const { data: contractQueue, isLoading: contractsLoading } = useDjClearanceQueue();
const { data: bookingQueue, isLoading: bookingsLoading } = useBookingDjClearanceQueue();
const schedulesQuery = useDjClearanceSchedules();
const contractItems = contractQueue?.items ?? [];
const bookingItems = bookingQueue ?? [];
const scheduleItems = schedulesQuery.data ?? [];
const [gatepassTarget, setGatepassTarget] =
useState<Freight.DjClearanceSchedule | null>(null);
const [gatepassAt, setGatepassAt] = useState<Date | null>(new Date());
const [granting, setGranting] = useState(false);
const columns = useMemo<ColumnDef<Freight.DjClearanceSchedule>[]>(
() => [
{
header: "Train",
accessorKey: "trainNumber",
cell: ({ row }) => (
<Text size="sm" fw={700}>
{row.original.trainNumber ?? "—"}
</Text>
),
},
{
header: "Route",
id: "route",
cell: ({ row }) => (
<Text size="sm">
{row.original.origin ?? "—"} {row.original.destination ?? "—"}
</Text>
),
},
{
header: "Scheduled departure",
id: "scheduled",
cell: ({ row }) => (
<Text size="sm">
{row.original.scheduledDepartureDate
? new Date(row.original.scheduledDepartureDate).toLocaleDateString()
: "—"}
</Text>
),
},
{
header: "Departed",
id: "departed",
cell: ({ row }) => (
<Text size="sm">
{row.original.actualDepartureAt
? new Date(row.original.actualDepartureAt).toLocaleString()
: "—"}
</Text>
),
},
{
header: "Arrived",
id: "arrived",
cell: ({ row }) => (
<Text size="sm">
{row.original.actualArrivalAt
? new Date(row.original.actualArrivalAt).toLocaleString()
: "—"}
</Text>
),
},
{
header: "Status",
accessorKey: "status",
cell: ({ row }) => (
<Badge variant="light" color={statusColor(row.original.status)} radius="sm">
{row.original.status}
</Badge>
),
},
{
header: "Customs bookings",
id: "customs",
cell: ({ row }) => {
const bookings = row.original.customsBookings;
const directions = [...new Set(bookings.map((b) => b.tradeDirection))];
return (
<Group gap={6} wrap="nowrap">
<Badge variant="light" color="edr-green" radius="sm">
{bookings.length}
</Badge>
{directions.map((d) => (
<Badge key={d} variant="outline" color={d === "IMPORT" ? "edr-green" : "blue"} radius="sm">
{d}
</Badge>
))}
</Group>
);
},
},
{
header: "Gate pass",
id: "gatepass",
cell: ({ row }) => {
const bookings = row.original.customsBookings;
const allGranted =
bookings.length > 0 && bookings.every((b) => b.gatepassGranted);
const grantedAt = bookings.find((b) => b.gatepassAt)?.gatepassAt ?? null;
if (allGranted) {
return (
<Badge variant="light" color="edr-green" radius="sm">
Granted{grantedAt ? ` · ${new Date(grantedAt).toLocaleString()}` : ""}
</Badge>
);
}
return (
<Button
size="xs"
color="edr-green"
leftSection={<Truck size={14} />}
onClick={(e) => {
e.stopPropagation();
setGatepassAt(new Date());
setGatepassTarget(row.original);
}}
>
Gate pass
</Button>
);
},
},
],
[],
);
return (
<PageContainer>
<PageHeader
title="GL Djibouti — Clearance"
subtitle="All customs contracts and bookings handed off to Djibouti GL — stays visible after DO/RO upload and booking creation."
subtitle="Customs contracts handed off to Djibouti GL, plus train schedules for gate-pass control."
/>
<Tabs defaultValue="contracts" keepMounted={false}>
<Tabs.List mb="md">
<Tabs.Tab value="contracts">Contracts ({contractItems.length})</Tabs.Tab>
<Tabs.Tab value="bookings">Bookings ({bookingItems.length})</Tabs.Tab>
<Tabs.Tab value="schedules" leftSection={<Train size={14} />}>
Schedules ({scheduleItems.length})
</Tabs.Tab>
</Tabs.List>
<Tabs.Panel value="contracts">
@@ -36,8 +178,7 @@ export default function GlDjiboutiClearanceListPage() {
<Stack gap="sm">
{contractItems.length === 0 ? (
<Text c="dimmed" ta="center" py="xl">
No Djibouti customs contracts yet. Items appear here once Ethiopia-side
pre-clearance is finalized.
No Djibouti customs contracts yet.
</Text>
) : (
contractItems.map((c) => (
@@ -73,51 +214,113 @@ export default function GlDjiboutiClearanceListPage() {
)}
</Tabs.Panel>
<Tabs.Panel value="bookings">
{bookingsLoading ? (
<Group justify="center" py={60}>
<Loader color="edr-green" />
</Group>
) : (
<Stack gap="sm">
{bookingItems.length === 0 ? (
<Text c="dimmed" ta="center" py="xl">
No Djibouti customs bookings yet.
</Text>
) : (
bookingItems.map((b) => (
<Card
key={b.id}
withBorder
radius="md"
padding="md"
style={{ cursor: "pointer" }}
onClick={() => navigate(`/dashboard/gl-djibouti/clearance/${b.id}`)}
>
<Group justify="space-between" wrap="nowrap">
<Group gap="sm">
<Container size={18} className="text-[color:var(--freight-brand)]" />
<div>
<Text fw={700}>{b.reference}</Text>
<Text size="sm" c="dimmed">
{b.tradeDirection} · {b.status}
</Text>
</div>
</Group>
<Group gap="xs">
<Badge variant="light" color="blue">
Booking
</Badge>
<ChevronRight size={18} className="text-muted-foreground" />
</Group>
</Group>
</Card>
))
)}
</Stack>
)}
<Tabs.Panel value="schedules">
<DataTable
columns={columns}
data={scheduleItems}
status={
schedulesQuery.isLoading
? "loading"
: schedulesQuery.isError
? "error"
: "success"
}
error={
schedulesQuery.isError
? {
message: "Failed to load train schedules.",
onRetry: () => void schedulesQuery.refetch(),
}
: undefined
}
emptyMessage="No train schedules carry customs bookings yet."
/>
</Tabs.Panel>
</Tabs>
<Modal
opened={gatepassTarget != null}
onClose={() => setGatepassTarget(null)}
title={
<Group gap={8}>
<Truck size={18} />
<Text fw={700}>
Gate pass train {gatepassTarget?.trainNumber ?? ""}
</Text>
</Group>
}
radius="md"
size="sm"
>
<Stack gap="md">
<Text size="sm" c="dimmed">
Grants the gate pass for all{" "}
{gatepassTarget?.customsBookings.length ?? 0} customs booking
{(gatepassTarget?.customsBookings.length ?? 0) === 1 ? "" : "s"} on this
train.
</Text>
<DateTimePicker
label="Gate pass time"
value={gatepassAt}
onChange={(v) => setGatepassAt(v ? new Date(v) : null)}
required
/>
<Group justify="flex-end">
<Button
variant="default"
onClick={() => setGatepassTarget(null)}
disabled={granting}
>
Cancel
</Button>
<Button
color="edr-green"
loading={granting}
leftSection={<Truck size={16} />}
onClick={async () => {
if (!gatepassTarget) return;
setGranting(true);
try {
const result = await contractsService.grantScheduleGatepass(
gatepassTarget.id,
(gatepassAt ?? new Date()).toISOString(),
);
if (result.skipped.length > 0) {
toast.error(
`${result.granted} granted, ${result.skipped.length} skipped: ${result.skipped[0]?.error ?? ""}`,
);
} else {
toast.success(
`Gate pass granted for ${result.granted} booking${result.granted === 1 ? "" : "s"}`,
);
}
setGatepassTarget(null);
void schedulesQuery.refetch();
} catch (e) {
toast.error(e instanceof Error ? e.message : "Failed");
} finally {
setGranting(false);
}
}}
>
Grant gate pass
</Button>
</Group>
</Stack>
</Modal>
</PageContainer>
);
}
function statusColor(status: string): string {
switch (status) {
case "SCHEDULED":
return "blue";
case "DISPATCHED":
return "yellow";
case "ARRIVED":
return "edr-green";
default:
return "gray";
}
}

View File

@@ -354,6 +354,59 @@ export const contractsService = {
return unwrap(response.data) as Freight.ClearanceT1State;
},
/** Train schedules carrying customs bookings — GL DJ gate-pass table. */
getDjClearanceSchedules: async (): Promise<Freight.DjClearanceSchedule[]> => {
const response = await client.get(C.CLEARANCE_DJ_SCHEDULES);
return unwrap(response.data) as Freight.DjClearanceSchedule[];
},
/** Gate pass for every customs booking on a train schedule (captures time). */
grantScheduleGatepass: async (
scheduleId: string,
gatepassAt?: string,
): Promise<{ granted: number; skipped: Array<{ bookingId: string; error: string }> }> => {
const response = await client.post(C.CLEARANCE_SCHEDULE_GATEPASS(scheduleId), {
gatepassAt,
});
return unwrap(response.data) as {
granted: number;
skipped: Array<{ bookingId: string; error: string }>;
};
},
/** Gate pass for a single customs booking (captures time). */
grantGatepass: async (
bookingId: string,
gatepassAt?: string,
): Promise<{ bookingId: string; gatepassAt: string }> => {
const response = await client.post(C.BOOKING_GATEPASS(bookingId), { gatepassAt });
return unwrap(response.data) as { bookingId: string; gatepassAt: string };
},
/** GL DJ raises the post-offload final invoice (amount + invoice document). */
sendFinalInvoice: async (
bookingId: string,
payload: { amount: number; currency: string; description?: string; file: File },
): Promise<Freight.ClearanceFinalInvoiceSummary> => {
const form = new FormData();
form.append("amount", String(payload.amount));
form.append("currency", payload.currency);
if (payload.description) form.append("description", payload.description);
form.append("file", payload.file);
const response = await client.post(C.BOOKING_FINAL_INVOICE(bookingId), form, {
headers: { "Content-Type": "multipart/form-data" },
});
return unwrap(response.data) as Freight.ClearanceFinalInvoiceSummary;
},
/** GL (ET or DJ) confirms the payment slip — settles the final invoice. */
confirmFinalInvoicePaid: async (
bookingId: string,
): Promise<Freight.ClearanceFinalInvoiceSummary> => {
const response = await client.post(C.BOOKING_FINAL_INVOICE_CONFIRM(bookingId));
return unwrap(response.data) as Freight.ClearanceFinalInvoiceSummary;
},
// ── Path A self-clearance (Operations review) ──
getOpsClearanceQueue: async (): Promise<PaginatedContracts> => {
const response = await client.get<PaginatedContracts>(

View File

@@ -131,6 +131,8 @@ export const URL_CONSTANTS = {
`/api/contracts/bookings/${bookingId}/milestones`,
BOOKING_DUTY_SLIP: (bookingId: string) =>
`/api/contracts/bookings/${bookingId}/duty-slip`,
BOOKING_FINAL_INVOICE_SLIP: (bookingId: string) =>
`/api/contracts/bookings/${bookingId}/final-invoice-slip`,
CAPACITY: (id: string) => `/api/contracts/${id}/capacity`,
BOOKING_REQUESTS: (id: string) => `/api/contracts/${id}/booking-requests`,
BOOKING_REQUEST_CANCEL: (reqId: string) =>

View File

@@ -12,6 +12,7 @@ import {
Button,
Card,
Center,
FileInput,
Group,
Loader,
Paper,
@@ -174,7 +175,7 @@ export default function ContractDetailPage() {
!!contract &&
contract.customsClearingEnabled &&
contract.contractKind === "ONE_TIME";
const { data: clearanceView } = useQuery({
const { data: clearanceView, refetch: refetchClearance } = useQuery({
...api.contracts.getClearance.queryOptions({ input: { id: id! } }),
enabled: !!id && (inClearance || isPhasedCustomsClearance),
});
@@ -583,6 +584,15 @@ export default function ContractDetailPage() {
<ContractClearanceWorkflowBanner contract={contract} />
) : null}
{clearanceView?.finalInvoice && clearanceView?.linkedBookingId ? (
<FinalInvoiceDueCard
invoice={clearanceView.finalInvoice}
bookingId={clearanceView.linkedBookingId}
onView={view}
onChanged={() => void refetchClearance()}
/>
) : null}
{canUploadClearance && (
<Paper
withBorder
@@ -1447,3 +1457,151 @@ function FactCell({
</Group>
);
}
/**
* Post-offload final invoice from GL Djibouti (export): shows the due amount +
* invoice document; the customer pays offline and attaches the payment slip
* here, then GL confirms and the badge flips to PAID.
*/
function FinalInvoiceDueCard({
invoice,
bookingId,
onView,
onChanged,
}: {
invoice: NonNullable<Freight.ContractClearanceView["finalInvoice"]>;
bookingId: string;
onView: (file: { name: string; url: string }) => void;
onChanged: () => void;
}) {
const [slip, setSlip] = useState<File | null>(null);
const [uploading, setUploading] = useState(false);
const paid = invoice.status === "PAID";
return (
<Paper
withBorder
radius="lg"
p="lg"
style={{
borderColor: paid ? "#CDEBDD" : "#F2D9A6",
background: paid ? "#F6FBF8" : "#FFFBF2",
position: "relative",
overflow: "hidden",
}}
>
<Box
style={{
position: "absolute",
left: 0,
top: 0,
bottom: 0,
width: 3,
background: paid ? GREEN : "#E3A93C",
}}
/>
<Group justify="space-between" align="flex-start" wrap="wrap" gap="md">
<div>
<Group gap={8} align="center">
<FileBadge size={16} color={paid ? GREEN : "#B07C1F"} />
<Text fw={700} fz={15} c={INK}>
{paid ? "Final invoice paid" : "Final invoice due"} {" "}
{invoice.invoiceNumber}
</Text>
<Badge color={paid ? "edr-green" : "yellow"} variant="light" radius="sm">
{invoice.status}
</Badge>
</Group>
<Text fz={20} fw={800} mt={6} c={INK}>
{invoice.totalAmount.toLocaleString()} {invoice.currency}
</Text>
{invoice.description ? (
<Text fz={13} c="dimmed" mt={2}>
{invoice.description}
</Text>
) : null}
{!paid ? (
<Text fz={13} c="#9A6B1F" mt={6}>
Pay the amount above and attach your payment slip Global
Logistics will confirm the payment.
</Text>
) : null}
</div>
<Stack gap="xs" miw={260}>
{invoice.invoiceFile ? (
<Button
variant="default"
radius="md"
size="sm"
leftSection={<Eye size={15} />}
onClick={() =>
onView({
name: invoice.invoiceFile!.name,
url: invoice.invoiceFile!.url,
})
}
>
View invoice
</Button>
) : null}
{invoice.slipFile ? (
<Button
variant="default"
radius="md"
size="sm"
leftSection={<Eye size={15} />}
onClick={() =>
onView({
name: invoice.slipFile!.name,
url: invoice.slipFile!.url,
})
}
>
View payment slip
</Button>
) : null}
{!paid ? (
<>
<FileInput
placeholder={
invoice.slipFile ? "Replace payment slip" : "Attach payment slip"
}
value={slip}
onChange={setSlip}
size="sm"
radius="md"
/>
<Button
color="edr-green"
radius="md"
size="sm"
loading={uploading}
disabled={!slip}
leftSection={<Upload size={15} />}
onClick={async () => {
if (!slip) return;
setUploading(true);
try {
await contractsService.uploadFinalInvoiceSlip(bookingId, slip);
setSlip(null);
toast.success("Payment slip attached");
onChanged();
} catch (e) {
toast.error(
e instanceof Error ? e.message : "Upload failed",
);
} finally {
setUploading(false);
}
}}
>
{invoice.slipFile ? "Replace slip" : "Submit payment slip"}
</Button>
</>
) : null}
</Stack>
</Group>
</Paper>
);
}

View File

@@ -318,4 +318,19 @@ export const contractsService = {
});
return data.data ?? data;
},
/** Customer attaches the payment slip for the GL final invoice (export). */
uploadFinalInvoiceSlip: async (
bookingId: string,
file: File,
): Promise<{ uploaded: boolean }> => {
const form = new FormData();
form.append("file", file);
const { data } = await client.post(
C.BOOKING_FINAL_INVOICE_SLIP(bookingId),
form,
{ headers: { "Content-Type": "multipart/form-data" } },
);
return data.data ?? data;
},
};

View File

@@ -40,6 +40,20 @@ export const CLEARANCE_WORKFLOW_FILE_CATALOG: ClearanceWorkflowFileCatalogEntry[
category: "djibouti",
tradeDirection: "IMPORT",
},
{
code: "final_invoice",
label: "Final Invoice",
uploadedBy: "gl_dj",
category: "djibouti",
tradeDirection: "EXPORT",
},
{
code: "final_invoice_slip",
label: "Final Invoice Payment Slip",
uploadedBy: "customer",
category: "djibouti",
tradeDirection: "EXPORT",
},
];
/** Legacy single-type declaration codes (still shown when already uploaded). */

View File

@@ -256,6 +256,57 @@ export interface ClearanceT1State {
closedAt?: string | null;
}
/** Train link state for the booking tied to a customs clearance flow. */
export interface ClearanceTrainState {
wagonAllocated: boolean;
departedAt: string | null;
arrivedAt: string | null;
}
/** Billing invoice `type` for the GL Djibouti post-offload final invoice. */
export const GL_FINAL_INVOICE_TYPE = "GL_FINAL";
/**
* Post-offload final invoice raised by GL Djibouti: customer pays offline and
* attaches a slip; GL (ET or DJ) confirms to mark it paid.
*/
export interface ClearanceFinalInvoiceSummary {
id: string;
invoiceNumber: string;
status: string;
totalAmount: number;
currency: string;
description?: string | null;
invoiceFile: { id: string; name: string; url: string } | null;
slipFile: { id: string; name: string; url: string } | null;
confirmedAt: string | null;
}
/** A customs booking riding a train schedule, as shown on the GL DJ schedules tab. */
export interface DjClearanceScheduleBooking {
bookingId: string;
reference: string;
tradeDirection: string;
contractId: string | null;
gatepassGranted: boolean;
gatepassAt: string | null;
}
/** Train schedule row for the GL Djibouti gate-pass table. */
export interface DjClearanceSchedule {
id: string;
trainNumber: string | null;
routeName: string | null;
origin: string | null;
destination: string | null;
status: string;
scheduledDepartureDate: string | null;
actualDepartureAt: string | null;
actualArrivalAt: string | null;
freightType: string | null;
customsBookings: DjClearanceScheduleBooking[];
}
export interface ContractClearanceView {
contractId: string;
/** Overall contract status (e.g. CLEARANCE_UNDER_REVIEW). */
@@ -299,6 +350,15 @@ export interface ContractClearanceView {
workflowFiles?: import("./clearance-files.catalog").ClearanceWorkflowFile[];
/** Import post-allocation T1 transit document state (null until a booking is linked). */
t1?: ClearanceT1State | null;
/** Train link state for the booking (both directions; null until a booking is linked). */
train?: ClearanceTrainState | null;
gatepassGranted?: boolean;
gatepassAt?: string | null;
t1Closed?: boolean;
t1ClosedAt?: string | null;
offloaded?: boolean;
/** GL Djibouti post-offload final invoice (export). */
finalInvoice?: ClearanceFinalInvoiceSummary | null;
}
export type ClearanceActorRole = "CUSTOMER" | "GL_ET" | "GL_DJ" | "OPERATIONS";
@@ -423,6 +483,7 @@ export const EXPORT_MILESTONES = [
"DEPARTED_TO_DJIBOUTI",
"ARRIVED_AT_DJIBOUTI",
"GATEPASS_GRANTED",
"T1_CLOSED",
"OFFLOADED",
] as const;

View File

@@ -557,6 +557,15 @@ export interface ClearanceView {
workflowFiles?: import("./clearance-files.catalog").ClearanceWorkflowFile[];
/** Import post-allocation T1 transit document state (null until wagon allocation). */
t1?: import("./contracts").ClearanceT1State | null;
/** Train link state for the booking (both directions). */
train?: import("./contracts").ClearanceTrainState | null;
gatepassGranted?: boolean;
gatepassAt?: string | null;
t1Closed?: boolean;
t1ClosedAt?: string | null;
offloaded?: boolean;
/** GL Djibouti post-offload final invoice (export). */
finalInvoice?: import("./contracts").ClearanceFinalInvoiceSummary | null;
}
/** Company an invoice is billed to (minimal projection). */