Merge branch 'freight/develop' into freight/feature/payment

This commit is contained in:
Eyosiyas Girma
2026-06-06 08:17:17 +03:00
committed by GitHub
92 changed files with 3293 additions and 1845 deletions

View File

@@ -75,7 +75,6 @@ import { CargoesModule } from './modules/cargoes/cargoes.module';
BookingsModule,
FilesModule,
ConsignmentsModule,
TrainsModule,
LocomotivesModule,
WagonTypesModule,
TrainSetsModule,

View File

@@ -0,0 +1,21 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class AddCompanyContactColumns1750000000000 implements MigrationInterface {
name = 'AddCompanyContactColumns1750000000000';
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE freight.companies ADD COLUMN IF NOT EXISTS contact_person_name VARCHAR(100);`);
await queryRunner.query(`ALTER TABLE freight.companies ADD COLUMN IF NOT EXISTS contact_person_phone VARCHAR(20);`);
await queryRunner.query(`ALTER TABLE freight.companies ADD COLUMN IF NOT EXISTS general_manager_name VARCHAR(100);`);
await queryRunner.query(`ALTER TABLE freight.companies ADD COLUMN IF NOT EXISTS general_manager_email VARCHAR(150);`);
await queryRunner.query(`ALTER TABLE freight.companies ADD COLUMN IF NOT EXISTS general_manager_phone VARCHAR(20);`);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE freight.companies DROP COLUMN IF EXISTS general_manager_phone;`);
await queryRunner.query(`ALTER TABLE freight.companies DROP COLUMN IF EXISTS general_manager_email;`);
await queryRunner.query(`ALTER TABLE freight.companies DROP COLUMN IF EXISTS general_manager_name;`);
await queryRunner.query(`ALTER TABLE freight.companies DROP COLUMN IF EXISTS contact_person_phone;`);
await queryRunner.query(`ALTER TABLE freight.companies DROP COLUMN IF EXISTS contact_person_name;`);
}
}

View File

@@ -0,0 +1,127 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class CreateFleetCrudTables1750100000000 implements MigrationInterface {
name = 'CreateFleetCrudTables1750100000000';
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`CREATE SCHEMA IF NOT EXISTS freight`);
await queryRunner.query(`
CREATE TABLE IF NOT EXISTS freight.wagons (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
wagon_number VARCHAR NOT NULL UNIQUE,
wagon_type_id UUID NOT NULL,
train_id UUID,
sequence_number INT,
tare_weight NUMERIC(10, 2) NOT NULL,
max_payload_weight NUMERIC(10, 2) NOT NULL,
status VARCHAR NOT NULL DEFAULT 'AVAILABLE',
notes TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
deleted_at TIMESTAMPTZ
);
`);
await queryRunner.query(`
CREATE TABLE IF NOT EXISTS freight.containers (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
container_number VARCHAR NOT NULL UNIQUE,
container_type_id UUID NOT NULL,
wagon_id UUID,
position INT,
tare_weight NUMERIC(10, 2) NOT NULL,
max_gross_weight NUMERIC(10, 2) NOT NULL,
seal_number VARCHAR,
status VARCHAR NOT NULL DEFAULT 'AVAILABLE',
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
deleted_at TIMESTAMPTZ
);
`);
await queryRunner.query(`
CREATE TABLE IF NOT EXISTS freight.cargoes (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
cargo_reference VARCHAR NOT NULL UNIQUE,
shipment_id UUID NOT NULL,
container_id UUID NOT NULL,
cargo_type_id UUID,
description TEXT,
quantity NUMERIC(12, 3) NOT NULL,
weight NUMERIC(10, 2) NOT NULL,
volume NUMERIC(10, 2),
status VARCHAR NOT NULL DEFAULT 'PENDING',
loaded_at TIMESTAMP,
unloaded_at TIMESTAMP,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
deleted_at TIMESTAMPTZ
);
`);
await queryRunner.query(`CREATE INDEX IF NOT EXISTS "IDX_wagons_train_id" ON freight.wagons (train_id)`);
await queryRunner.query(`CREATE INDEX IF NOT EXISTS "IDX_containers_wagon_id" ON freight.containers (wagon_id)`);
await queryRunner.query(`CREATE INDEX IF NOT EXISTS "IDX_cargoes_container_id" ON freight.cargoes (container_id)`);
await queryRunner.query(`
DO $$ BEGIN
ALTER TABLE freight.wagons
ADD CONSTRAINT "FK_wagons_train_id"
FOREIGN KEY (train_id) REFERENCES freight.trains(id) ON DELETE SET NULL;
EXCEPTION WHEN duplicate_object THEN NULL;
END $$;
`);
await queryRunner.query(`
DO $$ BEGIN
ALTER TABLE freight.wagons
ADD CONSTRAINT "FK_wagons_wagon_type_id"
FOREIGN KEY (wagon_type_id) REFERENCES freight.wagon_types(id);
EXCEPTION WHEN duplicate_object THEN NULL;
END $$;
`);
await queryRunner.query(`
DO $$ BEGIN
ALTER TABLE freight.containers
ADD CONSTRAINT "FK_containers_wagon_id"
FOREIGN KEY (wagon_id) REFERENCES freight.wagons(id) ON DELETE SET NULL;
EXCEPTION WHEN duplicate_object THEN NULL;
END $$;
`);
await queryRunner.query(`
DO $$ BEGIN
ALTER TABLE freight.containers
ADD CONSTRAINT "FK_containers_container_type_id"
FOREIGN KEY (container_type_id) REFERENCES freight.container_types(id);
EXCEPTION WHEN duplicate_object THEN NULL;
END $$;
`);
await queryRunner.query(`
DO $$ BEGIN
ALTER TABLE freight.cargoes
ADD CONSTRAINT "FK_cargoes_container_id"
FOREIGN KEY (container_id) REFERENCES freight.containers(id) ON DELETE RESTRICT;
EXCEPTION WHEN duplicate_object THEN NULL;
END $$;
`);
await queryRunner.query(`
DO $$ BEGIN
ALTER TABLE freight.cargoes
ADD CONSTRAINT "FK_cargoes_cargo_type_id"
FOREIGN KEY (cargo_type_id) REFERENCES freight.cargo_types(id);
EXCEPTION WHEN duplicate_object THEN NULL;
END $$;
`);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`DROP TABLE IF EXISTS freight.cargoes CASCADE`);
await queryRunner.query(`DROP TABLE IF EXISTS freight.containers CASCADE`);
await queryRunner.query(`DROP TABLE IF EXISTS freight.wagons CASCADE`);
}
}

View File

@@ -0,0 +1,46 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class SeedDefaultWagonTypes1750200000000 implements MigrationInterface {
name = 'SeedDefaultWagonTypes1750200000000';
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`
INSERT INTO freight.wagon_types (
code,
name,
capacity_tons,
length_meters,
max_wagons_per_train,
supported_load_types,
is_active
)
VALUES
('NW7', 'Double deck sedan wagon', 22, 26.066, NULL, ARRAY['vehicles', 'sedan'], true),
('NW5', 'Flat wagon (container)', 70, 14.000, 53, ARRAY['container', 'steel', 'machinery'], true),
('PW2', 'Box wagon', 70, 17.066, 18, ARRAY['general cargo', 'break bulk'], true),
('GW2', 'Tank wagon', 70, 12.228, 37, ARRAY['liquid', 'fuel'], true),
('CW4', 'Gondola covered wagon', 70, 13.976, 37, ARRAY['covered bulk cargo'], true),
('CW3', 'Gondola open wagon', 70, 13.976, NULL, ARRAY['open bulk cargo'], true),
('KW2', 'Hopper covered wagon', 69, 16.466, NULL, ARRAY['bulk grains'], true),
('KW3', 'Hopper open wagon', 70, 14.400, NULL, ARRAY['coal', 'bulk cargo'], true),
('NW6', 'Flat wagon (long cargo)', 70, 18.560, NULL, ARRAY['long cargo'], true),
('BW1', 'Refrigerated wagon', 38, 21.996, NULL, ARRAY['refrigerated cargo'], true)
ON CONFLICT (code) DO UPDATE SET
name = EXCLUDED.name,
capacity_tons = EXCLUDED.capacity_tons,
length_meters = EXCLUDED.length_meters,
max_wagons_per_train = EXCLUDED.max_wagons_per_train,
supported_load_types = EXCLUDED.supported_load_types,
is_active = true,
deleted_at = NULL,
updated_at = now();
`);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`
DELETE FROM freight.wagon_types
WHERE code IN ('NW7', 'NW5', 'PW2', 'GW2', 'CW4', 'CW3', 'KW2', 'KW3', 'NW6', 'BW1');
`);
}
}

View File

@@ -7,6 +7,7 @@ import {
ParseUUIDPipe,
Patch,
Post,
Query,
} from '@nestjs/common';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { CreateCargoDto } from './dto/create-cargo.dto';
@@ -28,8 +29,8 @@ export class CargoesController {
@Get()
@ApiOperation({ summary: 'List all cargoes' })
findAll() {
return this.cargoesService.findAll();
findAll(@Query() query: Record<string, string | undefined>) {
return this.cargoesService.findAll(query);
}
@Get(':id')
@@ -67,4 +68,4 @@ export class CargoesController {
deliver(@Param('id', ParseUUIDPipe) id: string, @Body() dto?: DeliverCargoDto) {
return this.cargoesService.deliverCargo(id, dto);
}
}
}

View File

@@ -2,13 +2,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 { CargoType } from '../rule-engine/entities/cargo-type.entity';
import { CargoesController } from './cargoes.controller';
import { CargoesService } from './cargoes.service';
@Module({
imports: [TypeOrmModule.forFeature([Cargo, Container])],
imports: [TypeOrmModule.forFeature([Cargo, Container, CargoType])],
controllers: [CargoesController],
providers: [CargoesService],
exports: [CargoesService],
})
export class CargoesModule {}
export class CargoesModule {}

View File

@@ -1,12 +1,13 @@
import { Injectable, NotFoundException, ConflictException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { FindOptionsOrder, FindOptionsWhere, ILike, 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';
import { CargoType } from '../rule-engine/entities/cargo-type.entity';
@Injectable()
export class CargoesService {
@@ -15,15 +16,64 @@ export class CargoesService {
private readonly cargoRepo: Repository<Cargo>,
@InjectRepository(Container)
private readonly containerRepo: Repository<Container>,
@InjectRepository(CargoType)
private readonly cargoTypeRepo: Repository<CargoType>,
) {}
async create(dto: CreateCargoDto): Promise<Cargo> {
const existing = await this.cargoRepo.findOne({
where: { cargoReference: dto.cargoReference },
});
if (existing) {
throw new ConflictException(`Cargo reference "${dto.cargoReference}" already exists`);
}
const container = await this.containerRepo.findOne({ where: { id: dto.containerId } });
if (!container) {
throw new NotFoundException(`Container ${dto.containerId} not found`);
}
if (dto.cargoTypeId) {
const cargoType = await this.cargoTypeRepo.findOne({
where: { id: dto.cargoTypeId, isActive: true },
});
if (!cargoType) throw new NotFoundException(`Cargo type ${dto.cargoTypeId} not found`);
}
const cargo = this.cargoRepo.create(dto);
return this.cargoRepo.save(cargo);
}
async findAll(): Promise<Cargo[]> {
return this.cargoRepo.find({ order: { cargoReference: 'ASC' } });
async findAll(query: Record<string, string | undefined> = {}): Promise<Cargo[]> {
const where: FindOptionsWhere<Cargo>[] | FindOptionsWhere<Cargo> = [];
const search = query.search?.trim();
const status = query.status?.trim();
const containerId = query.containerId?.trim();
if (search) {
where.push({
cargoReference: ILike(`%${search}%`),
...(status ? { status } : {}),
...(containerId ? { containerId } : {}),
});
where.push({
description: ILike(`%${search}%`),
...(status ? { status } : {}),
...(containerId ? { containerId } : {}),
});
}
const sortBy = ['cargoReference', 'quantity', 'weight', 'volume', 'status'].includes(query.sortBy ?? '')
? (query.sortBy as keyof Cargo)
: 'cargoReference';
const sortOrder = query.sortOrder?.toUpperCase() === 'DESC' ? 'DESC' : 'ASC';
return this.cargoRepo.find({
where: search ? where : { ...(status ? { status } : {}), ...(containerId ? { containerId } : {}) },
order: { [sortBy]: sortOrder } as FindOptionsOrder<Cargo>,
skip: query.page && query.limit ? (Number(query.page) - 1) * Number(query.limit) : undefined,
take: query.limit ? Number(query.limit) : undefined,
});
}
async findById(id: string): Promise<Cargo> {
@@ -34,6 +84,24 @@ export class CargoesService {
async update(id: string, dto: UpdateCargoDto): Promise<Cargo> {
const cargo = await this.findById(id);
if (dto.cargoReference && dto.cargoReference !== cargo.cargoReference) {
const existing = await this.cargoRepo.findOne({
where: { cargoReference: dto.cargoReference },
});
if (existing) {
throw new ConflictException(`Cargo reference "${dto.cargoReference}" already exists`);
}
}
if (dto.containerId) {
const container = await this.containerRepo.findOne({ where: { id: dto.containerId } });
if (!container) throw new NotFoundException(`Container ${dto.containerId} not found`);
}
if (dto.cargoTypeId) {
const cargoType = await this.cargoTypeRepo.findOne({
where: { id: dto.cargoTypeId, isActive: true },
});
if (!cargoType) throw new NotFoundException(`Cargo type ${dto.cargoTypeId} not found`);
}
Object.assign(cargo, dto);
return this.cargoRepo.save(cargo);
}
@@ -101,4 +169,4 @@ export class CargoesService {
return this.cargoRepo.save(cargo);
}
}
}

View File

@@ -53,6 +53,21 @@ export class Company extends BaseEntity {
@Column({ name: 'email', type: 'varchar', length: 150, nullable: true })
email?: string | null;
@Column({ name: 'contact_person_name', type: 'varchar', length: 100, nullable: true })
contactPersonName?: string | null;
@Column({ name: 'contact_person_phone', type: 'varchar', length: 20, nullable: true })
contactPersonPhone?: string | null;
@Column({ name: 'general_manager_name', type: 'varchar', length: 100, nullable: true })
generalManagerName?: string | null;
@Column({ name: 'general_manager_email', type: 'varchar', length: 150, nullable: true })
generalManagerEmail?: string | null;
@Column({ name: 'general_manager_phone', type: 'varchar', length: 20, nullable: true })
generalManagerPhone?: string | null;
@Column({ name: 'website', type: 'varchar', length: 200, nullable: true })
website?: string | null;

View File

@@ -7,6 +7,7 @@ import {
ParseUUIDPipe,
Patch,
Post,
Query,
} from '@nestjs/common';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { CreateContainerDto } from './dto/create-container.dto';
@@ -27,8 +28,8 @@ export class ContainersController {
@Get()
@ApiOperation({ summary: 'List all containers' })
findAll() {
return this.containersService.findAll();
findAll(@Query() query: Record<string, string | undefined>) {
return this.containersService.findAll(query);
}
@Get(':id')
@@ -60,4 +61,4 @@ export class ContainersController {
unassignFromWagon(@Param('id', ParseUUIDPipe) id: string) {
return this.containersService.unassignFromWagon(id);
}
}
}

View File

@@ -3,12 +3,13 @@ import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Container } from './entities/container.entity';
import { Wagon } from '../wagons/entities/wagon.entity';
import { ContainerType } from '../rule-engine/entities/container-type.entity';
import { ContainersController } from './containers.controller';
import { ContainersService } from './containers.service';
@Module({
imports: [TypeOrmModule.forFeature([Container, Wagon])], // ✅ add Wagon
imports: [TypeOrmModule.forFeature([Container, Wagon, ContainerType])],
controllers: [ContainersController],
providers: [ContainersService],
})
export class ContainersModule {}
export class ContainersModule {}

View File

@@ -1,12 +1,13 @@
// 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 { FindOptionsOrder, FindOptionsWhere, ILike, 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';
import { ContainerType } from '../rule-engine/entities/container-type.entity';
@Injectable()
export class ContainersService {
@@ -15,17 +16,61 @@ export class ContainersService {
private readonly containerRepo: Repository<Container>,
@InjectRepository(Wagon)
private readonly wagonRepo: Repository<Wagon>, // ✅ use raw repository
@InjectRepository(ContainerType)
private readonly containerTypeRepo: Repository<ContainerType>,
) {}
async create(dto: CreateContainerDto): Promise<Container> {
const existing = await this.containerRepo.findOne({
where: { containerNumber: dto.containerNumber },
});
if (existing) {
throw new ConflictException(`Container number "${dto.containerNumber}" already exists`);
}
const containerType = await this.containerTypeRepo.findOne({
where: { id: dto.containerTypeId, isActive: true },
});
if (!containerType) {
throw new NotFoundException(`Container type ${dto.containerTypeId} not found`);
}
if (dto.wagonId) {
const wagon = await this.wagonRepo.findOne({ where: { id: dto.wagonId } });
if (!wagon) throw new NotFoundException(`Wagon ${dto.wagonId} not found`);
}
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 findAll(query: Record<string, string | undefined> = {}): Promise<Container[]> {
const where: FindOptionsWhere<Container>[] | FindOptionsWhere<Container> = [];
const search = query.search?.trim();
const status = query.status?.trim();
const wagonId = query.wagonId?.trim();
if (search) {
where.push({
containerNumber: ILike(`%${search}%`),
...(status ? { status } : {}),
...(wagonId ? { wagonId } : {}),
});
}
const sortBy = ['containerNumber', 'tareWeight', 'maxGrossWeight', 'status', 'position'].includes(query.sortBy ?? '')
? (query.sortBy as keyof Container)
: 'containerNumber';
const sortOrder = query.sortOrder?.toUpperCase() === 'DESC' ? 'DESC' : 'ASC';
return this.containerRepo.find({
where: search ? where : { ...(status ? { status } : {}), ...(wagonId ? { wagonId } : {}) },
order: { [sortBy]: sortOrder } as FindOptionsOrder<Container>,
skip: query.page && query.limit ? (Number(query.page) - 1) * Number(query.limit) : undefined,
take: query.limit ? Number(query.limit) : undefined,
});
}
async findById(id: string): Promise<Container> {
@@ -36,9 +81,27 @@ export class ContainersService {
async update(id: string, dto: UpdateContainerDto): Promise<Container> {
const container = await this.findById(id);
if (dto.containerNumber && dto.containerNumber !== container.containerNumber) {
const existing = await this.containerRepo.findOne({
where: { containerNumber: dto.containerNumber },
});
if (existing) {
throw new ConflictException(`Container number "${dto.containerNumber}" already exists`);
}
}
if (dto.containerTypeId) {
const containerType = await this.containerTypeRepo.findOne({
where: { id: dto.containerTypeId, isActive: true },
});
if (!containerType) {
throw new NotFoundException(`Container type ${dto.containerTypeId} not found`);
}
}
if (dto.wagonId) {
const wagon = await this.wagonRepo.findOne({ where: { id: dto.wagonId } });
if (!wagon) throw new NotFoundException(`Wagon ${dto.wagonId} not found`);
}
Object.assign(container, dto);
if (dto.wagonId === undefined) container.wagonId = null;
if (dto.position === undefined) container.position = null;
return this.containerRepo.save(container);
}
@@ -82,4 +145,4 @@ export class ContainersService {
container.status = 'AVAILABLE';
return this.containerRepo.save(container);
}
}
}

View File

@@ -61,10 +61,10 @@ export class CustomersController {
return this.customersService.findById(id);
}
@Get("user/:userId")
findByUserId(@Param("userId", ParseUUIDPipe) userId: string): Promise<any> {
return this.customersService.findByUserId(userId);
}
// @Get("user/:userId")
// findByUserId(@Param("userId", ParseUUIDPipe) userId: string): Promise<any> {
// return this.customersService.findByUserId(userId);
// }
@Patch(":id")
@ApiOperation({ summary: "Update a customer" })

View File

@@ -52,15 +52,15 @@ export class CustomersService {
return customer;
}
async findByUserId(userId: string): Promise<Customer> {
const customer = await this.customersRepository.findByUserId(userId);
// async findByUserId(userId: string): Promise<Customer> {
// const customer = await this.customersRepository.findByUserId(userId);
if (!customer) {
throw new NotFoundException(`Customer with ID ${userId} not found`);
}
// if (!customer) {
// throw new NotFoundException(`Customer with ID ${userId} not found`);
// }
return customer;
}
// return customer;
//}
/** Get customer by email */
async findByEmail(email: string): Promise<Customer> {
@@ -100,16 +100,16 @@ export class CustomersService {
throw new BadRequestException("VAT number must be exactly 10 digits");
}
// Check email conflict
if (dto.email) {
const existing = await this.customersRepository.findByEmail(dto.email);
// // Check email conflict
// if (dto.email) {
// const existing = await this.customersRepository.findByEmail(dto.email);
if (existing && existing.userId !== id) {
throw new ConflictException(
`Customer with email "${dto.email}" already exists`,
);
}
}
// // if (existing && existing.userId !== id) {
// // throw new ConflictException(
// // `Customer with email "${dto.email}" already exists`,
// // );
// // }
// }
const updated = await this.customersRepository.update(id, dto);

View File

@@ -2,7 +2,7 @@
import { Customer } from '../entities/customer.entity';
export class ResponseCustomerDto {
UserId: string;
//UserId: string;
firstName: string;
lastName: string;
email: string;
@@ -30,7 +30,7 @@ export class ResponseCustomerDto {
updatedAt: Date;
constructor(customer: Customer) {
this.UserId = customer.userId;
//this.UserId = customer.userId;
this.firstName = customer.firstName;
this.lastName = customer.lastName;
this.email = customer.email;

View File

@@ -3,12 +3,12 @@ import { Column, Entity, Index } from 'typeorm';
@Entity({ schema: 'freight', name: 'customers' })
@Index(['email'])
@Index(['userId'])
//@Index(['userId'])
@Index(['tinNumber'])
@Index(['fanNumber'])
export class Customer extends BaseEntity {
@Column({ name: 'user_id', type: 'uuid' })
userId!: string;
//@Column({ name: 'user_id', type: 'uuid' })
//userId!: string;
@Column({ name: 'first_name', type: 'varchar', length: 100 })
firstName!: string;

View File

@@ -4,11 +4,6 @@ import { Public } from "@edr/api-common";
import { randomUUID } from "crypto";
import { Response } from "express"
// import * as fs from 'fs';
// import * as path from 'path';
// import Handlebars from 'handlebars';
@Public()
@Controller("payments")
export class PaymentController {
@@ -63,4 +58,4 @@ export class PaymentController {
`);
}
}
}

View File

@@ -1,5 +1,7 @@
import { ApiPropertyOptional } from '@nestjs/swagger';
import { IsDateString, IsOptional, IsUUID } from 'class-validator';
import { IsDateString, IsIn, IsOptional, IsUUID } from 'class-validator';
import { BOOKING_STATUSES } from '../../bookings/entities/booking.entity';
export class GetEligibleContainerBookingsDto {
@ApiPropertyOptional({ format: 'uuid' })
@@ -19,5 +21,6 @@ export class GetEligibleContainerBookingsDto {
@ApiPropertyOptional()
@IsOptional()
@IsIn(BOOKING_STATUSES)
status?: string;
}

View File

@@ -1,14 +1,18 @@
import {
Body,
Controller,
Delete,
Get,
Param,
ParseUUIDPipe,
Patch,
Post,
Query,
} from "@nestjs/common";
import { ApiOperation, ApiTags } from "@nestjs/swagger";
import { CreateTrainDto } from "./dto/create-train.dto";
import { UpdateTrainDto } from "./dto/update-train.dto";
import { TrainsService } from "./trains.service";
@ApiTags("trains")
@@ -24,8 +28,8 @@ export class TrainsController {
@Get()
@ApiOperation({ summary: "List all trains" })
findAll() {
return this.trainsService.findAll();
findAll(@Query() query: Record<string, string | undefined>) {
return this.trainsService.findAll(query);
}
@Get(":id")
@@ -33,4 +37,16 @@ export class TrainsController {
findOne(@Param("id", ParseUUIDPipe) id: string) {
return this.trainsService.findById(id);
}
@Patch(":id")
@ApiOperation({ summary: "Update a train" })
update(@Param("id", ParseUUIDPipe) id: string, @Body() dto: UpdateTrainDto) {
return this.trainsService.update(id, dto);
}
@Delete(":id")
@ApiOperation({ summary: "Delete a train" })
remove(@Param("id", ParseUUIDPipe) id: string) {
return this.trainsService.remove(id);
}
}

View File

@@ -1,6 +1,6 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { FindOptionsOrder, FindOptionsWhere, ILike, Repository } from 'typeorm';
import { CreateTrainDto } from './dto/create-train.dto';
import { UpdateTrainDto } from './dto/update-train.dto';
import { Train } from './entities/train.entity';
@@ -17,8 +17,28 @@ export class TrainsService {
return this.trainRepo.save(train);
}
findAll(): Promise<Train[]> {
return this.trainRepo.find({ order: { code: 'ASC' } });
findAll(query: Record<string, string | undefined> = {}): Promise<Train[]> {
const where: FindOptionsWhere<Train>[] | FindOptionsWhere<Train> = [];
const search = query.search?.trim();
const status = query.status?.trim();
if (search) {
where.push({ code: ILike(`%${search}%`), ...(status ? { status: status as Train['status'] } : {}) });
where.push({ trainNumber: ILike(`%${search}%`), ...(status ? { status: status as Train['status'] } : {}) });
where.push({ trainName: ILike(`%${search}%`), ...(status ? { status: status as Train['status'] } : {}) });
}
const sortBy = ['code', 'trainNumber', 'trainName', 'capacityTons', 'status'].includes(query.sortBy ?? '')
? (query.sortBy as keyof Train)
: 'code';
const sortOrder = query.sortOrder?.toUpperCase() === 'DESC' ? 'DESC' : 'ASC';
return this.trainRepo.find({
where: search ? where : status ? { status: status as Train['status'] } : {},
order: { [sortBy]: sortOrder } as FindOptionsOrder<Train>,
skip: query.page && query.limit ? (Number(query.page) - 1) * Number(query.limit) : undefined,
take: query.limit ? Number(query.limit) : undefined,
});
}
async findById(id: string): Promise<Train> {
@@ -38,4 +58,4 @@ export class TrainsService {
const train = await this.findById(id);
await this.trainRepo.remove(train);
}
}
}

View File

@@ -0,0 +1,16 @@
import { Controller, Get } from '@nestjs/common';
import { ApiTags, ApiOperation } from '@nestjs/swagger';
import { WagonTypesService } from './wagon-types.service';
import { WagonType } from './entities/wagon-type.entity';
@ApiTags('Wagon Types')
@Controller('wagon-types')
export class WagonTypesController {
constructor(private readonly wagonTypesService: WagonTypesService) {}
@Get()
@ApiOperation({ summary: 'Get all active wagon types' })
async findAll(): Promise<WagonType[]> {
return this.wagonTypesService.findAll();
}
}

View File

@@ -2,11 +2,13 @@ import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { WagonType } from './entities/wagon-type.entity';
import { WagonTypesController } from './wagon-types.controller';
import { WagonTypesRepository } from './wagon-types.repository';
import { WagonTypesService } from './wagon-types.service';
@Module({
imports: [TypeOrmModule.forFeature([WagonType])],
controllers: [WagonTypesController],
providers: [WagonTypesRepository, WagonTypesService],
exports: [WagonTypesRepository, WagonTypesService],
})

View File

@@ -7,6 +7,13 @@ import { WagonTypesRepository } from './wagon-types.repository';
export class WagonTypesService {
constructor(private readonly wagonTypesRepository: WagonTypesRepository) {}
async findAll(): Promise<WagonType[]> {
return this.wagonTypesRepository.findAll({
where: { isActive: true },
order: { code: 'ASC' },
});
}
async findByCode(code: string): Promise<WagonType> {
const [wagonType] = await this.wagonTypesRepository.findAll({ where: { code } });

View File

@@ -7,6 +7,7 @@ import {
ParseUUIDPipe,
Patch,
Post,
Query,
} from '@nestjs/common';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { CreateWagonDto } from './dto/create-wagon.dto';
@@ -28,8 +29,8 @@ export class WagonsController {
@Get()
@ApiOperation({ summary: 'List all wagons' })
findAll() {
return this.wagonsService.findAll();
findAll(@Query() query: Record<string, string | undefined>) {
return this.wagonsService.findAll(query);
}
@Get(':id')
@@ -73,4 +74,4 @@ export class TrainWagonsReorderController {
reorder(@Param('trainId', ParseUUIDPipe) trainId: string, @Body() dto: ReorderWagonsDto) {
return this.wagonsService.reorderWagons(trainId, dto);
}
}
}

View File

@@ -1,6 +1,6 @@
import { Injectable, NotFoundException, ConflictException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, DataSource } from 'typeorm';
import { Repository, DataSource, FindOptionsOrder, FindOptionsWhere, ILike } 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';
@@ -26,8 +26,31 @@ export class WagonsService {
return this.wagonRepo.save(wagon);
}
async findAll(): Promise<Wagon[]> {
return this.wagonRepo.find({ order: { wagonNumber: 'ASC' } });
async findAll(query: Record<string, string | undefined> = {}): Promise<Wagon[]> {
const where: FindOptionsWhere<Wagon>[] | FindOptionsWhere<Wagon> = [];
const search = query.search?.trim();
const status = query.status?.trim();
const trainId = query.trainId?.trim();
if (search) {
where.push({
wagonNumber: ILike(`%${search}%`),
...(status ? { status } : {}),
...(trainId ? { trainId } : {}),
});
}
const sortBy = ['wagonNumber', 'tareWeight', 'maxPayloadWeight', 'status', 'sequenceNumber'].includes(query.sortBy ?? '')
? (query.sortBy as keyof Wagon)
: 'wagonNumber';
const sortOrder = query.sortOrder?.toUpperCase() === 'DESC' ? 'DESC' : 'ASC';
return this.wagonRepo.find({
where: search ? where : { ...(status ? { status } : {}), ...(trainId ? { trainId } : {}) },
order: { [sortBy]: sortOrder } as FindOptionsOrder<Wagon>,
skip: query.page && query.limit ? (Number(query.page) - 1) * Number(query.limit) : undefined,
take: query.limit ? Number(query.limit) : undefined,
});
}
async findById(id: string): Promise<Wagon> {
@@ -39,8 +62,6 @@ export class WagonsService {
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);
}
@@ -98,4 +119,4 @@ export class WagonsService {
await queryRunner.release();
}
}
}
}

View File

@@ -0,0 +1,25 @@
const { Client } = require('pg');
(async function createSchema(){
const client = new Client({
host: 'localhost',
port: 5432,
user: 'postgres',
password: '',
database: 'edr_freight',
});
try {
console.log('Connecting to Postgres...');
await client.connect();
console.log('Creating schema freight if not exists...');
await client.query('CREATE SCHEMA IF NOT EXISTS freight');
console.log('Schema ensured.');
await client.end();
process.exit(0);
} catch (err) {
console.error('Failed to create schema:', err);
try { await client.end(); } catch {}
process.exit(1);
}
})();

View File

@@ -0,0 +1,27 @@
import { Client } from 'pg';
async function createSchema() {
const client = new Client({
host: 'localhost',
port: 5432,
user: 'postgres',
password: '',
database: 'edr_freight',
});
try {
console.log('Connecting to Postgres...');
await client.connect();
console.log('Creating schema freight if not exists...');
await client.query('CREATE SCHEMA IF NOT EXISTS freight');
console.log('Schema ensured.');
await client.end();
process.exit(0);
} catch (err) {
console.error('Failed to create schema:', err);
try { await client.end(); } catch {}
process.exit(1);
}
}
createSchema();

View File

@@ -0,0 +1,21 @@
import { AppDataSource } from '../data-source';
async function runMigrations() {
try {
console.log('Initializing datasource...');
await AppDataSource.initialize();
console.log('Datasource initialized. Running migrations...');
const migrations = await AppDataSource.runMigrations();
console.log(`Applied ${migrations.length} migrations.`);
await AppDataSource.destroy();
process.exit(0);
} catch (err) {
console.error('Migration run failed:', err);
try {
await AppDataSource.destroy();
} catch {}
process.exit(1);
}
}
runMigrations();

View File

@@ -4,7 +4,11 @@ import { DataSource } from "typeorm";
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";
import {
Company,
CompanyStatus,
CompanyType,
} 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";
@@ -14,7 +18,8 @@ import { ContainerType } from "../modules/rule-engine/entities/container-type.en
const SEED_FLAG = "SEED_DEMO_BOOKINGS";
const SERVICE_TYPE_CODE = "RAIL_CONTAINER";
const CUSTOMER_EMAIL = "train-scheduling-demo@edr.local";
const COMPANY_EMAIL = "train-scheduling-demo@edr.local";
const COMPANY_TIN = "1234567890";
const YARDS = [
{ code: "DJIBOUTI", label: "Djibouti", country: "Djibouti", displayOrder: 1 },
@@ -183,39 +188,35 @@ export class DemoBookingsSeeder {
{ conflictPaths: { code: true } },
);
await manager.getRepository(Customer).upsert(
await manager.getRepository(Company).upsert(
{
userId: "00000000-0000-0000-0000-000000000111",
firstName: "Train",
lastName: "Scheduling",
email: CUSTOMER_EMAIL,
phone: "251900000001",
companyName: "Train Scheduling Demo Customer",
companyEmail: CUSTOMER_EMAIL,
companyPhone: "251900000001",
companyLocation: "Addis Ababa",
companyAddress: "Demo Address",
customerType: "DEMO",
status: "ACTIVE",
contactPersonName: "Train Scheduling",
contactPersonPhone: "251900000001",
tinNumber: "1234567890",
name: "Train Scheduling Demo Customer",
type: CompanyType.Customer,
status: CompanyStatus.Active,
tin: COMPANY_TIN,
vatNumber: "1234567890",
fanNumber: "1234567890123456",
country: "Ethiopia",
address: "Demo Address",
phone: "251900000001",
email: COMPANY_EMAIL,
website: null,
contactPersonName: "Train Scheduling",
contactPersonPhone: "251900000001",
generalManagerName: "Demo Manager",
generalManagerEmail: CUSTOMER_EMAIL,
generalManagerEmail: COMPANY_EMAIL,
generalManagerPhone: "251900000001",
},
{ conflictPaths: { email: true } },
{ conflictPaths: { tin: true } },
);
const [serviceType, customer, yards, containerTypes] = await Promise.all([
const [serviceType, company, yards, containerTypes] = await Promise.all([
manager
.getRepository(ServiceType)
.findOneByOrFail({ code: SERVICE_TYPE_CODE }),
manager
.getRepository(Customer)
.findOneByOrFail({ email: CUSTOMER_EMAIL }),
.getRepository(Company)
.findOneByOrFail({ tin: COMPANY_TIN }),
manager.getRepository(Yard).find(),
manager.getRepository(ContainerType).find(),
]);
@@ -247,7 +248,7 @@ export class DemoBookingsSeeder {
await manager.getRepository(Booking).upsert(
{
reference: demoBooking.reference,
companyId: customer.id,
companyId: company.id,
status: "APPROVED",
scheduledDate: new Date(demoBooking.scheduledDate),
totalAmount: 0,