mirror of
https://github.com/Tria-plc/edr-platform.git
synced 2026-08-27 08:32:54 +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,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