change price logic on the ,rule engine ui, auto generate the contrat

This commit is contained in:
marshal
2026-06-08 10:04:23 +03:00
parent 4993453993
commit 88df20be6b
76 changed files with 4907 additions and 225 deletions

View File

@@ -14,6 +14,11 @@ export function computeNextStep(
const { status } = booking;
switch (status) {
case 'PRICE_CHANGED_PENDING_CONFIRM':
return {
action: 'CONFIRM_SUBMIT',
description: 'Price has changed since preview; confirm to submit booking',
};
case 'SUBMITTED':
return {
action: 'ACCEPT_INTAKE',

View File

@@ -14,6 +14,24 @@ import { GeneratePriceResponseDto, PriceLineItemDto } from './dto/generate-price
import { Booking } from './entities/booking.entity';
import { assertBookingStatus } from './booking-status.util';
export interface ComputedPriceResult {
lineItems: PriceLineItemDto[];
totalAmount: number;
currency: string;
usedRates: Rate[];
appliedModifiers: AppliedCargoModifier[];
priorityScore: number;
warnings: string[];
hardBlocked: string[];
}
type StoredPricingBreakdown = {
lineItems?: PriceLineItemDto[];
totalAmount?: number;
currency?: string;
generatedAt?: string;
} | null;
@Injectable()
export class BookingPricingService {
constructor(
@@ -26,22 +44,56 @@ export class BookingPricingService {
async generatePrice(bookingId: string): Promise<GeneratePriceResponseDto> {
const booking = await this.requireBooking(bookingId);
assertBookingStatus(booking, ['DRAFT']);
assertBookingStatus(booking, ['DRAFT', 'CHANGES_REQUESTED']);
const computed = await this.computePriceForBooking(booking);
this.ruleEngineService.assertNoHardBlocks({
priorityScore: computed.priorityScore,
appliedModifiers: computed.appliedModifiers,
containerWeightResults: [],
warnings: computed.warnings,
hardBlocked: computed.hardBlocked,
requiresDirectorApproval: false,
});
await this.bookingsRepository.update(bookingId, {
totalAmount: computed.totalAmount,
priorityScore: computed.priorityScore,
pricingBreakdown: {
lineItems: computed.lineItems,
totalAmount: computed.totalAmount,
currency: computed.currency,
generatedAt: new Date().toISOString(),
},
} as never);
return {
bookingId,
totalAmount: computed.totalAmount,
currency: computed.currency,
lineItems: computed.lineItems,
warnings: computed.warnings,
};
}
async computePriceForBooking(booking: Booking): Promise<ComputedPriceResult> {
const evalInput = await this.buildEvalInputForBooking(booking);
console.log('evalInput----', evalInput);
const ruleResult = await this.ruleEngineService.evaluate(evalInput);
this.ruleEngineService.assertNoHardBlocks(ruleResult);
const lineItems: PriceLineItemDto[] = [];
let total = 0;
const baseLines = await this.computeBaseRailLines(booking, evalInput);
const { lineItems: baseLines, usedRates: baseRates } =
await this.computeBaseRailLinesWithRates(booking, evalInput);
for (const line of baseLines) {
lineItems.push(line);
total += line.amount;
}
const liveRates = await this.ratesService.findLiveRates();
const rateById = new Map(liveRates.map((r) => [r.id, r]));
const usedRatesMap = new Map(baseRates.map((r) => [r.id, r]));
for (const mod of ruleResult.appliedModifiers) {
const item: PriceLineItemDto = {
code: mod.surchargeTypeCode,
@@ -51,30 +103,60 @@ export class BookingPricingService {
};
lineItems.push(item);
total += mod.calculatedAmount;
const rate = rateById.get(mod.rateId);
if (rate) usedRatesMap.set(rate.id, rate);
}
await this.persistPriceRun(bookingId, ruleResult.appliedModifiers, total);
await this.bookingsRepository.update(bookingId, {
totalAmount: total,
priorityScore: ruleResult.priorityScore,
pricingBreakdown: {
lineItems,
totalAmount: total,
currency: booking.paymentCurrency,
generatedAt: new Date().toISOString(),
},
} as never);
return {
bookingId,
lineItems,
totalAmount: total,
currency: booking.paymentCurrency,
lineItems,
usedRates: [...usedRatesMap.values()],
appliedModifiers: ruleResult.appliedModifiers,
priorityScore: ruleResult.priorityScore,
warnings: ruleResult.warnings,
hardBlocked: ruleResult.hardBlocked,
};
}
pricesMatch(stored: StoredPricingBreakdown, computed: ComputedPriceResult): boolean {
if (!stored?.lineItems?.length) return false;
if (Number(stored.totalAmount) !== computed.totalAmount) return false;
return (
this.lineItemsSignature(stored.lineItems) ===
this.lineItemsSignature(computed.lineItems)
);
}
async createPricingSnapshots(
bookingId: string,
usedRates: Rate[],
appliedModifiers: AppliedCargoModifier[],
): Promise<void> {
await this.bookingsRepository.clearPricingArtifacts(bookingId);
const snapshots = await this.ruleEngineService.snapshotRates(bookingId, usedRates);
const snapshotByRateId = new Map(snapshots.map((s) => [s.rateId, s.id]));
const rows = appliedModifiers
.map((m) => {
const snapshotId = snapshotByRateId.get(m.rateId);
if (!snapshotId) return null;
return {
bookingId,
surchargeTypeId: m.surchargeTypeId,
triggerValue: m.triggerValue,
calculatedAmount: m.calculatedAmount,
rateSnapshotId: snapshotId,
};
})
.filter((r): r is NonNullable<typeof r> => r !== null);
if (rows.length > 0) {
await this.bookingsRepository.createCargoModifiers(rows);
}
}
async buildEvalInputForBooking(booking: Booking): Promise<BookingEvaluationInput> {
const containers = await Promise.all(
(booking.bookingContainers ?? []).map(async (bc) => {
@@ -115,11 +197,7 @@ export class BookingPricingService {
totalAmount: number;
currency: string;
}> {
const stored = booking.pricingBreakdown as {
lineItems?: PriceLineItemDto[];
totalAmount?: number;
currency?: string;
} | null;
const stored = booking.pricingBreakdown as StoredPricingBreakdown;
if (stored?.lineItems?.length) {
return {
@@ -129,41 +207,28 @@ export class BookingPricingService {
};
}
const evalInput = await this.buildEvalInputForBooking(booking);
const ruleResult = await this.ruleEngineService.evaluate(evalInput);
const lineItems: PriceLineItemDto[] = [];
let total = 0;
const computed = await this.computePriceForBooking(booking);
const baseLines = await this.computeBaseRailLines(booking, evalInput);
for (const line of baseLines) {
lineItems.push(line);
total += line.amount;
}
for (const mod of ruleResult.appliedModifiers) {
lineItems.push({
code: mod.surchargeTypeCode,
description: `Surcharge: ${mod.surchargeTypeCode}`,
amount: mod.calculatedAmount,
currency: mod.currency,
});
total += mod.calculatedAmount;
}
if (lineItems.length === 0) {
total = Number(booking.totalAmount);
lineItems.push({
code: 'TOTAL',
description: 'Contract total',
amount: total,
if (computed.lineItems.length === 0) {
const total = Number(booking.totalAmount);
return {
lineItems: [
{
code: 'TOTAL',
description: 'Contract total',
amount: total,
currency: booking.paymentCurrency,
},
],
totalAmount: total,
currency: booking.paymentCurrency,
});
};
}
return {
lineItems,
totalAmount: total || Number(booking.totalAmount),
currency: booking.paymentCurrency,
lineItems: computed.lineItems,
totalAmount: computed.totalAmount || Number(booking.totalAmount),
currency: computed.currency,
};
}
@@ -190,14 +255,14 @@ export class BookingPricingService {
return score;
}
private async computeBaseRailLines(
private async computeBaseRailLinesWithRates(
booking: Booking,
evalInput: BookingEvaluationInput,
): Promise<PriceLineItemDto[]> {
): Promise<{ lineItems: PriceLineItemDto[]; usedRates: Rate[] }> {
const liveRates = await this.ratesService.findLiveRates();
const currency = booking.paymentCurrency;
const isBulk = booking.freightType === 'BULK';
console.log('liveRates----', liveRates);
const rateType =
booking.tradeDirection === 'IMPORT'
? isBulk
@@ -209,18 +274,15 @@ console.log('liveRates----', liveRates);
: 'CONTAINER_EXPORT'
: 'INTERCITY_CONTAINER';
console.log('rateType----', rateType);
const lines: PriceLineItemDto[] = [];
const usedRatesMap = new Map<string, Rate>();
const wagonCount = await this.bookingsRepository.calculateWagonCount(booking.id);
for (const container of evalInput.containers) {
console.log('container----', container);
const rate = this.pickRate(liveRates, rateType, container.containerTypeId, currency);
console.log('rate----', rate);
if (!rate) continue;
usedRatesMap.set(rate.id, rate);
const amount = this.amountForRate(rate, container.quantity, wagonCount);
lines.push({
code: rateType,
@@ -235,6 +297,7 @@ console.log('liveRates----', liveRates);
(r) => r.rateType === rateType && r.currency === currency && r.status === 'LIVE',
);
if (fallback) {
usedRatesMap.set(fallback.id, fallback);
const amount = this.amountForRate(fallback, 1, wagonCount);
lines.push({
code: rateType,
@@ -245,7 +308,7 @@ console.log('liveRates----', liveRates);
}
}
return lines;
return { lineItems: lines, usedRates: [...usedRatesMap.values()] };
}
private pickRate(
@@ -281,31 +344,15 @@ console.log('liveRates----', liveRates);
}
}
private async persistPriceRun(
bookingId: string,
modifiers: AppliedCargoModifier[],
_total: number,
): Promise<void> {
await this.bookingsRepository.clearPricingArtifacts(bookingId);
const snapshots = await this.ruleEngineService.snapshotLiveRates(bookingId);
const snapshotByRateId = new Map(snapshots.map((s) => [s.rateId, s.id]));
const rows = modifiers
.map((m) => {
const snapshotId = snapshotByRateId.get(m.rateId);
if (!snapshotId) return null;
return {
bookingId,
surchargeTypeId: m.surchargeTypeId,
triggerValue: m.triggerValue,
calculatedAmount: m.calculatedAmount,
rateSnapshotId: snapshotId,
};
})
.filter((r): r is NonNullable<typeof r> => r !== null);
if (rows.length > 0) {
await this.bookingsRepository.createCargoModifiers(rows);
}
private lineItemsSignature(items: PriceLineItemDto[]): string {
return JSON.stringify(
[...items]
.map((item) => ({
code: item.code,
amount: item.amount,
currency: item.currency,
}))
.sort((a, b) => a.code.localeCompare(b.code)),
);
}
}

View File

@@ -8,6 +8,8 @@ import { BookingPricingService } from './booking-pricing.service';
import { BookingsRepository } from './bookings.repository';
import { assertBookingStatus } from './booking-status.util';
import { computeNextStep, type BookingNextStep } from './booking-next-step.util';
import { SubmitBookingResponseDto } from './dto/submit-booking-response.dto';
import { PriceLineItemDto } from './dto/generate-price-response.dto';
import { Booking } from './entities/booking.entity';
import { BookingsService } from './bookings.service';
@@ -22,7 +24,7 @@ export class BookingTransitionService {
private readonly bookingsService: BookingsService,
) {}
async submit(bookingId: string): Promise<Booking> {
async submit(bookingId: string): Promise<SubmitBookingResponseDto> {
const booking = await this.bookingsService.findById(bookingId);
assertBookingStatus(booking, ['DRAFT', 'CHANGES_REQUESTED']);
@@ -32,14 +34,119 @@ export class BookingTransitionService {
);
}
const priorityScore = await this.pricingService.computeSubmitPriorityScore(booking);
await this.ruleEngineService.snapshotLiveRates(bookingId);
const computed = await this.pricingService.computePriceForBooking(booking);
this.ruleEngineService.assertNoHardBlocks({
priorityScore: computed.priorityScore,
appliedModifiers: computed.appliedModifiers,
containerWeightResults: [],
warnings: computed.warnings,
hardBlocked: computed.hardBlocked,
requiresDirectorApproval: false,
});
const stored = booking.pricingBreakdown as {
lineItems?: PriceLineItemDto[];
totalAmount?: number;
} | null;
const unchanged = this.pricingService.pricesMatch(stored, computed);
const priorityScore = await this.pricingService.computeSubmitPriorityScore(booking);
if (unchanged) {
await this.pricingService.createPricingSnapshots(
bookingId,
computed.usedRates,
computed.appliedModifiers,
);
const updated = await this.bookingsRepository.update(bookingId, {
status: 'SUBMITTED',
priorityScore,
} as never);
const finalBooking = await this.bookingsService.findById(updated!.id);
return {
bookingId: finalBooking.id,
status: finalBooking.status,
priceChanged: false,
totalAmount: Number(finalBooking.totalAmount),
currency: finalBooking.paymentCurrency,
lineItems: computed.lineItems,
};
}
const previousTotalAmount = Number(booking.totalAmount);
await this.bookingsRepository.update(bookingId, {
totalAmount: computed.totalAmount,
priorityScore: computed.priorityScore,
pricingBreakdown: {
lineItems: computed.lineItems,
totalAmount: computed.totalAmount,
currency: computed.currency,
generatedAt: new Date().toISOString(),
},
status: 'PRICE_CHANGED_PENDING_CONFIRM',
} as never);
const updatedBooking = await this.bookingsService.findById(bookingId);
return {
bookingId: updatedBooking.id,
status: updatedBooking.status,
priceChanged: true,
previousTotalAmount,
totalAmount: computed.totalAmount,
currency: computed.currency,
lineItems: computed.lineItems,
message: 'Price has changed since preview. Confirm to submit with the updated price.',
};
}
async confirmSubmit(bookingId: string): Promise<SubmitBookingResponseDto> {
const booking = await this.bookingsService.findById(bookingId);
assertBookingStatus(booking, ['PRICE_CHANGED_PENDING_CONFIRM']);
if (Number(booking.totalAmount) <= 0) {
throw new BadRequestException('No price to confirm');
}
const computed = await this.pricingService.computePriceForBooking(booking);
this.ruleEngineService.assertNoHardBlocks({
priorityScore: computed.priorityScore,
appliedModifiers: computed.appliedModifiers,
containerWeightResults: [],
warnings: computed.warnings,
hardBlocked: computed.hardBlocked,
requiresDirectorApproval: false,
});
await this.pricingService.createPricingSnapshots(
bookingId,
computed.usedRates,
computed.appliedModifiers,
);
const priorityScore = await this.pricingService.computeSubmitPriorityScore(booking);
const updated = await this.bookingsRepository.update(bookingId, {
status: 'SUBMITTED',
priorityScore,
totalAmount: computed.totalAmount,
pricingBreakdown: {
lineItems: computed.lineItems,
totalAmount: computed.totalAmount,
currency: computed.currency,
generatedAt: new Date().toISOString(),
},
} as never);
return this.bookingsService.findById(updated!.id);
const finalBooking = await this.bookingsService.findById(updated!.id);
return {
bookingId: finalBooking.id,
status: finalBooking.status,
priceChanged: false,
totalAmount: Number(finalBooking.totalAmount),
currency: finalBooking.paymentCurrency,
lineItems: computed.lineItems,
message: 'Booking submitted with confirmed price.',
};
}
async requestChanges(
@@ -279,6 +386,7 @@ export class BookingTransitionService {
assertBookingStatus(booking, [
'DRAFT',
'SUBMITTED',
'PRICE_CHANGED_PENDING_CONFIRM',
'CHANGES_REQUESTED',
'PENDING_APPROVAL',
'CONTRACT_READY',
@@ -321,4 +429,4 @@ export class BookingTransitionService {
nextStep,
};
}
}
}

View File

@@ -39,6 +39,7 @@ import { CreateBookingDto } from './dto/create-booking.dto';
import { BookingListSummaryDto } from './dto/booking-list-summary.dto';
import { FilterBookingDto } from './dto/filter-booking.dto';
import { GeneratePriceResponseDto } from './dto/generate-price-response.dto';
import { SubmitBookingResponseDto } from './dto/submit-booking-response.dto';
import {
ApproveStepDto,
CancelBookingDto,
@@ -165,17 +166,36 @@ export class BookingsController {
}
@Post(':id/generate-price')
@ApiOperation({ summary: 'Generate price preview (DRAFT only)' })
@ApiOperation({
summary: 'Generate price preview (DRAFT or CHANGES_REQUESTED)',
description:
'Computes and stores a price preview on the booking. Does not create rate snapshots.',
})
@ApiOkResponse({ type: GeneratePriceResponseDto })
generatePrice(@Param('id', ParseUUIDPipe) id: string) {
return this.pricingService.generatePrice(id);
}
@Post(':id/submit')
@ApiOperation({ summary: 'Customer submit booking' })
async submit(@Param('id', ParseUUIDPipe) id: string) {
const booking = await this.transitionService.submit(id);
return this.transitionService.enrichBookingResponse(booking);
@ApiOperation({
summary: 'Customer submit booking',
description:
'Recomputes price against live rates. If unchanged, creates rate snapshots and submits. If changed, updates the booking price and returns priceChanged=true for confirmation.',
})
@ApiOkResponse({ type: SubmitBookingResponseDto })
submit(@Param('id', ParseUUIDPipe) id: string) {
return this.transitionService.submit(id);
}
@Post(':id/confirm-submit')
@ApiOperation({
summary: 'Confirm submit after price change',
description:
'Creates rate snapshots for the updated booking price and moves the booking to SUBMITTED.',
})
@ApiOkResponse({ type: SubmitBookingResponseDto })
confirmSubmit(@Param('id', ParseUUIDPipe) id: string) {
return this.transitionService.confirmSubmit(id);
}
@Post(':id/staff/request-changes')

View File

@@ -345,6 +345,26 @@ export class BookingsRepository extends BaseRepository<Booking> {
await this.dataSource.getRepository(BookingRateSnapshot).delete({ bookingId });
}
async hasPricingArtifacts(bookingId: string): Promise<boolean> {
const snapshotCount = await this.dataSource
.getRepository(BookingRateSnapshot)
.count({ where: { bookingId } });
const modifierCount = await this.dataSource
.getRepository(BookingCargoModifier)
.count({ where: { bookingId } });
return snapshotCount > 0 || modifierCount > 0;
}
async invalidatePricingPreview(bookingId: string): Promise<void> {
if (await this.hasPricingArtifacts(bookingId)) {
await this.clearPricingArtifacts(bookingId);
}
await this.update(bookingId, {
totalAmount: 0,
pricingBreakdown: null,
} as never);
}
/** Queue listing with optional bulk exclusion for LINE_STAFF. */
async findQueue(options: {
status: string | string[];

View File

@@ -348,6 +348,15 @@ export class BookingsService {
this.ruleEngineService.assertNoHardBlocks(ruleResult);
warnings.push(...ruleResult.warnings);
const pricingFieldsChanged = this.pricingRelevantFieldsChanged(
existing,
dto,
freightType,
cargoTypeId,
allowConsolidation,
containers,
);
const updates: Record<string, unknown> = {
...dto,
freightType,
@@ -375,6 +384,10 @@ export class BookingsService {
);
}
if (pricingFieldsChanged) {
await this.bookingsRepository.invalidatePricingPreview(id);
}
if (files.length > 0) {
await this.filesService.uploadMany(id, 'bookings', files);
}
@@ -648,4 +661,57 @@ export class BookingsService {
),
};
}
private pricingRelevantFieldsChanged(
existing: Booking,
dto: UpdateBookingDto,
freightType: FreightType,
cargoTypeId: string | null | undefined,
allowConsolidation: boolean,
containers: CreateBookingContainerDto[],
): boolean {
if (dto.freightType !== undefined && dto.freightType !== existing.freightType) {
return true;
}
if (dto.tradeDirection !== undefined && dto.tradeDirection !== existing.tradeDirection) {
return true;
}
if (dto.paymentCurrency !== undefined && dto.paymentCurrency !== existing.paymentCurrency) {
return true;
}
if (dto.isHazardous !== undefined && dto.isHazardous !== existing.isHazardous) {
return true;
}
if (
dto.allowConsolidation !== undefined &&
dto.allowConsolidation !== existing.allowConsolidation
) {
return true;
}
if (dto.shippingLineId !== undefined && dto.shippingLineId !== existing.shippingLineId) {
return true;
}
if (dto.cargoTypeId !== undefined && dto.cargoTypeId !== existing.cargoTypeId) {
return true;
}
if (dto.containers !== undefined) {
const existingContainers =
existing.bookingContainers?.map((bc) => ({
containerTypeId: bc.containerTypeId,
quantity: bc.quantity,
vgmPerUnitTons: Number(bc.vgmPerUnitTons),
})) ?? [];
if (JSON.stringify(existingContainers) !== JSON.stringify(containers)) {
return true;
}
}
if (
freightType !== existing.freightType ||
(cargoTypeId ?? null) !== (existing.cargoTypeId ?? null) ||
allowConsolidation !== existing.allowConsolidation
) {
return true;
}
return false;
}
}

View File

@@ -0,0 +1,29 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { PriceLineItemDto } from './generate-price-response.dto';
export class SubmitBookingResponseDto {
@ApiProperty()
bookingId!: string;
@ApiProperty()
status!: string;
@ApiProperty()
priceChanged!: boolean;
@ApiPropertyOptional()
previousTotalAmount?: number;
@ApiProperty()
totalAmount!: number;
@ApiProperty()
currency!: string;
@ApiPropertyOptional({ type: [PriceLineItemDto] })
lineItems?: PriceLineItemDto[];
@ApiPropertyOptional()
message?: string;
}

View File

@@ -17,6 +17,7 @@ import { BookingReviewNote } from './booking-review-note.entity';
export const BOOKING_STATUSES = [
'DRAFT',
'SUBMITTED',
'PRICE_CHANGED_PENDING_CONFIRM',
'CHANGES_REQUESTED',
'PENDING_APPROVAL',
'APPROVED_PENDING_SIGNATURE',

View File

@@ -0,0 +1,17 @@
import { ApiPropertyOptional } from '@nestjs/swagger';
import { IsIn, IsOptional } from 'class-validator';
const OVERVIEW_RANGES = ['7d', '30d', '90d'] as const;
export type OverviewRangeQuery = (typeof OVERVIEW_RANGES)[number];
export class OverviewQueryDto {
@ApiPropertyOptional({
enum: OVERVIEW_RANGES,
default: '30d',
description: 'Time range for trend charts',
})
@IsOptional()
@IsIn(OVERVIEW_RANGES)
range?: OverviewRangeQuery = '30d';
}

View File

@@ -0,0 +1,104 @@
import { ApiProperty } from '@nestjs/swagger';
export class OverviewBookingKpisDto {
@ApiProperty() totalActive!: number;
@ApiProperty() needsAction!: number;
@ApiProperty() urgent!: number;
@ApiProperty() inApproval!: number;
@ApiProperty() submittedToday!: number;
}
export class OverviewOperationsKpisDto {
@ApiProperty() trainsActive!: number;
@ApiProperty() wagonsAvailable!: number;
@ApiProperty() containersInTransit!: number;
@ApiProperty() cargoesLoaded!: number;
}
export class OverviewCustomerKpisDto {
@ApiProperty() totalCustomers!: number;
@ApiProperty() newCustomersThisMonth!: number;
}
export class OverviewBillingKpisDto {
@ApiProperty() revenueMtdEtb!: number;
@ApiProperty() revenueMtdUsd!: number;
@ApiProperty() pendingPayments!: number;
@ApiProperty() successfulPaymentsMtd!: number;
}
export class OverviewStaffKpisDto {
@ApiProperty() activeEmployees!: number;
@ApiProperty() activeUsers!: number;
}
export class OverviewKpisDto {
@ApiProperty({ type: OverviewBookingKpisDto })
bookings!: OverviewBookingKpisDto;
@ApiProperty({ type: OverviewOperationsKpisDto })
operations!: OverviewOperationsKpisDto;
@ApiProperty({ type: OverviewCustomerKpisDto })
customers!: OverviewCustomerKpisDto;
@ApiProperty({ type: OverviewBillingKpisDto })
billing!: OverviewBillingKpisDto;
@ApiProperty({ type: OverviewStaffKpisDto })
staff!: OverviewStaffKpisDto;
}
export class OverviewTrendPointDto {
@ApiProperty({ example: '2026-06-01' }) date!: string;
@ApiProperty() count!: number;
}
export class OverviewStatusCountDto {
@ApiProperty() status!: string;
@ApiProperty() count!: number;
}
export class OverviewPipelineCountDto {
@ApiProperty() stage!: string;
@ApiProperty() count!: number;
}
export class OverviewPaymentTrendPointDto {
@ApiProperty({ example: '2026-06-01' }) date!: string;
@ApiProperty() amountEtb!: number;
@ApiProperty() amountUsd!: number;
}
export class OverviewRecentBookingDto {
@ApiProperty() id!: string;
@ApiProperty() reference!: string;
@ApiProperty() customerLabel!: string;
@ApiProperty() status!: string;
@ApiProperty() priorityScore!: number;
@ApiProperty({ nullable: true }) totalAmount!: number | null;
@ApiProperty({ nullable: true }) paymentCurrency!: string | null;
@ApiProperty() createdAt!: string;
}
export class OverviewResponseDto {
@ApiProperty({ type: OverviewKpisDto })
kpis!: OverviewKpisDto;
@ApiProperty({ type: [OverviewTrendPointDto] })
bookingTrend!: OverviewTrendPointDto[];
@ApiProperty({ type: [OverviewStatusCountDto] })
bookingsByStatus!: OverviewStatusCountDto[];
@ApiProperty({ type: [OverviewPipelineCountDto] })
bookingsByPipeline!: OverviewPipelineCountDto[];
@ApiProperty({ type: [OverviewPaymentTrendPointDto] })
paymentTrend!: OverviewPaymentTrendPointDto[];
@ApiProperty({ type: [OverviewRecentBookingDto] })
recentBookings!: OverviewRecentBookingDto[];
@ApiProperty() generatedAt!: string;
}

View File

@@ -0,0 +1,131 @@
import { ApiProperty } from '@nestjs/swagger';
import {
OverviewBillingKpisDto,
OverviewBookingKpisDto,
OverviewCustomerKpisDto,
OverviewOperationsKpisDto,
OverviewPaymentTrendPointDto,
OverviewPipelineCountDto,
OverviewRecentBookingDto,
OverviewStaffKpisDto,
OverviewStatusCountDto,
OverviewTrendPointDto,
} from './overview-response.dto';
export class OverviewLabelCountDto {
@ApiProperty() label!: string;
@ApiProperty() count!: number;
}
export class OverviewPaymentMethodDto {
@ApiProperty() method!: string;
@ApiProperty() count!: number;
@ApiProperty() amountEtb!: number;
@ApiProperty() amountUsd!: number;
}
export class OverviewCurrencyAmountDto {
@ApiProperty() currency!: string;
@ApiProperty() amount!: number;
}
export class OverviewBookingsTabDto {
@ApiProperty({ type: OverviewBookingKpisDto })
kpis!: OverviewBookingKpisDto;
@ApiProperty({ type: [OverviewTrendPointDto] })
bookingTrend!: OverviewTrendPointDto[];
@ApiProperty({ type: [OverviewStatusCountDto] })
bookingsByStatus!: OverviewStatusCountDto[];
@ApiProperty({ type: [OverviewPipelineCountDto] })
bookingsByPipeline!: OverviewPipelineCountDto[];
@ApiProperty({ type: [OverviewLabelCountDto] })
bookingsByFreightType!: OverviewLabelCountDto[];
@ApiProperty({ type: [OverviewLabelCountDto] })
bookingsByCurrency!: OverviewLabelCountDto[];
@ApiProperty({ type: [OverviewRecentBookingDto] })
recentBookings!: OverviewRecentBookingDto[];
@ApiProperty()
generatedAt!: string;
}
export class OverviewBillingTabDto {
@ApiProperty({ type: OverviewBillingKpisDto })
kpis!: OverviewBillingKpisDto;
@ApiProperty({ type: [OverviewPaymentTrendPointDto] })
paymentTrend!: OverviewPaymentTrendPointDto[];
@ApiProperty({ type: [OverviewStatusCountDto] })
paymentsByStatus!: OverviewStatusCountDto[];
@ApiProperty({ type: [OverviewPaymentMethodDto] })
paymentsByMethod!: OverviewPaymentMethodDto[];
@ApiProperty({ type: [OverviewCurrencyAmountDto] })
revenueByCurrency!: OverviewCurrencyAmountDto[];
@ApiProperty()
generatedAt!: string;
}
export class OverviewOperationsTabDto {
@ApiProperty({ type: OverviewOperationsKpisDto })
kpis!: OverviewOperationsKpisDto;
@ApiProperty({ type: [OverviewStatusCountDto] })
trainStatusBreakdown!: OverviewStatusCountDto[];
@ApiProperty({ type: [OverviewStatusCountDto] })
wagonStatusBreakdown!: OverviewStatusCountDto[];
@ApiProperty({ type: [OverviewStatusCountDto] })
containerStatusBreakdown!: OverviewStatusCountDto[];
@ApiProperty({ type: [OverviewStatusCountDto] })
cargoStatusBreakdown!: OverviewStatusCountDto[];
@ApiProperty()
generatedAt!: string;
}
export class OverviewCustomersTabDto {
@ApiProperty({ type: OverviewCustomerKpisDto })
kpis!: OverviewCustomerKpisDto;
@ApiProperty({ type: [OverviewTrendPointDto] })
customerGrowthTrend!: OverviewTrendPointDto[];
@ApiProperty({ type: [OverviewLabelCountDto] })
customersByType!: OverviewLabelCountDto[];
@ApiProperty({ type: [OverviewLabelCountDto] })
topCustomersByBookings!: OverviewLabelCountDto[];
@ApiProperty()
generatedAt!: string;
}
export class OverviewStaffTabDto {
@ApiProperty({ type: OverviewStaffKpisDto })
kpis!: OverviewStaffKpisDto;
@ApiProperty({ type: [OverviewStatusCountDto] })
usersByStatus!: OverviewStatusCountDto[];
@ApiProperty({ type: [OverviewTrendPointDto] })
employeeGrowthTrend!: OverviewTrendPointDto[];
@ApiProperty({ type: [OverviewLabelCountDto] })
activeUsersBreakdown!: OverviewLabelCountDto[];
@ApiProperty()
generatedAt!: string;
}

View File

@@ -0,0 +1,26 @@
export const OVERVIEW_URGENT_PRIORITY_THRESHOLD = 1000;
export const OVERVIEW_NEEDS_ACTION_STATUSES = [
'SUBMITTED',
'PENDING_APPROVAL',
'APPROVED_PENDING_SIGNATURE',
] as const;
export const OVERVIEW_IN_APPROVAL_STATUSES = [
'PENDING_APPROVAL',
'APPROVED_PENDING_SIGNATURE',
] as const;
export const OVERVIEW_CLOSED_STATUSES = [
'REJECTED',
'CANCELLED',
'COMPLETED',
] as const;
export const OVERVIEW_RANGE_DAYS = {
'7d': 7,
'30d': 30,
'90d': 90,
} as const;
export type OverviewRange = keyof typeof OVERVIEW_RANGE_DAYS;

View File

@@ -0,0 +1,74 @@
import { Controller, Get, Query } from '@nestjs/common';
import {
ApiBearerAuth,
ApiOkResponse,
ApiOperation,
ApiTags,
} from '@nestjs/swagger';
import { BookingView } from '../../common/booking-guards';
import { OverviewQueryDto } from './dto/overview-query.dto';
import { OverviewResponseDto } from './dto/overview-response.dto';
import {
OverviewBillingTabDto,
OverviewBookingsTabDto,
OverviewCustomersTabDto,
OverviewOperationsTabDto,
OverviewStaffTabDto,
} from './dto/overview-tab-response.dto';
import { OverviewService } from './overview.service';
@ApiTags('Overview')
@ApiBearerAuth()
@Controller('overview')
export class OverviewController {
constructor(private readonly overviewService: OverviewService) {}
@Get()
@BookingView()
@ApiOperation({ summary: 'Aggregated dashboard summary for backoffice overview' })
@ApiOkResponse({ type: OverviewResponseDto })
getDashboard(@Query() query: OverviewQueryDto): Promise<OverviewResponseDto> {
return this.overviewService.getDashboard(query.range ?? '30d');
}
@Get('bookings')
@BookingView()
@ApiOperation({ summary: 'Bookings tab metrics and charts' })
@ApiOkResponse({ type: OverviewBookingsTabDto })
getBookingsTab(@Query() query: OverviewQueryDto): Promise<OverviewBookingsTabDto> {
return this.overviewService.getBookingsTab(query.range ?? '30d');
}
@Get('billing')
@BookingView()
@ApiOperation({ summary: 'Billing tab metrics and charts' })
@ApiOkResponse({ type: OverviewBillingTabDto })
getBillingTab(@Query() query: OverviewQueryDto): Promise<OverviewBillingTabDto> {
return this.overviewService.getBillingTab(query.range ?? '30d');
}
@Get('operations')
@BookingView()
@ApiOperation({ summary: 'Operations tab metrics and charts' })
@ApiOkResponse({ type: OverviewOperationsTabDto })
getOperationsTab(): Promise<OverviewOperationsTabDto> {
return this.overviewService.getOperationsTab();
}
@Get('customers')
@BookingView()
@ApiOperation({ summary: 'Customers tab metrics and charts' })
@ApiOkResponse({ type: OverviewCustomersTabDto })
getCustomersTab(@Query() query: OverviewQueryDto): Promise<OverviewCustomersTabDto> {
return this.overviewService.getCustomersTab(query.range ?? '30d');
}
@Get('staff')
@BookingView()
@ApiOperation({ summary: 'Staff tab metrics and charts' })
@ApiOkResponse({ type: OverviewStaffTabDto })
getStaffTab(@Query() query: OverviewQueryDto): Promise<OverviewStaffTabDto> {
return this.overviewService.getStaffTab(query.range ?? '30d');
}
}

View File

@@ -0,0 +1,34 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Employee } from '@tria-plc/iamapi-common';
import { User } from '@tria-plc/iamapi-common/entities/iam/user/user.entity';
import { Booking } from '../bookings/entities/booking.entity';
import { Cargo } from '../cargoes/entities/cargoes.entity';
import { Container } from '../container-management/entities/container.entity';
import { Customer } from '../customers/entities/customer.entity';
import { PaymentEntity } from '../payment/entities/payment.entity';
import { Train } from '../trains/entities/train.entity';
import { Wagon } from '../wagons/entities/wagon.entity';
import { OverviewController } from './overview.controller';
import { OverviewRepository } from './overview.repository';
import { OverviewService } from './overview.service';
@Module({
imports: [
TypeOrmModule.forFeature([
Booking,
PaymentEntity,
Customer,
Train,
Wagon,
Container,
Cargo,
Employee,
User,
]),
],
controllers: [OverviewController],
providers: [OverviewService, OverviewRepository],
})
export class OverviewModule {}

View File

@@ -0,0 +1,553 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { EUserStatus } from '@tria-plc/api-common/utils/enums/user.enum';
import { Employee } from '@tria-plc/iamapi-common';
import { User } from '@tria-plc/iamapi-common/entities/iam/user/user.entity';
import { Freight } from '@edr/types';
import { Repository, ObjectLiteral } from 'typeorm';
import { Booking } from '../bookings/entities/booking.entity';
import { Cargo } from '../cargoes/entities/cargoes.entity';
import { Container } from '../container-management/entities/container.entity';
import { Customer } from '../customers/entities/customer.entity';
import { PaymentEntity } from '../payment/entities/payment.entity';
import { Train } from '../trains/entities/train.entity';
import { Wagon } from '../wagons/entities/wagon.entity';
import {
OVERVIEW_CLOSED_STATUSES,
OVERVIEW_IN_APPROVAL_STATUSES,
OVERVIEW_NEEDS_ACTION_STATUSES,
OVERVIEW_URGENT_PRIORITY_THRESHOLD,
} from './overview.constants';
export type OverviewBookingKpisRow = {
totalActive: number;
needsAction: number;
urgent: number;
inApproval: number;
submittedToday: number;
};
export type OverviewRecentBookingRow = {
id: string;
reference: string;
customerLabel: string;
status: string;
priorityScore: number;
totalAmount: number | null;
paymentCurrency: string | null;
createdAt: Date;
};
@Injectable()
export class OverviewRepository {
constructor(
@InjectRepository(Booking)
private readonly bookingRepository: Repository<Booking>,
@InjectRepository(PaymentEntity)
private readonly paymentRepository: Repository<PaymentEntity>,
@InjectRepository(Customer)
private readonly customerRepository: Repository<Customer>,
@InjectRepository(Train)
private readonly trainRepository: Repository<Train>,
@InjectRepository(Wagon)
private readonly wagonRepository: Repository<Wagon>,
@InjectRepository(Container)
private readonly containerRepository: Repository<Container>,
@InjectRepository(Cargo)
private readonly cargoRepository: Repository<Cargo>,
@InjectRepository(Employee)
private readonly employeeRepository: Repository<Employee>,
@InjectRepository(User)
private readonly userRepository: Repository<User>,
) {}
async getBookingKpis(): Promise<OverviewBookingKpisRow> {
const row = await this.bookingRepository
.createQueryBuilder('booking')
.select(
`COUNT(*) FILTER (WHERE booking.status NOT IN (:...closedStatuses) AND booking.status != 'DRAFT')::int`,
'totalActive',
)
.addSelect(
`COUNT(*) FILTER (WHERE booking.status IN (:...needsActionStatuses))::int`,
'needsAction',
)
.addSelect(
`COUNT(*) FILTER (WHERE booking.priority_score >= :urgentThreshold)::int`,
'urgent',
)
.addSelect(
`COUNT(*) FILTER (WHERE booking.status IN (:...inApprovalStatuses))::int`,
'inApproval',
)
.addSelect(
`COUNT(*) FILTER (WHERE booking.created_at >= CURRENT_DATE AND booking.status != 'DRAFT')::int`,
'submittedToday',
)
.where('booking.deleted_at IS NULL')
.setParameters({
closedStatuses: [...OVERVIEW_CLOSED_STATUSES],
needsActionStatuses: [...OVERVIEW_NEEDS_ACTION_STATUSES],
inApprovalStatuses: [...OVERVIEW_IN_APPROVAL_STATUSES],
urgentThreshold: OVERVIEW_URGENT_PRIORITY_THRESHOLD,
})
.getRawOne<Record<string, string>>();
return {
totalActive: Number(row?.totalActive ?? 0),
needsAction: Number(row?.needsAction ?? 0),
urgent: Number(row?.urgent ?? 0),
inApproval: Number(row?.inApproval ?? 0),
submittedToday: Number(row?.submittedToday ?? 0),
};
}
async getOperationsKpis(): Promise<{
trainsActive: number;
wagonsAvailable: number;
containersInTransit: number;
cargoesLoaded: number;
}> {
const [trainsActive, wagonsAvailable, containersInTransit, cargoesLoaded] =
await Promise.all([
this.trainRepository
.createQueryBuilder('train')
.where('train.deleted_at IS NULL')
.andWhere('train.status IN (:...statuses)', {
statuses: [
Freight.TrainStatus.InService,
Freight.TrainStatus.Scheduled,
],
})
.getCount(),
this.wagonRepository
.createQueryBuilder('wagon')
.where('wagon.deleted_at IS NULL')
.andWhere('wagon.status = :status', { status: 'AVAILABLE' })
.getCount(),
this.containerRepository
.createQueryBuilder('container')
.where('container.deleted_at IS NULL')
.andWhere('container.status = :status', { status: 'IN_TRANSIT' })
.getCount(),
this.cargoRepository
.createQueryBuilder('cargo')
.where('cargo.deleted_at IS NULL')
.andWhere('cargo.status IN (:...statuses)', {
statuses: ['LOADED', 'IN_TRANSIT'],
})
.getCount(),
]);
return { trainsActive, wagonsAvailable, containersInTransit, cargoesLoaded };
}
async getCustomerKpis(): Promise<{
totalCustomers: number;
newCustomersThisMonth: number;
}> {
const row = await this.customerRepository
.createQueryBuilder('customer')
.select('COUNT(*)::int', 'totalCustomers')
.addSelect(
`COUNT(*) FILTER (WHERE customer.created_at >= date_trunc('month', CURRENT_DATE))::int`,
'newCustomersThisMonth',
)
.where('customer.deleted_at IS NULL')
.getRawOne<Record<string, string>>();
return {
totalCustomers: Number(row?.totalCustomers ?? 0),
newCustomersThisMonth: Number(row?.newCustomersThisMonth ?? 0),
};
}
async getBillingKpis(): Promise<{
revenueMtdEtb: number;
revenueMtdUsd: number;
pendingPayments: number;
successfulPaymentsMtd: number;
}> {
const revenueRow = await this.paymentRepository
.createQueryBuilder('payment')
.select(
`COALESCE(SUM(payment.amount) FILTER (WHERE payment.currency = 'ETB'), 0)`,
'revenueMtdEtb',
)
.addSelect(
`COALESCE(SUM(payment.amount) FILTER (WHERE payment.currency = 'USD'), 0)`,
'revenueMtdUsd',
)
.addSelect(`COUNT(*)::int`, 'successfulPaymentsMtd')
.where('payment.status = :status', { status: 'success' })
.andWhere(
`COALESCE(payment.paid_at, payment.created_at) >= date_trunc('month', CURRENT_DATE)`,
)
.getRawOne<Record<string, string>>();
const pendingPayments = await this.paymentRepository
.createQueryBuilder('payment')
.where('payment.status IN (:...statuses)', {
statuses: ['action-required', 'processing'],
})
.getCount();
return {
revenueMtdEtb: Number(revenueRow?.revenueMtdEtb ?? 0),
revenueMtdUsd: Number(revenueRow?.revenueMtdUsd ?? 0),
pendingPayments,
successfulPaymentsMtd: Number(revenueRow?.successfulPaymentsMtd ?? 0),
};
}
async getStaffKpis(): Promise<{ activeEmployees: number; activeUsers: number }> {
const [activeEmployees, activeUsers] = await Promise.all([
this.employeeRepository.count({
where: { isCurrent: true },
}),
this.userRepository.count({
where: {
isActive: true,
status: EUserStatus.ACCEPTED,
},
}),
]);
return { activeEmployees, activeUsers };
}
async getBookingTrend(days: number): Promise<{ date: string; count: number }[]> {
const rows = await this.bookingRepository
.createQueryBuilder('booking')
.select(`to_char(booking.created_at::date, 'YYYY-MM-DD')`, 'date')
.addSelect('COUNT(*)::int', 'count')
.where('booking.deleted_at IS NULL')
.andWhere(`booking.created_at >= CURRENT_DATE - :days::int + 1`, { days })
.groupBy('booking.created_at::date')
.orderBy('booking.created_at::date', 'ASC')
.getRawMany<{ date: string; count: string }>();
return rows.map((row) => ({
date: row.date,
count: Number(row.count),
}));
}
async getStatusCounts(): Promise<Record<string, number>> {
const rows = await this.bookingRepository
.createQueryBuilder('booking')
.select('booking.status', 'status')
.addSelect('COUNT(*)::int', 'count')
.where('booking.deleted_at IS NULL')
.groupBy('booking.status')
.getRawMany<{ status: string; count: string }>();
return Object.fromEntries(
rows.map((row) => [row.status, Number(row.count)]),
);
}
async getPaymentTrend(
days: number,
): Promise<{ date: string; amountEtb: number; amountUsd: number }[]> {
const rows = await this.paymentRepository
.createQueryBuilder('payment')
.select(
`to_char(COALESCE(payment.paid_at, payment.created_at)::date, 'YYYY-MM-DD')`,
'date',
)
.addSelect(
`COALESCE(SUM(payment.amount) FILTER (WHERE payment.currency = 'ETB'), 0)`,
'amountEtb',
)
.addSelect(
`COALESCE(SUM(payment.amount) FILTER (WHERE payment.currency = 'USD'), 0)`,
'amountUsd',
)
.where('payment.status = :status', { status: 'success' })
.andWhere(
`COALESCE(payment.paid_at, payment.created_at) >= CURRENT_DATE - :days::int + 1`,
{ days },
)
.groupBy(`COALESCE(payment.paid_at, payment.created_at)::date`)
.orderBy(`COALESCE(payment.paid_at, payment.created_at)::date`, 'ASC')
.getRawMany<{ date: string; amountEtb: string; amountUsd: string }>();
return rows.map((row) => ({
date: row.date,
amountEtb: Number(row.amountEtb),
amountUsd: Number(row.amountUsd),
}));
}
async getRecentBookings(limit: number): Promise<OverviewRecentBookingRow[]> {
const rows = await this.bookingRepository
.createQueryBuilder('booking')
.leftJoin('booking.company', 'company')
.select('booking.id', 'id')
.addSelect('booking.reference', 'reference')
.addSelect('COALESCE(company.name, \'—\')', 'customerLabel')
.addSelect('booking.status', 'status')
.addSelect('booking.priority_score', 'priorityScore')
.addSelect('booking.total_amount', 'totalAmount')
.addSelect('booking.payment_currency', 'paymentCurrency')
.addSelect('booking.created_at', 'createdAt')
.where('booking.deleted_at IS NULL')
.orderBy('booking.created_at', 'DESC')
.limit(limit)
.getRawMany<{
id: string;
reference: string;
customerLabel: string;
status: string;
priorityScore: string;
totalAmount: string | null;
paymentCurrency: string | null;
createdAt: Date;
}>();
return rows.map((row) => ({
id: row.id,
reference: row.reference,
customerLabel: row.customerLabel,
status: row.status,
priorityScore: Number(row.priorityScore),
totalAmount: row.totalAmount != null ? Number(row.totalAmount) : null,
paymentCurrency: row.paymentCurrency,
createdAt: row.createdAt,
}));
}
async getBookingsByFreightType(): Promise<{ label: string; count: number }[]> {
const rows = await this.bookingRepository
.createQueryBuilder('booking')
.select('booking.freight_type', 'label')
.addSelect('COUNT(*)::int', 'count')
.where('booking.deleted_at IS NULL')
.andWhere("booking.status != 'DRAFT'")
.groupBy('booking.freight_type')
.orderBy('count', 'DESC')
.getRawMany<{ label: string; count: string }>();
return rows.map((row) => ({
label: row.label,
count: Number(row.count),
}));
}
async getBookingsByCurrency(): Promise<{ label: string; count: number }[]> {
const rows = await this.bookingRepository
.createQueryBuilder('booking')
.select('booking.payment_currency', 'label')
.addSelect('COUNT(*)::int', 'count')
.where('booking.deleted_at IS NULL')
.andWhere("booking.status != 'DRAFT'")
.groupBy('booking.payment_currency')
.orderBy('count', 'DESC')
.getRawMany<{ label: string; count: string }>();
return rows.map((row) => ({
label: row.label,
count: Number(row.count),
}));
}
async getPaymentsByStatus(): Promise<{ status: string; count: number }[]> {
const rows = await this.paymentRepository
.createQueryBuilder('payment')
.select('payment.status', 'status')
.addSelect('COUNT(*)::int', 'count')
.groupBy('payment.status')
.orderBy('count', 'DESC')
.getRawMany<{ status: string; count: string }>();
return rows.map((row) => ({
status: row.status,
count: Number(row.count),
}));
}
async getPaymentsByMethod(): Promise<
{ method: string; count: number; amountEtb: number; amountUsd: number }[]
> {
const rows = await this.paymentRepository
.createQueryBuilder('payment')
.select('payment.method', 'method')
.addSelect('COUNT(*)::int', 'count')
.addSelect(
`COALESCE(SUM(payment.amount) FILTER (WHERE payment.currency = 'ETB' AND payment.status = 'success'), 0)`,
'amountEtb',
)
.addSelect(
`COALESCE(SUM(payment.amount) FILTER (WHERE payment.currency = 'USD' AND payment.status = 'success'), 0)`,
'amountUsd',
)
.groupBy('payment.method')
.orderBy('count', 'DESC')
.getRawMany<{ method: string; count: string; amountEtb: string; amountUsd: string }>();
return rows.map((row) => ({
method: row.method,
count: Number(row.count),
amountEtb: Number(row.amountEtb),
amountUsd: Number(row.amountUsd),
}));
}
async getRevenueByCurrency(): Promise<{ currency: string; amount: number }[]> {
const rows = await this.paymentRepository
.createQueryBuilder('payment')
.select('payment.currency', 'currency')
.addSelect('COALESCE(SUM(payment.amount), 0)', 'amount')
.where('payment.status = :status', { status: 'success' })
.andWhere(
`COALESCE(payment.paid_at, payment.created_at) >= date_trunc('month', CURRENT_DATE)`,
)
.groupBy('payment.currency')
.getRawMany<{ currency: string; amount: string }>();
return rows.map((row) => ({
currency: row.currency,
amount: Number(row.amount),
}));
}
async getTrainStatusBreakdown(): Promise<{ status: string; count: number }[]> {
return this.statusBreakdown(this.trainRepository, 'train');
}
async getWagonStatusBreakdown(): Promise<{ status: string; count: number }[]> {
return this.statusBreakdown(this.wagonRepository, 'wagon');
}
async getContainerStatusBreakdown(): Promise<{ status: string; count: number }[]> {
return this.statusBreakdown(this.containerRepository, 'container');
}
async getCargoStatusBreakdown(): Promise<{ status: string; count: number }[]> {
return this.statusBreakdown(this.cargoRepository, 'cargo');
}
private async statusBreakdown(
repository: Repository<ObjectLiteral>,
alias: string,
): Promise<{ status: string; count: number }[]> {
const rows = await repository
.createQueryBuilder(alias)
.select(`${alias}.status`, 'status')
.addSelect('COUNT(*)::int', 'count')
.where(`${alias}.deleted_at IS NULL`)
.groupBy(`${alias}.status`)
.orderBy('count', 'DESC')
.getRawMany<{ status: string; count: string }>();
return rows.map((row) => ({
status: row.status,
count: Number(row.count),
}));
}
async getCustomerGrowthTrend(days: number): Promise<{ date: string; count: number }[]> {
const rows = await this.customerRepository
.createQueryBuilder('customer')
.select(`to_char(customer.created_at::date, 'YYYY-MM-DD')`, 'date')
.addSelect('COUNT(*)::int', 'count')
.where('customer.deleted_at IS NULL')
.andWhere(`customer.created_at >= CURRENT_DATE - :days::int + 1`, { days })
.groupBy('customer.created_at::date')
.orderBy('customer.created_at::date', 'ASC')
.getRawMany<{ date: string; count: string }>();
return rows.map((row) => ({
date: row.date,
count: Number(row.count),
}));
}
async getCustomersByType(): Promise<{ label: string; count: number }[]> {
const rows = await this.customerRepository
.createQueryBuilder('customer')
.select(`COALESCE(NULLIF(customer.customer_type, ''), 'Unknown')`, 'label')
.addSelect('COUNT(*)::int', 'count')
.where('customer.deleted_at IS NULL')
.groupBy('customer.customer_type')
.orderBy('count', 'DESC')
.getRawMany<{ label: string; count: string }>();
return rows.map((row) => ({
label: row.label,
count: Number(row.count),
}));
}
async getTopCustomersByBookings(limit: number): Promise<{ label: string; count: number }[]> {
const rows = await this.bookingRepository
.createQueryBuilder('booking')
.leftJoin('booking.company', 'company')
.select(`COALESCE(company.name, 'Unknown')`, 'label')
.addSelect('COUNT(*)::int', 'count')
.where('booking.deleted_at IS NULL')
.andWhere("booking.status != 'DRAFT'")
.groupBy('company.name')
.orderBy('count', 'DESC')
.limit(limit)
.getRawMany<{ label: string; count: string }>();
return rows.map((row) => ({
label: row.label,
count: Number(row.count),
}));
}
async getUsersByStatus(): Promise<{ status: string; count: number }[]> {
const rows = await this.userRepository
.createQueryBuilder('user')
.select('user.status', 'status')
.addSelect('COUNT(*)::int', 'count')
.groupBy('user.status')
.orderBy('count', 'DESC')
.getRawMany<{ status: string; count: string }>();
return rows.map((row) => ({
status: row.status,
count: Number(row.count),
}));
}
async getEmployeeGrowthTrend(days: number): Promise<{ date: string; count: number }[]> {
const rows = await this.employeeRepository
.createQueryBuilder('employee')
.select(`to_char(employee.created_at::date, 'YYYY-MM-DD')`, 'date')
.addSelect('COUNT(*)::int', 'count')
.where('employee.is_current = true')
.andWhere(`employee.created_at >= CURRENT_DATE - :days::int + 1`, { days })
.groupBy('employee.created_at::date')
.orderBy('employee.created_at::date', 'ASC')
.getRawMany<{ date: string; count: string }>();
return rows.map((row) => ({
date: row.date,
count: Number(row.count),
}));
}
async getActiveUsersBreakdown(): Promise<{ label: string; count: number }[]> {
const [active, inactive] = await Promise.all([
this.userRepository.count({
where: { isActive: true, status: EUserStatus.ACCEPTED },
}),
this.userRepository
.createQueryBuilder('user')
.where('user.is_active = false OR user.status != :status', {
status: EUserStatus.ACCEPTED,
})
.getCount(),
]);
return [
{ label: 'Active', count: active },
{ label: 'Inactive', count: inactive },
];
}
}

View File

@@ -0,0 +1,210 @@
import { Injectable } from '@nestjs/common';
import {
BOOKING_LIST_TABS,
mapStatusCountsToTabs,
} from '../bookings/booking-list-tabs.config';
import type { OverviewRangeQuery } from './dto/overview-query.dto';
import type { OverviewResponseDto } from './dto/overview-response.dto';
import type {
OverviewBillingTabDto,
OverviewBookingsTabDto,
OverviewCustomersTabDto,
OverviewOperationsTabDto,
OverviewStaffTabDto,
} from './dto/overview-tab-response.dto';
import { OVERVIEW_RANGE_DAYS } from './overview.constants';
import { OverviewRepository } from './overview.repository';
@Injectable()
export class OverviewService {
constructor(private readonly overviewRepository: OverviewRepository) {}
private mapStatusCounts(statusCounts: Record<string, number>) {
const pipelineTabs = mapStatusCountsToTabs(statusCounts);
const bookingsByPipeline = BOOKING_LIST_TABS.filter(
(tab) => tab.key !== 'all',
).map((tab) => ({
stage: tab.key,
count: pipelineTabs[tab.key],
}));
const bookingsByStatus = Object.entries(statusCounts)
.map(([status, count]) => ({ status, count }))
.sort((a, b) => b.count - a.count);
return { bookingsByPipeline, bookingsByStatus };
}
async getDashboard(range: OverviewRangeQuery = '30d'): Promise<OverviewResponseDto> {
const days = OVERVIEW_RANGE_DAYS[range];
const [
bookingKpis,
operationsKpis,
customerKpis,
billingKpis,
staffKpis,
bookingTrend,
statusCounts,
paymentTrend,
recentBookings,
] = await Promise.all([
this.overviewRepository.getBookingKpis(),
this.overviewRepository.getOperationsKpis(),
this.overviewRepository.getCustomerKpis(),
this.overviewRepository.getBillingKpis(),
this.overviewRepository.getStaffKpis(),
this.overviewRepository.getBookingTrend(days),
this.overviewRepository.getStatusCounts(),
this.overviewRepository.getPaymentTrend(days),
this.overviewRepository.getRecentBookings(8),
]);
const { bookingsByPipeline, bookingsByStatus } =
this.mapStatusCounts(statusCounts);
return {
kpis: {
bookings: bookingKpis,
operations: operationsKpis,
customers: customerKpis,
billing: billingKpis,
staff: staffKpis,
},
bookingTrend,
bookingsByStatus,
bookingsByPipeline,
paymentTrend,
recentBookings: recentBookings.map((row) => ({
...row,
createdAt: row.createdAt.toISOString(),
})),
generatedAt: new Date().toISOString(),
};
}
async getBookingsTab(range: OverviewRangeQuery = '30d'): Promise<OverviewBookingsTabDto> {
const days = OVERVIEW_RANGE_DAYS[range];
const [
kpis,
bookingTrend,
statusCounts,
bookingsByFreightType,
bookingsByCurrency,
recentBookings,
] = await Promise.all([
this.overviewRepository.getBookingKpis(),
this.overviewRepository.getBookingTrend(days),
this.overviewRepository.getStatusCounts(),
this.overviewRepository.getBookingsByFreightType(),
this.overviewRepository.getBookingsByCurrency(),
this.overviewRepository.getRecentBookings(8),
]);
const { bookingsByPipeline, bookingsByStatus } =
this.mapStatusCounts(statusCounts);
return {
kpis,
bookingTrend,
bookingsByStatus,
bookingsByPipeline,
bookingsByFreightType,
bookingsByCurrency,
recentBookings: recentBookings.map((row) => ({
...row,
createdAt: row.createdAt.toISOString(),
})),
generatedAt: new Date().toISOString(),
};
}
async getBillingTab(range: OverviewRangeQuery = '30d'): Promise<OverviewBillingTabDto> {
const days = OVERVIEW_RANGE_DAYS[range];
const [kpis, paymentTrend, paymentsByStatus, paymentsByMethod, revenueByCurrency] =
await Promise.all([
this.overviewRepository.getBillingKpis(),
this.overviewRepository.getPaymentTrend(days),
this.overviewRepository.getPaymentsByStatus(),
this.overviewRepository.getPaymentsByMethod(),
this.overviewRepository.getRevenueByCurrency(),
]);
return {
kpis,
paymentTrend,
paymentsByStatus,
paymentsByMethod,
revenueByCurrency,
generatedAt: new Date().toISOString(),
};
}
async getOperationsTab(): Promise<OverviewOperationsTabDto> {
const [
kpis,
trainStatusBreakdown,
wagonStatusBreakdown,
containerStatusBreakdown,
cargoStatusBreakdown,
] = await Promise.all([
this.overviewRepository.getOperationsKpis(),
this.overviewRepository.getTrainStatusBreakdown(),
this.overviewRepository.getWagonStatusBreakdown(),
this.overviewRepository.getContainerStatusBreakdown(),
this.overviewRepository.getCargoStatusBreakdown(),
]);
return {
kpis,
trainStatusBreakdown,
wagonStatusBreakdown,
containerStatusBreakdown,
cargoStatusBreakdown,
generatedAt: new Date().toISOString(),
};
}
async getCustomersTab(range: OverviewRangeQuery = '30d'): Promise<OverviewCustomersTabDto> {
const days = OVERVIEW_RANGE_DAYS[range];
const [kpis, customerGrowthTrend, customersByType, topCustomersByBookings] =
await Promise.all([
this.overviewRepository.getCustomerKpis(),
this.overviewRepository.getCustomerGrowthTrend(days),
this.overviewRepository.getCustomersByType(),
this.overviewRepository.getTopCustomersByBookings(8),
]);
return {
kpis,
customerGrowthTrend,
customersByType,
topCustomersByBookings,
generatedAt: new Date().toISOString(),
};
}
async getStaffTab(range: OverviewRangeQuery = '30d'): Promise<OverviewStaffTabDto> {
const days = OVERVIEW_RANGE_DAYS[range];
const [kpis, usersByStatus, employeeGrowthTrend, activeUsersBreakdown] =
await Promise.all([
this.overviewRepository.getStaffKpis(),
this.overviewRepository.getUsersByStatus(),
this.overviewRepository.getEmployeeGrowthTrend(days),
this.overviewRepository.getActiveUsersBreakdown(),
]);
return {
kpis,
usersByStatus,
employeeGrowthTrend,
activeUsersBreakdown,
generatedAt: new Date().toISOString(),
};
}
}

View File

@@ -5,6 +5,8 @@ import {
import { RuleEngineManage, RuleEngineView } from '../../../common/rule-engine-guards';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { CreateApprovalRuleDto } from '../dto/create-approval-rule.dto';
import { MoveOrderDto } from '../dto/move-order.dto';
import { ReorderItemsDto } from '../dto/reorder-items.dto';
import { UpdateApprovalRuleDto } from '../dto/update-approval-rule.dto';
import { ApprovalRulesService } from '../services/approval-rules.service';
@@ -35,6 +37,22 @@ export class ApprovalRulesController {
return this.service.findChain(flag === 'true');
}
@Post('reorder')
@RuleEngineManage('approval-rules')
@HttpCode(HttpStatus.NO_CONTENT)
@ApiOperation({ summary: 'Bulk reorder approval steps within a chain' })
reorder(@Body() dto: ReorderItemsDto) {
return this.service.reorder(dto);
}
@Post(':id/move-order')
@RuleEngineManage('approval-rules')
@HttpCode(HttpStatus.NO_CONTENT)
@ApiOperation({ summary: 'Move an approval step up or down within its chain' })
moveOrder(@Param('id', ParseUUIDPipe) id: string, @Body() dto: MoveOrderDto) {
return this.service.moveOrder(id, dto.direction);
}
@Get(':id')
@RuleEngineView('approval-rules')
@ApiOperation({ summary: 'Get an approval rule by ID' })

View File

@@ -5,6 +5,8 @@ import {
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { RuleEngineManage, RuleEngineView } from '../../../common/rule-engine-guards';
import { CreateCargoTypeDto } from '../dto/create-cargo-type.dto';
import { MoveOrderDto } from '../dto/move-order.dto';
import { ReorderItemsDto } from '../dto/reorder-items.dto';
import { UpdateCargoTypeDto } from '../dto/update-cargo-type.dto';
import { CargoTypesService } from '../services/cargo-types.service';
@@ -32,6 +34,22 @@ export class CargoTypesController {
});
}
@Post('reorder')
@RuleEngineManage('cargo-types')
@HttpCode(HttpStatus.NO_CONTENT)
@ApiOperation({ summary: 'Bulk reorder cargo types by ID list' })
reorder(@Body() dto: ReorderItemsDto) {
return this.service.reorder(dto);
}
@Post(':id/move-order')
@RuleEngineManage('cargo-types')
@HttpCode(HttpStatus.NO_CONTENT)
@ApiOperation({ summary: 'Move a cargo type up or down in display order' })
moveOrder(@Param('id', ParseUUIDPipe) id: string, @Body() dto: MoveOrderDto) {
return this.service.moveOrder(id, dto.direction);
}
@Get(':id')
@RuleEngineView('cargo-types')
@ApiOperation({ summary: 'Get a cargo type by ID' })

View File

@@ -5,6 +5,8 @@ import {
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { RuleEngineManage, RuleEngineView } from '../../../common/rule-engine-guards';
import { CreateContainerTypeDto } from '../dto/create-container-type.dto';
import { MoveOrderDto } from '../dto/move-order.dto';
import { ReorderItemsDto } from '../dto/reorder-items.dto';
import { UpdateContainerTypeDto } from '../dto/update-container-type.dto';
import { ContainerTypesService } from '../services/container-types.service';
@@ -25,6 +27,22 @@ export class ContainerTypesController {
});
}
@Post('reorder')
@RuleEngineManage('container-types')
@HttpCode(HttpStatus.NO_CONTENT)
@ApiOperation({ summary: 'Bulk reorder container types by ID list' })
reorder(@Body() dto: ReorderItemsDto) {
return this.service.reorder(dto);
}
@Post(':id/move-order')
@RuleEngineManage('container-types')
@HttpCode(HttpStatus.NO_CONTENT)
@ApiOperation({ summary: 'Move a container type up or down in display order' })
moveOrder(@Param('id', ParseUUIDPipe) id: string, @Body() dto: MoveOrderDto) {
return this.service.moveOrder(id, dto.direction);
}
@Get(':id')
@RuleEngineView('container-types')
@ApiOperation({ summary: 'Get a container type by ID' })

View File

@@ -5,6 +5,8 @@ import {
import { RuleEngineManage, RuleEngineView } from '../../../common/rule-engine-guards';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { CreateServiceTypeDto } from '../dto/create-service-type.dto';
import { MoveOrderDto } from '../dto/move-order.dto';
import { ReorderItemsDto } from '../dto/reorder-items.dto';
import { UpdateServiceTypeDto } from '../dto/update-service-type.dto';
import { ServiceTypesService } from '../services/service-types.service';
@@ -29,6 +31,22 @@ export class ServiceTypesController {
});
}
@Post('reorder')
@RuleEngineManage('service-types')
@HttpCode(HttpStatus.NO_CONTENT)
@ApiOperation({ summary: 'Bulk reorder service types by ID list' })
reorder(@Body() dto: ReorderItemsDto) {
return this.service.reorder(dto);
}
@Post(':id/move-order')
@RuleEngineManage('service-types')
@HttpCode(HttpStatus.NO_CONTENT)
@ApiOperation({ summary: 'Move a service type up or down in display order' })
moveOrder(@Param('id', ParseUUIDPipe) id: string, @Body() dto: MoveOrderDto) {
return this.service.moveOrder(id, dto.direction);
}
@Get(':id')
@RuleEngineView('service-types')
@ApiOperation({ summary: 'Get a service type by ID' })

View File

@@ -5,6 +5,8 @@ import {
import { RuleEngineManage, RuleEngineView } from '../../../common/rule-engine-guards';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { CreateYardDto } from '../dto/create-yard.dto';
import { MoveOrderDto } from '../dto/move-order.dto';
import { ReorderItemsDto } from '../dto/reorder-items.dto';
import { UpdateYardDto } from '../dto/update-yard.dto';
import { YardsService } from '../services/yards.service';
@@ -26,6 +28,22 @@ export class YardsController {
});
}
@Post('reorder')
@RuleEngineManage('yards')
@HttpCode(HttpStatus.NO_CONTENT)
@ApiOperation({ summary: 'Bulk reorder yards by ID list' })
reorder(@Body() dto: ReorderItemsDto) {
return this.service.reorder(dto);
}
@Post(':id/move-order')
@RuleEngineManage('yards')
@HttpCode(HttpStatus.NO_CONTENT)
@ApiOperation({ summary: 'Move a yard up or down in display order' })
moveOrder(@Param('id', ParseUUIDPipe) id: string, @Body() dto: MoveOrderDto) {
return this.service.moveOrder(id, dto.direction);
}
@Get(':id')
@RuleEngineView('yards')
@ApiOperation({ summary: 'Get a yard by ID' })

View File

@@ -1,5 +1,5 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsBoolean, IsInt, IsOptional, IsString, MaxLength, Min } from 'class-validator';
import { IsBoolean, IsInt, IsOptional, IsString, IsUUID, MaxLength, Min } from 'class-validator';
const ROLES = ['LINE_STAFF', 'DIRECTOR', 'CEO'] as const;
@@ -8,10 +8,16 @@ export class CreateApprovalRuleDto {
@IsBoolean()
requiresDirectorApproval!: boolean;
@ApiProperty({ description: 'Step sequence number (1 = first, 2 = second)', minimum: 1 })
@ApiPropertyOptional({ description: 'Step sequence number (auto-assigned if omitted)', minimum: 1 })
@IsOptional()
@IsInt()
@Min(1)
stepOrder!: number;
stepOrder?: number;
@ApiPropertyOptional({ description: 'Insert after this step ID within the same chain' })
@IsOptional()
@IsUUID('4')
insertAfterId?: string;
@ApiProperty({ enum: ROLES, description: 'Role required to action this step' })
@IsString()

View File

@@ -32,4 +32,9 @@ export class CreateCargoTypeDto {
@IsInt()
@Min(1)
displayOrder?: number;
@ApiPropertyOptional({ description: 'Insert after this record ID' })
@IsOptional()
@IsUUID('4')
insertAfterId?: string;
}

View File

@@ -1,6 +1,6 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { Transform } from 'class-transformer';
import { IsBoolean, IsInt, IsNumber, IsOptional, IsString, Max, MaxLength, Min } from 'class-validator';
import { IsBoolean, IsInt, IsNumber, IsOptional, IsString, IsUUID, Max, MaxLength, Min } from 'class-validator';
export class CreateContainerTypeDto {
@ApiProperty({ description: 'Customer-facing label, e.g. "20ft Dry Container"', maxLength: 100 })
@@ -40,4 +40,9 @@ export class CreateContainerTypeDto {
@IsInt()
@Min(1)
displayOrder?: number;
@ApiPropertyOptional({ description: 'Insert after this record ID' })
@IsOptional()
@IsUUID('4')
insertAfterId?: string;
}

View File

@@ -1,5 +1,5 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsBoolean, IsInt, IsOptional, IsString, MaxLength, Min } from 'class-validator';
import { IsBoolean, IsInt, IsOptional, IsString, IsUUID, MaxLength, Min } from 'class-validator';
export class CreateServiceTypeDto {
@ApiProperty({ description: 'Service type display name', maxLength: 255 })
@@ -48,4 +48,9 @@ export class CreateServiceTypeDto {
@IsInt()
@Min(1)
displayOrder?: number;
@ApiPropertyOptional({ description: 'Insert after this record ID' })
@IsOptional()
@IsUUID('4')
insertAfterId?: string;
}

View File

@@ -1,5 +1,5 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsBoolean, IsInt, IsOptional, IsString, MaxLength, Min } from 'class-validator';
import { IsBoolean, IsInt, IsOptional, IsString, IsUUID, MaxLength, Min } from 'class-validator';
export class CreateYardDto {
@ApiProperty({ description: 'Customer-facing yard label', maxLength: 100 })
@@ -22,4 +22,9 @@ export class CreateYardDto {
@IsInt()
@Min(1)
displayOrder?: number;
@ApiPropertyOptional({ description: 'Insert after this record ID' })
@IsOptional()
@IsUUID('4')
insertAfterId?: string;
}

View File

@@ -0,0 +1,8 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsIn } from 'class-validator';
export class MoveOrderDto {
@ApiProperty({ enum: ['up', 'down'] })
@IsIn(['up', 'down'])
direction!: 'up' | 'down';
}

View File

@@ -0,0 +1,17 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { ArrayMinSize, IsArray, IsBoolean, IsOptional, IsUUID } from 'class-validator';
export class ReorderItemsDto {
@ApiProperty({ description: 'Ordered list of record IDs (new display/step order)', type: [String] })
@IsArray()
@ArrayMinSize(1)
@IsUUID('4', { each: true })
ids!: string[];
@ApiPropertyOptional({
description: 'Approval-rules only: scope reorder to this chain',
})
@IsOptional()
@IsBoolean()
requiresDirectorApproval?: boolean;
}

View File

@@ -46,6 +46,7 @@ import { WeightLimitRulesRepository } from './repositories/weight-limit-rules.re
import { YardsRepository } from './repositories/yards.repository';
import { ApprovalRulesService } from './services/approval-rules.service';
import { DisplayOrderService } from './services/display-order.service';
import { CargoTypesService } from './services/cargo-types.service';
import { ContainerTypesService } from './services/container-types.service';
import { PriorityRulesService } from './services/priority-rules.service';
@@ -126,6 +127,7 @@ import { BookingRateSnapshot } from '../bookings/entities/booking-rate-snapshot.
ShippingLinesService,
RatesService,
ApprovalRulesService,
DisplayOrderService,
RuleEngineService,
],
exports: [

View File

@@ -315,15 +315,27 @@ export class RuleEngineService {
}
/**
* Snapshot all LIVE rates into booking_rate_snapshot for a booking.
* Snapshot only the rates used in a booking's final price.
*/
async snapshotLiveRates(bookingId: string): Promise<BookingRateSnapshot[]> {
const liveRates = await this.ratesRepo.findLiveRates();
async snapshotRates(
bookingId: string,
rates: Array<{
id: string;
rateType: string;
rateValue: number;
rateUnit: string;
currency: string;
}>,
): Promise<BookingRateSnapshot[]> {
const snapshotRepo = this.dataSource.getRepository(BookingRateSnapshot);
const now = new Date();
const seen = new Set<string>();
const snapshots: BookingRateSnapshot[] = [];
for (const rate of liveRates) {
for (const rate of rates) {
if (seen.has(rate.id)) continue;
seen.add(rate.id);
const snapshot = snapshotRepo.create({
bookingId,
rateId: rate.id,

View File

@@ -1,17 +1,20 @@
import { Inject, Injectable, NotFoundException } from '@nestjs/common';
import { BadRequestException, Inject, Injectable, NotFoundException } from '@nestjs/common';
import { CreateApprovalRuleDto } from '../dto/create-approval-rule.dto';
import { ReorderItemsDto } from '../dto/reorder-items.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';
import { DisplayOrderService } from './display-order.service';
@Injectable()
export class ApprovalRulesService {
constructor(
@Inject(APPROVAL_RULES_REPOSITORY)
private readonly repository: IApprovalRulesRepository,
private readonly displayOrder: DisplayOrderService,
) {}
/** List approval rules. */
@@ -21,7 +24,7 @@ export class ApprovalRulesService {
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 pageSize = filter.pageSize ?? 10;
const where: Record<string, unknown> = {};
if (filter.requiresDirectorApproval !== undefined) {
where.requiresDirectorApproval = filter.requiresDirectorApproval;
@@ -50,9 +53,20 @@ export class ApprovalRulesService {
/** Create an approval rule step. */
async create(dto: CreateApprovalRuleDto): Promise<ApprovalRule> {
if (dto.stepOrder !== undefined && dto.insertAfterId) {
throw new BadRequestException('Cannot set both stepOrder and insertAfterId');
}
const scopeWhere = { requiresDirectorApproval: dto.requiresDirectorApproval };
const stepOrder = await this.displayOrder.resolveCreateOrder(ApprovalRule, 'stepOrder', {
explicitOrder: dto.stepOrder,
insertAfterId: dto.insertAfterId,
scopeWhere,
});
return this.repository.create({
requiresDirectorApproval: dto.requiresDirectorApproval,
stepOrder: dto.stepOrder,
stepOrder,
requiredRole: dto.requiredRole,
actionLabel: dto.actionLabel,
blocksRole: dto.blocksRole,
@@ -72,4 +86,20 @@ export class ApprovalRulesService {
await this.findById(id);
await this.repository.softDelete(id);
}
async reorder(dto: ReorderItemsDto): Promise<void> {
if (dto.requiresDirectorApproval === undefined) {
throw new BadRequestException('requiresDirectorApproval is required for approval rule reorder');
}
await this.displayOrder.reorderByIds(ApprovalRule, 'stepOrder', dto.ids, {
requiresDirectorApproval: dto.requiresDirectorApproval,
});
}
async moveOrder(id: string, direction: 'up' | 'down'): Promise<void> {
const rule = await this.findById(id);
await this.displayOrder.moveOne(ApprovalRule, 'stepOrder', id, direction, {
requiresDirectorApproval: rule.requiresDirectorApproval,
});
}
}

View File

@@ -2,18 +2,21 @@ import { ConflictException, Inject, Injectable, NotFoundException } from '@nestj
import { ILike } from 'typeorm';
import { generateCode } from '../../../common/utils/generate-code.util';
import { CreateCargoTypeDto } from '../dto/create-cargo-type.dto';
import { ReorderItemsDto } from '../dto/reorder-items.dto';
import { UpdateCargoTypeDto } from '../dto/update-cargo-type.dto';
import { CargoType } from '../entities/cargo-type.entity';
import {
CARGO_TYPES_REPOSITORY,
ICargoTypesRepository,
} from '../interfaces/cargo-types.repository.interface';
import { DisplayOrderService } from './display-order.service';
@Injectable()
export class CargoTypesService {
constructor(
@Inject(CARGO_TYPES_REPOSITORY)
private readonly repository: ICargoTypesRepository,
private readonly displayOrder: DisplayOrderService,
) {}
/** List cargo types with pagination and optional filtering. */
@@ -28,7 +31,7 @@ export class CargoTypesService {
sortOrder?: 'ASC' | 'DESC';
}): Promise<{ data: CargoType[]; meta: { total: number; page: number; pageSize: number; totalPages: number } }> {
const page = filter.page ?? 1;
const pageSize = filter.pageSize ?? 20;
const pageSize = filter.pageSize ?? 10;
const where: Record<string, unknown> = {};
if (filter.isActive !== undefined) where.isActive = filter.isActive;
if (filter.requiresDirectorApproval !== undefined) where.requiresDirectorApproval = filter.requiresDirectorApproval;
@@ -66,6 +69,12 @@ export class CargoTypesService {
const parent = await this.repository.findById(dto.parentGroupId);
if (!parent) throw new NotFoundException(`Parent cargo type ${dto.parentGroupId} not found`);
}
const displayOrder = await this.displayOrder.resolveCreateOrder(CargoType, 'displayOrder', {
explicitOrder: dto.displayOrder,
insertAfterId: dto.insertAfterId,
});
return this.repository.create({
code,
cargoTypeName: dto.cargoTypeName,
@@ -73,7 +82,7 @@ export class CargoTypesService {
showFreeTextBox: dto.showFreeTextBox ?? false,
requiresDirectorApproval: dto.requiresDirectorApproval ?? false,
isActive: dto.isActive ?? true,
displayOrder: dto.displayOrder ?? 1,
displayOrder,
});
}
@@ -95,4 +104,13 @@ export class CargoTypesService {
await this.findById(id);
await this.repository.softDelete(id);
}
async reorder(dto: ReorderItemsDto): Promise<void> {
await this.displayOrder.reorderByIds(CargoType, 'displayOrder', dto.ids);
}
async moveOrder(id: string, direction: 'up' | 'down'): Promise<void> {
await this.findById(id);
await this.displayOrder.moveOne(CargoType, 'displayOrder', id, direction);
}
}

View File

@@ -1,18 +1,21 @@
import { ConflictException, Inject, Injectable, NotFoundException } from '@nestjs/common';
import { generateCode } from '../../../common/utils/generate-code.util';
import { CreateContainerTypeDto } from '../dto/create-container-type.dto';
import { ReorderItemsDto } from '../dto/reorder-items.dto';
import { UpdateContainerTypeDto } from '../dto/update-container-type.dto';
import { ContainerType } from '../entities/container-type.entity';
import {
CONTAINER_TYPES_REPOSITORY,
IContainerTypesRepository,
} from '../interfaces/container-types.repository.interface';
import { DisplayOrderService } from './display-order.service';
@Injectable()
export class ContainerTypesService {
constructor(
@Inject(CONTAINER_TYPES_REPOSITORY)
private readonly repository: IContainerTypesRepository,
private readonly displayOrder: DisplayOrderService,
) {}
/** List container types with pagination. */
@@ -22,7 +25,7 @@ export class ContainerTypesService {
pageSize?: number;
}): Promise<{ data: ContainerType[]; meta: { total: number; page: number; pageSize: number; totalPages: number } }> {
const page = filter.page ?? 1;
const pageSize = filter.pageSize ?? 20;
const pageSize = filter.pageSize ?? 10;
const where: Record<string, unknown> = {};
if (filter.isActive !== undefined) where.isActive = filter.isActive;
@@ -47,6 +50,12 @@ export class ContainerTypesService {
const code = generateCode(dto.label);
const existing = await this.repository.findByCode(code);
if (existing) throw new ConflictException(`Container type with label "${dto.label}" conflicts with existing code "${code}"`);
const displayOrder = await this.displayOrder.resolveCreateOrder(ContainerType, 'displayOrder', {
explicitOrder: dto.displayOrder,
insertAfterId: dto.insertAfterId,
});
return this.repository.create({
code,
label: dto.label,
@@ -55,7 +64,7 @@ export class ContainerTypesService {
isReefer: dto.isReefer ?? false,
isOpenTop: dto.isOpenTop ?? false,
isActive: dto.isActive ?? true,
displayOrder: dto.displayOrder ?? 1,
displayOrder,
});
}
@@ -72,4 +81,13 @@ export class ContainerTypesService {
await this.findById(id);
await this.repository.softDelete(id);
}
async reorder(dto: ReorderItemsDto): Promise<void> {
await this.displayOrder.reorderByIds(ContainerType, 'displayOrder', dto.ids);
}
async moveOrder(id: string, direction: 'up' | 'down'): Promise<void> {
await this.findById(id);
await this.displayOrder.moveOne(ContainerType, 'displayOrder', id, direction);
}
}

View File

@@ -0,0 +1,175 @@
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import { DataSource, EntityTarget, FindOptionsWhere, ObjectLiteral } from 'typeorm';
export type OrderField = 'displayOrder' | 'stepOrder';
@Injectable()
export class DisplayOrderService {
constructor(private readonly dataSource: DataSource) {}
async getMaxOrder<T extends ObjectLiteral>(
entity: EntityTarget<T>,
field: OrderField,
where?: FindOptionsWhere<T>,
): Promise<number> {
const repo = this.dataSource.getRepository(entity);
const qb = repo.createQueryBuilder('e').select(`MAX(e.${field})`, 'max');
if (where) {
Object.entries(where).forEach(([key, value]) => {
if (value !== undefined) {
qb.andWhere(`e.${key} = :${key}`, { [key]: value });
}
});
}
const row = await qb.getRawOne<{ max: string | null }>();
return row?.max ? Number(row.max) : 0;
}
async resolveCreateOrder<T extends ObjectLiteral>(
entity: EntityTarget<T>,
field: OrderField,
options: {
explicitOrder?: number;
insertAfterId?: string;
scopeWhere?: FindOptionsWhere<T>;
},
): Promise<number> {
const { explicitOrder, insertAfterId, scopeWhere } = options;
if (insertAfterId) {
if (explicitOrder !== undefined) {
throw new BadRequestException('Cannot set both explicit order and insertAfterId');
}
const repo = this.dataSource.getRepository(entity);
const after = await repo.findOne({
where: { id: insertAfterId, ...scopeWhere } as unknown as FindOptionsWhere<T>,
});
if (!after) {
throw new NotFoundException(`Record ${insertAfterId} not found in scope`);
}
const afterOrder = Number((after as Record<string, unknown>)[field]);
await this.shiftOrdersFrom(entity, field, afterOrder + 1, 1, scopeWhere);
return afterOrder + 1;
}
if (explicitOrder !== undefined) {
return explicitOrder;
}
const max = await this.getMaxOrder(entity, field, scopeWhere);
return max + 1;
}
async reorderByIds<T extends ObjectLiteral>(
entity: EntityTarget<T>,
field: OrderField,
ids: string[],
scopeWhere?: FindOptionsWhere<T>,
): Promise<void> {
const repo = this.dataSource.getRepository(entity);
const existing = await repo.find({
where: scopeWhere,
order: { [field]: 'ASC' } as never,
});
const scopedIds = new Set(existing.map((row) => String(row.id)));
if (ids.length !== scopedIds.size) {
throw new BadRequestException('Reorder list must include every item in scope exactly once');
}
for (const id of ids) {
if (!scopedIds.has(id)) {
throw new BadRequestException(`ID ${id} is not in the reorder scope`);
}
}
const queryRunner = this.dataSource.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
try {
for (let i = 0; i < ids.length; i++) {
await queryRunner.manager.update(entity, ids[i], { [field]: -(i + 1) } as never);
}
for (let i = 0; i < ids.length; i++) {
await queryRunner.manager.update(entity, ids[i], { [field]: i + 1 } as never);
}
await queryRunner.commitTransaction();
} catch (err) {
await queryRunner.rollbackTransaction();
throw err;
} finally {
await queryRunner.release();
}
}
async moveOne<T extends ObjectLiteral>(
entity: EntityTarget<T>,
field: OrderField,
id: string,
direction: 'up' | 'down',
scopeWhere?: FindOptionsWhere<T>,
): Promise<void> {
const repo = this.dataSource.getRepository(entity);
const items = await repo.find({
where: scopeWhere,
order: { [field]: 'ASC' } as never,
});
const index = items.findIndex((row) => String(row.id) === id);
if (index === -1) {
throw new NotFoundException(`Record ${id} not found in scope`);
}
const targetIndex = direction === 'up' ? index - 1 : index + 1;
if (targetIndex < 0 || targetIndex >= items.length) {
throw new BadRequestException(`Cannot move ${direction}`);
}
const current = items[index] as Record<string, unknown>;
const neighbor = items[targetIndex] as Record<string, unknown>;
const currentOrder = Number(current[field]);
const neighborOrder = Number(neighbor[field]);
const queryRunner = this.dataSource.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
try {
await queryRunner.manager.update(entity, String(current.id), { [field]: -1 } as never);
await queryRunner.manager.update(entity, String(neighbor.id), { [field]: -2 } as never);
await queryRunner.manager.update(entity, String(current.id), { [field]: neighborOrder } as never);
await queryRunner.manager.update(entity, String(neighbor.id), { [field]: currentOrder } as never);
await queryRunner.commitTransaction();
} catch (err) {
await queryRunner.rollbackTransaction();
throw err;
} finally {
await queryRunner.release();
}
}
private async shiftOrdersFrom<T extends ObjectLiteral>(
entity: EntityTarget<T>,
field: OrderField,
fromOrder: number,
delta: number,
scopeWhere?: FindOptionsWhere<T>,
): Promise<void> {
const repo = this.dataSource.getRepository(entity);
const orderColumn = repo.metadata.findColumnWithPropertyName(field)?.databaseName ?? field;
const qb = repo
.createQueryBuilder()
.update()
.set({ [field]: () => `"${orderColumn}" + ${delta}` } as never)
.where(`"${orderColumn}" >= :fromOrder`, { fromOrder });
if (scopeWhere) {
Object.entries(scopeWhere).forEach(([key, value]) => {
if (value !== undefined) {
const col = repo.metadata.findColumnWithPropertyName(key)?.databaseName ?? key;
qb.andWhere(`"${col}" = :scope_${key}`, { [`scope_${key}`]: value });
}
});
}
await qb.execute();
}
}

View File

@@ -30,7 +30,7 @@ export class RatesService {
skip: (page - 1) * pageSize,
take: pageSize,
});
return { data, meta: { total, page, pageSize, totalPages: Math.ceil(total / pageSize) } };
return { data, meta: { total, page, pageSize, totalPages: Math.max(1, Math.ceil(total / pageSize)) } };
}
/** Return all currently LIVE rates. */

View File

@@ -2,18 +2,21 @@ import { ConflictException, Inject, Injectable, NotFoundException } from '@nestj
import { ILike } from 'typeorm';
import { generateCode } from '../../../common/utils/generate-code.util';
import { CreateServiceTypeDto } from '../dto/create-service-type.dto';
import { ReorderItemsDto } from '../dto/reorder-items.dto';
import { UpdateServiceTypeDto } from '../dto/update-service-type.dto';
import { ServiceType } from '../entities/service-type.entity';
import {
IServiceTypesRepository,
SERVICE_TYPES_REPOSITORY,
} from '../interfaces/service-types.repository.interface';
import { DisplayOrderService } from './display-order.service';
@Injectable()
export class ServiceTypesService {
constructor(
@Inject(SERVICE_TYPES_REPOSITORY)
private readonly repository: IServiceTypesRepository,
private readonly displayOrder: DisplayOrderService,
) {}
/** List service types with pagination and optional filtering. */
@@ -27,7 +30,7 @@ export class ServiceTypesService {
sortOrder?: 'ASC' | 'DESC';
}): Promise<{ data: ServiceType[]; meta: { total: number; page: number; pageSize: number; totalPages: number } }> {
const page = filter.page ?? 1;
const pageSize = filter.pageSize ?? 20;
const pageSize = filter.pageSize ?? 10;
const where: Record<string, unknown> = {};
if (filter.isActive !== undefined) where.isActive = filter.isActive;
if (filter.canBeBookedAlone !== undefined) where.canBeBookedAlone = filter.canBeBookedAlone;
@@ -59,6 +62,12 @@ export class ServiceTypesService {
const code = generateCode(dto.serviceName);
const existing = await this.repository.findByCode(code);
if (existing) throw new ConflictException(`Service type with name "${dto.serviceName}" conflicts with existing code "${code}"`);
const displayOrder = await this.displayOrder.resolveCreateOrder(ServiceType, 'displayOrder', {
explicitOrder: dto.displayOrder,
insertAfterId: dto.insertAfterId,
});
return this.repository.create({
code,
serviceName: dto.serviceName,
@@ -69,7 +78,7 @@ export class ServiceTypesService {
includesCustoms: dto.includesCustoms ?? false,
priorityBonusPoints: dto.priorityBonusPoints ?? 0,
isActive: dto.isActive ?? true,
displayOrder: dto.displayOrder ?? 1,
displayOrder,
});
}
@@ -87,4 +96,13 @@ export class ServiceTypesService {
await this.findById(id);
await this.repository.softDelete(id);
}
async reorder(dto: ReorderItemsDto): Promise<void> {
await this.displayOrder.reorderByIds(ServiceType, 'displayOrder', dto.ids);
}
async moveOrder(id: string, direction: 'up' | 'down'): Promise<void> {
await this.findById(id);
await this.displayOrder.moveOne(ServiceType, 'displayOrder', id, direction);
}
}

View File

@@ -1,15 +1,18 @@
import { ConflictException, Inject, Injectable, NotFoundException } from '@nestjs/common';
import { generateCode } from '../../../common/utils/generate-code.util';
import { CreateYardDto } from '../dto/create-yard.dto';
import { ReorderItemsDto } from '../dto/reorder-items.dto';
import { UpdateYardDto } from '../dto/update-yard.dto';
import { Yard } from '../entities/yard.entity';
import { IYardsRepository, YARDS_REPOSITORY } from '../interfaces/yards.repository.interface';
import { DisplayOrderService } from './display-order.service';
@Injectable()
export class YardsService {
constructor(
@Inject(YARDS_REPOSITORY)
private readonly repository: IYardsRepository,
private readonly displayOrder: DisplayOrderService,
) {}
/** List yards with pagination. */
@@ -20,7 +23,7 @@ export class YardsService {
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 pageSize = filter.pageSize ?? 10;
const where: Record<string, unknown> = {};
if (filter.isActive !== undefined) where.isActive = filter.isActive;
if (filter.country) where.country = filter.country;
@@ -46,12 +49,18 @@ export class YardsService {
const code = generateCode(dto.label);
const existing = await this.repository.findByCode(code);
if (existing) throw new ConflictException(`Yard with label "${dto.label}" conflicts with existing code "${code}"`);
const displayOrder = await this.displayOrder.resolveCreateOrder(Yard, 'displayOrder', {
explicitOrder: dto.displayOrder,
insertAfterId: dto.insertAfterId,
});
return this.repository.create({
code,
label: dto.label,
country: dto.country,
isActive: dto.isActive ?? true,
displayOrder: dto.displayOrder ?? 1,
displayOrder,
});
}
@@ -68,4 +77,13 @@ export class YardsService {
await this.findById(id);
await this.repository.softDelete(id);
}
async reorder(dto: ReorderItemsDto): Promise<void> {
await this.displayOrder.reorderByIds(Yard, 'displayOrder', dto.ids);
}
async moveOrder(id: string, direction: 'up' | 'down'): Promise<void> {
await this.findById(id);
await this.displayOrder.moveOne(Yard, 'displayOrder', id, direction);
}
}