mirror of
https://github.com/Tria-plc/edr-platform.git
synced 2026-08-28 10:10:57 +00:00
api
This commit is contained in:
@@ -0,0 +1,3 @@
|
||||
import { GenerateFromScheduleDto } from './generate-from-schedule.dto';
|
||||
|
||||
export class CreateInterchangeDocumentDto extends GenerateFromScheduleDto {}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { IsIn, IsOptional, IsString, IsUUID, MaxLength } from 'class-validator';
|
||||
|
||||
import { INTERCHANGE_DIRECTIONS, InterchangeDirection } from '../entities/interchange-document.entity';
|
||||
|
||||
export class GenerateFromScheduleDto {
|
||||
@IsUUID()
|
||||
scheduleId!: string;
|
||||
|
||||
@IsIn(INTERCHANGE_DIRECTIONS)
|
||||
direction!: InterchangeDirection;
|
||||
|
||||
@IsString()
|
||||
@MaxLength(255)
|
||||
handoverLocation!: string;
|
||||
|
||||
@IsString()
|
||||
@MaxLength(255)
|
||||
handoverFrom!: string;
|
||||
|
||||
@IsString()
|
||||
@MaxLength(255)
|
||||
handoverTo!: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(255)
|
||||
operatorName?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(255)
|
||||
portOperatorName?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(255)
|
||||
shippingLineName?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(120)
|
||||
customsReference?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(120)
|
||||
manifestReference?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(120)
|
||||
generatedBy?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
remarks?: string;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { IsIn, IsOptional, IsString, IsUUID } from 'class-validator';
|
||||
|
||||
import {
|
||||
INTERCHANGE_DIRECTIONS,
|
||||
INTERCHANGE_DOCUMENT_STATUSES,
|
||||
InterchangeDirection,
|
||||
InterchangeDocumentStatus,
|
||||
} from '../entities/interchange-document.entity';
|
||||
|
||||
export class InterchangeDocumentQueryDto {
|
||||
@IsOptional()
|
||||
@IsIn(INTERCHANGE_DIRECTIONS)
|
||||
direction?: InterchangeDirection;
|
||||
|
||||
@IsOptional()
|
||||
@IsIn(INTERCHANGE_DOCUMENT_STATUSES)
|
||||
status?: InterchangeDocumentStatus;
|
||||
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
scheduleId?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
documentNo?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
dateFrom?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
dateTo?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
search?: string;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { IsOptional, IsString, MaxLength } from 'class-validator';
|
||||
|
||||
export class AcknowledgeInterchangeDocumentDto {
|
||||
@IsString()
|
||||
@MaxLength(120)
|
||||
acknowledgedBy!: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
remarks?: string;
|
||||
}
|
||||
|
||||
export class DisputeInterchangeDocumentDto {
|
||||
@IsString()
|
||||
remarks!: string;
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { BaseEntity } from '@edr/api-common';
|
||||
import { Column, Entity, Index, JoinColumn, ManyToOne } from 'typeorm';
|
||||
|
||||
import { Booking } from '../../bookings/entities/booking.entity';
|
||||
import { InterchangeDocument } from './interchange-document.entity';
|
||||
|
||||
export const INTERCHANGE_ITEM_TYPES = ['CONTAINER', 'CARGO'] as const;
|
||||
export type InterchangeItemType = (typeof INTERCHANGE_ITEM_TYPES)[number];
|
||||
|
||||
export const INTERCHANGE_CONDITION_STATUSES = [
|
||||
'GOOD',
|
||||
'DAMAGED',
|
||||
'SHORTAGE',
|
||||
'EXCESS',
|
||||
'HOLD',
|
||||
'UNKNOWN',
|
||||
] as const;
|
||||
export type InterchangeConditionStatus = (typeof INTERCHANGE_CONDITION_STATUSES)[number];
|
||||
|
||||
@Entity({ schema: 'freight', name: 'interchange_document_items' })
|
||||
@Index(['interchangeDocumentId'])
|
||||
@Index(['bookingId'])
|
||||
export class InterchangeDocumentItem extends BaseEntity {
|
||||
@Column({ name: 'interchange_document_id', type: 'uuid' })
|
||||
interchangeDocumentId!: string;
|
||||
|
||||
@ManyToOne(() => InterchangeDocument, (document) => document.items, { onDelete: 'CASCADE' })
|
||||
@JoinColumn({ name: 'interchange_document_id' })
|
||||
document?: InterchangeDocument;
|
||||
|
||||
@Column({ name: 'booking_id', type: 'uuid', nullable: true })
|
||||
bookingId?: string | null;
|
||||
|
||||
@ManyToOne(() => Booking, { nullable: true, onDelete: 'SET NULL' })
|
||||
@JoinColumn({ name: 'booking_id' })
|
||||
booking?: Booking | null;
|
||||
|
||||
@Column({ name: 'booking_reference', type: 'varchar', length: 64, nullable: true })
|
||||
bookingReference?: string | null;
|
||||
|
||||
@Column({ name: 'item_type', type: 'varchar', length: 20 })
|
||||
itemType!: InterchangeItemType;
|
||||
|
||||
@Column({ name: 'booking_container_id', type: 'uuid', nullable: true })
|
||||
bookingContainerId?: string | null;
|
||||
|
||||
@Column({ name: 'booking_cargo_id', type: 'uuid', nullable: true })
|
||||
bookingCargoId?: string | null;
|
||||
|
||||
@Column({ name: 'container_number', type: 'varchar', length: 64, nullable: true })
|
||||
containerNumber?: string | null;
|
||||
|
||||
@Column({ name: 'seal_number', type: 'varchar', length: 100, nullable: true })
|
||||
sealNumber?: string | null;
|
||||
|
||||
@Column({ name: 'cargo_id', type: 'uuid', nullable: true })
|
||||
cargoId?: string | null;
|
||||
|
||||
@Column({ name: 'cargo_type', type: 'varchar', length: 255, nullable: true })
|
||||
cargoType?: string | null;
|
||||
|
||||
@Column({ name: 'cargo_description', type: 'text', nullable: true })
|
||||
cargoDescription?: string | null;
|
||||
|
||||
@Column({ name: 'weight', type: 'numeric', precision: 14, scale: 3, nullable: true })
|
||||
weight?: number | null;
|
||||
|
||||
@Column({ name: 'quantity', type: 'numeric', precision: 12, scale: 3, nullable: true })
|
||||
quantity?: number | null;
|
||||
|
||||
@Column({ name: 'package_count', type: 'int', nullable: true })
|
||||
packageCount?: number | null;
|
||||
|
||||
@Column({ name: 'wagon_number', type: 'varchar', length: 80, nullable: true })
|
||||
wagonNumber?: string | null;
|
||||
|
||||
@Column({ name: 'condition_status', type: 'varchar', length: 20, default: 'GOOD' })
|
||||
conditionStatus!: InterchangeConditionStatus;
|
||||
|
||||
@Column({ name: 'damage_description', type: 'text', nullable: true })
|
||||
damageDescription?: string | null;
|
||||
|
||||
@Column({ name: 'remarks', type: 'text', nullable: true })
|
||||
remarks?: string | null;
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import { BaseEntity } from '@edr/api-common';
|
||||
import { Column, Entity, Index, OneToMany } from 'typeorm';
|
||||
|
||||
import { InterchangeDocumentItem } from './interchange-document-item.entity';
|
||||
|
||||
export const INTERCHANGE_DIRECTIONS = ['IMPORT', 'EXPORT'] as const;
|
||||
export type InterchangeDirection = (typeof INTERCHANGE_DIRECTIONS)[number];
|
||||
|
||||
export const INTERCHANGE_DOCUMENT_STATUSES = [
|
||||
'DRAFT',
|
||||
'GENERATED',
|
||||
'ACKNOWLEDGED',
|
||||
'DISPUTED',
|
||||
'CANCELLED',
|
||||
] as const;
|
||||
export type InterchangeDocumentStatus = (typeof INTERCHANGE_DOCUMENT_STATUSES)[number];
|
||||
|
||||
@Entity({ schema: 'freight', name: 'interchange_documents' })
|
||||
@Index(['documentNo'], { unique: true })
|
||||
@Index(['direction'])
|
||||
@Index(['status'])
|
||||
@Index(['scheduleId'])
|
||||
export class InterchangeDocument extends BaseEntity {
|
||||
@Column({ name: 'document_no', type: 'varchar', length: 40, unique: true })
|
||||
documentNo!: string;
|
||||
|
||||
@Column({ name: 'direction', type: 'varchar', length: 10 })
|
||||
direction!: InterchangeDirection;
|
||||
|
||||
@Column({ name: 'schedule_id', type: 'uuid', nullable: true })
|
||||
scheduleId?: string | null;
|
||||
|
||||
@Column({ name: 'train_no', type: 'varchar', length: 40, nullable: true })
|
||||
trainNo?: string | null;
|
||||
|
||||
@Column({ name: 'route_id', type: 'uuid', nullable: true })
|
||||
routeId?: string | null;
|
||||
|
||||
@Column({ name: 'origin_facility_id', type: 'uuid', nullable: true })
|
||||
originFacilityId?: string | null;
|
||||
|
||||
@Column({ name: 'destination_facility_id', type: 'uuid', nullable: true })
|
||||
destinationFacilityId?: string | null;
|
||||
|
||||
@Column({ name: 'handover_location', type: 'varchar', length: 255 })
|
||||
handoverLocation!: string;
|
||||
|
||||
@Column({ name: 'handover_from', type: 'varchar', length: 255 })
|
||||
handoverFrom!: string;
|
||||
|
||||
@Column({ name: 'handover_to', type: 'varchar', length: 255 })
|
||||
handoverTo!: string;
|
||||
|
||||
@Column({ name: 'operator_name', type: 'varchar', length: 255, nullable: true })
|
||||
operatorName?: string | null;
|
||||
|
||||
@Column({ name: 'port_operator_name', type: 'varchar', length: 255, nullable: true })
|
||||
portOperatorName?: string | null;
|
||||
|
||||
@Column({ name: 'shipping_line_name', type: 'varchar', length: 255, nullable: true })
|
||||
shippingLineName?: string | null;
|
||||
|
||||
@Column({ name: 'customs_reference', type: 'varchar', length: 120, nullable: true })
|
||||
customsReference?: string | null;
|
||||
|
||||
@Column({ name: 'manifest_reference', type: 'varchar', length: 120, nullable: true })
|
||||
manifestReference?: string | null;
|
||||
|
||||
@Column({ name: 'status', type: 'varchar', length: 20, default: 'DRAFT' })
|
||||
status!: InterchangeDocumentStatus;
|
||||
|
||||
@Column({ name: 'generated_at', type: 'timestamptz', nullable: true })
|
||||
generatedAt?: Date | null;
|
||||
|
||||
@Column({ name: 'acknowledged_at', type: 'timestamptz', nullable: true })
|
||||
acknowledgedAt?: Date | null;
|
||||
|
||||
@Column({ name: 'generated_by', type: 'varchar', length: 120, nullable: true })
|
||||
generatedBy?: string | null;
|
||||
|
||||
@Column({ name: 'acknowledged_by', type: 'varchar', length: 120, nullable: true })
|
||||
acknowledgedBy?: string | null;
|
||||
|
||||
@Column({ name: 'remarks', type: 'text', nullable: true })
|
||||
remarks?: string | null;
|
||||
|
||||
@OneToMany(() => InterchangeDocumentItem, (item) => item.document)
|
||||
items?: InterchangeDocumentItem[];
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { Body, Controller, Get, Param, ParseUUIDPipe, Patch, Post, Query } from '@nestjs/common';
|
||||
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
|
||||
import { GenerateFromScheduleDto } from './dto/generate-from-schedule.dto';
|
||||
import { InterchangeDocumentQueryDto } from './dto/interchange-document-query.dto';
|
||||
import {
|
||||
AcknowledgeInterchangeDocumentDto,
|
||||
DisputeInterchangeDocumentDto,
|
||||
} from './dto/update-interchange-document-status.dto';
|
||||
import { InterchangeDocumentsService } from './interchange-documents.service';
|
||||
|
||||
@ApiTags('interchange-documents')
|
||||
@ApiBearerAuth()
|
||||
@Controller('interchange-documents')
|
||||
export class InterchangeDocumentsController {
|
||||
constructor(private readonly service: InterchangeDocumentsService) {}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: 'List interchange documents' })
|
||||
findAll(@Query() query: InterchangeDocumentQueryDto) {
|
||||
return this.service.findAll(query);
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
@ApiOperation({ summary: 'Get interchange document detail' })
|
||||
findOne(@Param('id', ParseUUIDPipe) id: string) {
|
||||
return this.service.findOne(id);
|
||||
}
|
||||
|
||||
@Post('generate-from-schedule')
|
||||
@ApiOperation({ summary: 'Generate interchange document from a train schedule handover' })
|
||||
generateFromSchedule(@Body() dto: GenerateFromScheduleDto) {
|
||||
return this.service.generateFromSchedule(dto);
|
||||
}
|
||||
|
||||
@Patch(':id/acknowledge')
|
||||
@ApiOperation({ summary: 'Acknowledge an interchange document' })
|
||||
acknowledge(
|
||||
@Param('id', ParseUUIDPipe) id: string,
|
||||
@Body() dto: AcknowledgeInterchangeDocumentDto,
|
||||
) {
|
||||
return this.service.acknowledge(id, dto);
|
||||
}
|
||||
|
||||
@Patch(':id/dispute')
|
||||
@ApiOperation({ summary: 'Dispute an interchange document' })
|
||||
dispute(@Param('id', ParseUUIDPipe) id: string, @Body() dto: DisputeInterchangeDocumentDto) {
|
||||
return this.service.dispute(id, dto);
|
||||
}
|
||||
|
||||
@Patch(':id/cancel')
|
||||
@ApiOperation({ summary: 'Cancel a draft/generated interchange document' })
|
||||
cancel(@Param('id', ParseUUIDPipe) id: string) {
|
||||
return this.service.cancel(id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
|
||||
import { InterchangeDocumentItem } from './entities/interchange-document-item.entity';
|
||||
import { InterchangeDocument } from './entities/interchange-document.entity';
|
||||
import { InterchangeDocumentsController } from './interchange-documents.controller';
|
||||
import { InterchangeDocumentsRepository } from './interchange-documents.repository';
|
||||
import { InterchangeDocumentsService } from './interchange-documents.service';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([InterchangeDocument, InterchangeDocumentItem])],
|
||||
controllers: [InterchangeDocumentsController],
|
||||
providers: [InterchangeDocumentsRepository, InterchangeDocumentsService],
|
||||
exports: [InterchangeDocumentsService],
|
||||
})
|
||||
export class InterchangeDocumentsModule {}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { BaseRepository } from '@edr/api-common';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
|
||||
import { InterchangeDocument } from './entities/interchange-document.entity';
|
||||
|
||||
@Injectable()
|
||||
export class InterchangeDocumentsRepository extends BaseRepository<InterchangeDocument> {
|
||||
constructor(@InjectRepository(InterchangeDocument) repository: Repository<InterchangeDocument>) {
|
||||
super(repository);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,392 @@
|
||||
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { DataSource, FindOptionsWhere, ILike, Not } from 'typeorm';
|
||||
|
||||
import { deriveTradeDirection } from '../../common/derive-trade-direction.util';
|
||||
import { GenerateFromScheduleDto } from './dto/generate-from-schedule.dto';
|
||||
import { InterchangeDocumentQueryDto } from './dto/interchange-document-query.dto';
|
||||
import {
|
||||
AcknowledgeInterchangeDocumentDto,
|
||||
DisputeInterchangeDocumentDto,
|
||||
} from './dto/update-interchange-document-status.dto';
|
||||
import { InterchangeDocumentItem } from './entities/interchange-document-item.entity';
|
||||
import {
|
||||
InterchangeDirection,
|
||||
InterchangeDocument,
|
||||
InterchangeDocumentStatus,
|
||||
} from './entities/interchange-document.entity';
|
||||
|
||||
interface ScheduleSnapshot {
|
||||
id: string;
|
||||
status: string;
|
||||
trainNo: string | null;
|
||||
routeId: string | null;
|
||||
originFacilityId: string | null;
|
||||
destinationFacilityId: string | null;
|
||||
originCountry: string | null;
|
||||
destinationCountry: string | null;
|
||||
}
|
||||
|
||||
interface InterchangeItemSnapshot {
|
||||
bookingId: string;
|
||||
bookingReference: string | null;
|
||||
itemType: 'CONTAINER' | 'CARGO';
|
||||
bookingContainerId: string | null;
|
||||
bookingCargoId: string | null;
|
||||
containerNumber: string | null;
|
||||
sealNumber: string | null;
|
||||
cargoId: string | null;
|
||||
cargoType: string | null;
|
||||
cargoDescription: string | null;
|
||||
weight: string | number | null;
|
||||
quantity: string | number | null;
|
||||
packageCount: string | number | null;
|
||||
wagonNumber: string | null;
|
||||
hasDamage: boolean | null;
|
||||
damageDescription: string | null;
|
||||
hasWeightLoss: boolean | null;
|
||||
hasMissingItems: boolean | null;
|
||||
missingItemsDescription: string | null;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class InterchangeDocumentsService {
|
||||
constructor(private readonly dataSource: DataSource) {}
|
||||
|
||||
async findAll(query: InterchangeDocumentQueryDto): Promise<InterchangeDocument[]> {
|
||||
const where: FindOptionsWhere<InterchangeDocument>[] = [];
|
||||
const base: FindOptionsWhere<InterchangeDocument> = {
|
||||
...(query.direction ? { direction: query.direction } : {}),
|
||||
...(query.status ? { status: query.status } : {}),
|
||||
...(query.scheduleId ? { scheduleId: query.scheduleId } : {}),
|
||||
...(query.documentNo ? { documentNo: ILike(`%${query.documentNo}%`) } : {}),
|
||||
};
|
||||
|
||||
const search = query.search?.trim();
|
||||
if (search) {
|
||||
where.push(
|
||||
{ ...base, documentNo: ILike(`%${search}%`) },
|
||||
{ ...base, trainNo: ILike(`%${search}%`) },
|
||||
{ ...base, handoverLocation: ILike(`%${search}%`) },
|
||||
{ ...base, handoverFrom: ILike(`%${search}%`) },
|
||||
{ ...base, handoverTo: ILike(`%${search}%`) },
|
||||
);
|
||||
}
|
||||
|
||||
const qb = this.dataSource
|
||||
.getRepository(InterchangeDocument)
|
||||
.createQueryBuilder('doc')
|
||||
.leftJoinAndSelect('doc.items', 'items')
|
||||
.where(where.length ? where : base)
|
||||
.orderBy('doc.createdAt', 'DESC')
|
||||
.addOrderBy('items.createdAt', 'ASC');
|
||||
|
||||
if (query.dateFrom) qb.andWhere('doc.created_at >= :dateFrom', { dateFrom: query.dateFrom });
|
||||
if (query.dateTo) qb.andWhere('doc.created_at <= :dateTo', { dateTo: query.dateTo });
|
||||
|
||||
return qb.getMany();
|
||||
}
|
||||
|
||||
async findOne(id: string): Promise<InterchangeDocument> {
|
||||
const document = await this.dataSource.getRepository(InterchangeDocument).findOne({
|
||||
where: { id },
|
||||
relations: { items: true },
|
||||
order: { items: { createdAt: 'ASC' } },
|
||||
});
|
||||
if (!document) throw new NotFoundException(`Interchange document ${id} not found`);
|
||||
return document;
|
||||
}
|
||||
|
||||
async generateFromSchedule(dto: GenerateFromScheduleDto): Promise<InterchangeDocument> {
|
||||
const existing = await this.dataSource.getRepository(InterchangeDocument).findOne({
|
||||
where: {
|
||||
scheduleId: dto.scheduleId,
|
||||
direction: dto.direction,
|
||||
status: Not('CANCELLED') as unknown as InterchangeDocumentStatus,
|
||||
},
|
||||
relations: { items: true },
|
||||
});
|
||||
if (existing) return existing;
|
||||
|
||||
const schedule = await this.getScheduleSnapshot(dto.scheduleId);
|
||||
const routeDirection = deriveTradeDirection(
|
||||
{ country: schedule.originCountry },
|
||||
{ country: schedule.destinationCountry },
|
||||
);
|
||||
if (routeDirection !== dto.direction) {
|
||||
throw new BadRequestException(`Train schedule route is ${routeDirection}, not ${dto.direction}`);
|
||||
}
|
||||
|
||||
const itemSnapshots = await this.getScheduleItems(dto.scheduleId);
|
||||
if (itemSnapshots.length === 0) {
|
||||
throw new BadRequestException('No booking/container/cargo items found for this schedule');
|
||||
}
|
||||
|
||||
return this.dataSource.transaction(async (manager) => {
|
||||
const now = new Date();
|
||||
const document = manager.getRepository(InterchangeDocument).create({
|
||||
documentNo: await this.nextDocumentNo(dto.direction),
|
||||
direction: dto.direction,
|
||||
scheduleId: schedule.id,
|
||||
trainNo: schedule.trainNo,
|
||||
routeId: schedule.routeId,
|
||||
originFacilityId: schedule.originFacilityId,
|
||||
destinationFacilityId: schedule.destinationFacilityId,
|
||||
handoverLocation: dto.handoverLocation.trim(),
|
||||
handoverFrom: dto.handoverFrom.trim(),
|
||||
handoverTo: dto.handoverTo.trim(),
|
||||
operatorName: dto.operatorName?.trim() || null,
|
||||
portOperatorName: dto.portOperatorName?.trim() || null,
|
||||
shippingLineName: dto.shippingLineName?.trim() || null,
|
||||
customsReference: dto.customsReference?.trim() || null,
|
||||
manifestReference: dto.manifestReference?.trim() || null,
|
||||
status: 'GENERATED',
|
||||
generatedAt: now,
|
||||
generatedBy: dto.generatedBy?.trim() || null,
|
||||
remarks: dto.remarks?.trim() || null,
|
||||
});
|
||||
const saved = await manager.getRepository(InterchangeDocument).save(document);
|
||||
|
||||
const items = itemSnapshots.map((item) =>
|
||||
manager.getRepository(InterchangeDocumentItem).create({
|
||||
interchangeDocumentId: saved.id,
|
||||
bookingId: item.bookingId,
|
||||
bookingReference: item.bookingReference,
|
||||
itemType: item.itemType,
|
||||
bookingContainerId: item.bookingContainerId,
|
||||
bookingCargoId: item.bookingCargoId,
|
||||
containerNumber: item.containerNumber,
|
||||
sealNumber: item.sealNumber,
|
||||
cargoId: item.cargoId,
|
||||
cargoType: item.cargoType,
|
||||
cargoDescription: item.cargoDescription,
|
||||
weight: item.weight === null ? null : Number(item.weight) || null,
|
||||
quantity: item.quantity === null ? null : Number(item.quantity) || null,
|
||||
packageCount: item.packageCount === null ? null : Number(item.packageCount) || null,
|
||||
wagonNumber: item.wagonNumber,
|
||||
conditionStatus: this.conditionFromInspection(item),
|
||||
damageDescription:
|
||||
item.damageDescription ?? item.missingItemsDescription ?? null,
|
||||
remarks: null,
|
||||
}),
|
||||
);
|
||||
await manager.getRepository(InterchangeDocumentItem).save(items);
|
||||
|
||||
return manager.getRepository(InterchangeDocument).findOneOrFail({
|
||||
where: { id: saved.id },
|
||||
relations: { items: true },
|
||||
order: { items: { createdAt: 'ASC' } },
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async acknowledge(
|
||||
id: string,
|
||||
dto: AcknowledgeInterchangeDocumentDto,
|
||||
): Promise<InterchangeDocument> {
|
||||
const document = await this.findOne(id);
|
||||
if (document.status === 'CANCELLED') {
|
||||
throw new BadRequestException('Cancelled interchange document cannot be acknowledged');
|
||||
}
|
||||
await this.dataSource.getRepository(InterchangeDocument).update(id, {
|
||||
status: 'ACKNOWLEDGED',
|
||||
acknowledgedAt: new Date(),
|
||||
acknowledgedBy: dto.acknowledgedBy,
|
||||
remarks: dto.remarks ?? document.remarks ?? null,
|
||||
});
|
||||
return this.findOne(id);
|
||||
}
|
||||
|
||||
async dispute(id: string, dto: DisputeInterchangeDocumentDto): Promise<InterchangeDocument> {
|
||||
await this.findOne(id);
|
||||
await this.dataSource.getRepository(InterchangeDocument).update(id, {
|
||||
status: 'DISPUTED',
|
||||
remarks: dto.remarks,
|
||||
});
|
||||
return this.findOne(id);
|
||||
}
|
||||
|
||||
async cancel(id: string): Promise<InterchangeDocument> {
|
||||
const document = await this.findOne(id);
|
||||
if (!['DRAFT', 'GENERATED'].includes(document.status)) {
|
||||
throw new BadRequestException(`Interchange document ${document.status} cannot be cancelled`);
|
||||
}
|
||||
await this.dataSource.getRepository(InterchangeDocument).update(id, { status: 'CANCELLED' });
|
||||
return this.findOne(id);
|
||||
}
|
||||
|
||||
private async getScheduleSnapshot(scheduleId: string): Promise<ScheduleSnapshot> {
|
||||
const [schedule] = await this.dataSource.query(
|
||||
`SELECT ts.id,
|
||||
ts.status,
|
||||
ts.train_number AS "trainNo",
|
||||
ts.route_id AS "routeId",
|
||||
ts.origin_station_id AS "originFacilityId",
|
||||
ts.destination_station_id AS "destinationFacilityId",
|
||||
oy.country AS "originCountry",
|
||||
dy.country AS "destinationCountry"
|
||||
FROM freight.train_schedules ts
|
||||
LEFT JOIN freight.yards oy ON oy.id = ts.origin_station_id
|
||||
LEFT JOIN freight.yards dy ON dy.id = ts.destination_station_id
|
||||
WHERE ts.id = $1 AND ts.deleted_at IS NULL
|
||||
LIMIT 1`,
|
||||
[scheduleId],
|
||||
);
|
||||
if (!schedule) throw new NotFoundException(`Train schedule ${scheduleId} not found`);
|
||||
return schedule;
|
||||
}
|
||||
|
||||
private async getScheduleItems(scheduleId: string): Promise<InterchangeItemSnapshot[]> {
|
||||
return this.dataSource.query(
|
||||
`WITH assigned AS (
|
||||
SELECT b.id AS booking_id,
|
||||
b.reference,
|
||||
COALESCE(cgt.cargo_type_name, b.cargo_free_text) AS booking_cargo_type,
|
||||
b.cargo_free_text,
|
||||
b.cargo_total_weight_vgm,
|
||||
(
|
||||
SELECT string_agg(DISTINCT w.wagon_number, ', ' ORDER BY w.wagon_number)
|
||||
FROM freight.wagon_booking_allocations wba
|
||||
JOIN freight.train_set_wagons tsw ON tsw.id = wba.train_set_wagon_id
|
||||
LEFT JOIN freight.wagons w ON w.id = tsw.physical_wagon_id
|
||||
WHERE wba.booking_id = b.id
|
||||
) AS wagon_number,
|
||||
bool_or(COALESCE(wir.has_damage, false)) AS has_damage,
|
||||
bool_or(COALESCE(wir.has_weight_loss, false)) AS has_weight_loss,
|
||||
bool_or(COALESCE(wir.has_missing_items, false)) AS has_missing_items,
|
||||
string_agg(DISTINCT NULLIF(wir.damage_description, ''), '; ') AS damage_description,
|
||||
string_agg(DISTINCT NULLIF(wir.missing_items_description, ''), '; ') AS missing_items_description
|
||||
FROM freight.train_schedule_bookings tsb
|
||||
JOIN freight.bookings b ON b.id = tsb.booking_id AND b.deleted_at IS NULL
|
||||
LEFT JOIN freight.cargo_types cgt ON cgt.id = b.cargo_type_id
|
||||
LEFT JOIN freight.warehouse_inventory inv ON inv.booking_id = b.id AND inv.deleted_at IS NULL
|
||||
LEFT JOIN freight.warehouse_inspection_reports wir ON wir.inventory_id = inv.id AND wir.deleted_at IS NULL
|
||||
WHERE tsb.train_schedule_id = $1 AND tsb.deleted_at IS NULL
|
||||
GROUP BY b.id, b.reference, cgt.cargo_type_name, b.cargo_free_text, b.cargo_total_weight_vgm
|
||||
)
|
||||
SELECT a.booking_id AS "bookingId",
|
||||
a.reference AS "bookingReference",
|
||||
'CONTAINER' AS "itemType",
|
||||
COALESCE(c.booking_container_id, bc.id) AS "bookingContainerId",
|
||||
NULL AS "bookingCargoId",
|
||||
COALESCE(c.container_number, bc.container_number) AS "containerNumber",
|
||||
c.seal_number AS "sealNumber",
|
||||
NULL AS "cargoId",
|
||||
a.booking_cargo_type AS "cargoType",
|
||||
a.cargo_free_text AS "cargoDescription",
|
||||
COALESCE(bc.total_vgm_tons, c.max_gross_weight, a.cargo_total_weight_vgm) AS "weight",
|
||||
COALESCE(bc.quantity, 1) AS "quantity",
|
||||
COALESCE(bc.quantity, 1) AS "packageCount",
|
||||
a.wagon_number AS "wagonNumber",
|
||||
a.has_damage AS "hasDamage",
|
||||
a.damage_description AS "damageDescription",
|
||||
a.has_weight_loss AS "hasWeightLoss",
|
||||
a.has_missing_items AS "hasMissingItems",
|
||||
a.missing_items_description AS "missingItemsDescription"
|
||||
FROM assigned a
|
||||
JOIN freight.containers c ON c.booking_id = a.booking_id AND c.deleted_at IS NULL
|
||||
LEFT JOIN freight.booking_container bc ON bc.id = c.booking_container_id AND bc.deleted_at IS NULL
|
||||
UNION ALL
|
||||
SELECT a.booking_id AS "bookingId",
|
||||
a.reference AS "bookingReference",
|
||||
'CONTAINER' AS "itemType",
|
||||
bc.id AS "bookingContainerId",
|
||||
NULL AS "bookingCargoId",
|
||||
bc.container_number AS "containerNumber",
|
||||
NULL AS "sealNumber",
|
||||
NULL AS "cargoId",
|
||||
a.booking_cargo_type AS "cargoType",
|
||||
a.cargo_free_text AS "cargoDescription",
|
||||
COALESCE(bc.total_vgm_tons, a.cargo_total_weight_vgm) AS "weight",
|
||||
bc.quantity AS "quantity",
|
||||
bc.quantity AS "packageCount",
|
||||
a.wagon_number AS "wagonNumber",
|
||||
a.has_damage AS "hasDamage",
|
||||
a.damage_description AS "damageDescription",
|
||||
a.has_weight_loss AS "hasWeightLoss",
|
||||
a.has_missing_items AS "hasMissingItems",
|
||||
a.missing_items_description AS "missingItemsDescription"
|
||||
FROM assigned a
|
||||
JOIN freight.booking_container bc ON bc.booking_id = a.booking_id AND bc.deleted_at IS NULL
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM freight.containers c
|
||||
WHERE c.booking_container_id = bc.id AND c.deleted_at IS NULL
|
||||
)
|
||||
UNION ALL
|
||||
SELECT a.booking_id AS "bookingId",
|
||||
a.reference AS "bookingReference",
|
||||
'CARGO' AS "itemType",
|
||||
NULL AS "bookingContainerId",
|
||||
cg.id AS "bookingCargoId",
|
||||
NULL AS "containerNumber",
|
||||
NULL AS "sealNumber",
|
||||
cg.id AS "cargoId",
|
||||
COALESCE(cgt.cargo_type_name, a.booking_cargo_type) AS "cargoType",
|
||||
COALESCE(cg.description, a.cargo_free_text) AS "cargoDescription",
|
||||
COALESCE(cg.weight, a.cargo_total_weight_vgm) AS "weight",
|
||||
cg.quantity AS "quantity",
|
||||
cg.quantity AS "packageCount",
|
||||
a.wagon_number AS "wagonNumber",
|
||||
a.has_damage AS "hasDamage",
|
||||
a.damage_description AS "damageDescription",
|
||||
a.has_weight_loss AS "hasWeightLoss",
|
||||
a.has_missing_items AS "hasMissingItems",
|
||||
a.missing_items_description AS "missingItemsDescription"
|
||||
FROM assigned a
|
||||
JOIN freight.cargoes cg ON cg.booking_id = a.booking_id AND cg.deleted_at IS NULL
|
||||
LEFT JOIN freight.cargo_types cgt ON cgt.id = cg.cargo_type_id
|
||||
UNION ALL
|
||||
SELECT a.booking_id AS "bookingId",
|
||||
a.reference AS "bookingReference",
|
||||
CASE WHEN a.booking_cargo_type ILIKE '%container%' THEN 'CONTAINER' ELSE 'CARGO' END AS "itemType",
|
||||
NULL AS "bookingContainerId",
|
||||
NULL AS "bookingCargoId",
|
||||
NULL AS "containerNumber",
|
||||
NULL AS "sealNumber",
|
||||
NULL AS "cargoId",
|
||||
a.booking_cargo_type AS "cargoType",
|
||||
a.cargo_free_text AS "cargoDescription",
|
||||
a.cargo_total_weight_vgm AS "weight",
|
||||
1 AS "quantity",
|
||||
1 AS "packageCount",
|
||||
a.wagon_number AS "wagonNumber",
|
||||
a.has_damage AS "hasDamage",
|
||||
a.damage_description AS "damageDescription",
|
||||
a.has_weight_loss AS "hasWeightLoss",
|
||||
a.has_missing_items AS "hasMissingItems",
|
||||
a.missing_items_description AS "missingItemsDescription"
|
||||
FROM assigned a
|
||||
WHERE NOT EXISTS (SELECT 1 FROM freight.containers c WHERE c.booking_id = a.booking_id AND c.deleted_at IS NULL)
|
||||
AND NOT EXISTS (SELECT 1 FROM freight.booking_container bc WHERE bc.booking_id = a.booking_id AND bc.deleted_at IS NULL)
|
||||
AND NOT EXISTS (SELECT 1 FROM freight.cargoes cg WHERE cg.booking_id = a.booking_id AND cg.deleted_at IS NULL)
|
||||
ORDER BY "bookingReference" ASC NULLS LAST, "itemType" ASC, "containerNumber" ASC NULLS LAST`,
|
||||
[scheduleId],
|
||||
);
|
||||
}
|
||||
|
||||
private conditionFromInspection(item: InterchangeItemSnapshot) {
|
||||
if (item.hasDamage) return 'DAMAGED';
|
||||
if (item.hasWeightLoss || item.hasMissingItems) return 'SHORTAGE';
|
||||
return 'GOOD';
|
||||
}
|
||||
|
||||
private async nextDocumentNo(direction: InterchangeDirection): Promise<string> {
|
||||
const prefix = `ICD-${direction === 'EXPORT' ? 'EXP' : 'IMP'}-${this.yyyymmdd(new Date())}`;
|
||||
const [row] = await this.dataSource.query(
|
||||
`SELECT document_no AS "documentNo"
|
||||
FROM freight.interchange_documents
|
||||
WHERE document_no LIKE $1
|
||||
ORDER BY document_no DESC
|
||||
LIMIT 1`,
|
||||
[`${prefix}-%`],
|
||||
);
|
||||
const last = row?.documentNo ? Number(String(row.documentNo).split('-').pop()) || 0 : 0;
|
||||
return `${prefix}-${String(last + 1).padStart(4, '0')}`;
|
||||
}
|
||||
|
||||
private yyyymmdd(date: Date): string {
|
||||
const yyyy = date.getUTCFullYear();
|
||||
const mm = String(date.getUTCMonth() + 1).padStart(2, '0');
|
||||
const dd = String(date.getUTCDate()).padStart(2, '0');
|
||||
return `${yyyy}${mm}${dd}`;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { FindOptionsWhere } from 'typeorm';
|
||||
import { DataSource, FindOptionsWhere } from 'typeorm';
|
||||
|
||||
import { BookingsRepository } from '../bookings/bookings.repository';
|
||||
import { CreateLastMileDto } from './dto/create-last-mile.dto';
|
||||
@@ -29,6 +29,7 @@ export class LastMileService {
|
||||
constructor(
|
||||
private readonly lastMileRepository: LastMileRepository,
|
||||
private readonly bookingsRepository: BookingsRepository,
|
||||
private readonly dataSource: DataSource,
|
||||
) {}
|
||||
|
||||
async acceptBooking(bookingReference: string): Promise<LastMile> {
|
||||
@@ -44,6 +45,41 @@ export class LastMileService {
|
||||
);
|
||||
}
|
||||
|
||||
if ((booking.tradeDirection ?? '').toUpperCase() !== 'IMPORT') {
|
||||
throw new BadRequestException(`Booking ${bookingReference} is not an import booking`);
|
||||
}
|
||||
|
||||
if (!booking.lastMileDeliveryAddress?.trim()) {
|
||||
throw new BadRequestException(`Booking ${bookingReference} has no last-mile delivery address`);
|
||||
}
|
||||
|
||||
const [eligibleInventory] = await this.dataSource.query(
|
||||
`SELECT inv.id
|
||||
FROM freight.warehouse_inventory inv
|
||||
WHERE inv.booking_id = $1
|
||||
AND inv.deleted_at IS NULL
|
||||
AND inv.status = 'READY_FOR_PICKUP'
|
||||
AND inv.inspection_status = 'PASSED'
|
||||
LIMIT 1`,
|
||||
[booking.id],
|
||||
);
|
||||
if (!eligibleInventory) {
|
||||
throw new BadRequestException(
|
||||
`Booking ${bookingReference} is not eligible for last mile. Import inventory must pass inspection and be READY_FOR_PICKUP.`,
|
||||
);
|
||||
}
|
||||
|
||||
const [existing] = await this.dataSource.query(
|
||||
`SELECT id
|
||||
FROM freight.last_mile
|
||||
WHERE booking_id = $1 AND deleted_at IS NULL
|
||||
LIMIT 1`,
|
||||
[booking.id],
|
||||
);
|
||||
if (existing) {
|
||||
return this.findById(existing.id);
|
||||
}
|
||||
|
||||
return this.create({
|
||||
bookingId: booking.id,
|
||||
advancedPayment: booking.totalAmount,
|
||||
|
||||
@@ -62,13 +62,4 @@ export class Vehicle extends BaseEntity {
|
||||
|
||||
@Column({ name: 'assigned_driver_name', nullable: true })
|
||||
assignedDriverName?: string;
|
||||
|
||||
@Column({ name: 'code', nullable: true })
|
||||
code?: string;
|
||||
|
||||
@Column({ name: 'power_plate_no', nullable: true })
|
||||
powerPlateNo?: string;
|
||||
|
||||
@Column({ name: 'trailer_plate_no', nullable: true })
|
||||
trailerPlateNo?: string;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { IsBoolean, IsNumber, IsOptional, IsString, Min } from 'class-validator';
|
||||
import { IsBoolean, IsIn, IsNumber, IsOptional, IsString, Min } from 'class-validator';
|
||||
|
||||
export class GenerateInvoiceDto {
|
||||
@ApiPropertyOptional({ description: 'Create even when the calculated amount is zero.' })
|
||||
@@ -11,6 +11,11 @@ export class GenerateInvoiceDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
performedBy?: string;
|
||||
|
||||
@ApiPropertyOptional({ enum: ['ETB', 'USD'], description: 'Currency to bill the generated invoice in.' })
|
||||
@IsOptional()
|
||||
@IsIn(['ETB', 'USD'])
|
||||
billingCurrency?: 'ETB' | 'USD';
|
||||
}
|
||||
|
||||
export class PayInvoiceBodyDto {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { ExchangeService } from '@edr/api-common';
|
||||
import { DataSource } from 'typeorm';
|
||||
|
||||
import { CreateFeeRuleDto, UpdateFeeRuleDto } from './dto/fee-rule.dto';
|
||||
@@ -28,6 +29,8 @@ export interface FeePreview {
|
||||
freeDays: number;
|
||||
ratePerDay: number;
|
||||
currency: string;
|
||||
ruleCurrency: string | null;
|
||||
billingCurrency: string;
|
||||
startDate: string | null;
|
||||
endDate: string;
|
||||
endIsOpen: boolean; // true when still accruing (no release/gate-clear yet)
|
||||
@@ -45,6 +48,7 @@ export class WarehouseFeeService {
|
||||
constructor(
|
||||
private readonly dataSource: DataSource,
|
||||
private readonly feeRuleRepository: WarehouseFeeRuleRepository,
|
||||
private readonly exchangeService: ExchangeService,
|
||||
) {}
|
||||
|
||||
// ── Rule CRUD ──────────────────────────────────────────────────────────────
|
||||
@@ -137,12 +141,32 @@ export class WarehouseFeeService {
|
||||
return best;
|
||||
}
|
||||
|
||||
private compute(ruleType: FeeRuleType, rule: WarehouseFeeRule | null, item: ItemAttributes, now: Date): FeePreview {
|
||||
private normalizeCurrency(currency?: string | null): 'ETB' | 'USD' {
|
||||
return currency === 'ETB' ? 'ETB' : 'USD';
|
||||
}
|
||||
|
||||
private async convertAmount(amount: number, fromCurrency: string, toCurrency: string): Promise<number> {
|
||||
const from = this.normalizeCurrency(fromCurrency);
|
||||
const to = this.normalizeCurrency(toCurrency);
|
||||
if (from === to) return Math.round(amount * 100) / 100;
|
||||
const rate = await this.exchangeService.getRate(from, to);
|
||||
return Math.round(amount * rate * 100) / 100;
|
||||
}
|
||||
|
||||
private async compute(
|
||||
ruleType: FeeRuleType,
|
||||
rule: WarehouseFeeRule | null,
|
||||
item: ItemAttributes,
|
||||
now: Date,
|
||||
billingCurrency: string,
|
||||
): Promise<FeePreview> {
|
||||
const start = item.arrivedAt ? new Date(item.arrivedAt) : null;
|
||||
const endDate = item.gateClearedAt ?? item.releaseDate ?? now;
|
||||
const endIsOpen = !item.gateClearedAt && !item.releaseDate;
|
||||
const freeDays = rule?.freeDays ?? 0;
|
||||
const ratePerDay = Number(rule?.ratePerDay ?? 0);
|
||||
const ruleCurrency = rule ? this.normalizeCurrency(rule.currency) : null;
|
||||
const targetCurrency = this.normalizeCurrency(billingCurrency);
|
||||
const isContainer = (item.freightType ?? '').toUpperCase() === 'CONTAINER';
|
||||
const inventoryQuantity = Math.max(1, Math.round(Number(item.inventoryQuantity) || 1));
|
||||
const containerCount = isContainer
|
||||
@@ -154,15 +178,21 @@ export class WarehouseFeeService {
|
||||
: 0;
|
||||
const chargeableDays = Math.max(0, elapsedDays - freeDays);
|
||||
const billableUnits = chargeableDays * containerCount;
|
||||
const amount = Math.round(billableUnits * ratePerDay * 100) / 100;
|
||||
const sourceAmount = Math.round(billableUnits * ratePerDay * 100) / 100;
|
||||
const amount = ruleCurrency ? await this.convertAmount(sourceAmount, ruleCurrency, targetCurrency) : 0;
|
||||
const convertedRatePerDay = ruleCurrency
|
||||
? await this.convertAmount(ratePerDay, ruleCurrency, targetCurrency)
|
||||
: 0;
|
||||
|
||||
return {
|
||||
ruleType,
|
||||
ruleId: rule?.id ?? null,
|
||||
ruleName: rule?.name ?? null,
|
||||
freeDays,
|
||||
ratePerDay,
|
||||
currency: rule?.currency ?? 'USD',
|
||||
ratePerDay: convertedRatePerDay,
|
||||
currency: targetCurrency,
|
||||
ruleCurrency,
|
||||
billingCurrency: targetCurrency,
|
||||
startDate: start ? start.toISOString() : null,
|
||||
endDate: new Date(endDate).toISOString(),
|
||||
endIsOpen,
|
||||
@@ -175,14 +205,22 @@ export class WarehouseFeeService {
|
||||
}
|
||||
|
||||
/** Preview demurrage + storage fees for an inventory item using the most specific active rules. */
|
||||
async previewForInventory(inventoryId: string): Promise<FeePreview[]> {
|
||||
async previewForInventory(inventoryId: string, billingCurrency = 'USD'): Promise<FeePreview[]> {
|
||||
const item = await this.loadItem(inventoryId);
|
||||
const rules = await this.feeRuleRepository.findAll({ where: { isActive: true } });
|
||||
const now = new Date();
|
||||
|
||||
const byType: FeeRuleType[] = ['DEMURRAGE_FEE', 'STORAGE_FEE'];
|
||||
return byType.map((type) =>
|
||||
this.compute(type, this.bestRule(rules.filter((r) => r.ruleType === type), item), item, now),
|
||||
return Promise.all(
|
||||
byType.map((type) =>
|
||||
this.compute(
|
||||
type,
|
||||
this.bestRule(rules.filter((r) => r.ruleType === type), item),
|
||||
item,
|
||||
now,
|
||||
billingCurrency,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { DataSource } from 'typeorm';
|
||||
|
||||
import { FilesService } from '../files/files.service';
|
||||
import { LastMileService } from '../last-mile/last-mile.service';
|
||||
import { CreateInspectionReportDto } from './dto/create-inspection-report.dto';
|
||||
import { UpdateInspectionReportDto } from './dto/update-inspection-report.dto';
|
||||
import { WarehouseInspectionReport } from './entities/warehouse-inspection-report.entity';
|
||||
@@ -16,6 +17,7 @@ export class WarehouseInspectionService {
|
||||
private readonly dataSource: DataSource,
|
||||
private readonly inspectionRepository: WarehouseInspectionRepository,
|
||||
private readonly filesService: FilesService,
|
||||
private readonly lastMileService: LastMileService,
|
||||
) {}
|
||||
|
||||
/** Create or update the inspection report for an inventory item and sync its inspectionStatus. */
|
||||
@@ -70,9 +72,37 @@ export class WarehouseInspectionService {
|
||||
inspectedAt,
|
||||
});
|
||||
|
||||
if (dto.inspectionStatus === 'PASSED') {
|
||||
await this.markImportPickupReadyAndAcceptLastMile(inventoryId);
|
||||
}
|
||||
|
||||
return report;
|
||||
}
|
||||
|
||||
private async markImportPickupReadyAndAcceptLastMile(inventoryId: string): Promise<void> {
|
||||
const [row] = await this.dataSource.query(
|
||||
`SELECT inv.booking_id AS "bookingId",
|
||||
b.reference AS "bookingReference",
|
||||
b.trade_direction AS "tradeDirection",
|
||||
b.last_mile_delivery_address AS "lastMileDeliveryAddress"
|
||||
FROM freight.warehouse_inventory inv
|
||||
LEFT JOIN freight.bookings b ON b.id = inv.booking_id
|
||||
WHERE inv.id = $1 AND inv.deleted_at IS NULL
|
||||
LIMIT 1`,
|
||||
[inventoryId],
|
||||
);
|
||||
if ((row?.tradeDirection ?? '').toUpperCase() !== 'IMPORT') return;
|
||||
|
||||
await this.dataSource.getRepository(WarehouseInventory).update(inventoryId, {
|
||||
status: 'READY_FOR_PICKUP',
|
||||
readyForPickupAt: new Date(),
|
||||
});
|
||||
|
||||
if (row.bookingReference && row.lastMileDeliveryAddress) {
|
||||
await this.lastMileService.acceptBooking(row.bookingReference);
|
||||
}
|
||||
}
|
||||
|
||||
async findByInventory(inventoryId: string): Promise<WarehouseInspectionReport[]> {
|
||||
return this.inspectionRepository.findAll({
|
||||
where: { inventoryId },
|
||||
@@ -113,6 +143,9 @@ export class WarehouseInspectionService {
|
||||
await this.dataSource
|
||||
.getRepository(WarehouseInventory)
|
||||
.update(report.inventoryId, { inspectionStatus: dto.inspectionStatus });
|
||||
if (dto.inspectionStatus === 'PASSED') {
|
||||
await this.markImportPickupReadyAndAcceptLastMile(report.inventoryId);
|
||||
}
|
||||
}
|
||||
|
||||
return this.findById(id);
|
||||
|
||||
@@ -3,6 +3,9 @@ import { Between, DataSource, EntityManager, FindManyOptions, ILike, LessThanOrE
|
||||
|
||||
import { deriveTradeDirection } from '../../common/derive-trade-direction.util';
|
||||
import { Cargo } from '../cargoes/entities/cargoes.entity';
|
||||
import { InterchangeDocumentsService } from '../interchange-documents/interchange-documents.service';
|
||||
import type { InterchangeDocument } from '../interchange-documents/entities/interchange-document.entity';
|
||||
import { LastMileService } from '../last-mile/last-mile.service';
|
||||
import { ContractPdfService } from '../../contracts/contract-pdf.service';
|
||||
import { BulkInspectDto } from './dto/bulk-inspect.dto';
|
||||
import { BulkReceiveDto } from './dto/bulk-receive.dto';
|
||||
@@ -239,6 +242,7 @@ export interface AutoUnloadExportDjiboutiResult {
|
||||
unloadedCount: number;
|
||||
skippedCount: number;
|
||||
failedCount: number;
|
||||
interchangeDocument?: Pick<InterchangeDocument, 'id' | 'documentNo' | 'status'>;
|
||||
results: Array<{
|
||||
bookingId: string;
|
||||
itemType: 'CONTAINER' | 'CARGO';
|
||||
@@ -280,6 +284,8 @@ export class WarehouseInventoryService {
|
||||
private readonly invoices: WarehouseInvoiceService,
|
||||
private readonly inspectionService: WarehouseInspectionService,
|
||||
private readonly pdfService: ContractPdfService,
|
||||
private readonly interchangeDocuments: InterchangeDocumentsService,
|
||||
private readonly lastMileService: LastMileService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -1256,6 +1262,24 @@ export class WarehouseInventoryService {
|
||||
}
|
||||
});
|
||||
|
||||
if (result.unloadedCount > 0) {
|
||||
const document = await this.interchangeDocuments.generateFromSchedule({
|
||||
scheduleId,
|
||||
direction: 'EXPORT',
|
||||
handoverLocation: schedule.destinationName ?? 'Djibouti Port',
|
||||
handoverFrom: 'EDR',
|
||||
handoverTo: 'Djibouti Port Operator',
|
||||
portOperatorName: 'Doraleh Multipurpose Port',
|
||||
generatedBy: performedBy,
|
||||
remarks: 'Generated after export unloading at Djibouti Port',
|
||||
});
|
||||
result.interchangeDocument = {
|
||||
id: document.id,
|
||||
documentNo: document.documentNo,
|
||||
status: document.status,
|
||||
};
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -1327,6 +1351,7 @@ export class WarehouseInventoryService {
|
||||
manager,
|
||||
);
|
||||
});
|
||||
await this.acceptLastMileIfRequested(item.bookingId);
|
||||
result.results.push({ inventoryId, status: 'READY_FOR_PICKUP' });
|
||||
} else {
|
||||
result.results.push({ inventoryId, status: 'INSPECTED' });
|
||||
@@ -1339,6 +1364,20 @@ export class WarehouseInventoryService {
|
||||
|
||||
// ── Receive ──────────────────────────────────────────────────────────────
|
||||
|
||||
private async acceptLastMileIfRequested(bookingId?: string | null): Promise<void> {
|
||||
if (!bookingId) return;
|
||||
const [booking] = await this.dataSource.query(
|
||||
`SELECT reference,
|
||||
last_mile_delivery_address AS "lastMileDeliveryAddress"
|
||||
FROM freight.bookings
|
||||
WHERE id = $1 AND deleted_at IS NULL
|
||||
LIMIT 1`,
|
||||
[bookingId],
|
||||
);
|
||||
if (!booking?.reference || !booking.lastMileDeliveryAddress) return;
|
||||
await this.lastMileService.acceptBooking(booking.reference);
|
||||
}
|
||||
|
||||
async receive(dto: ReceiveWarehouseInventoryDto): Promise<WarehouseInventory> {
|
||||
const weight = Number(dto.weight) || 0;
|
||||
const volume = Number(dto.volume) || 0;
|
||||
|
||||
@@ -14,6 +14,7 @@ import { WarehouseFeeService } from './warehouse-fee.service';
|
||||
interface GenerateOptions {
|
||||
confirmZero?: boolean;
|
||||
performedBy?: string;
|
||||
billingCurrency?: 'ETB' | 'USD';
|
||||
}
|
||||
|
||||
export interface PayInvoiceDto {
|
||||
@@ -58,7 +59,8 @@ export class WarehouseInvoiceService {
|
||||
);
|
||||
}
|
||||
|
||||
const previews = await this.feeService.previewForInventory(inventoryId);
|
||||
const billingCurrency = opts.billingCurrency === 'ETB' ? 'ETB' : 'USD';
|
||||
const previews = await this.feeService.previewForInventory(inventoryId, billingCurrency);
|
||||
const isContainer = (item.freightType ?? '').toUpperCase() === 'CONTAINER';
|
||||
|
||||
const items = previews
|
||||
@@ -98,7 +100,7 @@ export class WarehouseInvoiceService {
|
||||
const invoiceType: WarehouseInvoiceType =
|
||||
hasDemurrage && hasStorage ? 'MIXED_WAREHOUSE_FEES' : hasStorage ? 'STORAGE_FEE' : 'DEMURRAGE';
|
||||
|
||||
const currency = items[0]?.currency ?? 'USD';
|
||||
const currency = billingCurrency;
|
||||
const now = new Date();
|
||||
const periodEnd = previews[0] ? new Date(previews[0].endDate) : now;
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Body, Controller, Delete, Get, HttpCode, Param, ParseUUIDPipe, Patch, Post } from '@nestjs/common';
|
||||
import { Body, Controller, Delete, Get, HttpCode, Param, ParseUUIDPipe, Patch, Post, Query } from '@nestjs/common';
|
||||
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
|
||||
import {
|
||||
@@ -79,7 +79,10 @@ export class WarehouseRulesController {
|
||||
|
||||
@Get('warehouse-inventory/:id/fee-preview')
|
||||
@ApiOperation({ summary: 'Preview demurrage + storage fees for an inventory item' })
|
||||
feePreview(@Param('id', ParseUUIDPipe) id: string) {
|
||||
return this.feeService.previewForInventory(id);
|
||||
feePreview(
|
||||
@Param('id', ParseUUIDPipe) id: string,
|
||||
@Query('billingCurrency') billingCurrency?: string,
|
||||
) {
|
||||
return this.feeService.previewForInventory(id, billingCurrency);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { ExchangeModule, ExchangeOptions } from '@edr/api-common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
|
||||
import { ContractPdfService } from '../../contracts/contract-pdf.service';
|
||||
import { FilesModule } from '../files/files.module';
|
||||
import { InterchangeDocumentsModule } from '../interchange-documents/interchange-documents.module';
|
||||
import { LastMileModule } from '../last-mile/last-mile.module';
|
||||
import { WarehouseActivityLog } from './entities/warehouse-activity-log.entity';
|
||||
import { WarehouseAllocationRule } from './entities/warehouse-allocation-rule.entity';
|
||||
import { WarehouseFeeInvoice } from './entities/warehouse-fee-invoice.entity';
|
||||
@@ -65,6 +69,13 @@ import { WarehousesService } from './warehouses.service';
|
||||
WarehouseFeeInvoiceItem,
|
||||
]),
|
||||
FilesModule,
|
||||
InterchangeDocumentsModule,
|
||||
LastMileModule,
|
||||
ExchangeModule.forRootAsync({
|
||||
inject: [ConfigService],
|
||||
useFactory: (config: ConfigService): ExchangeOptions =>
|
||||
config.get<ExchangeOptions>('app.cbeExchange') ?? {},
|
||||
}),
|
||||
],
|
||||
controllers: [
|
||||
WarehousesController,
|
||||
|
||||
Reference in New Issue
Block a user