enhance booking and contract notification systems

- Added detailed logging for socket connection events in useBookingWindowSocket.
- Introduced new notification types for contract status and schedule updates.
- Updated notification visuals to include new icons for contract status.
- Enhanced notification href resolution for contract status and schedule updates.
- Implemented booking lifecycle notifier service for customer and staff notifications.
- Created contract notifier service for managing contract lifecycle notifications.
- Added end-to-end tests for booking window socket functionality.
This commit is contained in:
Marshal
2026-07-06 21:03:08 +00:00
parent 8bd00ea78a
commit 05b13e84a8
38 changed files with 1450 additions and 95 deletions

View File

@@ -0,0 +1,307 @@
import { Injectable, Logger } from '@nestjs/common';
import {
NotificationAudience,
NotificationType,
NotifyInput,
} from '@edr/types';
import { Booking } from './entities/booking.entity';
import { NotificationsService } from '../notifications/notifications.service';
import { NotificationInboxService } from '../notification-inbox/notification-inbox.service';
/**
* Customer + staff notifications for the booking lifecycle: review, clearance
* and operation flow. Every customer event fans out over SMS + email (direct)
* and a persisted in-app notification deep-linking to the booking detail page;
* staff events land in the backoffice inbox. All sends are fire-and-forget and
* never throw — a notification failure must not break a booking transition.
*
* NOTE: the batch/payment-window notifications (pay-now, allocated, expired,
* displaced) are handled separately by {@link BookingNotifierService} in
* train-scheduling.
*/
@Injectable()
export class BookingLifecycleNotifierService {
private readonly logger = new Logger(BookingLifecycleNotifierService.name);
constructor(
private readonly notifications: NotificationsService,
private readonly inbox: NotificationInboxService,
) {}
private ref(b: Booking): string {
return `${b.reference}${b.isGovernment ? ' (gov)' : ''}`;
}
/** Send SMS + email to the booking's company contact; log-only on failure. */
private async notifyContact(
b: Booking,
message: string,
logLabel: string,
): Promise<void> {
this.logger.log(`${logLabel}${this.ref(b)}`);
const phone = b.company?.contactPersonPhone ?? b.company?.phone ?? null;
const email = b.company?.email ?? b.company?.generalManagerEmail ?? null;
if (phone) {
try {
await this.notifications.directSend('sms', phone, message);
} catch (err) {
this.logger.warn(`SMS failed for ${this.ref(b)}: ${(err as Error).message}`);
}
}
if (email) {
try {
await this.notifications.directSend('email', email, message);
} catch (err) {
this.logger.warn(`Email failed for ${this.ref(b)}: ${(err as Error).message}`);
}
}
if (!phone && !email) {
this.logger.warn(`No contact on file for ${this.ref(b)} — notification not sent`);
}
}
/** Persist + push an in-app item to all portal users of the booking's company. */
private inApp(
b: Booking,
title: string,
body: string,
overrides: Partial<NotifyInput> = {},
): void {
if (!b.companyId) return; // government/unlinked bookings have no portal users
void this.inbox.notify({
recipients: { companyId: b.companyId },
audience: NotificationAudience.PORTAL,
type: NotificationType.BOOKING_STATUS,
title,
body,
link: `/bookings/${b.id}`,
data: { bookingId: b.id, reference: b.reference },
...overrides,
});
}
/** Persist + push an in-app item to every backoffice staff user. */
private inAppStaff(
b: Booking,
title: string,
body: string,
overrides: Partial<NotifyInput> = {},
): void {
void this.inbox.notify({
recipients: { allBackoffice: true },
audience: NotificationAudience.BACKOFFICE,
type: NotificationType.REQUEST_SUBMITTED,
title,
body,
link: `/dashboard/booking-requests/${b.id}`,
data: { bookingId: b.id, reference: b.reference },
...overrides,
});
}
// ── Customer-facing lifecycle events ───────────────────────────────────────
/** Line staff accepted intake → booking is under approval. */
accepted(b: Booking): void {
const msg =
`Your booking ${b.reference} has been accepted and is now under approval. ` +
`We will notify you once it is approved.`;
void this.notifyContact(b, msg, 'ACCEPTED');
this.inApp(b, 'Booking accepted', msg);
}
/** All approval steps complete → contract generated, ready for customer to sign. */
approved(b: Booking): void {
const msg =
`Your booking ${b.reference} has been approved. ` +
`Please review and sign your contract from the portal.`;
void this.notifyContact(b, msg, 'APPROVED');
this.inApp(b, 'Booking approved', msg);
}
/** Staff rejected the booking (intake or approval step). */
rejected(b: Booking, reason: string): void {
const msg =
`Your booking ${b.reference} was rejected. Reason: ${reason}. ` +
`Please contact us for details.`;
void this.notifyContact(b, msg, 'REJECTED');
this.inApp(b, 'Booking rejected', msg);
}
/** Staff requested changes before approval. */
changesRequested(b: Booking, note: string): void {
const msg =
`Changes were requested on your booking ${b.reference}: ${note}. ` +
`Please update and resubmit from the portal.`;
void this.notifyContact(b, msg, 'CHANGES REQUESTED');
this.inApp(b, 'Booking changes requested', msg);
}
/** A clearance document was queried and needs the customer to re-upload. */
documentQueried(b: Booking, fileKey: string, note: string): void {
const msg =
`A clearance document on booking ${b.reference} needs attention: "${fileKey}". ` +
`${note}. Please re-upload from the portal.`;
void this.notifyContact(b, msg, 'DOCUMENT QUERIED');
this.inApp(b, 'Document queried', msg, {
type: NotificationType.DOCUMENT_ACTION,
});
}
/** Clearance finalized → customer can proceed to request operation. */
clearanceReady(b: Booking): void {
const msg =
`Clearance for booking ${b.reference} is complete. ` +
`You can now proceed to request operation from the portal.`;
void this.notifyContact(b, msg, 'CLEARANCE READY');
this.inApp(b, 'Clearance complete', msg, {
type: NotificationType.CLEARANCE_DECISION,
});
}
/** Operations returned the operation request for changes. */
operationChangesRequested(b: Booking, note: string): void {
const msg =
`Your operation request for booking ${b.reference} needs changes: ${note}. ` +
`Please update and resubmit from the portal.`;
void this.notifyContact(b, msg, 'OPERATION CHANGES REQUESTED');
this.inApp(b, 'Operation request needs changes', msg);
}
/** Operation accepted → invoice ready; await payment / booking window. */
operationAccepted(b: Booking): void {
const msg =
`Your operation request for booking ${b.reference} has been accepted. ` +
`An invoice has been prepared — watch for the payment window to secure your slot.`;
void this.notifyContact(b, msg, 'OPERATION ACCEPTED');
this.inApp(b, 'Operation request accepted', msg);
}
/** Shipment started → in transit. */
inTransit(b: Booking): void {
const msg = `Your shipment for booking ${b.reference} is now in transit.`;
void this.notifyContact(b, msg, 'IN TRANSIT');
this.inApp(b, 'Shipment in transit', msg);
}
/** Shipment delivered → completed. */
completed(b: Booking): void {
const msg = `Your shipment for booking ${b.reference} has been delivered. Thank you.`;
void this.notifyContact(b, msg, 'COMPLETED');
this.inApp(b, 'Shipment delivered', msg);
}
/** Booking cancelled. */
cancelled(b: Booking, reason: string): void {
const msg = `Your booking ${b.reference} has been cancelled. Reason: ${reason}.`;
void this.notifyContact(b, msg, 'CANCELLED');
this.inApp(b, 'Booking cancelled', msg);
}
// ── Clearance milestones needing customer action ──────────────────────────
/** GL advised duty & tax — the customer must pay and upload the slip. */
dutyAdvised(b: Booking, amount: number, currency: string): void {
const msg =
`Duty & tax of ${amount} ${currency} has been advised for booking ${b.reference}. ` +
`Please pay and upload the payment slip from the portal.`;
void this.notifyContact(b, msg, 'DUTY ADVISED');
this.inApp(b, 'Duty & tax advised', msg, {
type: NotificationType.INVOICE_ISSUED,
});
}
/** GL advised the post-arrival additional duty round (import). */
secondDutyAdvised(b: Booking, amount: number, currency: string): void {
const msg =
`Additional duty & tax of ${amount} ${currency} has been advised for booking ${b.reference}. ` +
`Please pay and upload the payment slip from the portal.`;
void this.notifyContact(b, msg, 'SECOND DUTY ADVISED');
this.inApp(b, 'Additional duty & tax advised', msg, {
type: NotificationType.INVOICE_ISSUED,
});
}
/** GL raised the final (post-offload) invoice — customer pays + uploads slip. */
finalInvoiceCreated(b: Booking, amount: number, currency: string): void {
const msg =
`A final invoice of ${amount} ${currency} has been issued for booking ${b.reference}. ` +
`Please pay and upload the payment slip from the portal.`;
void this.notifyContact(b, msg, 'FINAL INVOICE');
this.inApp(b, 'Final invoice issued', msg, {
type: NotificationType.INVOICE_ISSUED,
});
}
/** GL confirmed the final-invoice payment slip. */
finalInvoicePaid(b: Booking): void {
const msg = `Your final invoice payment for booking ${b.reference} has been confirmed. Thank you.`;
void this.notifyContact(b, msg, 'FINAL INVOICE PAID');
this.inApp(b, 'Final invoice paid', msg, {
type: NotificationType.INVOICE_ISSUED,
});
}
// ── Staff-facing (backoffice inbox) ────────────────────────────────────────
/** Customer submitted a booking for review. */
submittedToStaff(b: Booking): void {
this.inAppStaff(
b,
'New booking submitted',
`Booking ${this.ref(b)} was submitted and is awaiting intake review.`,
);
}
/** Customer signed the booking contract. */
customerSignedToStaff(b: Booking): void {
this.inAppStaff(
b,
'Customer signed booking contract',
`The contract for booking ${this.ref(b)} was signed by the customer.`,
);
}
/** Customer requested operation (picked a shipment day). */
operationRequestedToStaff(b: Booking): void {
this.inAppStaff(
b,
'Operation requested',
`Booking ${this.ref(b)} requested operation — review capacity, documents and route.`,
);
}
/** Customer uploaded clearance documents — review is next. */
clearanceDocsUploadedToStaff(b: Booking): void {
this.inAppStaff(
b,
'Clearance documents uploaded',
`Customer uploaded clearance documents for booking ${this.ref(b)} — review them in the clearance queue.`,
{
type: NotificationType.CLEARANCE_REVIEW,
link: `/dashboard/bookings/${b.id}/clearance`,
},
);
}
/** Customer uploaded a duty/tax payment slip — GL verifies it. */
dutySlipUploadedToStaff(b: Booking, round: 'first' | 'second' | 'final'): void {
const label =
round === 'final'
? 'final invoice'
: round === 'second'
? 'additional duty & tax'
: 'duty & tax';
this.inAppStaff(
b,
'Payment slip uploaded',
`Customer uploaded the ${label} payment slip for booking ${this.ref(b)}.`,
{
type: NotificationType.PAYMENT_RECEIVED,
link: `/dashboard/bookings/${b.id}/clearance`,
},
);
}
}

View File

@@ -30,14 +30,32 @@ describe('BookingTransitionService — acceptIntake validity window', () => {
ruleEngineService as never,
{} as never, // pricingService
{} as never, // contractService
{} as never, // invoiceService
{} as never, // filesService
{} as never, // fileUploadSettingsService
{} as never, // bookingBatchService
bookingsService as never,
{ isPhasedGeneralCustomsBooking: () => false } as never,
{} as never,
{} as never, // workflowService
{} as never, // invoiceService
{ validate20ftPairing: jest.fn().mockResolvedValue([]) } as never,
{
accepted: jest.fn(),
approved: jest.fn(),
rejected: jest.fn(),
changesRequested: jest.fn(),
documentQueried: jest.fn(),
clearanceReady: jest.fn(),
operationChangesRequested: jest.fn(),
operationAccepted: jest.fn(),
inTransit: jest.fn(),
completed: jest.fn(),
cancelled: jest.fn(),
submittedToStaff: jest.fn(),
customerSignedToStaff: jest.fn(),
operationRequestedToStaff: jest.fn(),
clearanceDocsUploadedToStaff: jest.fn(),
dutySlipUploadedToStaff: jest.fn(),
} as never, // notifier
);
return { service, bookingsRepository, ruleEngineService };
}

View File

@@ -41,14 +41,32 @@ describe('BookingTransitionService — finalizeClearance gate', () => {
{} as never, // ruleEngineService
{} as never, // pricingService
{} as never, // contractService
{} as never, // invoiceService
filesService as never,
fileUploadSettingsService as never,
{} as never, // bookingBatchService
bookingsService as never,
{ isPhasedGeneralCustomsBooking: () => false } as never,
{} as never,
{} as never, // workflowService
{} as never, // invoiceService
{ validate20ftPairing: jest.fn().mockResolvedValue([]) } as never,
{
accepted: jest.fn(),
approved: jest.fn(),
rejected: jest.fn(),
changesRequested: jest.fn(),
documentQueried: jest.fn(),
clearanceReady: jest.fn(),
operationChangesRequested: jest.fn(),
operationAccepted: jest.fn(),
inTransit: jest.fn(),
completed: jest.fn(),
cancelled: jest.fn(),
submittedToStaff: jest.fn(),
customerSignedToStaff: jest.fn(),
operationRequestedToStaff: jest.fn(),
clearanceDocsUploadedToStaff: jest.fn(),
dutySlipUploadedToStaff: jest.fn(),
} as never, // notifier
);
return { service, bookingsRepository };
}
@@ -126,14 +144,32 @@ describe('BookingTransitionService — finalizeClearance customs output gate', (
{} as never,
{} as never,
{} as never,
{} as never, // invoiceService
filesService as never,
fileUploadSettingsService as never,
{} as never,
{} as never, // bookingBatchService
bookingsService as never,
{ isPhasedGeneralCustomsBooking: () => false } as never,
{} as never,
{} as never, // workflowService
{} as never, // invoiceService
{ validate20ftPairing: jest.fn().mockResolvedValue([]) } as never,
{
accepted: jest.fn(),
approved: jest.fn(),
rejected: jest.fn(),
changesRequested: jest.fn(),
documentQueried: jest.fn(),
clearanceReady: jest.fn(),
operationChangesRequested: jest.fn(),
operationAccepted: jest.fn(),
inTransit: jest.fn(),
completed: jest.fn(),
cancelled: jest.fn(),
submittedToStaff: jest.fn(),
customerSignedToStaff: jest.fn(),
operationRequestedToStaff: jest.fn(),
clearanceDocsUploadedToStaff: jest.fn(),
dutySlipUploadedToStaff: jest.fn(),
} as never, // notifier
);
return { service, bookingsRepository };
}
@@ -197,14 +233,32 @@ describe('BookingTransitionService — submitClearanceDocuments required-fields
{} as never,
{} as never,
{} as never,
{} as never, // invoiceService
filesService as never,
fileUploadSettingsService as never,
{} as never,
{} as never, // bookingBatchService
bookingsService as never,
{ isPhasedGeneralCustomsBooking: () => false } as never,
{} as never,
{} as never, // workflowService
{} as never, // invoiceService
{ validate20ftPairing: jest.fn().mockResolvedValue([]) } as never,
{
accepted: jest.fn(),
approved: jest.fn(),
rejected: jest.fn(),
changesRequested: jest.fn(),
documentQueried: jest.fn(),
clearanceReady: jest.fn(),
operationChangesRequested: jest.fn(),
operationAccepted: jest.fn(),
inTransit: jest.fn(),
completed: jest.fn(),
cancelled: jest.fn(),
submittedToStaff: jest.fn(),
customerSignedToStaff: jest.fn(),
operationRequestedToStaff: jest.fn(),
clearanceDocsUploadedToStaff: jest.fn(),
dutySlipUploadedToStaff: jest.fn(),
} as never, // notifier
);
return { service, bookingsRepository, filesService };
}

View File

@@ -3,14 +3,17 @@ import { BookingTransitionService } from './booking-transition.service';
/**
* Operation-request review for general-contract drawdown orders:
* - ACCEPT a train order → FULLY_EXECUTED and enqueued into the batch pool.
* - ACCEPT a road order → ROAD_DISPATCH_PENDING, NOT enqueued.
* - ACCEPT a train order → FULLY_EXECUTED with the invoice ensured; import/
* domestic bookings wait for their booking-day window cycle (no immediate
* batch enqueue at accept time).
* - ACCEPT a road order → ROAD_DISPATCH_PENDING, never enters the train batch.
* - REQUEST_CHANGES requires a note → OPERATION_CHANGES_REQUESTED.
*/
describe('BookingTransitionService — operation review', () => {
function makeService(serviceTypeCode: string) {
const booking = {
id: 'b-1',
reference: 'BKG-1',
status: 'OPERATION_REQUEST_PENDING',
originYardId: 'o-1',
destinationYardId: 'd-1',
@@ -26,6 +29,14 @@ describe('BookingTransitionService — operation review', () => {
};
const bookingBatchService = {
enqueueRouteDayProcessing: jest.fn(),
pickExportSchedule: jest.fn(),
acceptExportBooking: jest.fn(),
};
const invoiceService = {
ensureInvoiceForBooking: jest
.fn()
.mockResolvedValue({ id: 'inv-1', invoiceNumber: 'INV-0001' }),
updateStatus: jest.fn().mockResolvedValue(undefined),
};
const service = new BookingTransitionService(
@@ -33,37 +44,60 @@ describe('BookingTransitionService — operation review', () => {
{} as never, // ruleEngineService
{} as never, // pricingService
{} as never, // contractService
{} as never, // invoiceService
{} as never, // filesService
{} as never, // fileUploadSettingsService
bookingBatchService as never,
bookingsService as never,
{ isPhasedGeneralCustomsBooking: () => false } as never,
{} as never,
{} as never, // workflowService
invoiceService as never,
{ validate20ftPairing: jest.fn().mockResolvedValue([]) } as never,
{
accepted: jest.fn(),
approved: jest.fn(),
rejected: jest.fn(),
changesRequested: jest.fn(),
documentQueried: jest.fn(),
clearanceReady: jest.fn(),
operationChangesRequested: jest.fn(),
operationAccepted: jest.fn(),
inTransit: jest.fn(),
completed: jest.fn(),
cancelled: jest.fn(),
submittedToStaff: jest.fn(),
customerSignedToStaff: jest.fn(),
operationRequestedToStaff: jest.fn(),
clearanceDocsUploadedToStaff: jest.fn(),
dutySlipUploadedToStaff: jest.fn(),
} as never, // notifier
);
return { service, bookingsRepository, bookingBatchService };
return { service, bookingsRepository, bookingBatchService, invoiceService };
}
it('ACCEPT of a train order → FULLY_EXECUTED and enqueues the batch pool', async () => {
const { service, bookingsRepository, bookingBatchService } =
it('ACCEPT of a train order → FULLY_EXECUTED, invoice ensured, batch waits for window cycle', async () => {
const { service, bookingsRepository, bookingBatchService, invoiceService } =
makeService('RAIL_CONTAINER');
await service.reviewOperationRequest('b-1', 'ACCEPT', 'staff-1');
expect(bookingsRepository.update).toHaveBeenCalledWith(
'b-1',
expect.objectContaining({ status: 'FULLY_EXECUTED' }),
);
expect(bookingBatchService.enqueueRouteDayProcessing).toHaveBeenCalledTimes(1);
expect(invoiceService.ensureInvoiceForBooking).toHaveBeenCalledTimes(1);
// Import/domestic train bookings are batched by the window cycle later —
// never enqueued directly at accept time.
expect(bookingBatchService.enqueueRouteDayProcessing).not.toHaveBeenCalled();
expect(bookingBatchService.acceptExportBooking).not.toHaveBeenCalled();
});
it('ACCEPT of a road order → ROAD_DISPATCH_PENDING and does NOT enqueue', async () => {
const { service, bookingsRepository, bookingBatchService } =
it('ACCEPT of a road order → ROAD_DISPATCH_PENDING and does NOT enter the batch', async () => {
const { service, bookingsRepository, bookingBatchService, invoiceService } =
makeService('ROAD_CONTAINER');
await service.reviewOperationRequest('b-1', 'ACCEPT', 'staff-1');
expect(bookingsRepository.update).toHaveBeenCalledWith(
'b-1',
expect.objectContaining({ status: 'ROAD_DISPATCH_PENDING' }),
);
expect(invoiceService.ensureInvoiceForBooking).toHaveBeenCalledTimes(1);
expect(bookingBatchService.enqueueRouteDayProcessing).not.toHaveBeenCalled();
});

View File

@@ -4,6 +4,7 @@ import {
Inject,
Injectable,
Logger,
Optional,
} from "@nestjs/common";
import type { TCurrentUser } from "@tria-plc/api-common/modules/auth/types/current-user.type";
@@ -15,6 +16,7 @@ import { RuleEngineService } from '../rule-engine/rule-engine.service';
import { FilesService } from '../files/files.service';
import { FileUploadSettingsService } from '../file-upload-settings/file-upload-settings.service';
import { BookingContractService } from './booking-contract.service';
import { BookingLifecycleNotifierService } from './booking-lifecycle-notifier.service';
import { BookingPricingService } from './booking-pricing.service';
import { ContainerValidationService } from './container-validation.service';
import { BookingsRepository } from './bookings.repository';
@@ -26,6 +28,7 @@ import { PriceLineItemDto } from './dto/generate-price-response.dto';
import { Booking } from './entities/booking.entity';
import { BookingsService } from './bookings.service';
import { BookingClearanceService } from '../contracts/booking-clearance.service';
import { ClearanceMilestoneService } from '../contracts/clearance-milestone.service';
import { ClearanceWorkflowService } from '../contracts/clearance-workflow.service';
import { ContractDocPhase } from '@edr/types';
@@ -53,7 +56,8 @@ export class BookingTransitionService {
private readonly workflowService: ClearanceWorkflowService,
private readonly invoiceService: BookingInvoiceService,
private readonly containerValidationService: ContainerValidationService,
private readonly notifier: BookingLifecycleNotifierService,
@Optional() private readonly milestoneService?: ClearanceMilestoneService,
) {}
private isPhasedGeneralCustoms(booking: Booking): boolean {
@@ -124,6 +128,9 @@ export class BookingTransitionService {
const finalBooking = await this.bookingsService.runConsolidationOnSubmit(
updated!.id,
);
if (finalBooking.status === "SUBMITTED") {
this.notifier.submittedToStaff(finalBooking);
}
return {
bookingId: finalBooking.id,
status: finalBooking.status,
@@ -204,6 +211,9 @@ export class BookingTransitionService {
const finalBooking = await this.bookingsService.runConsolidationOnSubmit(
updated!.id,
);
if (finalBooking.status === "SUBMITTED") {
this.notifier.submittedToStaff(finalBooking);
}
return {
bookingId: finalBooking.id,
status: finalBooking.status,
@@ -233,7 +243,9 @@ export class BookingTransitionService {
const updated = await this.bookingsRepository.update(bookingId, {
status: "CHANGES_REQUESTED",
} as never);
return this.bookingsService.findById(updated!.id);
const fresh = await this.bookingsService.findById(updated!.id);
this.notifier.changesRequested(fresh, note);
return fresh;
}
/** Auto-create booking approval steps from system rules when none exist yet. */
@@ -284,7 +296,9 @@ export class BookingTransitionService {
contractValidFrom: validFrom,
contractValidUntil: validUntil,
} as never);
return this.bookingsService.findById(updated!.id);
const fresh = await this.bookingsService.findById(updated!.id);
this.notifier.accepted(fresh);
return fresh;
}
async staffReject(
@@ -305,7 +319,9 @@ export class BookingTransitionService {
const updated = await this.bookingsRepository.update(bookingId, {
status: "REJECTED",
} as never);
return this.bookingsService.findById(updated!.id);
const fresh = await this.bookingsService.findById(updated!.id);
this.notifier.rejected(fresh, reason);
return fresh;
}
async approveStep(
@@ -394,7 +410,9 @@ export class BookingTransitionService {
if (allDone) {
const generated = await this.contractService.generateContract(bookingId);
return this.bookingsService.findById(generated.id);
const fresh = await this.bookingsService.findById(generated.id);
this.notifier.approved(fresh);
return fresh;
}
return this.bookingsService.findById(bookingId);
@@ -435,7 +453,9 @@ export class BookingTransitionService {
const updated = await this.bookingsRepository.update(bookingId, {
status: "REJECTED",
} as never);
return this.bookingsService.findById(updated!.id);
const fresh = await this.bookingsService.findById(updated!.id);
this.notifier.rejected(fresh, reason);
return fresh;
}
async customerSign(bookingId: string): Promise<Booking> {
@@ -446,7 +466,9 @@ export class BookingTransitionService {
status: "SIGNED_CUSTOMER",
customerSignedAt: new Date(),
} as never);
return this.bookingsService.findById(updated!.id);
const fresh = await this.bookingsService.findById(updated!.id);
this.notifier.customerSignedToStaff(fresh);
return fresh;
}
async startTransit(bookingId: string): Promise<Booking> {
@@ -456,7 +478,9 @@ export class BookingTransitionService {
const updated = await this.bookingsRepository.update(bookingId, {
status: "IN_TRANSIT",
} as never);
return this.bookingsService.findById(updated!.id);
const fresh = await this.bookingsService.findById(updated!.id);
this.notifier.inTransit(fresh);
return fresh;
}
async complete(bookingId: string): Promise<Booking> {
@@ -467,7 +491,28 @@ export class BookingTransitionService {
status: "COMPLETED",
endDate: new Date(),
} as never);
return this.bookingsService.findById(updated!.id);
const fresh = await this.bookingsService.findById(updated!.id);
this.notifier.completed(fresh);
// Customer tracking: close out the tail milestones so a finished shipment
// never shows a forever-pending timeline. EXIT_NOTE/PROCESS_COMPLETED are
// implied by delivery; a storage invoice that was never raised is skipped
// (storage billing does not apply to every shipment). All doc-trigger /
// best-effort — a booking without milestone rows is untouched.
if (this.milestoneService) {
for (const code of ["IMPORT_PROCESS_COMPLETED", "EXIT_NOTE_GENERATED"]) {
try {
await this.milestoneService.completeByDocTrigger({ bookingId }, code);
} catch {
/* tracking must never block completion */
}
}
try {
await this.milestoneService.skipForBooking(bookingId, "STORAGE_INVOICE_RAISED");
} catch {
/* no such milestone row (export / non-customs) — fine */
}
}
return fresh;
}
async cancel(bookingId: string, reason: string): Promise<Booking> {
@@ -491,7 +536,9 @@ export class BookingTransitionService {
const updated = await this.bookingsRepository.update(bookingId, {
status: "CANCELLED",
} as never);
return this.bookingsService.findById(updated!.id);
const fresh = await this.bookingsService.findById(updated!.id);
this.notifier.cancelled(fresh, reason);
return fresh;
}
/**
@@ -723,7 +770,9 @@ export class BookingTransitionService {
} as never);
}
return this.bookingsService.findById(bookingId);
const fresh = await this.bookingsService.findById(bookingId);
this.notifier.clearanceDocsUploadedToStaff(fresh);
return fresh;
}
/**
@@ -824,6 +873,9 @@ export class BookingTransitionService {
}
const updated = await this.bookingsService.findById(bookingId);
if (status === "QUERIED") {
this.notifier.documentQueried(updated, fileKey, note ?? '');
}
if (this.isPhasedGeneralCustoms(updated)) {
const allApproved = await this.isClearanceFullyApproved(updated);
if (allApproved) {
@@ -912,7 +964,9 @@ export class BookingTransitionService {
await this.bookingsRepository.update(bookingId, {
status: "CLEARANCE_READY",
} as never);
return this.bookingsService.findById(bookingId);
const fresh = await this.bookingsService.findById(bookingId);
this.notifier.clearanceReady(fresh);
return fresh;
}
/**
@@ -957,7 +1011,9 @@ export class BookingTransitionService {
status: "OPERATION_REQUEST_PENDING",
scheduledDate: date,
} as never);
return this.bookingsService.findById(bookingId);
const fresh = await this.bookingsService.findById(bookingId);
this.notifier.operationRequestedToStaff(fresh);
return fresh;
}
/**
@@ -992,7 +1048,9 @@ export class BookingTransitionService {
await this.bookingsRepository.update(bookingId, {
status: "OPERATION_CHANGES_REQUESTED",
} as never);
return this.bookingsService.findById(bookingId);
const fresh = await this.bookingsService.findById(bookingId);
this.notifier.operationChangesRequested(fresh, options.note);
return fresh;
}
// ACCEPT — enter the batch holding pool.
@@ -1037,7 +1095,9 @@ export class BookingTransitionService {
fullyExecutedAt: now,
lockedAt: booking.lockedAt ?? now,
} as never);
return this.bookingsService.findById(booking.id);
const roadFresh = await this.bookingsService.findById(booking.id);
this.notifier.operationAccepted(roadFresh);
return roadFresh;
}
await this.bookingsRepository.update(booking.id, {
@@ -1072,7 +1132,9 @@ export class BookingTransitionService {
// batch runs after the window closes + staff document review, never at accept
// time. (Legacy pre-migration schedules with no window phase are still served
// by the periodic legacy fill.)
return this.bookingsService.findById(booking.id);
const trainFresh = await this.bookingsService.findById(booking.id);
this.notifier.operationAccepted(trainFresh);
return trainFresh;
}
async enrichBookingResponse(booking: Booking): Promise<

View File

@@ -18,7 +18,10 @@ import { BookingInvoiceService } from './booking-invoice.service';
// import { BookingPaymentService } from './booking-payment.service';
import { BookingPricingService } from './booking-pricing.service';
import { BookingReferenceDataService } from './booking-reference-data.service';
import { BookingLifecycleNotifierService } from './booking-lifecycle-notifier.service';
import { BookingTransitionService } from './booking-transition.service';
import { NotificationsModule } from '../notifications/notifications.module';
import { NotificationInboxModule } from '../notification-inbox/notification-inbox.module';
import { BookingsController } from './bookings.controller';
// import { PayController } from './pay.controller';
import { BookingsRepository } from './bookings.repository';
@@ -64,6 +67,8 @@ import { VehiclesModule } from "../vehicles/vehicles.module";
CustomerTruckContainer,
]),
BillingModule,
NotificationsModule,
NotificationInboxModule,
forwardRef(() => FirstMileModule),
forwardRef(() => TrainSchedulingModule),
forwardRef(() => ContractsModule),
@@ -90,6 +95,7 @@ import { VehiclesModule } from "../vehicles/vehicles.module";
ContainerValidationService,
BookingReferenceDataService,
BookingPricingService,
BookingLifecycleNotifierService,
BookingTransitionService,
BookingContractService,
BookingInvoiceService,
@@ -107,6 +113,7 @@ import { VehiclesModule } from "../vehicles/vehicles.module";
BookingsRepository,
BookingPricingService,
BookingInvoiceService,
BookingLifecycleNotifierService,
CustomerTruckService,
ContainerReceiptService,
],

View File

@@ -1388,6 +1388,17 @@ export class BookingsService {
);
}
// Surface the assigned train's operational status so the portal stepper
// can show the Arrival stage: the booking status stays IN_TRANSIT from
// dispatch until delivery, so arrival is only knowable from the schedule.
if (booking.trainScheduleId) {
const schedule = await this.dataSource
.getRepository(TrainSchedule)
.findOne({ where: { id: booking.trainScheduleId } });
(booking as Booking & { trainScheduleStatus?: string | null }).trainScheduleStatus =
schedule?.status ?? null;
}
return booking;
}