complete rule engine and booking flow

This commit is contained in:
marshal
2026-05-30 10:27:59 +03:00
parent 800f036005
commit 430dc44937
74 changed files with 4304 additions and 1248 deletions

View File

@@ -0,0 +1,75 @@
import { Inject, Injectable, NotFoundException } from '@nestjs/common';
import { CreateApprovalRuleDto } from '../dto/create-approval-rule.dto';
import { UpdateApprovalRuleDto } from '../dto/update-approval-rule.dto';
import { ApprovalRule } from '../entities/approval-rule.entity';
import {
APPROVAL_RULES_REPOSITORY,
IApprovalRulesRepository,
} from '../interfaces/approval-rules.repository.interface';
@Injectable()
export class ApprovalRulesService {
constructor(
@Inject(APPROVAL_RULES_REPOSITORY)
private readonly repository: IApprovalRulesRepository,
) {}
/** List approval rules. */
async findAll(filter: {
requiresDirectorApproval?: boolean;
page?: number;
pageSize?: number;
}): Promise<{ data: ApprovalRule[]; meta: { total: number; page: number; pageSize: number; totalPages: number } }> {
const page = filter.page ?? 1;
const pageSize = filter.pageSize ?? 20;
const where: Record<string, unknown> = {};
if (filter.requiresDirectorApproval !== undefined) {
where.requiresDirectorApproval = filter.requiresDirectorApproval;
}
const [data, total] = await this.repository.findAndCount({
where,
order: { requiresDirectorApproval: 'ASC', stepOrder: 'ASC' },
skip: (page - 1) * pageSize,
take: pageSize,
});
return { data, meta: { total, page, pageSize, totalPages: Math.ceil(total / pageSize) } };
}
/** Get approval chain for a cargo type flag. */
async findChain(requiresDirectorApproval: boolean): Promise<ApprovalRule[]> {
return this.repository.findChainForCargo(requiresDirectorApproval);
}
/** Get an approval rule by ID. */
async findById(id: string): Promise<ApprovalRule> {
const entity = await this.repository.findById(id);
if (!entity) throw new NotFoundException(`Approval rule ${id} not found`);
return entity;
}
/** Create an approval rule step. */
async create(dto: CreateApprovalRuleDto): Promise<ApprovalRule> {
return this.repository.create({
requiresDirectorApproval: dto.requiresDirectorApproval,
stepOrder: dto.stepOrder,
requiredRole: dto.requiredRole,
actionLabel: dto.actionLabel,
blocksRole: dto.blocksRole,
});
}
/** Update an approval rule. */
async update(id: string, dto: UpdateApprovalRuleDto): Promise<ApprovalRule> {
await this.findById(id);
const updated = await this.repository.update(id, dto);
if (!updated) throw new NotFoundException(`Approval rule ${id} not found`);
return updated;
}
/** Soft-delete an approval rule. */
async remove(id: string): Promise<void> {
await this.findById(id);
await this.repository.softDelete(id);
}
}

View File

@@ -27,7 +27,7 @@ export class ContainerTypesService {
const [data, total] = await this.repository.findAndCount({
where,
order: { sizeCode: 'ASC' },
order: { code: 'ASC' },
skip: (page - 1) * pageSize,
take: pageSize,
});
@@ -43,23 +43,27 @@ export class ContainerTypesService {
/** Create a new container type. */
async create(dto: CreateContainerTypeDto): Promise<ContainerType> {
const existing = await this.repository.findBySizeCode(dto.sizeCode);
if (existing) throw new ConflictException(`Container type with sizeCode "${dto.sizeCode}" already exists`);
const existing = await this.repository.findByCode(dto.code);
if (existing) throw new ConflictException(`Container type with code "${dto.code}" already exists`);
return this.repository.create({
sizeCode: dto.sizeCode,
description: dto.description ?? null,
containersPerWagon: dto.containersPerWagon,
code: dto.code,
label: dto.label,
sizeFt: dto.sizeFt,
wagonsPerUnit: dto.wagonsPerUnit,
isReefer: dto.isReefer ?? false,
isOpenTop: dto.isOpenTop ?? false,
isActive: dto.isActive ?? true,
displayOrder: dto.displayOrder ?? 1,
});
}
/** Update an existing container type. */
async update(id: string, dto: UpdateContainerTypeDto): Promise<ContainerType> {
await this.findById(id);
if (dto.sizeCode) {
const conflict = await this.repository.findBySizeCode(dto.sizeCode);
if (dto.code) {
const conflict = await this.repository.findByCode(dto.code);
if (conflict && conflict.id !== id) {
throw new ConflictException(`Container type with sizeCode "${dto.sizeCode}" already exists`);
throw new ConflictException(`Container type with code "${dto.code}" already exists`);
}
}
const updated = await this.repository.update(id, dto);

View File

@@ -27,7 +27,7 @@ export class PriorityRulesService {
const [data, total] = await this.repository.findAndCount({
where,
order: { priorityType: 'ASC' },
order: { code: 'ASC' },
skip: (page - 1) * pageSize,
take: pageSize,
});
@@ -43,16 +43,15 @@ export class PriorityRulesService {
/** Create a new priority rule. */
async create(dto: CreatePriorityRuleDto): Promise<PriorityRule> {
const existing = await this.repository.findAll({ where: { priorityType: dto.priorityType } });
const existing = await this.repository.findAll({ where: { code: dto.code } });
if (existing.length > 0) {
throw new ConflictException(`Priority rule for type "${dto.priorityType}" already exists`);
throw new ConflictException(`Priority rule with code "${dto.code}" already exists`);
}
return this.repository.create({
priorityType: dto.priorityType,
ruleName: dto.ruleName,
description: dto.description ?? null,
activationCondition: dto.activationCondition ?? null,
bonusPoints: dto.bonusPoints,
code: dto.code,
label: dto.label,
score: dto.score,
conditionCurrency: dto.conditionCurrency ?? null,
isActive: dto.isActive ?? false,
});
}

View File

@@ -0,0 +1,114 @@
import { BadRequestException, Inject, Injectable, NotFoundException } from '@nestjs/common';
import { ApproveRateDto, CreateRateDto } from '../dto/create-rate.dto';
import { UpdateRateDto } from '../dto/update-rate.dto';
import { Rate } from '../entities/rate.entity';
import { IRatesRepository, RATES_REPOSITORY } from '../interfaces/rates.repository.interface';
@Injectable()
export class RatesService {
constructor(
@Inject(RATES_REPOSITORY)
private readonly repository: IRatesRepository,
) {}
/** List rates with pagination. */
async findAll(filter: {
status?: string;
rateType?: string;
page?: number;
pageSize?: number;
}): Promise<{ data: Rate[]; meta: { total: number; page: number; pageSize: number; totalPages: number } }> {
const page = filter.page ?? 1;
const pageSize = filter.pageSize ?? 20;
const where: Record<string, unknown> = {};
if (filter.status) where.status = filter.status;
if (filter.rateType) where.rateType = filter.rateType;
const [data, total] = await this.repository.findAndCount({
where,
order: { effectiveFrom: 'DESC' },
skip: (page - 1) * pageSize,
take: pageSize,
});
return { data, meta: { total, page, pageSize, totalPages: Math.ceil(total / pageSize) } };
}
/** Return all currently LIVE rates. */
async findLiveRates(): Promise<Rate[]> {
return this.repository.findLiveRates();
}
/** Get a rate by ID. */
async findById(id: string): Promise<Rate> {
const entity = await this.repository.findById(id);
if (!entity) throw new NotFoundException(`Rate ${id} not found`);
return entity;
}
/** Create a rate in DRAFT status. */
async create(dto: CreateRateDto): Promise<Rate> {
return this.repository.create({
rateType: dto.rateType as Rate['rateType'],
containerTypeId: dto.containerTypeId,
tradeDirection: dto.tradeDirection,
currency: dto.currency,
rateValue: dto.rateValue,
rateUnit: dto.rateUnit as Rate['rateUnit'],
status: 'DRAFT',
proposedByStaffId: dto.proposedByStaffId,
effectiveFrom: new Date(dto.effectiveFrom),
effectiveTo: dto.effectiveTo ? new Date(dto.effectiveTo) : undefined,
});
}
/** Update a DRAFT rate. */
async update(id: string, dto: UpdateRateDto): Promise<Rate> {
const existing = await this.findById(id);
if (existing.status !== 'DRAFT') {
throw new BadRequestException('Only DRAFT rates can be updated');
}
const updates: Partial<Rate> = {};
if (dto.rateType) updates.rateType = dto.rateType as Rate['rateType'];
if (dto.containerTypeId !== undefined) updates.containerTypeId = dto.containerTypeId;
if (dto.tradeDirection !== undefined) updates.tradeDirection = dto.tradeDirection;
if (dto.currency) updates.currency = dto.currency;
if (dto.rateValue !== undefined) updates.rateValue = dto.rateValue;
if (dto.rateUnit) updates.rateUnit = dto.rateUnit as Rate['rateUnit'];
if (dto.proposedByStaffId) updates.proposedByStaffId = dto.proposedByStaffId;
if (dto.effectiveFrom) updates.effectiveFrom = new Date(dto.effectiveFrom);
if (dto.effectiveTo) updates.effectiveTo = new Date(dto.effectiveTo);
const updated = await this.repository.update(id, updates);
if (!updated) throw new NotFoundException(`Rate ${id} not found`);
return updated;
}
/** Submit a DRAFT rate for CEO approval. */
async submitForApproval(id: string): Promise<Rate> {
const rate = await this.findById(id);
if (rate.status !== 'DRAFT') {
throw new BadRequestException('Only DRAFT rates can be submitted for approval');
}
const updated = await this.repository.update(id, { status: 'PENDING_APPROVAL' });
return updated!;
}
/** CEO approves a rate — moves to LIVE. */
async approve(id: string, dto: ApproveRateDto): Promise<Rate> {
const rate = await this.findById(id);
if (rate.status !== 'PENDING_APPROVAL') {
throw new BadRequestException('Only PENDING_APPROVAL rates can be approved');
}
const updated = await this.repository.update(id, {
status: 'LIVE',
approvedByCeoId: dto.approvedByCeoId,
approvedAt: new Date(),
});
return updated!;
}
/** Soft-delete a rate. */
async remove(id: string): Promise<void> {
await this.findById(id);
await this.repository.softDelete(id);
}
}

View File

@@ -0,0 +1,76 @@
import { ConflictException, Inject, Injectable, NotFoundException } from '@nestjs/common';
import { CreateShippingLineDto } from '../dto/create-shipping-line.dto';
import { UpdateShippingLineDto } from '../dto/update-shipping-line.dto';
import { ShippingLine } from '../entities/shipping-line.entity';
import {
IShippingLinesRepository,
SHIPPING_LINES_REPOSITORY,
} from '../interfaces/shipping-lines.repository.interface';
@Injectable()
export class ShippingLinesService {
constructor(
@Inject(SHIPPING_LINES_REPOSITORY)
private readonly repository: IShippingLinesRepository,
) {}
/** List shipping lines with pagination. */
async findAll(filter: {
isActive?: boolean;
page?: number;
pageSize?: number;
}): Promise<{ data: ShippingLine[]; meta: { total: number; page: number; pageSize: number; totalPages: number } }> {
const page = filter.page ?? 1;
const pageSize = filter.pageSize ?? 20;
const where: Record<string, unknown> = {};
if (filter.isActive !== undefined) where.isActive = filter.isActive;
const [data, total] = await this.repository.findAndCount({
where,
order: { code: 'ASC' },
skip: (page - 1) * pageSize,
take: pageSize,
});
return { data, meta: { total, page, pageSize, totalPages: Math.ceil(total / pageSize) } };
}
/** Get a shipping line by ID. */
async findById(id: string): Promise<ShippingLine> {
const entity = await this.repository.findById(id);
if (!entity) throw new NotFoundException(`Shipping line ${id} not found`);
return entity;
}
/** Create a shipping line. */
async create(dto: CreateShippingLineDto): Promise<ShippingLine> {
const existing = await this.repository.findByCode(dto.code);
if (existing) throw new ConflictException(`Shipping line with code "${dto.code}" already exists`);
return this.repository.create({
code: dto.code,
label: dto.label,
mappedToCode: dto.mappedToCode,
showExtraFeeNotice: dto.showExtraFeeNotice ?? false,
isActive: dto.isActive ?? true,
});
}
/** Update a shipping line. */
async update(id: string, dto: UpdateShippingLineDto): Promise<ShippingLine> {
await this.findById(id);
if (dto.code) {
const conflict = await this.repository.findByCode(dto.code);
if (conflict && conflict.id !== id) {
throw new ConflictException(`Shipping line with code "${dto.code}" already exists`);
}
}
const updated = await this.repository.update(id, dto);
if (!updated) throw new NotFoundException(`Shipping line ${id} not found`);
return updated;
}
/** Soft-delete a shipping line. */
async remove(id: string): Promise<void> {
await this.findById(id);
await this.repository.softDelete(id);
}
}

View File

@@ -27,7 +27,7 @@ export class SurchargeTypesService {
const [data, total] = await this.repository.findAndCount({
where,
order: { name: 'ASC' },
order: { label: 'ASC' },
skip: (page - 1) * pageSize,
take: pageSize,
});
@@ -47,8 +47,9 @@ export class SurchargeTypesService {
if (existing) throw new ConflictException(`Surcharge type with code "${dto.code}" already exists`);
return this.repository.create({
code: dto.code,
name: dto.name,
description: dto.description ?? null,
label: dto.label,
triggerCondition: dto.triggerCondition as SurchargeType['triggerCondition'],
rateId: dto.rateId,
isActive: dto.isActive ?? true,
});
}
@@ -62,7 +63,13 @@ export class SurchargeTypesService {
throw new ConflictException(`Surcharge type with code "${dto.code}" already exists`);
}
}
const updated = await this.repository.update(id, dto);
const patch: Partial<SurchargeType> = {};
if (dto.code !== undefined) patch.code = dto.code;
if (dto.label !== undefined) patch.label = dto.label;
if (dto.triggerCondition !== undefined) patch.triggerCondition = dto.triggerCondition as SurchargeType['triggerCondition'];
if (dto.rateId !== undefined) patch.rateId = dto.rateId;
if (dto.isActive !== undefined) patch.isActive = dto.isActive;
const updated = await this.repository.update(id, patch);
if (!updated) throw new NotFoundException(`Surcharge type ${id} not found`);
return updated;
}

View File

@@ -1,76 +0,0 @@
import { Inject, Injectable, NotFoundException } from '@nestjs/common';
import { CreateSurchargeDto } from '../dto/create-surcharge.dto';
import { UpdateSurchargeDto } from '../dto/update-surcharge.dto';
import { Surcharge } from '../entities/surcharge.entity';
import {
ISurchargesRepository,
SURCHARGES_REPOSITORY,
} from '../interfaces/surcharges.repository.interface';
@Injectable()
export class SurchargesService {
constructor(
@Inject(SURCHARGES_REPOSITORY)
private readonly repository: ISurchargesRepository,
) {}
/** List surcharges with pagination. */
async findAll(filter: {
isActive?: boolean;
surchargeTypeId?: string;
page?: number;
pageSize?: number;
}): Promise<{ data: Surcharge[]; meta: { total: number; page: number; pageSize: number; totalPages: number } }> {
const page = filter.page ?? 1;
const pageSize = filter.pageSize ?? 20;
const where: Record<string, unknown> = {};
if (filter.isActive !== undefined) where.isActive = filter.isActive;
if (filter.surchargeTypeId) where.surchargeTypeId = filter.surchargeTypeId;
const [data, total] = await this.repository.findAndCount({
where,
relations: { surchargeType: true },
order: { feeName: 'ASC' },
skip: (page - 1) * pageSize,
take: pageSize,
});
return { data, meta: { total, page, pageSize, totalPages: Math.ceil(total / pageSize) } };
}
/** Get a single surcharge by ID. */
async findById(id: string): Promise<Surcharge> {
const entity = await this.repository.findById(id);
if (!entity) throw new NotFoundException(`Surcharge ${id} not found`);
return entity;
}
/** Create a new surcharge. */
async create(dto: CreateSurchargeDto): Promise<Surcharge> {
return this.repository.create({
surchargeTypeId: dto.surchargeTypeId,
feeName: dto.feeName,
triggerDescription: dto.triggerDescription ?? null,
calculationMethod: dto.calculationMethod,
rate: dto.rate,
currency: dto.currency,
applyToRail: dto.applyToRail ?? false,
applyToFirstMile: dto.applyToFirstMile ?? false,
applyToLastMile: dto.applyToLastMile ?? false,
isActive: dto.isActive ?? true,
});
}
/** Update an existing surcharge. */
async update(id: string, dto: UpdateSurchargeDto): Promise<Surcharge> {
await this.findById(id);
const updated = await this.repository.update(id, dto);
if (!updated) throw new NotFoundException(`Surcharge ${id} not found`);
return updated;
}
/** Soft-delete a surcharge. */
async remove(id: string): Promise<void> {
await this.findById(id);
await this.repository.softDelete(id);
}
}

View File

@@ -1,4 +1,4 @@
import { BadRequestException, Inject, Injectable, NotFoundException } from '@nestjs/common';
import { Inject, Injectable, NotFoundException } from '@nestjs/common';
import { CreateWeightLimitRuleDto } from '../dto/create-weight-limit-rule.dto';
import { UpdateWeightLimitRuleDto } from '../dto/update-weight-limit-rule.dto';
import { WeightLimitRule } from '../entities/weight-limit-rule.entity';
@@ -16,20 +16,21 @@ export class WeightLimitRulesService {
/** List weight limit rules with pagination. */
async findAll(filter: {
isActive?: boolean;
containerTypeId?: string;
tradeDirection?: string;
page?: number;
pageSize?: number;
}): Promise<{ data: WeightLimitRule[]; meta: { total: number; page: number; pageSize: number; totalPages: number } }> {
const page = filter.page ?? 1;
const pageSize = filter.pageSize ?? 20;
const where: Record<string, unknown> = {};
if (filter.isActive !== undefined) where.isActive = filter.isActive;
if (filter.containerTypeId) where.containerTypeId = filter.containerTypeId;
if (filter.tradeDirection) where.tradeDirection = filter.tradeDirection;
const [data, total] = await this.repository.findAndCount({
where,
relations: { containerType: true, surcharge: { surchargeType: true } },
relations: { containerType: true },
order: { effectiveFrom: 'DESC' },
skip: (page - 1) * pageSize,
take: pageSize,
});
@@ -45,27 +46,25 @@ export class WeightLimitRulesService {
/** Create a new weight limit rule. */
async create(dto: CreateWeightLimitRuleDto): Promise<WeightLimitRule> {
if (dto.warningThresholdTons > dto.maxWeightTons) {
throw new BadRequestException('warningThresholdTons must be ≤ maxWeightTons');
}
return this.repository.create({
containerTypeId: dto.containerTypeId,
tradeDirection: dto.tradeDirection,
maxWeightTons: dto.maxWeightTons,
warningThresholdTons: dto.warningThresholdTons,
exceededAction: dto.exceededAction,
surchargeId: dto.surchargeId ?? null,
isActive: dto.isActive ?? true,
maxVgmTons: dto.maxVgmTons,
effectiveFrom: new Date(dto.effectiveFrom),
effectiveTo: dto.effectiveTo ? new Date(dto.effectiveTo) : null,
});
}
/** Update an existing weight limit rule. */
async update(id: string, dto: UpdateWeightLimitRuleDto): Promise<WeightLimitRule> {
const existing = await this.findById(id);
const warning = dto.warningThresholdTons ?? existing.warningThresholdTons;
const max = dto.maxWeightTons ?? existing.maxWeightTons;
if (warning > max) throw new BadRequestException('warningThresholdTons must be ≤ maxWeightTons');
const updated = await this.repository.update(id, dto);
await this.findById(id);
const patch: Partial<WeightLimitRule> = {};
if (dto.containerTypeId !== undefined) patch.containerTypeId = dto.containerTypeId;
if (dto.tradeDirection !== undefined) patch.tradeDirection = dto.tradeDirection;
if (dto.maxVgmTons !== undefined) patch.maxVgmTons = dto.maxVgmTons;
if (dto.effectiveFrom !== undefined) patch.effectiveFrom = new Date(dto.effectiveFrom);
if (dto.effectiveTo !== undefined) patch.effectiveTo = new Date(dto.effectiveTo);
const updated = await this.repository.update(id, patch);
if (!updated) throw new NotFoundException(`Weight limit rule ${id} not found`);
return updated;
}

View File

@@ -0,0 +1,75 @@
import { ConflictException, Inject, Injectable, NotFoundException } from '@nestjs/common';
import { CreateYardDto } from '../dto/create-yard.dto';
import { UpdateYardDto } from '../dto/update-yard.dto';
import { Yard } from '../entities/yard.entity';
import { IYardsRepository, YARDS_REPOSITORY } from '../interfaces/yards.repository.interface';
@Injectable()
export class YardsService {
constructor(
@Inject(YARDS_REPOSITORY)
private readonly repository: IYardsRepository,
) {}
/** List yards with pagination. */
async findAll(filter: {
isActive?: boolean;
country?: string;
page?: number;
pageSize?: number;
}): Promise<{ data: Yard[]; meta: { total: number; page: number; pageSize: number; totalPages: number } }> {
const page = filter.page ?? 1;
const pageSize = filter.pageSize ?? 20;
const where: Record<string, unknown> = {};
if (filter.isActive !== undefined) where.isActive = filter.isActive;
if (filter.country) where.country = filter.country;
const [data, total] = await this.repository.findAndCount({
where,
order: { displayOrder: 'ASC', code: 'ASC' },
skip: (page - 1) * pageSize,
take: pageSize,
});
return { data, meta: { total, page, pageSize, totalPages: Math.ceil(total / pageSize) } };
}
/** Get a yard by ID. */
async findById(id: string): Promise<Yard> {
const entity = await this.repository.findById(id);
if (!entity) throw new NotFoundException(`Yard ${id} not found`);
return entity;
}
/** Create a yard. */
async create(dto: CreateYardDto): Promise<Yard> {
const existing = await this.repository.findByCode(dto.code);
if (existing) throw new ConflictException(`Yard with code "${dto.code}" already exists`);
return this.repository.create({
code: dto.code,
label: dto.label,
country: dto.country,
isActive: dto.isActive ?? true,
displayOrder: dto.displayOrder ?? 1,
});
}
/** Update a yard. */
async update(id: string, dto: UpdateYardDto): Promise<Yard> {
await this.findById(id);
if (dto.code) {
const conflict = await this.repository.findByCode(dto.code);
if (conflict && conflict.id !== id) {
throw new ConflictException(`Yard with code "${dto.code}" already exists`);
}
}
const updated = await this.repository.update(id, dto);
if (!updated) throw new NotFoundException(`Yard ${id} not found`);
return updated;
}
/** Soft-delete a yard. */
async remove(id: string): Promise<void> {
await this.findById(id);
await this.repository.softDelete(id);
}
}