feat(bookings): enhance operation request flow and add location selection for first/last mile

This commit is contained in:
Marshal
2026-06-24 00:35:37 +00:00
parent 8ef7641048
commit 5be181aba8
12 changed files with 444 additions and 120 deletions

View File

@@ -70,7 +70,26 @@ export function computeNextStep(
case 'CLEARANCE_READY':
return {
action: 'PROCEED_TO_OPERATION',
description: 'Clearance is ready — proceed to operation',
description:
'Clearance is ready — pick a schedule day and request operation',
};
case 'OPERATION_REQUEST_PENDING':
return {
action: 'AWAIT_OPERATION_REVIEW',
description:
'Operations is reviewing your request (capacity, documents, route)',
};
case 'OPERATION_CHANGES_REQUESTED':
return {
action: 'RESUBMIT_OPERATION',
description:
'Operations requested changes — update and resubmit your operation request',
};
case 'OPERATION_PRICE_PENDING_CONFIRM':
return {
action: 'CONFIRM_OPERATION_PRICE',
description:
'Operations adjusted the price — confirm the new total to proceed',
};
case 'OPERATION_REQUESTED':
return {

View File

@@ -32,6 +32,7 @@ describe('BookingTransitionService — acceptIntake validity window', () => {
{} as never, // contractService
{} as never, // filesService
{} as never, // fileUploadSettingsService
{} as never, // bookingBatchService
bookingsService as never,
);
return { service, bookingsRepository, ruleEngineService };

View File

@@ -43,6 +43,7 @@ describe('BookingTransitionService — finalizeClearance gate', () => {
{} as never, // contractService
filesService as never,
fileUploadSettingsService as never,
{} as never, // bookingBatchService
bookingsService as never,
);
return { service, bookingsRepository };

View File

@@ -7,6 +7,8 @@ import {
import type { TCurrentUser } from '@tria-plc/api-common/modules/auth/types/current-user.type';
import { assertCanApproveBookingStep } from '../../common/freight-permission.util';
import { BookingBatchService } from '../train-scheduling/booking-batch.service';
import { eatDay } from '../train-scheduling/batch-window.util';
import { RuleEngineService } from '../rule-engine/rule-engine.service';
import { FilesService } from '../files/files.service';
import { FileUploadSettingsService } from '../file-upload-settings/file-upload-settings.service';
@@ -30,6 +32,8 @@ export class BookingTransitionService {
private readonly contractService: BookingContractService,
private readonly filesService: FilesService,
private readonly fileUploadSettingsService: FileUploadSettingsService,
@Inject(forwardRef(() => BookingBatchService))
private readonly bookingBatchService: BookingBatchService,
@Inject(forwardRef(() => BookingsService))
private readonly bookingsService: BookingsService,
) {}
@@ -769,16 +773,134 @@ export class BookingTransitionService {
return this.bookingsService.findById(bookingId);
}
/** Customer proceeds to operation once clearance is ready → OPERATION_REQUESTED. */
async requestOperation(bookingId: string): Promise<Booking> {
/**
* Customer proceeds to operation once clearance is ready. They pick the
* schedule day (the train departure day) for the shipment; the request then
* sits at OPERATION_REQUEST_PENDING for the operations team to review
* (capacity, documents, route) before it enters the batch holding pool.
*
* Allowed from CLEARANCE_READY (first request) and OPERATION_CHANGES_REQUESTED
* (resubmit after the operations team returned it for changes).
*/
async requestOperation(
bookingId: string,
scheduledDate: string,
): Promise<Booking> {
const booking = await this.bookingsService.findById(bookingId);
assertBookingStatus(booking, ['CLEARANCE_READY']);
assertBookingStatus(booking, ['CLEARANCE_READY', 'OPERATION_CHANGES_REQUESTED']);
const date = new Date(scheduledDate);
if (Number.isNaN(date.getTime())) {
throw new BadRequestException('A valid schedule date is required');
}
await this.bookingsRepository.update(bookingId, {
status: 'OPERATION_REQUESTED',
status: 'OPERATION_REQUEST_PENDING',
scheduledDate: date,
} as never);
return this.bookingsService.findById(bookingId);
}
/**
* Operations team reviews a pending operation request (capacity, documents,
* route). Three outcomes:
* - ACCEPT → booking enters the batch holding pool (FULLY_EXECUTED).
* - REQUEST_CHANGES → returned to the customer with a note to fix and resubmit.
* - ADJUST_PRICE → a new total is set; the customer must re-confirm it
* before the booking can enter the pool.
*/
async reviewOperationRequest(
bookingId: string,
decision: 'ACCEPT' | 'REQUEST_CHANGES' | 'ADJUST_PRICE',
actorId: string,
options: { note?: string; amount?: number } = {},
): Promise<Booking> {
const booking = await this.bookingsService.findById(bookingId);
assertBookingStatus(booking, ['OPERATION_REQUEST_PENDING']);
if (decision === 'REQUEST_CHANGES') {
if (!options.note?.trim()) {
throw new BadRequestException(
'A note is required when requesting changes',
);
}
await this.bookingsRepository.createReviewNote(
bookingId,
options.note,
'CHANGES_REQUESTED',
actorId,
);
await this.bookingsRepository.update(bookingId, {
status: 'OPERATION_CHANGES_REQUESTED',
} as never);
return this.bookingsService.findById(bookingId);
}
if (decision === 'ADJUST_PRICE') {
if (options.amount == null || options.amount < 0) {
throw new BadRequestException(
'A non-negative adjusted amount is required to adjust the price',
);
}
await this.bookingsRepository.update(bookingId, {
adjustedTotalAmount: options.amount,
adjustedByStaffId: actorId,
adjustedAt: new Date(),
adjustmentReason: options.note ?? null,
status: 'OPERATION_PRICE_PENDING_CONFIRM',
} as never);
return this.bookingsService.findById(bookingId);
}
// ACCEPT — enter the batch holding pool.
return this.acceptOperationRequest(booking);
}
/**
* Customer re-confirms (or rejects) an operations price adjustment. Accepting
* pushes the booking into the pool; rejecting returns it to the customer as an
* operation change request so they can resubmit or cancel.
*/
async confirmOperationPrice(
bookingId: string,
accept: boolean,
): Promise<Booking> {
const booking = await this.bookingsService.findById(bookingId);
assertBookingStatus(booking, ['OPERATION_PRICE_PENDING_CONFIRM']);
if (!accept) {
await this.bookingsRepository.update(bookingId, {
status: 'OPERATION_CHANGES_REQUESTED',
} as never);
return this.bookingsService.findById(bookingId);
}
return this.acceptOperationRequest(booking);
}
/**
* Move a reviewed operation request into the batch holding pool. The pool query
* (findBatchPoolByRouteDay) keys on FULLY_EXECUTED + scheduled_date, so we set
* those and kick the day-level fill immediately instead of waiting for cron.
*/
private async acceptOperationRequest(booking: Booking): Promise<Booking> {
const now = new Date();
await this.bookingsRepository.update(booking.id, {
status: 'FULLY_EXECUTED',
fullyExecutedAt: now,
lockedAt: booking.lockedAt ?? now,
} as never);
if (booking.scheduledDate) {
this.bookingBatchService.enqueueRouteDayProcessing(
booking.originYardId,
booking.destinationYardId,
eatDay(new Date(booking.scheduledDate)),
);
}
return this.bookingsService.findById(booking.id);
}
async enrichBookingResponse(booking: Booking): Promise<Booking & {
latestChangeRequestNote?: string | null;
contractSummary?: string | null;

View File

@@ -50,6 +50,9 @@ import {
RejectStepDto,
RequestChangesDto,
ReviewDocumentDto,
RequestOperationDto,
OperationReviewDto,
ConfirmOperationPriceDto,
StaffRejectDto,
} from './dto/request-changes.dto';
import { ContractViewDto } from './dto/contract-view.dto';
@@ -360,10 +363,56 @@ export class BookingsController {
@Post(':id/clearance/proceed')
@ApiOperation({
summary: 'Customer proceeds to operation (CLEARANCE_READY → OPERATION_REQUESTED)',
summary:
'Customer requests operation with a schedule day ' +
'(CLEARANCE_READY | OPERATION_CHANGES_REQUESTED → OPERATION_REQUEST_PENDING)',
})
async proceedToOperation(@Param('id', ParseUUIDPipe) id: string) {
const booking = await this.transitionService.requestOperation(id);
async proceedToOperation(
@Param('id', ParseUUIDPipe) id: string,
@Body() dto: RequestOperationDto,
) {
const booking = await this.transitionService.requestOperation(
id,
dto.scheduledDate,
);
return this.transitionService.enrichBookingResponse(booking);
}
@Post(':id/operation/review')
@BookingStaff(FREIGHT_PERMS.bookings.operations)
@ApiOperation({
summary:
'Operations reviews an operation request: ACCEPT (→ batch pool), ' +
'REQUEST_CHANGES (→ back to customer), or ADJUST_PRICE (→ customer re-confirm)',
})
async reviewOperationRequest(
@Param('id', ParseUUIDPipe) id: string,
@Body() dto: OperationReviewDto,
@CurrentUser() user: AuthUserPayload,
) {
const booking = await this.transitionService.reviewOperationRequest(
id,
dto.decision,
resolveAuthUserId(user),
{ note: dto.note, amount: dto.amount },
);
return this.transitionService.enrichBookingResponse(booking);
}
@Post(':id/operation/confirm-price')
@ApiOperation({
summary:
'Customer confirms or rejects an operations price adjustment ' +
'(OPERATION_PRICE_PENDING_CONFIRM → batch pool | OPERATION_CHANGES_REQUESTED)',
})
async confirmOperationPrice(
@Param('id', ParseUUIDPipe) id: string,
@Body() dto: ConfirmOperationPriceDto,
) {
const booking = await this.transitionService.confirmOperationPrice(
id,
dto.accept,
);
return this.transitionService.enrichBookingResponse(booking);
}

View File

@@ -1,5 +1,7 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import {
IsBoolean,
IsDateString,
IsIn,
IsInt,
IsNumber,
@@ -99,3 +101,51 @@ export class ReviewDocumentDto {
@IsString()
note?: string;
}
export class RequestOperationDto {
@ApiProperty({
description:
'The schedule day (train departure day) the customer selects for this ' +
'shipment. ISO date — the booking enters the batch pool for this route + day.',
example: '2026-07-15',
})
@IsDateString()
scheduledDate!: string;
}
export class OperationReviewDto {
@ApiProperty({
description:
'The operations decision: ACCEPT enters the batch pool; REQUEST_CHANGES ' +
'returns it to the customer with a note; ADJUST_PRICE sets a new total the ' +
'customer must re-confirm before it proceeds.',
enum: ['ACCEPT', 'REQUEST_CHANGES', 'ADJUST_PRICE'],
})
@IsIn(['ACCEPT', 'REQUEST_CHANGES', 'ADJUST_PRICE'])
decision!: 'ACCEPT' | 'REQUEST_CHANGES' | 'ADJUST_PRICE';
@ApiPropertyOptional({
description: 'Required for REQUEST_CHANGES (what the customer must fix).',
})
@IsOptional()
@IsString()
note?: string;
@ApiPropertyOptional({
description: 'New total price — required for ADJUST_PRICE.',
})
@IsOptional()
@IsNumber()
@Min(0)
amount?: number;
}
export class ConfirmOperationPriceDto {
@ApiProperty({
description:
'true to accept the operations price adjustment and proceed to the ' +
'batch pool; false to reject it (returns to operation changes requested).',
})
@IsBoolean()
accept!: boolean;
}

View File

@@ -48,6 +48,12 @@ export const BOOKING_STATUSES = [
'DOCUMENTS_UNDER_REVIEW',
'CLEARANCE_READY',
'OPERATION_REQUESTED',
// Operations review gate: customer picks a schedule day and submits the
// operation request; the operations team reviews capacity/docs/route before
// the booking enters the batch holding pool.
'OPERATION_REQUEST_PENDING',
'OPERATION_CHANGES_REQUESTED',
'OPERATION_PRICE_PENDING_CONFIRM',
] as const;
export type BookingStatus = (typeof BOOKING_STATUSES)[number];

View File

@@ -216,6 +216,26 @@ export class BookingBatchService implements OnModuleInit {
);
}
/**
* Fire-and-forget batch pipeline for a (route, day) directly — used when a
* booking enters the pool without a target train yet (e.g. after the
* operations team accepts an operation request). The booking is already
* FULLY_EXECUTED with its scheduled_date set, so the day-level fill will pick
* it up; this just runs that fill immediately instead of waiting for the cron.
*/
enqueueRouteDayProcessing(
originYardId: string,
destinationYardId: string,
day: string,
): void {
void this.processRouteDay({ originYardId, destinationYardId, day }).catch(
(err) =>
this.logger.error(
`processRouteDay for ${originYardId}${destinationYardId} on ${day} failed: ${(err as Error).message}`,
),
);
}
/** Resolve a schedule's (route, day) group and run the day-level pipeline. */
private async processRouteDayForSchedule(scheduleId: string): Promise<void> {
const schedule = await this.trainSchedulesRepository.findById(scheduleId);