finilize gl

This commit is contained in:
marshal
2026-07-02 12:06:17 +03:00
parent 9c18d086d7
commit 4fefe4f827
50 changed files with 5150 additions and 1793 deletions

View File

@@ -6,6 +6,7 @@ import { FileUploadSettingsService } from '../file-upload-settings/file-upload-s
import { FilesService } from '../files/files.service';
import { ContractsRepository } from './contracts.repository';
import { ContractsService, PaginatedContracts } from './contracts.service';
import { BookingsService } from '../bookings/bookings.service';
import { contractClearanceCodes } from './contract-clearance.util';
import { ClearanceWorkflowService } from './clearance-workflow.service';
import { ClearanceMilestoneService } from './clearance-milestone.service';
@@ -14,7 +15,7 @@ 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';
import { assertDeclarationFiles, buildWorkflowFiles } from './phased-clearance.util';
import { buildWorkflowFiles, belongsOnDjClearanceQueue, belongsOnEtClearanceQueue, DJ_CONTRACT_QUEUE_STATUSES, persistDeclarationUploads, persistTransitPermitUploads, PHASED_CUSTOMS_CONTRACT_QUEUE_STATUSES } from './phased-clearance.util';
const RO_VESSEL_MIN_DAYS_CODE = 'ro_vessel_min_days';
@@ -66,6 +67,9 @@ export interface ContractClearanceView {
roAmendmentRequestedAt?: string | null;
bookingReady?: boolean;
preClearanceFinalized?: boolean;
/** Export post-booking clearance finalized (transit permit uploaded + GL confirmed). */
exportClearanceFinalized?: boolean;
linkedBookingId?: string | null;
dutyAdvice?: {
amount: number;
currency: string;
@@ -80,6 +84,7 @@ export class ContractClearanceService {
constructor(
private readonly contractsRepository: ContractsRepository,
private readonly contractsService: ContractsService,
private readonly bookingsService: BookingsService,
private readonly filesService: FilesService,
private readonly fileUploadSettingsService: FileUploadSettingsService,
private readonly workflowService: ClearanceWorkflowService,
@@ -198,14 +203,40 @@ export class ContractClearanceService {
);
contract = await this.reconcilePrematureBookingReady(contractId, contract, boundary);
const phase = this.workflowService.resolvePhase(contract, cycle, milestones);
const nextAction = this.workflowService.computeNextAction(contract, cycle, milestones);
const dutyAdvice = this.buildDutyAdvice(files, milestones);
const documentFileKeys = new Set(documents.map((d) => d.fileKey));
const workflowFiles = buildWorkflowFiles(
let workflowFiles = buildWorkflowFiles(
files,
contract.tradeDirection ?? 'IMPORT',
documentFileKeys,
);
if (cycle?.bookingId) {
const bookingFiles = await this.filesService.findByResource(
cycle.bookingId,
'bookings',
);
const bookingWorkflow = buildWorkflowFiles(
bookingFiles,
contract.tradeDirection ?? 'IMPORT',
);
const byCode = new Map(workflowFiles.map((f) => [f.code, f]));
for (const row of bookingWorkflow) {
if (row.file) byCode.set(row.code, row);
}
workflowFiles = [...byCode.values()];
}
let nextAction = this.workflowService.computeNextAction(contract, cycle, milestones);
if (cycle?.bookingId && contract.tradeDirection === 'EXPORT') {
const bookingMilestones = await this.workflowService.listMilestonesForBooking(
cycle.bookingId,
);
const booking = await this.bookingsService.findById(cycle.bookingId);
if (booking) {
nextAction = this.workflowService.computeNextActionForBooking(
booking,
bookingMilestones,
);
}
}
return {
contractId,
@@ -237,6 +268,8 @@ export class ContractClearanceService {
: null,
bookingReady: boundary,
preClearanceFinalized: Boolean(cycle?.preClearanceFinalizedAt),
exportClearanceFinalized: Boolean(cycle?.completedAt),
linkedBookingId: cycle?.bookingId ?? null,
dutyAdvice,
workflowFiles,
};
@@ -413,6 +446,7 @@ export class ContractClearanceService {
if (contract.customsClearingEnabled && contract.contractKind === 'ONE_TIME') {
await this.workflowService.onCustomerDocsUploaded(contractId, contract.tradeDirection);
await this.workflowService.onDocumentReviewReopened(contractId);
}
return this.contractsService.findById(contractId);
@@ -505,6 +539,15 @@ export class ContractClearanceService {
const { inputCode, outputCode } = contractClearanceCodes(contract);
const cycle = await this.contractsRepository.currentCycle(contractId);
if (
status === 'QUERIED' &&
this.isPhasedCustoms(contract) &&
cycle?.preClearanceFinalizedAt
) {
throw new BadRequestException(
'Customer documents cannot be queried after pre-clearance is finalized.',
);
}
const reviews = await this.contractsRepository.findDocumentReviews(
contractId,
cycle?.id ?? null,
@@ -539,10 +582,12 @@ export class ContractClearanceService {
} as never);
if (cycle) {
await this.contractsRepository.setCycleStatus(cycle.id, 'AWAITING_DOCUMENTS');
if (this.isPhasedCustoms(contract) && cycle.preClearanceFinalizedAt) {
}
if (this.isPhasedCustoms(contract)) {
await this.workflowService.onDocumentReviewReopened(contractId);
if (cycle) {
await this.contractsRepository.updateCycle(cycle.id, {
preClearanceFinalizedAt: null,
currentPhase: ContractDocPhase.GlEtPostClearance,
currentPhase: ContractDocPhase.GlEtReview,
});
}
}
@@ -704,19 +749,14 @@ export class ContractClearanceService {
}
/**
* GL ET clearance hub: every customs (Path B) contract that still needs
* customs clearance — awaiting the customer's documents, under GL review, or
* finalized and waiting for the customer to create the booking in the portal.
* GL ET clearance hub: every customs (Path B) contract in phased clearance,
* including after booking is created.
*/
async queue(filter: FilterContractDto): Promise<PaginatedContracts> {
return this.contractsRepository.findAllPaginated({
page: filter.page ?? 1,
pageSize: filter.pageSize ?? 100,
statuses: [
'AWAITING_CLEARANCE_DOCUMENTS',
'CLEARANCE_UNDER_REVIEW',
'CLEARANCE_READY_FOR_BOOKING',
],
statuses: [...PHASED_CUSTOMS_CONTRACT_QUEUE_STATUSES],
customsClearingEnabled: true,
sortBy: filter.sortBy,
sortOrder: filter.sortOrder,
@@ -799,16 +839,13 @@ export class ContractClearanceService {
if (files.length === 0) {
throw new BadRequestException('No declaration documents uploaded');
}
assertDeclarationFiles(files, contract.tradeDirection);
for (const file of files) {
await this.filesService.upsertByCode({
resourceId: contractId,
resource: 'contracts',
code: file.fieldname,
file,
});
}
await persistDeclarationUploads(
this.filesService,
contractId,
'contracts',
files,
);
await this.workflowService.onDeclarationUploaded(contractId, userId);
@@ -913,7 +950,7 @@ export class ContractClearanceService {
async uploadTransitPermit(
contractId: string,
file: Express.Multer.File,
files: Express.Multer.File[],
userId?: string,
): Promise<Contract> {
const contract = await this.contractsService.findById(contractId);
@@ -927,14 +964,16 @@ export class ContractClearanceService {
'TRANSIT_PERMIT_UPLOADED',
);
if (!file) throw new BadRequestException('No transit permit uploaded');
if (files.length === 0) {
throw new BadRequestException('No transit permit documents uploaded');
}
await this.filesService.upsertByCode({
resourceId: contractId,
resource: 'contracts',
code: 'transit_permitted',
file,
});
await persistTransitPermitUploads(
this.filesService,
contractId,
'contracts',
files,
);
await this.workflowService.completeMilestone(contractId, 'TRANSIT_PERMIT_UPLOADED', userId);
@@ -1135,12 +1174,51 @@ export class ContractClearanceService {
return this.contractsService.findById(contractId);
}
/** GL ET queue: customs ONE_TIME contracts with a pending ET-owned milestone. */
/** GL ET finalizes export clearance after post-booking transit permit is uploaded. */
async finalizeExportClearance(contractId: string, userId?: string): Promise<Contract> {
const contract = await this.contractsService.findById(contractId);
this.assertPhasedCustoms(contract);
if (contract.tradeDirection !== 'EXPORT') {
throw new BadRequestException('Export clearance finalize applies only to export contracts.');
}
const cycle = await this.contractsRepository.currentCycle(contractId);
if (!cycle?.bookingId) {
throw new BadRequestException(
'A shipment booking must exist before export clearance can be finalized.',
);
}
if (cycle.completedAt) {
return this.contractsService.findById(contractId);
}
const bookingMilestones = await this.workflowService.listMilestonesForBooking(
cycle.bookingId,
);
const transportDone = bookingMilestones.some(
(m) => m.milestoneCode === 'EXPORT_TRANSPORT_ISSUED' && m.status === 'COMPLETED',
);
if (!transportDone) {
throw new BadRequestException(
'Upload the transit permit before finalizing export clearance.',
);
}
await this.contractsRepository.updateCycle(cycle.id, {
completedAt: new Date(),
currentPhase: ContractDocPhase.GlEtPostClearance,
});
void userId;
return this.contractsService.findById(contractId);
}
/** GL ET queue: customs ONE_TIME contracts in phased clearance (persistent after booking). */
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'],
statuses: [...PHASED_CUSTOMS_CONTRACT_QUEUE_STATUSES],
customsClearingEnabled: true,
contractKind: 'ONE_TIME',
sortBy: filter.sortBy,
@@ -1150,13 +1228,7 @@ export class ContractClearanceService {
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);
if (belongsOnEtClearanceQueue(milestones)) filtered.push(c);
}
const page = filter.page ?? 1;
@@ -1178,12 +1250,12 @@ export class ContractClearanceService {
};
}
/** GL DJ queue: customs ONE_TIME contracts with a pending DJ-owned milestone or RO hold. */
/** GL DJ queue: customs ONE_TIME contracts handed off to or handled by Djibouti GL. */
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'],
statuses: [...DJ_CONTRACT_QUEUE_STATUSES],
customsClearingEnabled: true,
contractKind: 'ONE_TIME',
sortBy: filter.sortBy,
@@ -1194,9 +1266,9 @@ export class ContractClearanceService {
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);
if (belongsOnDjClearanceQueue(c.tradeDirection, cycle, milestones)) {
filtered.push(c);
}
}
const page = filter.page ?? 1;