Merge branch 'dev' into fixes

This commit is contained in:
Nathnael
2026-08-04 09:00:52 +00:00
188 changed files with 12946 additions and 1758 deletions

View File

@@ -16,7 +16,7 @@ import {
containersPerWagonForSize,
wagonsPerUnitForSize,
} from '../rule-engine/container-type.util';
import { bulkItemWagonsForAllowedTypes } from '../train-scheduling/train-capacity.util';
import { bulkWagonsForAllowedTypes } from '../train-scheduling/train-capacity.util';
import { BookingsRepository } from './bookings.repository';
import { wagonRemainder } from './consolidation.service';
import { GeneratePriceResponseDto, PriceLineItemDto } from './dto/generate-price-response.dto';
@@ -1190,8 +1190,10 @@ export class BookingPricingService {
// Break-bulk (PER_ITEM): `tons` above is the item count; size by
// indivisible items instead of pretending the count is tonnage. Best
// count across allowed wagon types, each capped by its items-fit.
const byItems = bulkItemWagonsForAllowedTypes(booking, cargo, capacity);
if (byItems > 0) return byItems;
// PER_TON cargo may cap tons per wagon below the rating (sugar 50T on a
// 70T wagon) — 200T then prices 4 wagons, not 3.
const byWagons = bulkWagonsForAllowedTypes(booking, cargo, capacity);
if (byWagons > 0) return byWagons;
return Math.max(1, Math.ceil(tons / capacity));
} catch {
return null;

View File

@@ -22,6 +22,7 @@ import {
IYardsRepository,
YARDS_REPOSITORY,
} from "../rule-engine/interfaces/yards.repository.interface";
import { YardFacilitiesService } from "../rule-engine/services/yard-facilities.service";
import {
BookingReferenceCargoTypeChildDto,
BookingReferenceCargoTypeGroupDto,
@@ -170,11 +171,18 @@ export class BookingReferenceDataService {
private readonly shippingLinesRepository: IShippingLinesRepository,
@Inject(CARGO_TYPES_REPOSITORY)
private readonly cargoTypesRepository: ICargoTypesRepository,
private readonly yardFacilitiesService: YardFacilitiesService,
) { }
async getReferenceData(): Promise<BookingReferenceDataDto> {
const [yards, containerTypes, serviceTypes, shippingLines, cargoTypes] =
await Promise.all([
const [
yards,
containerTypes,
serviceTypes,
shippingLines,
cargoTypes,
facilityYards,
] = await Promise.all([
this.yardsRepository.findAll({
where: { isActive: true },
order: { displayOrder: "ASC", code: "ASC" },
@@ -195,17 +203,30 @@ export class BookingReferenceDataService {
where: { isActive: true },
order: { displayOrder: "ASC", code: "ASC" },
}),
this.yardFacilitiesService.listFacilityYards(),
]);
// Every active yard is still listed; a yard with no facility record simply
// reports no capability, so the forms drop it from the pickers themselves.
const facilityByYardId = new Map(facilityYards.map((f) => [f.yardId, f]));
return {
yard: yards.map(
(y): BookingReferenceYardDto => ({
yard: yards.map((y): BookingReferenceYardDto => {
const facility = facilityByYardId.get(y.id);
return {
id: y.id,
name: y.label,
code: y.code,
country: y.country,
}),
),
hasContainerFacilityOrigin:
facility?.hasContainerFacilityOrigin ?? false,
hasBulkFacilityOrigin: facility?.hasBulkFacilityOrigin ?? false,
hasContainerFacilityDestination:
facility?.hasContainerFacilityDestination ?? false,
hasBulkFacilityDestination:
facility?.hasBulkFacilityDestination ?? false,
};
}),
containers: groupContainersBySize(containerTypes),
service: serviceTypes.map(
(s): BookingReferenceServiceDto => ({

View File

@@ -927,13 +927,6 @@ export class BookingTransitionService {
"OPERATION_CHANGES_REQUESTED",
]);
// A company sitting on another unpaid hold commits nothing new — this is
// the moment export capacity locks, so the lock applies here too.
// Government bookings allocate without paying and are exempt.
if (!booking.isGovernment) {
await this.bookingsService.assertNoUnpaidHold(booking.companyId);
}
// A bare initiated instance (clearance-first flow) carries no cargo or
// price — it must go through the contract completion endpoint, which
// persists cargo, prices, invoices and only then lands here itself.

View File

@@ -43,6 +43,8 @@ import {
RoAmendmentDto,
} from '../contracts/dto/phased-clearance.dto';
import { BookingReferenceDataService } from './booking-reference-data.service';
import { scopedDirections } from '../user-trade-access/trade-scope.util';
import { UserTradeAccessService } from '../user-trade-access/user-trade-access.service';
import { BookingsService } from './bookings.service';
import { BookingReferenceDataDto } from './dto/booking-reference-data.dto';
import { CreateBookingDto } from './dto/create-booking.dto';
@@ -150,6 +152,7 @@ export class BookingsController {
private readonly containerReceiptService: ContainerReceiptService,
private readonly firstMileService: FirstMileService,
private readonly lastMileService: LastMileService,
private readonly userTradeAccessService: UserTradeAccessService,
) {}
@Post()
@@ -217,7 +220,16 @@ export class BookingsController {
// Staff (backoffice) see every booking. Customers (portal) are always
// force-scoped to their own company, regardless of any companyId they pass.
if (hasFreightPermission(user, FREIGHT_PERMS.bookings.view)) {
return this.bookingsService.findAll(filter);
// Per-user trade-direction scope (import/export/intercity checkboxes).
const allowed =
await this.userTradeAccessService.resolveAllowedDirections(user);
const dirs = scopedDirections(allowed, filter.tradeDirection);
return this.bookingsService.findAll(
filter,
undefined,
undefined,
dirs ?? undefined,
);
}
// Global Logistics has clearance:view but NOT bookings:view — it is scoped
// to the customs document-clearance queue only and never sees the general

View File

@@ -1,4 +1,5 @@
import { Module, forwardRef } from "@nestjs/common";
import { UserTradeAccessModule } from "../user-trade-access/user-trade-access.module";
import { ConfigService } from "@nestjs/config";
import { TypeOrmModule } from "@nestjs/typeorm";
import { ExchangeModule, ExchangeOptions } from "@edr/api-common";
@@ -80,6 +81,7 @@ import { VehiclesModule } from "../vehicles/vehicles.module";
MinioModule,
VehiclesModule,
CompaniesModule,
UserTradeAccessModule,
// CustomersModule,
RuleEngineModule,
FileUploadSettingsModule,

View File

@@ -17,6 +17,7 @@ import { ContainerType } from '../rule-engine/entities/container-type.entity';
import { Contract } from '../contracts/entities/contract.entity';
import { ContractRateSnapshot } from '../contracts/entities/contract-rate-snapshot.entity';
import { ContractRoute } from '../contracts/entities/contract-route.entity';
import { applyDirectionScope } from '../user-trade-access/trade-scope.util';
import { BookingCargoModifier } from './entities/booking-cargo-modifier.entity';
import {
BookingDocumentReview,
@@ -64,6 +65,8 @@ export interface BookingListFilterOptions {
freightType?: string;
bookingType?: string;
tradeDirection?: string;
/** Per-user trade-direction scope — `[]` matches nothing. */
tradeDirections?: string[];
paymentCurrency?: string;
paymentStatus?: string;
excludePaymentStatus?: string;
@@ -1000,6 +1003,9 @@ export class BookingsRepository extends BaseRepository<Booking> {
tradeDirection: options.tradeDirection,
});
}
if (options.tradeDirections) {
applyDirectionScope(qb, 'booking.trade_direction', options.tradeDirections);
}
if (options.paymentCurrency) {
qb.andWhere('booking.payment_currency = :paymentCurrency', {
paymentCurrency: options.paymentCurrency,
@@ -1390,16 +1396,6 @@ export class BookingsRepository extends BaseRepository<Booking> {
.getMany();
}
/** Open unpaid holds (wagons reserved, pay window running) for a company. */
countUnpaidHoldsForCompany(companyId: string): Promise<number> {
return this.repository.count({
where: {
companyId,
status: In(['SELECTED_FOR_BATCH', 'AWAITING_PAYMENT']),
},
});
}
/** Bookings currently reserved (SELECTED_FOR_BATCH) against a schedule. */
findReservedForSchedule(scheduleId: string): Promise<Booking[]> {
return this.repository

View File

@@ -28,6 +28,7 @@ import { EventEmitter2 } from '@nestjs/event-emitter';
import { DataSource, In } from 'typeorm';
import { deriveTradeDirection } from '../../common/derive-trade-direction.util';
import { assertExportReceivedWithGrn } from '../../common/export-received-gate';
import { Yard } from '../rule-engine/entities/yard.entity';
import { ServiceType } from '../rule-engine/entities/service-type.entity';
import { TrainSchedule } from '../train-schedules/entities/train-schedule.entity';
@@ -239,6 +240,10 @@ export class BookingsService {
*/
async carriageAcceptanceSheet(bookingId: string): Promise<{ filename: string; buffer: Buffer }> {
const booking = await this.findById(bookingId);
// The sheet attests that EDR has taken custody. For export that happens at
// cargo receipt (GRN), so the GRN is required even when wagons are already
// allocated — an allocation is a plan, not possession.
await assertExportReceivedWithGrn(this.dataSource, booking);
let wagons: CarriageAcceptanceWagonRow[] = await this.dataSource.query(
`SELECT tsw.sequence_no AS "sequenceNo",
COALESCE(wt.code, wt.name) AS "wagonType",
@@ -291,7 +296,10 @@ export class BookingsService {
LEFT JOIN freight.containers c
ON c.id = inv.container_id AND c.deleted_at IS NULL
WHERE inv.booking_id = $1 AND inv.deleted_at IS NULL
AND COALESCE(NULLIF(TRIM(inv.grn_number), ''), '') <> ''
AND COALESCE(
NULLIF(TRIM(inv.grn_number), ''),
substring(inv.notes FROM 'GRN Number: ([^\\n\\r]+)')
) IS NOT NULL
ORDER BY inv.created_at`,
[bookingId],
)
@@ -909,24 +917,6 @@ export class BookingsService {
return result.booking;
}
/**
* A company with an open unpaid hold (SELECTED_FOR_BATCH — wagons reserved,
* pay window running) may not take more capacity until it pays or the hold
* dies: otherwise one customer can lock a train's wagons over and over
* without ever paying. EXPIRED / CANCELLED holds free the lock.
*/
async assertNoUnpaidHold(companyId?: string | null): Promise<void> {
if (!companyId) return;
const holds =
await this.bookingsRepository.countUnpaidHoldsForCompany(companyId);
if (holds > 0) {
throw new ConflictException(
'You already have a booking waiting for payment. Pay it or cancel it ' +
'before making a new booking.',
);
}
}
/** Create a new freight booking. */
async create(
dto: CreateBookingDto,
@@ -989,10 +979,6 @@ export class BookingsService {
companyId = company.id;
}
// Government bookings allocate without paying, so the unpaid-hold lock
// only applies to commercial companies.
if (!isGovernment) await this.assertNoUnpaidHold(companyId);
if (dto.trainScheduleId) {
// Staff manual pin: the schedule must be OPEN and on the same route.
const schedule = await this.dataSource
@@ -1619,6 +1605,7 @@ export class BookingsService {
filter: FilterBookingDto,
forceCompanyId?: string,
forceCompanyProfileId?: string,
tradeDirections?: string[],
): Promise<PaginatedBookings> {
const page = filter.page ?? 1;
const pageSize = filter.pageSize ?? 20;
@@ -1638,6 +1625,7 @@ export class BookingsService {
// ANDs both, so cross-company access is impossible.
companyId: forceCompanyId ?? filter.companyId,
companyProfileId: forceCompanyProfileId ?? filter.companyProfileId,
tradeDirections,
contractType: filter.contractType,
serviceTypeId: filter.serviceTypeId,
cargoTypeId: filter.cargoTypeId,

View File

@@ -13,6 +13,18 @@ export class BookingReferenceYardDto {
@ApiProperty({ example: 'Ethiopia' })
country!: string;
@ApiProperty({ description: 'Can load containers onto a train here.' })
hasContainerFacilityOrigin!: boolean;
@ApiProperty({ description: 'Can load bulk cargo onto a train here.' })
hasBulkFacilityOrigin!: boolean;
@ApiProperty({ description: 'Can receive containers off a train here.' })
hasContainerFacilityDestination!: boolean;
@ApiProperty({ description: 'Can receive bulk cargo off a train here.' })
hasBulkFacilityDestination!: boolean;
}
export class BookingReferenceContainerTypeDto {