Merge pull request #95 from Tria-plc/feature/trains-management

Feature/trains management
This commit is contained in:
Hagernesh Tadesse
2026-06-05 11:00:38 +03:00
committed by GitHub
83 changed files with 3309 additions and 65 deletions

View File

@@ -37,8 +37,7 @@
"puppeteer": "^24.2.0",
"pg": "^8.13.0",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1",
"typeorm": "^0.3.20"
"rxjs": "^7.8.1"
},
"devDependencies": {
"@edr/api-common": "workspace:*",
@@ -60,6 +59,7 @@
"ts-loader": "^9.5.1",
"ts-node": "^10.9.2",
"tsconfig-paths": "^4.2.0",
"typeorm": "^1.0.0",
"typescript": "^5.5.4"
},
"jest": {

View File

@@ -12,7 +12,8 @@ import databaseConfig from "./config/database.config";
import { BookingsModule } from "./modules/bookings/bookings.module";
import { FilesModule } from "./modules/files/files.module";
import { ConsignmentsModule } from "./modules/consignments/consignments.module";
import { TrainsModule } from "./modules/trains/trains.module";
//import { TrainsModule } from "./modules/trains/trains.module";
import { LocomotivesModule } from "./modules/locomotives/locomotives.module";
import { WagonTypesModule } from "./modules/wagon-types/wagon-types.module";
import { TrainSetsModule } from "./modules/train-sets/train-sets.module";
@@ -38,6 +39,11 @@ import { DemoUsersSeeder } from "./seed/demo-users.seeder";
import { DemoBookingsSeeder } from "./seed/demo-bookings.seeder";
import { PricingDataSeeder } from "./seed/pricing-data.seeder";
import { FileUploadSettingsSeeder } from "./seed/file-upload-settings.seeder";
//New Trains, Wagons, Container and Cargo management modules
import { TrainsModule } from "./modules/trains/trains.module";
import { WagonsModule } from './modules/wagons/wagons.module';
import { ContainersModule } from './modules/container-management/containers.module';
import { CargoesModule } from './modules/cargoes/cargoes.module';
@Module({
imports: [
@@ -83,6 +89,11 @@ import { FileUploadSettingsSeeder } from "./seed/file-upload-settings.seeder";
RuleEngineModule,
BackofficeModule,
DemoPermissionsModule,
//New Modules
TrainsModule,
WagonsModule,
ContainersModule,
CargoesModule,
],
providers: [EdrOrgSeeder, DemoUsersSeeder, DemoBookingsSeeder, PricingDataSeeder, FileUploadSettingsSeeder],
})

View File

@@ -0,0 +1,20 @@
// apps/edr-freight-api/src/data-source.ts
import { DataSource } from 'typeorm';
//import { ensurePostgresSchemas } from './utils/ensure-postgres-schemas'; // adjust path if needed
export const AppDataSource = new DataSource({
type: 'postgres',
host: 'localhost',
port: 5432,
username: 'postgres',
password: '', // Laragon default: empty
database: 'edr_freight',
schema: 'freight', // default schema for entities without an explicit schema
entities: [__dirname + '/**/*.entity{.ts,.js}'],
migrations: [__dirname + '/migrations/*{.ts,.js}'],
synchronize: false,
logging: true,
});
// Optional: call ensurePostgresSchemas before initializing
// But you can also run it separately.

View File

@@ -43,10 +43,10 @@ export class MoveCustomersToFreightSchema1748900000000 implements MigrationInter
CREATE INDEX IF NOT EXISTS "IDX_freight_customers_email"
ON freight.customers (email);
`);
await queryRunner.query(`
CREATE INDEX IF NOT EXISTS "IDX_freight_customers_user_id"
ON freight.customers (user_id);
`);
// await queryRunner.query(`
// CREATE INDEX IF NOT EXISTS "IDX_freight_customers_user_id"
// ON freight.customers (user_id);
//`);
// Copy rows from public.customers when that legacy table exists
await queryRunner.query(`

View File

@@ -0,0 +1,70 @@
import {
Body,
Controller,
Delete,
Get,
Param,
ParseUUIDPipe,
Patch,
Post,
} from '@nestjs/common';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { CreateCargoDto } from './dto/create-cargo.dto';
import { UpdateCargoDto } from './dto/update-cargo.dto';
import { LoadCargoDto } from './dto/load-cargo.dto';
import { DeliverCargoDto } from './dto/deliver-cargo.dto';
import { CargoesService } from './cargoes.service';
@ApiTags('cargoes')
@Controller('cargoes')
export class CargoesController {
constructor(private readonly cargoesService: CargoesService) {}
@Post()
@ApiOperation({ summary: 'Create a new cargo' })
create(@Body() dto: CreateCargoDto) {
return this.cargoesService.create(dto);
}
@Get()
@ApiOperation({ summary: 'List all cargoes' })
findAll() {
return this.cargoesService.findAll();
}
@Get(':id')
@ApiOperation({ summary: 'Get a cargo by ID' })
findOne(@Param('id', ParseUUIDPipe) id: string) {
return this.cargoesService.findById(id);
}
@Patch(':id')
@ApiOperation({ summary: 'Update a cargo' })
update(@Param('id', ParseUUIDPipe) id: string, @Body() dto: UpdateCargoDto) {
return this.cargoesService.update(id, dto);
}
@Delete(':id')
@ApiOperation({ summary: 'Delete a cargo' })
remove(@Param('id', ParseUUIDPipe) id: string) {
return this.cargoesService.remove(id);
}
@Post(':id/load')
@ApiOperation({ summary: 'Load cargo into a container' })
load(@Param('id', ParseUUIDPipe) id: string, @Body() dto: LoadCargoDto) {
return this.cargoesService.loadCargo(id, dto);
}
@Post(':id/unload')
@ApiOperation({ summary: 'Unload cargo from container' })
unload(@Param('id', ParseUUIDPipe) id: string) {
return this.cargoesService.unloadCargo(id);
}
@Post(':id/deliver')
@ApiOperation({ summary: 'Mark cargo as delivered' })
deliver(@Param('id', ParseUUIDPipe) id: string, @Body() dto?: DeliverCargoDto) {
return this.cargoesService.deliverCargo(id, dto);
}
}

View File

@@ -0,0 +1,14 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Cargo } from './entities/cargoes.entity';
import { Container } from '../container-management/entities/container.entity';
import { CargoesController } from './cargoes.controller';
import { CargoesService } from './cargoes.service';
@Module({
imports: [TypeOrmModule.forFeature([Cargo, Container])],
controllers: [CargoesController],
providers: [CargoesService],
exports: [CargoesService],
})
export class CargoesModule {}

View File

@@ -0,0 +1,15 @@
import { BaseRepository } from '@edr/api-common';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Cargo } from './entities/cargoes.entity';
@Injectable()
export class CargoesRepository extends BaseRepository<Cargo> {
constructor(
@InjectRepository(Cargo)
repository: Repository<Cargo>,
) {
super(repository);
}
}

View File

@@ -0,0 +1,104 @@
import { Injectable, NotFoundException, ConflictException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { CreateCargoDto } from './dto/create-cargo.dto';
import { UpdateCargoDto } from './dto/update-cargo.dto';
import { LoadCargoDto } from './dto/load-cargo.dto';
import { DeliverCargoDto } from './dto/deliver-cargo.dto';
import { Cargo } from './entities/cargoes.entity';
import { Container } from '../container-management/entities/container.entity';
@Injectable()
export class CargoesService {
constructor(
@InjectRepository(Cargo)
private readonly cargoRepo: Repository<Cargo>,
@InjectRepository(Container)
private readonly containerRepo: Repository<Container>,
) {}
async create(dto: CreateCargoDto): Promise<Cargo> {
const cargo = this.cargoRepo.create(dto);
return this.cargoRepo.save(cargo);
}
async findAll(): Promise<Cargo[]> {
return this.cargoRepo.find({ order: { cargoReference: 'ASC' } });
}
async findById(id: string): Promise<Cargo> {
const cargo = await this.cargoRepo.findOne({ where: { id } });
if (!cargo) throw new NotFoundException(`Cargo ${id} not found`);
return cargo;
}
async update(id: string, dto: UpdateCargoDto): Promise<Cargo> {
const cargo = await this.findById(id);
Object.assign(cargo, dto);
return this.cargoRepo.save(cargo);
}
async remove(id: string): Promise<void> {
const cargo = await this.findById(id);
await this.cargoRepo.remove(cargo);
}
async loadCargo(id: string, dto: LoadCargoDto): Promise<Cargo> {
const cargo = await this.cargoRepo.findOne({
where: { id },
relations: { container: true }, // ✅ fixed
});
if (!cargo) throw new NotFoundException('Cargo not found');
if (cargo.status !== 'PENDING') {
throw new ConflictException('Cargo already loaded or delivered');
}
cargo.status = 'LOADED';
cargo.loadedAt = new Date();
cargo.quantity = dto.quantity;
cargo.weight = dto.weight;
cargo.volume = dto.volume ?? null;
if (dto.description) cargo.description = dto.description;
if (cargo.container) {
cargo.container.status = 'LOADED';
await this.containerRepo.save(cargo.container);
}
return this.cargoRepo.save(cargo);
}
async unloadCargo(id: string): Promise<Cargo> {
const cargo = await this.findById(id);
if (cargo.status !== 'LOADED') {
throw new ConflictException('Cargo is not loaded');
}
cargo.status = 'UNLOADED';
cargo.unloadedAt = new Date();
return this.cargoRepo.save(cargo);
}
async deliverCargo(id: string, dto?: DeliverCargoDto): Promise<Cargo> {
const cargo = await this.cargoRepo.findOne({
where: { id },
relations: { container: true }, // ✅ fixed
});
if (!cargo) throw new NotFoundException('Cargo not found');
if (cargo.status !== 'LOADED') {
throw new ConflictException('Only loaded cargo can be delivered');
}
cargo.status = 'DELIVERED';
if (dto?.deliveryRemarks) cargo.description = dto.deliveryRemarks;
const remaining = await this.cargoRepo.count({
where: { containerId: cargo.containerId, status: 'LOADED' },
});
if (remaining === 0 && cargo.container) {
cargo.container.status = 'AVAILABLE';
await this.containerRepo.save(cargo.container);
}
return this.cargoRepo.save(cargo);
}
}

View File

@@ -0,0 +1,45 @@
import { IsString, IsUUID, IsOptional, IsNumber, Min, IsIn, IsDateString } from 'class-validator';
export class CreateCargoDto {
@IsString()
cargoReference!: string;
@IsUUID()
shipmentId!: string;
@IsUUID()
containerId!: string;
@IsOptional()
@IsUUID()
cargoTypeId?: string;
@IsOptional()
@IsString()
description?: string;
@IsNumber()
@Min(0.001)
quantity!: number;
@IsNumber()
@Min(0)
weight!: number;
@IsOptional()
@IsNumber()
@Min(0)
volume?: number;
@IsOptional()
@IsIn(['PENDING', 'LOADED', 'IN_TRANSIT', 'DELIVERED', 'UNLOADED'])
status?: string;
@IsOptional()
@IsDateString()
loadedAt?: string;
@IsOptional()
@IsDateString()
unloadedAt?: string;
}

View File

@@ -0,0 +1,7 @@
import { IsOptional, IsString } from 'class-validator';
export class DeliverCargoDto {
@IsOptional()
@IsString()
deliveryRemarks?: string;
}

View File

@@ -0,0 +1,20 @@
import { IsNumber, Min, IsOptional, IsString } from 'class-validator';
export class LoadCargoDto {
@IsNumber()
@Min(0.001)
quantity!: number;
@IsNumber()
@Min(0)
weight!: number;
@IsOptional()
@IsNumber()
@Min(0)
volume?: number;
@IsOptional()
@IsString()
description?: string;
}

View File

@@ -0,0 +1,4 @@
import { PartialType } from '@nestjs/swagger';
import { CreateCargoDto } from './create-cargo.dto';
export class UpdateCargoDto extends PartialType(CreateCargoDto) {}

View File

@@ -0,0 +1,45 @@
// apps/edr-freight-api/src/modules/cargoes/entities/cargo.entity.ts
import { Entity, Column, ManyToOne, JoinColumn } from 'typeorm';
import { BaseEntity } from '@edr/api-common';
import { Container } from '../../container-management/entities/container.entity';
@Entity({ name: 'cargoes', schema: 'freight' })
export class Cargo extends BaseEntity {
@Column({ unique: true, name: 'cargo_reference' })
cargoReference!: string;
@Column({ name: 'shipment_id', type: 'uuid' })
shipmentId!: string;
@Column({ name: 'container_id', type: 'uuid' })
containerId!: string;
@Column({ name: 'cargo_type_id', type: 'uuid', nullable: true })
cargoTypeId!: string | null; // optional link to cargo_types table
@Column({ type: 'text', nullable: true })
description!: string | null;
@Column({ type: 'decimal', precision: 12, scale: 3 })
quantity!: number;
@Column({ type: 'decimal', precision: 10, scale: 2 })
weight!: number; // kg
@Column({ type: 'decimal', precision: 10, scale: 2, nullable: true })
volume!: number | null; // m³
@Column({ type: 'varchar', default: 'PENDING' })
status!: string; // PENDING, LOADED, IN_TRANSIT, DELIVERED, UNLOADED
@Column({ name: 'loaded_at', type: 'timestamp', nullable: true })
loadedAt!: Date | null;
@Column({ name: 'unloaded_at', type: 'timestamp', nullable: true })
unloadedAt!: Date | null;
// Relationship to Container
@ManyToOne(() => Container, (container) => container.cargoes, { onDelete: 'RESTRICT' })
@JoinColumn({ name: 'container_id' })
container!: Container;
}

View File

@@ -0,0 +1,63 @@
import {
Body,
Controller,
Delete,
Get,
Param,
ParseUUIDPipe,
Patch,
Post,
} from '@nestjs/common';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { CreateContainerDto } from './dto/create-container.dto';
import { UpdateContainerDto } from './dto/update-container.dto';
import { AssignContainerToWagonDto } from './dto/assign-container-to-wagon.dto';
import { ContainersService } from './containers.service';
@ApiTags('containers')
@Controller('containers')
export class ContainersController {
constructor(private readonly containersService: ContainersService) {}
@Post()
@ApiOperation({ summary: 'Create a new container' })
create(@Body() dto: CreateContainerDto) {
return this.containersService.create(dto);
}
@Get()
@ApiOperation({ summary: 'List all containers' })
findAll() {
return this.containersService.findAll();
}
@Get(':id')
@ApiOperation({ summary: 'Get a container by ID' })
findOne(@Param('id', ParseUUIDPipe) id: string) {
return this.containersService.findById(id);
}
@Patch(':id')
@ApiOperation({ summary: 'Update a container' })
update(@Param('id', ParseUUIDPipe) id: string, @Body() dto: UpdateContainerDto) {
return this.containersService.update(id, dto);
}
@Delete(':id')
@ApiOperation({ summary: 'Delete a container' })
remove(@Param('id', ParseUUIDPipe) id: string) {
return this.containersService.remove(id);
}
@Post(':id/assign-wagon')
@ApiOperation({ summary: 'Assign container to a wagon' })
assignToWagon(@Param('id', ParseUUIDPipe) id: string, @Body() dto: AssignContainerToWagonDto) {
return this.containersService.assignToWagon(id, dto);
}
@Post(':id/unassign-wagon')
@ApiOperation({ summary: 'Unassign container from wagon' })
unassignFromWagon(@Param('id', ParseUUIDPipe) id: string) {
return this.containersService.unassignFromWagon(id);
}
}

View File

@@ -0,0 +1,14 @@
// apps/edr-freight-api/src/modules/container-management/containers.module.ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Container } from './entities/container.entity';
import { Wagon } from '../wagons/entities/wagon.entity';
import { ContainersController } from './containers.controller';
import { ContainersService } from './containers.service';
@Module({
imports: [TypeOrmModule.forFeature([Container, Wagon])], // ✅ add Wagon
controllers: [ContainersController],
providers: [ContainersService],
})
export class ContainersModule {}

View File

@@ -0,0 +1,15 @@
import { BaseRepository } from '@edr/api-common';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Container } from './entities/container.entity';
@Injectable()
export class ContainersRepository extends BaseRepository<Container> {
constructor(
@InjectRepository(Container)
repository: Repository<Container>,
) {
super(repository);
}
}

View File

@@ -0,0 +1,86 @@
import { Injectable, NotFoundException, ConflictException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { CreateContainerDto } from './dto/create-container.dto';
import { UpdateContainerDto } from './dto/update-container.dto';
import { AssignContainerToWagonDto } from './dto/assign-container-to-wagon.dto';
import { Container } from './entities/container.entity';
//import { ContainersRepository } from './containers.repository';
import { WagonsRepository } from '../wagons/wagons.repository';
@Injectable()
export class ContainersService {
constructor(
@InjectRepository(Container)
private readonly containerRepo: Repository<Container>,
private readonly wagonsRepository: WagonsRepository,
) {}
async create(dto: CreateContainerDto): Promise<Container> {
const container = this.containerRepo.create(dto);
// Convert undefined to null for optional fields
if (dto.wagonId === undefined) container.wagonId = null;
if (dto.position === undefined) container.position = null;
return this.containerRepo.save(container);
}
async findAll(): Promise<Container[]> {
return this.containerRepo.find({ order: { containerNumber: 'ASC' } });
}
async findById(id: string): Promise<Container> {
const container = await this.containerRepo.findOne({ where: { id } });
if (!container) throw new NotFoundException(`Container ${id} not found`);
return container;
}
async update(id: string, dto: UpdateContainerDto): Promise<Container> {
const container = await this.findById(id);
Object.assign(container, dto);
// Convert undefined to null for nullable fields
if (dto.wagonId === undefined) container.wagonId = null;
if (dto.position === undefined) container.position = null;
return this.containerRepo.save(container);
}
async remove(id: string): Promise<void> {
const container = await this.findById(id);
await this.containerRepo.remove(container);
}
async assignToWagon(containerId: string, dto: AssignContainerToWagonDto): Promise<Container> {
const container = await this.findById(containerId);
if (container.status === 'LOADED') {
throw new ConflictException('Cannot reassign a loaded container');
}
const wagon = await this.wagonsRepository.findById(dto.wagonId);
if (!wagon) throw new NotFoundException('Wagon not found');
let position: number | null = dto.position ?? null; // convert undefined to null
if (position === null) {
const maxPos = await this.containerRepo
.createQueryBuilder('c')
.select('MAX(c.position)', 'max')
.where('c.wagonId = :wagonId', { wagonId: wagon.id })
.getRawOne();
position = (maxPos?.max ?? 0) + 1;
}
container.wagonId = wagon.id;
container.position = position; // now position is number | null, safe
container.status = 'AVAILABLE';
return this.containerRepo.save(container);
}
async unassignFromWagon(containerId: string): Promise<Container> {
const container = await this.findById(containerId);
if (container.status === 'LOADED') {
throw new ConflictException('Cannot unassign a loaded container');
}
container.wagonId = null;
container.position = null;
container.status = 'AVAILABLE';
return this.containerRepo.save(container);
}
}

View File

@@ -0,0 +1,85 @@
// apps/edr-freight-api/src/modules/container-management/containers.service.ts
import { Injectable, NotFoundException, ConflictException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { CreateContainerDto } from './dto/create-container.dto';
import { UpdateContainerDto } from './dto/update-container.dto';
import { AssignContainerToWagonDto } from './dto/assign-container-to-wagon.dto';
import { Container } from './entities/container.entity';
import { Wagon } from '../wagons/entities/wagon.entity';
@Injectable()
export class ContainersService {
constructor(
@InjectRepository(Container)
private readonly containerRepo: Repository<Container>,
@InjectRepository(Wagon)
private readonly wagonRepo: Repository<Wagon>, // ✅ use raw repository
) {}
async create(dto: CreateContainerDto): Promise<Container> {
const container = this.containerRepo.create(dto);
if (dto.wagonId === undefined) container.wagonId = null;
if (dto.position === undefined) container.position = null;
return this.containerRepo.save(container);
}
async findAll(): Promise<Container[]> {
return this.containerRepo.find({ order: { containerNumber: 'ASC' } });
}
async findById(id: string): Promise<Container> {
const container = await this.containerRepo.findOne({ where: { id } });
if (!container) throw new NotFoundException(`Container ${id} not found`);
return container;
}
async update(id: string, dto: UpdateContainerDto): Promise<Container> {
const container = await this.findById(id);
Object.assign(container, dto);
if (dto.wagonId === undefined) container.wagonId = null;
if (dto.position === undefined) container.position = null;
return this.containerRepo.save(container);
}
async remove(id: string): Promise<void> {
const container = await this.findById(id);
await this.containerRepo.remove(container);
}
async assignToWagon(containerId: string, dto: AssignContainerToWagonDto): Promise<Container> {
const container = await this.findById(containerId);
if (container.status === 'LOADED') {
throw new ConflictException('Cannot reassign a loaded container');
}
const wagon = await this.wagonRepo.findOne({ where: { id: dto.wagonId } });
if (!wagon) throw new NotFoundException(`Wagon ${dto.wagonId} not found`);
let position: number | null = dto.position ?? null;
if (position === null) {
const maxPos = await this.containerRepo
.createQueryBuilder('c')
.select('MAX(c.position)', 'max')
.where('c.wagonId = :wagonId', { wagonId: wagon.id })
.getRawOne();
position = (maxPos?.max ?? 0) + 1;
}
container.wagonId = wagon.id;
container.position = position;
container.status = 'AVAILABLE';
return this.containerRepo.save(container);
}
async unassignFromWagon(containerId: string): Promise<Container> {
const container = await this.findById(containerId);
if (container.status === 'LOADED') {
throw new ConflictException('Cannot unassign a loaded container');
}
container.wagonId = null;
container.position = null;
container.status = 'AVAILABLE';
return this.containerRepo.save(container);
}
}

View File

@@ -0,0 +1,11 @@
import { IsUUID, IsOptional, IsInt, Min } from 'class-validator';
export class AssignContainerToWagonDto {
@IsUUID()
wagonId!: string;
@IsOptional()
@IsInt()
@Min(1)
position?: number;
}

View File

@@ -0,0 +1,34 @@
import { IsString, IsUUID, IsOptional, IsInt, Min, IsNumber, IsIn } from 'class-validator';
export class CreateContainerDto {
@IsString()
containerNumber!: string;
@IsUUID()
containerTypeId!: string;
@IsOptional()
@IsUUID()
wagonId?: string;
@IsOptional()
@IsInt()
@Min(1)
position?: number;
@IsNumber()
@Min(0)
tareWeight!: number;
@IsNumber()
@Min(0)
maxGrossWeight!: number;
@IsOptional()
@IsString()
sealNumber?: string;
@IsOptional()
@IsIn(['AVAILABLE', 'LOADED', 'IN_TRANSIT', 'MAINTENANCE', 'DAMAGED'])
status?: string;
}

View File

@@ -0,0 +1,4 @@
import { PartialType } from '@nestjs/swagger';
import { CreateContainerDto } from './create-container.dto';
export class UpdateContainerDto extends PartialType(CreateContainerDto) {}

View File

@@ -0,0 +1,45 @@
// apps/edr-freight-api/src/modules/container-management/entities/container.entity.ts
import { Entity, Column, ManyToOne, OneToMany, JoinColumn } from 'typeorm';
import { BaseEntity } from '@edr/api-common';
import { Wagon } from '../../wagons/entities/wagon.entity';
import { Cargo } from '../../cargoes/entities/cargoes.entity';
@Entity({ name: 'containers', schema: 'freight' })
export class Container extends BaseEntity {
@Column({ unique: true, name: 'container_number' })
containerNumber!: string;
@Column({ name: 'container_type_id', type: 'uuid' })
containerTypeId!: string;
@Column({ name: 'wagon_id', type: 'uuid', nullable: true })
wagonId!: string | null;
@Column({ type: 'int', nullable: true })
position!: number | null; // position on the wagon (1..N)
@Column({ name: 'tare_weight', type: 'decimal', precision: 10, scale: 2 })
tareWeight!: number;
@Column({ name: 'max_gross_weight', type: 'decimal', precision: 10, scale: 2 })
maxGrossWeight!: number;
@Column({
name: 'seal_number',
type: 'varchar',
nullable: true,
})
sealNumber!: string | null;
@Column({ type: 'varchar', default: 'AVAILABLE' })
status!: string; // AVAILABLE, LOADED, IN_TRANSIT, MAINTENANCE, DAMAGED
// Relationship to Wagon
@ManyToOne(() => Wagon, (wagon) => wagon.containers, { onDelete: 'SET NULL' })
@JoinColumn({ name: 'wagon_id' })
wagon!: Wagon | null;
// Relationship to Cargo
@OneToMany(() => Cargo, (cargo) => cargo.container)
cargoes!: Cargo[];
}

View File

@@ -82,6 +82,17 @@ export class TrainSchedulingService {
async getEligibleContainerBookings(query: GetEligibleContainerBookingsDto) {
const bookingRepository = this.dataSource.getRepository(Booking);
const queryBuilder = bookingRepository
<<<<<<< HEAD
.createQueryBuilder('booking')
.leftJoinAndSelect('booking.company', 'company')
.leftJoinAndSelect('booking.originYard', 'originYard')
.leftJoinAndSelect('booking.destinationYard', 'destinationYard')
.leftJoinAndSelect('booking.bookingContainers', 'bookingContainer')
.leftJoinAndSelect('bookingContainer.containerType', 'containerType')
.leftJoin(TrainScheduleBooking, 'scheduleBooking', 'scheduleBooking.booking_id = booking.id')
.where('booking.freightType = :freightType', { freightType: 'CONTAINER' })
.andWhere('scheduleBooking.id IS NULL');
=======
.createQueryBuilder("booking")
.leftJoinAndSelect("booking.customer", "customer")
.leftJoinAndSelect("booking.originYard", "originYard")
@@ -95,6 +106,7 @@ export class TrainSchedulingService {
)
.where("booking.freightType = :freightType", { freightType: "CONTAINER" })
.andWhere("scheduleBooking.id IS NULL");
>>>>>>> bd6ad54eea229305a214d06081e0ffd27fe163b8
if (query.originStationId) {
queryBuilder.andWhere("booking.originYardId = :originStationId", {
@@ -132,6 +144,13 @@ export class TrainSchedulingService {
const items: EligibleBookingItem[] = bookings.map((booking) => ({
id: booking.id,
reference: booking.reference,
<<<<<<< HEAD
customer: booking.company?.name ?? booking.company?.email ?? 'Unknown customer',
containerType: booking.bookingContainers
?.map((container) => container.containerType?.label ?? container.containerType?.code ?? 'Container')
.join(', ') ?? 'Container',
quantity: booking.bookingContainers?.reduce((sum, container) => sum + Number(container.quantity ?? 0), 0) ?? 0,
=======
customer:
booking.company?.name ?? booking.company?.email ?? "Unknown customer",
containerType:
@@ -148,6 +167,7 @@ export class TrainSchedulingService {
(sum, container) => sum + Number(container.quantity ?? 0),
0,
) ?? 0,
>>>>>>> bd6ad54eea229305a214d06081e0ffd27fe163b8
weightTons: this.roundTons(booking.cargoTotalWeightVgm),
origin:
booking.originYard?.label ??
@@ -654,6 +674,17 @@ export class TrainSchedulingService {
}
async getContainerTrainScheduleById(id: string) {
<<<<<<< HEAD
const schedule = await this.dataSource.getRepository(TrainSchedule).findOne({
where: { id },
relations: {
trainSet: { locomotive: true, wagons: { wagonType: true, allocations: { booking: true } } },
originStation: true,
destinationStation: true,
scheduleBookings: { booking: { company: true, originYard: true, destinationYard: true } },
},
});
=======
const schedule = await this.dataSource
.getRepository(TrainSchedule)
.findOne({
@@ -670,6 +701,7 @@ export class TrainSchedulingService {
},
},
});
>>>>>>> bd6ad54eea229305a214d06081e0ffd27fe163b8
if (!schedule) {
throw new NotFoundException(`Train schedule ${id} not found`);

View File

@@ -1,5 +1,5 @@
import { Freight } from "@edr/types";
import { IsEnum, IsNumber, IsOptional, IsString, Min } from "class-validator";
import { IsString, IsNumber, IsOptional, IsUUID, IsDateString, Min, IsEnum } from 'class-validator';
import { Freight } from '@edr/types';
export class CreateTrainDto {
@IsString()
@@ -11,9 +11,45 @@ export class CreateTrainDto {
@IsOptional()
@IsEnum(Freight.TrainStatus)
status?: Freight.TrainStatus;
status?: Freight.TrainStatus; // ✅ uses enum, not string
@IsOptional()
@IsString()
notes?: string;
}
@IsOptional()
@IsString()
trainNumber?: string;
@IsOptional()
@IsString()
trainName?: string;
@IsOptional()
@IsUUID()
routeId?: string;
@IsOptional()
@IsUUID()
originStationId?: string;
@IsOptional()
@IsUUID()
destinationStationId?: string;
@IsOptional()
@IsDateString()
departureTime?: string;
@IsOptional()
@IsDateString()
arrivalTime?: string;
@IsOptional()
@IsString()
locomotiveNumber?: string;
@IsOptional()
@IsString()
remarks?: string;
}

View File

@@ -0,0 +1,4 @@
import { PartialType } from '@nestjs/swagger';
import { CreateTrainDto } from './create-train.dto';
export class UpdateTrainDto extends PartialType(CreateTrainDto) {}

View File

@@ -1,23 +1,58 @@
import { BaseEntity } from "@edr/api-common";
import { Freight } from "@edr/types";
import { Column, Entity } from "typeorm";
// apps/edr-freight-api/src/modules/trains/entities/train.entity.ts
import { BaseEntity } from '@edr/api-common';
import { Freight } from '@edr/types';
import { Column, Entity, OneToMany } from 'typeorm';
import { Wagon } from '../../wagons/entities/wagon.entity';
@Entity({ schema:"freight",name: "trains" })
@Entity({ schema: 'freight', name: 'trains' })
export class Train extends BaseEntity {
@Column({ name: "code", type: "varchar", length: 32, unique: true })
// --- existing fields (keep for backward compatibility) ---
@Column({ name: 'code', type: 'varchar', length: 32, unique: true })
code!: string;
@Column({ name: "capacity_tons", type: "numeric", precision: 10, scale: 2 })
@Column({ name: 'capacity_tons', type: 'numeric', precision: 10, scale: 2 })
capacityTons!: number;
@Column({
name: "status",
type: "enum",
name: 'status',
type: 'enum',
enum: Freight.TrainStatus,
default: Freight.TrainStatus.Available,
})
status!: Freight.TrainStatus;
@Column({ name: "notes", type: "text", nullable: true })
@Column({ name: 'notes', type: 'text', nullable: true })
notes?: string | null;
}
// --- new required fields ---
@Column({ name: 'train_number', type: 'varchar', length: 20, unique: true, nullable: true })
trainNumber?: string;
@Column({ name: 'train_name', type: 'varchar', length: 100, nullable: true })
trainName?: string;
@Column({ name: 'route_id', type: 'uuid', nullable: true })
routeId?: string;
@Column({ name: 'origin_station_id', type: 'uuid', nullable: true })
originStationId?: string;
@Column({ name: 'destination_station_id', type: 'uuid', nullable: true })
destinationStationId?: string;
@Column({ name: 'departure_time', type: 'timestamp', nullable: true })
departureTime?: Date;
@Column({ name: 'arrival_time', type: 'timestamp', nullable: true })
arrivalTime?: Date;
@Column({ name: 'locomotive_number', type: 'varchar', length: 50, nullable: true })
locomotiveNumber?: string;
@Column({ name: 'remarks', type: 'text', nullable: true })
remarks?: string;
// --- relationships ---
@OneToMany(() => Wagon, (wagon) => wagon.train)
wagons!: Wagon[]; // fixed typo: was 'wagens'
}

View File

@@ -1,15 +1,14 @@
import { Module } from "@nestjs/common";
import { TypeOrmModule } from "@nestjs/typeorm";
import { Train } from "./entities/train.entity";
import { TrainsController } from "./trains.controller";
import { TrainsRepository } from "./trains.repository";
import { TrainsService } from "./trains.service";
// apps/edr-freight-api/src/modules/trains/trains.module.ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Train } from './entities/train.entity';
import { TrainsController } from './trains.controller';
import { TrainsService } from './trains.service';
@Module({
imports: [TypeOrmModule.forFeature([Train])],
controllers: [TrainsController],
providers: [TrainsService, TrainsRepository],
exports: [TrainsService],
providers: [TrainsService],
exports: [TrainsService], // if other modules need it
})
export class TrainsModule {}
export class TrainsModule {}

View File

@@ -1,29 +1,41 @@
import { Injectable, NotFoundException } from "@nestjs/common";
import { CreateTrainDto } from "./dto/create-train.dto";
import { Train } from "./entities/train.entity";
import { TrainsRepository } from "./trains.repository";
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { CreateTrainDto } from './dto/create-train.dto';
import { UpdateTrainDto } from './dto/update-train.dto';
import { Train } from './entities/train.entity';
@Injectable()
export class TrainsService {
constructor(private readonly trainsRepository: TrainsRepository) {}
constructor(
@InjectRepository(Train)
private readonly trainRepo: Repository<Train>,
) {}
/** Register a new train in the fleet. */
create(dto: CreateTrainDto): Promise<Train> {
return this.trainsRepository.create(dto);
const train = this.trainRepo.create(dto);
return this.trainRepo.save(train);
}
/** List every active train. */
findAll(): Promise<Train[]> {
return this.trainsRepository.findAll({ order: { code: "ASC" } });
return this.trainRepo.find({ order: { code: 'ASC' } });
}
/** Get a single train by ID. */
async findById(id: string): Promise<Train> {
const train = await this.trainsRepository.findById(id);
if (!train) {
throw new NotFoundException(`Train ${id} not found`);
}
const train = await this.trainRepo.findOne({ where: { id } });
if (!train) throw new NotFoundException(`Train ${id} not found`);
return train;
}
}
async update(id: string, dto: UpdateTrainDto): Promise<Train> {
const train = await this.findById(id);
Object.assign(train, dto);
// Convert undefined to null for optional fields if needed
return this.trainRepo.save(train);
}
async remove(id: string): Promise<void> {
const train = await this.findById(id);
await this.trainRepo.remove(train);
}
}

View File

@@ -0,0 +1,11 @@
import { IsUUID, IsOptional, IsInt, Min } from 'class-validator';
export class AssignWagonToTrainDto {
@IsUUID()
trainId!: string;
@IsOptional()
@IsInt()
@Min(1)
sequenceNumber?: number;
}

View File

@@ -0,0 +1,34 @@
import { IsString, IsUUID, IsOptional, IsInt, Min, IsNumber, IsIn } from 'class-validator';
export class CreateWagonDto {
@IsString()
wagonNumber!: string;
@IsUUID()
wagonTypeId!: string;
@IsOptional()
@IsUUID()
trainId?: string;
@IsOptional()
@IsInt()
@Min(1)
sequenceNumber?: number;
@IsNumber()
@Min(0)
tareWeight!: number;
@IsNumber()
@Min(0)
maxPayloadWeight!: number;
@IsOptional()
@IsIn(['AVAILABLE', 'ASSIGNED', 'MAINTENANCE', 'RETIRED'])
status?: string;
@IsOptional()
@IsString()
notes?: string;
}

View File

@@ -0,0 +1,7 @@
import { IsArray, IsUUID } from 'class-validator';
export class ReorderWagonsDto {
@IsArray()
@IsUUID(4, { each: true })
wagonIds!: string[];
}

View File

@@ -0,0 +1,4 @@
import { PartialType } from '@nestjs/swagger';
import { CreateWagonDto } from './create-wagon.dto';
export class UpdateWagonDto extends PartialType(CreateWagonDto) {}

View File

@@ -0,0 +1,41 @@
// apps/edr-freight-api/src/modules/wagons/entities/wagon.entity.ts
import { Entity, Column, ManyToOne, OneToMany, JoinColumn } from 'typeorm';
import { BaseEntity } from '@edr/api-common';
import { Train } from '../../trains/entities/train.entity';
import { Container } from '../../container-management/entities/container.entity';
@Entity({ name: 'wagons', schema: 'freight' })
export class Wagon extends BaseEntity {
@Column({ unique: true, name: 'wagon_number' })
wagonNumber!: string;
@Column({ name: 'wagon_type_id', type: 'uuid' })
wagonTypeId!: string;
@Column({ name: 'train_id', type: 'uuid', nullable: true })
trainId!: string | null;
@Column({ name: 'sequence_number', type: 'int', nullable: true })
sequenceNumber!: number | null;
@Column({ name: 'tare_weight', type: 'decimal', precision: 10, scale: 2 })
tareWeight!: number;
@Column({ name: 'max_payload_weight', type: 'decimal', precision: 10, scale: 2 })
maxPayloadWeight!: number;
@Column({ type: 'varchar', default: 'AVAILABLE' })
status!: string; // AVAILABLE, ASSIGNED, MAINTENANCE, RETIRED
@Column({ type: 'text', nullable: true })
notes!: string | null;
// Relationship to Train
@ManyToOne(() => Train, (train) => train.wagons, { onDelete: 'SET NULL' })
@JoinColumn({ name: 'train_id' })
train!: Train | null;
// Relationship to Container
@OneToMany(() => Container, (container) => container.wagon)
containers!: Container[];
}

View File

@@ -0,0 +1,76 @@
import {
Body,
Controller,
Delete,
Get,
Param,
ParseUUIDPipe,
Patch,
Post,
} from '@nestjs/common';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { CreateWagonDto } from './dto/create-wagon.dto';
import { UpdateWagonDto } from './dto/update-wagon.dto';
import { AssignWagonToTrainDto } from './dto/assign-wagon-to-train.dto';
import { ReorderWagonsDto } from './dto/reorder-wagons.dto';
import { WagonsService } from './wagons.service';
@ApiTags('wagons')
@Controller('wagons')
export class WagonsController {
constructor(private readonly wagonsService: WagonsService) {}
@Post()
@ApiOperation({ summary: 'Create a new wagon' })
create(@Body() dto: CreateWagonDto) {
return this.wagonsService.create(dto);
}
@Get()
@ApiOperation({ summary: 'List all wagons' })
findAll() {
return this.wagonsService.findAll();
}
@Get(':id')
@ApiOperation({ summary: 'Get a wagon by ID' })
findOne(@Param('id', ParseUUIDPipe) id: string) {
return this.wagonsService.findById(id);
}
@Patch(':id')
@ApiOperation({ summary: 'Update a wagon' })
update(@Param('id', ParseUUIDPipe) id: string, @Body() dto: UpdateWagonDto) {
return this.wagonsService.update(id, dto);
}
@Delete(':id')
@ApiOperation({ summary: 'Delete a wagon' })
remove(@Param('id', ParseUUIDPipe) id: string) {
return this.wagonsService.remove(id);
}
@Post(':id/assign-train')
@ApiOperation({ summary: 'Assign wagon to a train' })
assignToTrain(@Param('id', ParseUUIDPipe) id: string, @Body() dto: AssignWagonToTrainDto) {
return this.wagonsService.assignToTrain(id, dto);
}
@Post(':id/unassign-train')
@ApiOperation({ summary: 'Unassign wagon from train' })
unassignFromTrain(@Param('id', ParseUUIDPipe) id: string) {
return this.wagonsService.unassignFromTrain(id);
}
}
// Separate controller for trainspecific reorder (registered in module)
@Controller('trains/:trainId/reorder-wagons')
export class TrainWagonsReorderController {
constructor(private readonly wagonsService: WagonsService) {}
@Post()
@ApiOperation({ summary: 'Reorder wagons of a train' })
reorder(@Param('trainId', ParseUUIDPipe) trainId: string, @Body() dto: ReorderWagonsDto) {
return this.wagonsService.reorderWagons(trainId, dto);
}
}

View File

@@ -0,0 +1,14 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Wagon } from './entities/wagon.entity';
import { Train } from '../trains/entities/train.entity';
import { WagonsController, TrainWagonsReorderController } from './wagons.controller';
import { WagonsService } from './wagons.service';
@Module({
imports: [TypeOrmModule.forFeature([Wagon, Train])],
controllers: [WagonsController, TrainWagonsReorderController],
providers: [WagonsService],
exports: [WagonsService],
})
export class WagonsModule {}

View File

@@ -0,0 +1,15 @@
import { BaseRepository } from '@edr/api-common';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Wagon } from './entities/wagon.entity';
@Injectable()
export class WagonsRepository extends BaseRepository<Wagon> {
constructor(
@InjectRepository(Wagon)
repository: Repository<Wagon>,
) {
super(repository);
}
}

View File

@@ -0,0 +1,101 @@
import { Injectable, NotFoundException, ConflictException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, DataSource } from 'typeorm';
import { CreateWagonDto } from './dto/create-wagon.dto';
import { UpdateWagonDto } from './dto/update-wagon.dto';
import { AssignWagonToTrainDto } from './dto/assign-wagon-to-train.dto';
import { ReorderWagonsDto } from './dto/reorder-wagons.dto';
import { Wagon } from './entities/wagon.entity';
import { Train } from '../trains/entities/train.entity';
@Injectable()
export class WagonsService {
constructor(
@InjectRepository(Wagon)
private readonly wagonRepo: Repository<Wagon>,
@InjectRepository(Train)
private readonly trainRepo: Repository<Train>,
private readonly dataSource: DataSource,
) {}
async create(dto: CreateWagonDto): Promise<Wagon> {
const wagon = this.wagonRepo.create(dto);
// Convert undefined to null for nullable fields
if (dto.trainId === undefined) wagon.trainId = null;
if (dto.sequenceNumber === undefined) wagon.sequenceNumber = null;
return this.wagonRepo.save(wagon);
}
async findAll(): Promise<Wagon[]> {
return this.wagonRepo.find({ order: { wagonNumber: 'ASC' } });
}
async findById(id: string): Promise<Wagon> {
const wagon = await this.wagonRepo.findOne({ where: { id } });
if (!wagon) throw new NotFoundException(`Wagon ${id} not found`);
return wagon;
}
async update(id: string, dto: UpdateWagonDto): Promise<Wagon> {
const wagon = await this.findById(id);
Object.assign(wagon, dto);
if (dto.trainId === undefined) wagon.trainId = null;
if (dto.sequenceNumber === undefined) wagon.sequenceNumber = null;
return this.wagonRepo.save(wagon);
}
async remove(id: string): Promise<void> {
const wagon = await this.findById(id);
await this.wagonRepo.remove(wagon);
}
async assignToTrain(wagonId: string, dto: AssignWagonToTrainDto): Promise<Wagon> {
const wagon = await this.findById(wagonId);
if (wagon.status === 'ASSIGNED') {
throw new ConflictException('Wagon already assigned to a train');
}
const train = await this.trainRepo.findOne({ where: { id: dto.trainId } });
if (!train) throw new NotFoundException('Train not found');
let sequence: number | null = dto.sequenceNumber ?? null;
if (sequence === null) {
const maxSeq = await this.wagonRepo
.createQueryBuilder('w')
.select('MAX(w.sequenceNumber)', 'max')
.where('w.trainId = :trainId', { trainId: train.id })
.getRawOne();
sequence = (maxSeq?.max ?? 0) + 1;
}
wagon.trainId = train.id;
wagon.sequenceNumber = sequence;
wagon.status = 'ASSIGNED';
return this.wagonRepo.save(wagon);
}
async unassignFromTrain(wagonId: string): Promise<Wagon> {
const wagon = await this.findById(wagonId);
wagon.trainId = null;
wagon.sequenceNumber = null;
wagon.status = 'AVAILABLE';
return this.wagonRepo.save(wagon);
}
async reorderWagons(_trainId: string, dto: ReorderWagonsDto): Promise<void> {
const queryRunner = this.dataSource.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
try {
for (let i = 0; i < dto.wagonIds.length; i++) {
await queryRunner.manager.update(Wagon, dto.wagonIds[i], { sequenceNumber: i + 1 });
}
await queryRunner.commitTransaction();
} catch (err) {
await queryRunner.rollbackTransaction();
throw err;
} finally {
await queryRunner.release();
}
}
}

View File

@@ -2,6 +2,16 @@ import { Injectable, Logger } from "@nestjs/common";
import { randomUUID } from "crypto";
import { DataSource } from "typeorm";
<<<<<<< HEAD
import { BookingContainer } from '../modules/bookings/entities/booking-container.entity';
import { Booking } from '../modules/bookings/entities/booking.entity';
import { Company } from '../modules/companies/entities/company.entity';
import { Locomotive } from '../modules/locomotives/entities/locomotive.entity';
import { ServiceType } from '../modules/rule-engine/entities/service-type.entity';
import { Yard } from '../modules/rule-engine/entities/yard.entity';
import { WagonType } from '../modules/wagon-types/entities/wagon-type.entity';
import { ContainerType } from '../modules/rule-engine/entities/container-type.entity';
=======
import { BookingContainer } from "../modules/bookings/entities/booking-container.entity";
import { Booking } from "../modules/bookings/entities/booking.entity";
import { Customer } from "../modules/customers/entities/customer.entity";
@@ -10,6 +20,7 @@ import { ServiceType } from "../modules/rule-engine/entities/service-type.entity
import { Yard } from "../modules/rule-engine/entities/yard.entity";
import { WagonType } from "../modules/wagon-types/entities/wagon-type.entity";
import { ContainerType } from "../modules/rule-engine/entities/container-type.entity";
>>>>>>> bd6ad54eea229305a214d06081e0ffd27fe163b8
const SEED_FLAG = "SEED_DEMO_BOOKINGS";
@@ -209,6 +220,11 @@ export class DemoBookingsSeeder {
{ conflictPaths: { email: true } },
);
<<<<<<< HEAD
const [serviceType, company, yards, containerTypes] = await Promise.all([
manager.getRepository(ServiceType).findOneByOrFail({ code: SERVICE_TYPE_CODE }),
manager.getRepository(Customer).findOneByOrFail({ email: CUSTOMER_EMAIL }),
=======
const [serviceType, customer, yards, containerTypes] = await Promise.all([
manager
.getRepository(ServiceType)
@@ -216,6 +232,7 @@ export class DemoBookingsSeeder {
manager
.getRepository(Customer)
.findOneByOrFail({ email: CUSTOMER_EMAIL }),
>>>>>>> bd6ad54eea229305a214d06081e0ffd27fe163b8
manager.getRepository(Yard).find(),
manager.getRepository(ContainerType).find(),
]);
@@ -247,8 +264,13 @@ export class DemoBookingsSeeder {
await manager.getRepository(Booking).upsert(
{
reference: demoBooking.reference,
<<<<<<< HEAD
companyId: company.id,
status: 'APPROVED',
=======
companyId: customer.id,
status: "APPROVED",
>>>>>>> bd6ad54eea229305a214d06081e0ffd27fe163b8
scheduledDate: new Date(demoBooking.scheduledDate),
totalAmount: 0,
paymentStatus: "PENDING",

View File

@@ -27,6 +27,7 @@
"react-hot-toast": "^2.6.0",
"react-router-dom": "^6.27.0",
"recharts": "^3.8.1",
"sonner": "^2.0.7",
"tailwind-merge": "^3.6.0",
"zustand": "^5.0.0"
},

View File

@@ -7,7 +7,11 @@ import {
Paperclip,
Settings,
SlidersHorizontal,
TrainTrack,
Train,
Truck,
Container,
Package,
//TrainTrack,
} from "lucide-react";
import { FreightDashboardLayout, type SidebarItem, type SidebarSection } from "@/components/layout";
@@ -32,6 +36,11 @@ import RuleEngineLegacyRedirect from "./pages/ruleEngine/RuleEngineLegacyRedirec
import RuleEngineResourcePage from "./pages/ruleEngine/RuleEngineResourcePage";
import TrainsPage from "./pages/trains/TrainsPage";
import { getCategorySidebarChildren } from "./pages/ruleEngine/config/resources";
//import TrainsPage from "./pages/trains/TrainsPage";
import TrainDetailPage from "./pages/trains/TrainDetailPage";
import WagonsPage from "./pages/wagons/WagonsPage";
import ContainersPage from "./pages/containers_management/ContainersPage";
import CargoesPage from "./pages/cargoes/CargoesPage";
const buildSidebarSections = (demoItems: SidebarItem[]): SidebarSection[] => [
{
@@ -51,11 +60,36 @@ const buildSidebarSections = (demoItems: SidebarItem[]): SidebarSection[] => [
{
label: "Train scheduling",
href: "/dashboard/operations/train-scheduling",
icon: <TrainTrack />,
icon: <Train />,
},
...demoItems,
],
},
{
title: "Fleet Management",
items: [
{
label: "Trains",
href: "/dashboard/trains",
icon: <Train />,
},
{
label: "Wagons",
href: "/dashboard/wagons",
icon: <Truck />,
},
{
label: "Containers",
href: "/dashboard/containers",
icon: <Container />,
},
{
label: "Cargoes",
href: "/dashboard/cargoes",
icon: <Package />,
},
],
},
{
title: "Administration",
items: [
@@ -208,6 +242,12 @@ const App = () => {
/>
<Route path="operations/train-scheduling" element={<TrainsPage />} />
<Route path="trains" element={<TrainsPage />} />
<Route path="trains/:id" element={<TrainDetailPage />} />
<Route path="wagons" element={<WagonsPage />} />
<Route path="containers" element={<ContainersPage />} />
<Route path="cargoes" element={<CargoesPage />} />
<Route path="user-management" element={<UserManagementPage />} />
<Route path="user-management/users" element={<UsersPage />} />
<Route path="user-management/position-types" element={<PositionTypesPage />} />

View File

@@ -52,3 +52,10 @@ export interface AuthTokens {
export interface LoginResponse extends Partial<AuthTokens> {
mfaRequired?: boolean;
}
// Additional types for Matrix form test
export interface User {
id: string;
name: string;
role: "ADMIN" | "MANAGER" | "CHIEF_EXECUTIVE";
}

View File

@@ -11,3 +11,5 @@ export const useAuth = () => {
return context;
};

View File

@@ -0,0 +1,330 @@
// components/baselineRatematrix/RateMatrixForm.tsx
import React, { useState, useCallback } from 'react';
// import { useForm } from 'react-hook-form';
// import { zodResolver } from '@hookform/resolvers/zod';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';
import { z } from 'zod';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Loader2, Save, Send, Shield, AlertTriangle } from 'lucide-react';
import { RateTypeSection } from './RateTypeSection';
import { ConfirmationDialog } from './ConfirmationDialog';
import { ValidationSummary } from './ValidationSummary';
import { LoadingScreen } from '@/ui/LoadingScreen';
import { useRateMatrixAuth } from '@/auth/hooks/useAuth';
import { useReferenceData } from '@/hooks/useReferenceData';
import { queryKeys } from '@/constants/queryKeys';
import { API_URLS } from '@/constants/apiUrls';
import {
RATE_TYPES,
RATE_TYPE_LABELS,
REQUIRED_RATE_TYPES
} from '@/constants/rateMatrixConstants';
import { rateMatrixRulesEngine } from '../../ruleEngine/rateMatrixRules';
import type { RateEntry } from './types';
const formSchema = z.object({
matrixName: z.string().min(1, 'Matrix name is required').max(200),
effectiveDate: z.string().min(1, 'Effective date is required'),
expiryDate: z.string().optional(),
currency: z.string().min(1, 'Currency is required'),
});
type FormData = z.infer<typeof formSchema>;
const createInitialSections = (): RateEntry[] => {
return REQUIRED_RATE_TYPES.map(rateType => ({
rateType,
entries: [{
validFrom: '',
validTo: '',
}],
}));
};
export function RateMatrixForm() {
const [rateSections, setRateSections] = useState<RateEntry[]>(createInitialSections());
const [showConfirmation, setShowConfirmation] = useState(false);
const [savedMatrixId, setSavedMatrixId] = useState<string | null>(null);
const [validationErrors, setValidationErrors] = useState<any[]>([]);
const { isDirector } = useRateMatrixAuth();
const { data: referenceData, isLoading: isLoadingReference } = useReferenceData();
const queryClient = useQueryClient();
const form = useForm<FormData>({
resolver: zodResolver(formSchema),
defaultValues: {
matrixName: '',
effectiveDate: '',
expiryDate: '',
currency: 'USD',
},
});
// Save draft mutation
const saveDraftMutation = useMutation({
mutationFn: async (data: FormData & { rateSections: RateEntry[] }) => {
const response = await fetch(API_URLS.RATE_MATRIX.DRAFT, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
});
if (!response.ok) throw new Error('Failed to save draft');
return response.json();
},
onSuccess: (data) => {
setSavedMatrixId(data.id);
queryClient.invalidateQueries({ queryKey: queryKeys.rateMatrix.all });
toast.success('Draft saved successfully');
},
onError: (error) => {
toast.error('Failed to save draft');
},
});
// Submit for approval mutation
const submitMutation = useMutation({
mutationFn: async (matrixId: string) => {
const response = await fetch(API_URLS.RATE_MATRIX.SUBMIT(matrixId), {
method: 'POST',
});
if (!response.ok) throw new Error('Failed to submit');
return response.json();
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: queryKeys.rateMatrix.all });
toast.success('Rate matrix submitted for executive approval and locked!');
setShowConfirmation(false);
},
onError: (error) => {
toast.error('Failed to submit for approval');
setShowConfirmation(false);
},
});
const handleValidate = useCallback(() => {
const validation = rateMatrixRulesEngine.validate(rateSections);
setValidationErrors([...validation.errors, ...validation.warnings]);
if (validation.isValid) {
toast.success('All validations passed!');
}
}, [rateSections]);
const handleSaveDraft = async () => {
const formData = form.getValues();
await saveDraftMutation.mutateAsync({
...formData,
rateSections,
});
};
const handleSubmitClick = async () => {
const isFormValid = await form.trigger();
if (!isFormValid) return;
const validation = rateMatrixRulesEngine.validate(rateSections);
setValidationErrors([...validation.errors, ...validation.warnings]);
if (!validation.isValid) {
toast.error('Please fix validation errors before submitting');
return;
}
setShowConfirmation(true);
};
const handleConfirmSubmit = async () => {
const formData = form.getValues();
try {
let matrixId = savedMatrixId;
if (!matrixId) {
const draftResult = await saveDraftMutation.mutateAsync({
...formData,
rateSections,
});
matrixId = draftResult.id;
}
await submitMutation.mutateAsync(matrixId!);
} catch (error) {
// Error handling done in mutations
}
};
if (isLoadingReference) {
return <LoadingScreen message="Loading reference data..." />;
}
if (!isDirector) {
return (
<div className="flex items-center justify-center min-h-screen">
<Alert variant="destructive" className="max-w-md">
<AlertTriangle className="h-4 w-4" />
<AlertTitle>Access Denied</AlertTitle>
<AlertDescription>
Only Directors can access the rate matrix registration.
</AlertDescription>
</Alert>
</div>
);
}
return (
<div className="container mx-auto py-8 px-4 max-w-7xl">
{/* Header */}
<div className="mb-8">
<h1 className="text-3xl font-bold tracking-tight">
Baseline Rate Matrix Registration
</h1>
<p className="text-muted-foreground mt-2">
Submit a comprehensive rate matrix for executive approval
</p>
</div>
{/* Director Warning */}
<Alert variant="warning" className="mb-6 border-amber-500 bg-amber-50">
<Shield className="h-4 w-4" />
<AlertTitle>Director Notice</AlertTitle>
<AlertDescription>
Once submitted, this matrix will be locked pending Chief Executive approval.
No edits can be made by any user until authorization is granted.
</AlertDescription>
</Alert>
<form onSubmit={(e) => e.preventDefault()}>
{/* Matrix Metadata */}
<Card className="mb-6">
<CardHeader>
<CardTitle>Matrix Information</CardTitle>
</CardHeader>
<CardContent>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
<div className="space-y-2">
<Label htmlFor="matrixName">Matrix Name *</Label>
<Input
id="matrixName"
{...form.register('matrixName')}
placeholder="e.g., Q4 2026 Baseline Matrix"
className={form.formState.errors.matrixName ? 'border-destructive' : ''}
/>
{form.formState.errors.matrixName && (
<p className="text-sm text-destructive">
{form.formState.errors.matrixName.message}
</p>
)}
</div>
<div className="space-y-2">
<Label htmlFor="effectiveDate">Effective Date *</Label>
<Input
id="effectiveDate"
type="date"
{...form.register('effectiveDate')}
className={form.formState.errors.effectiveDate ? 'border-destructive' : ''}
/>
</div>
<div className="space-y-2">
<Label htmlFor="expiryDate">Expiry Date</Label>
<Input
id="expiryDate"
type="date"
{...form.register('expiryDate')}
/>
</div>
<div className="space-y-2">
<Label htmlFor="currency">Currency *</Label>
<select
id="currency"
{...form.register('currency')}
className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2"
>
{referenceData?.currencies?.map((currency: any) => (
<option key={currency.code} value={currency.code}>
{currency.code} - {currency.name}
</option>
))}
</select>
</div>
</div>
</CardContent>
</Card>
{/* Rate Type Sections */}
<div className="space-y-6">
{rateSections.map((section, index) => (
<RateTypeSection
key={section.rateType}
section={section}
sectionIndex={index}
onUpdate={(updatedSection) => {
const newSections = [...rateSections];
newSections[index] = updatedSection;
setRateSections(newSections);
}}
referenceData={referenceData}
/>
))}
</div>
{/* Validation Errors */}
{validationErrors.length > 0 && (
<div className="mt-6">
<ValidationSummary errors={validationErrors} />
</div>
)}
{/* Form Actions */}
<div className="sticky bottom-6 mt-8 p-6 bg-background border rounded-lg shadow-lg flex gap-4 justify-end">
<Button
type="button"
variant="outline"
onClick={handleSaveDraft}
disabled={saveDraftMutation.isPending}
>
{saveDraftMutation.isPending ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<Save className="mr-2 h-4 w-4" />
)}
Save as Draft
</Button>
<Button
type="button"
variant="secondary"
onClick={handleValidate}
>
Validate All Rates
</Button>
<Button
type="button"
onClick={handleSubmitClick}
disabled={submitMutation.isPending}
>
<Send className="mr-2 h-4 w-4" />
Submit for Executive Approval
</Button>
</div>
</form>
{/* Confirmation Dialog */}
<ConfirmationDialog
open={showConfirmation}
onOpenChange={setShowConfirmation}
onConfirm={handleConfirmSubmit}
isLoading={submitMutation.isPending}
/>
</div>
);
}

View File

@@ -0,0 +1,46 @@
import { useCargoesByContainer, useDeliverCargo, useUnloadCargo } from '@/hooks/useCargoes';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { LoadCargoDialog } from './LoadCargoDialog';
import type { Cargo } from '@/services/cargoService';
export function CargoesTable({ containerId }: { containerId: string }) {
const { data: cargoes, refetch } = useCargoesByContainer(containerId);
const deliver = useDeliverCargo();
const unload = useUnloadCargo();
if (!cargoes?.length) return <div className="text-muted-foreground">No cargoes for this container.</div>;
return (
<Table>
<TableHeader>
<TableRow>
<TableHead>Reference</TableHead>
<TableHead>Description</TableHead>
<TableHead>Quantity</TableHead>
<TableHead>Weight (kg)</TableHead>
<TableHead>Status</TableHead>
<TableHead>Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{cargoes.map((cargo: Cargo) => (
<TableRow key={cargo.id}>
<TableCell>{cargo.cargoReference}</TableCell>
<TableCell>{cargo.description || '-'}</TableCell>
<TableCell>{cargo.quantity}</TableCell>
<TableCell>{cargo.weight}</TableCell>
<TableCell><Badge variant="outline">{cargo.status}</Badge></TableCell>
<TableCell className="space-x-2">
{cargo.status === 'PENDING' && <LoadCargoDialog cargoId={cargo.id} onSuccess={() => refetch()} />}
{cargo.status === 'LOADED' && <Button size="sm" onClick={() => deliver.mutateAsync(cargo.id).then(() => refetch())}>Deliver</Button>}
{cargo.status === 'LOADED' && <Button size="sm" variant="outline" onClick={() => unload.mutateAsync(cargo.id).then(() => refetch())}>Unload</Button>}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
);
}

View File

@@ -0,0 +1,38 @@
import { useState } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useLoadCargo } from '@/hooks/useCargoes';
import { useToast } from '@/hooks/use-toast';
export function LoadCargoDialog({ cargoId, onSuccess }: { cargoId: string; onSuccess?: () => void }) {
const [open, setOpen] = useState(false);
const [quantity, setQuantity] = useState(0);
const [weight, setWeight] = useState(0);
const [volume, setVolume] = useState<number>();
const load = useLoadCargo();
const { toast } = useToast();
const handleLoad = async () => {
await load.mutateAsync({ id: cargoId, quantity, weight, volume });
toast({ title: 'Loaded', description: 'Cargo loaded into container.' });
setOpen(false);
onSuccess?.();
};
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild><Button size="sm">Load Cargo</Button></DialogTrigger>
<DialogContent>
<DialogHeader><DialogTitle>Load Cargo</DialogTitle></DialogHeader>
<div className="space-y-4">
<div><Label>Quantity*</Label><Input type="number" required value={quantity} onChange={e => setQuantity(parseFloat(e.target.value))} /></div>
<div><Label>Weight (kg)*</Label><Input type="number" required value={weight} onChange={e => setWeight(parseFloat(e.target.value))} /></div>
<div><Label>Volume (m³)</Label><Input type="number" value={volume ?? ''} onChange={e => setVolume(parseFloat(e.target.value) || undefined)} /></div>
<Button onClick={handleLoad} disabled={load.isPending}>Confirm Load</Button>
</div>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,41 @@
import { useState } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useContainers, useAssignContainerToWagon } from '@/hooks/useContainers';
import { useToast } from '@/hooks/use-toast';
import { Plus } from 'lucide-react';
export function AssignContainerDialog({ wagonId }: { wagonId: string }) {
const [open, setOpen] = useState(false);
const [containerId, setContainerId] = useState('');
const [position, setPosition] = useState<number>();
const { data: containers } = useContainers();
const assign = useAssignContainerToWagon();
const { toast } = useToast();
const available = containers?.filter(c => c.status === 'AVAILABLE' && !c.wagonId);
const handleAssign = async () => {
if (!containerId) return;
await assign.mutateAsync({ containerId, wagonId, position });
toast({ title: 'Assigned', description: 'Container placed on wagon.' });
setOpen(false);
};
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild><Button size="sm"><Plus className="mr-2 h-4 w-4" />Assign Container</Button></DialogTrigger>
<DialogContent>
<DialogHeader><DialogTitle>Assign Container to Wagon</DialogTitle></DialogHeader>
<div className="space-y-4">
<div><Label>Container</Label><Select value={containerId} onValueChange={setContainerId}><SelectTrigger><SelectValue placeholder="Select container" /></SelectTrigger><SelectContent>{available?.map(c => <SelectItem key={c.id} value={c.id}>{c.containerNumber}</SelectItem>)}</SelectContent></Select></div>
<div><Label>Position (optional)</Label><Input type="number" value={position ?? ''} onChange={e => setPosition(parseInt(e.target.value) || undefined)} /></div>
<Button onClick={handleAssign} disabled={assign.isPending}>Assign</Button>
</div>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,44 @@
import { useContainersByWagon, useUnassignContainer } from '@/hooks/useContainers';
import { Button } from '@/components/ui/button';
import { Trash2 } from 'lucide-react';
import type { Container } from '@/services/containerService';
export function ContainersTable({ wagonId }: { wagonId: string }) {
const { data: containers, refetch } = useContainersByWagon(wagonId);
const unassign = useUnassignContainer();
if (!containers?.length) return <div className="text-muted-foreground">No containers assigned.</div>;
return (
<table className="w-full table-fixed">
<thead>
<tr>
<th className="text-left">Number</th>
<th className="text-left">Type</th>
<th className="text-left">Position</th>
<th className="text-left">Status</th>
<th className="text-left">Actions</th>
</tr>
</thead>
<tbody>
{containers.map((container: Container) => (
<tr key={container.id}>
<td className="py-2">{container.containerNumber}</td>
<td className="py-2">{container.containerTypeId}</td>
<td className="py-2">{container.position}</td>
<td className="py-2">{container.status}</td>
<td className="py-2">
<Button
variant="ghost"
size="icon"
onClick={() => unassign.mutateAsync(container.id).then(() => refetch())}
>
<Trash2 className="h-4 w-4" />
</Button>
</td>
</tr>
))}
</tbody>
</table>
);
}

View File

@@ -0,0 +1,173 @@
// ruleEngine/rateMatrixRules.ts
import { RATE_TYPES, REQUIRED_RATE_TYPES, MATRIX_STATUS } from '@/constants/rateMatrixConstants';
interface RateEntry {
rateType: string;
entries: Array<Record<string, any>>;
}
interface ValidationRule {
id: string;
description: string;
severity: 'error' | 'warning';
validate: (data: any) => boolean;
message: string;
}
export class RateMatrixRulesEngine {
private rules: ValidationRule[] = [];
constructor() {
this.initializeRules();
}
private initializeRules() {
// Rule 1: All rate types must be present
this.rules.push({
id: 'ALL_TYPES_REQUIRED',
description: 'Verify all 13 rate types are included',
severity: 'error',
validate: (rateSections: RateEntry[]) => {
const submittedTypes = rateSections.map(s => s.rateType);
return REQUIRED_RATE_TYPES.every(type => submittedTypes.includes(type));
},
message: 'All 13 rate types must be included in the submission',
});
// Rule 2: Each rate type must have at least one entry
this.rules.push({
id: 'MINIMUM_ENTRIES',
description: 'Each rate type requires at least one rate entry',
severity: 'error',
validate: (rateSections: RateEntry[]) => {
return rateSections.every(section => section.entries.length > 0);
},
message: 'Each rate type must have at least one rate entry',
});
// Rule 3: Dates must be valid
this.rules.push({
id: 'VALID_DATES',
description: 'Rate entries must have valid date ranges',
severity: 'error',
validate: (rateSections: RateEntry[]) => {
return rateSections.every(section =>
section.entries.every(entry => {
if (!entry.validFrom) return false;
if (entry.validTo && new Date(entry.validTo) <= new Date(entry.validFrom)) {
return false;
}
return true;
})
);
},
message: 'All rate entries must have valid dates (Valid To must be after Valid From)',
});
// Rule 4: Rates must be non-negative
this.rules.push({
id: 'NON_NEGATIVE_RATES',
description: 'All rate values must be non-negative',
severity: 'error',
validate: (rateSections: RateEntry[]) => {
const numericFields = ['baseRate', 'ratePerMetricTon', 'ratePerKm',
'ratePerTrip', 'ratePerDay', 'ratePerUnit'];
return rateSections.every(section =>
section.entries.every(entry => {
return numericFields.every(field => {
const value = entry[field];
return value === undefined || value === '' || Number(value) >= 0;
});
})
);
},
message: 'Rate values cannot be negative',
});
// Rule 5: Business rule - Demurrage free days should be reasonable
this.rules.push({
id: 'DEMURRAGE_FREE_DAYS',
description: 'Demurrage free days should be between 0 and 30',
severity: 'warning',
validate: (rateSections: RateEntry[]) => {
const demurrageSection = rateSections.find(
s => s.rateType === RATE_TYPES.DEMURRAGE
);
if (!demurrageSection) return true;
return demurrageSection.entries.every(entry => {
const freeDays = Number(entry.freeDays);
return !freeDays || (freeDays >= 0 && freeDays <= 30);
});
},
message: 'Demurrage free days typically range from 0 to 30 days',
});
// Rule 6: Cancellation fee percentage should be 0-100
this.rules.push({
id: 'CANCELLATION_FEE_RANGE',
description: 'Cancellation fee percentage must be between 0 and 100',
severity: 'error',
validate: (rateSections: RateEntry[]) => {
const cancellationSection = rateSections.find(
s => s.rateType === RATE_TYPES.CANCELLATION_FEE
);
if (!cancellationSection) return true;
return cancellationSection.entries.every(entry => {
const percentage = Number(entry.cancellationFeePercentage);
return !percentage || (percentage >= 0 && percentage <= 100);
});
},
message: 'Cancellation fee percentage must be between 0 and 100',
});
}
validate(data: RateEntry[]) {
const errors: Array<{ ruleId: string; message: string; severity: string }> = [];
const warnings: Array<{ ruleId: string; message: string; severity: string }> = [];
this.rules.forEach(rule => {
if (!rule.validate(data)) {
const issue = {
ruleId: rule.id,
message: rule.message,
severity: rule.severity,
};
if (rule.severity === 'error') {
errors.push(issue);
} else {
warnings.push(issue);
}
}
});
return {
isValid: errors.length === 0,
errors,
warnings,
};
}
// Check if matrix can transition to a new status
canTransition(fromStatus: string, toStatus: string, userRole: string): boolean {
const transitions: Record<string, Array<{ to: string; allowedRoles: string[] }>> = {
[MATRIX_STATUS.DRAFT]: [
{ to: MATRIX_STATUS.PENDING_APPROVAL, allowedRoles: ['Director'] },
],
[MATRIX_STATUS.PENDING_APPROVAL]: [
{ to: MATRIX_STATUS.ACTIVE, allowedRoles: ['Chief Executive'] },
{ to: MATRIX_STATUS.REJECTED, allowedRoles: ['Chief Executive'] },
],
};
const allowedTransitions = transitions[fromStatus] || [];
const transition = allowedTransitions.find(t => t.to === toStatus);
return transition ? transition.allowedRoles.includes(userRole) : false;
}
}
export const rateMatrixRulesEngine = new RateMatrixRulesEngine();

View File

@@ -0,0 +1,19 @@
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Train } from '@/services/trainService';
export function TrainDetailCard({ train }: { train: Train }) {
return (
<Card>
<CardHeader><CardTitle>{train.trainNumber || train.code} - {train.trainName || 'Unnamed'}</CardTitle></CardHeader>
<CardContent className="grid md:grid-cols-2 gap-4">
<div><span className="font-medium">Status:</span> {train.status}</div>
<div><span className="font-medium">Capacity:</span> {train.capacityTons} tons</div>
<div><span className="font-medium">Origin:</span> {train.originStationId || '-'}</div>
<div><span className="font-medium">Destination:</span> {train.destinationStationId || '-'}</div>
<div><span className="font-medium">Departure:</span> {train.departureTime ? new Date(train.departureTime).toLocaleString() : '-'}</div>
<div><span className="font-medium">Arrival:</span> {train.arrivalTime ? new Date(train.arrivalTime).toLocaleString() : '-'}</div>
{train.remarks && <div className="col-span-2"><span className="font-medium">Remarks:</span> {train.remarks}</div>}
</CardContent>
</Card>
);
}

View File

@@ -0,0 +1,59 @@
import { useState, useEffect } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useCreateTrain, useUpdateTrain } from '@/hooks/useTrains';
import { useToast } from '@/hooks/use-toast';
interface TrainFormDialogProps {
trigger?: React.ReactNode;
train?: any;
onSuccess?: () => void;
}
export function TrainFormDialog({ trigger, train, onSuccess }: TrainFormDialogProps) {
const [open, setOpen] = useState(false);
const [form, setForm] = useState({ code: '', capacityTons: 0, trainNumber: '', trainName: '' });
const createTrain = useCreateTrain();
const updateTrain = useUpdateTrain();
const { toast } = useToast();
useEffect(() => {
if (train) setForm({
code: train.code,
capacityTons: train.capacityTons,
trainNumber: train.trainNumber || '',
trainName: train.trainName || '',
});
}, [train]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
try {
if (train) await updateTrain.mutateAsync({ id: train.id, data: form });
else await createTrain.mutateAsync(form);
toast({ title: train ? 'Train updated' : 'Train created', description: `${form.code} saved.` });
setOpen(false);
onSuccess?.();
} catch {
toast({ title: 'Error', description: `Failed to ${train ? 'update' : 'create'} train.`, variant: 'destructive' });
}
};
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>{trigger || <Button>New Train</Button>}</DialogTrigger>
<DialogContent>
<DialogHeader><DialogTitle>{train ? 'Edit Train' : 'Create Train'}</DialogTitle></DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4">
<div><Label>Code*</Label><Input required value={form.code} onChange={e => setForm({...form, code: e.target.value})} /></div>
<div><Label>Capacity (tons)*</Label><Input type="number" required value={form.capacityTons} onChange={e => setForm({...form, capacityTons: parseFloat(e.target.value)})} /></div>
<div><Label>Train Number</Label><Input value={form.trainNumber} onChange={e => setForm({...form, trainNumber: e.target.value})} /></div>
<div><Label>Train Name</Label><Input value={form.trainName} onChange={e => setForm({...form, trainName: e.target.value})} /></div>
<Button type="submit" disabled={createTrain.isPending || updateTrain.isPending}>Save</Button>
</form>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,45 @@
import { useTrains, useDeleteTrain } from '@/hooks/useTrains';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Eye, Trash2 } from 'lucide-react';
import { Link } from 'react-router-dom';
export function TrainsTable() {
const { data: trains, isLoading } = useTrains();
const deleteTrain = useDeleteTrain();
if (isLoading) return <div>Loading trains...</div>;
return (
<Table>
<TableHeader>
<TableRow>
<TableHead>Number</TableHead>
<TableHead>Name</TableHead>
<TableHead>Status</TableHead>
<TableHead>Capacity (tons)</TableHead>
<TableHead>Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{trains?.map(train => (
<TableRow key={train.id}>
<TableCell>{train.trainNumber || train.code}</TableCell>
<TableCell>{train.trainName || '-'}</TableCell>
<TableCell><Badge variant="outline">{train.status}</Badge></TableCell>
<TableCell>{train.capacityTons}</TableCell>
<TableCell className="flex space-x-2">
<Link to={`/trains/${train.id}`}>
<Button variant="ghost" size="icon"><Eye className="h-4 w-4" /></Button>
</Link>
<Button variant="ghost" size="icon" onClick={() => deleteTrain.mutate(train.id)}>
<Trash2 className="h-4 w-4" />
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
);
}

View File

@@ -0,0 +1,47 @@
import * as React from "react";
import { cva, type VariantProps } from "class-variance-authority";
import { Slot } from "radix-ui";
import { cn } from "@/lib/utils";
const badgeVariants = cva(
"inline-flex w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-full border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
secondary: "bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
destructive:
"bg-destructive text-white focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40 [a&]:hover:bg-destructive/90",
outline:
"border-border text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
ghost: "[a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
link: "text-primary underline-offset-4 [a&]:hover:underline",
},
},
defaultVariants: {
variant: "default",
},
},
);
function Badge({
className,
variant = "default",
asChild = false,
...props
}: React.ComponentProps<"span"> &
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
const Comp = asChild ? Slot.Root : "span";
return (
<Comp
data-slot="badge"
data-variant={variant}
className={cn(badgeVariants({ variant }), className)}
{...props}
/>
);
}
export { Badge, badgeVariants };

View File

@@ -0,0 +1,8 @@
export * from './table';
export * from './badge';
export * from './button';
export * from './dialog';
export * from './input';
export * from './label';
export * from './textarea';
export * from './Breadcrumbs';

View File

@@ -0,0 +1,114 @@
import * as React from "react";
import { cn } from "@/lib/utils";
function Table({ className, ...props }: React.ComponentProps<"table">) {
return (
<div
data-slot="table-container"
className="relative w-full overflow-x-auto"
>
<table
data-slot="table"
className={cn("w-full caption-bottom text-sm", className)}
{...props}
/>
</div>
);
}
function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
return (
<thead
data-slot="table-header"
className={cn("[&_tr]:border-b outline-ring/50", className)}
{...props}
/>
);
}
function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
return (
<tbody
data-slot="table-body"
className={cn("[&_tr:last-child]:border-0", className)}
{...props}
/>
);
}
function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
return (
<tfoot
data-slot="table-footer"
className={cn(
"border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",
className,
)}
{...props}
/>
);
}
function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
return (
<tr
data-slot="table-row"
className={cn(
"border-b transition-colors bg-background hover:bg-muted/50 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted",
className,
)}
{...props}
/>
);
}
function TableHead({ className, ...props }: React.ComponentProps<"th">) {
return (
<th
data-slot="table-head"
className={cn(
"h-10 bg-muted first-of-type:pl-4 last-of-type:pr-4 first-of-type: p-2 py-4 text-left align-middle font-medium whitespace-nowrap text-secondary-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className,
)}
{...props}
/>
);
}
function TableCell({ className, ...props }: React.ComponentProps<"td">) {
return (
<td
data-slot="table-cell"
className={cn(
"p-2 align-middle first-of-type:pl-4 last-of-type:pr-4 whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className,
)}
{...props}
/>
);
}
function TableCaption({
className,
...props
}: React.ComponentProps<"caption">) {
return (
<caption
data-slot="table-caption"
className={cn("mt-4 text-sm text-muted-foreground", className)}
{...props}
/>
);
}
export {
Table,
TableHeader,
TableBody,
TableFooter,
TableHead,
TableRow,
TableCell,
TableCaption,
};

View File

@@ -0,0 +1,52 @@
import { useState } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useWagons, useAssignWagonToTrain } from '@/hooks/useWagons';
import { useToast } from '@/hooks/use-toast';
import { Plus } from 'lucide-react';
export function AssignWagonDialog({ trainId }: { trainId: string }) {
const [open, setOpen] = useState(false);
const [wagonId, setWagonId] = useState('');
const [sequence, setSequence] = useState<number>();
const { data: wagons } = useWagons();
const assign = useAssignWagonToTrain();
const { toast } = useToast();
const available = wagons?.filter(w => w.status === 'AVAILABLE' || !w.trainId);
const handleAssign = async () => {
if (!wagonId) return;
await assign.mutateAsync({ wagonId, trainId, sequenceNumber: sequence });
toast({ title: 'Assigned', description: 'Wagon attached to train.' });
setOpen(false);
};
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild><Button size="sm"><Plus className="mr-2 h-4 w-4" />Assign Wagon</Button></DialogTrigger>
<DialogContent>
<DialogHeader><DialogTitle>Assign Wagon to Train</DialogTitle></DialogHeader>
<div className="space-y-4">
<div>
<Label>Wagon</Label>
<Select value={wagonId} onValueChange={setWagonId}>
<SelectTrigger><SelectValue placeholder="Select wagon" /></SelectTrigger>
<SelectContent>
{available?.map(w => <SelectItem key={w.id} value={w.id}>{w.wagonNumber}</SelectItem>)}
</SelectContent>
</Select>
</div>
<div>
<Label>Sequence (optional)</Label>
<Input type="number" value={sequence ?? ''} onChange={e => setSequence(parseInt(e.target.value) || undefined)} />
</div>
<Button onClick={handleAssign} disabled={assign.isPending}>Assign</Button>
</div>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,71 @@
// src/components/wagons/WagonFormDialog.tsx
import { useState, useEffect } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useCreateWagon, useUpdateWagon } from '@/hooks/useWagons';
import { useToast } from '@/hooks/use-toast';
interface WagonFormDialogProps {
trigger?: React.ReactNode;
wagon?: any;
onSuccess?: () => void;
}
export function WagonFormDialog({ trigger, wagon, onSuccess }: WagonFormDialogProps) {
const [open, setOpen] = useState(false);
const [form, setForm] = useState({
wagonNumber: '',
wagonTypeId: '',
tareWeight: 0,
maxPayloadWeight: 0,
status: 'AVAILABLE',
notes: ''
});
const createWagon = useCreateWagon();
const updateWagon = useUpdateWagon();
const { toast } = useToast();
useEffect(() => {
if (wagon) setForm({
wagonNumber: wagon.wagonNumber,
wagonTypeId: wagon.wagonTypeId,
tareWeight: wagon.tareWeight,
maxPayloadWeight: wagon.maxPayloadWeight,
status: wagon.status,
notes: wagon.notes || ''
});
}, [wagon]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
try {
if (wagon) await updateWagon.mutateAsync({ id: wagon.id, data: form });
else await createWagon.mutateAsync(form);
toast({ title: wagon ? 'Wagon updated' : 'Wagon created', description: `${form.wagonNumber} saved.` });
setOpen(false);
onSuccess?.();
} catch {
toast({ title: 'Error', description: `Failed to ${wagon ? 'update' : 'create'} wagon.`, variant: 'destructive' });
}
};
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>{trigger || <Button>New Wagon</Button>}</DialogTrigger>
<DialogContent>
<DialogHeader><DialogTitle>{wagon ? 'Edit Wagon' : 'Create Wagon'}</DialogTitle></DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4">
<div><Label>Wagon Number*</Label><Input required value={form.wagonNumber} onChange={e => setForm({...form, wagonNumber: e.target.value})} /></div>
<div><Label>Wagon Type ID*</Label><Input required value={form.wagonTypeId} onChange={e => setForm({...form, wagonTypeId: e.target.value})} /></div>
<div><Label>Tare Weight (kg)*</Label><Input type="number" required value={form.tareWeight} onChange={e => setForm({...form, tareWeight: parseFloat(e.target.value)})} /></div>
<div><Label>Max Payload (kg)*</Label><Input type="number" required value={form.maxPayloadWeight} onChange={e => setForm({...form, maxPayloadWeight: parseFloat(e.target.value)})} /></div>
<div><Label>Status</Label><Input value={form.status} onChange={e => setForm({...form, status: e.target.value})} /></div>
<div><Label>Notes</Label><Input value={form.notes} onChange={e => setForm({...form, notes: e.target.value})} /></div>
<Button type="submit" disabled={createWagon.isPending || updateWagon.isPending}>Save</Button>
</form>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,63 @@
import { useWagonsByTrain, useUnassignWagon, useReorderWagons } from '@/hooks/useWagons';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Button } from '@/components/ui/button';
import { Trash2, GripVertical } from 'lucide-react';
import { DragDropContext, Droppable, Draggable } from '@hello-pangea/dnd';
export function WagonsTable({ trainId }: { trainId: string }) {
const { data: wagons, refetch } = useWagonsByTrain(trainId);
const unassign = useUnassignWagon();
const reorder = useReorderWagons();
const onDragEnd = (result: any) => {
if (!result.destination) return;
const items = Array.from(wagons || []);
const [removed] = items.splice(result.source.index, 1);
items.splice(result.destination.index, 0, removed);
reorder.mutate({ trainId, wagonIds: items.map(w => w.id) });
};
if (!wagons?.length) return <div className="text-muted-foreground">No wagons assigned.</div>;
return (
<DragDropContext onDragEnd={onDragEnd}>
<Droppable droppableId="wagons">
{(provided) => (
<Table {...provided.droppableProps} ref={provided.innerRef}>
<TableHeader>
<TableRow>
<TableHead className="w-10"></TableHead>
<TableHead>Number</TableHead>
<TableHead>Type</TableHead>
<TableHead>Sequence</TableHead>
<TableHead>Status</TableHead>
<TableHead>Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{wagons.map((wagon, idx) => (
<Draggable key={wagon.id} draggableId={wagon.id} index={idx}>
{(provided) => (
<TableRow ref={provided.innerRef} {...provided.draggableProps}>
<TableCell {...provided.dragHandleProps}><GripVertical className="h-4 w-4 cursor-grab" /></TableCell>
<TableCell>{wagon.wagonNumber}</TableCell>
<TableCell>{wagon.wagonTypeId}</TableCell>
<TableCell>{wagon.sequenceNumber}</TableCell>
<TableCell>{wagon.status}</TableCell>
<TableCell>
<Button variant="ghost" size="icon" onClick={() => unassign.mutateAsync(wagon.id).then(() => refetch())}>
<Trash2 className="h-4 w-4" />
</Button>
</TableCell>
</TableRow>
)}
</Draggable>
))}
{provided.placeholder}
</TableBody>
</Table>
)}
</Droppable>
</DragDropContext>
);
}

View File

@@ -160,4 +160,18 @@ export const URL_CONSTANTS = {
APPROVAL_RULE_BY_ID: (id: string) => `/approval-rules/${id}`,
APPROVAL_RULES_CHAIN: "/approval-rules/chain",
},
RATE_MATRIX: {
BASE: '/api/rate-matrices',
DRAFT: '/api/rate-matrices/draft',
SUBMIT: (id: string) => `/api/rate-matrices/${id}/submit`,
AUTHORIZE: (id: string) => `/api/rate-matrices/${id}/authorize`,
LIST: '/api/rate-matrices',
DETAIL: (id: string) => `/api/rate-matrices/${id}`,
},
REFERENCE: {
PORTS: '/api/reference/ports',
CITIES: '/api/reference/cities',
CONTAINER_TYPES: '/api/reference/container-types',
CURRENCIES: '/api/reference/currencies',
},
};

View File

@@ -0,0 +1,60 @@
// constants/rateMatrixConstants.ts
export const RATE_TYPES = {
CONTAINER_IMPORT: 'container_import',
CONTAINER_EXPORT: 'container_export',
BULK_IMPORT: 'bulk_import',
BULK_EXPORT: 'bulk_export',
INTER_CITY_BULK: 'inter_city_bulk',
INTER_CITY_CONTAINER: 'inter_city_container',
FIRST_MILE: 'first_mile',
LAST_MILE: 'last_mile',
DEMURRAGE: 'demurrage',
LASHING: 'lashing',
DOUBLE_HANDLING: 'double_handling',
CONTAINER_WITH_RETURN: 'container_with_return',
CANCELLATION_FEE: 'cancellation_fee',
} as const;
export const RATE_TYPE_LABELS = {
[RATE_TYPES.CONTAINER_IMPORT]: 'Container Import Rates',
[RATE_TYPES.CONTAINER_EXPORT]: 'Container Export Rates',
[RATE_TYPES.BULK_IMPORT]: 'Bulk Import Rates',
[RATE_TYPES.BULK_EXPORT]: 'Bulk Export Rates',
[RATE_TYPES.INTER_CITY_BULK]: 'Inter City Bulk Rates',
[RATE_TYPES.INTER_CITY_CONTAINER]: 'Inter City Container Rates',
[RATE_TYPES.FIRST_MILE]: 'First Mile Cost Rates',
[RATE_TYPES.LAST_MILE]: 'Last Mile Cost Rates',
[RATE_TYPES.DEMURRAGE]: 'Demurrage Cost Rates',
[RATE_TYPES.LASHING]: 'Lashing Cost Rates',
[RATE_TYPES.DOUBLE_HANDLING]: 'Double Handling Cost Rates',
[RATE_TYPES.CONTAINER_WITH_RETURN]: 'Container With Return Cost Rates',
[RATE_TYPES.CANCELLATION_FEE]: 'Cancellation Fee Cost Rates',
} as const;
export const REQUIRED_RATE_TYPES = Object.values(RATE_TYPES);
export const RATE_FIELDS_CONFIG = {
[RATE_TYPES.CONTAINER_IMPORT]: [
{ name: 'portOfLoading', label: 'Port of Loading', type: 'text', required: true },
{ name: 'portOfDischarge', label: 'Port of Discharge', type: 'text', required: true },
{ name: 'containerType', label: 'Container Type', type: 'select', required: true },
{ name: 'baseRate', label: 'Base Rate', type: 'number', required: true, min: 0, step: '0.01' },
{ name: 'baf', label: 'Bunker Adjustment Factor', type: 'number', required: false, min: 0 },
{ name: 'caf', label: 'Currency Adjustment Factor', type: 'number', required: false, min: 0 },
],
[RATE_TYPES.DEMURRAGE]: [
{ name: 'containerType', label: 'Container Type', type: 'select', required: true },
{ name: 'freeDays', label: 'Free Days', type: 'number', required: true, min: 0 },
{ name: 'ratePerDay', label: 'Rate per Day', type: 'number', required: true, min: 0 },
{ name: 'maximumDays', label: 'Maximum Days', type: 'number', required: false, min: 1 },
],
// ... define for all 13 rate types
} as const;
export const MATRIX_STATUS = {
DRAFT: 'draft',
PENDING_APPROVAL: 'pending_approval',
ACTIVE: 'active',
REJECTED: 'rejected',
EXPIRED: 'expired',
} as const;

View File

@@ -0,0 +1,24 @@
import toast from 'react-hot-toast';
interface ToastOptions {
title?: string;
description?: string;
variant?: 'default' | 'destructive';
duration?: number;
}
export function useToast() {
const showToast = (options: ToastOptions) => {
const { title, description, variant = 'default', duration = 3000 } = options;
const message = title ? `${title}${description ? ': ' + description : ''}` : description || '';
if (variant === 'destructive') {
toast.error(message, { duration });
} else {
toast.success(message, { duration });
}
};
return { toast: showToast };
}

View File

@@ -0,0 +1,39 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { cargoService } from '@/services/cargoService';
export const cargoKeys = {
all: ['cargoes'] as const,
byContainer: (containerId: string) => [...cargoKeys.all, 'container', containerId] as const,
};
export function useCargoes() {
return useQuery({ queryKey: cargoKeys.all, queryFn: () => cargoService.getAll().then(res => res.data) });
}
export function useCargoesByContainer(containerId: string) {
return useQuery({ queryKey: cargoKeys.byContainer(containerId), queryFn: () => cargoService.getByContainer(containerId).then(res => res.data), enabled: !!containerId });
}
export function useLoadCargo() {
const qc = useQueryClient();
return useMutation({
mutationFn: ({ id, quantity, weight, volume }: any) => cargoService.load(id, quantity, weight, volume),
onSuccess: (_, { id }) => qc.invalidateQueries({ queryKey: cargoKeys.all })
});
}
export function useDeliverCargo() {
const qc = useQueryClient();
return useMutation({
mutationFn: (id: string) => cargoService.deliver(id),
onSuccess: () => qc.invalidateQueries({ queryKey: cargoKeys.all })
});
}
export function useUnloadCargo() {
const qc = useQueryClient();
return useMutation({
mutationFn: (id: string) => cargoService.unload(id),
onSuccess: () => qc.invalidateQueries({ queryKey: cargoKeys.all })
});
}

View File

@@ -0,0 +1,31 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { containerService } from '@/services/containerService';
export const containerKeys = {
all: ['containers'] as const,
byWagon: (wagonId: string) => [...containerKeys.all, 'wagon', wagonId] as const,
};
export function useContainers() {
return useQuery({ queryKey: containerKeys.all, queryFn: () => containerService.getAll().then(res => res.data) });
}
export function useContainersByWagon(wagonId: string) {
return useQuery({ queryKey: containerKeys.byWagon(wagonId), queryFn: () => containerService.getByWagon(wagonId).then(res => res.data), enabled: !!wagonId });
}
export function useAssignContainerToWagon() {
const qc = useQueryClient();
return useMutation({
mutationFn: ({ containerId, wagonId, position }: any) => containerService.assignToWagon(containerId, wagonId, position),
onSuccess: (_, { wagonId }) => qc.invalidateQueries({ queryKey: containerKeys.byWagon(wagonId) })
});
}
export function useUnassignContainer() {
const qc = useQueryClient();
return useMutation({
mutationFn: containerService.unassign,
onSuccess: () => qc.invalidateQueries({ queryKey: containerKeys.all })
});
}

View File

@@ -0,0 +1,35 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { trainService } from '@/services/trains.service';
export const trainKeys = {
all: ['trains'] as const,
lists: () => [...trainKeys.all, 'list'] as const,
details: () => [...trainKeys.all, 'detail'] as const,
detail: (id: string) => [...trainKeys.details(), id] as const,
};
export function useTrains() {
return useQuery({ queryKey: trainKeys.lists(), queryFn: () => trainService.getAll().then(res => res.data) });
}
export function useTrain(id: string) {
return useQuery({ queryKey: trainKeys.detail(id), queryFn: () => trainService.getById(id).then(res => res.data), enabled: !!id });
}
export function useCreateTrain() {
const qc = useQueryClient();
return useMutation({ mutationFn: trainService.create, onSuccess: () => qc.invalidateQueries({ queryKey: trainKeys.lists() }) });
}
export function useUpdateTrain() {
const qc = useQueryClient();
return useMutation({ mutationFn: ({ id, data }: any) => trainService.update(id, data), onSuccess: (_, { id }) => {
qc.invalidateQueries({ queryKey: trainKeys.lists() });
qc.invalidateQueries({ queryKey: trainKeys.detail(id) });
} });
}
export function useDeleteTrain() {
const qc = useQueryClient();
return useMutation({ mutationFn: trainService.delete, onSuccess: () => qc.invalidateQueries({ queryKey: trainKeys.lists() }) });
}

View File

@@ -0,0 +1,41 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { wagonService } from '@/services/wagon.service';
export const wagonKeys = {
all: ['wagons'] as const,
byTrain: (trainId: string) => [...wagonKeys.all, 'train', trainId] as const,
details: () => [...wagonKeys.all, 'detail'] as const,
};
export function useWagons() {
return useQuery({ queryKey: wagonKeys.all, queryFn: () => wagonService.getAll().then(res => res.data) });
}
export function useWagonsByTrain(trainId: string) {
return useQuery({ queryKey: wagonKeys.byTrain(trainId), queryFn: () => wagonService.getByTrain(trainId).then(res => res.data), enabled: !!trainId });
}
export function useAssignWagonToTrain() {
const qc = useQueryClient();
return useMutation({ mutationFn: ({ wagonId, trainId, sequenceNumber }: any) => wagonService.assignToTrain(wagonId, trainId, sequenceNumber), onSuccess: (_, { trainId }) => qc.invalidateQueries({ queryKey: wagonKeys.byTrain(trainId) }) });
}
export function useUnassignWagon() {
const qc = useQueryClient();
return useMutation({ mutationFn: wagonService.unassign, onSuccess: () => qc.invalidateQueries({ queryKey: wagonKeys.all }) });
}
export function useReorderWagons() {
const qc = useQueryClient();
return useMutation({ mutationFn: ({ trainId, wagonIds }: any) => wagonService.reorder(trainId, wagonIds), onSuccess: (_, { trainId }) => qc.invalidateQueries({ queryKey: wagonKeys.byTrain(trainId) }) });
}
export function useCreateWagon() {
const qc = useQueryClient();
return useMutation({ mutationFn: wagonService.create, onSuccess: () => qc.invalidateQueries({ queryKey: wagonKeys.all }) });
}
export function useUpdateWagon() {
const qc = useQueryClient();
return useMutation({ mutationFn: ({ id, data }: any) => wagonService.update(id, data), onSuccess: () => qc.invalidateQueries({ queryKey: wagonKeys.all }) });
}

View File

@@ -0,0 +1,117 @@
// pages/admin/rateMatrix/RateMatrixApproval.tsx
import React from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { LoadingScreen } from '@/ui/LoadingScreen';
import { useRateMatrixAuth } from '@/auth/hooks/useAuth';
import { queryKeys } from '../../../constants/QUERY_KEYS';
import { API_URLS } from '@/constants/URL_CONSTANTS';
//import { MATRIX_STATUS } from '@/constants/rateMatrixConstants';
import { toast } from 'sonner';
import { Navigate } from 'react-router-dom';
export default function RateMatrixApprovalPage() {
const { isChiefExecutive } = useRateMatrixAuth();
const queryClient = useQueryClient();
const pendingMatricesQueryKey = [...queryKeys.rateMatrix.all, 'pending-approval'];
const { data: pendingMatrices, isLoading } = useQuery({
queryKey: pendingMatricesQueryKey,
queryFn: async () => {
const response = await fetch(`${API_URLS.RATE_MATRIX.LIST}?status=pending_approval`);
return response.json();
},
});
const authorizeMutation = useMutation({
mutationFn: async ({ matrixId, signature }: { matrixId: string; signature: string }) => {
const response = await fetch(API_URLS.RATE_MATRIX.AUTHORIZE(matrixId), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ digitalSignature: signature }),
});
if (!response.ok) throw new Error('Authorization failed');
return response.json();
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: pendingMatricesQueryKey });
toast.success('Rate matrix authorized successfully!');
},
onError: () => {
toast.error('Failed to authorize rate matrix');
},
});
if (!isChiefExecutive) {
return <Navigate to="/unauthorized" replace />;
}
if (isLoading) return <LoadingScreen />;
return (
<div className="container mx-auto py-8">
<h1 className="text-3xl font-bold mb-8">Pending Rate Matrix Approvals</h1>
<div className="space-y-6">
{pendingMatrices?.map((matrix: any) => (
<Card key={matrix.id}>
<CardHeader>
<CardTitle className="flex items-center justify-between">
<span>{matrix.matrixName}</span>
<Badge variant="secondary">{matrix.status}</Badge>
</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-4">
<div className="grid grid-cols-2 gap-4">
<div>
<p className="text-sm font-semibold">Effective Date</p>
<p>{matrix.effectiveDate}</p>
</div>
<div>
<p className="text-sm font-semibold">Submitted By</p>
<p>{matrix.createdBy}</p>
</div>
</div>
<div>
<p className="text-sm font-semibold mb-2">Rate Types Included:</p>
<div className="flex flex-wrap gap-2">
{matrix.rateEntries?.map((entry: any) => (
<Badge key={entry.id} variant="outline">
{entry.rateType}
</Badge>
))}
</div>
</div>
<div className="flex gap-4">
<Button
onClick={() => {
// Implement digital signature collection
const signature = prompt('Enter digital signature:');
if (signature) {
authorizeMutation.mutate({
matrixId: matrix.id,
signature
});
}
}}
disabled={authorizeMutation.isPending}
>
Authorize & Release
</Button>
<Button variant="outline">
Request Changes
</Button>
</div>
</div>
</CardContent>
</Card>
))}
</div>
</div>
);
}

View File

@@ -0,0 +1,25 @@
// pages/admin/rateMatrix/RateMatrixRegistration.tsx
import React from 'react';
import { RateMatrixForm } from '@/components/baselineRatematrix/RateMatrixForm';
import { useRateMatrixAuth } from '@/auth/useAuth';
import { Navigate } from 'react-router-dom';
// Local lightweight fallback for LoadingScreen to avoid import errors
const LoadingScreen: React.FC<{ message?: string }> = ({ message = 'Loading...' }) => (
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100%' }}>
<div>{message}</div>
</div>
);
export default function RateMatrixRegistrationPage() {
const { isDirector, isLoading } = useRateMatrixAuth();
if (isLoading) {
return <LoadingScreen message="Checking permissions..." />;
}
if (!isDirector) {
return <Navigate to="/unauthorized" replace />;
}
return <RateMatrixForm />;
}

View File

@@ -0,0 +1,34 @@
import { useCargoes } from '@/hooks/useCargoes';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
import { LoadCargoDialog } from '@/components/cargoes/LoadCargoDialog';
export default function CargoesPage() {
const { data: cargoes, refetch, isLoading } = useCargoes();
if (isLoading) return <div>Loading cargoes...</div>;
return (
<Card>
<CardHeader><CardTitle>All Cargoes</CardTitle></CardHeader>
<CardContent>
<Table>
<TableHeader><TableRow><TableHead>Reference</TableHead><TableHead>Description</TableHead><TableHead>Quantity</TableHead><TableHead>Weight</TableHead><TableHead>Status</TableHead><TableHead>Actions</TableHead></TableRow></TableHeader>
<TableBody>
{cargoes?.map(c => (
<TableRow key={c.id}>
<TableCell>{c.cargoReference}</TableCell>
<TableCell>{c.description || '-'}</TableCell>
<TableCell>{c.quantity}</TableCell>
<TableCell>{c.weight} kg</TableCell>
<TableCell><Badge variant="outline">{c.status}</Badge></TableCell>
<TableCell>
{c.status === 'PENDING' && <LoadCargoDialog cargoId={c.id} onSuccess={() => refetch()} />}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</CardContent>
</Card>
);
}

View File

@@ -0,0 +1,29 @@
import { useContainers } from '@/hooks/useContainers';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
export default function ContainersPage() {
const { data: containers, isLoading } = useContainers();
if (isLoading) return <div>Loading containers...</div>;
return (
<Card>
<CardHeader><CardTitle>All Containers</CardTitle></CardHeader>
<CardContent>
<Table>
<TableHeader><TableRow><TableHead>Number</TableHead><TableHead>Type</TableHead><TableHead>Wagon</TableHead><TableHead>Status</TableHead></TableRow></TableHeader>
<TableBody>
{containers?.map(c => (
<TableRow key={c.id}>
<TableCell>{c.containerNumber}</TableCell>
<TableCell>{c.containerTypeId}</TableCell>
<TableCell>{c.wagonId || 'Unassigned'}</TableCell>
<TableCell><Badge variant="outline">{c.status}</Badge></TableCell>
</TableRow>
))}
</TableBody>
</Table>
</CardContent>
</Card>
);
}

View File

@@ -0,0 +1,33 @@
import { useParams } from 'react-router-dom';
import { useTrain } from '@/hooks/useTrains';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { AssignWagonDialog } from '@/components/AssignWagonDialog';
import { WagonsTable } from '@/components/WagonsTable';
export default function TrainDetailPage() {
const { id } = useParams<{ id: string }>();
const { data: train, isLoading } = useTrain(id!);
if (isLoading) return <Skeleton className="h-96 w-full" />;
if (!train) return <div>Train not found</div>;
return (
<div className="space-y-6">
<Card>
<CardHeader><CardTitle>{train.trainNumber || train.code} - {train.trainName || 'Unnamed'}</CardTitle></CardHeader>
<CardContent className="grid md:grid-cols-2 gap-4">
<div><span className="font-medium">Status:</span> {train.status}</div>
<div><span className="font-medium">Capacity:</span> {train.capacityTons} tons</div>
<div><span className="font-medium">Origin Station:</span> {train.originStationId || '-'}</div>
<div><span className="font-medium">Destination:</span> {train.destinationStationId || '-'}</div>
</CardContent>
</Card>
<div className="flex justify-between items-center">
<h2 className="text-xl font-semibold">Wagons</h2>
<AssignWagonDialog trainId={train.id} />
</div>
<WagonsTable trainId={train.id} />
</div>
);
}

View File

@@ -1,3 +1,42 @@
<<<<<<< HEAD
import { useState } from 'react';
import { useTrains, useDeleteTrain, useCreateTrain } from '@/hooks/useTrains';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useToast } from '@/hooks/use-toast';
import { Plus, Eye, Trash2 } from 'lucide-react';
import { Link } from 'react-router-dom';
const CreateTrainForm = ({ onSuccess }: { onSuccess: () => void }) => {
const [form, setForm] = useState({ code: '', capacityTons: 0, trainNumber: '', trainName: '' });
const createTrain = useCreateTrain();
const { toast } = useToast();
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
try {
await createTrain.mutateAsync(form);
toast({ title: 'Train created', description: `${form.code} added.` });
onSuccess();
} catch {
toast({ title: 'Error', description: 'Failed to create train.', variant: 'destructive' });
}
};
return (
<form onSubmit={handleSubmit} className="space-y-4">
<div><Label>Code*</Label><Input required value={form.code} onChange={e => setForm({...form, code: e.target.value})} /></div>
<div><Label>Capacity (tons)*</Label><Input type="number" required value={form.capacityTons} onChange={e => setForm({...form, capacityTons: parseFloat(e.target.value)})} /></div>
<div><Label>Train Number</Label><Input value={form.trainNumber} onChange={e => setForm({...form, trainNumber: e.target.value})} /></div>
<div><Label>Train Name</Label><Input value={form.trainName} onChange={e => setForm({...form, trainName: e.target.value})} /></div>
<Button type="submit" disabled={createTrain.isPending}>Save</Button>
</form>
=======
import { useMemo, useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { isAxiosError } from 'axios';
@@ -755,7 +794,45 @@ const TrainsPage = () => {
</DialogContent>
</Dialog>
</div>
>>>>>>> 523d7e58422f1bde8024c2dd237092a7cf6aa190
);
};
export default TrainsPage;
export default function TrainsPage() {
const { data: trains, isLoading } = useTrains();
const deleteTrain = useDeleteTrain();
const [open, setOpen] = useState(false);
if (isLoading) return <div className="p-8">Loading trains...</div>;
return (
<Card>
<CardHeader className="flex flex-row items-center justify-between">
<CardTitle>Trains</CardTitle>
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild><Button size="sm"><Plus className="mr-2 h-4 w-4" />New Train</Button></DialogTrigger>
<DialogContent><DialogHeader><DialogTitle>Create Train</DialogTitle></DialogHeader><CreateTrainForm onSuccess={() => setOpen(false)} /></DialogContent>
</Dialog>
</CardHeader>
<CardContent>
<Table>
<TableHeader><TableRow><TableHead>Number</TableHead><TableHead>Name</TableHead><TableHead>Status</TableHead><TableHead>Capacity</TableHead><TableHead>Actions</TableHead></TableRow></TableHeader>
<TableBody>
{trains?.map(train => (
<TableRow key={train.id}>
<TableCell>{train.trainNumber || train.code}</TableCell>
<TableCell>{train.trainName || '-'}</TableCell>
<TableCell><Badge variant="outline">{train.status}</Badge></TableCell>
<TableCell>{train.capacityTons} t</TableCell>
<TableCell className="flex space-x-2">
<Link to={`/trains/${train.id}`}><Button variant="ghost" size="icon"><Eye className="h-4 w-4" /></Button></Link>
<Button variant="ghost" size="icon" onClick={() => deleteTrain.mutate(train.id)}><Trash2 className="h-4 w-4" /></Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</CardContent>
</Card>
);
}

View File

@@ -0,0 +1,29 @@
import { useWagons } from '@/hooks/useWagons';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
export default function WagonsPage() {
const { data: wagons, isLoading } = useWagons();
if (isLoading) return <div>Loading wagons...</div>;
return (
<Card>
<CardHeader><CardTitle>All Wagons</CardTitle></CardHeader>
<CardContent>
<Table>
<TableHeader><TableRow><TableHead>Number</TableHead><TableHead>Type</TableHead><TableHead>Train</TableHead><TableHead>Status</TableHead></TableRow></TableHeader>
<TableBody>
{wagons?.map(w => (
<TableRow key={w.id}>
<TableCell>{w.wagonNumber}</TableCell>
<TableCell>{w.wagonTypeId}</TableCell>
<TableCell>{w.trainId || 'Unassigned'}</TableCell>
<TableCell><Badge variant="outline">{w.status}</Badge></TableCell>
</TableRow>
))}
</TableBody>
</Table>
</CardContent>
</Card>
);
}

View File

@@ -0,0 +1,26 @@
import { apiClient } from '@/lib/axios';
export interface Cargo {
id: string;
cargoReference: string;
shipmentId: string;
containerId: string;
cargoTypeId?: string;
description?: string;
quantity: number;
weight: number;
volume?: number;
status: 'PENDING' | 'LOADED' | 'IN_TRANSIT' | 'DELIVERED' | 'UNLOADED';
loadedAt?: string;
unloadedAt?: string;
}
export const cargoService = {
getAll: () => apiClient.get<Cargo[]>('/cargoes'),
getByContainer: (containerId: string) => apiClient.get<Cargo[]>(`/cargoes?containerId=${containerId}`),
create: (data: any) => apiClient.post('/cargoes', data),
load: (cargoId: string, quantity: number, weight: number, volume?: number) =>
apiClient.post(`/cargoes/${cargoId}/load`, { quantity, weight, volume }),
deliver: (cargoId: string) => apiClient.post(`/cargoes/${cargoId}/deliver`),
unload: (cargoId: string) => apiClient.post(`/cargoes/${cargoId}/unload`),
};

View File

@@ -0,0 +1,21 @@
import { apiClient } from '@/lib/axios';
export interface Container {
id: string;
containerNumber: string;
containerTypeId: string;
wagonId: string | null;
position: number | null;
tareWeight: number;
maxGrossWeight: number;
sealNumber?: string;
status: string;
}
export const containerService = {
getAll: () => apiClient.get<Container[]>('/containers'),
getByWagon: (wagonId: string) => apiClient.get<Container[]>(`/containers?wagonId=${wagonId}`),
assignToWagon: (containerId: string, wagonId: string, position?: number) =>
apiClient.post(`/containers/${containerId}/assign-wagon`, { wagonId, position }),
unassign: (containerId: string) => apiClient.post(`/containers/${containerId}/unassign-wagon`),
};

View File

@@ -0,0 +1,26 @@
import { apiClient } from '@/lib/axios';
export interface Train {
id: string;
code: string;
capacityTons: number;
trainNumber?: string;
trainName?: string;
routeId?: string;
originStationId?: string;
destinationStationId?: string;
departureTime?: string;
arrivalTime?: string;
locomotiveNumber?: string;
status: string;
remarks?: string;
}
export const trainService = {
getAll: () => apiClient.get<Train[]>('/trains'),
getById: (id: string) => apiClient.get<Train>(`/trains/${id}`),
create: (data: Partial<Train>) => apiClient.post('/trains', data),
update: (id: string, data: Partial<Train>) => apiClient.patch(`/trains/${id}`, data),
delete: (id: string) => apiClient.delete(`/trains/${id}`),
getDetails: (id: string) => apiClient.get(`/trains/${id}/details`),
};

View File

@@ -0,0 +1,26 @@
import { apiClient } from '@/lib/axios';
export interface Wagon {
id: string;
wagonNumber: string;
wagonTypeId: string;
trainId: string | null;
sequenceNumber: number | null;
tareWeight: number;
maxPayloadWeight: number;
status: string;
notes?: string;
}
export const wagonService = {
getAll: () => apiClient.get<Wagon[]>('/wagons'),
getByTrain: (trainId: string) => apiClient.get<Wagon[]>(`/wagons?trainId=${trainId}`),
assignToTrain: (wagonId: string, trainId: string, sequenceNumber?: number) =>
apiClient.post(`/wagons/${wagonId}/assign-train`, { trainId, sequenceNumber }),
unassign: (wagonId: string) => apiClient.post(`/wagons/${wagonId}/unassign-train`),
reorder: (trainId: string, wagonIds: string[]) =>
apiClient.post(`/trains/${trainId}/reorder-wagons`, { wagonIds }),
create: (data: Partial<Wagon>) => apiClient.post('/wagons', data),
update: (id: string, data: Partial<Wagon>) => apiClient.patch(`/wagons/${id}`, data),
};

View File

@@ -0,0 +1,47 @@
import * as React from "react";
import { cva, type VariantProps } from "class-variance-authority";
import { Slot } from "radix-ui";
import { cn } from "@/lib/utils";
const badgeVariants = cva(
"inline-flex w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-full border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
secondary: "bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
destructive:
"bg-destructive text-white focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40 [a&]:hover:bg-destructive/90",
outline:
"border-border text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
ghost: "[a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
link: "text-primary underline-offset-4 [a&]:hover:underline",
},
},
defaultVariants: {
variant: "default",
},
},
);
function Badge({
className,
variant = "default",
asChild = false,
...props
}: React.ComponentProps<"span"> &
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
const Comp = asChild ? Slot.Root : "span";
return (
<Comp
data-slot="badge"
data-variant={variant}
className={cn(badgeVariants({ variant }), className)}
{...props}
/>
);
}
export { Badge, badgeVariants };

View File

@@ -0,0 +1,8 @@
export * from './table';
export * from './badge';
export * from './button';
export * from './dialog';
export * from './input';
export * from './label';
export * from './textarea';
export * from './Breadcrumbs';

View File

@@ -0,0 +1,114 @@
import * as React from "react";
import { cn } from "@/lib/utils";
function Table({ className, ...props }: React.ComponentProps<"table">) {
return (
<div
data-slot="table-container"
className="relative w-full overflow-x-auto"
>
<table
data-slot="table"
className={cn("w-full caption-bottom text-sm", className)}
{...props}
/>
</div>
);
}
function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
return (
<thead
data-slot="table-header"
className={cn("[&_tr]:border-b outline-ring/50", className)}
{...props}
/>
);
}
function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
return (
<tbody
data-slot="table-body"
className={cn("[&_tr:last-child]:border-0", className)}
{...props}
/>
);
}
function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
return (
<tfoot
data-slot="table-footer"
className={cn(
"border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",
className,
)}
{...props}
/>
);
}
function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
return (
<tr
data-slot="table-row"
className={cn(
"border-b transition-colors bg-background hover:bg-muted/50 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted",
className,
)}
{...props}
/>
);
}
function TableHead({ className, ...props }: React.ComponentProps<"th">) {
return (
<th
data-slot="table-head"
className={cn(
"h-10 bg-muted first-of-type:pl-4 last-of-type:pr-4 first-of-type: p-2 py-4 text-left align-middle font-medium whitespace-nowrap text-secondary-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className,
)}
{...props}
/>
);
}
function TableCell({ className, ...props }: React.ComponentProps<"td">) {
return (
<td
data-slot="table-cell"
className={cn(
"p-2 align-middle first-of-type:pl-4 last-of-type:pr-4 whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className,
)}
{...props}
/>
);
}
function TableCaption({
className,
...props
}: React.ComponentProps<"caption">) {
return (
<caption
data-slot="table-caption"
className={cn("mt-4 text-sm text-muted-foreground", className)}
{...props}
/>
);
}
export {
Table,
TableHeader,
TableBody,
TableFooter,
TableHead,
TableRow,
TableCell,
TableCaption,
};

View File

@@ -0,0 +1,24 @@
// vite.config.ts
import path from "node:path";
import { fileURLToPath } from "node:url";
import { defineConfig } from "file:///C:/laragon/www/edr-platform/node_modules/.pnpm/vite@5.4.21_@types+node@20.19.41_lightningcss@1.32.0_terser@5.48.0/node_modules/vite/dist/node/index.js";
import react from "file:///C:/laragon/www/edr-platform/node_modules/.pnpm/@vitejs+plugin-react@4.7.0_vite@5.4.21_@types+node@20.19.41_lightningcss@1.32.0_terser@5.48.0_/node_modules/@vitejs/plugin-react/dist/index.js";
import tailwindcss from "file:///C:/laragon/www/edr-platform/node_modules/.pnpm/@tailwindcss+vite@4.3.0_vite@5.4.21_@types+node@20.19.41_lightningcss@1.32.0_terser@5.48.0_/node_modules/@tailwindcss/vite/dist/index.mjs";
var __vite_injected_original_import_meta_url = "file:///C:/laragon/www/edr-platform/apps/edr-freight-web/portal/vite.config.ts";
var __dirname = path.dirname(fileURLToPath(__vite_injected_original_import_meta_url));
var vite_config_default = defineConfig({
plugins: [react(), tailwindcss()],
resolve: {
alias: {
"@": path.resolve(__dirname, "./src")
}
},
server: {
port: 5173,
host: "0.0.0.0"
}
});
export {
vite_config_default as default
};
//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsidml0ZS5jb25maWcudHMiXSwKICAic291cmNlc0NvbnRlbnQiOiBbImNvbnN0IF9fdml0ZV9pbmplY3RlZF9vcmlnaW5hbF9kaXJuYW1lID0gXCJDOlxcXFxsYXJhZ29uXFxcXHd3d1xcXFxlZHItcGxhdGZvcm1cXFxcYXBwc1xcXFxlZHItZnJlaWdodC13ZWJcXFxccG9ydGFsXCI7Y29uc3QgX192aXRlX2luamVjdGVkX29yaWdpbmFsX2ZpbGVuYW1lID0gXCJDOlxcXFxsYXJhZ29uXFxcXHd3d1xcXFxlZHItcGxhdGZvcm1cXFxcYXBwc1xcXFxlZHItZnJlaWdodC13ZWJcXFxccG9ydGFsXFxcXHZpdGUuY29uZmlnLnRzXCI7Y29uc3QgX192aXRlX2luamVjdGVkX29yaWdpbmFsX2ltcG9ydF9tZXRhX3VybCA9IFwiZmlsZTovLy9DOi9sYXJhZ29uL3d3dy9lZHItcGxhdGZvcm0vYXBwcy9lZHItZnJlaWdodC13ZWIvcG9ydGFsL3ZpdGUuY29uZmlnLnRzXCI7aW1wb3J0IHBhdGggZnJvbSBcIm5vZGU6cGF0aFwiO1xyXG5pbXBvcnQgeyBmaWxlVVJMVG9QYXRoIH0gZnJvbSBcIm5vZGU6dXJsXCI7XHJcblxyXG5pbXBvcnQgeyBkZWZpbmVDb25maWcgfSBmcm9tIFwidml0ZVwiO1xyXG5pbXBvcnQgcmVhY3QgZnJvbSBcIkB2aXRlanMvcGx1Z2luLXJlYWN0XCI7XHJcbmltcG9ydCB0YWlsd2luZGNzcyBmcm9tIFwiQHRhaWx3aW5kY3NzL3ZpdGVcIjtcclxuXHJcbmNvbnN0IF9fZGlybmFtZSA9IHBhdGguZGlybmFtZShmaWxlVVJMVG9QYXRoKGltcG9ydC5tZXRhLnVybCkpO1xyXG5cclxuZXhwb3J0IGRlZmF1bHQgZGVmaW5lQ29uZmlnKHtcclxuICBwbHVnaW5zOiBbcmVhY3QoKSwgdGFpbHdpbmRjc3MoKV0sXHJcbiAgcmVzb2x2ZToge1xyXG4gICAgYWxpYXM6IHtcclxuICAgICAgXCJAXCI6IHBhdGgucmVzb2x2ZShfX2Rpcm5hbWUsIFwiLi9zcmNcIiksXHJcbiAgICB9LFxyXG4gIH0sXHJcbiAgc2VydmVyOiB7XHJcbiAgICBwb3J0OiA1MTczLFxyXG4gICAgaG9zdDogXCIwLjAuMC4wXCIsXHJcbiAgfSxcclxufSk7XHJcbiJdLAogICJtYXBwaW5ncyI6ICI7QUFBcVcsT0FBTyxVQUFVO0FBQ3RYLFNBQVMscUJBQXFCO0FBRTlCLFNBQVMsb0JBQW9CO0FBQzdCLE9BQU8sV0FBVztBQUNsQixPQUFPLGlCQUFpQjtBQUwyTSxJQUFNLDJDQUEyQztBQU9wUixJQUFNLFlBQVksS0FBSyxRQUFRLGNBQWMsd0NBQWUsQ0FBQztBQUU3RCxJQUFPLHNCQUFRLGFBQWE7QUFBQSxFQUMxQixTQUFTLENBQUMsTUFBTSxHQUFHLFlBQVksQ0FBQztBQUFBLEVBQ2hDLFNBQVM7QUFBQSxJQUNQLE9BQU87QUFBQSxNQUNMLEtBQUssS0FBSyxRQUFRLFdBQVcsT0FBTztBQUFBLElBQ3RDO0FBQUEsRUFDRjtBQUFBLEVBQ0EsUUFBUTtBQUFBLElBQ04sTUFBTTtBQUFBLElBQ04sTUFBTTtBQUFBLEVBQ1I7QUFDRixDQUFDOyIsCiAgIm5hbWVzIjogW10KfQo=

View File

@@ -17,20 +17,22 @@
"prepare": "husky"
},
"devDependencies": {
"turbo": "^2.3.0",
"typescript": "^5.5.4",
"prettier": "^3.3.3",
"@commitlint/cli": "^19.5.0",
"@commitlint/config-conventional": "^19.5.0",
"husky": "^9.1.6",
"lint-staged": "^15.2.10",
"@commitlint/cli": "^19.5.0",
"@commitlint/config-conventional": "^19.5.0"
"prettier": "^3.3.3",
"turbo": "^2.3.0",
"typeorm": "0.3.30",
"typescript": "^5.5.4"
},
"pnpm": {
"overrides": {
"date-fns": "^3.6.0",
"pdfjs-dist": "^3.11.174",
"react": "19.2.6",
"react-dom": "19.2.6"
"react-dom": "19.2.6",
"typeorm": "0.3.30"
}
},
"lint-staged": {

25
pnpm-lock.yaml generated
View File

@@ -9,6 +9,7 @@ overrides:
pdfjs-dist: ^3.11.174
react: 19.2.6
react-dom: 19.2.6
typeorm: 0.3.30
importers:
@@ -32,6 +33,9 @@ importers:
turbo:
specifier: ^2.3.0
version: 2.9.14
typeorm:
specifier: 0.3.30
version: 0.3.30(babel-plugin-macros@3.1.0)(pg@8.21.0)(ts-node@10.9.2(@types/node@20.19.41)(typescript@5.9.3))
typescript:
specifier: ^5.5.4
version: 5.9.3
@@ -113,9 +117,6 @@ importers:
rxjs:
specifier: ^7.8.1
version: 7.8.2
typeorm:
specifier: ^0.3.20
version: 0.3.30(babel-plugin-macros@3.1.0)(pg@8.21.0)(ts-node@10.9.2(@types/node@20.19.41)(typescript@5.9.3))
devDependencies:
'@edr/eslint-config':
specifier: workspace:*
@@ -168,6 +169,9 @@ importers:
tsconfig-paths:
specifier: ^4.2.0
version: 4.2.0
typeorm:
specifier: 0.3.30
version: 0.3.30(babel-plugin-macros@3.1.0)(pg@8.21.0)(ts-node@10.9.2(@types/node@20.19.41)(typescript@5.9.3))
typescript:
specifier: ^5.5.4
version: 5.9.3
@@ -219,6 +223,9 @@ importers:
recharts:
specifier: ^3.8.1
version: 3.8.1(@types/react@18.3.29)(react-dom@19.2.6(react@19.2.6))(react-is@19.2.6)(react@19.2.6)(redux@5.0.1)
sonner:
specifier: ^2.0.7
version: 2.0.7(react-dom@19.2.6(react@19.2.6))(react@19.2.6)
tailwind-merge:
specifier: ^3.6.0
version: 3.6.0
@@ -420,7 +427,7 @@ importers:
specifier: ^7.8.1
version: 7.8.2
typeorm:
specifier: ^0.3.20
specifier: 0.3.30
version: 0.3.30(babel-plugin-macros@3.1.0)(pg@8.21.0)(ts-node@10.9.2(@types/node@20.19.41)(typescript@5.9.3))
devDependencies:
'@edr/eslint-config':
@@ -625,7 +632,7 @@ importers:
specifier: ^7.8.1
version: 7.8.2
typeorm:
specifier: ^0.3.20
specifier: 0.3.30
version: 0.3.30(babel-plugin-macros@3.1.0)(pg@8.21.0)(ts-node@10.9.2(@types/node@20.19.41)(typescript@5.9.3))
typescript:
specifier: ^5.5.4
@@ -2052,7 +2059,7 @@ packages:
'@nestjs/core': ^10.0.0 || ^11.0.0
reflect-metadata: ^0.1.13 || ^0.2.0
rxjs: ^7.2.0
typeorm: ^0.3.0 || ^1.0.0-dev
typeorm: 0.3.30
'@noble/ciphers@1.3.0':
resolution: {integrity: sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw==}
@@ -3656,7 +3663,7 @@ packages:
'@tria-plc/iamapi-common': '*'
reflect-metadata: ^0.2.0
rxjs: ^7.8.0
typeorm: ^0.3.0
typeorm: 0.3.30
'@tria-plc/iamapi-common@0.1.6':
resolution: {integrity: sha512-qaCLZ1TgbcQ5XciRuA/aZjRCM/GmGYgcmsyDDIlhiMNw3FL3DCiR/QiFuQpERvV4FqgQNBJg66+S/jXO3I2jbw==, tarball: https://npm.pkg.github.com/download/@tria-plc/iamapi-common/0.1.6/e2a8f3357b650bb9477facae4aaa7044382acebf}
@@ -3677,7 +3684,7 @@ packages:
class-validator: ^0.14.1
reflect-metadata: ^0.2.0
rxjs: ^7.8.0
typeorm: ^0.3.0
typeorm: 0.3.30
'@tria-plc/iamui-common@1.1.1':
resolution: {integrity: sha512-aj9fMxmB/3kwSnN1vl8NvmCrI/1quNjfg9Bb7fJR4HhWEE26foIZC2xeg1ERzQxBll6rMj/R0Zl0+Riv6OONTQ==, tarball: https://npm.pkg.github.com/download/@tria-plc/iamui-common/1.1.1/98fa2e350b807e9d123cab7d75038a027005ef41}
@@ -9840,7 +9847,7 @@ packages:
hasBin: true
peerDependencies:
'@faker-js/faker': '>=8.4.1'
typeorm: ~0.3.0
typeorm: 0.3.30
typeorm@0.3.30:
resolution: {integrity: sha512-8T35PzjefOdqc2ZR9mwLQj0pUGp6lQhMbK2EvVMwJVJWlaoHm0v/Q6dThNOZkFchD+0yMg8gwjKM28ePiLSXSQ==}