Enhance clearance milestone management and introduce new contract actions

- Added new milestones for 'Transit Permit Uploaded' and 'Export Transport Document Issued' in the clearance milestone catalog.
- Implemented methods in ClearanceMilestoneService to skip milestones and complete them with metadata.
- Updated ContractBookingService to check boundary conditions before booking creation.
- Introduced new endpoints in ContractsController for uploading customs declarations, advising duty, and handling various document uploads.
- Enhanced the UI to support new clearance actions and display relevant components based on milestone statuses.
This commit is contained in:
marshal
2026-07-01 10:20:16 +03:00
parent ccd5d6de31
commit 612df8daff
36 changed files with 3018 additions and 57 deletions

View File

@@ -1,13 +1,20 @@
import { BadRequestException, ConflictException, Injectable } from '@nestjs/common';
import { ContractDocPhase } from '@edr/types';
import { DropdownSettingsService } from '../dropdown-settings/dropdown-settings.service';
import { FileUploadSettingsService } from '../file-upload-settings/file-upload-settings.service';
import { FilesService } from '../files/files.service';
import { ContractsRepository } from './contracts.repository';
import { ContractsService, PaginatedContracts } from './contracts.service';
import { contractClearanceCodes } from './contract-clearance.util';
import { ClearanceWorkflowService } from './clearance-workflow.service';
import { ClearanceMilestoneService } from './clearance-milestone.service';
import { Contract } from './entities/contract.entity';
import { ContractDocReviewStatus } from './entities/contract-document-review.entity';
import { FilterContractDto } from './dto/filter-contract.dto';
import { AdviseContractDutyDto } from './dto/phased-clearance.dto';
const RO_VESSEL_MIN_DAYS_CODE = 'ro_vessel_min_days';
export interface ContractClearanceDocument {
fileKey: string;
@@ -34,6 +41,28 @@ export interface ContractClearanceView {
outputCode: string | null;
documents: ContractClearanceDocument[];
allApproved: boolean;
phase?: string | null;
milestones?: Array<{
id: string;
milestoneCode: string;
milestoneLabel: string;
status: string;
ownerRegion?: string | null;
metadata?: Record<string, unknown> | null;
sortOrder: number;
}>;
nextAction?: {
actor: string;
action: string;
milestoneCode?: string | null;
blockedReason?: string | null;
} | null;
dutyRequired?: boolean | null;
roHold?: boolean;
roHoldReason?: string | null;
vesselDepartureDate?: string | null;
roAmendmentRequestedAt?: string | null;
bookingReady?: boolean;
}
@Injectable()
@@ -43,8 +72,20 @@ export class ContractClearanceService {
private readonly contractsService: ContractsService,
private readonly filesService: FilesService,
private readonly fileUploadSettingsService: FileUploadSettingsService,
private readonly workflowService: ClearanceWorkflowService,
private readonly milestoneService: ClearanceMilestoneService,
private readonly dropdownSettingsService: DropdownSettingsService,
) {}
private assertPhasedCustoms(contract: Contract): void {
if (!contract.customsClearingEnabled) {
throw new BadRequestException('Phased clearance applies only to customs contracts.');
}
if (contract.contractKind !== 'ONE_TIME') {
throw new BadRequestException('Phased clearance (Phase 1) applies to one-time contracts.');
}
}
/** The pre-booking clearance document grid for a contract (Path B). */
async getClearanceView(contractId: string): Promise<ContractClearanceView> {
const contract = await this.contractsService.findById(contractId);
@@ -109,6 +150,13 @@ export class ContractClearanceService {
}
const allApproved = await this.isClearanceFullyApproved(contract);
const milestones = await this.workflowService.listMilestones(contractId);
const phase = this.workflowService.resolvePhase(contract, cycle, milestones);
const nextAction = this.workflowService.computeNextAction(contract, cycle, milestones);
const boundary = await this.workflowService.isBoundaryComplete(
contractId,
contract.tradeDirection,
);
return {
contractId,
@@ -120,6 +168,25 @@ export class ContractClearanceService {
outputCode,
documents,
allApproved,
phase,
milestones: milestones.map((m) => ({
id: m.id,
milestoneCode: m.milestoneCode,
milestoneLabel: m.milestoneLabel,
status: m.status,
ownerRegion: m.ownerRegion,
metadata: (m.metadata ?? null) as Record<string, unknown> | null,
sortOrder: m.sortOrder,
})),
nextAction,
dutyRequired: cycle?.dutyRequired ?? null,
roHold: Boolean(cycle?.roHoldReason),
roHoldReason: cycle?.roHoldReason ?? null,
vesselDepartureDate: cycle?.vesselDepartureDate ?? null,
roAmendmentRequestedAt: cycle?.roAmendmentRequestedAt
? cycle.roAmendmentRequestedAt.toISOString()
: null,
bookingReady: boundary,
};
}
@@ -262,8 +329,15 @@ export class ContractClearanceService {
clearanceStatus: 'DOCUMENTS_UNDER_REVIEW',
} as never);
if (cycle) {
await this.contractsRepository.setCycleStatus(cycle.id, 'DOCUMENTS_UNDER_REVIEW');
await this.contractsRepository.setCycleStatus(cycle.id, 'DOCUMENTS_UNDER_REVIEW', {
currentPhase: ContractDocPhase.GlEtReview,
});
}
if (contract.customsClearingEnabled && contract.contractKind === 'ONE_TIME') {
await this.workflowService.onCustomerDocsUploaded(contractId, contract.tradeDirection);
}
return this.contractsService.findById(contractId);
}
@@ -391,6 +465,23 @@ export class ContractClearanceService {
}
} else if (status === 'APPROVED') {
await this.bumpToUnderReviewWhenFullyApproved(contractId);
const refreshed = await this.contractsService.findById(contractId);
if (
refreshed.customsClearingEnabled &&
refreshed.contractKind === 'ONE_TIME' &&
(await this.isClearanceFullyApproved(refreshed))
) {
await this.workflowService.onAllDocsApproved(contractId);
const c = await this.contractsRepository.currentCycle(contractId);
if (c) {
await this.contractsRepository.updateCycle(c.id, {
currentPhase:
refreshed.tradeDirection === 'EXPORT'
? ContractDocPhase.GlDjCollection
: ContractDocPhase.GlEtOutput,
});
}
}
}
return this.contractsService.findById(contractId);
@@ -567,4 +658,395 @@ export class ContractClearanceService {
sortOrder: filter.sortOrder ?? 'DESC',
});
}
// ── Phased clearance actions (ONE_TIME customs, Phase 1) ───────────────────
async uploadDeclaration(
contractId: string,
files: Express.Multer.File[],
userId?: string,
): Promise<Contract> {
const contract = await this.contractsService.findById(contractId);
this.assertPhasedCustoms(contract);
await this.workflowService.assertPriorComplete(
contractId,
contract.tradeDirection,
'DECLARED',
);
if (files.length === 0) {
throw new BadRequestException('No declaration documents uploaded');
}
for (const file of files) {
await this.filesService.upsertByCode({
resourceId: contractId,
resource: 'contracts',
code: file.fieldname,
file,
});
}
await this.workflowService.onDeclarationUploaded(contractId, userId);
const cycle = await this.contractsRepository.currentCycle(contractId);
if (cycle) {
await this.contractsRepository.updateCycle(cycle.id, {
currentPhase:
contract.tradeDirection === 'EXPORT'
? ContractDocPhase.GlEtPostClearance
: ContractDocPhase.CustomerDuty,
});
}
return this.contractsService.findById(contractId);
}
async adviseDuty(
contractId: string,
dto: AdviseContractDutyDto,
userId?: string,
): Promise<Contract> {
const contract = await this.contractsService.findById(contractId);
this.assertPhasedCustoms(contract);
if (contract.tradeDirection !== 'IMPORT') {
throw new BadRequestException('Duty advice applies only to import contracts.');
}
await this.workflowService.assertPriorComplete(contractId, 'IMPORT', 'DUTY_TAXES_ADVISED');
const cycle = await this.contractsRepository.currentCycle(contractId);
if (!cycle) throw new BadRequestException('No clearance cycle found');
await this.contractsRepository.updateCycle(cycle.id, {
dutyRequired: dto.dutyRequired,
currentPhase: dto.dutyRequired
? ContractDocPhase.CustomerDuty
: ContractDocPhase.GlEtPostClearance,
});
if (!dto.dutyRequired) {
await this.workflowService.onDutySkipped(contractId);
} else {
if (dto.amount == null || dto.amount < 0) {
throw new BadRequestException('Duty amount is required when duty applies.');
}
await this.milestoneService.adviseDutyForContract(
contractId,
{
amount: dto.amount,
currency: dto.currency ?? 'ETB',
declarationSerial: dto.declarationSerial,
},
userId,
);
}
return this.contractsService.findById(contractId);
}
async uploadDutySlip(
contractId: string,
file: Express.Multer.File,
): Promise<Contract> {
const contract = await this.contractsService.findById(contractId);
this.assertPhasedCustoms(contract);
if (contract.tradeDirection !== 'IMPORT') {
throw new BadRequestException('Duty slip upload applies only to import contracts.');
}
const cycle = await this.contractsRepository.currentCycle(contractId);
if (!cycle?.dutyRequired) {
throw new BadRequestException('Duty/tax is not required for this clearance.');
}
if (!file) throw new BadRequestException('No payment slip uploaded');
await this.filesService.upsertByCode({
resourceId: contractId,
resource: 'contracts',
code: 'duty_tax_receipt',
file,
});
await this.workflowService.completeMilestone(contractId, 'DUTY_TAX_PAID');
if (cycle) {
await this.contractsRepository.updateCycle(cycle.id, {
currentPhase: ContractDocPhase.GlEtPostClearance,
});
}
return this.contractsService.findById(contractId);
}
async uploadTransitPermit(
contractId: string,
file: Express.Multer.File,
userId?: string,
): Promise<Contract> {
const contract = await this.contractsService.findById(contractId);
this.assertPhasedCustoms(contract);
if (contract.tradeDirection !== 'IMPORT') {
throw new BadRequestException('Transit permit applies only to import contracts.');
}
await this.workflowService.assertPriorComplete(
contractId,
'IMPORT',
'TRANSIT_PERMIT_UPLOADED',
);
if (!file) throw new BadRequestException('No transit permit uploaded');
await this.filesService.upsertByCode({
resourceId: contractId,
resource: 'contracts',
code: 'transit_permitted',
file,
});
await this.workflowService.completeMilestone(contractId, 'TRANSIT_PERMIT_UPLOADED', userId);
const cycle = await this.contractsRepository.currentCycle(contractId);
if (cycle) {
await this.contractsRepository.updateCycle(cycle.id, {
currentPhase: ContractDocPhase.GlDjCollection,
});
}
return this.contractsService.findById(contractId);
}
async uploadDeliveryOrder(
contractId: string,
file: Express.Multer.File,
userId?: string,
): Promise<Contract> {
const contract = await this.contractsService.findById(contractId);
this.assertPhasedCustoms(contract);
if (contract.tradeDirection !== 'IMPORT') {
throw new BadRequestException('Delivery Order applies only to import contracts.');
}
await this.workflowService.assertPriorComplete(contractId, 'IMPORT', 'DO_COLLECTED');
if (!file) throw new BadRequestException('No Delivery Order uploaded');
await this.filesService.upsertByCode({
resourceId: contractId,
resource: 'contracts',
code: 'delivery_order',
file,
});
await this.workflowService.completeMilestone(contractId, 'DO_COLLECTED', userId);
await this.workflowService.markReadyForBooking(contractId);
return this.contractsService.findById(contractId);
}
private async resolveRoMinDays(): Promise<number> {
try {
const setting = await this.dropdownSettingsService.getByCode(RO_VESSEL_MIN_DAYS_CODE);
const first = setting.children?.[0];
const n = Number(first?.value);
return Number.isFinite(n) && n > 0 ? n : 2;
} catch {
return 2;
}
}
private daysUntil(dateStr: string): number {
const target = new Date(dateStr);
const today = new Date();
today.setHours(0, 0, 0, 0);
target.setHours(0, 0, 0, 0);
return Math.floor((target.getTime() - today.getTime()) / (24 * 60 * 60 * 1000));
}
async uploadReleaseOrder(
contractId: string,
file: Express.Multer.File,
vesselDepartureDate: string,
userId?: string,
): Promise<{ contract: Contract; hold: boolean; holdReason?: string }> {
const contract = await this.contractsService.findById(contractId);
this.assertPhasedCustoms(contract);
if (contract.tradeDirection !== 'EXPORT') {
throw new BadRequestException('Release Order applies only to export contracts.');
}
await this.workflowService.assertPriorComplete(
contractId,
'EXPORT',
'RELEASE_ORDER_SECURED',
);
if (!file) throw new BadRequestException('No Release Order uploaded');
if (!vesselDepartureDate?.trim()) {
throw new BadRequestException('Vessel departure date is required');
}
const minDays = await this.resolveRoMinDays();
const leadDays = this.daysUntil(vesselDepartureDate);
const cycle = await this.contractsRepository.currentCycle(contractId);
if (!cycle) throw new BadRequestException('No clearance cycle found');
await this.filesService.upsertByCode({
resourceId: contractId,
resource: 'contracts',
code: 'release_order',
file,
});
await this.contractsRepository.updateCycle(cycle.id, {
vesselDepartureDate,
roAmendmentRequestedAt: null,
});
if (leadDays < minDays) {
const reason = `Vessel departs in ${leadDays} day(s) — minimum lead time is ${minDays} day(s). Request a port amendment or upload a new RO with a later date.`;
await this.contractsRepository.updateCycle(cycle.id, {
roHoldReason: reason,
currentPhase: ContractDocPhase.GlDjCollection,
});
return { contract: await this.contractsService.findById(contractId), hold: true, holdReason: reason };
}
await this.contractsRepository.updateCycle(cycle.id, {
roHoldReason: null,
currentPhase: ContractDocPhase.GlEtOutput,
});
await this.workflowService.completeMilestone(contractId, 'RELEASE_ORDER_SECURED', userId);
return { contract: await this.contractsService.findById(contractId), hold: false };
}
async requestRoAmendment(
contractId: string,
note?: string,
userId?: string,
): Promise<Contract> {
const contract = await this.contractsService.findById(contractId);
this.assertPhasedCustoms(contract);
if (contract.tradeDirection !== 'EXPORT') {
throw new BadRequestException('RO amendment applies only to export contracts.');
}
const cycle = await this.contractsRepository.currentCycle(contractId);
if (!cycle) throw new BadRequestException('No clearance cycle found');
const reason =
note?.trim() ||
'Port amendment requested — vessel departure window is too short. A new Release Order will be required.';
await this.contractsRepository.updateCycle(cycle.id, {
roAmendmentRequestedAt: new Date(),
roHoldReason: reason,
currentPhase: ContractDocPhase.GlDjCollection,
});
if (userId) {
await this.contractsRepository.createReviewNote(
contractId,
reason,
'CHANGES_REQUESTED',
userId,
'GL_DJ',
);
}
return this.contractsService.findById(contractId);
}
async confirmExportRelease(contractId: string, userId?: string): Promise<Contract> {
const contract = await this.contractsService.findById(contractId);
this.assertPhasedCustoms(contract);
if (contract.tradeDirection !== 'EXPORT') {
throw new BadRequestException('Export release applies only to export contracts.');
}
await this.workflowService.assertPriorComplete(contractId, 'EXPORT', 'EXPORT_RELEASED');
await this.workflowService.onExportReleased(contractId, userId);
return this.contractsService.findById(contractId);
}
/** GL ET queue: customs ONE_TIME contracts with a pending ET-owned milestone. */
async etQueue(filter: FilterContractDto): Promise<PaginatedContracts> {
const base = await this.contractsRepository.findAllPaginated({
page: 1,
pageSize: 500,
statuses: ['AWAITING_CLEARANCE_DOCUMENTS', 'CLEARANCE_UNDER_REVIEW', 'CLEARANCE_READY_FOR_BOOKING'],
customsClearingEnabled: true,
contractKind: 'ONE_TIME',
sortBy: filter.sortBy,
sortOrder: filter.sortOrder,
});
const filtered: typeof base.items = [];
for (const c of base.items) {
const milestones = await this.workflowService.listMilestones(c.id);
const pending = this.workflowService.etPendingMilestoneCodes(milestones);
const next = this.workflowService.computeNextAction(
c,
await this.contractsRepository.currentCycle(c.id),
milestones,
);
if (pending || next?.actor === 'GL_ET') filtered.push(c);
}
const page = filter.page ?? 1;
const pageSize = filter.pageSize ?? 50;
const start = (page - 1) * pageSize;
const items = filtered.slice(start, start + pageSize);
return {
items,
total: filtered.length,
meta: {
page,
pageSize,
total: filtered.length,
totalPages: Math.ceil(filtered.length / pageSize) || 1,
hasNextPage: start + pageSize < filtered.length,
hasPreviousPage: page > 1,
},
};
}
/** GL DJ queue: customs ONE_TIME contracts with a pending DJ-owned milestone or RO hold. */
async djQueue(filter: FilterContractDto): Promise<PaginatedContracts> {
const base = await this.contractsRepository.findAllPaginated({
page: 1,
pageSize: 500,
statuses: ['AWAITING_CLEARANCE_DOCUMENTS', 'CLEARANCE_UNDER_REVIEW', 'CLEARANCE_READY_FOR_BOOKING'],
customsClearingEnabled: true,
contractKind: 'ONE_TIME',
sortBy: filter.sortBy,
sortOrder: filter.sortOrder,
});
const filtered: typeof base.items = [];
for (const c of base.items) {
const cycle = await this.contractsRepository.currentCycle(c.id);
const milestones = await this.workflowService.listMilestones(c.id);
const pending = this.workflowService.djPendingMilestoneCodes(milestones);
const next = this.workflowService.computeNextAction(c, cycle, milestones);
if (cycle?.roHoldReason || pending || next?.actor === 'GL_DJ') filtered.push(c);
}
const page = filter.page ?? 1;
const pageSize = filter.pageSize ?? 50;
const start = (page - 1) * pageSize;
const items = filtered.slice(start, start + pageSize);
return {
items,
total: filtered.length,
meta: {
page,
pageSize,
total: filtered.length,
totalPages: Math.ceil(filtered.length / pageSize) || 1,
hasNextPage: start + pageSize < filtered.length,
hasPreviousPage: page > 1,
},
};
}
}