mirror of
https://github.com/Tria-plc/edr-platform.git
synced 2026-08-27 00:52:50 +00:00
feat: Implement consolidated booking functionality
- Added support for viewing and managing consolidated bookings in BookingRequestDetailPage. - Enhanced BookingRequestsPage to display paired bookings in a single row. - Introduced pairedDecision method in bookings service to handle decisions for both halves of a consolidated pair. - Updated contracts service to include methods for manual consolidation of odd-20ft bookings. - Created new components for selecting and editing consolidation partners. - Added tests for paired decision logic and manual consolidation scenarios. - Updated UI to reflect changes in booking handling and provide user feedback for odd container counts.
This commit is contained in:
@@ -0,0 +1,132 @@
|
||||
import { BookingTransitionService } from './booking-transition.service';
|
||||
import { Booking } from './entities/booking.entity';
|
||||
|
||||
/**
|
||||
* Staff decisions on a consolidated pair. Two bookings sharing a wagon must move
|
||||
* together: accepting one alone would put half a wagon into the approval chain,
|
||||
* and cancelling one alone would strand the other on a wagon it can no longer
|
||||
* fill. All-or-nothing — if either half throws, neither booking moved.
|
||||
*/
|
||||
describe('BookingTransitionService — paired staff decisions', () => {
|
||||
function makeService(booking: Partial<Booking>) {
|
||||
const bookingsService = {
|
||||
findById: jest.fn().mockResolvedValue(booking as Booking),
|
||||
};
|
||||
// Runs the callback so a throw propagates, which is what the all-or-nothing
|
||||
// guarantee reduces to from this service's point of view.
|
||||
const dataSource = {
|
||||
transaction: jest.fn(async (cb: () => Promise<unknown>) => cb()),
|
||||
};
|
||||
|
||||
const service = new BookingTransitionService(
|
||||
{} as never, // bookingsRepository
|
||||
{} as never, // ruleEngineService
|
||||
{} as never, // pricingService
|
||||
{} as never, // contractService
|
||||
{} as never, // filesService
|
||||
{} as never, // fileUploadSettingsService
|
||||
{} as never, // bookingBatchService
|
||||
bookingsService as never,
|
||||
{} as never, // bookingClearanceService
|
||||
{} as never, // workflowService
|
||||
{} as never, // invoiceService
|
||||
{} as never, // containerValidationService
|
||||
{} as never, // notifier
|
||||
{} as never, // events
|
||||
undefined, // milestoneService
|
||||
dataSource as never,
|
||||
);
|
||||
return { service, dataSource };
|
||||
}
|
||||
|
||||
const paired = {
|
||||
id: 'b-1',
|
||||
reference: 'BK-1',
|
||||
consolidationPartnerId: 'b-2',
|
||||
} as Booking;
|
||||
|
||||
it('accepts both halves with the same validity window', async () => {
|
||||
const { service } = makeService(paired);
|
||||
const accept = jest
|
||||
.spyOn(service, 'acceptIntake')
|
||||
.mockImplementation(async (id) => ({ id }) as Booking);
|
||||
|
||||
const result = await service.applyPairedDecision('b-1', 'accept', 'staff-1', {
|
||||
validityDays: 30,
|
||||
});
|
||||
|
||||
expect(accept).toHaveBeenCalledTimes(2);
|
||||
expect(accept).toHaveBeenNthCalledWith(1, 'b-1', 'staff-1', 30);
|
||||
expect(accept).toHaveBeenNthCalledWith(2, 'b-2', 'staff-1', 30);
|
||||
expect(result.booking.id).toBe('b-1');
|
||||
expect(result.partner.id).toBe('b-2');
|
||||
});
|
||||
|
||||
it('cancels both halves with the same reason', async () => {
|
||||
const { service } = makeService(paired);
|
||||
const cancel = jest
|
||||
.spyOn(service, 'cancel')
|
||||
.mockImplementation(async (id) => ({ id }) as Booking);
|
||||
|
||||
await service.applyPairedDecision('b-1', 'cancel', 'staff-1', {
|
||||
reason: 'customer withdrew',
|
||||
});
|
||||
|
||||
expect(cancel).toHaveBeenNthCalledWith(1, 'b-1', 'customer withdrew');
|
||||
expect(cancel).toHaveBeenNthCalledWith(2, 'b-2', 'customer withdrew');
|
||||
});
|
||||
|
||||
it('propagates a failure on the second half so neither is committed', async () => {
|
||||
const { service, dataSource } = makeService(paired);
|
||||
jest
|
||||
.spyOn(service, 'cancel')
|
||||
.mockImplementationOnce(async (id) => ({ id }) as Booking)
|
||||
.mockImplementationOnce(async () => {
|
||||
throw new Error('partner is already in transit');
|
||||
});
|
||||
|
||||
await expect(
|
||||
service.applyPairedDecision('b-1', 'cancel', 'staff-1', { reason: 'x' }),
|
||||
).rejects.toThrow('partner is already in transit');
|
||||
|
||||
// Both halves ran inside one transaction, so the throw rolls the first back.
|
||||
expect(dataSource.transaction).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('refuses a booking that has no partner', async () => {
|
||||
const { service } = makeService({
|
||||
id: 'b-1',
|
||||
consolidationPartnerId: null,
|
||||
} as Booking);
|
||||
|
||||
await expect(
|
||||
service.applyPairedDecision('b-1', 'cancel', 'staff-1', { reason: 'x' }),
|
||||
).rejects.toThrow(/no consolidation partner/i);
|
||||
});
|
||||
|
||||
it('requires a validity window to accept', async () => {
|
||||
const { service } = makeService(paired);
|
||||
const accept = jest.spyOn(service, 'acceptIntake');
|
||||
|
||||
await expect(
|
||||
service.applyPairedDecision('b-1', 'accept', 'staff-1', {}),
|
||||
).rejects.toThrow(/validity/i);
|
||||
expect(accept).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('routes operationAccept through the operation review on both halves', async () => {
|
||||
const { service } = makeService(paired);
|
||||
const review = jest
|
||||
.spyOn(service, 'reviewOperationRequest')
|
||||
.mockImplementation(async (id) => ({ id }) as Booking);
|
||||
|
||||
await service.applyPairedDecision('b-1', 'operationAccept', 'staff-1', {});
|
||||
|
||||
expect(review).toHaveBeenNthCalledWith(1, 'b-1', 'ACCEPT', 'staff-1', {
|
||||
note: undefined,
|
||||
});
|
||||
expect(review).toHaveBeenNthCalledWith(2, 'b-2', 'ACCEPT', 'staff-1', {
|
||||
note: undefined,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -455,6 +455,75 @@ export class BookingTransitionService {
|
||||
return this.cancel(bookingId, reason ?? "Customer cancelled before payment");
|
||||
}
|
||||
|
||||
/**
|
||||
* Run a staff decision across BOTH halves of a consolidated pair.
|
||||
*
|
||||
* Two bookings that share a wagon must move together: accepting one while the
|
||||
* other stays behind would put half a wagon into the approval chain, and
|
||||
* cancelling one alone would strand the other on a wagon it can no longer
|
||||
* fill. All-or-nothing — if either half throws, the transaction rolls back and
|
||||
* neither booking moved.
|
||||
*
|
||||
* Each half still runs the ordinary single-booking transition, so pricing,
|
||||
* invoicing and notifications stay per booking: the customers are billed and
|
||||
* notified separately, exactly as they are today.
|
||||
*/
|
||||
async applyPairedDecision(
|
||||
bookingId: string,
|
||||
decision: "accept" | "cancel" | "operationAccept" | "requestChanges",
|
||||
actorId: string,
|
||||
options: { reason?: string; note?: string; validityDays?: number } = {},
|
||||
): Promise<{ booking: Booking; partner: Booking }> {
|
||||
const booking = await this.bookingsService.findById(bookingId);
|
||||
const partnerId = booking.consolidationPartnerId;
|
||||
if (!partnerId) {
|
||||
throw new BadRequestException(
|
||||
"This booking has no consolidation partner — use the single-booking action.",
|
||||
);
|
||||
}
|
||||
|
||||
const runOne = async (id: string): Promise<Booking> => {
|
||||
switch (decision) {
|
||||
case "accept":
|
||||
// Same requirement as the single-booking accept: the approval chain
|
||||
// needs a contract validity window.
|
||||
if (!(Number(options.validityDays) > 0)) {
|
||||
throw new BadRequestException(
|
||||
"Contract validity (days) is required to accept.",
|
||||
);
|
||||
}
|
||||
return this.acceptIntake(id, actorId, Number(options.validityDays));
|
||||
case "cancel":
|
||||
return this.cancel(
|
||||
id,
|
||||
options.reason ?? "Cancelled with its consolidation partner",
|
||||
);
|
||||
case "operationAccept":
|
||||
return this.reviewOperationRequest(id, "ACCEPT", actorId, {
|
||||
note: options.note,
|
||||
});
|
||||
case "requestChanges":
|
||||
return this.requestChanges(id, options.note ?? "", actorId);
|
||||
}
|
||||
};
|
||||
|
||||
// Without a DataSource (unit tests hand-construct this service) fall back to
|
||||
// running the two halves directly — the ordering guarantee still holds, only
|
||||
// the rollback does not.
|
||||
if (!this.dataSource) {
|
||||
const own = await runOne(bookingId);
|
||||
const other = await runOne(partnerId);
|
||||
return { booking: own, partner: other };
|
||||
}
|
||||
|
||||
return this.dataSource.transaction(async () => {
|
||||
// Sequential: one connection per transaction context.
|
||||
const own = await runOne(bookingId);
|
||||
const other = await runOne(partnerId);
|
||||
return { booking: own, partner: other };
|
||||
});
|
||||
}
|
||||
|
||||
async cancel(bookingId: string, reason: string): Promise<Booking> {
|
||||
const booking = await this.bookingsService.findById(bookingId);
|
||||
assertBookingStatus(booking, [
|
||||
|
||||
@@ -59,6 +59,7 @@ import { SubmitBookingResponseDto } from './dto/submit-booking-response.dto';
|
||||
import {
|
||||
AcceptIntakeDto,
|
||||
CancelBookingDto,
|
||||
PairedDecisionDto,
|
||||
RejectBookingDto,
|
||||
RequestChangesDto,
|
||||
ReviewDocumentDto,
|
||||
@@ -1541,6 +1542,31 @@ export class BookingsController {
|
||||
return this.transitionService.enrichBookingResponse(booking);
|
||||
}
|
||||
|
||||
@Post(":id/paired-decision")
|
||||
@BookingStaff(FREIGHT_PERMS.bookings.cancel)
|
||||
@ApiOperation({
|
||||
summary:
|
||||
"Apply a staff decision (accept / cancel / operationAccept / requestChanges) to BOTH halves of a consolidated pair, all-or-nothing.",
|
||||
})
|
||||
async pairedDecision(
|
||||
@Param("id", ParseUUIDPipe) id: string,
|
||||
@Body() dto: PairedDecisionDto,
|
||||
@CurrentUser() user: AuthUserPayload,
|
||||
) {
|
||||
const { booking, partner } = await this.transitionService.applyPairedDecision(
|
||||
id,
|
||||
dto.decision,
|
||||
resolveAuthUserId(user),
|
||||
{ reason: dto.reason, note: dto.note, validityDays: dto.validityDays },
|
||||
);
|
||||
// Sequential enrichment: both go back so the UI can refresh either tab.
|
||||
const enrichedBooking =
|
||||
await this.transitionService.enrichBookingResponse(booking);
|
||||
const enrichedPartner =
|
||||
await this.transitionService.enrichBookingResponse(partner);
|
||||
return { booking: enrichedBooking, partner: enrichedPartner };
|
||||
}
|
||||
|
||||
@Post(":id/cancel")
|
||||
@BookingStaff(FREIGHT_PERMS.bookings.cancel)
|
||||
@ApiOperation({ summary: "Cancel booking" })
|
||||
|
||||
@@ -308,6 +308,72 @@ export class BookingsRepository extends BaseRepository<Booking> {
|
||||
.find({ where: { contractId } });
|
||||
}
|
||||
|
||||
/**
|
||||
* Bookings a GL operator may manually link to `booking` as its odd-20ft
|
||||
* consolidation partner (Path B customs flow). Unlike
|
||||
* {@link findComplementaryConsolidationPartner} — which auto-pairs on an exact
|
||||
* quantity complement — this lists CANDIDATES for a human to choose from, so
|
||||
* the filter is deliberately looser: any other customs booking on the same
|
||||
* route/direction that is itself carrying an odd 20ft count. Two odd counts
|
||||
* always sum to even, so any pick fills the shared wagon.
|
||||
*
|
||||
* Bare instances awaiting completion have no persisted containers yet, so the
|
||||
* odd-count test runs on the requested container lines when they exist and the
|
||||
* booking is offered as a candidate when they do not (GL enters its cargo on
|
||||
* the split form).
|
||||
*/
|
||||
async findManualConsolidationCandidates(
|
||||
booking: Booking,
|
||||
limit = 50,
|
||||
): Promise<Booking[]> {
|
||||
const rows = await this.repository
|
||||
.createQueryBuilder('b')
|
||||
.leftJoinAndSelect('b.bookingContainers', 'bc')
|
||||
.leftJoinAndSelect('bc.containerType', 'ct')
|
||||
.leftJoinAndSelect('b.company', 'company')
|
||||
.where('b.id != :bookingId', { bookingId: booking.id })
|
||||
// Never offer a booking that already shares a wagon with someone else.
|
||||
.andWhere('b.consolidationPartnerId IS NULL')
|
||||
// Customs-only: this manual flow exists because a customs (Path B)
|
||||
// instance is completed by GL, not by the customer.
|
||||
.andWhere('b.customsClearingEnabled = true')
|
||||
// Same physical wagon ⇒ same route and same direction.
|
||||
.andWhere('b.originYardId = :originYardId', {
|
||||
originYardId: booking.originYardId,
|
||||
})
|
||||
.andWhere('b.destinationYardId = :destinationYardId', {
|
||||
destinationYardId: booking.destinationYardId,
|
||||
})
|
||||
.andWhere('b.tradeDirection = :tradeDirection', {
|
||||
tradeDirection: booking.tradeDirection,
|
||||
})
|
||||
// Bookable = clearance finished and the booking is waiting to be completed,
|
||||
// the same set completeUnderContract accepts, plus one already parked for a
|
||||
// partner.
|
||||
.andWhere('b.status IN (:...statuses)', {
|
||||
statuses: [
|
||||
'CLEARANCE_READY',
|
||||
'OPERATION_CHANGES_REQUESTED',
|
||||
'PENDING_CONSOLIDATION',
|
||||
],
|
||||
})
|
||||
.orderBy('b.createdAt', 'ASC')
|
||||
.take(limit)
|
||||
.getMany();
|
||||
|
||||
// Odd-20ft test in memory: a bare instance has no containers yet (GL fills
|
||||
// them on the split form) and stays a candidate; one that already carries
|
||||
// cargo qualifies only when its 20ft total is odd.
|
||||
return rows.filter((row) => {
|
||||
const lines = row.bookingContainers ?? [];
|
||||
if (lines.length === 0) return true;
|
||||
const ft20 = lines
|
||||
.filter((line) => Number(line.containerType?.sizeFt) === 20)
|
||||
.reduce((sum, line) => sum + Number(line.quantity || 0), 0);
|
||||
return ft20 % 2 === 1;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Find another booking whose container quantity complements this one to fill whole wagon(s)
|
||||
* (same route, same container type, partial wagon on both sides). Only 20ft lines ever
|
||||
@@ -508,6 +574,25 @@ export class BookingsRepository extends BaseRepository<Booking> {
|
||||
} as never);
|
||||
}
|
||||
|
||||
/**
|
||||
* Link two bookings as consolidation partners WITHOUT touching their statuses.
|
||||
* Used by the manual GL pairing, where both bookings have just been completed
|
||||
* into their live status — unlike {@link pairConsolidation}, which exists to
|
||||
* resume bookings parked in PENDING_CONSOLIDATION and rewrites status as part
|
||||
* of that resume.
|
||||
*/
|
||||
async linkConsolidationPartners(
|
||||
bookingId: string,
|
||||
partnerId: string,
|
||||
): Promise<void> {
|
||||
await this.repository.update(bookingId, {
|
||||
consolidationPartnerId: partnerId,
|
||||
} as never);
|
||||
await this.repository.update(partnerId, {
|
||||
consolidationPartnerId: bookingId,
|
||||
} as never);
|
||||
}
|
||||
|
||||
/** Un-pair a consolidation. */
|
||||
async unpairConsolidation(bookingId: string, partnerId: string): Promise<void> {
|
||||
await this.repository.update(bookingId, {
|
||||
|
||||
@@ -125,3 +125,36 @@ export class OperationReviewDto {
|
||||
@IsString()
|
||||
note?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* A staff decision applied to BOTH halves of a consolidated pair. The two
|
||||
* bookings share a wagon, so they advance or cancel together — never one alone.
|
||||
*/
|
||||
export class PairedDecisionDto {
|
||||
@ApiProperty({
|
||||
enum: ["accept", "cancel", "operationAccept", "requestChanges"],
|
||||
description: 'Which staff decision to apply to both bookings.',
|
||||
})
|
||||
@IsIn(["accept", "cancel", "operationAccept", "requestChanges"])
|
||||
decision!: "accept" | "cancel" | "operationAccept" | "requestChanges";
|
||||
|
||||
@ApiPropertyOptional({ description: "Cancellation reason (decision=cancel)." })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
reason?: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description: "Message to the customer (decision=requestChanges).",
|
||||
})
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
note?: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description: "Contract validity window in days (decision=accept).",
|
||||
})
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
validityDays?: number;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
import { ContractBookingService } from './contract-booking.service';
|
||||
import { Booking } from '../bookings/entities/booking.entity';
|
||||
|
||||
/**
|
||||
* Manual (GL-driven) odd-20ft consolidation. On a customs contract GL completes
|
||||
* the booking, so GL also picks who shares its wagon: two bookings each carrying
|
||||
* an odd 20ft count are completed together onto one wagon.
|
||||
*
|
||||
* The two invariants that matter are that the pair is all-or-nothing (a failure
|
||||
* on either half must leave NEITHER booking completed and no link written) and
|
||||
* that the two bookings stay financially separate — one completion each, so one
|
||||
* price and one invoice each.
|
||||
*/
|
||||
describe('ContractBookingService — manual odd-20ft consolidation', () => {
|
||||
function makeService(overrides: {
|
||||
bookingsRepository?: Partial<Record<string, jest.Mock>>;
|
||||
dataSource?: unknown;
|
||||
}) {
|
||||
const bookingsRepository = {
|
||||
findByIdWithFiles: jest.fn(),
|
||||
findManualConsolidationCandidates: jest.fn().mockResolvedValue([]),
|
||||
linkConsolidationPartners: jest.fn().mockResolvedValue(undefined),
|
||||
...overrides.bookingsRepository,
|
||||
};
|
||||
|
||||
// A transaction that simply runs the callback — enough to assert the
|
||||
// all-or-nothing contract: whatever throws inside propagates out, and the
|
||||
// caller observes no link written.
|
||||
const dataSource = overrides.dataSource ?? {
|
||||
transaction: jest.fn(async (cb: (m: unknown) => Promise<unknown>) => cb({})),
|
||||
};
|
||||
|
||||
const service = new ContractBookingService(
|
||||
{ findByIdWithRelations: jest.fn() } as never,
|
||||
bookingsRepository as never,
|
||||
{} as never, // bookingPricingService
|
||||
{} as never, // consolidationService
|
||||
{} as never, // containerTypesService
|
||||
{} as never, // ruleEngineService
|
||||
{} as never, // milestoneService
|
||||
{} as never, // invoiceService
|
||||
{} as never, // bookingNotifier
|
||||
dataSource as never,
|
||||
{} as never, // trainSchedulingService
|
||||
{} as never, // bookingBatchService
|
||||
{} as never, // bookingTransitionService
|
||||
);
|
||||
return { service, bookingsRepository, dataSource };
|
||||
}
|
||||
|
||||
const partnerBooking = {
|
||||
id: 'b-2',
|
||||
reference: 'BK-2',
|
||||
contractId: 'c-2',
|
||||
consolidationPartnerId: null,
|
||||
} as unknown as Booking;
|
||||
|
||||
const pairDto = {
|
||||
partnerBookingId: 'b-2',
|
||||
booking: { scheduledDate: '2026-09-01' },
|
||||
partner: { scheduledDate: '2026-09-01' },
|
||||
};
|
||||
|
||||
it('completes both halves and links them', async () => {
|
||||
const { service, bookingsRepository } = makeService({
|
||||
bookingsRepository: {
|
||||
findByIdWithFiles: jest
|
||||
.fn()
|
||||
// partner lookup before the transaction
|
||||
.mockResolvedValueOnce(partnerBooking)
|
||||
// the two reloads after it
|
||||
.mockResolvedValueOnce({ id: 'b-1', reference: 'BK-1' } as Booking)
|
||||
.mockResolvedValueOnce({ id: 'b-2', reference: 'BK-2' } as Booking),
|
||||
},
|
||||
});
|
||||
|
||||
// Each half runs the ordinary completion machine — one call per booking, so
|
||||
// each is priced and invoiced on its own.
|
||||
const complete = jest
|
||||
.spyOn(service, 'completeUnderContract')
|
||||
.mockImplementation(
|
||||
async (_contractId, bookingId) =>
|
||||
({
|
||||
booking: { id: bookingId } as Booking,
|
||||
warnings: [],
|
||||
}) as never,
|
||||
);
|
||||
|
||||
const result = await service.completeConsolidatedPair(
|
||||
'c-1',
|
||||
'b-1',
|
||||
pairDto as never,
|
||||
);
|
||||
|
||||
expect(complete).toHaveBeenCalledTimes(2);
|
||||
// The partner is completed against ITS OWN contract, not this one.
|
||||
expect(complete.mock.calls[0][0]).toBe('c-1');
|
||||
expect(complete.mock.calls[1][0]).toBe('c-2');
|
||||
// Neither half may re-enter the automatic matcher — GL links them here.
|
||||
expect(complete.mock.calls[0][2]).toMatchObject({
|
||||
skipAutoConsolidation: true,
|
||||
});
|
||||
expect(complete.mock.calls[1][2]).toMatchObject({
|
||||
skipAutoConsolidation: true,
|
||||
});
|
||||
expect(bookingsRepository.linkConsolidationPartners).toHaveBeenCalledWith(
|
||||
'b-1',
|
||||
'b-2',
|
||||
);
|
||||
expect(result.booking.id).toBe('b-1');
|
||||
expect(result.partner.id).toBe('b-2');
|
||||
});
|
||||
|
||||
it('links nothing when the partner half fails (all-or-nothing)', async () => {
|
||||
const { service, bookingsRepository } = makeService({
|
||||
bookingsRepository: {
|
||||
findByIdWithFiles: jest.fn().mockResolvedValue(partnerBooking),
|
||||
},
|
||||
});
|
||||
|
||||
jest
|
||||
.spyOn(service, 'completeUnderContract')
|
||||
.mockImplementationOnce(
|
||||
async () => ({ booking: { id: 'b-1' } as Booking, warnings: [] }) as never,
|
||||
)
|
||||
.mockImplementationOnce(async () => {
|
||||
throw new Error('no train space for the partner');
|
||||
});
|
||||
|
||||
await expect(
|
||||
service.completeConsolidatedPair('c-1', 'b-1', pairDto as never),
|
||||
).rejects.toThrow('no train space for the partner');
|
||||
|
||||
// The link is the last write in the transaction — it must never happen when
|
||||
// a half failed, so the rollback leaves no dangling pairing.
|
||||
expect(bookingsRepository.linkConsolidationPartners).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('refuses a partner that already shares a wagon', async () => {
|
||||
const { service } = makeService({
|
||||
bookingsRepository: {
|
||||
findByIdWithFiles: jest.fn().mockResolvedValue({
|
||||
...partnerBooking,
|
||||
consolidationPartnerId: 'b-9',
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
await expect(
|
||||
service.completeConsolidatedPair('c-1', 'b-1', pairDto as never),
|
||||
).rejects.toThrow(/already shares a wagon/i);
|
||||
});
|
||||
|
||||
it('refuses to consolidate a booking with itself', async () => {
|
||||
const { service } = makeService({});
|
||||
|
||||
await expect(
|
||||
service.completeConsolidatedPair('c-1', 'b-1', {
|
||||
...pairDto,
|
||||
partnerBookingId: 'b-1',
|
||||
} as never),
|
||||
).rejects.toThrow(/cannot be consolidated with itself/i);
|
||||
});
|
||||
|
||||
it('offers only bookings whose own 20ft count is odd', async () => {
|
||||
// Two odd counts always sum to even, so an odd partner is exactly what fills
|
||||
// the wagon; an even one would leave the pair partial again.
|
||||
const rows = [
|
||||
{
|
||||
id: 'odd',
|
||||
reference: 'BK-ODD',
|
||||
bookingContainers: [
|
||||
{ quantity: 3, containerType: { sizeFt: 20 } },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'even',
|
||||
reference: 'BK-EVEN',
|
||||
bookingContainers: [
|
||||
{ quantity: 4, containerType: { sizeFt: 20 } },
|
||||
],
|
||||
},
|
||||
// A bare instance has no cargo yet — GL enters it on the split form, so it
|
||||
// stays a candidate.
|
||||
{ id: 'bare', reference: 'BK-BARE', bookingContainers: [] },
|
||||
];
|
||||
|
||||
const { service } = makeService({
|
||||
bookingsRepository: {
|
||||
findByIdWithFiles: jest
|
||||
.fn()
|
||||
.mockResolvedValue({ id: 'b-1', contractId: 'c-1' } as Booking),
|
||||
findManualConsolidationCandidates: jest.fn(async (booking: Booking) =>
|
||||
// Mirror the repository's in-memory odd filter.
|
||||
rows.filter((row) => {
|
||||
void booking;
|
||||
const lines = row.bookingContainers ?? [];
|
||||
if (lines.length === 0) return true;
|
||||
const ft20 = lines
|
||||
.filter((l) => Number(l.containerType?.sizeFt) === 20)
|
||||
.reduce((sum, l) => sum + Number(l.quantity || 0), 0);
|
||||
return ft20 % 2 === 1;
|
||||
}),
|
||||
),
|
||||
},
|
||||
});
|
||||
|
||||
const candidates = await service.listConsolidationCandidates('c-1', 'b-1');
|
||||
expect(candidates.map((c) => c.reference)).toEqual(['BK-ODD', 'BK-BARE']);
|
||||
expect(candidates[0].ft20Quantity).toBe(3);
|
||||
expect(candidates[1].hasCargo).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -44,6 +44,7 @@ import {
|
||||
import { ClearanceMilestoneService } from './clearance-milestone.service';
|
||||
import { isEffectivelyExpired } from './utils/contract-expiry.util';
|
||||
import {
|
||||
CompleteConsolidatedPairDto,
|
||||
CreateBookingContainerLineDto,
|
||||
CreateBookingUnderContractDto,
|
||||
} from './dto/create-booking-under-contract.dto';
|
||||
@@ -62,6 +63,25 @@ export interface CreateBookingUnderContractResult {
|
||||
warnings: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* A booking GL may pick as the shared-wagon partner of an odd-20ft customs
|
||||
* booking. `hasCargo` is false for a bare instance whose containers GL still has
|
||||
* to enter on the split completion form.
|
||||
*/
|
||||
export interface ConsolidationCandidate {
|
||||
id: string;
|
||||
reference: string;
|
||||
contractId: string | null;
|
||||
companyName: string | null;
|
||||
status: string;
|
||||
tradeDirection: string | null;
|
||||
originYardId: string | null;
|
||||
destinationYardId: string | null;
|
||||
scheduledDate: string | null;
|
||||
ft20Quantity: number;
|
||||
hasCargo: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Outstanding split remainder of a contract: what was booked in the first split
|
||||
* booking's pre-split snapshot MINUS everything currently booked. Container
|
||||
@@ -598,6 +618,134 @@ export class ContractBookingService {
|
||||
return created;
|
||||
}
|
||||
|
||||
/**
|
||||
* Candidate partners a GL operator may link to an odd-20ft customs booking.
|
||||
* Manual counterpart to the automatic pairing in {@link consolidateDrawdown} —
|
||||
* a customs instance is completed by GL, so GL also chooses who shares its
|
||||
* wagon rather than waiting for the auto-matcher to find an exact complement.
|
||||
*/
|
||||
async listConsolidationCandidates(
|
||||
contractId: string,
|
||||
bookingId: string,
|
||||
): Promise<ConsolidationCandidate[]> {
|
||||
const booking = await this.bookingsRepository.findByIdWithFiles(bookingId);
|
||||
if (!booking || booking.contractId !== contractId) {
|
||||
throw new NotFoundException(`Booking ${bookingId} not found on this contract`);
|
||||
}
|
||||
|
||||
const rows = await this.bookingsRepository.findManualConsolidationCandidates(
|
||||
booking,
|
||||
);
|
||||
return rows.map((row) => {
|
||||
const lines = row.bookingContainers ?? [];
|
||||
return {
|
||||
id: row.id,
|
||||
reference: row.reference,
|
||||
contractId: row.contractId ?? null,
|
||||
companyName: row.company?.name ?? null,
|
||||
status: row.status,
|
||||
tradeDirection: row.tradeDirection ?? null,
|
||||
originYardId: row.originYardId ?? null,
|
||||
destinationYardId: row.destinationYardId ?? null,
|
||||
scheduledDate: row.scheduledDate ? row.scheduledDate.toISOString() : null,
|
||||
ft20Quantity: lines
|
||||
.filter((line) => Number(line.containerType?.sizeFt) === 20)
|
||||
.reduce((sum, line) => sum + Number(line.quantity || 0), 0),
|
||||
hasCargo: lines.length > 0,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Complete an odd-20ft customs booking together with the partner booking GL
|
||||
* picked for its shared wagon. Both halves run the ordinary
|
||||
* {@link completeUnderContract} machine — same gates, same pricing, same
|
||||
* per-booking invoice, so each customer still pays only its own shipment — and
|
||||
* are linked as consolidation partners at the end.
|
||||
*
|
||||
* All-or-nothing: the two completions plus the pairing run inside one
|
||||
* transaction, so a failure on either half leaves neither booking completed
|
||||
* and no half-linked wagon behind. `runInTransaction` is used rather than a
|
||||
* manual QueryRunner so the nested services join the same transactional
|
||||
* context through the shared DataSource.
|
||||
*/
|
||||
async completeConsolidatedPair(
|
||||
contractId: string,
|
||||
bookingId: string,
|
||||
dto: CompleteConsolidatedPairDto,
|
||||
actorPermissions?: unknown,
|
||||
): Promise<{
|
||||
booking: Booking;
|
||||
partner: Booking;
|
||||
warnings: string[];
|
||||
}> {
|
||||
if (dto.partnerBookingId === bookingId) {
|
||||
throw new BadRequestException(
|
||||
'A booking cannot be consolidated with itself.',
|
||||
);
|
||||
}
|
||||
|
||||
const partner = await this.bookingsRepository.findByIdWithFiles(
|
||||
dto.partnerBookingId,
|
||||
);
|
||||
if (!partner) {
|
||||
throw new NotFoundException(
|
||||
`Partner booking ${dto.partnerBookingId} not found`,
|
||||
);
|
||||
}
|
||||
if (partner.consolidationPartnerId) {
|
||||
throw new ConflictException(
|
||||
`Booking ${partner.reference} already shares a wagon with another booking.`,
|
||||
);
|
||||
}
|
||||
if (!partner.contractId) {
|
||||
throw new BadRequestException(
|
||||
`Booking ${partner.reference} is not a contract booking and cannot be completed here.`,
|
||||
);
|
||||
}
|
||||
|
||||
const warnings: string[] = [];
|
||||
|
||||
const { ownId, partnerId } = await this.dataSource.transaction(async () => {
|
||||
const own = await this.completeUnderContract(
|
||||
contractId,
|
||||
bookingId,
|
||||
{ ...dto.booking, skipAutoConsolidation: true },
|
||||
// Both halves are completed by the same GL actor that reached this
|
||||
// endpoint — the customs gate in completeUnderContract re-checks it.
|
||||
actorPermissions,
|
||||
);
|
||||
warnings.push(...own.warnings);
|
||||
|
||||
const other = await this.completeUnderContract(
|
||||
partner.contractId as string,
|
||||
partner.id,
|
||||
{ ...dto.partner, skipAutoConsolidation: true },
|
||||
actorPermissions,
|
||||
);
|
||||
warnings.push(...other.warnings);
|
||||
|
||||
// Link the two halves. Written directly (not via pairConsolidation) because
|
||||
// both bookings have just been completed into their live status here —
|
||||
// pairConsolidation exists to RESUME bookings parked in
|
||||
// PENDING_CONSOLIDATION and would overwrite that status.
|
||||
await this.bookingsRepository.linkConsolidationPartners(
|
||||
own.booking.id,
|
||||
other.booking.id,
|
||||
);
|
||||
return { ownId: own.booking.id, partnerId: other.booking.id };
|
||||
});
|
||||
|
||||
// Sequential reads: one connection per transaction context.
|
||||
const finalBooking = await this.bookingsRepository.findByIdWithFiles(ownId);
|
||||
const finalPartner = await this.bookingsRepository.findByIdWithFiles(partnerId);
|
||||
return {
|
||||
booking: finalBooking!,
|
||||
partner: finalPartner ?? partner,
|
||||
warnings,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Complete a bare initiated booking after its per-booking clearance is
|
||||
* finalized (CLEARANCE_READY) or operations returned it for changes
|
||||
@@ -826,10 +974,18 @@ export class ContractBookingService {
|
||||
// exactly like a drawdown created with cargo does. The shipment day is
|
||||
// stored first so the pairing event can resume straight into the
|
||||
// operations queue.
|
||||
// Customs (Path B) instances are exempt from the AUTO-matcher: GL links
|
||||
// their shared wagon by hand through completeConsolidatedPair, so nothing
|
||||
// may claim a partner for them behind GL's back. A customs half completed
|
||||
// as part of a manual pair carries `skipAutoConsolidation`; one completed
|
||||
// alone still falls through to the automatic gate below, so an odd 20ft
|
||||
// booking can never proceed on a partial wagon. Non-customs drawdowns are
|
||||
// unaffected.
|
||||
const withContainers = await this.bookingsRepository.findByIdWithFiles(booking.id);
|
||||
if (
|
||||
withContainers &&
|
||||
freightType === 'CONTAINER' &&
|
||||
!dto.skipAutoConsolidation &&
|
||||
(await this.consolidationService.needsConsolidationFromBooking(withContainers))
|
||||
) {
|
||||
await this.bookingsRepository.update(booking.id, {
|
||||
|
||||
@@ -76,7 +76,10 @@ import {
|
||||
import { SignContractDto } from './dto/sign-contract.dto';
|
||||
import { ReviewClearanceDocumentDto } from './dto/review-clearance-document.dto';
|
||||
import { RenewContractDto } from './dto/renew-contract.dto';
|
||||
import { CreateBookingUnderContractDto } from './dto/create-booking-under-contract.dto';
|
||||
import {
|
||||
CompleteConsolidatedPairDto,
|
||||
CreateBookingUnderContractDto,
|
||||
} from './dto/create-booking-under-contract.dto';
|
||||
import {
|
||||
CreateBookingRequestDto,
|
||||
ReviewBookingRequestDto,
|
||||
@@ -1152,6 +1155,41 @@ export class ContractsController {
|
||||
// Customs (Path B) instances may only be completed by GL Ethiopia — the
|
||||
// service checks the actor's contracts:create_booking permission.
|
||||
return this.contractBookingService.completeUnderContract(
|
||||
id,
|
||||
bookingId,
|
||||
// skipAutoConsolidation is internal to the manual pair-completion path; a
|
||||
// client must never suppress the wagon gate on a lone booking.
|
||||
{ ...dto, skipAutoConsolidation: false },
|
||||
user,
|
||||
);
|
||||
}
|
||||
|
||||
@Get(':id/bookings/:bookingId/consolidation-candidates')
|
||||
@MixedAudience(FREIGHT_PERMS.contracts.createBooking)
|
||||
@ApiOperation({
|
||||
summary:
|
||||
'Bookings GL may link to this odd-20ft customs booking as its shared-wagon partner (same route and direction, customs, odd 20ft, unpaired).',
|
||||
})
|
||||
listConsolidationCandidates(
|
||||
@Param('id', ParseUUIDPipe) id: string,
|
||||
@Param('bookingId', ParseUUIDPipe) bookingId: string,
|
||||
) {
|
||||
return this.contractBookingService.listConsolidationCandidates(id, bookingId);
|
||||
}
|
||||
|
||||
@Post(':id/bookings/:bookingId/complete-consolidated')
|
||||
@MixedAudience(FREIGHT_PERMS.contracts.createBooking)
|
||||
@ApiOperation({
|
||||
summary:
|
||||
'Complete this booking and its chosen shared-wagon partner together (all-or-nothing). Each booking is priced and invoiced separately — only the wagon is shared.',
|
||||
})
|
||||
completeConsolidatedPair(
|
||||
@Param('id', ParseUUIDPipe) id: string,
|
||||
@Param('bookingId', ParseUUIDPipe) bookingId: string,
|
||||
@Body() dto: CompleteConsolidatedPairDto,
|
||||
@CurrentUser() user: TCurrentUser & { sub?: string },
|
||||
) {
|
||||
return this.contractBookingService.completeConsolidatedPair(
|
||||
id,
|
||||
bookingId,
|
||||
dto,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { ApiHideProperty, ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { Transform, Type } from 'class-transformer';
|
||||
import {
|
||||
IsArray,
|
||||
@@ -219,4 +219,46 @@ export class CreateBookingUnderContractDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
notes?: string;
|
||||
|
||||
/**
|
||||
* Internal: set by the manual GL pair-completion path, never by a client.
|
||||
* Suppresses the automatic wagon-consolidation gate for this completion
|
||||
* because the caller links the shared wagon itself. Excluded from the public
|
||||
* schema so a client cannot set it to bypass the gate on a lone booking.
|
||||
*/
|
||||
@ApiHideProperty()
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
skipAutoConsolidation?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Complete an odd-20ft customs booking together with the partner booking GL
|
||||
* picked to share its wagon. Each half carries its own full completion payload —
|
||||
* the two bookings stay separately priced and separately invoiced, they only
|
||||
* share the wagon.
|
||||
*/
|
||||
export class CompleteConsolidatedPairDto {
|
||||
@ApiProperty({
|
||||
format: 'uuid',
|
||||
description: 'The booking chosen to share this booking’s wagon.',
|
||||
})
|
||||
@IsUUID()
|
||||
partnerBookingId!: string;
|
||||
|
||||
@ApiProperty({
|
||||
type: CreateBookingUnderContractDto,
|
||||
description: 'Completion payload for the booking in the URL.',
|
||||
})
|
||||
@ValidateNested()
|
||||
@Type(() => CreateBookingUnderContractDto)
|
||||
booking!: CreateBookingUnderContractDto;
|
||||
|
||||
@ApiProperty({
|
||||
type: CreateBookingUnderContractDto,
|
||||
description: 'Completion payload for the partner booking.',
|
||||
})
|
||||
@ValidateNested()
|
||||
@Type(() => CreateBookingUnderContractDto)
|
||||
partner!: CreateBookingUnderContractDto;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user