mirror of
https://github.com/Tria-plc/edr-platform.git
synced 2026-08-27 00:52:50 +00:00
Rule engine UI
This commit is contained in:
@@ -18,6 +18,7 @@
|
||||
"@nestjs/common": "^11.0.0",
|
||||
"@nestjs/config": "^4.0.0",
|
||||
"@nestjs/core": "^11.0.0",
|
||||
"@nestjs/mapped-types": "^2.1.1",
|
||||
"@nestjs/microservices": "^11.0.0",
|
||||
"@nestjs/platform-express": "^11.0.0",
|
||||
"@nestjs/swagger": "^11.4.2",
|
||||
|
||||
206
apps/edr-freight-api/pnpm-lock.yaml
generated
Normal file
206
apps/edr-freight-api/pnpm-lock.yaml
generated
Normal file
@@ -0,0 +1,206 @@
|
||||
lockfileVersion: '9.0'
|
||||
|
||||
settings:
|
||||
autoInstallPeers: true
|
||||
excludeLinksFromLockfile: false
|
||||
|
||||
importers:
|
||||
|
||||
.:
|
||||
dependencies:
|
||||
'@edr/api-common':
|
||||
specifier: workspace:*
|
||||
version: link:../../packages/api-common
|
||||
'@edr/types':
|
||||
specifier: workspace:*
|
||||
version: link:../../packages/types
|
||||
'@nestjs/common':
|
||||
specifier: ^11.0.0
|
||||
version: 11.1.24(reflect-metadata@0.2.2)(rxjs@7.8.2)
|
||||
'@nestjs/mapped-types':
|
||||
specifier: ^2.1.1
|
||||
version: 2.1.1(@nestjs/common@11.1.24(reflect-metadata@0.2.2)(rxjs@7.8.2))(reflect-metadata@0.2.2)
|
||||
reflect-metadata:
|
||||
specifier: ^0.2.2
|
||||
version: 0.2.2
|
||||
rxjs:
|
||||
specifier: ^7.8.1
|
||||
version: 7.8.2
|
||||
devDependencies:
|
||||
'@edr/eslint-config':
|
||||
specifier: workspace:*
|
||||
version: link:../../packages/config/eslint-config
|
||||
'@edr/tsconfig':
|
||||
specifier: workspace:*
|
||||
version: link:../../packages/config/tsconfig
|
||||
|
||||
packages:
|
||||
|
||||
'@borewit/text-codec@0.2.2':
|
||||
resolution: {integrity: sha512-DDaRehssg1aNrH4+2hnj1B7vnUGEjU6OIlyRdkMd0aUdIUvKXrJfXsy8LVtXAy7DRvYVluWbMspsRhz2lcW0mQ==}
|
||||
|
||||
'@lukeed/csprng@1.1.0':
|
||||
resolution: {integrity: sha512-Z7C/xXCiGWsg0KuKsHTKJxbWhpI3Vs5GwLfOean7MGyVFGqdRgBbAjOCh6u4bbjPc/8MJ2pZmK/0DLdCbivLDA==}
|
||||
engines: {node: '>=8'}
|
||||
|
||||
'@nestjs/common@11.1.24':
|
||||
resolution: {integrity: sha512-9zHxaDDM+oXW9As6UsP5yYB+UqczBmpeSCIFWdPEtEukMnZhxODG1BBjaUcdBB8Sc1uzojSJSJlp3yFp853t1g==}
|
||||
peerDependencies:
|
||||
class-transformer: '>=0.4.1'
|
||||
class-validator: '>=0.13.2'
|
||||
reflect-metadata: ^0.1.12 || ^0.2.0
|
||||
rxjs: ^7.1.0
|
||||
peerDependenciesMeta:
|
||||
class-transformer:
|
||||
optional: true
|
||||
class-validator:
|
||||
optional: true
|
||||
|
||||
'@nestjs/mapped-types@2.1.1':
|
||||
resolution: {integrity: sha512-SCCoMEJ6jdeI5h/N+KCVF1+pmg/hmEkNA5nHTS8Gvww7T/LCl4o1gFLinw2iQ60w7slFkszHcGLKGdazVI4F8A==}
|
||||
peerDependencies:
|
||||
'@nestjs/common': ^10.0.0 || ^11.0.0
|
||||
class-transformer: ^0.4.0 || ^0.5.0
|
||||
class-validator: ^0.13.0 || ^0.14.0 || ^0.15.0
|
||||
reflect-metadata: ^0.1.12 || ^0.2.0
|
||||
peerDependenciesMeta:
|
||||
class-transformer:
|
||||
optional: true
|
||||
class-validator:
|
||||
optional: true
|
||||
|
||||
'@tokenizer/inflate@0.4.1':
|
||||
resolution: {integrity: sha512-2mAv+8pkG6GIZiF1kNg1jAjh27IDxEPKwdGul3snfztFerfPGI1LjDezZp3i7BElXompqEtPmoPx6c2wgtWsOA==}
|
||||
engines: {node: '>=18'}
|
||||
|
||||
'@tokenizer/token@0.3.0':
|
||||
resolution: {integrity: sha512-OvjF+z51L3ov0OyAU0duzsYuvO01PH7x4t6DJx+guahgTnBHkhJdG7soQeTSFLWN3efnHyibZ4Z8l2EuWwJN3A==}
|
||||
|
||||
debug@4.4.3:
|
||||
resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==}
|
||||
engines: {node: '>=6.0'}
|
||||
peerDependencies:
|
||||
supports-color: '*'
|
||||
peerDependenciesMeta:
|
||||
supports-color:
|
||||
optional: true
|
||||
|
||||
file-type@21.3.4:
|
||||
resolution: {integrity: sha512-Ievi/yy8DS3ygGvT47PjSfdFoX+2isQueoYP1cntFW1JLYAuS4GD7NUPGg4zv2iZfV52uDyk5w5Z0TdpRS6Q1g==}
|
||||
engines: {node: '>=20'}
|
||||
|
||||
ieee754@1.2.1:
|
||||
resolution: {integrity: sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==}
|
||||
|
||||
iterare@1.2.1:
|
||||
resolution: {integrity: sha512-RKYVTCjAnRthyJes037NX/IiqeidgN1xc3j1RjFfECFp28A1GVwK9nA+i0rJPaHqSZwygLzRnFlzUuHFoWWy+Q==}
|
||||
engines: {node: '>=6'}
|
||||
|
||||
load-esm@1.0.3:
|
||||
resolution: {integrity: sha512-v5xlu8eHD1+6r8EHTg6hfmO97LN8ugKtiXcy5e6oN72iD2r6u0RPfLl6fxM+7Wnh2ZRq15o0russMst44WauPA==}
|
||||
engines: {node: '>=13.2.0'}
|
||||
|
||||
ms@2.1.3:
|
||||
resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}
|
||||
|
||||
reflect-metadata@0.2.2:
|
||||
resolution: {integrity: sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==}
|
||||
|
||||
rxjs@7.8.2:
|
||||
resolution: {integrity: sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==}
|
||||
|
||||
strtok3@10.3.5:
|
||||
resolution: {integrity: sha512-ki4hZQfh5rX0QDLLkOCj+h+CVNkqmp/CMf8v8kZpkNVK6jGQooMytqzLZYUVYIZcFZ6yDB70EfD8POcFXiF5oA==}
|
||||
engines: {node: '>=18'}
|
||||
|
||||
token-types@6.1.2:
|
||||
resolution: {integrity: sha512-dRXchy+C0IgK8WPC6xvCHFRIWYUbqqdEIKPaKo/AcTUNzwLTK6AH7RjdLWsEZcAN/TBdtfUw3PYEgPr5VPr6ww==}
|
||||
engines: {node: '>=14.16'}
|
||||
|
||||
tslib@2.8.1:
|
||||
resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==}
|
||||
|
||||
uid@2.0.2:
|
||||
resolution: {integrity: sha512-u3xV3X7uzvi5b1MncmZo3i2Aw222Zk1keqLA1YkHldREkAhAqi65wuPfe7lHx8H/Wzy+8CE7S7uS3jekIM5s8g==}
|
||||
engines: {node: '>=8'}
|
||||
|
||||
uint8array-extras@1.5.0:
|
||||
resolution: {integrity: sha512-rvKSBiC5zqCCiDZ9kAOszZcDvdAHwwIKJG33Ykj43OKcWsnmcBRL09YTU4nOeHZ8Y2a7l1MgTd08SBe9A8Qj6A==}
|
||||
engines: {node: '>=18'}
|
||||
|
||||
snapshots:
|
||||
|
||||
'@borewit/text-codec@0.2.2': {}
|
||||
|
||||
'@lukeed/csprng@1.1.0': {}
|
||||
|
||||
'@nestjs/common@11.1.24(reflect-metadata@0.2.2)(rxjs@7.8.2)':
|
||||
dependencies:
|
||||
file-type: 21.3.4
|
||||
iterare: 1.2.1
|
||||
load-esm: 1.0.3
|
||||
reflect-metadata: 0.2.2
|
||||
rxjs: 7.8.2
|
||||
tslib: 2.8.1
|
||||
uid: 2.0.2
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
'@nestjs/mapped-types@2.1.1(@nestjs/common@11.1.24(reflect-metadata@0.2.2)(rxjs@7.8.2))(reflect-metadata@0.2.2)':
|
||||
dependencies:
|
||||
'@nestjs/common': 11.1.24(reflect-metadata@0.2.2)(rxjs@7.8.2)
|
||||
reflect-metadata: 0.2.2
|
||||
|
||||
'@tokenizer/inflate@0.4.1':
|
||||
dependencies:
|
||||
debug: 4.4.3
|
||||
token-types: 6.1.2
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
'@tokenizer/token@0.3.0': {}
|
||||
|
||||
debug@4.4.3:
|
||||
dependencies:
|
||||
ms: 2.1.3
|
||||
|
||||
file-type@21.3.4:
|
||||
dependencies:
|
||||
'@tokenizer/inflate': 0.4.1
|
||||
strtok3: 10.3.5
|
||||
token-types: 6.1.2
|
||||
uint8array-extras: 1.5.0
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
ieee754@1.2.1: {}
|
||||
|
||||
iterare@1.2.1: {}
|
||||
|
||||
load-esm@1.0.3: {}
|
||||
|
||||
ms@2.1.3: {}
|
||||
|
||||
reflect-metadata@0.2.2: {}
|
||||
|
||||
rxjs@7.8.2:
|
||||
dependencies:
|
||||
tslib: 2.8.1
|
||||
|
||||
strtok3@10.3.5:
|
||||
dependencies:
|
||||
'@tokenizer/token': 0.3.0
|
||||
|
||||
token-types@6.1.2:
|
||||
dependencies:
|
||||
'@borewit/text-codec': 0.2.2
|
||||
'@tokenizer/token': 0.3.0
|
||||
ieee754: 1.2.1
|
||||
|
||||
tslib@2.8.1: {}
|
||||
|
||||
uid@2.0.2:
|
||||
dependencies:
|
||||
'@lukeed/csprng': 1.1.0
|
||||
|
||||
uint8array-extras@1.5.0: {}
|
||||
@@ -18,11 +18,11 @@ import { NotificationsModule } from "./modules/notifications/notifications.modul
|
||||
import { FileUploadSettingsModule } from "./modules/file-upload-settings/file-upload-settings.module";
|
||||
import { DropdownSettingsModule } from "./modules/dropdown-settings/dropdown-settings.module";
|
||||
import { OtpModule } from './modules/otp/otp.module';
|
||||
import { DropdownSettingsService } from "./modules/dropdown-settings/dropdown-settings.service";
|
||||
import { ServiceTypesModule } from "./modules/service-types/service-types.module";
|
||||
import { CargoTypesModule } from "./modules/cargo-types/cargo-types.module";
|
||||
import { BackofficeModule } from "./modules/backoffice/backoffice.module";
|
||||
import { EdrOrgSeeder } from "./seed/edr-org.seeder";
|
||||
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule.forRoot({
|
||||
@@ -47,6 +47,8 @@ import { EdrOrgSeeder } from "./seed/edr-org.seeder";
|
||||
FileUploadSettingsModule,
|
||||
DropdownSettingsModule,
|
||||
OtpModule,
|
||||
ServiceTypesModule,
|
||||
CargoTypesModule,
|
||||
BackofficeModule,
|
||||
],
|
||||
providers: [EdrOrgSeeder],
|
||||
@@ -55,7 +57,7 @@ export class AppModule implements OnApplicationBootstrap {
|
||||
constructor(
|
||||
private readonly seeder: DataSeeder,
|
||||
private readonly edrOrgSeeder: EdrOrgSeeder,
|
||||
) {}
|
||||
) { }
|
||||
|
||||
async onApplicationBootstrap() {
|
||||
await this.seeder.run();
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
import { MigrationInterface, QueryRunner, Table, TableIndex, TableForeignKey } from "typeorm";
|
||||
|
||||
export class AddServiceTypesAndCargoTypes1748427600000 implements MigrationInterface {
|
||||
name = "AddServiceTypesAndCargoTypes1748427600000";
|
||||
|
||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||
// Create service_types table
|
||||
await queryRunner.createTable(
|
||||
new Table({
|
||||
name: "service_types",
|
||||
schema: "freight",
|
||||
columns: [
|
||||
{
|
||||
name: "id",
|
||||
type: "uuid",
|
||||
isPrimary: true,
|
||||
generationStrategy: "uuid",
|
||||
default: "uuid_generate_v4()",
|
||||
},
|
||||
{
|
||||
name: "service_name",
|
||||
type: "varchar",
|
||||
length: "255",
|
||||
isNullable: false,
|
||||
},
|
||||
{
|
||||
name: "description",
|
||||
type: "text",
|
||||
isNullable: true,
|
||||
},
|
||||
{
|
||||
name: "can_be_booked_alone",
|
||||
type: "boolean",
|
||||
default: true,
|
||||
isNullable: false,
|
||||
},
|
||||
{
|
||||
name: "includes_first_mile",
|
||||
type: "boolean",
|
||||
default: false,
|
||||
isNullable: false,
|
||||
},
|
||||
{
|
||||
name: "includes_last_mile",
|
||||
type: "boolean",
|
||||
default: false,
|
||||
isNullable: false,
|
||||
},
|
||||
{
|
||||
name: "includes_customs",
|
||||
type: "boolean",
|
||||
default: false,
|
||||
isNullable: false,
|
||||
},
|
||||
{
|
||||
name: "priority_bonus_points",
|
||||
type: "int",
|
||||
default: 0,
|
||||
isNullable: false,
|
||||
},
|
||||
{
|
||||
name: "is_active",
|
||||
type: "boolean",
|
||||
default: true,
|
||||
isNullable: false,
|
||||
},
|
||||
{
|
||||
name: "display_order",
|
||||
type: "int",
|
||||
default: 1,
|
||||
isNullable: false,
|
||||
},
|
||||
{
|
||||
name: "created_at",
|
||||
type: "timestamptz",
|
||||
default: "now()",
|
||||
isNullable: false,
|
||||
},
|
||||
{
|
||||
name: "updated_at",
|
||||
type: "timestamptz",
|
||||
default: "now()",
|
||||
isNullable: false,
|
||||
},
|
||||
{
|
||||
name: "deleted_at",
|
||||
type: "timestamptz",
|
||||
isNullable: true,
|
||||
},
|
||||
],
|
||||
}),
|
||||
true,
|
||||
);
|
||||
|
||||
// Create indexes for service_types
|
||||
await queryRunner.createIndex(
|
||||
"freight.service_types",
|
||||
new TableIndex({
|
||||
name: "IDX_SERVICE_TYPES_IS_ACTIVE",
|
||||
columnNames: ["is_active"],
|
||||
}),
|
||||
);
|
||||
await queryRunner.createIndex(
|
||||
"freight.service_types",
|
||||
new TableIndex({
|
||||
name: "IDX_SERVICE_TYPES_DISPLAY_ORDER",
|
||||
columnNames: ["display_order"],
|
||||
}),
|
||||
);
|
||||
|
||||
// Create cargo_types table
|
||||
await queryRunner.createTable(
|
||||
new Table({
|
||||
name: "cargo_types",
|
||||
schema: "freight",
|
||||
columns: [
|
||||
{
|
||||
name: "id",
|
||||
type: "uuid",
|
||||
isPrimary: true,
|
||||
generationStrategy: "uuid",
|
||||
default: "uuid_generate_v4()",
|
||||
},
|
||||
{
|
||||
name: "cargo_type_name",
|
||||
type: "varchar",
|
||||
length: "255",
|
||||
isNullable: false,
|
||||
},
|
||||
{
|
||||
name: "parent_group_id",
|
||||
type: "uuid",
|
||||
isNullable: true,
|
||||
},
|
||||
{
|
||||
name: "show_free_text_box",
|
||||
type: "boolean",
|
||||
default: false,
|
||||
isNullable: false,
|
||||
},
|
||||
{
|
||||
name: "requires_director_approval",
|
||||
type: "boolean",
|
||||
default: false,
|
||||
isNullable: false,
|
||||
},
|
||||
{
|
||||
name: "is_active",
|
||||
type: "boolean",
|
||||
default: true,
|
||||
isNullable: false,
|
||||
},
|
||||
{
|
||||
name: "display_order",
|
||||
type: "int",
|
||||
default: 1,
|
||||
isNullable: false,
|
||||
},
|
||||
{
|
||||
name: "created_at",
|
||||
type: "timestamptz",
|
||||
default: "now()",
|
||||
isNullable: false,
|
||||
},
|
||||
{
|
||||
name: "updated_at",
|
||||
type: "timestamptz",
|
||||
default: "now()",
|
||||
isNullable: false,
|
||||
},
|
||||
{
|
||||
name: "deleted_at",
|
||||
type: "timestamptz",
|
||||
isNullable: true,
|
||||
},
|
||||
],
|
||||
}),
|
||||
true,
|
||||
);
|
||||
|
||||
// Create indexes for cargo_types
|
||||
await queryRunner.createIndex(
|
||||
"freight.cargo_types",
|
||||
new TableIndex({
|
||||
name: "IDX_CARGO_TYPES_IS_ACTIVE",
|
||||
columnNames: ["is_active"],
|
||||
}),
|
||||
);
|
||||
await queryRunner.createIndex(
|
||||
"freight.cargo_types",
|
||||
new TableIndex({
|
||||
name: "IDX_CARGO_TYPES_DISPLAY_ORDER",
|
||||
columnNames: ["display_order"],
|
||||
}),
|
||||
);
|
||||
await queryRunner.createIndex(
|
||||
"freight.cargo_types",
|
||||
new TableIndex({
|
||||
name: "IDX_CARGO_TYPES_PARENT_GROUP_ID",
|
||||
columnNames: ["parent_group_id"],
|
||||
}),
|
||||
);
|
||||
|
||||
// Create self-referencing foreign key for cargo_types
|
||||
await queryRunner.createForeignKey(
|
||||
"freight.cargo_types",
|
||||
new TableForeignKey({
|
||||
name: "FK_CARGO_TYPES_PARENT_GROUP",
|
||||
columnNames: ["parent_group_id"],
|
||||
referencedSchema: "freight",
|
||||
referencedTableName: "cargo_types",
|
||||
referencedColumnNames: ["id"],
|
||||
onDelete: "SET NULL",
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||
// Drop foreign key first
|
||||
await queryRunner.dropForeignKey("freight.cargo_types", "FK_CARGO_TYPES_PARENT_GROUP");
|
||||
|
||||
// Drop cargo_types table
|
||||
await queryRunner.dropTable("freight.cargo_types", true);
|
||||
|
||||
// Drop service_types table
|
||||
await queryRunner.dropTable("freight.service_types", true);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { PartialType } from "@nestjs/swagger";
|
||||
import { PartialType } from "@nestjs/mapped-types";
|
||||
|
||||
import { CreateBookingDto } from "./create-booking.dto";
|
||||
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
HttpCode,
|
||||
HttpStatus,
|
||||
Param,
|
||||
ParseUUIDPipe,
|
||||
Patch,
|
||||
Post,
|
||||
Query,
|
||||
} from "@nestjs/common";
|
||||
import { ApiBearerAuth, ApiOperation, ApiTags } from "@nestjs/swagger";
|
||||
|
||||
import { CargoTypesService } from "./cargo-types.service";
|
||||
import { CreateCargoTypeDto } from "./dto/create-cargo-type.dto";
|
||||
import { FilterCargoTypeDto } from "./dto/filter-cargo-type.dto";
|
||||
import { UpdateCargoTypeDto } from "./dto/update-cargo-type.dto";
|
||||
|
||||
@ApiTags("cargo-types")
|
||||
@Controller("cargo-types")
|
||||
// @UseGuards(JwtAuthGuard) — TODO: add when auth package integrated
|
||||
@ApiBearerAuth()
|
||||
export class CargoTypesController {
|
||||
constructor(private readonly service: CargoTypesService) {}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({
|
||||
summary: "List cargo types",
|
||||
description: "Paginated list with optional filtering by isActive, requiresDirectorApproval, parentGroupId, and name search.",
|
||||
})
|
||||
findAll(@Query() filter: FilterCargoTypeDto) {
|
||||
return this.service.findAll(filter);
|
||||
}
|
||||
|
||||
@Get(":id")
|
||||
@ApiOperation({ summary: "Get a cargo type by ID", description: "Returns the cargo type with parent and children relations." })
|
||||
findOne(@Param("id", ParseUUIDPipe) id: string) {
|
||||
return this.service.findById(id);
|
||||
}
|
||||
|
||||
@Post()
|
||||
@ApiOperation({ summary: "Create a new cargo type" })
|
||||
create(@Body() dto: CreateCargoTypeDto) {
|
||||
return this.service.create(dto);
|
||||
}
|
||||
|
||||
@Patch(":id")
|
||||
@ApiOperation({ summary: "Update a cargo type" })
|
||||
update(
|
||||
@Param("id", ParseUUIDPipe) id: string,
|
||||
@Body() dto: UpdateCargoTypeDto,
|
||||
) {
|
||||
return this.service.update(id, dto);
|
||||
}
|
||||
|
||||
@Delete(":id")
|
||||
@HttpCode(HttpStatus.NO_CONTENT)
|
||||
@ApiOperation({ summary: "Soft-delete a cargo type" })
|
||||
remove(@Param("id", ParseUUIDPipe) id: string) {
|
||||
return this.service.remove(id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { Module } from "@nestjs/common";
|
||||
import { TypeOrmModule } from "@nestjs/typeorm";
|
||||
|
||||
import { CargoType } from "./entities/cargo-type.entity";
|
||||
import { CARGO_TYPES_REPOSITORY } from "./interfaces/cargo-types.repository.interface";
|
||||
import { CargoTypesRepository } from "./cargo-types.repository";
|
||||
import { CargoTypesController } from "./cargo-types.controller";
|
||||
import { CargoTypesService } from "./cargo-types.service";
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([CargoType])],
|
||||
controllers: [CargoTypesController],
|
||||
providers: [
|
||||
CargoTypesRepository,
|
||||
{
|
||||
provide: CARGO_TYPES_REPOSITORY,
|
||||
useExisting: CargoTypesRepository,
|
||||
},
|
||||
CargoTypesService,
|
||||
],
|
||||
exports: [CargoTypesService],
|
||||
})
|
||||
export class CargoTypesModule {}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { BaseRepository } from "@edr/api-common";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import { InjectRepository } from "@nestjs/typeorm";
|
||||
import { FindManyOptions, Repository } from "typeorm";
|
||||
|
||||
import { CargoType } from "./entities/cargo-type.entity";
|
||||
import { ICargoTypesRepository } from "./interfaces/cargo-types.repository.interface";
|
||||
|
||||
@Injectable()
|
||||
export class CargoTypesRepository
|
||||
extends BaseRepository<CargoType>
|
||||
implements ICargoTypesRepository
|
||||
{
|
||||
constructor(
|
||||
@InjectRepository(CargoType)
|
||||
repository: Repository<CargoType>,
|
||||
) {
|
||||
super(repository);
|
||||
}
|
||||
|
||||
override findById(id: string): Promise<CargoType | null> {
|
||||
return this.repository.findOne({
|
||||
where: { id },
|
||||
relations: { parent: true, children: true },
|
||||
});
|
||||
}
|
||||
|
||||
override findAndCount(options?: FindManyOptions<CargoType>): Promise<[CargoType[], number]> {
|
||||
return this.repository.findAndCount(options);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
import { ConflictException, Inject, Injectable, NotFoundException } from "@nestjs/common";
|
||||
import { ILike } from "typeorm";
|
||||
|
||||
import { CreateCargoTypeDto } from "./dto/create-cargo-type.dto";
|
||||
import { FilterCargoTypeDto } from "./dto/filter-cargo-type.dto";
|
||||
import { UpdateCargoTypeDto } from "./dto/update-cargo-type.dto";
|
||||
import { CargoType } from "./entities/cargo-type.entity";
|
||||
import {
|
||||
CARGO_TYPES_REPOSITORY,
|
||||
ICargoTypesRepository,
|
||||
} from "./interfaces/cargo-types.repository.interface";
|
||||
|
||||
@Injectable()
|
||||
export class CargoTypesService {
|
||||
constructor(
|
||||
@Inject(CARGO_TYPES_REPOSITORY)
|
||||
private readonly repository: ICargoTypesRepository,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Find all cargo types with pagination and optional filtering.
|
||||
*/
|
||||
async findAll(filter: FilterCargoTypeDto): Promise<{
|
||||
data: CargoType[];
|
||||
meta: {
|
||||
total: number;
|
||||
page: number;
|
||||
pageSize: number;
|
||||
totalPages: number;
|
||||
};
|
||||
}> {
|
||||
const where: Record<string, unknown> = {};
|
||||
|
||||
if (filter.isActive !== undefined) {
|
||||
where.isActive = filter.isActive;
|
||||
}
|
||||
|
||||
if (filter.requiresDirectorApproval !== undefined) {
|
||||
where.requiresDirectorApproval = filter.requiresDirectorApproval;
|
||||
}
|
||||
|
||||
if (filter.parentGroupId !== undefined) {
|
||||
where.parentGroupId = filter.parentGroupId;
|
||||
}
|
||||
|
||||
if (filter.search) {
|
||||
where.cargoTypeName = ILike(`%${filter.search}%`);
|
||||
}
|
||||
|
||||
const [data, total] = await this.repository.findAndCount({
|
||||
where,
|
||||
order: { [filter.sortBy!]: filter.sortOrder },
|
||||
skip: (filter.page! - 1) * filter.pageSize!,
|
||||
take: filter.pageSize,
|
||||
relations: { parent: true },
|
||||
});
|
||||
|
||||
return {
|
||||
data,
|
||||
meta: {
|
||||
total,
|
||||
page: filter.page!,
|
||||
pageSize: filter.pageSize!,
|
||||
totalPages: Math.ceil(total / filter.pageSize!),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a single cargo type by ID.
|
||||
*/
|
||||
async findById(id: string): Promise<CargoType> {
|
||||
const entity = await this.repository.findById(id);
|
||||
if (!entity) {
|
||||
throw new NotFoundException(`Cargo type ${id} not found`);
|
||||
}
|
||||
return entity;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new cargo type.
|
||||
*/
|
||||
async create(dto: CreateCargoTypeDto): Promise<CargoType> {
|
||||
// Validate parent exists if provided
|
||||
if (dto.parentGroupId) {
|
||||
const parent = await this.repository.findById(dto.parentGroupId);
|
||||
if (!parent) {
|
||||
throw new NotFoundException(`Parent cargo type ${dto.parentGroupId} not found`);
|
||||
}
|
||||
}
|
||||
|
||||
return this.repository.create({
|
||||
cargoTypeName: dto.cargoTypeName,
|
||||
parentGroupId: dto.parentGroupId ?? null,
|
||||
showFreeTextBox: dto.showFreeTextBox ?? false,
|
||||
requiresDirectorApproval: dto.requiresDirectorApproval ?? false,
|
||||
isActive: dto.isActive ?? true,
|
||||
displayOrder: dto.displayOrder ?? 1,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Update an existing cargo type.
|
||||
*/
|
||||
async update(id: string, dto: UpdateCargoTypeDto): Promise<CargoType> {
|
||||
await this.findById(id);
|
||||
|
||||
// Validate parent exists if provided
|
||||
const parentGroupId = dto.parentGroupId;
|
||||
if (parentGroupId) {
|
||||
const parent = await this.repository.findById(parentGroupId);
|
||||
if (!parent) {
|
||||
throw new NotFoundException(`Parent cargo type ${parentGroupId} not found`);
|
||||
}
|
||||
// Prevent circular reference
|
||||
if (parentGroupId === id) {
|
||||
throw new ConflictException("A cargo type cannot be its own parent");
|
||||
}
|
||||
}
|
||||
|
||||
const updated = await this.repository.update(id, dto);
|
||||
if (!updated) {
|
||||
throw new NotFoundException(`Cargo type ${id} not found`);
|
||||
}
|
||||
return this.findById(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Soft-delete a cargo type.
|
||||
*/
|
||||
async remove(id: string): Promise<void> {
|
||||
await this.findById(id);
|
||||
await this.repository.softDelete(id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { IsBoolean, IsInt, IsOptional, IsString, IsUUID, MaxLength, Min } from "class-validator";
|
||||
|
||||
export class CreateCargoTypeDto {
|
||||
@ApiProperty({ description: "Cargo type name", maxLength: 255 })
|
||||
@IsString()
|
||||
@MaxLength(255)
|
||||
cargoTypeName!: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "Parent cargo type group ID (UUID) for hierarchical structure" })
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
parentGroupId?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "Show free text box for this cargo type", default: false })
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
showFreeTextBox?: boolean = false;
|
||||
|
||||
@ApiPropertyOptional({ description: "Requires director approval for this cargo type", default: false })
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
requiresDirectorApproval?: boolean = false;
|
||||
|
||||
@ApiPropertyOptional({ description: "Is the cargo type active", default: true })
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
isActive?: boolean = true;
|
||||
|
||||
@ApiPropertyOptional({ description: "Display order for UI", default: 1 })
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
displayOrder?: number = 1;
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { Transform, Type } from "class-transformer";
|
||||
import { IsBoolean, IsIn, IsInt, IsOptional, IsString, IsUUID, Min } from "class-validator";
|
||||
|
||||
export class FilterCargoTypeDto {
|
||||
@ApiPropertyOptional({ description: "Filter by active status" })
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
@Transform(({ value }) => value === "true" || value === true)
|
||||
isActive?: boolean;
|
||||
|
||||
@ApiPropertyOptional({ description: "Filter by requires director approval" })
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
@Transform(({ value }) => value === "true" || value === true)
|
||||
requiresDirectorApproval?: boolean;
|
||||
|
||||
@ApiPropertyOptional({ description: "Filter by parent group ID (or 'root' for top-level only)" })
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
parentGroupId?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "Search by cargo type name (case-insensitive)" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
search?: string;
|
||||
|
||||
@ApiPropertyOptional({ enum: ["cargoTypeName", "displayOrder", "createdAt"], default: "displayOrder" })
|
||||
@IsOptional()
|
||||
@IsIn(["cargoTypeName", "displayOrder", "createdAt"])
|
||||
sortBy?: string = "displayOrder";
|
||||
|
||||
@ApiPropertyOptional({ enum: ["ASC", "DESC"], default: "ASC" })
|
||||
@IsOptional()
|
||||
@IsIn(["ASC", "DESC"])
|
||||
sortOrder?: "ASC" | "DESC" = "ASC";
|
||||
|
||||
@ApiPropertyOptional({ description: "Page number", default: 1, minimum: 1 })
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
page?: number = 1;
|
||||
|
||||
@ApiPropertyOptional({ description: "Items per page", default: 20, minimum: 1 })
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
pageSize?: number = 20;
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { PartialType } from "@nestjs/mapped-types";
|
||||
|
||||
import { CreateCargoTypeDto } from "./create-cargo-type.dto";
|
||||
|
||||
export class UpdateCargoTypeDto extends PartialType(CreateCargoTypeDto) {}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { BaseEntity } from "@edr/api-common";
|
||||
import { Column, Entity, Index, ManyToOne, OneToMany, JoinColumn } from "typeorm";
|
||||
|
||||
@Entity({ schema: "freight", name: "cargo_types" })
|
||||
@Index(["isActive"])
|
||||
@Index(["displayOrder"])
|
||||
@Index(["parentGroupId"])
|
||||
export class CargoType extends BaseEntity {
|
||||
@Column({ name: "cargo_type_name", type: "varchar", length: 255, nullable: false })
|
||||
cargoTypeName!: string;
|
||||
|
||||
@Column({ name: "parent_group_id", type: "uuid", nullable: true })
|
||||
parentGroupId?: string | null;
|
||||
|
||||
@Column({ name: "show_free_text_box", type: "boolean", default: false })
|
||||
showFreeTextBox!: boolean;
|
||||
|
||||
@Column({ name: "requires_director_approval", type: "boolean", default: false })
|
||||
requiresDirectorApproval!: boolean;
|
||||
|
||||
@Column({ name: "is_active", type: "boolean", default: true })
|
||||
isActive!: boolean;
|
||||
|
||||
@Column({ name: "display_order", type: "int", default: 1 })
|
||||
displayOrder!: number;
|
||||
|
||||
@ManyToOne(() => CargoType, (cargoType) => cargoType.children, {
|
||||
nullable: true,
|
||||
onDelete: "SET NULL",
|
||||
})
|
||||
@JoinColumn({ name: "parent_group_id" })
|
||||
parent?: CargoType | null;
|
||||
|
||||
@OneToMany(() => CargoType, (cargoType) => cargoType.parent)
|
||||
children?: CargoType[];
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { FindManyOptions } from "typeorm";
|
||||
|
||||
import { CargoType } from "../entities/cargo-type.entity";
|
||||
|
||||
export interface ICargoTypesRepository {
|
||||
findById(id: string): Promise<CargoType | null>;
|
||||
findAll(options?: FindManyOptions<CargoType>): Promise<CargoType[]>;
|
||||
findAndCount(options?: FindManyOptions<CargoType>): Promise<[CargoType[], number]>;
|
||||
create(data: Partial<CargoType>): Promise<CargoType>;
|
||||
update(id: string, data: Partial<CargoType>): Promise<CargoType | null>;
|
||||
softDelete(id: string): Promise<void>;
|
||||
}
|
||||
|
||||
export const CARGO_TYPES_REPOSITORY = Symbol("CARGO_TYPES_REPOSITORY");
|
||||
@@ -1,5 +1,5 @@
|
||||
// src/modules/customers/dto/update-customer.dto.ts
|
||||
import { PartialType } from '@nestjs/swagger';
|
||||
import { PartialType } from '@nestjs/mapped-types';
|
||||
import { CreateCustomerDto } from './create-customer.dto';
|
||||
|
||||
export class UpdateCustomerDto extends PartialType(CreateCustomerDto) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { PartialType } from "@nestjs/swagger";
|
||||
import { PartialType } from "@nestjs/mapped-types";
|
||||
|
||||
import { CreateCustomerDto } from "./create-customer.dto";
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { PartialType } from "@nestjs/swagger";
|
||||
import { PartialType } from "@nestjs/mapped-types";
|
||||
|
||||
import { CreateDropdownOptionDto } from "./create-dropdown-option.dto";
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { OmitType, PartialType } from "@nestjs/swagger";
|
||||
import { OmitType, PartialType } from "@nestjs/mapped-types";
|
||||
|
||||
import { CreateDropdownSettingDto } from "./create-dropdown-setting.dto";
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { PartialType } from "@nestjs/swagger";
|
||||
import { PartialType } from "@nestjs/mapped-types";
|
||||
|
||||
import { CreateFileUploadFieldDto } from "./create-file-upload-field.dto";
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { OmitType, PartialType } from "@nestjs/swagger";
|
||||
import { OmitType, PartialType } from "@nestjs/mapped-types";
|
||||
|
||||
import { CreateFileUploadSettingDto } from "./create-file-upload-setting.dto";
|
||||
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { IsBoolean, IsInt, IsOptional, IsString, MaxLength, Min } from "class-validator";
|
||||
|
||||
export class CreateServiceTypeDto {
|
||||
@ApiProperty({ description: "Service type name", maxLength: 255 })
|
||||
@IsString()
|
||||
@MaxLength(255)
|
||||
serviceName!: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "Detailed description of the service" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
description?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "Can be booked alone", default: true })
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
canBeBookedAlone?: boolean = true;
|
||||
|
||||
@ApiPropertyOptional({ description: "Includes first mile service", default: false })
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
includesFirstMile?: boolean = false;
|
||||
|
||||
@ApiPropertyOptional({ description: "Includes last mile service", default: false })
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
includesLastMile?: boolean = false;
|
||||
|
||||
@ApiPropertyOptional({ description: "Includes customs clearance", default: false })
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
includesCustoms?: boolean = false;
|
||||
|
||||
@ApiPropertyOptional({ description: "Priority bonus points for booking priority", default: 0 })
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(0)
|
||||
priorityBonusPoints?: number = 0;
|
||||
|
||||
@ApiPropertyOptional({ description: "Is the service type active", default: true })
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
isActive?: boolean = true;
|
||||
|
||||
@ApiPropertyOptional({ description: "Display order for UI", default: 1 })
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
displayOrder?: number = 1;
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { Transform, Type } from "class-transformer";
|
||||
import { IsBoolean, IsIn, IsInt, IsOptional, IsString, Min } from "class-validator";
|
||||
|
||||
export class FilterServiceTypeDto {
|
||||
@ApiPropertyOptional({ description: "Filter by active status" })
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
@Transform(({ value }) => value === "true" || value === true)
|
||||
isActive?: boolean;
|
||||
|
||||
@ApiPropertyOptional({ description: "Filter by can be booked alone" })
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
@Transform(({ value }) => value === "true" || value === true)
|
||||
canBeBookedAlone?: boolean;
|
||||
|
||||
@ApiPropertyOptional({ description: "Search by service name (case-insensitive)" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
search?: string;
|
||||
|
||||
@ApiPropertyOptional({ enum: ["serviceName", "displayOrder", "createdAt"], default: "displayOrder" })
|
||||
@IsOptional()
|
||||
@IsIn(["serviceName", "displayOrder", "createdAt"])
|
||||
sortBy?: string = "displayOrder";
|
||||
|
||||
@ApiPropertyOptional({ enum: ["ASC", "DESC"], default: "ASC" })
|
||||
@IsOptional()
|
||||
@IsIn(["ASC", "DESC"])
|
||||
sortOrder?: "ASC" | "DESC" = "ASC";
|
||||
|
||||
@ApiPropertyOptional({ description: "Page number", default: 1, minimum: 1 })
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
page?: number = 1;
|
||||
|
||||
@ApiPropertyOptional({ description: "Items per page", default: 20, minimum: 1 })
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
pageSize?: number = 20;
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { PartialType } from "@nestjs/mapped-types";
|
||||
|
||||
import { CreateServiceTypeDto } from "./create-service-type.dto";
|
||||
|
||||
export class UpdateServiceTypeDto extends PartialType(CreateServiceTypeDto) {}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { BaseEntity } from "@edr/api-common";
|
||||
import { Column, Entity, Index } from "typeorm";
|
||||
|
||||
@Entity({ schema: "freight", name: "service_types" })
|
||||
@Index(["isActive"])
|
||||
@Index(["displayOrder"])
|
||||
export class ServiceType extends BaseEntity {
|
||||
@Column({ name: "service_name", type: "varchar", length: 255, nullable: false })
|
||||
serviceName!: string;
|
||||
|
||||
@Column({ name: "description", type: "text", nullable: true })
|
||||
description?: string | null;
|
||||
|
||||
@Column({ name: "can_be_booked_alone", type: "boolean", default: true })
|
||||
canBeBookedAlone!: boolean;
|
||||
|
||||
@Column({ name: "includes_first_mile", type: "boolean", default: false })
|
||||
includesFirstMile!: boolean;
|
||||
|
||||
@Column({ name: "includes_last_mile", type: "boolean", default: false })
|
||||
includesLastMile!: boolean;
|
||||
|
||||
@Column({ name: "includes_customs", type: "boolean", default: false })
|
||||
includesCustoms!: boolean;
|
||||
|
||||
@Column({ name: "priority_bonus_points", type: "int", default: 0 })
|
||||
priorityBonusPoints!: number;
|
||||
|
||||
@Column({ name: "is_active", type: "boolean", default: true })
|
||||
isActive!: boolean;
|
||||
|
||||
@Column({ name: "display_order", type: "int", default: 1 })
|
||||
displayOrder!: number;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { FindManyOptions } from "typeorm";
|
||||
|
||||
import { ServiceType } from "../entities/service-type.entity";
|
||||
|
||||
export interface IServiceTypesRepository {
|
||||
findById(id: string): Promise<ServiceType | null>;
|
||||
findAll(options?: FindManyOptions<ServiceType>): Promise<ServiceType[]>;
|
||||
findAndCount(options?: FindManyOptions<ServiceType>): Promise<[ServiceType[], number]>;
|
||||
create(data: Partial<ServiceType>): Promise<ServiceType>;
|
||||
update(id: string, data: Partial<ServiceType>): Promise<ServiceType | null>;
|
||||
softDelete(id: string): Promise<void>;
|
||||
}
|
||||
|
||||
export const SERVICE_TYPES_REPOSITORY = Symbol("SERVICE_TYPES_REPOSITORY");
|
||||
@@ -0,0 +1,64 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
HttpCode,
|
||||
HttpStatus,
|
||||
Param,
|
||||
ParseUUIDPipe,
|
||||
Patch,
|
||||
Post,
|
||||
Query,
|
||||
} from "@nestjs/common";
|
||||
import { ApiBearerAuth, ApiOperation, ApiTags } from "@nestjs/swagger";
|
||||
|
||||
import { CreateServiceTypeDto } from "./dto/create-service-type.dto";
|
||||
import { FilterServiceTypeDto } from "./dto/filter-service-type.dto";
|
||||
import { UpdateServiceTypeDto } from "./dto/update-service-type.dto";
|
||||
import { ServiceTypesService } from "./service-types.service";
|
||||
|
||||
@ApiTags("service-types")
|
||||
@Controller("service-types")
|
||||
// @UseGuards(JwtAuthGuard) — TODO: add when auth package integrated
|
||||
@ApiBearerAuth()
|
||||
export class ServiceTypesController {
|
||||
constructor(private readonly service: ServiceTypesService) {}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({
|
||||
summary: "List service types",
|
||||
description: "Paginated list with optional filtering by isActive, canBeBookedAlone, and name search.",
|
||||
})
|
||||
findAll(@Query() filter: FilterServiceTypeDto) {
|
||||
return this.service.findAll(filter);
|
||||
}
|
||||
|
||||
@Get(":id")
|
||||
@ApiOperation({ summary: "Get a service type by ID" })
|
||||
findOne(@Param("id", ParseUUIDPipe) id: string) {
|
||||
return this.service.findById(id);
|
||||
}
|
||||
|
||||
@Post()
|
||||
@ApiOperation({ summary: "Create a new service type" })
|
||||
create(@Body() dto: CreateServiceTypeDto) {
|
||||
return this.service.create(dto);
|
||||
}
|
||||
|
||||
@Patch(":id")
|
||||
@ApiOperation({ summary: "Update a service type" })
|
||||
update(
|
||||
@Param("id", ParseUUIDPipe) id: string,
|
||||
@Body() dto: UpdateServiceTypeDto,
|
||||
) {
|
||||
return this.service.update(id, dto);
|
||||
}
|
||||
|
||||
@Delete(":id")
|
||||
@HttpCode(HttpStatus.NO_CONTENT)
|
||||
@ApiOperation({ summary: "Soft-delete a service type" })
|
||||
remove(@Param("id", ParseUUIDPipe) id: string) {
|
||||
return this.service.remove(id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { Module } from "@nestjs/common";
|
||||
import { TypeOrmModule } from "@nestjs/typeorm";
|
||||
|
||||
import { ServiceType } from "./entities/service-type.entity";
|
||||
import { SERVICE_TYPES_REPOSITORY } from "./interfaces/service-types.repository.interface";
|
||||
import { ServiceTypesRepository } from "./service-types.repository";
|
||||
import { ServiceTypesController } from "./service-types.controller";
|
||||
import { ServiceTypesService } from "./service-types.service";
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([ServiceType])],
|
||||
controllers: [ServiceTypesController],
|
||||
providers: [
|
||||
ServiceTypesRepository,
|
||||
{
|
||||
provide: SERVICE_TYPES_REPOSITORY,
|
||||
useExisting: ServiceTypesRepository,
|
||||
},
|
||||
ServiceTypesService,
|
||||
],
|
||||
exports: [ServiceTypesService],
|
||||
})
|
||||
export class ServiceTypesModule {}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { BaseRepository } from "@edr/api-common";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import { InjectRepository } from "@nestjs/typeorm";
|
||||
import { FindManyOptions, Repository } from "typeorm";
|
||||
|
||||
import { ServiceType } from "./entities/service-type.entity";
|
||||
import { IServiceTypesRepository } from "./interfaces/service-types.repository.interface";
|
||||
|
||||
@Injectable()
|
||||
export class ServiceTypesRepository
|
||||
extends BaseRepository<ServiceType>
|
||||
implements IServiceTypesRepository
|
||||
{
|
||||
constructor(
|
||||
@InjectRepository(ServiceType)
|
||||
repository: Repository<ServiceType>,
|
||||
) {
|
||||
super(repository);
|
||||
}
|
||||
|
||||
override findById(id: string): Promise<ServiceType | null> {
|
||||
return this.repository.findOne({
|
||||
where: { id },
|
||||
});
|
||||
}
|
||||
|
||||
override findAndCount(options?: FindManyOptions<ServiceType>): Promise<[ServiceType[], number]> {
|
||||
return this.repository.findAndCount(options);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import { Inject, Injectable, NotFoundException } from "@nestjs/common";
|
||||
import { ILike } from "typeorm";
|
||||
|
||||
import { CreateServiceTypeDto } from "./dto/create-service-type.dto";
|
||||
import { FilterServiceTypeDto } from "./dto/filter-service-type.dto";
|
||||
import { UpdateServiceTypeDto } from "./dto/update-service-type.dto";
|
||||
import { ServiceType } from "./entities/service-type.entity";
|
||||
import {
|
||||
IServiceTypesRepository,
|
||||
SERVICE_TYPES_REPOSITORY,
|
||||
} from "./interfaces/service-types.repository.interface";
|
||||
|
||||
@Injectable()
|
||||
export class ServiceTypesService {
|
||||
constructor(
|
||||
@Inject(SERVICE_TYPES_REPOSITORY)
|
||||
private readonly repository: IServiceTypesRepository,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Find all service types with pagination and optional filtering.
|
||||
*/
|
||||
async findAll(filter: FilterServiceTypeDto): Promise<{
|
||||
data: ServiceType[];
|
||||
meta: {
|
||||
total: number;
|
||||
page: number;
|
||||
pageSize: number;
|
||||
totalPages: number;
|
||||
};
|
||||
}> {
|
||||
const where: Record<string, unknown> = {};
|
||||
|
||||
if (filter.isActive !== undefined) {
|
||||
where.isActive = filter.isActive;
|
||||
}
|
||||
|
||||
if (filter.canBeBookedAlone !== undefined) {
|
||||
where.canBeBookedAlone = filter.canBeBookedAlone;
|
||||
}
|
||||
|
||||
if (filter.search) {
|
||||
where.serviceName = ILike(`%${filter.search}%`);
|
||||
}
|
||||
|
||||
const [data, total] = await this.repository.findAndCount({
|
||||
where,
|
||||
order: { [filter.sortBy!]: filter.sortOrder },
|
||||
skip: (filter.page! - 1) * filter.pageSize!,
|
||||
take: filter.pageSize,
|
||||
});
|
||||
|
||||
return {
|
||||
data,
|
||||
meta: {
|
||||
total,
|
||||
page: filter.page!,
|
||||
pageSize: filter.pageSize!,
|
||||
totalPages: Math.ceil(total / filter.pageSize!),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a single service type by ID.
|
||||
*/
|
||||
async findById(id: string): Promise<ServiceType> {
|
||||
const entity = await this.repository.findById(id);
|
||||
if (!entity) {
|
||||
throw new NotFoundException(`Service type ${id} not found`);
|
||||
}
|
||||
return entity;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new service type.
|
||||
*/
|
||||
async create(dto: CreateServiceTypeDto): Promise<ServiceType> {
|
||||
return this.repository.create({
|
||||
serviceName: dto.serviceName,
|
||||
description: dto.description ?? null,
|
||||
canBeBookedAlone: dto.canBeBookedAlone ?? true,
|
||||
includesFirstMile: dto.includesFirstMile ?? false,
|
||||
includesLastMile: dto.includesLastMile ?? false,
|
||||
includesCustoms: dto.includesCustoms ?? false,
|
||||
priorityBonusPoints: dto.priorityBonusPoints ?? 0,
|
||||
isActive: dto.isActive ?? true,
|
||||
displayOrder: dto.displayOrder ?? 1,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Update an existing service type.
|
||||
*/
|
||||
async update(id: string, dto: UpdateServiceTypeDto): Promise<ServiceType> {
|
||||
await this.findById(id);
|
||||
const updated = await this.repository.update(id, dto);
|
||||
if (!updated) {
|
||||
throw new NotFoundException(`Service type ${id} not found`);
|
||||
}
|
||||
return this.findById(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Soft-delete a service type.
|
||||
*/
|
||||
async remove(id: string): Promise<void> {
|
||||
await this.findById(id);
|
||||
await this.repository.softDelete(id);
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,9 @@ import { LayoutDashboard, Network, Settings } from "lucide-react";
|
||||
import { useAuth } from "./auth/useAuth";
|
||||
import LoginPage from "./pages/auth/LoginPage";
|
||||
import OverviewPage from "./pages/dashboard/OverviewPage";
|
||||
import EmployeesPage from "./pages/dashboard/user-management/EmployeesPage";
|
||||
import PermissionsPage from "./pages/dashboard/user-management/PermissionsPage";
|
||||
import RolesPage from "./pages/dashboard/user-management/RolesPage";
|
||||
import UserManagementPage from "./pages/dashboard/user-management/UserManagementPage";
|
||||
import LoadingScreen from "./components/LoadingScreen";
|
||||
import { RuleEnginePage } from "./pages/ruleEngine/RuleEngine";
|
||||
@@ -19,6 +22,20 @@ const sidebarItems: SidebarItem[] = [
|
||||
label: "User management",
|
||||
href: "/dashboard/user-management",
|
||||
icon: <Network />,
|
||||
children: [
|
||||
{
|
||||
label: "Employees",
|
||||
href: "/dashboard/user-management/employees",
|
||||
},
|
||||
{
|
||||
label: "Permissions",
|
||||
href: "/dashboard/user-management/permissions",
|
||||
},
|
||||
{
|
||||
label: "Roles",
|
||||
href: "/dashboard/user-management/roles",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
label: "Rule Engine",
|
||||
@@ -73,7 +90,13 @@ const App = () => {
|
||||
<Route path="/dashboard" element={<DashboardShell />}>
|
||||
<Route path="overview" element={<OverviewPage />} />
|
||||
<Route path="user-management" element={<UserManagementPage />} />
|
||||
|
||||
<Route path="rule-engine" element={<RuleEnginePage />} />
|
||||
|
||||
<Route path="user-management/employees" element={<EmployeesPage />} />
|
||||
<Route path="user-management/permissions" element={<PermissionsPage />} />
|
||||
<Route path="user-management/roles" element={<RolesPage />} />
|
||||
|
||||
<Route path="org-structure" element={<Navigate to="/dashboard/user-management" replace />} />
|
||||
<Route path="org-structure/*" element={<Navigate to="/dashboard/user-management" replace />} />
|
||||
</Route>
|
||||
|
||||
@@ -0,0 +1,321 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { isAxiosError } from "axios";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@edr/ui-common";
|
||||
|
||||
import { api } from "@/auth/http";
|
||||
import { useAuth } from "@/auth/useAuth";
|
||||
|
||||
interface LocaleText {
|
||||
en?: string;
|
||||
am?: string;
|
||||
}
|
||||
|
||||
interface EmployeeUserRecord {
|
||||
id: string;
|
||||
name?: LocaleText;
|
||||
email?: string;
|
||||
phoneNumber?: string;
|
||||
username?: string;
|
||||
}
|
||||
|
||||
interface EmployeePositionSummary {
|
||||
id: string;
|
||||
position?: {
|
||||
id: string;
|
||||
name?: LocaleText;
|
||||
key?: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface EmployeeRecord {
|
||||
id: string;
|
||||
name?: LocaleText;
|
||||
status?: string;
|
||||
user?: EmployeeUserRecord;
|
||||
employeePositions?: EmployeePositionSummary[];
|
||||
}
|
||||
|
||||
interface ListResponse<T> {
|
||||
count?: number;
|
||||
items?: T[];
|
||||
data?: T[];
|
||||
}
|
||||
|
||||
const getLocaleLabel = (value?: LocaleText | null, fallback = "Unnamed") =>
|
||||
value?.en ?? value?.am ?? fallback;
|
||||
|
||||
const getItems = <T,>(payload: ListResponse<T> | T[] | undefined | null) => {
|
||||
if (!payload) {
|
||||
return [] as T[];
|
||||
}
|
||||
|
||||
if (Array.isArray(payload)) {
|
||||
return payload;
|
||||
}
|
||||
|
||||
return payload.items ?? payload.data ?? [];
|
||||
};
|
||||
|
||||
const getEmployeeDisplayName = (employee: EmployeeRecord) =>
|
||||
getLocaleLabel(
|
||||
employee.name ?? employee.user?.name,
|
||||
employee.user?.email ?? employee.user?.username ?? employee.id,
|
||||
);
|
||||
|
||||
const EmployeesPage = () => {
|
||||
const { user } = useAuth();
|
||||
const [employees, setEmployees] = useState<EmployeeRecord[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
const [selectedEmployee, setSelectedEmployee] = useState<EmployeeRecord | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let isMounted = true;
|
||||
const organizationIds = Array.from(
|
||||
new Set(
|
||||
(user?.employee ?? [])
|
||||
.map((employee) => employee.organizationId)
|
||||
.filter((organizationId): organizationId is string => Boolean(organizationId)),
|
||||
),
|
||||
);
|
||||
|
||||
const loadEmployees = async () => {
|
||||
setLoading(true);
|
||||
setErrorMessage(null);
|
||||
|
||||
if (!organizationIds.length) {
|
||||
setEmployees([]);
|
||||
setErrorMessage("No employee organization scope is available for this account.");
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const responses = await Promise.all(
|
||||
organizationIds.map((organizationId) =>
|
||||
api.get<ListResponse<EmployeeRecord>>(
|
||||
`/employees/${organizationId}/by-organization`,
|
||||
{
|
||||
params: {
|
||||
skip: 0,
|
||||
take: 1000,
|
||||
},
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
if (!isMounted) {
|
||||
return;
|
||||
}
|
||||
|
||||
const uniqueEmployees = Array.from(
|
||||
new Map(
|
||||
responses
|
||||
.flatMap((response) => getItems(response.data))
|
||||
.map((employee) => [employee.id, employee]),
|
||||
).values(),
|
||||
);
|
||||
|
||||
setEmployees(
|
||||
uniqueEmployees.sort((left, right) =>
|
||||
getEmployeeDisplayName(left).localeCompare(getEmployeeDisplayName(right)),
|
||||
),
|
||||
);
|
||||
} catch (error) {
|
||||
if (!isMounted) {
|
||||
return;
|
||||
}
|
||||
|
||||
setErrorMessage(
|
||||
isAxiosError(error)
|
||||
? error.response?.data?.message ?? "Unable to load employees."
|
||||
: "Unable to load employees.",
|
||||
);
|
||||
} finally {
|
||||
if (isMounted) {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
void loadEmployees();
|
||||
|
||||
return () => {
|
||||
isMounted = false;
|
||||
};
|
||||
}, [user]);
|
||||
|
||||
return (
|
||||
<section className="p-6">
|
||||
<div className="space-y-6 rounded-2xl border border-border bg-card p-8 shadow-sm">
|
||||
<div className="space-y-3">
|
||||
<p className="text-sm font-medium uppercase tracking-[0.2em] text-muted-foreground">
|
||||
User Management
|
||||
</p>
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-3xl font-semibold text-foreground">Employees</h1>
|
||||
<p className="mt-3 max-w-2xl text-sm text-muted-foreground">
|
||||
Browse employees within your accessible scope and open a record to review contact and position details.
|
||||
</p>
|
||||
</div>
|
||||
<div className="rounded-full border border-border bg-muted px-3 py-1 text-sm font-medium text-muted-foreground">
|
||||
{employees.length} employees
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{loading ? (
|
||||
<div className="rounded-2xl border border-dashed border-border bg-muted px-4 py-8 text-center text-sm text-muted-foreground">
|
||||
Loading employees...
|
||||
</div>
|
||||
) : errorMessage ? (
|
||||
<div className="rounded-2xl border border-red-200 bg-red-50 px-4 py-8 text-center text-sm text-red-700 dark:border-red-950 dark:bg-red-950/30 dark:text-red-300">
|
||||
{errorMessage}
|
||||
</div>
|
||||
) : employees.length ? (
|
||||
<div className="overflow-x-auto rounded-2xl border border-border">
|
||||
<table className="min-w-[980px] w-full border-collapse text-left text-sm">
|
||||
<thead className="bg-muted/60 text-muted-foreground">
|
||||
<tr>
|
||||
<th className="px-4 py-3 font-medium">Name</th>
|
||||
<th className="px-4 py-3 font-medium">Username</th>
|
||||
<th className="px-4 py-3 font-medium">Email</th>
|
||||
<th className="px-4 py-3 font-medium">Phone</th>
|
||||
<th className="px-4 py-3 font-medium">Status</th>
|
||||
<th className="px-4 py-3 font-medium">Positions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{employees.map((employee) => {
|
||||
const positions = employee.employeePositions?.map((item) => getLocaleLabel(item.position?.name, item.position?.key ?? "Unnamed")) ?? [];
|
||||
|
||||
return (
|
||||
<tr
|
||||
key={employee.id}
|
||||
onClick={() => setSelectedEmployee(employee)}
|
||||
className="cursor-pointer border-t border-border bg-background transition hover:bg-accent/20"
|
||||
>
|
||||
<td className="px-4 py-3 font-medium text-foreground">{getEmployeeDisplayName(employee)}</td>
|
||||
<td className="px-4 py-3 text-muted-foreground">{employee.user?.username ?? "-"}</td>
|
||||
<td className="px-4 py-3 text-muted-foreground">{employee.user?.email ?? "-"}</td>
|
||||
<td className="px-4 py-3 text-muted-foreground">{employee.user?.phoneNumber ?? "-"}</td>
|
||||
<td className="px-4 py-3 text-muted-foreground">{employee.status ?? "-"}</td>
|
||||
<td className="px-4 py-3 text-muted-foreground">{positions.join(", ") || "-"}</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
) : (
|
||||
<div className="rounded-2xl border border-dashed border-border bg-muted px-4 py-8 text-center text-sm text-muted-foreground">
|
||||
No employees are available in your scope.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Dialog open={Boolean(selectedEmployee)} onOpenChange={(open) => !open && setSelectedEmployee(null)}>
|
||||
<DialogContent className="max-h-[85vh] overflow-y-auto sm:max-w-2xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
{selectedEmployee ? getEmployeeDisplayName(selectedEmployee) : "Employee details"}
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
{selectedEmployee
|
||||
? "Review the employee profile, contact information, and assigned positions."
|
||||
: undefined}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{selectedEmployee ? (
|
||||
<div className="space-y-6">
|
||||
<div className="grid gap-4 rounded-2xl border border-border bg-muted/40 p-4 sm:grid-cols-2">
|
||||
<div>
|
||||
<p className="text-xs font-medium uppercase tracking-[0.18em] text-muted-foreground">
|
||||
Employee name
|
||||
</p>
|
||||
<p className="mt-2 text-sm font-semibold text-foreground">
|
||||
{getEmployeeDisplayName(selectedEmployee)}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-xs font-medium uppercase tracking-[0.18em] text-muted-foreground">
|
||||
Status
|
||||
</p>
|
||||
<p className="mt-2 text-sm font-semibold text-foreground">
|
||||
{selectedEmployee.status ?? "-"}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-xs font-medium uppercase tracking-[0.18em] text-muted-foreground">
|
||||
Username
|
||||
</p>
|
||||
<p className="mt-2 text-sm text-foreground">{selectedEmployee.user?.username ?? "-"}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-xs font-medium uppercase tracking-[0.18em] text-muted-foreground">
|
||||
Email
|
||||
</p>
|
||||
<p className="mt-2 text-sm text-foreground">{selectedEmployee.user?.email ?? "-"}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-xs font-medium uppercase tracking-[0.18em] text-muted-foreground">
|
||||
Phone
|
||||
</p>
|
||||
<p className="mt-2 text-sm text-foreground">{selectedEmployee.user?.phoneNumber ?? "-"}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-xs font-medium uppercase tracking-[0.18em] text-muted-foreground">
|
||||
Employee ID
|
||||
</p>
|
||||
<p className="mt-2 font-mono text-sm text-foreground">{selectedEmployee.id}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<h2 className="text-sm font-semibold text-foreground">Assigned positions</h2>
|
||||
<div className="rounded-full border border-border bg-muted px-3 py-1 text-xs font-medium text-muted-foreground">
|
||||
{selectedEmployee.employeePositions?.length ?? 0} positions
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{selectedEmployee.employeePositions?.length ? (
|
||||
<div className="grid gap-3 md:grid-cols-2">
|
||||
{selectedEmployee.employeePositions.map((item) => (
|
||||
<article
|
||||
key={item.id}
|
||||
className="rounded-2xl border border-border/70 bg-background/80 p-4 shadow-sm"
|
||||
>
|
||||
<p className="truncate text-sm font-semibold text-foreground">
|
||||
{getLocaleLabel(item.position?.name, item.position?.key ?? "Unnamed")}
|
||||
</p>
|
||||
<p className="mt-1 truncate font-mono text-xs text-muted-foreground/90">
|
||||
{item.position?.key ?? "-"}
|
||||
</p>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="rounded-2xl border border-dashed border-border bg-muted px-4 py-8 text-center text-sm text-muted-foreground">
|
||||
No positions are assigned to this employee.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</section>
|
||||
);
|
||||
};
|
||||
|
||||
export default EmployeesPage;
|
||||
@@ -0,0 +1,265 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { isAxiosError } from "axios";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@edr/ui-common";
|
||||
|
||||
import { api } from "@/auth/http";
|
||||
|
||||
interface LocaleText {
|
||||
en?: string;
|
||||
am?: string;
|
||||
}
|
||||
|
||||
interface PermissionRecord {
|
||||
id: string;
|
||||
key: string;
|
||||
name?: LocaleText;
|
||||
applicationId?: string | null;
|
||||
}
|
||||
|
||||
interface ApplicationRecord {
|
||||
id: string;
|
||||
key: string;
|
||||
name?: LocaleText;
|
||||
}
|
||||
|
||||
interface ListResponse<T> {
|
||||
count?: number;
|
||||
items?: T[];
|
||||
data?: T[];
|
||||
}
|
||||
|
||||
const PAGE_SIZE = 2000;
|
||||
const ALL_APPLICATIONS_VALUE = "all";
|
||||
const SYSTEM_APPLICATION_VALUE = "system";
|
||||
|
||||
const getLocaleLabel = (value?: LocaleText | null, fallback = "Unnamed") =>
|
||||
value?.en ?? value?.am ?? fallback;
|
||||
|
||||
const getItems = <T,>(payload: ListResponse<T> | T[] | undefined | null) => {
|
||||
if (!payload) {
|
||||
return [] as T[];
|
||||
}
|
||||
|
||||
if (Array.isArray(payload)) {
|
||||
return payload;
|
||||
}
|
||||
|
||||
return payload.items ?? payload.data ?? [];
|
||||
};
|
||||
|
||||
const sortPermissions = (items: PermissionRecord[]) =>
|
||||
[...items].sort((left, right) =>
|
||||
getLocaleLabel(left.name, left.key).localeCompare(
|
||||
getLocaleLabel(right.name, right.key),
|
||||
),
|
||||
);
|
||||
|
||||
const PermissionsPage = () => {
|
||||
const [permissions, setPermissions] = useState<PermissionRecord[]>([]);
|
||||
const [applications, setApplications] = useState<ApplicationRecord[]>([]);
|
||||
const [selectedApplication, setSelectedApplication] = useState(ALL_APPLICATIONS_VALUE);
|
||||
const [count, setCount] = useState(0);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [loadingMore, setLoadingMore] = useState(false);
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let isMounted = true;
|
||||
|
||||
const loadPageData = async () => {
|
||||
setLoading(true);
|
||||
setErrorMessage(null);
|
||||
|
||||
try {
|
||||
const [permissionsResponse, applicationsResponse] = await Promise.all([
|
||||
api.get<ListResponse<PermissionRecord>>("/permissions", {
|
||||
params: {
|
||||
skip: 0,
|
||||
take: PAGE_SIZE,
|
||||
},
|
||||
}),
|
||||
api.get<ListResponse<ApplicationRecord>>("/applications"),
|
||||
]);
|
||||
|
||||
if (!isMounted) {
|
||||
return;
|
||||
}
|
||||
|
||||
const items = sortPermissions(getItems(permissionsResponse.data));
|
||||
const applicationItems = [...getItems(applicationsResponse.data)].sort((left, right) =>
|
||||
getLocaleLabel(left.name, left.key).localeCompare(
|
||||
getLocaleLabel(right.name, right.key),
|
||||
),
|
||||
);
|
||||
|
||||
setPermissions(items);
|
||||
setApplications(applicationItems);
|
||||
setCount(permissionsResponse.data.count ?? items.length);
|
||||
} catch (error) {
|
||||
if (!isMounted) {
|
||||
return;
|
||||
}
|
||||
|
||||
setErrorMessage(
|
||||
isAxiosError(error)
|
||||
? error.response?.data?.message ?? "Unable to load permissions."
|
||||
: "Unable to load permissions.",
|
||||
);
|
||||
} finally {
|
||||
if (isMounted) {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
void loadPageData();
|
||||
|
||||
return () => {
|
||||
isMounted = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const hasMore = count > permissions.length;
|
||||
const filteredPermissions = permissions.filter((permission) => {
|
||||
if (selectedApplication === ALL_APPLICATIONS_VALUE) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (selectedApplication === SYSTEM_APPLICATION_VALUE) {
|
||||
return !permission.applicationId;
|
||||
}
|
||||
|
||||
return permission.applicationId === selectedApplication;
|
||||
});
|
||||
|
||||
const handleLoadMore = async () => {
|
||||
setLoadingMore(true);
|
||||
setErrorMessage(null);
|
||||
|
||||
try {
|
||||
const response = await api.get<ListResponse<PermissionRecord>>("/permissions", {
|
||||
params: {
|
||||
skip: permissions.length,
|
||||
take: PAGE_SIZE,
|
||||
},
|
||||
});
|
||||
|
||||
const nextItems = sortPermissions(getItems(response.data));
|
||||
|
||||
setPermissions((current) => [...current, ...nextItems]);
|
||||
setCount(response.data.count ?? permissions.length + nextItems.length);
|
||||
} catch (error) {
|
||||
setErrorMessage(
|
||||
isAxiosError(error)
|
||||
? error.response?.data?.message ?? "Unable to load more permissions."
|
||||
: "Unable to load more permissions.",
|
||||
);
|
||||
} finally {
|
||||
setLoadingMore(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<section className="p-6">
|
||||
<div className="space-y-6 rounded-2xl border border-border bg-card p-8 shadow-sm">
|
||||
<div className="space-y-3">
|
||||
<p className="text-sm font-medium uppercase tracking-[0.2em] text-muted-foreground">
|
||||
User Management
|
||||
</p>
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-3xl font-semibold text-foreground">Permissions</h1>
|
||||
<p className="mt-3 max-w-2xl text-sm text-muted-foreground">
|
||||
Browse the full IAM permission catalog for the freight backoffice environment.
|
||||
</p>
|
||||
</div>
|
||||
<div className="rounded-full border border-border bg-muted px-3 py-1 text-sm font-medium text-muted-foreground">
|
||||
{filteredPermissions.length} permissions
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-3 rounded-2xl border border-border bg-background/60 p-4 md:grid-cols-[minmax(0,260px)_1fr] md:items-end">
|
||||
<div className="space-y-2">
|
||||
<p className="text-xs font-medium uppercase tracking-[0.18em] text-muted-foreground">
|
||||
Application
|
||||
</p>
|
||||
<Select value={selectedApplication} onValueChange={setSelectedApplication}>
|
||||
<SelectTrigger className="w-full rounded-xl bg-background">
|
||||
<SelectValue placeholder="Select application" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value={ALL_APPLICATIONS_VALUE}>All applications</SelectItem>
|
||||
<SelectItem value={SYSTEM_APPLICATION_VALUE}>System permissions</SelectItem>
|
||||
{applications.map((application) => (
|
||||
<SelectItem key={application.id} value={application.id}>
|
||||
{getLocaleLabel(application.name, application.key)}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Filter the IAM permission catalog by application, or view the shared system permissions that do not belong to any application.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{loading ? (
|
||||
<div className="rounded-2xl border border-dashed border-border bg-muted px-4 py-8 text-center text-sm text-muted-foreground">
|
||||
Loading permissions...
|
||||
</div>
|
||||
) : errorMessage ? (
|
||||
<div className="rounded-2xl border border-red-200 bg-red-50 px-4 py-8 text-center text-sm text-red-700 dark:border-red-950 dark:bg-red-950/30 dark:text-red-300">
|
||||
{errorMessage}
|
||||
</div>
|
||||
) : filteredPermissions.length ? (
|
||||
<div className="grid gap-3 md:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4">
|
||||
{filteredPermissions.map((permission) => (
|
||||
<article
|
||||
key={permission.id}
|
||||
className="rounded-2xl border border-border/70 bg-background/80 p-4 shadow-sm transition hover:border-border hover:bg-accent/20"
|
||||
>
|
||||
<div className="min-w-0 space-y-1">
|
||||
<p className="truncate text-sm font-semibold leading-5 text-foreground">
|
||||
{getLocaleLabel(permission.name, permission.key)}
|
||||
</p>
|
||||
<p className="truncate font-mono text-xs text-muted-foreground/90">
|
||||
{permission.key}
|
||||
</p>
|
||||
</div>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="rounded-2xl border border-dashed border-border bg-muted px-4 py-8 text-center text-sm text-muted-foreground">
|
||||
No permissions match the selected application.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{hasMore ? (
|
||||
<div className="flex items-center justify-between gap-4 rounded-2xl border border-border bg-background px-4 py-3">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Showing {permissions.length} of {count} permissions.
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void handleLoadMore()}
|
||||
disabled={loadingMore}
|
||||
className="inline-flex items-center justify-center rounded-xl bg-emerald-600 px-3 py-2 text-sm font-medium text-white transition hover:bg-emerald-700 disabled:cursor-not-allowed disabled:opacity-60"
|
||||
>
|
||||
{loadingMore ? "Loading..." : "Load more"}
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
};
|
||||
|
||||
export default PermissionsPage;
|
||||
@@ -1,11 +1,292 @@
|
||||
import FeaturePlaceholder from "@/components/FeaturePlaceholder";
|
||||
import { useEffect, useState } from "react";
|
||||
import { isAxiosError } from "axios";
|
||||
import { Shield } from "lucide-react";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@edr/ui-common";
|
||||
|
||||
import { api } from "@/auth/http";
|
||||
|
||||
interface LocaleText {
|
||||
en?: string;
|
||||
am?: string;
|
||||
}
|
||||
|
||||
interface RoleRecord {
|
||||
id: string;
|
||||
key: string;
|
||||
name?: LocaleText;
|
||||
}
|
||||
|
||||
interface PermissionRecord {
|
||||
id: string;
|
||||
key: string;
|
||||
name?: LocaleText;
|
||||
}
|
||||
|
||||
interface ListResponse<T> {
|
||||
items?: T[];
|
||||
data?: T[];
|
||||
}
|
||||
|
||||
const getLocaleLabel = (value?: LocaleText | null, fallback = "Unnamed") =>
|
||||
value?.en ?? value?.am ?? fallback;
|
||||
|
||||
const getItems = <T,>(payload: ListResponse<T> | T[] | undefined | null) => {
|
||||
if (!payload) {
|
||||
return [] as T[];
|
||||
}
|
||||
|
||||
if (Array.isArray(payload)) {
|
||||
return payload;
|
||||
}
|
||||
|
||||
return payload.items ?? payload.data ?? [];
|
||||
};
|
||||
|
||||
const RolesPage = () => {
|
||||
const [roles, setRoles] = useState<RoleRecord[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
const [selectedRole, setSelectedRole] = useState<RoleRecord | null>(null);
|
||||
const [rolePermissions, setRolePermissions] = useState<PermissionRecord[]>([]);
|
||||
const [rolePermissionsLoading, setRolePermissionsLoading] = useState(false);
|
||||
const [rolePermissionsError, setRolePermissionsError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let isMounted = true;
|
||||
|
||||
const loadRoles = async () => {
|
||||
setLoading(true);
|
||||
setErrorMessage(null);
|
||||
|
||||
try {
|
||||
const response = await api.get<ListResponse<RoleRecord>>("/roles");
|
||||
|
||||
if (!isMounted) {
|
||||
return;
|
||||
}
|
||||
|
||||
setRoles(
|
||||
getItems(response.data).sort((left, right) =>
|
||||
getLocaleLabel(left.name, left.key).localeCompare(
|
||||
getLocaleLabel(right.name, right.key),
|
||||
),
|
||||
),
|
||||
);
|
||||
} catch (error) {
|
||||
if (!isMounted) {
|
||||
return;
|
||||
}
|
||||
|
||||
setErrorMessage(
|
||||
isAxiosError(error)
|
||||
? error.response?.data?.message ?? "Unable to load roles."
|
||||
: "Unable to load roles.",
|
||||
);
|
||||
} finally {
|
||||
if (isMounted) {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
void loadRoles();
|
||||
|
||||
return () => {
|
||||
isMounted = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedRole) {
|
||||
setRolePermissions([]);
|
||||
setRolePermissionsError(null);
|
||||
setRolePermissionsLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
let isMounted = true;
|
||||
|
||||
const loadRolePermissions = async () => {
|
||||
setRolePermissionsLoading(true);
|
||||
setRolePermissionsError(null);
|
||||
|
||||
try {
|
||||
const response = await api.get<ListResponse<PermissionRecord>>(
|
||||
`/role-permissions/given-first/${selectedRole.id}`,
|
||||
);
|
||||
|
||||
if (!isMounted) {
|
||||
return;
|
||||
}
|
||||
|
||||
setRolePermissions(
|
||||
getItems(response.data).sort((left, right) =>
|
||||
getLocaleLabel(left.name, left.key).localeCompare(
|
||||
getLocaleLabel(right.name, right.key),
|
||||
),
|
||||
),
|
||||
);
|
||||
} catch (error) {
|
||||
if (!isMounted) {
|
||||
return;
|
||||
}
|
||||
|
||||
setRolePermissionsError(
|
||||
isAxiosError(error)
|
||||
? error.response?.data?.message ?? "Unable to load role details."
|
||||
: "Unable to load role details.",
|
||||
);
|
||||
} finally {
|
||||
if (isMounted) {
|
||||
setRolePermissionsLoading(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
void loadRolePermissions();
|
||||
|
||||
return () => {
|
||||
isMounted = false;
|
||||
};
|
||||
}, [selectedRole]);
|
||||
|
||||
return (
|
||||
<FeaturePlaceholder
|
||||
title="Roles"
|
||||
description="Define backoffice access roles, capability groups, and permission boundaries for freight administration."
|
||||
/>
|
||||
<section className="p-6">
|
||||
<div className="space-y-6 rounded-2xl border border-border bg-card p-8 shadow-sm">
|
||||
<div className="space-y-3">
|
||||
<p className="text-sm font-medium uppercase tracking-[0.2em] text-muted-foreground">
|
||||
User Management
|
||||
</p>
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-3xl font-semibold text-foreground">Roles</h1>
|
||||
<p className="mt-3 max-w-2xl text-sm text-muted-foreground">
|
||||
Browse freight backoffice roles and their internal keys in a simple grid view.
|
||||
</p>
|
||||
</div>
|
||||
<div className="rounded-full border border-border bg-muted px-3 py-1 text-sm font-medium text-muted-foreground">
|
||||
{roles.length} roles
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{loading ? (
|
||||
<div className="rounded-2xl border border-dashed border-border bg-muted px-4 py-8 text-center text-sm text-muted-foreground">
|
||||
Loading roles...
|
||||
</div>
|
||||
) : errorMessage ? (
|
||||
<div className="rounded-2xl border border-red-200 bg-red-50 px-4 py-8 text-center text-sm text-red-700 dark:border-red-950 dark:bg-red-950/30 dark:text-red-300">
|
||||
{errorMessage}
|
||||
</div>
|
||||
) : roles.length ? (
|
||||
<div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
|
||||
{roles.map((role) => (
|
||||
<button
|
||||
key={role.id}
|
||||
type="button"
|
||||
onClick={() => setSelectedRole(role)}
|
||||
className="rounded-2xl border border-border bg-background p-5 text-left transition hover:border-border/80 hover:bg-accent/20"
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex h-10 w-10 items-center justify-center rounded-xl bg-sky-50 text-sky-600 dark:bg-sky-950/40 dark:text-sky-300">
|
||||
<Shield className="h-5 w-5" />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<p className="truncate text-sm font-semibold text-foreground">
|
||||
{getLocaleLabel(role.name, role.key)}
|
||||
</p>
|
||||
<p className="truncate text-xs text-muted-foreground">{role.key}</p>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="rounded-2xl border border-dashed border-border bg-muted px-4 py-8 text-center text-sm text-muted-foreground">
|
||||
No roles available.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Dialog open={Boolean(selectedRole)} onOpenChange={(open) => !open && setSelectedRole(null)}>
|
||||
<DialogContent className="max-h-[85vh] overflow-y-auto sm:max-w-2xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{selectedRole ? getLocaleLabel(selectedRole.name, selectedRole.key) : "Role details"}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{selectedRole
|
||||
? `Review the permission set assigned to ${getLocaleLabel(selectedRole.name, selectedRole.key)}.`
|
||||
: undefined}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{selectedRole ? (
|
||||
<div className="space-y-6">
|
||||
<div className="grid gap-4 rounded-2xl border border-border bg-muted/40 p-4 sm:grid-cols-2">
|
||||
<div>
|
||||
<p className="text-xs font-medium uppercase tracking-[0.18em] text-muted-foreground">
|
||||
Role name
|
||||
</p>
|
||||
<p className="mt-2 text-sm font-semibold text-foreground">
|
||||
{getLocaleLabel(selectedRole.name, selectedRole.key)}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-xs font-medium uppercase tracking-[0.18em] text-muted-foreground">
|
||||
Role key
|
||||
</p>
|
||||
<p className="mt-2 font-mono text-sm text-foreground">{selectedRole.key}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<h2 className="text-sm font-semibold text-foreground">Permissions</h2>
|
||||
<div className="rounded-full border border-border bg-muted px-3 py-1 text-xs font-medium text-muted-foreground">
|
||||
{rolePermissions.length} permissions
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{rolePermissionsLoading ? (
|
||||
<div className="rounded-2xl border border-dashed border-border bg-muted px-4 py-8 text-center text-sm text-muted-foreground">
|
||||
Loading role details...
|
||||
</div>
|
||||
) : rolePermissionsError ? (
|
||||
<div className="rounded-2xl border border-red-200 bg-red-50 px-4 py-8 text-center text-sm text-red-700 dark:border-red-950 dark:bg-red-950/30 dark:text-red-300">
|
||||
{rolePermissionsError}
|
||||
</div>
|
||||
) : rolePermissions.length ? (
|
||||
<div className="grid gap-3 md:grid-cols-2">
|
||||
{rolePermissions.map((permission) => (
|
||||
<article
|
||||
key={permission.id}
|
||||
className="rounded-2xl border border-border/70 bg-background/80 p-4 shadow-sm"
|
||||
>
|
||||
<p className="truncate text-sm font-semibold leading-5 text-foreground">
|
||||
{getLocaleLabel(permission.name, permission.key)}
|
||||
</p>
|
||||
<p className="mt-1 truncate font-mono text-xs text-muted-foreground/90">
|
||||
{permission.key}
|
||||
</p>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="rounded-2xl border border-dashed border-border bg-muted px-4 py-8 text-center text-sm text-muted-foreground">
|
||||
No permissions are assigned to this role.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</section>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
UserCircle,
|
||||
FileUp,
|
||||
MapPinned,
|
||||
Loader2,
|
||||
} from "lucide-react";
|
||||
|
||||
import BookingsPage from "./pages/bookings/BookingsPage";
|
||||
@@ -31,12 +32,7 @@ import TrackingPage from "./pages/tracking/TrackingPage";
|
||||
import BillingPage from "./pages/billing/BillingPage";
|
||||
import TrainsPage from "./pages/trains/TrainsPage";
|
||||
import DashboardPage from "./pages/dashboard/DashboardPage";
|
||||
import {
|
||||
IamLoginPage,
|
||||
LoadingScreen,
|
||||
useAuth,
|
||||
useAuthUser,
|
||||
} from "@tria-plc/iamui-common";
|
||||
import useAuth from "./hooks/useAuth";
|
||||
import CustomersPage from "./pages/customers/CustomersPage";
|
||||
import CustomerDetailPage from "./pages/customers/CustomerDetailPage";
|
||||
import NewCustomerPage from "./pages/customers/NewCustomerPage";
|
||||
@@ -46,9 +42,12 @@ import FileUploadSettingsPage from "./pages/admin/FileUploadSettingsPage";
|
||||
import MyPortalPage from "./pages/portal/MyPortalPage";
|
||||
import EDRFreightLandingPage from "./pages/EDRFreightLandingPage";
|
||||
import SignupPage from "./pages/accounts/SignupPage";
|
||||
import OnboardingPage from "./pages/accounts/OnboardingPage";
|
||||
import VerificationOtpPage from "./pages/accounts/VerificationOtpPage";
|
||||
import SetPasswordPage from "./pages/accounts/SetPasswordPage";
|
||||
import LoginPage from "./pages/accounts/LoginPage";
|
||||
import Station from "./components/stations/Station";
|
||||
import { useEffect } from "react";
|
||||
|
||||
const sidebarItems: SidebarItem[] = [
|
||||
{ label: "My Portal", href: "/", icon: <UserCircle /> },
|
||||
@@ -72,44 +71,42 @@ const sidebarItems: SidebarItem[] = [
|
||||
const App = () => {
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const { user, loading } = useAuth();
|
||||
const { logout } = useAuthUser();
|
||||
const { user, isPending, logout, customer, customerQuery } = useAuth();
|
||||
|
||||
if (loading) {
|
||||
return <LoadingScreen />;
|
||||
console.log({ customer, isPending, user });
|
||||
useEffect(() => {
|
||||
if (!user) return;
|
||||
// if (!user.hasSetPassword) navigate("/set-password");
|
||||
}, [user]);
|
||||
|
||||
if (isPending) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-screen">
|
||||
<Loader2 className="animate-spin text-primary" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (user) {
|
||||
if (!user) {
|
||||
return (
|
||||
<Routes>
|
||||
<Route path="/" element={<EDRFreightLandingPage />} />
|
||||
<Route path="/login" element={<LoginPage />} />
|
||||
<Route path="/signup" element={<SignupPage />} />
|
||||
<Route path="/otp" element={<VerificationOtpPage />} />
|
||||
<Route path="/set-password" element={<SetPasswordPage />} />
|
||||
<Route path="/auth" element={<IamLoginPage />} />
|
||||
{/* <Route path="*" element={<Navigate to="/auth" replace />} /> */}
|
||||
<Route path="*" element={<Navigate to="/login" replace />} />
|
||||
</Routes>
|
||||
);
|
||||
}
|
||||
|
||||
if (user && !customer && !customerQuery.isPending) {
|
||||
return <OnboardingPage />;
|
||||
}
|
||||
|
||||
const displayName = user?.name?.en || user?.username || user?.email || "User";
|
||||
const userEmail = user?.email;
|
||||
|
||||
const handleLogout = () => {
|
||||
logout();
|
||||
[
|
||||
"auth-token",
|
||||
"refresh-token",
|
||||
"auth-user",
|
||||
"current-position-id",
|
||||
"selected-position-id",
|
||||
].forEach((name) => {
|
||||
document.cookie = `${name}=; Max-Age=0; path=/`;
|
||||
});
|
||||
localStorage.clear();
|
||||
window.location.replace("/auth");
|
||||
};
|
||||
|
||||
return (
|
||||
<DashboardLayout
|
||||
title="EDR Freight"
|
||||
@@ -119,7 +116,7 @@ const App = () => {
|
||||
enableThemeToggle
|
||||
userName={displayName}
|
||||
userEmail={userEmail}
|
||||
onLogout={handleLogout}
|
||||
onLogout={logout}
|
||||
>
|
||||
<Routes>
|
||||
<Route path="/dashboard" element={<DashboardPage />} />
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { ShieldCheck, Train } from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export interface AuthLayoutProps {
|
||||
children: ReactNode;
|
||||
parentClassName?: string;
|
||||
contentClassName?: string;
|
||||
left: {
|
||||
badge: string;
|
||||
title: string;
|
||||
description: string;
|
||||
features: string[];
|
||||
stats: {
|
||||
label: string;
|
||||
value: string;
|
||||
footer: string;
|
||||
progress: string;
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
export default function AuthLayout({
|
||||
children,
|
||||
parentClassName,
|
||||
contentClassName,
|
||||
left,
|
||||
}: AuthLayoutProps) {
|
||||
return (
|
||||
<div className="min-h-screen bg-background text-foreground">
|
||||
<div className={cn("grid min-h-screen lg:grid-cols-2", parentClassName)}>
|
||||
<div className="relative hidden overflow-hidden bg-primary p-8 px-12 text-primary-foreground lg:flex lg:flex-col lg:justify-between">
|
||||
<div className="absolute inset-0 bg-[radial-gradient(circle_at_top_right,rgba(255,255,255,0.14),transparent_35%)]" />
|
||||
<div className="relative z-10">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex size-14 items-center justify-center rounded-3xl bg-white/10 backdrop-blur">
|
||||
<Train className="size-7" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-xl font-bold">EDR Freight</h1>
|
||||
<p className="mt-1 text-sm opacity-80">
|
||||
Railway Logistics Platform
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-16 max-w-lg">
|
||||
<div className="inline-flex rounded-full bg-white/10 px-4 py-2 text-sm font-semibold backdrop-blur">
|
||||
{left.badge}
|
||||
</div>
|
||||
<h2 className="mt-6 text-4xl font-bold leading-tight tracking-tight">
|
||||
{left.title}
|
||||
</h2>
|
||||
<p className="mt-6 text-lg leading-8 opacity-85">
|
||||
{left.description}
|
||||
</p>
|
||||
</div>
|
||||
<div className="mt-14 grid gap-5">
|
||||
{left.features.map((item) => (
|
||||
<div key={item} className="flex items-center gap-3">
|
||||
<div className="flex size-10 items-center justify-center rounded-2xl bg-white/10">
|
||||
<ShieldCheck className="size-5" />
|
||||
</div>
|
||||
<span className="font-medium">{item}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center justify-center p-6 md:p-10",
|
||||
contentClassName,
|
||||
)}
|
||||
>
|
||||
<div className="w-full max-w-lg">
|
||||
<div className="mb-8 flex items-center gap-3 lg:hidden">
|
||||
<div className="flex size-12 items-center justify-center rounded-2xl bg-primary text-primary-foreground">
|
||||
<Train className="size-6" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">EDR Freight</h1>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Railway Logistics Platform
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div>{children}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { Field, FieldLabel, FieldError, Input } from "@edr/ui-common";
|
||||
|
||||
interface PhoneInputProps {
|
||||
disabled?: boolean;
|
||||
countryCode?: React.ComponentProps<typeof Input>;
|
||||
phone?: React.ComponentProps<typeof Input>;
|
||||
countryCodeError?: { message?: string };
|
||||
phoneError?: { message?: string };
|
||||
label?: string;
|
||||
}
|
||||
|
||||
export default function PhoneInput({
|
||||
disabled,
|
||||
countryCode: countryCodeProps,
|
||||
phone: phoneProps,
|
||||
countryCodeError,
|
||||
phoneError,
|
||||
label = "Phone Number",
|
||||
}: PhoneInputProps) {
|
||||
return (
|
||||
<Field data-invalid={Boolean(countryCodeError || phoneError)}>
|
||||
<FieldLabel>{label}</FieldLabel>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
type="text"
|
||||
disabled={disabled}
|
||||
className="w-20"
|
||||
aria-invalid={Boolean(countryCodeError)}
|
||||
{...countryCodeProps}
|
||||
/>
|
||||
<Input
|
||||
type="tel"
|
||||
placeholder="912345678"
|
||||
disabled={disabled}
|
||||
className="flex-1"
|
||||
aria-invalid={Boolean(phoneError)}
|
||||
{...phoneProps}
|
||||
/>
|
||||
</div>
|
||||
<FieldError errors={[countryCodeError, phoneError]} />
|
||||
</Field>
|
||||
);
|
||||
}
|
||||
@@ -1,21 +1,25 @@
|
||||
export const URL_CONSTANTS = {
|
||||
AUTH: {
|
||||
LOGIN: "/auth/login",
|
||||
REGISTER: "/auth/register",
|
||||
REFRESH_TOKEN: "/auth/refresh-token",
|
||||
LOGOUT: "/auth/logout",
|
||||
LOGIN: "/api/auth/login",
|
||||
REGISTER: "/api/auth/register",
|
||||
REFRESH_TOKEN: "/api/auth/refresh-token",
|
||||
LOGOUT: "/api/auth/logout",
|
||||
PROFILE: "/auth/profile",
|
||||
},
|
||||
|
||||
USERS: {
|
||||
SIGN_UP: "/api/auth/signup",
|
||||
GENERATE_VERIFICATION_CODE: "/api/auth/generate-verification-code",
|
||||
BASE: "/users",
|
||||
BY_ID: (id: string | number) => `/users/${id}`,
|
||||
SIGN_UP: "/api/auth/signup",
|
||||
SET_PASSWORD: "/api/auth/set-password",
|
||||
ME: "/api/auth/me"
|
||||
ME: "/api/auth/me",
|
||||
GENERATE_VERIFICATION_CODE: "/users/generate-verification-code",
|
||||
},
|
||||
|
||||
OTP: {
|
||||
SEND: "/api/otp/send",
|
||||
VERIFY: "/api/otp/verify",
|
||||
},
|
||||
ROLES: {
|
||||
BASE: "/roles",
|
||||
BY_ID: (id: string | number) => `/roles/${id}`,
|
||||
@@ -68,11 +72,11 @@ export const URL_CONSTANTS = {
|
||||
BY_ID: (id: string | number) => `/customers/${id}`,
|
||||
BOOKINGS: (id: string | number) => `/customers/${id}/bookings`,
|
||||
},
|
||||
|
||||
|
||||
CUSTOMERS_API: {
|
||||
BASE: "/api/customers",
|
||||
BY_ID: (id: string) => `/api/customers/${id}`,
|
||||
BY_USER_ID: (id: string) => `/api/customers/user/${id}`
|
||||
BY_USER_ID: (id: string) => `/api/customers/user/${id}`,
|
||||
},
|
||||
|
||||
BOOKINGS: {
|
||||
@@ -81,9 +85,4 @@ export const URL_CONSTANTS = {
|
||||
CANCEL: (id: string | number) => `/bookings/${id}/cancel`,
|
||||
CONFIRM: (id: string | number) => `/bookings/${id}/confirm`,
|
||||
},
|
||||
|
||||
OTP: {
|
||||
SEND: "/api/otp/send",
|
||||
VERIFY: "/api/otp/verify",
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
185
apps/edr-freight-web/portal/src/hooks/useAuth.ts
Normal file
185
apps/edr-freight-web/portal/src/hooks/useAuth.ts
Normal file
@@ -0,0 +1,185 @@
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { api } from "@/services/api";
|
||||
import type {
|
||||
LoginPayload,
|
||||
LoginResponse,
|
||||
SignupPayload,
|
||||
SignupResponse,
|
||||
OtpResponse,
|
||||
} from "@/types/auth";
|
||||
import type { Result } from "@/utils/result";
|
||||
import { extractApiError } from "@/utils/result";
|
||||
|
||||
function setCookie(name: string, value: string, days: number) {
|
||||
const expires = new Date();
|
||||
expires.setDate(expires.getDate() + days);
|
||||
document.cookie = `${name}=${value}; path=/; expires=${expires.toUTCString()}; SameSite=Lax`;
|
||||
}
|
||||
|
||||
function getCookie(name: string): string | undefined {
|
||||
return document.cookie
|
||||
.split("; ")
|
||||
.find((row) => row.startsWith(`${name}=`))
|
||||
?.split("=")[1];
|
||||
}
|
||||
|
||||
const useAuth = () => {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const authQuery = useQuery(
|
||||
api.auth.getMyInfo.queryOptions({
|
||||
enabled: !!getCookie("auth-token"),
|
||||
retry: false,
|
||||
staleTime: 10 * 60 * 1000,
|
||||
}),
|
||||
);
|
||||
|
||||
const customerQuery = useQuery(
|
||||
api.customers.getByUserId.queryOptions({
|
||||
input: { id: authQuery.data?.id ?? "" },
|
||||
enabled: !!authQuery.data?.id,
|
||||
retry: false,
|
||||
staleTime: 10 * 60 * 1000,
|
||||
refetchOnWindowFocus: false,
|
||||
}),
|
||||
);
|
||||
|
||||
const hasToken = !!getCookie("auth-token");
|
||||
const isPending = authQuery.isPending && hasToken;
|
||||
|
||||
const login = async (
|
||||
payload: LoginPayload,
|
||||
): Promise<Result<LoginResponse>> => {
|
||||
try {
|
||||
const res = await api.auth.login.call(payload);
|
||||
setCookie("auth-token", res.token, 7);
|
||||
setCookie("refresh-token", res.refreshToken, 7);
|
||||
await authQuery.refetch();
|
||||
return { success: true, data: res };
|
||||
} catch (err) {
|
||||
return { success: false, error: extractApiError(err) };
|
||||
}
|
||||
};
|
||||
|
||||
const signup = async (
|
||||
payload: SignupPayload,
|
||||
): Promise<Result<SignupResponse>> => {
|
||||
try {
|
||||
const res = await api.auth.createUser.call(payload);
|
||||
setCookie("auth-token", res.token, 7);
|
||||
setCookie("refresh-token", res.refreshToken, 7);
|
||||
await authQuery.refetch();
|
||||
const otpCode = res.otp?.split(" ")?.[6] ?? "";
|
||||
localStorage.setItem("otp", otpCode);
|
||||
localStorage.setItem("otp-phone", payload.phoneNumber);
|
||||
localStorage.setItem("otp-email", payload.email);
|
||||
api.auth.sendOTP
|
||||
.call({ phone: payload.phoneNumber, otp: otpCode })
|
||||
.catch(() => { });
|
||||
return { success: true, data: res };
|
||||
} catch (err) {
|
||||
return { success: false, error: extractApiError(err) };
|
||||
}
|
||||
};
|
||||
|
||||
const setPassword = async (data: {
|
||||
newPassword: string;
|
||||
confirmPassword: string;
|
||||
}): Promise<Result<void>> => {
|
||||
try {
|
||||
const userId = authQuery.data?.id ?? "";
|
||||
const email = localStorage.getItem("otp-email") ?? "";
|
||||
const verificationCode = localStorage.getItem("otp") ?? "";
|
||||
await api.auth.setPassword.call({
|
||||
newPassword: data.newPassword,
|
||||
confirmPassword: data.confirmPassword,
|
||||
userId,
|
||||
email,
|
||||
verificationCode,
|
||||
});
|
||||
["userId", "otp", "otp-phone", "otp-email"].forEach((k) =>
|
||||
localStorage.removeItem(k),
|
||||
);
|
||||
await queryClient.invalidateQueries({
|
||||
queryKey: api.auth.getMyInfo.queryKey(),
|
||||
});
|
||||
return { success: true, data: undefined };
|
||||
} catch (err) {
|
||||
return { success: false, error: extractApiError(err) };
|
||||
}
|
||||
};
|
||||
|
||||
const verifyOTP = async (otp: string): Promise<Result<OtpResponse>> => {
|
||||
try {
|
||||
const phone = localStorage.getItem("otp-phone") ?? "";
|
||||
const res = await api.auth.verifyOTP.call({ phone, otp });
|
||||
return { success: true, data: res };
|
||||
} catch (err) {
|
||||
return { success: false, error: extractApiError(err) };
|
||||
}
|
||||
};
|
||||
|
||||
const sendOTP = async (otp: string): Promise<Result<OtpResponse>> => {
|
||||
try {
|
||||
const phone = localStorage.getItem("otp-phone") ?? "";
|
||||
const res = await api.auth.sendOTP.call({ phone, otp });
|
||||
return { success: true, data: res };
|
||||
} catch (err) {
|
||||
return { success: false, error: extractApiError(err) };
|
||||
}
|
||||
};
|
||||
|
||||
const generateVerificationCode = async (
|
||||
type: string,
|
||||
): Promise<Result<string>> => {
|
||||
try {
|
||||
const email = localStorage.getItem("otp-email") ?? "";
|
||||
const phoneNumber = localStorage.getItem("otp-phone") ?? "";
|
||||
const res = await api.auth.generateVerificationCode.call({
|
||||
email,
|
||||
phoneNumber,
|
||||
type,
|
||||
});
|
||||
return { success: true, data: res };
|
||||
} catch (err) {
|
||||
return { success: false, error: extractApiError(err) };
|
||||
}
|
||||
};
|
||||
|
||||
const logout = async () => {
|
||||
try {
|
||||
await api.auth.logout.call();
|
||||
} catch {
|
||||
// proceed with client-side cleanup even if server call fails
|
||||
}
|
||||
[
|
||||
"auth-token",
|
||||
"refresh-token",
|
||||
"auth-user",
|
||||
"current-position-id",
|
||||
"selected-position-id",
|
||||
].forEach((name) => {
|
||||
document.cookie = `${name}=; Max-Age=0; path=/`;
|
||||
});
|
||||
localStorage.clear();
|
||||
queryClient.clear();
|
||||
window.location.href = "/login";
|
||||
};
|
||||
|
||||
return {
|
||||
isPending,
|
||||
user: authQuery.data ?? null,
|
||||
customer: customerQuery.data ?? null,
|
||||
login,
|
||||
signup,
|
||||
setPassword,
|
||||
verifyOTP,
|
||||
sendOTP,
|
||||
generateVerificationCode,
|
||||
logout,
|
||||
authQuery,
|
||||
customerQuery,
|
||||
};
|
||||
};
|
||||
|
||||
export default useAuth;
|
||||
@@ -2,18 +2,11 @@ import { StrictMode } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { BrowserRouter } from "react-router-dom";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import "@tria-plc/iamui-common/styles.css";
|
||||
import "@edr/ui-common/styles.css";
|
||||
import "../index.css";
|
||||
import "@edr/ui-common/theme.css";
|
||||
|
||||
import App from "./App";
|
||||
import {
|
||||
AuthProvider,
|
||||
configureIam,
|
||||
UserProvider,
|
||||
axiosInstance,
|
||||
} from "@tria-plc/iamui-common";
|
||||
|
||||
// Purge cookies that were stored as the literal string "undefined" before the
|
||||
// envelope interceptor fix. Without this, stale sessions would keep sending
|
||||
@@ -29,36 +22,6 @@ import {
|
||||
});
|
||||
|
||||
const queryClient = new QueryClient();
|
||||
window.__IAM_CONFIG__ = {
|
||||
apiUrl: `${import.meta.env.VITE_BASE_API_URL}/api`,
|
||||
postLoginPath: "/",
|
||||
};
|
||||
|
||||
// Unwrap the StandardResponse envelope ({ success, data, timestamp }) that the
|
||||
// freight API's ResponseTransformInterceptor adds to every response, so that
|
||||
// iamui-common can read response.data.token / response.data fields as expected.
|
||||
axiosInstance.interceptors.response.use((response) => {
|
||||
if (
|
||||
response.data &&
|
||||
typeof response.data === "object" &&
|
||||
"success" in response.data &&
|
||||
"data" in response.data
|
||||
) {
|
||||
response.data = response.data.data;
|
||||
}
|
||||
return response;
|
||||
});
|
||||
window.__USER_MANAGEMENT_BRANDING__ = {
|
||||
organizationName: "EDR Platform",
|
||||
appName: "EDR Portal",
|
||||
moduleBasePath: "/user-management",
|
||||
backToAppPath: "/",
|
||||
backToAppLabel: "Back to dashboard",
|
||||
};
|
||||
|
||||
configureIam({
|
||||
apiUrl: `${import.meta.env.VITE_BASE_API_URL}/api`,
|
||||
});
|
||||
|
||||
const rootElement = document.getElementById("root");
|
||||
|
||||
@@ -70,11 +33,7 @@ createRoot(document.getElementById("root")!).render(
|
||||
<StrictMode>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<BrowserRouter>
|
||||
<AuthProvider>
|
||||
<UserProvider>
|
||||
<App />
|
||||
</UserProvider>
|
||||
</AuthProvider>
|
||||
<App />
|
||||
</BrowserRouter>
|
||||
</QueryClientProvider>
|
||||
</StrictMode>,
|
||||
|
||||
190
apps/edr-freight-web/portal/src/pages/accounts/LoginPage.tsx
Normal file
190
apps/edr-freight-web/portal/src/pages/accounts/LoginPage.tsx
Normal file
@@ -0,0 +1,190 @@
|
||||
import { useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { ArrowRight, Mail, Phone, Loader2 } from "lucide-react";
|
||||
import useAuth from "@/hooks/useAuth";
|
||||
import AuthLayout from "@/components/auth/AuthLayout";
|
||||
import {
|
||||
Button,
|
||||
Input,
|
||||
Field,
|
||||
FieldLabel,
|
||||
FieldError,
|
||||
FieldGroup,
|
||||
} from "@edr/ui-common";
|
||||
import PhoneInput from "@/components/auth/PhoneInput";
|
||||
|
||||
type LoginMethod = "email" | "phone";
|
||||
|
||||
export default function LoginPage() {
|
||||
const navigate = useNavigate();
|
||||
const { login } = useAuth();
|
||||
const [method, setMethod] = useState<LoginMethod>("email");
|
||||
const [identifier, setIdentifier] = useState("");
|
||||
const [countryCode, setCountryCode] = useState("+251");
|
||||
const [phoneNumber, setPhoneNumber] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
setLoading(true);
|
||||
try {
|
||||
const loginId = method === "email"
|
||||
? identifier
|
||||
: `${countryCode}${phoneNumber.startsWith("0") ? phoneNumber.slice(1) : phoneNumber}`;
|
||||
const result = await login({ email: loginId, password });
|
||||
if (result.success) {
|
||||
navigate("/");
|
||||
} else {
|
||||
setError(result.error.message);
|
||||
}
|
||||
} catch {
|
||||
setError("An unexpected error occurred");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<AuthLayout
|
||||
left={{
|
||||
badge: "Welcome Back",
|
||||
title: "Sign in to your freight operations account",
|
||||
description:
|
||||
"Access your dashboard to manage shipments, monitor railway operations, track consignments, and streamline logistics workflows.",
|
||||
features: [
|
||||
"Real-time shipment tracking",
|
||||
"Secure logistics management",
|
||||
"Enterprise-grade operations",
|
||||
"Multi-corridor freight monitoring",
|
||||
],
|
||||
stats: {
|
||||
label: "Active Corridors",
|
||||
value: "24+",
|
||||
footer: "Operational",
|
||||
progress: "w-[95%]",
|
||||
},
|
||||
}}
|
||||
>
|
||||
<div className="mb-6">
|
||||
<div className="mb-4 flex size-12 items-center justify-center rounded-2xl bg-primary/10 text-primary">
|
||||
<Mail className="size-6" />
|
||||
</div>
|
||||
<h2 className="text-2xl font-black tracking-tight">Welcome back</h2>
|
||||
<p className="mt-2 text-base text-muted-foreground">
|
||||
Enter your credentials to access your portal
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="flex flex-col gap-4">
|
||||
<div className="flex gap-2 rounded-lg bg-muted p-1">
|
||||
<Button
|
||||
type="button"
|
||||
variant={"ghost"}
|
||||
size="sm"
|
||||
onClick={() => setMethod("email")}
|
||||
className={`flex-1 hover:bg-background/40! ${method === "email" ? "bg-background shadow border" : ""}`}
|
||||
>
|
||||
<Mail data-icon="inline-start" />
|
||||
Email
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant={"ghost"}
|
||||
size="sm"
|
||||
onClick={() => setMethod("phone")}
|
||||
className={`flex-1 hover:bg-background/40! ${method === "phone" ? "bg-background shadow border" : ""}`}
|
||||
>
|
||||
<Phone data-icon="inline-start" />
|
||||
Phone
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<FieldGroup>
|
||||
{method === "email" ? (
|
||||
<Field>
|
||||
<FieldLabel>Email Address</FieldLabel>
|
||||
<Input
|
||||
type="email"
|
||||
placeholder="name@company.com"
|
||||
value={identifier}
|
||||
onChange={(e) => setIdentifier(e.target.value)}
|
||||
required
|
||||
disabled={loading}
|
||||
/>
|
||||
</Field>
|
||||
) : (
|
||||
<PhoneInput
|
||||
disabled={loading}
|
||||
countryCode={{
|
||||
value: countryCode,
|
||||
onChange: (e: React.ChangeEvent<HTMLInputElement>) => setCountryCode(e.target.value),
|
||||
}}
|
||||
phone={{
|
||||
value: phoneNumber,
|
||||
onChange: (e: React.ChangeEvent<HTMLInputElement>) => setPhoneNumber(e.target.value),
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
<Field>
|
||||
<div className="flex items-center justify-between">
|
||||
<FieldLabel>Password</FieldLabel>
|
||||
<Button
|
||||
type="button"
|
||||
variant="link"
|
||||
size="xs"
|
||||
className="h-auto p-0"
|
||||
>
|
||||
Forgot password?
|
||||
</Button>
|
||||
</div>
|
||||
<Input
|
||||
type="password"
|
||||
placeholder="••••••••"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
disabled={loading}
|
||||
/>
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
|
||||
{error && (
|
||||
<div className="rounded-xl border border-red-200 bg-red-50 px-4 py-2.5 text-sm text-red-700">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Button type="submit" disabled={loading} size="lg" className="w-full">
|
||||
{loading ? (
|
||||
<>
|
||||
<Loader2 className="animate-spin" data-icon="inline-start" />
|
||||
Signing in...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
Sign In
|
||||
<ArrowRight data-icon="inline-end" />
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
|
||||
<p className="text-center text-sm text-muted-foreground">
|
||||
Don't have an account?{" "}
|
||||
<Button
|
||||
type="button"
|
||||
variant="link"
|
||||
size="sm"
|
||||
onClick={() => navigate("/signup")}
|
||||
className="h-auto p-0 font-semibold"
|
||||
>
|
||||
Create an account
|
||||
</Button>
|
||||
</p>
|
||||
</form>
|
||||
</AuthLayout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,520 @@
|
||||
import { useState } from "react";
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
ArrowRight,
|
||||
ArrowLeft,
|
||||
Building2,
|
||||
User,
|
||||
FileText,
|
||||
CheckCircle2,
|
||||
Loader2,
|
||||
} from "lucide-react";
|
||||
import useAuth from "@/hooks/useAuth";
|
||||
import { api } from "@/services/api";
|
||||
import type { CreateCustomerDto } from "@/types/customers";
|
||||
import AuthLayout from "@/components/auth/AuthLayout";
|
||||
import PhoneInput from "@/components/auth/PhoneInput";
|
||||
import {
|
||||
Button,
|
||||
Input,
|
||||
Field,
|
||||
FieldLabel,
|
||||
FieldError,
|
||||
FieldGroup,
|
||||
} from "@edr/ui-common";
|
||||
|
||||
type OnboardingStep = "company" | "personnel" | "poa";
|
||||
|
||||
const onboardingSchema = z.object({
|
||||
companyName: z.string().min(1, "Company name is required"),
|
||||
companyEmail: z.string().email("Invalid email address"),
|
||||
companyPhone: z.string().min(1, "Company phone is required"),
|
||||
companyPhoneCountryCode: z.string().min(1, "Country code is required"),
|
||||
companyLocation: z.string().min(1, "Location is required"),
|
||||
companyAddress: z.string().min(1, "Address is required"),
|
||||
tinNumber: z.string().length(10, "TIN must be exactly 10 digits"),
|
||||
vatNumber: z
|
||||
.string()
|
||||
.min(1, "VAT number is required")
|
||||
.length(10, "VAT number must be exactly 10 digits"),
|
||||
fanNumber: z.string().length(16, "FAN must be exactly 16 digits"),
|
||||
contactPersonName: z.string().min(1, "Contact person name is required"),
|
||||
contactPersonPhone: z.string().min(1, "Contact person phone is required"),
|
||||
contactPersonPhoneCountryCode: z.string().min(1, "Country code is required"),
|
||||
generalManagerName: z.string().min(1, "GM name is required"),
|
||||
generalManagerEmail: z.string().email("Invalid GM email"),
|
||||
generalManagerPhone: z.string().min(1, "GM phone is required"),
|
||||
generalManagerPhoneCountryCode: z.string().min(1, "Country code is required"),
|
||||
poaName: z.string().optional(),
|
||||
poaPhone: z.string().optional(),
|
||||
poaPhoneCountryCode: z.string().optional(),
|
||||
poaAddress: z.string().optional(),
|
||||
poaEmail: z.string().optional(),
|
||||
poaLocation: z.string().optional(),
|
||||
});
|
||||
|
||||
type FormData = z.infer<typeof onboardingSchema>;
|
||||
|
||||
const stepFields: Record<OnboardingStep, (keyof FormData)[]> = {
|
||||
company: [
|
||||
"companyName",
|
||||
"companyEmail",
|
||||
"companyPhone",
|
||||
"companyPhoneCountryCode",
|
||||
"companyLocation",
|
||||
"companyAddress",
|
||||
"tinNumber",
|
||||
"vatNumber",
|
||||
"fanNumber",
|
||||
],
|
||||
personnel: [
|
||||
"contactPersonName",
|
||||
"contactPersonPhone",
|
||||
"contactPersonPhoneCountryCode",
|
||||
"generalManagerName",
|
||||
"generalManagerEmail",
|
||||
"generalManagerPhone",
|
||||
"generalManagerPhoneCountryCode",
|
||||
],
|
||||
poa: [],
|
||||
};
|
||||
|
||||
export default function OnboardingPage() {
|
||||
const queryClient = useQueryClient();
|
||||
const { user } = useAuth();
|
||||
const [step, setStep] = useState<OnboardingStep>("company");
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
trigger,
|
||||
formState: { errors },
|
||||
} = useForm<FormData>({
|
||||
resolver: zodResolver(onboardingSchema),
|
||||
defaultValues: {
|
||||
companyName: "",
|
||||
companyEmail: "",
|
||||
companyPhone: "",
|
||||
companyPhoneCountryCode: "+251",
|
||||
companyLocation: "",
|
||||
companyAddress: "",
|
||||
tinNumber: "",
|
||||
vatNumber: "",
|
||||
fanNumber: "",
|
||||
contactPersonName: "",
|
||||
contactPersonPhone: "",
|
||||
contactPersonPhoneCountryCode: "+251",
|
||||
generalManagerName: "",
|
||||
generalManagerEmail: "",
|
||||
generalManagerPhone: "",
|
||||
generalManagerPhoneCountryCode: "+251",
|
||||
poaName: "",
|
||||
poaPhone: "",
|
||||
poaPhoneCountryCode: "+251",
|
||||
poaAddress: "",
|
||||
poaEmail: "",
|
||||
poaLocation: "",
|
||||
},
|
||||
});
|
||||
|
||||
const createCustomerMutation = useMutation({
|
||||
mutationFn: (payload: CreateCustomerDto) =>
|
||||
api.customers.create.call(payload),
|
||||
onSuccess: () => {
|
||||
if (user)
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: api.customers.getByUserId.queryKey({ id: user.id }),
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const nextStep = async () => {
|
||||
if (step === "poa") {
|
||||
handleSubmit(onSubmit)();
|
||||
return;
|
||||
}
|
||||
const fields = stepFields[step];
|
||||
const isValid = await trigger(fields);
|
||||
if (!isValid) return;
|
||||
setStep(step === "company" ? "personnel" : "poa");
|
||||
};
|
||||
|
||||
const prevStep = () => {
|
||||
if (step === "personnel") setStep("company");
|
||||
else if (step === "poa") setStep("personnel");
|
||||
};
|
||||
|
||||
const onSubmit = async (data: FormData) => {
|
||||
const nameParts = (user?.name?.en ?? "").split(" ");
|
||||
const payload: CreateCustomerDto = {
|
||||
userId: user!.id,
|
||||
firstName: nameParts[0] || "",
|
||||
lastName: nameParts.slice(-1)[0] || "",
|
||||
email: user!.email,
|
||||
phone: user!.phoneNumber,
|
||||
companyName: data.companyName,
|
||||
companyEmail: data.companyEmail,
|
||||
companyPhone: `${data.companyPhoneCountryCode}${data.companyPhone}`,
|
||||
companyLocation: data.companyLocation,
|
||||
companyAddress: data.companyAddress,
|
||||
contactPersonName: data.contactPersonName,
|
||||
contactPersonPhone: `${data.contactPersonPhoneCountryCode}${data.contactPersonPhone}`,
|
||||
tinNumber: data.tinNumber,
|
||||
vatNumber: data.vatNumber,
|
||||
fanNumber: data.fanNumber,
|
||||
generalManagerName: data.generalManagerName,
|
||||
generalManagerEmail: data.generalManagerEmail,
|
||||
generalManagerPhone: `${data.generalManagerPhoneCountryCode}${data.generalManagerPhone}`,
|
||||
poaName: data.poaName || undefined,
|
||||
poaPhone:
|
||||
data.poaPhone && data.poaPhoneCountryCode
|
||||
? `${data.poaPhoneCountryCode}${data.poaPhone}`
|
||||
: undefined,
|
||||
poaAddress: data.poaAddress || undefined,
|
||||
poaEmail: data.poaEmail || undefined,
|
||||
poaLocation: data.poaLocation || undefined,
|
||||
};
|
||||
createCustomerMutation.mutate(payload);
|
||||
};
|
||||
|
||||
return (
|
||||
<AuthLayout
|
||||
left={{
|
||||
badge: "Complete Your Profile",
|
||||
title: "Set up your company profile",
|
||||
description:
|
||||
"Provide your business details to start using EDR Freight for managing shipments, tracking consignments, and streamlining logistics operations across Ethiopia and Djibouti.",
|
||||
features: [
|
||||
"Company registration details",
|
||||
"Contact and management personnel",
|
||||
"Power of Attorney (optional)",
|
||||
],
|
||||
stats: {
|
||||
label: "Active Customers",
|
||||
value: "500+",
|
||||
footer: "And growing",
|
||||
progress: "w-[95%]",
|
||||
},
|
||||
}}
|
||||
>
|
||||
<div className="mb-8 lg:col-span-2">
|
||||
<div className="flex items-center justify-between max-w-lg mx-auto relative px-2">
|
||||
<div className="absolute top-1/2 left-0 w-full h-0.5 bg-border -translate-y-1/2 z-0" />
|
||||
<StepIcon
|
||||
icon={<Building2 className="size-5" />}
|
||||
active={step === "company"}
|
||||
completed={step !== "company"}
|
||||
/>
|
||||
<StepIcon
|
||||
icon={<User className="size-5" />}
|
||||
active={step === "personnel"}
|
||||
completed={step === "poa"}
|
||||
/>
|
||||
<StepIcon
|
||||
icon={<FileText className="size-5" />}
|
||||
active={step === "poa"}
|
||||
completed={false}
|
||||
/>
|
||||
</div>
|
||||
<p className="text-center text-sm text-muted-foreground mt-3">
|
||||
{step === "company" && "Step 1 of 3 — Company Information"}
|
||||
{step === "personnel" && "Step 2 of 3 — Personnel Details"}
|
||||
{step === "poa" && "Step 3 of 3 — Power of Attorney (Optional)"}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="flex flex-col gap-4">
|
||||
<FieldGroup className="gap-4">
|
||||
{step === "company" && (
|
||||
<>
|
||||
<Field data-invalid={Boolean(errors.companyName)}>
|
||||
<FieldLabel>Company Name</FieldLabel>
|
||||
<Input
|
||||
placeholder="Global Logistics Ltd"
|
||||
aria-invalid={Boolean(errors.companyName)}
|
||||
{...register("companyName")}
|
||||
/>
|
||||
<FieldError errors={[errors.companyName]} />
|
||||
</Field>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<Field data-invalid={Boolean(errors.companyEmail)}>
|
||||
<FieldLabel>Company Email</FieldLabel>
|
||||
<Input
|
||||
type="email"
|
||||
placeholder="ops@company.com"
|
||||
aria-invalid={Boolean(errors.companyEmail)}
|
||||
{...register("companyEmail")}
|
||||
/>
|
||||
<FieldError errors={[errors.companyEmail]} />
|
||||
</Field>
|
||||
|
||||
<PhoneInput
|
||||
countryCode={{ ...register("companyPhoneCountryCode") }}
|
||||
phone={{
|
||||
...register("companyPhone"),
|
||||
placeholder: "912345678",
|
||||
}}
|
||||
countryCodeError={errors.companyPhoneCountryCode}
|
||||
phoneError={errors.companyPhone}
|
||||
label="Company Phone"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<Field data-invalid={Boolean(errors.companyLocation)}>
|
||||
<FieldLabel>Location</FieldLabel>
|
||||
<Input
|
||||
placeholder="Addis Ababa, Ethiopia"
|
||||
aria-invalid={Boolean(errors.companyLocation)}
|
||||
{...register("companyLocation")}
|
||||
/>
|
||||
<FieldError errors={[errors.companyLocation]} />
|
||||
</Field>
|
||||
|
||||
<Field data-invalid={Boolean(errors.companyAddress)}>
|
||||
<FieldLabel>Address</FieldLabel>
|
||||
<Input
|
||||
placeholder="Bole Subcity, Woreda 03"
|
||||
aria-invalid={Boolean(errors.companyAddress)}
|
||||
{...register("companyAddress")}
|
||||
/>
|
||||
<FieldError errors={[errors.companyAddress]} />
|
||||
</Field>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<Field data-invalid={Boolean(errors.tinNumber)}>
|
||||
<FieldLabel>TIN Number (10 digits)</FieldLabel>
|
||||
<Input
|
||||
placeholder="1234567890"
|
||||
maxLength={10}
|
||||
aria-invalid={Boolean(errors.tinNumber)}
|
||||
{...register("tinNumber")}
|
||||
/>
|
||||
<FieldError errors={[errors.tinNumber]} />
|
||||
</Field>
|
||||
|
||||
<Field data-invalid={Boolean(errors.vatNumber)}>
|
||||
<FieldLabel>VAT Number</FieldLabel>
|
||||
<Input
|
||||
placeholder="VAT-12345"
|
||||
aria-invalid={Boolean(errors.vatNumber)}
|
||||
maxLength={10}
|
||||
{...register("vatNumber")}
|
||||
/>
|
||||
<FieldError errors={[errors.vatNumber]} />
|
||||
</Field>
|
||||
</div>
|
||||
|
||||
<Field data-invalid={Boolean(errors.fanNumber)}>
|
||||
<FieldLabel>FAN Number (16 digits)</FieldLabel>
|
||||
<Input
|
||||
placeholder="1234567890123456"
|
||||
maxLength={16}
|
||||
aria-invalid={Boolean(errors.fanNumber)}
|
||||
{...register("fanNumber")}
|
||||
/>
|
||||
<FieldError errors={[errors.fanNumber]} />
|
||||
</Field>
|
||||
</>
|
||||
)}
|
||||
|
||||
{step === "personnel" && (
|
||||
<>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Personal details are pulled from your account. Contact and
|
||||
management info is collected below.
|
||||
</p>
|
||||
|
||||
<div>
|
||||
<h3 className="text-sm font-semibold text-foreground mb-3">
|
||||
Contact Person
|
||||
</h3>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<Field data-invalid={Boolean(errors.contactPersonName)}>
|
||||
<FieldLabel>Name</FieldLabel>
|
||||
<Input
|
||||
placeholder="Jane Smith"
|
||||
aria-invalid={Boolean(errors.contactPersonName)}
|
||||
{...register("contactPersonName")}
|
||||
/>
|
||||
<FieldError errors={[errors.contactPersonName]} />
|
||||
</Field>
|
||||
|
||||
<PhoneInput
|
||||
countryCode={{
|
||||
...register("contactPersonPhoneCountryCode"),
|
||||
}}
|
||||
phone={{
|
||||
...register("contactPersonPhone"),
|
||||
placeholder: "912345678",
|
||||
}}
|
||||
countryCodeError={errors.contactPersonPhoneCountryCode}
|
||||
phoneError={errors.contactPersonPhone}
|
||||
label="Phone"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<hr className="border-border" />
|
||||
|
||||
<div>
|
||||
<h3 className="text-sm font-semibold text-foreground mb-3">
|
||||
General Manager
|
||||
</h3>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<Field
|
||||
className="col-span-2"
|
||||
data-invalid={Boolean(errors.generalManagerName)}
|
||||
>
|
||||
<FieldLabel>Name</FieldLabel>
|
||||
<Input
|
||||
placeholder="Abebe Bikila"
|
||||
aria-invalid={Boolean(errors.generalManagerName)}
|
||||
{...register("generalManagerName")}
|
||||
/>
|
||||
<FieldError errors={[errors.generalManagerName]} />
|
||||
</Field>
|
||||
|
||||
<Field data-invalid={Boolean(errors.generalManagerEmail)}>
|
||||
<FieldLabel>Email</FieldLabel>
|
||||
<Input
|
||||
type="email"
|
||||
placeholder="gm@company.com"
|
||||
aria-invalid={Boolean(errors.generalManagerEmail)}
|
||||
{...register("generalManagerEmail")}
|
||||
/>
|
||||
<FieldError errors={[errors.generalManagerEmail]} />
|
||||
</Field>
|
||||
|
||||
<PhoneInput
|
||||
countryCode={{
|
||||
...register("generalManagerPhoneCountryCode"),
|
||||
}}
|
||||
phone={{
|
||||
...register("generalManagerPhone"),
|
||||
placeholder: "912345678",
|
||||
}}
|
||||
countryCodeError={errors.generalManagerPhoneCountryCode}
|
||||
phoneError={errors.generalManagerPhone}
|
||||
label="Phone"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{step === "poa" && (
|
||||
<>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Power of Attorney details are optional. Skip if not applicable.
|
||||
</p>
|
||||
|
||||
<Field>
|
||||
<FieldLabel>PoA Name</FieldLabel>
|
||||
<Input
|
||||
placeholder="Authorized Representative Name"
|
||||
{...register("poaName")}
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<Field>
|
||||
<FieldLabel>PoA Email</FieldLabel>
|
||||
<Input
|
||||
type="email"
|
||||
placeholder="poa@company.com"
|
||||
{...register("poaEmail")}
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<PhoneInput
|
||||
countryCode={{ ...register("poaPhoneCountryCode") }}
|
||||
phone={{ ...register("poaPhone"), placeholder: "912345678" }}
|
||||
label="PoA Phone"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<Field>
|
||||
<FieldLabel>PoA Location</FieldLabel>
|
||||
<Input
|
||||
placeholder="City, Country"
|
||||
{...register("poaLocation")}
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<Field>
|
||||
<FieldLabel>PoA Address</FieldLabel>
|
||||
<Input
|
||||
placeholder="Full Address"
|
||||
{...register("poaAddress")}
|
||||
/>
|
||||
</Field>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</FieldGroup>
|
||||
|
||||
<div className="flex items-center justify-between pt-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={prevStep}
|
||||
disabled={step === "company"}
|
||||
>
|
||||
<ArrowLeft />
|
||||
Back
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
onClick={nextStep}
|
||||
disabled={createCustomerMutation.isPending}
|
||||
>
|
||||
{createCustomerMutation.isPending ? (
|
||||
<>
|
||||
<Loader2 className="animate-spin" />
|
||||
Submitting...
|
||||
</>
|
||||
) : step === "poa" ? (
|
||||
"Complete Registration"
|
||||
) : (
|
||||
<>
|
||||
Next Step
|
||||
<ArrowRight />
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</AuthLayout>
|
||||
);
|
||||
}
|
||||
|
||||
function StepIcon({
|
||||
icon,
|
||||
active,
|
||||
completed,
|
||||
}: {
|
||||
icon: React.ReactNode;
|
||||
active: boolean;
|
||||
completed: boolean;
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
className={`relative z-10 flex h-10 w-10 items-center justify-center rounded-full border-2 transition-all ${completed
|
||||
? "bg-primary border-primary text-primary-foreground"
|
||||
: active
|
||||
? "bg-background border-primary text-primary shadow-md"
|
||||
: "bg-background border-border text-muted-foreground"
|
||||
}`}
|
||||
>
|
||||
{completed ? <CheckCircle2 className="size-5" /> : icon}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,418 +1,217 @@
|
||||
import { setPassword } from "@/services/account";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import {
|
||||
ArrowRight,
|
||||
LockKeyhole,
|
||||
ShieldCheck,
|
||||
Train,
|
||||
Eye,
|
||||
EyeOff,
|
||||
} from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { useState, useMemo } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { z } from "zod";
|
||||
import { ArrowRight, Check, Eye, EyeOff, LockKeyhole, Loader2, X } from "lucide-react";
|
||||
import useAuth from "@/hooks/useAuth";
|
||||
import AuthLayout from "@/components/auth/AuthLayout";
|
||||
import { cn } from "@/lib/utils";
|
||||
import {
|
||||
Button,
|
||||
Input,
|
||||
Field,
|
||||
FieldLabel,
|
||||
FieldError,
|
||||
FieldGroup,
|
||||
} from "@edr/ui-common";
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// Schema
|
||||
// -----------------------------------------------------------------------------
|
||||
const passwordRequirements = [
|
||||
{ label: "At least 8 characters", test: (v: string) => v.length >= 8 },
|
||||
{ label: "One uppercase letter", test: (v: string) => /[A-Z]/.test(v) },
|
||||
{ label: "One lowercase letter", test: (v: string) => /[a-z]/.test(v) },
|
||||
{ label: "One number", test: (v: string) => /\d/.test(v) },
|
||||
{ label: "One special character", test: (v: string) => /[^A-Za-z0-9]/.test(v) },
|
||||
] as const;
|
||||
|
||||
const passwordSchema = z
|
||||
.object({
|
||||
password: z
|
||||
.string()
|
||||
.min(
|
||||
8,
|
||||
"Password must be at least 8 characters"
|
||||
),
|
||||
|
||||
confirmPassword: z
|
||||
.string()
|
||||
.min(
|
||||
8,
|
||||
"Confirm password is required"
|
||||
),
|
||||
.min(8, "Password must be at least 8 characters")
|
||||
.regex(/[A-Z]/, "Password must include an uppercase letter")
|
||||
.regex(/[a-z]/, "Password must include a lowercase letter")
|
||||
.regex(/\d/, "Password must include a number")
|
||||
.regex(/[^A-Za-z0-9]/, "Password must include a special character"),
|
||||
confirmPassword: z.string().min(1, "Please confirm your password"),
|
||||
})
|
||||
.refine(
|
||||
(data) =>
|
||||
data.password ===
|
||||
data.confirmPassword,
|
||||
{
|
||||
message:
|
||||
"Passwords do not match",
|
||||
path: ["confirmPassword"],
|
||||
}
|
||||
);
|
||||
.refine((data) => data.password === data.confirmPassword, {
|
||||
message: "Passwords do not match",
|
||||
path: ["confirmPassword"],
|
||||
});
|
||||
|
||||
type FormData = z.infer<
|
||||
typeof passwordSchema
|
||||
>;
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// Component
|
||||
// -----------------------------------------------------------------------------
|
||||
type FormData = z.infer<typeof passwordSchema>;
|
||||
|
||||
export default function SetPasswordPage() {
|
||||
const [
|
||||
showPassword,
|
||||
setShowPassword,
|
||||
] = useState(false);
|
||||
|
||||
const [
|
||||
showConfirmPassword,
|
||||
setShowConfirmPassword,
|
||||
] = useState(false);
|
||||
const navigate = useNavigate();
|
||||
const { setPassword } = useAuth();
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const [showConfirmPassword, setShowConfirmPassword] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
watch,
|
||||
formState: { errors },
|
||||
reset,
|
||||
} = useForm<FormData>({
|
||||
resolver:
|
||||
zodResolver(passwordSchema),
|
||||
|
||||
defaultValues: {
|
||||
password: "",
|
||||
confirmPassword: "",
|
||||
},
|
||||
resolver: zodResolver(passwordSchema),
|
||||
defaultValues: { password: "", confirmPassword: "" },
|
||||
});
|
||||
|
||||
const naviagte = useNavigate();
|
||||
const password = watch("password");
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Mutation
|
||||
// ---------------------------------------------------------------------------
|
||||
const requirements = useMemo(
|
||||
() => passwordRequirements.map((r) => ({ ...r, met: r.test(password || "") })),
|
||||
[password],
|
||||
);
|
||||
|
||||
const setPasswordMutation =
|
||||
useMutation({
|
||||
mutationFn: async (
|
||||
data: FormData
|
||||
) => setPassword({
|
||||
newPassword: data?.password,
|
||||
confirmPassword: data?.confirmPassword,
|
||||
userId: localStorage.getItem("userId"),
|
||||
email: localStorage.getItem("otp-email"),
|
||||
verificationCode: localStorage.getItem("otp"),
|
||||
}),
|
||||
const allMet = requirements.every((r) => r.met);
|
||||
|
||||
onSuccess: () => {
|
||||
naviagte("/auth");
|
||||
reset();
|
||||
},
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Submit
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const onSubmit = async (
|
||||
data: FormData
|
||||
) => {
|
||||
const onSubmit = async (data: FormData) => {
|
||||
setError(null);
|
||||
setLoading(true);
|
||||
try {
|
||||
await setPasswordMutation.mutateAsync(
|
||||
data
|
||||
);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
const result = await setPassword({
|
||||
newPassword: data.password,
|
||||
confirmPassword: data.confirmPassword,
|
||||
});
|
||||
if (result.success) {
|
||||
navigate("/auth");
|
||||
} else {
|
||||
setError(result.error.message);
|
||||
}
|
||||
} catch {
|
||||
setError("An unexpected error occurred");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// UI
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-background text-foreground">
|
||||
<div className="grid min-h-screen lg:grid-cols-2">
|
||||
{/* ------------------------------------------------------------------ */}
|
||||
{/* Left Side */}
|
||||
{/* ------------------------------------------------------------------ */}
|
||||
|
||||
<div className="relative hidden overflow-hidden bg-primary p-12 text-primary-foreground lg:flex lg:flex-col lg:justify-between">
|
||||
<div className="absolute inset-0 bg-[radial-gradient(circle_at_top_right,rgba(255,255,255,0.14),transparent_35%)]" />
|
||||
|
||||
<div className="relative z-10">
|
||||
{/* Logo */}
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex size-14 items-center justify-center rounded-3xl bg-white/10 backdrop-blur">
|
||||
<Train className="size-7" />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h1 className="text-3xl font-black tracking-tight">
|
||||
EDR Freight
|
||||
</h1>
|
||||
|
||||
<p className="mt-1 text-sm opacity-80">
|
||||
Railway Logistics
|
||||
Platform
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Hero */}
|
||||
<div className="mt-20 max-w-lg">
|
||||
<div className="inline-flex rounded-full bg-white/10 px-4 py-2 text-sm font-semibold backdrop-blur">
|
||||
Account Security
|
||||
</div>
|
||||
|
||||
<h2 className="mt-6 text-5xl font-black leading-tight tracking-tight">
|
||||
Set your secure
|
||||
password
|
||||
</h2>
|
||||
|
||||
<p className="mt-6 text-lg leading-8 opacity-85">
|
||||
Create a strong
|
||||
password to secure
|
||||
your EDR Freight
|
||||
account and protect
|
||||
railway logistics
|
||||
operations and shipment
|
||||
data.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Features */}
|
||||
<div className="mt-14 grid gap-5">
|
||||
{[
|
||||
"Enterprise-grade security",
|
||||
"Protected account access",
|
||||
"Secure freight operations",
|
||||
"Advanced authentication system",
|
||||
].map((item) => (
|
||||
<div
|
||||
key={item}
|
||||
className="flex items-center gap-3"
|
||||
>
|
||||
<div className="flex size-10 items-center justify-center rounded-2xl bg-white/10">
|
||||
<ShieldCheck className="size-5" />
|
||||
</div>
|
||||
|
||||
<span className="font-medium">
|
||||
{item}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Stats */}
|
||||
<div className="relative z-10 rounded-[32px] border border-white/10 bg-white/10 p-6 backdrop-blur-xl">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm opacity-80">
|
||||
Security Protection
|
||||
</p>
|
||||
|
||||
<h3 className="mt-2 text-4xl font-black">
|
||||
256-bit
|
||||
</h3>
|
||||
</div>
|
||||
|
||||
<div className="rounded-2xl bg-white/10 px-4 py-2 text-sm font-semibold">
|
||||
Encrypted
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-6 h-3 overflow-hidden rounded-full bg-white/10">
|
||||
<div className="h-full w-[98%] rounded-full bg-white" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ------------------------------------------------------------------ */}
|
||||
{/* Right Side */}
|
||||
{/* ------------------------------------------------------------------ */}
|
||||
|
||||
<div className="flex items-center justify-center p-6 md:p-10">
|
||||
<div className="w-full max-w-xl">
|
||||
{/* Mobile Logo */}
|
||||
<div className="mb-8 flex items-center gap-3 lg:hidden">
|
||||
<div className="flex size-12 items-center justify-center rounded-2xl bg-primary text-primary-foreground">
|
||||
<Train className="size-6" />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">
|
||||
EDR Freight
|
||||
</h1>
|
||||
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Railway Logistics
|
||||
Platform
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Card */}
|
||||
<div className="rounded-[36px] border border-border bg-card p-8 shadow-2xl md:p-10">
|
||||
{/* Header */}
|
||||
<div className="mb-8">
|
||||
<div className="mb-4 flex size-16 items-center justify-center rounded-3xl bg-primary/10 text-primary">
|
||||
<LockKeyhole className="size-8" />
|
||||
</div>
|
||||
|
||||
<h2 className="text-4xl font-black tracking-tight">
|
||||
Set Password
|
||||
</h2>
|
||||
|
||||
<p className="mt-3 text-lg text-muted-foreground">
|
||||
Create a secure
|
||||
password for your
|
||||
EDR Freight account.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Success */}
|
||||
{setPasswordMutation.isSuccess && (
|
||||
<div className="mb-6 rounded-2xl border border-green-200 bg-green-50 px-4 py-3 text-sm text-green-700">
|
||||
Password updated
|
||||
successfully.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Error */}
|
||||
{setPasswordMutation.isError && (
|
||||
<div className="mb-6 rounded-2xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
|
||||
Failed to set
|
||||
password. Please try
|
||||
again.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Form */}
|
||||
<form
|
||||
onSubmit={handleSubmit(
|
||||
onSubmit
|
||||
)}
|
||||
className="space-y-6"
|
||||
>
|
||||
{/* Password */}
|
||||
<div>
|
||||
<label className="mb-2 block text-sm font-semibold">
|
||||
Password
|
||||
</label>
|
||||
|
||||
<div className="relative">
|
||||
<input
|
||||
type={
|
||||
showPassword
|
||||
? "text"
|
||||
: "password"
|
||||
}
|
||||
placeholder="Enter password"
|
||||
disabled={
|
||||
setPasswordMutation.isPending
|
||||
}
|
||||
{...register(
|
||||
"password"
|
||||
)}
|
||||
className="h-14 w-full rounded-2xl border border-input bg-background px-4 pr-14 outline-none transition focus:border-primary focus:ring-4 focus:ring-primary/10 disabled:opacity-60"
|
||||
/>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() =>
|
||||
setShowPassword(
|
||||
!showPassword
|
||||
)
|
||||
}
|
||||
className="absolute right-4 top-1/2 -translate-y-1/2 text-muted-foreground"
|
||||
>
|
||||
{showPassword ? (
|
||||
<EyeOff className="size-5" />
|
||||
) : (
|
||||
<Eye className="size-5" />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{errors.password && (
|
||||
<p className="mt-1 text-sm text-red-500">
|
||||
{
|
||||
errors.password
|
||||
.message
|
||||
}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Confirm Password */}
|
||||
<div>
|
||||
<label className="mb-2 block text-sm font-semibold">
|
||||
Confirm Password
|
||||
</label>
|
||||
|
||||
<div className="relative">
|
||||
<input
|
||||
type={
|
||||
showConfirmPassword
|
||||
? "text"
|
||||
: "password"
|
||||
}
|
||||
placeholder="Confirm password"
|
||||
disabled={
|
||||
setPasswordMutation.isPending
|
||||
}
|
||||
{...register(
|
||||
"confirmPassword"
|
||||
)}
|
||||
className="h-14 w-full rounded-2xl border border-input bg-background px-4 pr-14 outline-none transition focus:border-primary focus:ring-4 focus:ring-primary/10 disabled:opacity-60"
|
||||
/>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() =>
|
||||
setShowConfirmPassword(
|
||||
!showConfirmPassword
|
||||
)
|
||||
}
|
||||
className="absolute right-4 top-1/2 -translate-y-1/2 text-muted-foreground"
|
||||
>
|
||||
{showConfirmPassword ? (
|
||||
<EyeOff className="size-5" />
|
||||
) : (
|
||||
<Eye className="size-5" />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{errors.confirmPassword && (
|
||||
<p className="mt-1 text-sm text-red-500">
|
||||
{
|
||||
errors
|
||||
.confirmPassword
|
||||
.message
|
||||
}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Submit */}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={
|
||||
setPasswordMutation.isPending
|
||||
}
|
||||
className="flex h-14 w-full items-center justify-center gap-2 rounded-2xl bg-primary text-lg font-semibold text-primary-foreground shadow-lg transition hover:-translate-y-0.5 hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-60"
|
||||
>
|
||||
{setPasswordMutation.isPending ? (
|
||||
"Saving..."
|
||||
) : (
|
||||
<>
|
||||
Save Password
|
||||
|
||||
<ArrowRight className="size-5" />
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<AuthLayout
|
||||
left={{
|
||||
badge: "Account Security",
|
||||
title: "Set your secure password",
|
||||
description:
|
||||
"Create a strong password to secure your EDR Freight account and protect railway logistics operations and shipment data.",
|
||||
features: [
|
||||
"Enterprise-grade security",
|
||||
"Protected account access",
|
||||
"Secure freight operations",
|
||||
"Advanced authentication system",
|
||||
],
|
||||
stats: { label: "Security Protection", value: "256-bit", footer: "Encrypted", progress: "w-[98%]" },
|
||||
}}
|
||||
>
|
||||
<div className="mb-6">
|
||||
<div className="mb-4 flex size-12 items-center justify-center rounded-2xl bg-primary/10 text-primary">
|
||||
<LockKeyhole className="size-6" />
|
||||
</div>
|
||||
<h2 className="text-2xl font-black tracking-tight">Set Password</h2>
|
||||
<p className="mt-2 text-base text-muted-foreground">
|
||||
Create a secure password for your account.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="mb-4 rounded-xl border border-red-200 bg-red-50 px-4 py-2.5 text-sm text-red-700">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="flex flex-col gap-4">
|
||||
<FieldGroup>
|
||||
<Field data-invalid={Boolean(errors.password)}>
|
||||
<FieldLabel>Password</FieldLabel>
|
||||
<div className="relative">
|
||||
<Input
|
||||
type={showPassword ? "text" : "password"}
|
||||
placeholder="Enter password"
|
||||
disabled={loading}
|
||||
aria-invalid={Boolean(errors.password)}
|
||||
className="pr-12"
|
||||
{...register("password")}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={() => setShowPassword(!showPassword)}
|
||||
className="absolute right-1 top-1/2 -translate-y-1/2 text-muted-foreground"
|
||||
>
|
||||
{showPassword ? <EyeOff /> : <Eye />}
|
||||
</Button>
|
||||
</div>
|
||||
<FieldError errors={[errors.password]} />
|
||||
</Field>
|
||||
|
||||
{password && (
|
||||
<ul className="space-y-1.5">
|
||||
{requirements.map((req) => (
|
||||
<li
|
||||
key={req.label}
|
||||
className={cn(
|
||||
"flex items-center gap-2 text-sm",
|
||||
req.met ? "text-emerald-600" : "text-muted-foreground",
|
||||
)}
|
||||
>
|
||||
{req.met ? (
|
||||
<Check className="size-4 shrink-0 text-emerald-500" />
|
||||
) : (
|
||||
<X className="size-4 shrink-0 text-muted-foreground/50" />
|
||||
)}
|
||||
{req.label}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
<Field data-invalid={Boolean(errors.confirmPassword)}>
|
||||
<FieldLabel>Confirm Password</FieldLabel>
|
||||
<div className="relative">
|
||||
<Input
|
||||
type={showConfirmPassword ? "text" : "password"}
|
||||
placeholder="Confirm password"
|
||||
disabled={loading}
|
||||
aria-invalid={Boolean(errors.confirmPassword)}
|
||||
className="pr-12"
|
||||
{...register("confirmPassword")}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={() => setShowConfirmPassword(!showConfirmPassword)}
|
||||
className="absolute right-1 top-1/2 -translate-y-1/2 text-muted-foreground"
|
||||
>
|
||||
{showConfirmPassword ? <EyeOff /> : <Eye />}
|
||||
</Button>
|
||||
</div>
|
||||
<FieldError errors={[errors.confirmPassword]} />
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={loading || !allMet}
|
||||
size="lg"
|
||||
className="w-full"
|
||||
>
|
||||
{loading ? (
|
||||
<>
|
||||
<Loader2 className="animate-spin" data-icon="inline-start" />
|
||||
Saving...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
Save Password
|
||||
<ArrowRight data-icon="inline-end" />
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
</AuthLayout>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,534 +1,197 @@
|
||||
import { userType } from "@/enums/userType";
|
||||
import { createOTP, createUser } from "@/services/account";
|
||||
|
||||
import { CreateUserPayload } from "@/types/createUser";
|
||||
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
|
||||
import {
|
||||
ArrowRight,
|
||||
ShieldCheck,
|
||||
Train,
|
||||
UserPlus,
|
||||
} from "lucide-react";
|
||||
|
||||
import { useForm } from "react-hook-form";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { z } from "zod";
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// Schema
|
||||
// -----------------------------------------------------------------------------
|
||||
import { ArrowRight, UserPlus, Loader2 } from "lucide-react";
|
||||
import { userType } from "@/enums/userType";
|
||||
import useAuth from "@/hooks/useAuth";
|
||||
import type { SignupPayload } from "@/types/auth";
|
||||
import AuthLayout from "@/components/auth/AuthLayout";
|
||||
import PhoneInput from "@/components/auth/PhoneInput";
|
||||
import {
|
||||
Button,
|
||||
Input,
|
||||
Field,
|
||||
FieldLabel,
|
||||
FieldError,
|
||||
FieldGroup,
|
||||
} from "@edr/ui-common";
|
||||
|
||||
const userSchema = z.object({
|
||||
email: z
|
||||
.string()
|
||||
.email("Invalid email address"),
|
||||
|
||||
username: z
|
||||
.string()
|
||||
.min(
|
||||
3,
|
||||
"Username must be at least 3 characters"
|
||||
),
|
||||
|
||||
countryCode: z
|
||||
.string()
|
||||
.min(
|
||||
1,
|
||||
"Country code is required"
|
||||
),
|
||||
|
||||
phone: z
|
||||
.string()
|
||||
.min(
|
||||
9,
|
||||
"Phone number is too short"
|
||||
)
|
||||
.max(
|
||||
9,
|
||||
"Phone number is too long"
|
||||
),
|
||||
|
||||
email: z.string().email("Invalid email address"),
|
||||
username: z.string().min(3, "Username must be at least 3 characters"),
|
||||
countryCode: z.string().min(1, "Country code is required"),
|
||||
phone: z.string().min(9, "Phone number is too short").max(9, "Phone number is too long"),
|
||||
userType: z.string(),
|
||||
|
||||
name: z.object({
|
||||
en: z
|
||||
.string()
|
||||
.min(2, "Name is required"),
|
||||
|
||||
en: z.string().min(2, "Name is required"),
|
||||
am: z.string().nullable(),
|
||||
}),
|
||||
});
|
||||
|
||||
type FormData = z.infer<
|
||||
typeof userSchema
|
||||
>;
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// Component
|
||||
// -----------------------------------------------------------------------------
|
||||
type FormData = z.infer<typeof userSchema>;
|
||||
|
||||
export default function SignupPage() {
|
||||
const navigate = useNavigate();
|
||||
const { signup } = useAuth();
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
formState: { errors },
|
||||
reset,
|
||||
} = useForm<FormData>({
|
||||
resolver:
|
||||
zodResolver(userSchema),
|
||||
|
||||
resolver: zodResolver(userSchema),
|
||||
defaultValues: {
|
||||
email: "",
|
||||
username: "",
|
||||
countryCode: "+251",
|
||||
phone: "",
|
||||
userType:
|
||||
userType.individual,
|
||||
|
||||
name: {
|
||||
en: "",
|
||||
am: "",
|
||||
},
|
||||
userType: userType.individual,
|
||||
name: { en: "", am: "" },
|
||||
},
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Create User Mutation
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const createUserMutation =
|
||||
useMutation({
|
||||
mutationFn: (
|
||||
user: CreateUserPayload
|
||||
) => createUser(user),
|
||||
|
||||
onSuccess: () => {
|
||||
reset();
|
||||
},
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Submit
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const onSubmit = async (
|
||||
data: FormData
|
||||
) => {
|
||||
const onSubmit = async (data: FormData) => {
|
||||
setError(null);
|
||||
setLoading(true);
|
||||
try {
|
||||
const normalizedPhone =
|
||||
data.phone.startsWith(
|
||||
"0"
|
||||
)
|
||||
? data.phone.slice(1)
|
||||
: data.phone;
|
||||
|
||||
const fullPhoneNumber = `${data.countryCode
|
||||
}${normalizedPhone}`;
|
||||
|
||||
const payload: CreateUserPayload =
|
||||
{
|
||||
const normalizedPhone = data.phone.startsWith("0") ? data.phone.slice(1) : data.phone;
|
||||
const payload: SignupPayload = {
|
||||
email: data.email,
|
||||
|
||||
username:
|
||||
data.username,
|
||||
|
||||
phoneNumber:
|
||||
fullPhoneNumber,
|
||||
|
||||
userType:
|
||||
data.userType,
|
||||
|
||||
name: {
|
||||
en: data.name.en,
|
||||
am:
|
||||
data.name.am ||
|
||||
"",
|
||||
},
|
||||
username: data.username,
|
||||
phoneNumber: `${data.countryCode}${normalizedPhone}`,
|
||||
userType: data.userType,
|
||||
name: { en: data.name.en, am: data.name.am ?? "" },
|
||||
};
|
||||
|
||||
const res =
|
||||
await createUserMutation.mutateAsync(
|
||||
payload
|
||||
);
|
||||
|
||||
if (res?.success) {
|
||||
// save auth token
|
||||
// document.cookie = `auth-token=${res.data?.token}; path=/`;
|
||||
localStorage.setItem(
|
||||
"auth-token",
|
||||
`auth-token=${res.data?.token}; path=/`
|
||||
);
|
||||
localStorage.setItem(
|
||||
"userId",res.data?.userId
|
||||
);
|
||||
localStorage.setItem(
|
||||
"otp",res.data?.otp?.split(" ")?.[6]
|
||||
);
|
||||
createOTP({ phone: payload.phoneNumber, otp:res.data?.otp?.split(" ")?.[6] })
|
||||
// save phone for otp page
|
||||
localStorage.setItem(
|
||||
"otp-phone",
|
||||
payload.phoneNumber
|
||||
);
|
||||
// save phone for set password page
|
||||
|
||||
localStorage.setItem(
|
||||
"otp-email",
|
||||
payload.email
|
||||
);
|
||||
// navigate otp page
|
||||
const result = await signup(payload);
|
||||
if (result.success) {
|
||||
navigate("/otp");
|
||||
} else {
|
||||
setError(result.error.message);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
} catch {
|
||||
setError("An unexpected error occurred");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// UI
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-background text-foreground">
|
||||
<div className="grid min-h-screen lg:grid-cols-2">
|
||||
{/* ------------------------------------------------------------------ */}
|
||||
{/* Left Side */}
|
||||
{/* ------------------------------------------------------------------ */}
|
||||
|
||||
<div className="relative hidden overflow-hidden bg-primary p-12 text-primary-foreground lg:flex lg:flex-col lg:justify-between">
|
||||
<div className="absolute inset-0 bg-[radial-gradient(circle_at_top_right,rgba(255,255,255,0.14),transparent_35%)]" />
|
||||
|
||||
<div className="relative z-10">
|
||||
{/* Logo */}
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex size-14 items-center justify-center rounded-3xl bg-white/10 backdrop-blur">
|
||||
<Train className="size-7" />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h1 className="text-3xl font-black tracking-tight">
|
||||
EDR Freight
|
||||
</h1>
|
||||
|
||||
<p className="mt-1 text-sm opacity-80">
|
||||
Railway Logistics
|
||||
Platform
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Hero */}
|
||||
<div className="mt-20 max-w-lg">
|
||||
<div className="inline-flex rounded-full bg-white/10 px-4 py-2 text-sm font-semibold backdrop-blur">
|
||||
Smart Freight
|
||||
Operations
|
||||
</div>
|
||||
|
||||
<h2 className="mt-6 text-5xl font-black leading-tight tracking-tight">
|
||||
Create your freight
|
||||
operations account
|
||||
</h2>
|
||||
|
||||
<p className="mt-6 text-lg leading-8 opacity-85">
|
||||
Join EDR Freight to
|
||||
manage shipments,
|
||||
monitor railway
|
||||
operations, track
|
||||
consignments, and
|
||||
streamline logistics
|
||||
workflows across
|
||||
Ethiopia and
|
||||
Djibouti.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Features */}
|
||||
<div className="mt-14 grid gap-5">
|
||||
{[
|
||||
"Real-time shipment tracking",
|
||||
"Secure logistics management",
|
||||
"Enterprise-grade operations",
|
||||
"Multi-corridor freight monitoring",
|
||||
].map((item) => (
|
||||
<div
|
||||
key={item}
|
||||
className="flex items-center gap-3"
|
||||
>
|
||||
<div className="flex size-10 items-center justify-center rounded-2xl bg-white/10">
|
||||
<ShieldCheck className="size-5" />
|
||||
</div>
|
||||
|
||||
<span className="font-medium">
|
||||
{item}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Stats */}
|
||||
<div className="relative z-10 rounded-[32px] border border-white/10 bg-white/10 p-6 backdrop-blur-xl">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm opacity-80">
|
||||
Active Corridors
|
||||
</p>
|
||||
|
||||
<h3 className="mt-2 text-4xl font-black">
|
||||
24+
|
||||
</h3>
|
||||
</div>
|
||||
|
||||
<div className="rounded-2xl bg-white/10 px-4 py-2 text-sm font-semibold">
|
||||
Operational
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-6 h-3 overflow-hidden rounded-full bg-white/10">
|
||||
<div className="h-full w-[95%] rounded-full bg-white" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ------------------------------------------------------------------ */}
|
||||
{/* Right Side */}
|
||||
{/* ------------------------------------------------------------------ */}
|
||||
|
||||
<div className="flex items-center justify-center p-6 md:p-10">
|
||||
<div className="w-full max-w-2xl">
|
||||
{/* Mobile Logo */}
|
||||
<div className="mb-8 flex items-center gap-3 lg:hidden">
|
||||
<div className="flex size-12 items-center justify-center rounded-2xl bg-primary text-primary-foreground">
|
||||
<Train className="size-6" />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">
|
||||
EDR Freight
|
||||
</h1>
|
||||
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Railway Logistics
|
||||
Platform
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Form Card */}
|
||||
<div className="rounded-[36px] border border-border bg-card p-8 shadow-2xl md:p-10">
|
||||
{/* Header */}
|
||||
<div className="mb-8">
|
||||
<div className="mb-4 flex size-16 items-center justify-center rounded-3xl bg-primary/10 text-primary">
|
||||
<UserPlus className="size-8" />
|
||||
</div>
|
||||
|
||||
<h2 className="text-4xl font-black tracking-tight">
|
||||
Create Account
|
||||
</h2>
|
||||
|
||||
<p className="mt-3 text-lg text-muted-foreground">
|
||||
Register to access
|
||||
EDR Freight
|
||||
services and railway
|
||||
logistics operations.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Success */}
|
||||
{createUserMutation.isSuccess && (
|
||||
<div className="mb-6 rounded-2xl border border-green-200 bg-green-50 px-4 py-3 text-sm text-green-700">
|
||||
Account created
|
||||
successfully.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Error */}
|
||||
{createUserMutation.isError && (
|
||||
<div className="mb-6 rounded-2xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
|
||||
Failed to create
|
||||
account. Please try
|
||||
again.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Form */}
|
||||
<form
|
||||
onSubmit={handleSubmit(
|
||||
onSubmit
|
||||
)}
|
||||
className="space-y-6"
|
||||
>
|
||||
{/* Full Name */}
|
||||
<div>
|
||||
<label className="mb-2 block text-sm font-semibold">
|
||||
Full Name
|
||||
</label>
|
||||
|
||||
<input
|
||||
type="text"
|
||||
placeholder="John Doe"
|
||||
disabled={
|
||||
createUserMutation.isPending
|
||||
}
|
||||
{...register(
|
||||
"name.en"
|
||||
)}
|
||||
className="h-13 w-full rounded-2xl border border-input bg-background px-4 outline-none transition focus:border-primary focus:ring-4 focus:ring-primary/10 disabled:opacity-60"
|
||||
/>
|
||||
|
||||
{errors.name?.en && (
|
||||
<p className="mt-1 text-sm text-red-500">
|
||||
{
|
||||
errors.name.en
|
||||
.message
|
||||
}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Username */}
|
||||
<div>
|
||||
<label className="mb-2 block text-sm font-semibold">
|
||||
Username
|
||||
</label>
|
||||
|
||||
<input
|
||||
type="text"
|
||||
placeholder="john_doe"
|
||||
disabled={
|
||||
createUserMutation.isPending
|
||||
}
|
||||
{...register(
|
||||
"username"
|
||||
)}
|
||||
className="h-13 w-full rounded-2xl border border-input bg-background px-4 outline-none transition focus:border-primary focus:ring-4 focus:ring-primary/10 disabled:opacity-60"
|
||||
/>
|
||||
|
||||
{errors.username && (
|
||||
<p className="mt-1 text-sm text-red-500">
|
||||
{
|
||||
errors.username
|
||||
.message
|
||||
}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Email */}
|
||||
<div>
|
||||
<label className="mb-2 block text-sm font-semibold">
|
||||
Email Address
|
||||
</label>
|
||||
|
||||
<input
|
||||
type="email"
|
||||
placeholder="john@example.com"
|
||||
disabled={
|
||||
createUserMutation.isPending
|
||||
}
|
||||
{...register(
|
||||
"email"
|
||||
)}
|
||||
className="h-13 w-full rounded-2xl border border-input bg-background px-4 outline-none transition focus:border-primary focus:ring-4 focus:ring-primary/10 disabled:opacity-60"
|
||||
/>
|
||||
|
||||
{errors.email && (
|
||||
<p className="mt-1 text-sm text-red-500">
|
||||
{
|
||||
errors.email
|
||||
.message
|
||||
}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Phone */}
|
||||
<div>
|
||||
<label className="mb-2 block text-sm font-semibold">
|
||||
Phone Number
|
||||
</label>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
type="text"
|
||||
disabled={
|
||||
createUserMutation.isPending
|
||||
}
|
||||
{...register(
|
||||
"countryCode"
|
||||
)}
|
||||
className="h-13 w-28 rounded-2xl border border-input bg-background px-4 outline-none transition focus:border-primary focus:ring-4 focus:ring-primary/10 disabled:opacity-60"
|
||||
/>
|
||||
|
||||
<input
|
||||
type="tel"
|
||||
placeholder="912345678"
|
||||
disabled={
|
||||
createUserMutation.isPending
|
||||
}
|
||||
{...register(
|
||||
"phone"
|
||||
)}
|
||||
className="h-13 flex-1 rounded-2xl border border-input bg-background px-4 outline-none transition focus:border-primary focus:ring-4 focus:ring-primary/10 disabled:opacity-60"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{(errors.countryCode ||
|
||||
errors.phone) && (
|
||||
<p className="mt-1 text-sm text-red-500">
|
||||
{errors
|
||||
.countryCode
|
||||
?.message ||
|
||||
errors.phone
|
||||
?.message}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Submit */}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={
|
||||
createUserMutation.isPending
|
||||
}
|
||||
className="flex h-14 w-full items-center justify-center gap-2 rounded-2xl bg-primary text-lg font-semibold text-primary-foreground shadow-lg transition hover:-translate-y-0.5 hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-60"
|
||||
>
|
||||
{createUserMutation.isPending ? (
|
||||
"Creating..."
|
||||
) : (
|
||||
<>
|
||||
Create Account
|
||||
|
||||
<ArrowRight className="size-5" />
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
|
||||
{/* Footer */}
|
||||
<p className="text-center text-sm text-muted-foreground">
|
||||
Already have an
|
||||
account?
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className="ml-2 font-semibold text-primary hover:underline"
|
||||
>
|
||||
Sign In
|
||||
</button>
|
||||
</p>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<AuthLayout
|
||||
left={{
|
||||
badge: "Smart Freight Operations",
|
||||
title: "Create your freight operations account",
|
||||
description:
|
||||
"Join EDR Freight to manage shipments, monitor railway operations, track consignments, and streamline logistics workflows across Ethiopia and Djibouti.",
|
||||
features: [
|
||||
"Real-time shipment tracking",
|
||||
"Secure logistics management",
|
||||
"Enterprise-grade operations",
|
||||
"Multi-corridor freight monitoring",
|
||||
],
|
||||
stats: { label: "Active Corridors", value: "24+", footer: "Operational", progress: "w-[95%]" },
|
||||
}}
|
||||
>
|
||||
<div className="mb-6">
|
||||
<div className="mb-4 flex size-12 items-center justify-center rounded-2xl bg-primary/10 text-primary">
|
||||
<UserPlus className="size-6" />
|
||||
</div>
|
||||
<h2 className="text-2xl font-black tracking-tight">Create Account</h2>
|
||||
<p className="mt-2 text-base text-muted-foreground">
|
||||
Register to access EDR Freight services.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="mb-4 rounded-xl border border-red-200 bg-red-50 px-4 py-2.5 text-sm text-red-700">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="flex flex-col gap-4">
|
||||
<FieldGroup className="gap-4">
|
||||
<Field data-invalid={Boolean(errors.name?.en)}>
|
||||
<FieldLabel>Full Name</FieldLabel>
|
||||
<Input
|
||||
type="text"
|
||||
placeholder="John Doe"
|
||||
disabled={loading}
|
||||
aria-invalid={Boolean(errors.name?.en)}
|
||||
{...register("name.en")}
|
||||
/>
|
||||
<FieldError errors={[errors.name?.en]} />
|
||||
</Field>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<Field data-invalid={Boolean(errors.username)}>
|
||||
<FieldLabel>Username</FieldLabel>
|
||||
<Input
|
||||
type="text"
|
||||
placeholder="john_doe"
|
||||
disabled={loading}
|
||||
aria-invalid={Boolean(errors.username)}
|
||||
{...register("username")}
|
||||
/>
|
||||
<FieldError errors={[errors.username]} />
|
||||
</Field>
|
||||
|
||||
<Field data-invalid={Boolean(errors.email)}>
|
||||
<FieldLabel>Email Address</FieldLabel>
|
||||
<Input
|
||||
type="email"
|
||||
placeholder="john@example.com"
|
||||
disabled={loading}
|
||||
aria-invalid={Boolean(errors.email)}
|
||||
{...register("email")}
|
||||
/>
|
||||
<FieldError errors={[errors.email]} />
|
||||
</Field>
|
||||
</div>
|
||||
|
||||
<PhoneInput
|
||||
disabled={loading}
|
||||
countryCode={{ ...register("countryCode") }}
|
||||
phone={{ ...register("phone") }}
|
||||
countryCodeError={errors.countryCode}
|
||||
phoneError={errors.phone}
|
||||
/>
|
||||
</FieldGroup>
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
size="lg"
|
||||
className="w-full"
|
||||
>
|
||||
{loading ? (
|
||||
<>
|
||||
<Loader2 className="animate-spin" data-icon="inline-start" />
|
||||
Creating...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
Create Account
|
||||
<ArrowRight data-icon="inline-end" />
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
|
||||
<p className="text-center text-sm text-muted-foreground">
|
||||
Already have an account?
|
||||
<Button
|
||||
type="button"
|
||||
variant="link"
|
||||
size="sm"
|
||||
onClick={() => navigate("/login")}
|
||||
className="h-auto p-0 font-semibold"
|
||||
>
|
||||
Sign In
|
||||
</Button>
|
||||
</p>
|
||||
</form>
|
||||
</AuthLayout>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,70 +1,36 @@
|
||||
import { verificationCodeType } from "@/enums/verificationCodeType";
|
||||
|
||||
import {
|
||||
generateVerificationCode,
|
||||
verifyOTP,
|
||||
} from "@/services/account";
|
||||
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
|
||||
import {
|
||||
ArrowRight,
|
||||
ShieldCheck,
|
||||
Train,
|
||||
MailCheck,
|
||||
RotateCw,
|
||||
} from "lucide-react";
|
||||
|
||||
import { useForm } from "react-hook-form";
|
||||
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { z } from "zod";
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// Schema
|
||||
// -----------------------------------------------------------------------------
|
||||
import { ArrowRight, MailCheck, RotateCw, Loader2 } from "lucide-react";
|
||||
import { verificationCodeType } from "@/enums/verificationCodeType";
|
||||
import useAuth from "@/hooks/useAuth";
|
||||
import AuthLayout from "@/components/auth/AuthLayout";
|
||||
import {
|
||||
Button,
|
||||
Input,
|
||||
Field,
|
||||
FieldLabel,
|
||||
FieldError,
|
||||
FieldGroup,
|
||||
} from "@edr/ui-common";
|
||||
|
||||
const otpSchema = z.object({
|
||||
code: z
|
||||
.string()
|
||||
.regex(
|
||||
/^\d{6}$/,
|
||||
"OTP must be exactly 6 digits"
|
||||
),
|
||||
code: z.string().regex(/^\d{6}$/, "OTP must be exactly 6 digits"),
|
||||
});
|
||||
|
||||
type FormData = z.infer<
|
||||
typeof otpSchema
|
||||
>;
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// Component
|
||||
// -----------------------------------------------------------------------------
|
||||
type FormData = z.infer<typeof otpSchema>;
|
||||
|
||||
export default function VerificationOtpPage() {
|
||||
const navigate =
|
||||
useNavigate();
|
||||
const navigate = useNavigate();
|
||||
const { verifyOTP, generateVerificationCode } = useAuth();
|
||||
const [verifying, setVerifying] = useState(false);
|
||||
const [resending, setResending] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [resentMessage, setResentMessage] = useState<string | null>(null);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Local Storage Data
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const phone =
|
||||
localStorage.getItem(
|
||||
"otp-phone"
|
||||
) || "";
|
||||
|
||||
const email =
|
||||
localStorage.getItem(
|
||||
"otp-email"
|
||||
) || "";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Form
|
||||
// ---------------------------------------------------------------------------
|
||||
const phone = localStorage.getItem("otp-phone") || "";
|
||||
|
||||
const {
|
||||
register,
|
||||
@@ -72,383 +38,165 @@ export default function VerificationOtpPage() {
|
||||
formState: { errors },
|
||||
watch,
|
||||
} = useForm<FormData>({
|
||||
resolver:
|
||||
zodResolver(otpSchema),
|
||||
|
||||
defaultValues: {
|
||||
code: "",
|
||||
},
|
||||
resolver: zodResolver(otpSchema),
|
||||
defaultValues: { code: "" },
|
||||
});
|
||||
|
||||
const otpValue =
|
||||
watch("code");
|
||||
const otpValue = watch("code");
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Verify Mutation
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const verifyMutation =
|
||||
useMutation({
|
||||
mutationFn: async (
|
||||
data: {
|
||||
phone: string;
|
||||
otp: string;
|
||||
}
|
||||
) => verifyOTP(data),
|
||||
|
||||
onSuccess: () => {
|
||||
navigate(
|
||||
"/set-password"
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Resend Mutation
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const resendMutation =
|
||||
useMutation({
|
||||
mutationFn: async () => {
|
||||
return generateVerificationCode(
|
||||
{
|
||||
email,
|
||||
phoneNumber:
|
||||
phone,
|
||||
|
||||
type:
|
||||
verificationCodeType.setPassword,
|
||||
}
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Submit
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const onSubmit = async (
|
||||
data: FormData
|
||||
) => {
|
||||
const onSubmit = async (data: FormData) => {
|
||||
setError(null);
|
||||
setVerifying(true);
|
||||
try {
|
||||
await verifyMutation.mutateAsync(
|
||||
{
|
||||
phone,
|
||||
otp: data.code,
|
||||
}
|
||||
);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
const result = await verifyOTP(data.code);
|
||||
if (result.success) {
|
||||
navigate("/set-password");
|
||||
} else {
|
||||
setError(result.error.message);
|
||||
}
|
||||
} catch {
|
||||
setError("An unexpected error occurred");
|
||||
} finally {
|
||||
setVerifying(false);
|
||||
}
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
const handleResend = async () => {
|
||||
setResentMessage(null);
|
||||
setResending(true);
|
||||
try {
|
||||
const result = await generateVerificationCode(verificationCodeType.setPassword);
|
||||
if (result.success) {
|
||||
setResentMessage("New OTP code sent successfully.");
|
||||
} else {
|
||||
setError(result.error.message);
|
||||
}
|
||||
} catch {
|
||||
setError("An unexpected error occurred");
|
||||
} finally {
|
||||
setResending(false);
|
||||
}
|
||||
};
|
||||
|
||||
const maskedPhone =
|
||||
phone.length > 4
|
||||
? `${phone.slice(
|
||||
0,
|
||||
7
|
||||
)}******`
|
||||
: phone;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// UI
|
||||
// ---------------------------------------------------------------------------
|
||||
const maskedPhone = phone.length > 4 ? `${phone.slice(0, 7)}******` : phone;
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-background text-foreground">
|
||||
<div className="grid min-h-screen lg:grid-cols-2">
|
||||
{/* ------------------------------------------------------------------ */}
|
||||
{/* Left Side */}
|
||||
{/* ------------------------------------------------------------------ */}
|
||||
|
||||
<div className="relative hidden overflow-hidden bg-primary p-12 text-primary-foreground lg:flex lg:flex-col lg:justify-between">
|
||||
<div className="absolute inset-0 bg-[radial-gradient(circle_at_top_right,rgba(255,255,255,0.14),transparent_35%)]" />
|
||||
|
||||
<div className="relative z-10">
|
||||
{/* Logo */}
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex size-14 items-center justify-center rounded-3xl bg-white/10 backdrop-blur">
|
||||
<Train className="size-7" />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h1 className="text-3xl font-black tracking-tight">
|
||||
EDR Freight
|
||||
</h1>
|
||||
|
||||
<p className="mt-1 text-sm opacity-80">
|
||||
Railway Logistics
|
||||
Platform
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Hero */}
|
||||
<div className="mt-20 max-w-lg">
|
||||
<div className="inline-flex rounded-full bg-white/10 px-4 py-2 text-sm font-semibold backdrop-blur">
|
||||
Secure
|
||||
Verification
|
||||
</div>
|
||||
|
||||
<h2 className="mt-6 text-5xl font-black leading-tight tracking-tight">
|
||||
Verify your
|
||||
account securely
|
||||
</h2>
|
||||
|
||||
<p className="mt-6 text-lg leading-8 opacity-85">
|
||||
Enter the
|
||||
verification code
|
||||
sent to your phone
|
||||
number to continue
|
||||
using EDR Freight
|
||||
logistics services.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Features */}
|
||||
<div className="mt-14 grid gap-5">
|
||||
{[
|
||||
"Secure OTP verification",
|
||||
"Protected account access",
|
||||
"Fast identity confirmation",
|
||||
"Enterprise-grade security",
|
||||
].map((item) => (
|
||||
<div
|
||||
key={item}
|
||||
className="flex items-center gap-3"
|
||||
>
|
||||
<div className="flex size-10 items-center justify-center rounded-2xl bg-white/10">
|
||||
<ShieldCheck className="size-5" />
|
||||
</div>
|
||||
|
||||
<span className="font-medium">
|
||||
{item}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Footer Stats */}
|
||||
<div className="relative z-10 rounded-[32px] border border-white/10 bg-white/10 p-6 backdrop-blur-xl">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm opacity-80">
|
||||
Verification
|
||||
Security
|
||||
</p>
|
||||
|
||||
<h3 className="mt-2 text-4xl font-black">
|
||||
99.9%
|
||||
</h3>
|
||||
</div>
|
||||
|
||||
<div className="rounded-2xl bg-white/10 px-4 py-2 text-sm font-semibold">
|
||||
Protected
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-6 h-3 overflow-hidden rounded-full bg-white/10">
|
||||
<div className="h-full w-[99%] rounded-full bg-white" />
|
||||
</div>
|
||||
</div>
|
||||
<AuthLayout
|
||||
left={{
|
||||
badge: "Secure Verification",
|
||||
title: "Verify your account securely",
|
||||
description:
|
||||
"Enter the verification code sent to your phone number to continue using EDR Freight logistics services.",
|
||||
features: [
|
||||
"Secure OTP verification",
|
||||
"Protected account access",
|
||||
"Fast identity confirmation",
|
||||
"Enterprise-grade security",
|
||||
],
|
||||
stats: { label: "Verification Security", value: "99.9%", footer: "Protected", progress: "w-[99%]" },
|
||||
}}
|
||||
>
|
||||
<div className="mb-6">
|
||||
<div className="mb-4 flex size-12 items-center justify-center rounded-2xl bg-primary/10 text-primary">
|
||||
<MailCheck className="size-6" />
|
||||
</div>
|
||||
|
||||
{/* ------------------------------------------------------------------ */}
|
||||
{/* Right Side */}
|
||||
{/* ------------------------------------------------------------------ */}
|
||||
|
||||
<div className="flex items-center justify-center p-6 md:p-10">
|
||||
<div className="w-full max-w-xl">
|
||||
{/* Mobile Logo */}
|
||||
<div className="mb-8 flex items-center gap-3 lg:hidden">
|
||||
<div className="flex size-12 items-center justify-center rounded-2xl bg-primary text-primary-foreground">
|
||||
<Train className="size-6" />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">
|
||||
EDR Freight
|
||||
</h1>
|
||||
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Railway Logistics
|
||||
Platform
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* OTP Card */}
|
||||
<div className="rounded-[36px] border border-border bg-card p-8 shadow-2xl md:p-10">
|
||||
{/* Header */}
|
||||
<div className="mb-8">
|
||||
<div className="mb-4 flex size-16 items-center justify-center rounded-3xl bg-primary/10 text-primary">
|
||||
<MailCheck className="size-8" />
|
||||
</div>
|
||||
|
||||
<h2 className="text-4xl font-black tracking-tight">
|
||||
OTP Verification
|
||||
</h2>
|
||||
|
||||
<p className="mt-3 text-lg text-muted-foreground">
|
||||
Enter the
|
||||
6-digit code sent
|
||||
to:
|
||||
</p>
|
||||
|
||||
<div className="mt-4 rounded-2xl border border-border bg-muted/50 px-4 py-3">
|
||||
<p className="font-semibold">
|
||||
{maskedPhone}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Success */}
|
||||
{verifyMutation.isSuccess && (
|
||||
<div className="mb-6 rounded-2xl border border-green-200 bg-green-50 px-4 py-3 text-sm text-green-700">
|
||||
Verification
|
||||
successful.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Error */}
|
||||
{verifyMutation.isError && (
|
||||
<div className="mb-6 rounded-2xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
|
||||
Invalid OTP
|
||||
code. Please try
|
||||
again.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Resend Success */}
|
||||
{resendMutation.isSuccess && (
|
||||
<div className="mb-6 rounded-2xl border border-blue-200 bg-blue-50 px-4 py-3 text-sm text-blue-700">
|
||||
New OTP code sent
|
||||
successfully.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Form */}
|
||||
<form
|
||||
onSubmit={handleSubmit(
|
||||
onSubmit
|
||||
)}
|
||||
className="space-y-6"
|
||||
>
|
||||
{/* OTP */}
|
||||
<div>
|
||||
<label className="mb-2 block text-sm font-semibold">
|
||||
Verification
|
||||
Code
|
||||
</label>
|
||||
|
||||
<input
|
||||
type="text"
|
||||
inputMode="numeric"
|
||||
autoComplete="one-time-code"
|
||||
maxLength={6}
|
||||
placeholder="123456"
|
||||
disabled={
|
||||
verifyMutation.isPending
|
||||
}
|
||||
{...register(
|
||||
"code"
|
||||
)}
|
||||
className="h-16 w-full rounded-2xl border border-input bg-background px-5 text-center text-3xl font-black tracking-[12px] outline-none transition focus:border-primary focus:ring-4 focus:ring-primary/10 disabled:opacity-60"
|
||||
/>
|
||||
|
||||
<div className="mt-2 flex items-center justify-between">
|
||||
{errors.code ? (
|
||||
<p className="text-sm text-red-500">
|
||||
{
|
||||
errors.code
|
||||
.message
|
||||
}
|
||||
</p>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Enter the OTP
|
||||
sent to your
|
||||
phone
|
||||
</p>
|
||||
)}
|
||||
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{
|
||||
otpValue.length
|
||||
}
|
||||
/6
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Verify Button */}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={
|
||||
verifyMutation.isPending ||
|
||||
otpValue.length !==
|
||||
6
|
||||
}
|
||||
className="flex h-14 w-full items-center justify-center gap-2 rounded-2xl bg-primary text-lg font-semibold text-primary-foreground shadow-lg transition hover:-translate-y-0.5 hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-60"
|
||||
>
|
||||
{verifyMutation.isPending ? (
|
||||
"Verifying..."
|
||||
) : (
|
||||
<>
|
||||
Verify Account
|
||||
|
||||
<ArrowRight className="size-5" />
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
|
||||
{/* Resend */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() =>
|
||||
resendMutation.mutate()
|
||||
}
|
||||
disabled={
|
||||
resendMutation.isPending
|
||||
}
|
||||
className="flex h-14 w-full items-center justify-center gap-2 rounded-2xl border border-border bg-background text-base font-semibold transition hover:bg-muted disabled:cursor-not-allowed disabled:opacity-60"
|
||||
>
|
||||
{resendMutation.isPending ? (
|
||||
"Sending..."
|
||||
) : (
|
||||
<>
|
||||
<RotateCw className="size-5" />
|
||||
|
||||
Resend Code
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
|
||||
{/* Footer */}
|
||||
<p className="text-center text-sm text-muted-foreground">
|
||||
Didn’t receive
|
||||
the code?
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() =>
|
||||
resendMutation.mutate()
|
||||
}
|
||||
className="ml-2 font-semibold text-primary hover:underline"
|
||||
>
|
||||
Send again
|
||||
</button>
|
||||
</p>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<h2 className="text-2xl font-black tracking-tight">OTP Verification</h2>
|
||||
<p className="mt-2 text-base text-muted-foreground">Enter the 6-digit code sent to:</p>
|
||||
<div className="mt-3 rounded-xl border border-border bg-muted/50 px-4 py-2">
|
||||
<p className="text-sm font-semibold">{maskedPhone}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="mb-4 rounded-xl border border-red-200 bg-red-50 px-4 py-2.5 text-sm text-red-700">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{resentMessage && (
|
||||
<div className="mb-4 rounded-xl border border-blue-200 bg-blue-50 px-4 py-2.5 text-sm text-blue-700">
|
||||
{resentMessage}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="flex flex-col gap-4">
|
||||
<FieldGroup>
|
||||
<Field data-invalid={Boolean(errors.code)}>
|
||||
<FieldLabel>Verification Code</FieldLabel>
|
||||
<Input
|
||||
type="text"
|
||||
inputMode="numeric"
|
||||
autoComplete="one-time-code"
|
||||
maxLength={6}
|
||||
placeholder="123456"
|
||||
disabled={verifying}
|
||||
aria-invalid={Boolean(errors.code)}
|
||||
className="h-14 text-center text-2xl font-black tracking-[10px]"
|
||||
{...register("code")}
|
||||
/>
|
||||
<div className="mt-1.5 flex items-center justify-between">
|
||||
{errors.code ? (
|
||||
<FieldError errors={[errors.code]} />
|
||||
) : (
|
||||
<p className="text-xs text-muted-foreground">Enter the OTP sent to your phone</p>
|
||||
)}
|
||||
<span className="text-xs text-muted-foreground">{otpValue.length}/6</span>
|
||||
</div>
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={verifying || otpValue.length !== 6}
|
||||
size="lg"
|
||||
className="w-full"
|
||||
>
|
||||
{verifying ? (
|
||||
<>
|
||||
<Loader2 className="animate-spin" data-icon="inline-start" />
|
||||
Verifying...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
Verify Account
|
||||
<ArrowRight data-icon="inline-end" />
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={handleResend}
|
||||
disabled={resending}
|
||||
className="w-full"
|
||||
>
|
||||
{resending ? (
|
||||
<>
|
||||
<Loader2 className="animate-spin" data-icon="inline-start" />
|
||||
Sending...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<RotateCw data-icon="inline-start" />
|
||||
Resend Code
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
|
||||
<p className="text-center text-sm text-muted-foreground">
|
||||
Didn't receive the code?
|
||||
<Button
|
||||
type="button"
|
||||
variant="link"
|
||||
size="sm"
|
||||
onClick={handleResend}
|
||||
className="h-auto p-0 font-semibold"
|
||||
>
|
||||
Send again
|
||||
</Button>
|
||||
</p>
|
||||
</form>
|
||||
</AuthLayout>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { CheckCircle2, ChevronLeft, ChevronRight } from "lucide-react";
|
||||
import { Button } from "@edr/ui-common";
|
||||
import Breadcrumbs from "@/components/Breadcrumbs";
|
||||
import { addBooking } from "./bookings.mock";
|
||||
import { getCurrentCustomer } from "@/lib/currentCustomer";
|
||||
import { api } from "@/services/api";
|
||||
import type { CreateBookingPayload } from "@/services/bookings.service";
|
||||
@@ -33,10 +33,18 @@ import {
|
||||
|
||||
export default function NewBookingPage() {
|
||||
const navigate = useNavigate();
|
||||
const queryClient = useQueryClient();
|
||||
const [step, setStep] = useState(1);
|
||||
const [renewalValidating, setRenewalValidating] = useState(false);
|
||||
const [renewalValid, setRenewalValid] = useState<boolean | null>(null);
|
||||
const [submitted, setSubmitted] = useState(false);
|
||||
const createMutation = useMutation({
|
||||
mutationFn: (payload: CreateBookingPayload) =>
|
||||
api.bookings.create.call(payload),
|
||||
onSuccess: (booking) => {
|
||||
queryClient.invalidateQueries({ queryKey: api.bookings.list.queryKey() });
|
||||
setTimeout(() => navigate(`/bookings/${booking.id}`), 2500);
|
||||
},
|
||||
});
|
||||
|
||||
const form = useForm<BookingFormValues>({
|
||||
defaultValues: initialBookingFormValues,
|
||||
@@ -48,8 +56,6 @@ export default function NewBookingPage() {
|
||||
const destinationYard = form.watch("destinationYard");
|
||||
const containers = form.watch("containers");
|
||||
const previousContractRef = form.watch("previousContractRef");
|
||||
const contractId =
|
||||
form.watch("draftContractId") || form.watch("previousContractRef");
|
||||
|
||||
const direction = useMemo(
|
||||
() => getRouteDirection(originYard, destinationYard),
|
||||
@@ -113,7 +119,7 @@ export default function NewBookingPage() {
|
||||
setStep((currentStep) => Math.min(STEPS.length, currentStep + 1));
|
||||
}
|
||||
|
||||
function handleSubmit(data: BookingFormValues) {
|
||||
const handleSubmit = form.handleSubmit((data) => {
|
||||
if (data.contractType === "renewal" && renewalValid !== true) {
|
||||
form.setError("previousContractRef", {
|
||||
type: "manual",
|
||||
@@ -124,15 +130,7 @@ export default function NewBookingPage() {
|
||||
}
|
||||
|
||||
const me = getCurrentCustomer();
|
||||
const reference =
|
||||
data.draftContractId ||
|
||||
data.previousContractRef ||
|
||||
`EDR-DRAFT-${Date.now()}`;
|
||||
|
||||
const qtyCount =
|
||||
data.cargoType === "container"
|
||||
? data.containers.reduce((acc, c) => acc + Number(c.qty || 0), 0)
|
||||
: 1;
|
||||
const reference = data.previousContractRef;
|
||||
|
||||
const totalWeight =
|
||||
data.cargoType === "container"
|
||||
@@ -142,48 +140,13 @@ export default function NewBookingPage() {
|
||||
)
|
||||
: Number(data.cargoWeight || 0);
|
||||
|
||||
const description =
|
||||
data.cargoType === "container"
|
||||
? data.containers.map((c) => `${c.qty} × ${c.type}`).join(", ")
|
||||
: data.freightType === "bulk"
|
||||
? `Bulk - ${data.bulkCommodity === "Others" ? data.bulkCommodityOther : data.bulkCommodity}`
|
||||
: `Break-Bulk - ${data.breakBulkType === "Others" ? data.breakBulkTypeOther : data.breakBulkType}`;
|
||||
|
||||
const newBooking = {
|
||||
id: Date.now(),
|
||||
reference,
|
||||
customerId: me.id,
|
||||
customer: me.company,
|
||||
cargoType: (data.cargoType === "container"
|
||||
? "Containerized"
|
||||
: "Bulk") as any,
|
||||
originStation: data.originYard,
|
||||
destinationStation: data.destinationYard,
|
||||
transportMode: (data.serviceType === "rail"
|
||||
? "Rail"
|
||||
: "Multimodal") as any,
|
||||
containerType: (data.cargoType === "container" &&
|
||||
data.containers[0]?.type === "40ft"
|
||||
? "40FT"
|
||||
: "20FT") as any,
|
||||
containerCount: qtyCount,
|
||||
weightTons: totalWeight,
|
||||
requestedDate: new Date().toISOString().slice(0, 10),
|
||||
priority: (data.isHazardous ? "High" : "Normal") as any,
|
||||
cargoDescription: description,
|
||||
specialInstructions: data.notes || "Standard handling required",
|
||||
status: "Pending" as any,
|
||||
};
|
||||
|
||||
addBooking(newBooking);
|
||||
|
||||
// Call API using api.bookings.create.call
|
||||
const apiPayload = {
|
||||
reference,
|
||||
customerId: String(me.id),
|
||||
scheduledDate: new Date().toISOString().slice(0, 10),
|
||||
totalAmount: 0,
|
||||
contractType: data.contractType.toUpperCase(),
|
||||
contractType:
|
||||
data.contractType.toUpperCase() as CreateBookingPayload["contractType"],
|
||||
previousContractId: data.previousContractRef || undefined,
|
||||
serviceType:
|
||||
data.serviceType === "rail" ? "RAIL_ONLY" : "RAIL_AND_FORWARDING",
|
||||
@@ -197,8 +160,8 @@ export default function NewBookingPage() {
|
||||
: undefined,
|
||||
equipmentReturn:
|
||||
data.equipmentReturn === "with_return"
|
||||
? "WITH_RETURN"
|
||||
: "WITHOUT_RETURN",
|
||||
? ("WITH_RETURN" as const)
|
||||
: ("WITHOUT_RETURN" as const),
|
||||
originStation: data.originYard,
|
||||
destinationStation: data.destinationYard,
|
||||
cargoTotalWeightVgm: totalWeight,
|
||||
@@ -220,31 +183,18 @@ export default function NewBookingPage() {
|
||||
...(data.cargoType === "container" && data.containers.length > 0
|
||||
? {
|
||||
containers: data.containers.map((c) => ({
|
||||
type: c.type === "40ft" ? "40FT" as const : "20FT" as const,
|
||||
type: c.type === "40ft" ? ("40FT" as const) : ("20FT" as const),
|
||||
qty: Number(c.qty || 1),
|
||||
vgm: Number(c.vgm || 0),
|
||||
})),
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
} satisfies CreateBookingPayload;
|
||||
|
||||
api.bookings.create
|
||||
.call(apiPayload as CreateBookingPayload)
|
||||
.then((created) => {
|
||||
console.log("Successfully created booking via API:", created);
|
||||
})
|
||||
.catch((err) => {
|
||||
console.warn(
|
||||
"API call failed (expected if API server is offline), falling back to mock storage:",
|
||||
err,
|
||||
);
|
||||
});
|
||||
createMutation.mutate(apiPayload);
|
||||
});
|
||||
|
||||
setSubmitted(true);
|
||||
setTimeout(() => navigate("/bookings"), 2500);
|
||||
}
|
||||
|
||||
if (submitted) {
|
||||
if (createMutation.isSuccess && createMutation.data) {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center p-6">
|
||||
<div className="w-full max-w-sm rounded-2xl border border-border bg-card p-10 text-center shadow-sm">
|
||||
@@ -257,7 +207,7 @@ export default function NewBookingPage() {
|
||||
notified once approved.
|
||||
</p>
|
||||
<p className="mt-4 font-mono text-sm font-semibold text-primary">
|
||||
{contractId}
|
||||
{createMutation.data.reference}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -268,7 +218,7 @@ export default function NewBookingPage() {
|
||||
<form
|
||||
id="new-booking-form"
|
||||
className="flex flex-col"
|
||||
onSubmit={form.handleSubmit(handleSubmit)}
|
||||
onSubmit={handleSubmit}
|
||||
>
|
||||
<div className="sticky top-0 z-20 border-b border-border bg-background">
|
||||
<div className="mx-auto max-w-4xl space-y-3 px-6 py-3">
|
||||
|
||||
@@ -151,7 +151,6 @@ export const bookingFormSchema = z
|
||||
.object({
|
||||
contractType: z.enum(["new", "renewal"], "Select a contract type."),
|
||||
previousContractRef: z.string(),
|
||||
draftContractId: z.string(),
|
||||
serviceType: z.enum(["rail", "rail_forwarding"], "Select a service type."),
|
||||
firstMileEnabled: z.boolean(),
|
||||
pickUpAddress: z.string(),
|
||||
@@ -162,7 +161,7 @@ export const bookingFormSchema = z
|
||||
destinationYard: z.string(),
|
||||
cargoType: z.enum(["container", "bulk"], "Select a cargo type."),
|
||||
cargoWeight: z.string(),
|
||||
freightType: z.enum(["bulk", "break_bulk", ""]).default(""),
|
||||
freightType: z.enum(["bulk", "break_bulk"]),
|
||||
bulkCommodity: z.string(),
|
||||
bulkCommodityOther: z.string(),
|
||||
breakBulkType: z.string(),
|
||||
@@ -188,14 +187,6 @@ export const bookingFormSchema = z
|
||||
termsAccepted: z.boolean(),
|
||||
})
|
||||
.superRefine((data, ctx) => {
|
||||
if (data.contractType === "new" && !data.draftContractId.trim()) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: ["draftContractId"],
|
||||
message: "A draft contract ID is required.",
|
||||
});
|
||||
}
|
||||
|
||||
if (data.contractType === "renewal" && !data.previousContractRef.trim()) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
@@ -360,7 +351,6 @@ export type BookingFormValues = z.infer<typeof bookingFormSchema>;
|
||||
|
||||
export const initialBookingFormValues: Partial<BookingFormValues> = {
|
||||
previousContractRef: "",
|
||||
draftContractId: "",
|
||||
firstMileEnabled: false,
|
||||
pickUpAddress: "",
|
||||
lastMileEnabled: false,
|
||||
@@ -383,7 +373,7 @@ export const initialBookingFormValues: Partial<BookingFormValues> = {
|
||||
};
|
||||
|
||||
export const stepFields: Record<number, Array<keyof BookingFormValues>> = {
|
||||
1: ["contractType", "previousContractRef", "draftContractId"],
|
||||
1: ["contractType", "previousContractRef"],
|
||||
2: ["serviceType"],
|
||||
3: [
|
||||
"firstMileEnabled",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Controller, type UseFormReturn } from "react-hook-form";
|
||||
import { FileText, Loader2, RefreshCw } from "lucide-react";
|
||||
import { Button, Field, FieldError, FieldLabel, Input } from "@edr/ui-common";
|
||||
import { type BookingFormValues, genContractId } from "./schema";
|
||||
import { Button, Field, FieldLabel, Input } from "@edr/ui-common";
|
||||
import { type BookingFormValues } from "./schema";
|
||||
import { AlertBox, OptionCard, OptionFieldError, StepHeader } from "./shared";
|
||||
|
||||
type BookingForm = UseFormReturn<BookingFormValues>;
|
||||
@@ -18,9 +18,7 @@ export function Step1ContractType({
|
||||
onValidate: () => void;
|
||||
}) {
|
||||
const contractType = form.watch("contractType");
|
||||
const draftContractId = form.watch("draftContractId");
|
||||
const previousContractRef = form.watch("previousContractRef");
|
||||
const errors = form.formState.errors;
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
@@ -40,12 +38,6 @@ export function Step1ContractType({
|
||||
onClick={() => {
|
||||
field.onChange("new");
|
||||
form.clearErrors(["contractType", "previousContractRef"]);
|
||||
if (!draftContractId) {
|
||||
form.setValue("draftContractId", genContractId(), {
|
||||
shouldDirty: true,
|
||||
shouldValidate: true,
|
||||
});
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="mb-2 flex h-9 w-9 items-center justify-center rounded-lg bg-primary/10">
|
||||
@@ -55,11 +47,6 @@ export function Step1ContractType({
|
||||
<p className="mt-0.5 text-xs text-muted-foreground">
|
||||
Blank contract form. A draft ID is auto-generated.
|
||||
</p>
|
||||
{field.value === "new" && draftContractId && (
|
||||
<p className="mt-2 font-mono text-xs font-semibold text-primary">
|
||||
{draftContractId}
|
||||
</p>
|
||||
)}
|
||||
</OptionCard>
|
||||
|
||||
<OptionCard
|
||||
@@ -115,9 +102,6 @@ export function Step1ContractType({
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
<FieldError
|
||||
errors={[fieldState.error, errors.draftContractId]}
|
||||
/>
|
||||
</Field>
|
||||
)}
|
||||
/>
|
||||
|
||||
@@ -1,13 +1,6 @@
|
||||
import {
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
} from "react";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
|
||||
import {
|
||||
Link,
|
||||
useNavigate,
|
||||
} from "react-router-dom";
|
||||
import { Link, useNavigate } from "react-router-dom";
|
||||
|
||||
import {
|
||||
Building2,
|
||||
@@ -31,19 +24,10 @@ import { formatCurrency } from "@/pages/billing/invoices.mock";
|
||||
|
||||
import { customersService } from "@/services/customers.service";
|
||||
|
||||
import { getMyInfo } from "@/services/account";
|
||||
import { authService } from "@/services/auth.service";
|
||||
import NewCustomerPage from "../customers/NewCustomerPage";
|
||||
import { Button } from "@edr/ui-common";
|
||||
|
||||
type Customer = {
|
||||
id: string;
|
||||
companyName: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
email: string;
|
||||
phone: string;
|
||||
};
|
||||
|
||||
export default function MyPortalPage() {
|
||||
const navigate = useNavigate();
|
||||
|
||||
@@ -58,58 +42,10 @@ export default function MyPortalPage() {
|
||||
// MOCK DATA
|
||||
// ------------------------------------------------------------
|
||||
|
||||
const me = useMemo(() => getCurrentCustomer(), []);
|
||||
const myBookings = useMemo(() => getMyBookings(), []);
|
||||
const myShipments = useMemo(() => getMyShipments(), []);
|
||||
const myInvoices = useMemo(() => getMyInvoices(), []);
|
||||
|
||||
// ------------------------------------------------------------
|
||||
// FETCH CUSTOMER
|
||||
// ------------------------------------------------------------
|
||||
|
||||
useEffect(() => {
|
||||
const initialize = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
|
||||
const userRes = await getMyInfo();
|
||||
const userId = userRes?.data?.id;
|
||||
localStorage.setItem("currentUser", JSON.stringify(userRes.data));
|
||||
// if (!userId) {
|
||||
// navigate("/login");
|
||||
// return;
|
||||
// }
|
||||
|
||||
const res = await customersService.getByUserId(userId);
|
||||
if (res) {
|
||||
setCustomer(res);
|
||||
return;
|
||||
}
|
||||
|
||||
// customer not found → onboarding
|
||||
// navigate("/customers/register");
|
||||
} catch (error: any) {
|
||||
console.error("Customer fetch failed:", error);
|
||||
|
||||
const status = error?.response?.status;
|
||||
|
||||
if (status === 404) {
|
||||
// navigate("/customers/register");
|
||||
return;
|
||||
}
|
||||
|
||||
if (status === 401) {
|
||||
// navigate("/login");
|
||||
return;
|
||||
}
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
initialize();
|
||||
}, [navigate]);
|
||||
|
||||
// ------------------------------------------------------------
|
||||
// LOADING
|
||||
// ------------------------------------------------------------
|
||||
@@ -118,9 +54,7 @@ export default function MyPortalPage() {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-slate-50">
|
||||
<div className="rounded-2xl bg-white px-6 py-4 shadow-sm">
|
||||
<p className="text-sm text-slate-600">
|
||||
Loading portal...
|
||||
</p>
|
||||
<p className="text-sm text-slate-600">Loading portal...</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
@@ -134,9 +68,7 @@ export default function MyPortalPage() {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-slate-50">
|
||||
<div className="text-center space-y-4">
|
||||
<p className="text-slate-600">
|
||||
No customer profile found
|
||||
</p>
|
||||
<p className="text-slate-600">No customer profile found</p>
|
||||
|
||||
{/* <Link
|
||||
to="/customers/register"
|
||||
@@ -146,12 +78,9 @@ export default function MyPortalPage() {
|
||||
Create Customer Profile
|
||||
</Link> */}
|
||||
<NewCustomerPage>
|
||||
<Button
|
||||
className="inline-flex items-center gap-2 rounded-2xl bg-[#10B981] px-4 py-2 text-white"
|
||||
|
||||
>
|
||||
<Button className="inline-flex items-center gap-2 rounded-2xl bg-[#10B981] px-4 py-2 text-white">
|
||||
<Plus className="h-4 w-4" />
|
||||
Create Customer Profile
|
||||
Create Customer Profile
|
||||
</Button>
|
||||
</NewCustomerPage>
|
||||
</div>
|
||||
@@ -164,31 +93,24 @@ export default function MyPortalPage() {
|
||||
// ------------------------------------------------------------
|
||||
|
||||
const activeBookings = myBookings.filter(
|
||||
(b) =>
|
||||
b.status === "Confirmed" ||
|
||||
b.status === "In Transit"
|
||||
(b) => b.status === "Confirmed" || b.status === "In Transit",
|
||||
);
|
||||
|
||||
const activeShipments = myShipments.filter(
|
||||
(s) => s.status === "In Transit"
|
||||
);
|
||||
const activeShipments = myShipments.filter((s) => s.status === "In Transit");
|
||||
|
||||
const outstandingInvoices = myInvoices.filter(
|
||||
(i) => i.status === "Sent" || i.status === "Overdue"
|
||||
(i) => i.status === "Sent" || i.status === "Overdue",
|
||||
);
|
||||
|
||||
const totalOutstanding = outstandingInvoices.reduce(
|
||||
(sum, i) =>
|
||||
i.currency === "USD" ? sum + i.amount : sum,
|
||||
0
|
||||
(sum, i) => (i.currency === "USD" ? sum + i.amount : sum),
|
||||
0,
|
||||
);
|
||||
|
||||
const totalSpent = myInvoices.reduce(
|
||||
(sum, i) =>
|
||||
i.status === "Paid" && i.currency === "USD"
|
||||
? sum + i.amount
|
||||
: sum,
|
||||
0
|
||||
i.status === "Paid" && i.currency === "USD" ? sum + i.amount : sum,
|
||||
0,
|
||||
);
|
||||
|
||||
// ------------------------------------------------------------
|
||||
@@ -198,13 +120,11 @@ export default function MyPortalPage() {
|
||||
return (
|
||||
<div className="min-h-screen bg-slate-50 p-6">
|
||||
<div className="mx-auto max-w-7xl space-y-6">
|
||||
|
||||
<Breadcrumbs items={[{ label: "My Portal" }]} />
|
||||
|
||||
{/* HERO */}
|
||||
<div className="rounded-3xl bg-gradient-to-r from-[#059669] to-[#10B981] p-6 text-white">
|
||||
<div className="flex justify-between flex-col md:flex-row gap-6">
|
||||
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="h-14 w-14 flex items-center justify-center rounded-2xl bg-white/20 text-xl font-bold">
|
||||
{customer.companyName?.charAt(0)}
|
||||
@@ -244,7 +164,6 @@ export default function MyPortalPage() {
|
||||
|
||||
{/* KPI */}
|
||||
<div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
|
||||
|
||||
<KpiCard
|
||||
label="Active Bookings"
|
||||
value={String(activeBookings.length)}
|
||||
@@ -283,7 +202,6 @@ export default function MyPortalPage() {
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
// ------------------------------------------------------------
|
||||
// KPI CARD
|
||||
// ------------------------------------------------------------
|
||||
@@ -304,24 +222,16 @@ function KpiCard({
|
||||
tone?: "brand" | "danger";
|
||||
}) {
|
||||
const iconClassName =
|
||||
tone === "danger"
|
||||
? "bg-red-100 text-red-600"
|
||||
: "bg-[#10B981] text-white";
|
||||
tone === "danger" ? "bg-red-100 text-red-600" : "bg-[#10B981] text-white";
|
||||
|
||||
const content = (
|
||||
<div className="flex items-start justify-between">
|
||||
<div>
|
||||
<p className="text-sm text-slate-500">
|
||||
{label}
|
||||
</p>
|
||||
<p className="text-sm text-slate-500">{label}</p>
|
||||
|
||||
<h3 className="mt-2 text-2xl font-bold text-slate-900">
|
||||
{value}
|
||||
</h3>
|
||||
<h3 className="mt-2 text-2xl font-bold text-slate-900">{value}</h3>
|
||||
|
||||
<p className="mt-1 text-xs text-slate-500">
|
||||
{sub}
|
||||
</p>
|
||||
<p className="mt-1 text-xs text-slate-500">{sub}</p>
|
||||
</div>
|
||||
|
||||
<div
|
||||
@@ -337,18 +247,11 @@ function KpiCard({
|
||||
|
||||
if (href) {
|
||||
return (
|
||||
<Link
|
||||
to={href}
|
||||
className={`block ${className}`}
|
||||
>
|
||||
<Link to={href} className={`block ${className}`}>
|
||||
{content}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={className}>
|
||||
{content}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return <div className={className}>{content}</div>;
|
||||
}
|
||||
|
||||
@@ -1,92 +0,0 @@
|
||||
import { URL_CONSTANTS } from "@/constants/URLS";
|
||||
import { CreateUserPayload } from "@/types/createUser";
|
||||
import { VerificationCodePayload } from "@/types/generateVerificationCode";
|
||||
import { UserTypeRequest } from "@/types/userTypeRequest";
|
||||
import { client } from "@/utils/api";
|
||||
import { ApiResponse } from "@edr/types";
|
||||
import { GenerateVerifcationCodePayload } from "node_modules/@tria-plc/iamui-common/dist/types/shared/services/authService";
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// API
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
export const createUser = async (
|
||||
body: CreateUserPayload
|
||||
) => {
|
||||
const res =
|
||||
await client.post<
|
||||
ApiResponse<any>
|
||||
>(
|
||||
URL_CONSTANTS.USERS.SIGN_UP,
|
||||
body
|
||||
);
|
||||
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const getMyInfo = async () => {
|
||||
const res =
|
||||
await client.get<
|
||||
ApiResponse<any>
|
||||
>(
|
||||
URL_CONSTANTS.USERS.ME
|
||||
);
|
||||
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const generateVerificationCode = async (
|
||||
body: VerificationCodePayload
|
||||
) => {
|
||||
const res =
|
||||
await client.patch<
|
||||
ApiResponse<string>
|
||||
>(
|
||||
URL_CONSTANTS.USERS.GENERATE_VERIFICATION_CODE,
|
||||
body
|
||||
);
|
||||
|
||||
return res.data.data;
|
||||
};
|
||||
|
||||
export const setPassword = async (
|
||||
body: any
|
||||
) => {
|
||||
const res =
|
||||
await client.patch<
|
||||
ApiResponse<string>
|
||||
>(
|
||||
URL_CONSTANTS.USERS.SET_PASSWORD,
|
||||
body
|
||||
);
|
||||
|
||||
return res.data.data;
|
||||
};
|
||||
|
||||
export const createOTP = async (
|
||||
body: any
|
||||
) => {
|
||||
const res =
|
||||
await client.post<
|
||||
ApiResponse<any>
|
||||
>(
|
||||
URL_CONSTANTS.OTP.SEND,
|
||||
body
|
||||
);
|
||||
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const verifyOTP = async (
|
||||
body: any
|
||||
) => {
|
||||
const res =
|
||||
await client.post<
|
||||
ApiResponse<any>
|
||||
>(
|
||||
URL_CONSTANTS.OTP.VERIFY,
|
||||
body
|
||||
);
|
||||
|
||||
return res.data;
|
||||
};
|
||||
@@ -13,6 +13,8 @@ import { consignmentsService } from "./consignments.service";
|
||||
import { trackingService } from "./tracking.service";
|
||||
import { fileUploadSettingsService } from "./fileUploadSettings.service";
|
||||
import { dropdownSettingsService } from "./dropdownSettings.service";
|
||||
import { authService } from "./auth.service";
|
||||
import { customersService } from "./customers.service";
|
||||
import {
|
||||
CreateDropdownOptionDto,
|
||||
CreateDropdownSettingDto,
|
||||
@@ -21,12 +23,101 @@ import {
|
||||
UpdateDropdownOptionDto,
|
||||
UpdateDropdownSettingDto,
|
||||
} from "@/types/dropdownSettings";
|
||||
import {
|
||||
CreateCustomerDto,
|
||||
Customer,
|
||||
UpdateCustomerDto,
|
||||
} from "@/types/customers";
|
||||
import type {
|
||||
AuthUser,
|
||||
GenerateVerificationCodePayload,
|
||||
LoginPayload,
|
||||
LoginResponse,
|
||||
OtpPayload,
|
||||
OtpResponse,
|
||||
SetPasswordPayload,
|
||||
SignupPayload,
|
||||
SignupResponse,
|
||||
} from "@/types/auth";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// API definition
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const api = {
|
||||
auth: {
|
||||
login: endpoint<LoginPayload, LoginResponse>(
|
||||
"auth",
|
||||
"login",
|
||||
authService.login,
|
||||
),
|
||||
createUser: endpoint<SignupPayload, SignupResponse>(
|
||||
"auth",
|
||||
"createUser",
|
||||
authService.createUser,
|
||||
),
|
||||
getMyInfo: endpoint<void, AuthUser>(
|
||||
"auth",
|
||||
"getMyInfo",
|
||||
authService.getMyInfo,
|
||||
),
|
||||
generateVerificationCode: endpoint<GenerateVerificationCodePayload, string>(
|
||||
"auth",
|
||||
"generateVerificationCode",
|
||||
authService.generateVerificationCode,
|
||||
),
|
||||
setPassword: endpoint<SetPasswordPayload, void>(
|
||||
"auth",
|
||||
"setPassword",
|
||||
authService.setPassword,
|
||||
),
|
||||
sendOTP: endpoint<OtpPayload, OtpResponse>(
|
||||
"auth",
|
||||
"sendOTP",
|
||||
authService.sendOTP,
|
||||
),
|
||||
verifyOTP: endpoint<OtpPayload, OtpResponse>(
|
||||
"auth",
|
||||
"verifyOTP",
|
||||
authService.verifyOTP,
|
||||
),
|
||||
logout: endpoint<void, void>("auth", "logout", authService.logout),
|
||||
},
|
||||
|
||||
customers: {
|
||||
list: endpoint<void, Customer[]>(
|
||||
"customers",
|
||||
"list",
|
||||
customersService.list,
|
||||
),
|
||||
|
||||
get: endpoint<{ id: string }, Customer>("customers", "get", ({ id }) =>
|
||||
customersService.getById(id),
|
||||
),
|
||||
|
||||
create: endpoint<CreateCustomerDto, Customer>(
|
||||
"customers",
|
||||
"create",
|
||||
customersService.create,
|
||||
),
|
||||
|
||||
update: endpoint<{ id: string; dto: UpdateCustomerDto }, Customer>(
|
||||
"customers",
|
||||
"update",
|
||||
({ id, dto }) => customersService.update(id, dto),
|
||||
),
|
||||
|
||||
remove: endpoint<{ id: string }, void>("customers", "remove", ({ id }) =>
|
||||
customersService.remove(id),
|
||||
),
|
||||
|
||||
getByUserId: endpoint<{ id: string }, Customer | null>(
|
||||
"customers",
|
||||
"getByUserId",
|
||||
({ id }) => customersService.getByUserId(id),
|
||||
),
|
||||
},
|
||||
|
||||
bookings: {
|
||||
list: endpoint<void, PaginatedResponse<Freight.IBooking>>(
|
||||
"bookings",
|
||||
|
||||
90
apps/edr-freight-web/portal/src/services/auth.service.ts
Normal file
90
apps/edr-freight-web/portal/src/services/auth.service.ts
Normal file
@@ -0,0 +1,90 @@
|
||||
import { URL_CONSTANTS } from "@/constants/URLS";
|
||||
import { client } from "@/utils/api";
|
||||
import { ApiResponse } from "@edr/types";
|
||||
import type {
|
||||
AuthUser,
|
||||
GenerateVerificationCodePayload,
|
||||
LoginPayload,
|
||||
LoginResponse,
|
||||
OtpPayload,
|
||||
OtpResponse,
|
||||
SetPasswordPayload,
|
||||
SignupPayload,
|
||||
SignupResponse,
|
||||
} from "@/types/auth";
|
||||
|
||||
export const authService = {
|
||||
login: async (body: LoginPayload) => {
|
||||
const res = await client.post<ApiResponse<LoginResponse>>(
|
||||
URL_CONSTANTS.AUTH.LOGIN,
|
||||
body,
|
||||
);
|
||||
return res.data.data;
|
||||
},
|
||||
|
||||
createUser: async (body: SignupPayload) => {
|
||||
const res = await client.post<ApiResponse<SignupResponse>>(
|
||||
URL_CONSTANTS.USERS.SIGN_UP,
|
||||
body,
|
||||
);
|
||||
return res.data.data;
|
||||
},
|
||||
|
||||
getMyInfo: async () => {
|
||||
const res = await client.get<ApiResponse<AuthUser>>(
|
||||
URL_CONSTANTS.USERS.ME,
|
||||
);
|
||||
return res.data.data;
|
||||
},
|
||||
|
||||
generateVerificationCode: async (body: GenerateVerificationCodePayload) => {
|
||||
const res = await client.patch<ApiResponse<string>>(
|
||||
URL_CONSTANTS.USERS.GENERATE_VERIFICATION_CODE,
|
||||
body,
|
||||
);
|
||||
return res.data.data;
|
||||
},
|
||||
|
||||
setPassword: async (body: SetPasswordPayload) => {
|
||||
const res = await client.patch<ApiResponse<void>>(
|
||||
URL_CONSTANTS.USERS.SET_PASSWORD,
|
||||
body,
|
||||
);
|
||||
return res.data.data;
|
||||
},
|
||||
|
||||
sendOTP: async (body: OtpPayload) => {
|
||||
const res = await client.post<ApiResponse<OtpResponse>>(
|
||||
URL_CONSTANTS.OTP.SEND,
|
||||
body,
|
||||
);
|
||||
return res.data.data;
|
||||
},
|
||||
|
||||
verifyOTP: async (body: OtpPayload) => {
|
||||
const res = await client.post<ApiResponse<OtpResponse>>(
|
||||
URL_CONSTANTS.OTP.VERIFY,
|
||||
body,
|
||||
);
|
||||
return res.data.data;
|
||||
},
|
||||
|
||||
refreshToken: async () => {
|
||||
const refreshTokenCookie = document.cookie
|
||||
.split("; ")
|
||||
.find((row) => row.startsWith("refresh-token="))
|
||||
?.split("=")[1];
|
||||
const res = await client.post<ApiResponse<LoginResponse>>(
|
||||
URL_CONSTANTS.AUTH.REFRESH_TOKEN,
|
||||
{ refreshToken: refreshTokenCookie },
|
||||
);
|
||||
return res.data.data;
|
||||
},
|
||||
|
||||
logout: async () => {
|
||||
const res = await client.patch<ApiResponse<void>>(
|
||||
URL_CONSTANTS.AUTH.LOGOUT,
|
||||
);
|
||||
return res.data.data;
|
||||
},
|
||||
};
|
||||
@@ -7,6 +7,7 @@ import type {
|
||||
Customer,
|
||||
UpdateCustomerDto,
|
||||
} from "@/types/customers";
|
||||
import { isAxiosError } from "axios";
|
||||
|
||||
const BASE = URL_CONSTANTS.CUSTOMERS_API.BASE;
|
||||
|
||||
@@ -23,22 +24,26 @@ export const customersService = {
|
||||
return unwrap(response.data);
|
||||
},
|
||||
|
||||
getByUserId: async (userId: string): Promise<Customer> => {
|
||||
const response = await client.get<ApiResponse<Customer>>(
|
||||
URL_CONSTANTS.CUSTOMERS_API.BY_USER_ID(userId),
|
||||
);
|
||||
getByUserId: async (userId: string): Promise<Customer | null> => {
|
||||
try {
|
||||
const response = await client.get<ApiResponse<Customer>>(
|
||||
URL_CONSTANTS.CUSTOMERS_API.BY_USER_ID(userId),
|
||||
);
|
||||
return unwrap(response.data);
|
||||
} catch (e) {
|
||||
if (isAxiosError(e) && e.response?.status === 404) {
|
||||
return null;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
},
|
||||
|
||||
create: async (payload: CreateCustomerDto): Promise<Customer> => {
|
||||
const response = await client.post<ApiResponse<Customer>>(BASE, payload);
|
||||
return unwrap(response.data);
|
||||
},
|
||||
|
||||
create: async (payload: any): Promise<any> => {
|
||||
const response = await client.post<ApiResponse<any>>(BASE, payload);
|
||||
return unwrap(response.data);
|
||||
},
|
||||
|
||||
update: async (
|
||||
id: string,
|
||||
payload: UpdateCustomerDto,
|
||||
): Promise<Customer> => {
|
||||
update: async (id: string, payload: UpdateCustomerDto): Promise<Customer> => {
|
||||
const response = await client.patch<ApiResponse<Customer>>(
|
||||
URL_CONSTANTS.CUSTOMERS_API.BY_ID(id),
|
||||
payload,
|
||||
|
||||
65
apps/edr-freight-web/portal/src/types/auth.ts
Normal file
65
apps/edr-freight-web/portal/src/types/auth.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
export interface AuthUser {
|
||||
id: string;
|
||||
name: { am: string; en: string };
|
||||
email: string;
|
||||
roles: string[];
|
||||
status: string;
|
||||
employee: any[];
|
||||
userType: string;
|
||||
username: string;
|
||||
permissions: string[];
|
||||
phoneNumber: string;
|
||||
sharepointId: string | null;
|
||||
hasSetPassword: boolean;
|
||||
hasFinishedRegistration: boolean;
|
||||
hasFinishedDMSOnboarding: boolean;
|
||||
}
|
||||
|
||||
export interface SignupPayload {
|
||||
email: string;
|
||||
username: string;
|
||||
phoneNumber: string;
|
||||
userType: string;
|
||||
name: { en: string; am: string };
|
||||
}
|
||||
|
||||
export interface SignupResponse {
|
||||
token: string;
|
||||
refreshToken: string;
|
||||
otp: string;
|
||||
userId: string;
|
||||
}
|
||||
|
||||
export interface OtpPayload {
|
||||
phone: string;
|
||||
otp: string;
|
||||
}
|
||||
|
||||
export interface OtpResponse {
|
||||
success: boolean;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface SetPasswordPayload {
|
||||
newPassword: string;
|
||||
confirmPassword: string;
|
||||
userId: string;
|
||||
email: string;
|
||||
verificationCode: string;
|
||||
}
|
||||
|
||||
export interface GenerateVerificationCodePayload {
|
||||
email: string;
|
||||
phoneNumber: string;
|
||||
type: string;
|
||||
}
|
||||
|
||||
export interface LoginPayload {
|
||||
email: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface LoginResponse {
|
||||
token: string;
|
||||
refreshToken: string;
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
export type CreateUserPayload = {
|
||||
email: string;
|
||||
username: string;
|
||||
phoneNumber: string;
|
||||
userType: string;
|
||||
name: {
|
||||
en: string;
|
||||
am?: string;
|
||||
};
|
||||
};
|
||||
@@ -1,5 +0,0 @@
|
||||
export type VerificationCodePayload = {
|
||||
email: string;
|
||||
phoneNumber: string;
|
||||
type: string;
|
||||
};
|
||||
@@ -2,38 +2,129 @@ import {
|
||||
UseQueryOptions,
|
||||
QueryObserverOptions,
|
||||
} from "@tanstack/react-query";
|
||||
import axios from "axios";
|
||||
import axios, { AxiosError, InternalAxiosRequestConfig } from "axios";
|
||||
import { URL_CONSTANTS } from "@/constants/URLS";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Axios client
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const client = axios.create({
|
||||
const client = axios.create({
|
||||
baseURL: import.meta.env.VITE_API_URL,
|
||||
});
|
||||
|
||||
function getCookie(name: string): string | undefined {
|
||||
return document.cookie
|
||||
.split("; ")
|
||||
.find((row) => row.startsWith(`${name}=`))
|
||||
?.split("=")[1];
|
||||
}
|
||||
|
||||
function setCookie(name: string, value: string, days: number) {
|
||||
const expires = new Date();
|
||||
expires.setDate(expires.getDate() + days);
|
||||
document.cookie = `${name}=${value}; path=/; expires=${expires.toUTCString()}; SameSite=Lax`;
|
||||
}
|
||||
|
||||
function clearAuthCookies() {
|
||||
["auth-token", "refresh-token", "auth-user", "current-position-id", "selected-position-id"].forEach(
|
||||
(name) => {
|
||||
document.cookie = `${name}=; Max-Age=0; path=/`;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// Attach auth token to every request
|
||||
client.interceptors.request.use((config) => {
|
||||
// TODO: replace with secure storage (cookie/localStorage/auth provider)
|
||||
const token = document.cookie
|
||||
.split("; ")
|
||||
.find((row) => row.startsWith("auth-token="))
|
||||
?.split("=")[1];
|
||||
|
||||
const token = getCookie("auth-token");
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
return config;
|
||||
});
|
||||
|
||||
// Handle auth errors globally
|
||||
// Token refresh state
|
||||
let isRefreshing = false;
|
||||
let failedQueue: {
|
||||
resolve: (token: string) => void;
|
||||
reject: (error: unknown) => void;
|
||||
}[] = [];
|
||||
|
||||
function processQueue(error: unknown, token?: string) {
|
||||
failedQueue.forEach(({ resolve, reject }) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
} else {
|
||||
resolve(token!);
|
||||
}
|
||||
});
|
||||
failedQueue = [];
|
||||
}
|
||||
|
||||
// Handle auth errors globally with token refresh
|
||||
client.interceptors.response.use(
|
||||
(response) => response,
|
||||
(error) => {
|
||||
if (error.response?.status === 401) {
|
||||
window.location.href = "/auth";
|
||||
async (error: AxiosError) => {
|
||||
const originalRequest = error.config as InternalAxiosRequestConfig & {
|
||||
_retry?: boolean;
|
||||
};
|
||||
|
||||
// Don't intercept if:
|
||||
// - no response (network error)
|
||||
// - status is not 401
|
||||
// - already retried
|
||||
// - it's the refresh endpoint itself
|
||||
if (
|
||||
!error.response ||
|
||||
error.response.status !== 401 ||
|
||||
originalRequest._retry ||
|
||||
originalRequest.url === URL_CONSTANTS.AUTH.REFRESH_TOKEN
|
||||
) {
|
||||
return Promise.reject(error);
|
||||
}
|
||||
return Promise.reject(error);
|
||||
}
|
||||
|
||||
if (isRefreshing) {
|
||||
return new Promise<string>((resolve, reject) => {
|
||||
failedQueue.push({ resolve, reject });
|
||||
}).then((token) => {
|
||||
originalRequest.headers.Authorization = `Bearer ${token}`;
|
||||
return client(originalRequest);
|
||||
});
|
||||
}
|
||||
|
||||
originalRequest._retry = true;
|
||||
isRefreshing = true;
|
||||
|
||||
const refreshToken = getCookie("refresh-token");
|
||||
|
||||
if (!refreshToken) {
|
||||
isRefreshing = false;
|
||||
clearAuthCookies();
|
||||
if (window.location.pathname !== "/login") {
|
||||
window.location.href = "/login";
|
||||
}
|
||||
return Promise.reject(error);
|
||||
}
|
||||
|
||||
try {
|
||||
const { data } = await client.post<{ data: { token: string; refreshToken: string } }>(
|
||||
URL_CONSTANTS.AUTH.REFRESH_TOKEN,
|
||||
{ refreshToken },
|
||||
);
|
||||
const { token, refreshToken: newRefreshToken } = data.data;
|
||||
setCookie("auth-token", token, 7);
|
||||
setCookie("refresh-token", newRefreshToken, 7);
|
||||
originalRequest.headers.Authorization = `Bearer ${token}`;
|
||||
processQueue(null, token);
|
||||
return client(originalRequest);
|
||||
} catch (refreshError) {
|
||||
processQueue(refreshError, undefined);
|
||||
clearAuthCookies();
|
||||
if (window.location.pathname !== "/login") {
|
||||
window.location.href = "/login";
|
||||
}
|
||||
return Promise.reject(refreshError);
|
||||
} finally {
|
||||
isRefreshing = false;
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
export { client };
|
||||
export type { UseQueryOptions, QueryObserverOptions };
|
||||
|
||||
29
apps/edr-freight-web/portal/src/utils/result.ts
Normal file
29
apps/edr-freight-web/portal/src/utils/result.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
export type Result<T, E = { code: string; message: string; statusCode?: number }> =
|
||||
| { success: true; data: T }
|
||||
| { success: false; error: E };
|
||||
|
||||
export type ApiError = {
|
||||
code: string;
|
||||
message: string;
|
||||
statusCode?: number;
|
||||
};
|
||||
|
||||
export function extractApiError(err: unknown): ApiError {
|
||||
if (err && typeof err === "object") {
|
||||
const obj = err as Record<string, unknown>;
|
||||
const response = obj.response as Record<string, unknown> | undefined;
|
||||
if (response) {
|
||||
const statusCode = response.status as number | undefined;
|
||||
const data = response.data as Record<string, unknown> | undefined;
|
||||
return {
|
||||
code: (data?.error as string) || (data?.message as string) || "api_error",
|
||||
message: (data?.message as string) || (data?.error as string) || "An unexpected error occurred",
|
||||
statusCode,
|
||||
};
|
||||
}
|
||||
if (obj.message && typeof obj.message === "string") {
|
||||
return { code: "client_error", message: obj.message };
|
||||
}
|
||||
}
|
||||
return { code: "unknown_error", message: "An unexpected error occurred" };
|
||||
}
|
||||
@@ -64,17 +64,29 @@ export interface ICustomer extends BaseEntity {
|
||||
}
|
||||
|
||||
export interface CreateCustomerDto {
|
||||
name: string;
|
||||
userId: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
email: string;
|
||||
phone: string;
|
||||
company?: string;
|
||||
customerType?: CustomerType;
|
||||
status?: CustomerStatus;
|
||||
tinNumber?: string;
|
||||
city?: string;
|
||||
country?: string;
|
||||
address?: string;
|
||||
taxId?: string;
|
||||
companyName: string;
|
||||
companyEmail: string;
|
||||
companyPhone: string;
|
||||
companyLocation: string;
|
||||
companyAddress: string;
|
||||
contactPersonName: string;
|
||||
contactPersonPhone: string;
|
||||
tinNumber: string;
|
||||
vatNumber: string;
|
||||
fanNumber: string;
|
||||
generalManagerName: string;
|
||||
generalManagerEmail: string;
|
||||
generalManagerPhone: string;
|
||||
poaName?: string;
|
||||
poaPhone?: string;
|
||||
poaAddress?: string;
|
||||
poaEmail?: string;
|
||||
poaLocation?: string;
|
||||
notes?: string;
|
||||
}
|
||||
|
||||
@@ -108,11 +120,54 @@ export interface IConsignment extends BaseEntity {
|
||||
export interface IBooking extends BaseEntity {
|
||||
reference: string;
|
||||
customerId: string;
|
||||
trainId?: string;
|
||||
trainId?: string | null;
|
||||
status: BookingStatus;
|
||||
scheduledDate: string;
|
||||
totalAmount: number;
|
||||
paymentStatus: PaymentStatus;
|
||||
|
||||
contractType: "NEW" | "RENEWAL";
|
||||
previousContractId?: string | null;
|
||||
serviceType: "RAIL_ONLY" | "RAIL_AND_FORWARDING";
|
||||
|
||||
firstMileEnabled: boolean;
|
||||
firstMilePickupAddress?: string | null;
|
||||
lastMileEnabled: boolean;
|
||||
lastMileDeliveryAddress?: string | null;
|
||||
|
||||
equipmentReturn: "WITH_RETURN" | "WITHOUT_RETURN";
|
||||
originStation: string;
|
||||
destinationStation: string;
|
||||
cargoTotalWeightVgm: number;
|
||||
|
||||
freightType: "BULK" | "BREAK_BULK";
|
||||
freightSubtype?: string | null;
|
||||
|
||||
isHazardous: boolean;
|
||||
isRefrigerated: boolean;
|
||||
|
||||
tradeDirection: "IMPORT" | "EXPORT";
|
||||
paymentCurrency: string;
|
||||
allowConsolidation: boolean;
|
||||
consolidationPartnerId?: string | null;
|
||||
|
||||
startDate?: string | null;
|
||||
endDate?: string | null;
|
||||
financialTerms?: string | null;
|
||||
|
||||
containers?: Array<{ type: string; qty: number; vgm: number }> | null;
|
||||
|
||||
versionNumber: number;
|
||||
priorityScore: number;
|
||||
|
||||
approvedByStaffId?: string | null;
|
||||
approvedByStaffAt?: string | null;
|
||||
signedByDirectorId?: string | null;
|
||||
signedByDirectorAt?: string | null;
|
||||
signedByCeoId?: string | null;
|
||||
signedByCeoAt?: string | null;
|
||||
|
||||
files?: Array<{ id: string; name: string; url: string; mimeType: string }>;
|
||||
}
|
||||
|
||||
export interface IInvoice extends BaseEntity {
|
||||
|
||||
Reference in New Issue
Block a user