diff --git a/apps/edr-freight-api/src/app.module.ts b/apps/edr-freight-api/src/app.module.ts index f49c062ef..b2a1f0c1a 100644 --- a/apps/edr-freight-api/src/app.module.ts +++ b/apps/edr-freight-api/src/app.module.ts @@ -20,8 +20,9 @@ import { DropdownSettingsModule } from "./modules/dropdown-settings/dropdown-set import { OtpModule } from './modules/otp/otp.module'; import { RuleEngineModule } from "./modules/rule-engine/rule-engine.module"; import { BackofficeModule } from "./modules/backoffice/backoffice.module"; +import { DemoPermissionsModule } from "./modules/demo-permissions/demo-permissions.module"; import { EdrOrgSeeder } from "./seed/edr-org.seeder"; - +import { DemoUsersSeeder } from "./seed/demo-users.seeder"; @Module({ imports: [ @@ -49,17 +50,20 @@ import { EdrOrgSeeder } from "./seed/edr-org.seeder"; OtpModule, RuleEngineModule, BackofficeModule, + DemoPermissionsModule, ], - providers: [EdrOrgSeeder], + providers: [EdrOrgSeeder, DemoUsersSeeder], }) export class AppModule implements OnApplicationBootstrap { constructor( private readonly seeder: DataSeeder, private readonly edrOrgSeeder: EdrOrgSeeder, - ) {} + private readonly demoUsersSeeder: DemoUsersSeeder, + ) { } async onApplicationBootstrap() { await this.seeder.run(); await this.edrOrgSeeder.run(); + await this.demoUsersSeeder.run(); } } diff --git a/apps/edr-freight-api/src/modules/demo-permissions/demo-permissions.controller.ts b/apps/edr-freight-api/src/modules/demo-permissions/demo-permissions.controller.ts new file mode 100644 index 000000000..6f425e1bb --- /dev/null +++ b/apps/edr-freight-api/src/modules/demo-permissions/demo-permissions.controller.ts @@ -0,0 +1,22 @@ +import { Controller, Get, UseGuards } from "@nestjs/common"; +import { ApiOperation, ApiTags } from "@nestjs/swagger"; + +import { PermissionGuard } from "@tria-plc/api-common/modules/auth/services/permission.guard"; + +@ApiTags("demo-permissions") +@Controller() +export class DemoPermissionsController { + @Get("test_user1") + @ApiOperation({ summary: "Permission demo (can:demo:user1)" }) + @UseGuards(PermissionGuard(["can:demo:user1"])) + testUser1() { + return { ok: true, permission: "can:demo:user1" }; + } + + @Get("test_user2") + @ApiOperation({ summary: "Permission demo (can:demo:user2)" }) + @UseGuards(PermissionGuard(["can:demo:user2"])) + testUser2() { + return { ok: true, permission: "can:demo:user2" }; + } +} diff --git a/apps/edr-freight-api/src/modules/demo-permissions/demo-permissions.module.ts b/apps/edr-freight-api/src/modules/demo-permissions/demo-permissions.module.ts new file mode 100644 index 000000000..db73ed728 --- /dev/null +++ b/apps/edr-freight-api/src/modules/demo-permissions/demo-permissions.module.ts @@ -0,0 +1,8 @@ +import { Module } from "@nestjs/common"; + +import { DemoPermissionsController } from "./demo-permissions.controller"; + +@Module({ + controllers: [DemoPermissionsController], +}) +export class DemoPermissionsModule {} diff --git a/apps/edr-freight-api/src/seed/demo-users.seeder.ts b/apps/edr-freight-api/src/seed/demo-users.seeder.ts new file mode 100644 index 000000000..8d886e3aa --- /dev/null +++ b/apps/edr-freight-api/src/seed/demo-users.seeder.ts @@ -0,0 +1,213 @@ +import { Injectable, Logger } from "@nestjs/common"; +import { hashPassword } from "@tria-plc/api-common/utils/argon"; +import { EUserStatus } from "@tria-plc/api-common/utils/enums/user.enum"; +import { ERoleKey } from "@tria-plc/api-common/utils/enums/seed.enum"; +import { + Employee, + Organization, + Permission, + Role, + RolePermission, + User, + UserCredential, + UserRole, +} from "@tria-plc/iamapi-common"; +import { DataSource } from "typeorm"; + +const SEED_FLAG = "SEED_DEMO_USERS"; + +const DEMO_ORG_KEY = "demo_iam"; +const DEMO_ORG_NAME = { en: "Demo IAM" }; + +const DEMO_PERMISSIONS = [ + { key: "can:demo:user1", name: { en: "Can access demo user1" } }, + { key: "can:demo:user2", name: { en: "Can access demo user2" } }, +]; + +const DEMO_ROLES = [ + { key: "demo_user1", name: { en: "Demo User1" } }, + { key: "demo_user2", name: { en: "Demo User2" } }, +]; + +const DEMO_USERS = [ + { + email: "user@gmail.com", + username: "user", + name: { en: "Demo User 1" }, + roleKey: "demo_user1", + }, + { + email: "user2@gmail.com", + username: "user2", + name: { en: "Demo User 2" }, + roleKey: "demo_user2", + }, +]; + +@Injectable() +export class DemoUsersSeeder { + private readonly logger = new Logger(DemoUsersSeeder.name); + + constructor(private readonly dataSource: DataSource) {} + + async run() { + const shouldSeed = process.env[SEED_FLAG]?.trim().toLowerCase() === "true"; + if (!shouldSeed) { + this.logger.log(`Skipping demo user seed because ${SEED_FLAG} is not enabled`); + return; + } + + await this.dataSource.transaction(async (manager) => { + const organizationRepository = manager.getRepository(Organization); + const employeeRepository = manager.getRepository(Employee); + const permissionRepository = manager.getRepository(Permission); + const roleRepository = manager.getRepository(Role); + const rolePermissionRepository = manager.getRepository(RolePermission); + const userRepository = manager.getRepository(User); + const userCredentialRepository = manager.getRepository(UserCredential); + const userRoleRepository = manager.getRepository(UserRole); + + await organizationRepository.upsert( + { + key: DEMO_ORG_KEY, + name: DEMO_ORG_NAME, + // status defaults to ACTIVE in IAM entity + isGovernmentOrganization: true, + }, + { conflictPaths: { key: true } }, + ); + + const organization = await organizationRepository.findOne({ + where: { key: DEMO_ORG_KEY }, + select: { id: true, key: true }, + }); + + if (!organization) { + throw new Error("demo_org_seed_failed"); + } + + await permissionRepository.upsert(DEMO_PERMISSIONS, { + conflictPaths: { key: true }, + }); + + await roleRepository.upsert(DEMO_ROLES, { + conflictPaths: { key: true }, + }); + + const roles = await roleRepository.find({ where: DEMO_ROLES.map((r) => ({ key: r.key })) }); + const permissions = await permissionRepository.find({ + where: DEMO_PERMISSIONS.map((p) => ({ key: p.key })), + }); + + const roleByKey = new Map(roles.map((r) => [r.key, r])); + const permissionByKey = new Map(permissions.map((p) => [p.key, p])); + + const superAdminRole = await roleRepository.findOne({ + where: { key: ERoleKey.SUPER_ADMIN }, + select: { id: true, key: true }, + }); + + const rolePermissionsToUpsert = [ + { + roleId: roleByKey.get("demo_user1")!.id, + permissionId: permissionByKey.get("can:demo:user1")!.id, + }, + { + roleId: roleByKey.get("demo_user2")!.id, + permissionId: permissionByKey.get("can:demo:user2")!.id, + }, + ...(superAdminRole + ? ([ + { + roleId: superAdminRole.id, + permissionId: permissionByKey.get("can:demo:user1")!.id, + }, + { + roleId: superAdminRole.id, + permissionId: permissionByKey.get("can:demo:user2")!.id, + }, + ] as Array<{ roleId: string; permissionId: string }>) + : []), + ]; + + await rolePermissionRepository.upsert(rolePermissionsToUpsert, { + conflictPaths: { roleId: true, permissionId: true }, + }); + + const hashedPassword = await hashPassword("12345678"); + + for (const demoUser of DEMO_USERS) { + const existingUser = await userRepository.findOne({ + where: { email: demoUser.email }, + select: { id: true, email: true }, + }); + + let user = existingUser; + if (!user) { + user = await userRepository.save( + userRepository.create({ + email: demoUser.email, + username: demoUser.username, + name: demoUser.name, + isActive: true, + hasSetPassword: true, + status: EUserStatus.ACCEPTED, + }), + ); + } + + // Ensure an active credential exists for login. + const activeCredentialExists = await userCredentialRepository.exists({ + where: { + userId: user.id, + isActive: true, + }, + }); + + if (!activeCredentialExists) { + await userCredentialRepository.insert({ + userId: user.id, + password: hashedPassword, + isActive: true, + }); + } + + // Login query requires a current employee in an ACTIVE organization. + const employeeExists = await employeeRepository.exists({ + where: { + userId: user.id, + organizationId: organization.id, + isCurrent: true, + }, + }); + + if (!employeeExists) { + await employeeRepository.insert({ + userId: user.id, + organizationId: organization.id, + isCurrent: true, + name: demoUser.name, + }); + } + + const role = roleByKey.get(demoUser.roleKey); + if (!role) { + throw new Error(`missing_role:${demoUser.roleKey}`); + } + + await userRoleRepository.upsert( + { + userId: user.id, + roleId: role.id, + organizationId: organization.id, + }, + { conflictPaths: { userId: true, roleId: true } }, + ); + } + }); + + this.logger.log( + "Seeded demo users + permissions (user@gmail.com, user2@gmail.com; permissions can:demo:user1/can:demo:user2)", + ); + } +} diff --git a/apps/edr-freight-web/backoffice/src/App.tsx b/apps/edr-freight-web/backoffice/src/App.tsx index 7947060ef..1ae5efea1 100644 --- a/apps/edr-freight-web/backoffice/src/App.tsx +++ b/apps/edr-freight-web/backoffice/src/App.tsx @@ -1,6 +1,6 @@ import { Navigate, Outlet, Route, Routes, useLocation, useNavigate } from "react-router-dom"; import { DashboardLayout, type SidebarItem } from "@edr/ui-common"; -import { LayoutDashboard, Network } from "lucide-react"; +import { LayoutDashboard, Network, Settings } from "lucide-react"; import { useAuth } from "./auth/useAuth"; import LoginPage from "./pages/auth/LoginPage"; @@ -10,39 +10,77 @@ 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 DemoUser1Page from "./pages/dashboard/demo/DemoUser1Page"; +import DemoUser2Page from "./pages/dashboard/demo/DemoUser2Page"; -const sidebarItems: SidebarItem[] = [ - { - label: "Overview", - href: "/dashboard/overview", - icon: , - }, - { - label: "User management", - href: "/dashboard/user-management", - icon: , - children: [ - { - label: "Employees", - href: "/dashboard/user-management/employees", - }, - { - label: "Permissions", - href: "/dashboard/user-management/permissions", - }, - { - label: "Roles", - href: "/dashboard/user-management/roles", - }, - ], - }, -]; +const hasPermission = ( + user: ReturnType["user"], + key: string, +) => { + if (!user) return false; + if (user.permissions?.some((p) => p.key === key)) return true; + return (user.employee ?? []).some((emp) => + (emp.positions ?? []).some((pos) => + (pos.permissions ?? []).some((p) => p.key === key), + ), + ); +}; const DashboardShell = () => { const navigate = useNavigate(); const location = useLocation(); const { user, logout } = useAuth(); + const sidebarItems: SidebarItem[] = [ + { + label: "Overview", + href: "/dashboard/overview", + icon: , + }, + { + label: "User management", + href: "/dashboard/user-management", + icon: , + 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", + href: "/dashboard/rule-engine", + icon: , + }, + ...(hasPermission(user, "can:demo:user1") + ? ([ + { + label: "User1", + href: "/dashboard/user1", + icon: , + }, + ] as SidebarItem[]) + : []), + ...(hasPermission(user, "can:demo:user2") + ? ([ + { + label: "User2", + href: "/dashboard/user2", + icon: , + }, + ] as SidebarItem[]) + : []), + ]; + const displayName = user?.name?.en || user?.username || user?.email || "User"; return ( @@ -84,9 +122,15 @@ const App = () => { }> } /> } /> + + } /> + } /> } /> } /> + + } /> + } /> } /> } /> diff --git a/apps/edr-freight-web/backoffice/src/components/ruleEngine/ContractType.tsx b/apps/edr-freight-web/backoffice/src/components/ruleEngine/ContractType.tsx new file mode 100644 index 000000000..dff4d0c7c --- /dev/null +++ b/apps/edr-freight-web/backoffice/src/components/ruleEngine/ContractType.tsx @@ -0,0 +1,221 @@ +import { JSXElementConstructor, MouseEventHandler, ReactElement, ReactNode, SetStateAction, useState } from 'react'; + +export const ContractTypePage = () => { + const [expandedSections, setExpandedSections] = useState({ + contractType: true, + serviceType: false, + cargoType: false + }); + + const [contractTypes, setContractTypes] = useState([ + { id: 1, name: 'Shipper', description: 'Company that sends the freight' }, + { id: 2, name: 'Consignee', description: 'Company that receives the freight' }, + { id: 3, name: 'Third Party', description: 'Company that is neither the shipper nor the consignee but is involved in the freight process' } + ]); + + const [serviceTypes, setServiceTypes] = useState([ + { id: 1, name: 'Standard', description: 'Regular shipping service' }, + { id: 2, name: 'Express', description: 'Fast delivery service' }, + { id: 3, name: 'Economy', description: 'Cost-effective shipping option' } + ]); + + const [cargoTypes, setCargoTypes] = useState([ + { id: 1, name: 'General Cargo', description: 'Standard packaged goods' }, + { id: 2, name: 'Temperature Controlled', description: 'Goods requiring specific temperature' }, + { id: 3, name: 'Hazardous Materials', description: 'Dangerous goods requiring special handling' } + ]); + + const [newContractType, setNewContractType] = useState({ name: '', description: '' }); + const [newServiceType, setNewServiceType] = useState({ name: '', description: '' }); + const [newCargoType, setNewCargoType] = useState({ name: '', description: '' }); + const [showAddForms, setShowAddForms] = useState({ + contractType: false, + serviceType: false, + + cargoType: false + }); + + type SectionKey = 'contractType' | 'serviceType' | 'cargoType'; + + const toggleSection = (section: SectionKey) => { + setExpandedSections(prev => ({ + ...prev, + [section]: !prev[section] + })); + }; + + const toggleAddForm = (section: SectionKey) => { + setShowAddForms(prev => ({ + ...prev, + [section]: !prev[section] + })); + }; + + const handleAddContractType = () => { + if (newContractType.name && newContractType.description) { + setContractTypes([ + ...contractTypes, + { id: Date.now(), ...newContractType } + ]); + setNewContractType({ name: '', description: '' }); + toggleAddForm('contractType'); + } + }; + + const handleAddServiceType = () => { + if (newServiceType.name && newServiceType.description) { + setServiceTypes([ + ...serviceTypes, + { id: Date.now(), ...newServiceType } + ]); + setNewServiceType({ name: '', description: '' }); + toggleAddForm('serviceType'); + } + }; + + const handleAddCargoType = () => { + if (newCargoType.name && newCargoType.description) { + setCargoTypes([ + ...cargoTypes, + { id: Date.now(), ...newCargoType } + ]); + setNewCargoType({ name: '', description: '' }); + toggleAddForm('cargoType'); + } + }; + + const handleDelete = (type: string, id: number) => { + if (type === 'contract') { + setContractTypes(contractTypes.filter(item => item.id !== id)); + } else if (type === 'service') { + setServiceTypes(serviceTypes.filter(item => item.id !== id)); + } else if (type === 'cargo') { + setCargoTypes(cargoTypes.filter(item => item.id !== id)); + } + }; + + const handleEdit = (type: any, id: any) => { + // Implement edit functionality as needed + alert(`Edit ${type} type with id: ${id}`); + }; + + const renderTable = (title: string | number | boolean | ReactElement> | Iterable | null | undefined, types: any[], onAdd: { (): void; (): void; (): void; }, newItem: { name: any; description: any; }, setNewItem: { (value: SetStateAction<{ name: string; description: string; }>): void; (value: SetStateAction<{ name: string; description: string; }>): void; (value: SetStateAction<{ name: string; description: string; }>): void; (arg0: any): void; }, showAddForm: boolean, typeKey: string, addHandler: MouseEventHandler | undefined) => ( +
+
toggleSection(typeKey)} + > + + {expandedSections[typeKey] ? '▼' : '▶'} + +

{title}

+
+ + {expandedSections[typeKey] && ( +
+ + + {showAddForm && ( +
+

Add New {title.replace(' Types', '')}

+
+ setNewItem({ ...newItem, name: e.target.value })} + style={{ marginRight: '10px', padding: '5px' }} + /> + setNewItem({ ...newItem, description: e.target.value })} + style={{ marginRight: '10px', padding: '5px' }} + /> + + +
+
+ )} + + + + + + + + + + + + {types.map((type) => ( + + + + + + + ))} + +
IDNameDescriptionActions
{type.id}{type.name}{type.description} + + +
+
+ )} +
+ ); + + return ( +
+ {renderTable( + 'Contract Types', + contractTypes, + handleAddContractType, + newContractType, + setNewContractType, + showAddForms.contractType, + 'contractType', + handleAddContractType + )} + + {renderTable( + 'Service Types', + serviceTypes, + handleAddServiceType, + newServiceType, + setNewServiceType, + showAddForms.serviceType, + 'serviceType', + handleAddServiceType + )} + + {renderTable( + 'Cargo Types', + cargoTypes, + handleAddCargoType, + newCargoType, + setNewCargoType, + showAddForms.cargoType, + 'cargoType', + handleAddCargoType + )} +
+ ); +}; \ No newline at end of file diff --git a/apps/edr-freight-web/backoffice/src/pages/dashboard/demo/DemoUser1Page.tsx b/apps/edr-freight-web/backoffice/src/pages/dashboard/demo/DemoUser1Page.tsx new file mode 100644 index 000000000..e47cb95bd --- /dev/null +++ b/apps/edr-freight-web/backoffice/src/pages/dashboard/demo/DemoUser1Page.tsx @@ -0,0 +1,67 @@ +import { useEffect, useState } from "react"; + +import { api } from "@/auth/http"; + +const DemoUser1Page = () => { + const [data, setData] = useState(null); + const [error, setError] = useState(null); + const [loading, setLoading] = useState(true); + + useEffect(() => { + let cancelled = false; + + const run = async () => { + setLoading(true); + setError(null); + + try { + const response = await api.get("/test_user1"); + if (cancelled) return; + setData(response.data); + } catch (e: any) { + if (cancelled) return; + const message = + e?.response?.data?.message || + e?.response?.data?.error || + e?.message || + "Request failed"; + setError(String(message)); + } finally { + if (!cancelled) setLoading(false); + } + }; + + void run(); + return () => { + cancelled = true; + }; + }, []); + + return ( +
+
+

User1 Demo

+

+ Calls GET /api/test_user1 (requires{' '} + can:demo:user1). +

+ +
+ {loading ?

Loading...

: null} + {error ? ( +
+ {error} +
+ ) : null} + {!loading && !error ? ( +
+              {JSON.stringify(data, null, 2)}
+            
+ ) : null} +
+
+
+ ); +}; + +export default DemoUser1Page; diff --git a/apps/edr-freight-web/backoffice/src/pages/dashboard/demo/DemoUser2Page.tsx b/apps/edr-freight-web/backoffice/src/pages/dashboard/demo/DemoUser2Page.tsx new file mode 100644 index 000000000..5ef7ad172 --- /dev/null +++ b/apps/edr-freight-web/backoffice/src/pages/dashboard/demo/DemoUser2Page.tsx @@ -0,0 +1,67 @@ +import { useEffect, useState } from "react"; + +import { api } from "@/auth/http"; + +const DemoUser2Page = () => { + const [data, setData] = useState(null); + const [error, setError] = useState(null); + const [loading, setLoading] = useState(true); + + useEffect(() => { + let cancelled = false; + + const run = async () => { + setLoading(true); + setError(null); + + try { + const response = await api.get("/test_user2"); + if (cancelled) return; + setData(response.data); + } catch (e: any) { + if (cancelled) return; + const message = + e?.response?.data?.message || + e?.response?.data?.error || + e?.message || + "Request failed"; + setError(String(message)); + } finally { + if (!cancelled) setLoading(false); + } + }; + + void run(); + return () => { + cancelled = true; + }; + }, []); + + return ( +
+
+

User2 Demo

+

+ Calls GET /api/test_user2 (requires{' '} + can:demo:user2). +

+ +
+ {loading ?

Loading...

: null} + {error ? ( +
+ {error} +
+ ) : null} + {!loading && !error ? ( +
+              {JSON.stringify(data, null, 2)}
+            
+ ) : null} +
+
+
+ ); +}; + +export default DemoUser2Page; diff --git a/apps/edr-freight-web/backoffice/src/pages/ruleEngine/RuleEngine.tsx b/apps/edr-freight-web/backoffice/src/pages/ruleEngine/RuleEngine.tsx new file mode 100644 index 000000000..96493948d --- /dev/null +++ b/apps/edr-freight-web/backoffice/src/pages/ruleEngine/RuleEngine.tsx @@ -0,0 +1,14 @@ +import { ContractTypePage, } from "@/components/ruleEngine/ContractType"; + +export const RuleEnginePage = () => { + return
+

+ Rule Engine Page +

+ +
+ +
+ +
; +}; \ No newline at end of file diff --git a/apps/edr-freight-web/portal/src/App.tsx b/apps/edr-freight-web/portal/src/App.tsx index 968f0925d..139e74280 100644 --- a/apps/edr-freight-web/portal/src/App.tsx +++ b/apps/edr-freight-web/portal/src/App.tsx @@ -7,109 +7,79 @@ import { } from "react-router-dom"; import { DashboardLayout, type SidebarItem } from "@edr/ui-common"; import { - LayoutDashboard, - Users, CalendarCheck, - Package, MapPin, - Train, Receipt, FileText, - Settings, - UserCircle, - FileUp, - MapPinned, + Home, + Loader2, + User, } from "lucide-react"; -import BookingsPage from "./pages/bookings/BookingsPage"; +import useAuth from "./hooks/useAuth"; + +import ProfilePage from "./pages/ProfilePage"; +import MyPortalPage from "./pages/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 MyBookings from "./pages/bookings/MyBookings"; import BookingDetailPage from "./pages/bookings/BookingDetailPage"; import NewBookingPage from "./pages/bookings/NewBookingPage"; -import ConsignmentsPage from "./pages/consignments/ConsignmentsPage"; -import ConsignmentDetailPage from "./pages/consignments/ConsignmentDetailPage"; 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 CustomersPage from "./pages/customers/CustomersPage"; -import CustomerDetailPage from "./pages/customers/CustomerDetailPage"; -import NewCustomerPage from "./pages/customers/NewCustomerPage"; -import DocumentsPage from "./pages/documents/DocumentsPage"; -import DropdownSettingsPage from "./pages/admin/DropdownSettingsPage"; -import FileUploadSettingsPage from "./pages/admin/FileUploadSettingsPage"; -import MyPortalPage from "./pages/portal/MyPortalPage"; -import EDRFreightLandingPage from "./pages/EDRFreightLandingPage"; -import SignupPage from "./pages/accounts/SignupPage"; -import VerificationOtpPage from "./pages/accounts/VerificationOtpPage"; -import SetPasswordPage from "./pages/accounts/SetPasswordPage"; -import Station from "./components/stations/Station"; +import { useEffect } from "react"; const sidebarItems: SidebarItem[] = [ - { label: "My Portal", href: "/", icon: }, - { label: "Dashboard", href: "/dashboard", icon: }, - { label: "Customers", href: "/customers", icon: }, + { label: "Home", href: "/", icon: }, { label: "My Bookings", href: "/bookings", icon: }, - { label: "Consignments", href: "/consignments", icon: }, { label: "Tracking", href: "/tracking", icon: }, - { label: "Stations", href: "/stations", icon: }, - { label: "Trains", href: "/trains", icon: }, { label: "Billing", href: "/billing", icon: }, - { label: "Documents", href: "/documents", icon: }, - { label: "Dropdown Settings", href: "/admin/dropdowns", icon: }, - { - label: "File Upload Settings", - href: "/admin/file-uploads", - icon: , - }, + { label: "Profile", href: "/profile", icon: }, ]; 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 ; + console.log({ customer, isPending, user }); + useEffect(() => { + if (!user) return; + // if (!user.hasSetPassword) navigate("/set-password"); + }, [user]); + + if (isPending) { + return ( +
+ +
+ ); } - if (user) { + if (!user) { return ( } /> + } /> } /> } /> } /> - } /> - {/* } /> */} + } /> ); } + if (user && !customer && !customerQuery.isPending) { + return ; + } + 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 ( { enableThemeToggle userName={displayName} userEmail={userEmail} - onLogout={handleLogout} + onLogout={logout} > - } /> } /> } /> - } /> - } /> - } /> - } /> } /> } /> - } /> - } /> } /> - } /> - } /> } /> - } /> - } /> - } - /> - } /> + } /> } /> diff --git a/apps/edr-freight-web/portal/src/components/auth/AuthLayout.tsx b/apps/edr-freight-web/portal/src/components/auth/AuthLayout.tsx new file mode 100644 index 000000000..9d023a3ec --- /dev/null +++ b/apps/edr-freight-web/portal/src/components/auth/AuthLayout.tsx @@ -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 ( +
+
+
+
+
+
+
+ +
+
+

EDR Freight

+

+ Railway Logistics Platform +

+
+
+
+
+ {left.badge} +
+

+ {left.title} +

+

+ {left.description} +

+
+
+ {left.features.map((item) => ( +
+
+ +
+ {item} +
+ ))} +
+
+
+
+
+
+
+ +
+
+

EDR Freight

+

+ Railway Logistics Platform +

+
+
+
{children}
+
+
+
+
+ ); +} diff --git a/apps/edr-freight-web/portal/src/components/auth/PhoneInput.tsx b/apps/edr-freight-web/portal/src/components/auth/PhoneInput.tsx new file mode 100644 index 000000000..e490a28ef --- /dev/null +++ b/apps/edr-freight-web/portal/src/components/auth/PhoneInput.tsx @@ -0,0 +1,43 @@ +import { Field, FieldLabel, FieldError, Input } from "@edr/ui-common"; + +interface PhoneInputProps { + disabled?: boolean; + countryCode?: React.ComponentProps; + phone?: React.ComponentProps; + countryCodeError?: { message?: string }; + phoneError?: { message?: string }; + label?: string; +} + +export default function PhoneInput({ + disabled, + countryCode: countryCodeProps, + phone: phoneProps, + countryCodeError, + phoneError, + label = "Phone Number", +}: PhoneInputProps) { + return ( + + {label} +
+ + +
+ +
+ ); +} diff --git a/apps/edr-freight-web/portal/src/components/stations/Station.tsx b/apps/edr-freight-web/portal/src/components/stations/Station.tsx deleted file mode 100644 index da65b3094..000000000 --- a/apps/edr-freight-web/portal/src/components/stations/Station.tsx +++ /dev/null @@ -1,228 +0,0 @@ -import { useMemo, useState } from "react"; -import { - AlertCircle, - CircleOff, - Loader2, - MapPin, - Search, - TrainFront, -} from "lucide-react"; - -import Breadcrumbs from "@/components/Breadcrumbs"; -import { useDropdownSettingByCode } from "@/hooks/useDropdownSettings"; -import type { DropdownOption } from "@/types/dropdownSettings"; -import { - Card, - CardContent, - CardDescription, - CardHeader, - CardTitle, - DataTable, - DataTableFooter, - Input, - type ColumnDef, - usePagination, -} from "@edr/ui-common"; - -const STATION_DROPDOWN_CODE = "stations_ter"; - -export default function Station() { - const { pagination, setPagination } = usePagination({ pageSize: 10 }); - const [query, setQuery] = useState(""); - - const { data, isLoading, isError, error } = useDropdownSettingByCode( - STATION_DROPDOWN_CODE, - ); - - const stations = useMemo( - () => [...(data?.children ?? [])].sort((a, b) => a.order - b.order), - [data?.children], - ); - - const filtered = useMemo(() => { - const q = query.trim().toLowerCase(); - if (!q) return stations; - - return stations.filter( - (station) => - station.label.toLowerCase().includes(q) || - station.value.toLowerCase().includes(q) || - (station.note ?? "").toLowerCase().includes(q), - ); - }, [query, stations]); - - const total = filtered.length; - const pageCount = Math.max(1, Math.ceil(total / pagination.pageSize)); - const start = pagination.pageIndex * pagination.pageSize; - const end = Math.min(start + pagination.pageSize, total); - const paginatedData = useMemo( - () => filtered.slice(start, end), - [end, filtered, start], - ); - - const activeCount = stations.filter((station) => !station.disabled).length; - const disabledCount = stations.length - activeCount; - - const status: "loading" | "error" | "success" = isLoading - ? "loading" - : isError - ? "error" - : "success"; - - const columns: ColumnDef[] = [ - { - id: "station", - header: "Station", - cell: ({ row }) => { - const station = row.original; - return ( -
-
- -
-
-

{station.label}

-

- {station.note ?? "No station note"} -

-
-
- ); - }, - }, - { - id: "value", - header: "Code", - cell: ({ row }) => ( - - {row.original.value} - - ), - }, - { - accessorKey: "order", - header: "Order", - }, - { - id: "status", - header: "Status", - cell: ({ row }) => - row.original.disabled ? ( - - - Disabled - - ) : ( - - - Active - - ), - }, - ]; - - return ( -
-
- - - -
-

- Stations -

-

- Station options loaded from dropdown code{" "} - stations_ter. -

-
- -
- - { - setQuery(event.target.value); - setPagination({ - pageIndex: 0, - pageSize: pagination.pageSize, - }); - }} - placeholder="Search stations..." - className="pl-8!" - /> -
-
- -
- - - -
- - {isError ? ( - - - - Failed to load stations.{" "} - {error instanceof Error ? error.message : "Unknown error."} - - - ) : null} - - - - Station List - - All configured freight stations from the dropdown service. - - - - - {isLoading ? ( -
- - Loading stations... -
- ) : ( - - )} -
-
-
-
- ); -} - -function StationStat({ label, value }: { label: string; value: number }) { - return ( - - -
-

{label}

-

{value}

-
-
- -
-
-
- ); -} diff --git a/apps/edr-freight-web/portal/src/constants/URLS.ts b/apps/edr-freight-web/portal/src/constants/URLS.ts index f22b31e39..84db5e2c2 100644 --- a/apps/edr-freight-web/portal/src/constants/URLS.ts +++ b/apps/edr-freight-web/portal/src/constants/URLS.ts @@ -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", - } -}; \ No newline at end of file +}; diff --git a/apps/edr-freight-web/portal/src/hooks/useAuth.ts b/apps/edr-freight-web/portal/src/hooks/useAuth.ts new file mode 100644 index 000000000..dd9a1c5b6 --- /dev/null +++ b/apps/edr-freight-web/portal/src/hooks/useAuth.ts @@ -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> => { + 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> => { + 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> => { + 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> => { + 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> => { + 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> => { + 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; diff --git a/apps/edr-freight-web/portal/src/main.tsx b/apps/edr-freight-web/portal/src/main.tsx index 45014a8d5..8c4fbeb96 100644 --- a/apps/edr-freight-web/portal/src/main.tsx +++ b/apps/edr-freight-web/portal/src/main.tsx @@ -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( - - - - - + , diff --git a/apps/edr-freight-web/portal/src/pages/EDRFreightLandingPage.tsx b/apps/edr-freight-web/portal/src/pages/EDRFreightLandingPage.tsx index d0faeb662..54bffc47b 100644 --- a/apps/edr-freight-web/portal/src/pages/EDRFreightLandingPage.tsx +++ b/apps/edr-freight-web/portal/src/pages/EDRFreightLandingPage.tsx @@ -1,3 +1,4 @@ +import { Link } from "react-router-dom"; import { ArrowRight, BarChart3, @@ -85,9 +86,7 @@ export default function EDRFreightLandingPage() {
-

- EDR Freight -

+

EDR Freight

Rail Logistics Platform @@ -119,20 +118,20 @@ export default function EDRFreightLandingPage() {

- Login - + - Get Started - +
); -} \ No newline at end of file +} diff --git a/apps/edr-freight-web/portal/src/pages/MyPortalPage.tsx b/apps/edr-freight-web/portal/src/pages/MyPortalPage.tsx new file mode 100644 index 000000000..440617f3e --- /dev/null +++ b/apps/edr-freight-web/portal/src/pages/MyPortalPage.tsx @@ -0,0 +1,360 @@ +import { useMemo } from "react"; +import { Link } from "react-router-dom"; +import { + ArrowRight, + Building2, + CheckCircle2, + Clock, + DollarSign, + Eye, + Mail, + MapPin, + Package, + Phone, + Plus, + Receipt, + Truck, +} from "lucide-react"; + +import { + getCurrentCustomer, + getMyBookings, + getMyInvoices, + getMyShipments, +} from "@/lib/currentCustomer"; +import { formatCurrency } from "@/pages/billing/invoices.mock"; +import type { ShipmentStatus } from "@/pages/tracking/shipments.mock"; +import type { InvoiceStatus } from "@/pages/billing/invoices.mock"; +import type { BookingStatus } from "@/pages/bookings/bookings.mock"; +import { + Button, + Card, + CardContent, + CardHeader, + CardTitle, + CardDescription, +} from "@edr/ui-common"; + +export default function MyPortalPage() { + const me = useMemo(() => getCurrentCustomer(), []); + const myBookings = useMemo(() => getMyBookings(), []); + const myShipments = useMemo(() => getMyShipments(), []); + const myInvoices = useMemo(() => getMyInvoices(), []); + + const activeBookings = myBookings.filter( + (b) => b.status === "Confirmed" || b.status === "In Transit", + ); + const activeShipments = myShipments.filter((s) => s.status === "In Transit"); + const outstandingInvoices = myInvoices.filter( + (inv) => inv.status === "Sent" || inv.status === "Overdue", + ); + const totalOutstanding = outstandingInvoices + .filter((inv) => inv.currency === "USD") + .reduce((sum, inv) => sum + inv.amount, 0); + const totalSpent = myInvoices + .filter((inv) => inv.status === "Paid" && inv.currency === "USD") + .reduce((sum, inv) => sum + inv.amount, 0); + + const recentBookings = [...myBookings].slice(0, 5); + const recentInvoices = [...myInvoices].slice(0, 4); + + return ( +
+
+ {/* Welcome banner */} +
+
+
+
+ {me.company.charAt(0)} +
+
+

Welcome back

+

{me.name}

+

+ + {me.company} + · + + {me.customerType} + +

+
+
+ +
+ + + + + + +
+
+
+ + {/* Active Shipments */} + + +
+ Active Shipments + + Live tracking for your in-flight cargo + +
+ + View all + + +
+ + + {activeShipments.length === 0 ? ( +

+ No shipments currently in transit. +

+ ) : ( +
+ {activeShipments.slice(0, 4).map((shipment) => ( +
+
+ + {shipment.reference} + + +
+

+ {shipment.originStation} + + {shipment.destinationStation} +

+
+ + + {shipment.currentLocation} + + ETA {shipment.eta} +
+
+
+
+
+ ))} +
+ )} + + + + {/* Recent bookings */} + + +
+ Recent Bookings + Your latest freight requests +
+ + View all + + +
+ + + {recentBookings.length === 0 ? ( +

+ You haven't booked any freight yet. +

+ ) : ( +
+ + + + + + + + + + + + {recentBookings.map((booking) => ( + + + + + + + + ))} + +
ReferenceRouteCargoStatus + Action +
+ {booking.reference} + + {booking.originStation} → {booking.destinationStation} + + {booking.cargoType} + + + + + + +
+
+ )} +
+
+ + {/* Invoices */} + + +
+ Recent Invoices + + {outstandingInvoices.length} outstanding · {myInvoices.length}{" "} + total + +
+ + View all + + +
+ + + {recentInvoices.length === 0 ? ( +

+ No invoices yet. +

+ ) : ( +
+ {recentInvoices.map((invoice) => ( +
+
+ + +
+

+ {formatCurrency(invoice.amount, invoice.currency)} +

+

+ + Due {invoice.dueDate} +

+
+ ))} +
+ )} +
+
+
+
+ ); +} + +function ProfileRow({ + icon, + label, + value, +}: { + icon: React.ReactNode; + label: string; + value: string; +}) { + return ( +
+
{icon}
+
+

{label}

+

{value}

+
+
+ ); +} + +function ShipmentBadge({ status }: { status: ShipmentStatus }) { + const styles: Record = { + "In Transit": "bg-indigo-100 text-indigo-700", + Delivered: "bg-emerald-100 text-emerald-700", + Delayed: "bg-red-100 text-red-700", + }; + return ( + + {status} + + ); +} + +function BookingBadge({ status }: { status: BookingStatus }) { + const styles: Record = { + Pending: "bg-amber-100 text-amber-700", + Confirmed: "bg-sky-100 text-sky-700", + "In Transit": "bg-indigo-100 text-indigo-700", + Delivered: "bg-emerald-100 text-emerald-700", + Cancelled: "bg-red-100 text-red-700", + }; + return ( + + {status} + + ); +} + +function InvoiceBadge({ status }: { status: InvoiceStatus }) { + const styles: Record = { + Draft: "bg-slate-100 text-slate-600", + Sent: "bg-sky-100 text-sky-700", + Paid: "bg-emerald-100 text-emerald-700", + Overdue: "bg-red-100 text-red-700", + Cancelled: "bg-amber-100 text-amber-700", + }; + return ( + + {status} + + ); +} diff --git a/apps/edr-freight-web/portal/src/pages/ProfilePage.tsx b/apps/edr-freight-web/portal/src/pages/ProfilePage.tsx new file mode 100644 index 000000000..e0d364bc1 --- /dev/null +++ b/apps/edr-freight-web/portal/src/pages/ProfilePage.tsx @@ -0,0 +1,326 @@ +import { useMemo } from "react"; +import { + User, + Building2, + Phone, + Mail, + MapPin, + ShieldCheck, + Briefcase, + UserCheck, + Building, + Globe, + Fingerprint, + FileCheck, + Settings2, + ExternalLink, +} from "lucide-react"; +import useAuth from "@/hooks/useAuth"; +import { + Card, + CardHeader, + CardTitle, + CardDescription, + CardContent, + CardAction, + Badge, + Separator, + SmartFileInput, + Button, +} from "@edr/ui-common"; +import type { IFileUploadSetting } from "@edr/types/freight"; +import { cn } from "@/lib/utils"; + +export default function ProfilePage() { + const { user, customer, isPending } = useAuth(); + + const documentSettings = useMemo(() => ({ + id: "profile-docs", + code: "customer_documents", + label: "Customer Documents", + entity: "customer", + createdAt: new Date(), + updatedAt: new Date(), + fields: [ + { + id: "doc-tin", + settingId: "profile-docs", + fileKey: "tin_certificate", + fileLabel: "TIN Certificate", + isRequired: true, + isMultiple: false, + maxFiles: 1, + allowedExtensions: [".pdf", ".jpg", ".jpeg", ".png"], + maxSizeMb: 5, + order: 1, + createdAt: new Date(), + updatedAt: new Date(), + }, + { + id: "doc-license", + settingId: "profile-docs", + fileKey: "business_license", + fileLabel: "Business/Investment License", + isRequired: true, + isMultiple: false, + maxFiles: 1, + allowedExtensions: [".pdf", ".jpg", ".jpeg", ".png"], + maxSizeMb: 5, + order: 2, + createdAt: new Date(), + updatedAt: new Date(), + }, + { + id: "doc-reg", + settingId: "profile-docs", + fileKey: "registration_certificate", + fileLabel: "Business Registration Certificate", + isRequired: true, + isMultiple: false, + maxFiles: 1, + allowedExtensions: [".pdf", ".jpg", ".jpeg", ".png"], + maxSizeMb: 5, + order: 3, + createdAt: new Date(), + updatedAt: new Date(), + }, + { + id: "doc-id", + settingId: "profile-docs", + fileKey: "national_id", + fileLabel: "National ID", + isRequired: true, + isMultiple: false, + maxFiles: 1, + allowedExtensions: [".pdf", ".jpg", ".jpeg", ".png"], + maxSizeMb: 5, + order: 4, + createdAt: new Date(), + updatedAt: new Date(), + }, + { + id: "doc-poa", + settingId: "profile-docs", + fileKey: "power_of_attorney", + fileLabel: "Power of Attorney", + isRequired: false, + isMultiple: false, + maxFiles: 1, + allowedExtensions: [".pdf", ".jpg", ".jpeg", ".png"], + maxSizeMb: 5, + order: 5, + createdAt: new Date(), + updatedAt: new Date(), + }, + ], + }), []); + + if (isPending) { + return ( +
+
+
+ ); + } + + const displayName = user?.name?.en || user?.username || user?.email || "User"; + + return ( +
+
+ {/* Header Section */} +
+
+
+ +
+
+
+

+ {displayName} +

+ + Verified + +
+

+ + {customer?.companyName || "No Company Linked"} +

+
+
+
+ +
+
+ + + +
+ {/* Left Column - Personal & Company Info */} +
+
+ {/* Personal Details Card */} + + + + + Personal Details + + Your account contact information + + + + + + } label="Email Address" value={user?.email} /> + } label="Phone Number" value={user?.phoneNumber} /> + } label="Username" value={user?.username} /> + + + + {/* Company Details Card */} + + + + + Company Details + + Business registration information + + + } label="Location" value={customer?.companyLocation} /> + } label="Address" value={customer?.companyAddress} /> + } label="TIN Number" value={customer?.tinNumber} /> + } label="FAN Number" value={customer?.fanNumber} /> + + +
+ + {/* Personnel Card */} + + + + + Key Personnel + + Management and contact persons + + +
+

+ Contact Person +

+
+ + +
+
+
+

+ General Manager +

+
+ + + +
+
+
+
+ + {/* Power of Attorney Section (Conditional) */} + {customer?.poaName && ( + + + + + Power of Attorney + + Authorized representative details + + + + + + + + + )} +
+ + {/* Right Column - Documents */} +
+ + + + + Documents + + Manage required business documents + + + + + + + +
+ +
+ +

Secure Account

+

+ Your information is protected by enterprise-grade security. + Contact support for verified information updates. +

+
+ +
+
+
+
+
+
+
+ ); +} + +function InfoItem({ + icon, + label, + value, +}: { + icon?: React.ReactNode; + label: string; + value?: string | null; +}) { + return ( +
+ {icon && ( +
+ {icon} +
+ )} +
+

+ {label} +

+

+ {value || "—"} +

+
+
+ ); +} diff --git a/apps/edr-freight-web/portal/src/pages/accounts/LoginPage.tsx b/apps/edr-freight-web/portal/src/pages/accounts/LoginPage.tsx new file mode 100644 index 000000000..4cfc64619 --- /dev/null +++ b/apps/edr-freight-web/portal/src/pages/accounts/LoginPage.tsx @@ -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("email"); + const [identifier, setIdentifier] = useState(""); + const [countryCode, setCountryCode] = useState("+251"); + const [phoneNumber, setPhoneNumber] = useState(""); + const [password, setPassword] = useState(""); + const [error, setError] = useState(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 ( + +
+
+ +
+

Welcome back

+

+ Enter your credentials to access your portal +

+
+ +
+
+ + +
+ + + {method === "email" ? ( + + Email Address + setIdentifier(e.target.value)} + required + disabled={loading} + /> + + ) : ( + ) => setCountryCode(e.target.value), + }} + phone={{ + value: phoneNumber, + onChange: (e: React.ChangeEvent) => setPhoneNumber(e.target.value), + }} + /> + )} + + +
+ Password + +
+ setPassword(e.target.value)} + required + disabled={loading} + /> +
+
+ + {error && ( +
+ {error} +
+ )} + + + +

+ Don't have an account?{" "} + +

+
+
+ ); +} diff --git a/apps/edr-freight-web/portal/src/pages/accounts/OnboardingPage.tsx b/apps/edr-freight-web/portal/src/pages/accounts/OnboardingPage.tsx new file mode 100644 index 000000000..cea9d1774 --- /dev/null +++ b/apps/edr-freight-web/portal/src/pages/accounts/OnboardingPage.tsx @@ -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; + +const stepFields: Record = { + 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("company"); + + const { + register, + handleSubmit, + trigger, + formState: { errors }, + } = useForm({ + 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 ( + +
+
+
+ } + active={step === "company"} + completed={step !== "company"} + /> + } + active={step === "personnel"} + completed={step === "poa"} + /> + } + active={step === "poa"} + completed={false} + /> +
+

+ {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)"} +

+
+ +
+ + {step === "company" && ( + <> + + Company Name + + + + +
+ + Company Email + + + + + +
+ +
+ + Location + + + + + + Address + + + +
+ +
+ + TIN Number (10 digits) + + + + + + VAT Number + + + +
+ + + FAN Number (16 digits) + + + + + )} + + {step === "personnel" && ( + <> +

+ Personal details are pulled from your account. Contact and + management info is collected below. +

+ +
+

+ Contact Person +

+
+ + Name + + + + + +
+
+ +
+ +
+

+ General Manager +

+
+ + Name + + + + + + Email + + + + + +
+
+ + )} + + {step === "poa" && ( + <> +

+ Power of Attorney details are optional. Skip if not applicable. +

+ + + PoA Name + + + +
+ + PoA Email + + + + +
+ +
+ + PoA Location + + + + + PoA Address + + +
+ + )} +
+ +
+ + + +
+
+ + ); +} + +function StepIcon({ + icon, + active, + completed, +}: { + icon: React.ReactNode; + active: boolean; + completed: boolean; +}) { + return ( +
+ {completed ? : icon} +
+ ); +} diff --git a/apps/edr-freight-web/portal/src/pages/accounts/SetPasswordPage.tsx b/apps/edr-freight-web/portal/src/pages/accounts/SetPasswordPage.tsx index 83a9cd78d..44ae45afa 100644 --- a/apps/edr-freight-web/portal/src/pages/accounts/SetPasswordPage.tsx +++ b/apps/edr-freight-web/portal/src/pages/accounts/SetPasswordPage.tsx @@ -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; 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(null); + const [loading, setLoading] = useState(false); const { register, handleSubmit, + watch, formState: { errors }, - reset, } = useForm({ - 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 ( -
-
- {/* ------------------------------------------------------------------ */} - {/* Left Side */} - {/* ------------------------------------------------------------------ */} - -
-
- -
- {/* Logo */} -
-
- -
- -
-

- EDR Freight -

- -

- Railway Logistics - Platform -

-
-
- - {/* Hero */} -
-
- Account Security -
- -

- Set your secure - password -

- -

- 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", - ].map((item) => ( -
-
- -
- - - {item} - -
- ))} -
-
- - {/* Stats */} -
-
-
-

- Security Protection -

- -

- 256-bit -

-
- -
- Encrypted -
-
- -
-
-
-
-
- - {/* ------------------------------------------------------------------ */} - {/* Right Side */} - {/* ------------------------------------------------------------------ */} - -
-
- {/* Mobile Logo */} -
-
- -
- -
-

- EDR Freight -

- -

- Railway Logistics - Platform -

-
-
- - {/* Card */} -
- {/* Header */} -
-
- -
- -

- Set Password -

- -

- Create a secure - password for your - EDR Freight account. -

-
- - {/* Success */} - {setPasswordMutation.isSuccess && ( -
- Password updated - successfully. -
- )} - - {/* Error */} - {setPasswordMutation.isError && ( -
- Failed to set - password. Please try - again. -
- )} - - {/* Form */} -
- {/* Password */} -
- - -
- - - -
- - {errors.password && ( -

- { - errors.password - .message - } -

- )} -
- - {/* Confirm Password */} -
- - -
- - - -
- - {errors.confirmPassword && ( -

- { - errors - .confirmPassword - .message - } -

- )} -
- - {/* Submit */} - -
-
-
+ +
+
+
+

Set Password

+

+ Create a secure password for your account. +

-
+ + {error && ( +
+ {error} +
+ )} + +
+ + + Password +
+ + +
+ +
+ + {password && ( +
    + {requirements.map((req) => ( +
  • + {req.met ? ( + + ) : ( + + )} + {req.label} +
  • + ))} +
+ )} + + + Confirm Password +
+ + +
+ +
+
+ + +
+ ); -} \ No newline at end of file +} diff --git a/apps/edr-freight-web/portal/src/pages/accounts/SignupPage.tsx b/apps/edr-freight-web/portal/src/pages/accounts/SignupPage.tsx index 2b9b7f135..bfb175895 100644 --- a/apps/edr-freight-web/portal/src/pages/accounts/SignupPage.tsx +++ b/apps/edr-freight-web/portal/src/pages/accounts/SignupPage.tsx @@ -1,534 +1,186 @@ -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" - ), - + email: z.string().email("Invalid email address"), + 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" - ), - + .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; export default function SignupPage() { const navigate = useNavigate(); + const { signup } = useAuth(); + const [error, setError] = useState(null); + const [loading, setLoading] = useState(false); const { register, handleSubmit, formState: { errors }, - reset, } = useForm({ - 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.email, + 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 ( -
-
- {/* ------------------------------------------------------------------ */} - {/* Left Side */} - {/* ------------------------------------------------------------------ */} - -
-
- -
- {/* Logo */} -
-
- -
- -
-

- EDR Freight -

- -

- Railway Logistics - Platform -

-
-
- - {/* Hero */} -
-
- Smart Freight - Operations -
- -

- Create your freight - operations account -

- -

- 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", - ].map((item) => ( -
-
- -
- - - {item} - -
- ))} -
-
- - {/* Stats */} -
-
-
-

- Active Corridors -

- -

- 24+ -

-
- -
- Operational -
-
- -
-
-
-
-
- - {/* ------------------------------------------------------------------ */} - {/* Right Side */} - {/* ------------------------------------------------------------------ */} - -
-
- {/* Mobile Logo */} -
-
- -
- -
-

- EDR Freight -

- -

- Railway Logistics - Platform -

-
-
- - {/* Form Card */} -
- {/* Header */} -
-
- -
- -

- Create Account -

- -

- Register to access - EDR Freight - services and railway - logistics operations. -

-
- - {/* Success */} - {createUserMutation.isSuccess && ( -
- Account created - successfully. -
- )} - - {/* Error */} - {createUserMutation.isError && ( -
- Failed to create - account. Please try - again. -
- )} - - {/* Form */} -
- {/* Full Name */} -
- - - - - {errors.name?.en && ( -

- { - errors.name.en - .message - } -

- )} -
- - {/* Username */} -
- - - - - {errors.username && ( -

- { - errors.username - .message - } -

- )} -
- - {/* Email */} -
- - - - - {errors.email && ( -

- { - errors.email - .message - } -

- )} -
- - {/* Phone */} -
- - -
- - - -
- - {(errors.countryCode || - errors.phone) && ( -

- {errors - .countryCode - ?.message || - errors.phone - ?.message} -

- )} -
- - {/* Submit */} - - - {/* Footer */} -

- Already have an - account? - - -

-
-
-
+ +
+
+
+

Create Account

+

+ Register to access EDR Freight services. +

-
+ + {error && ( +
+ {error} +
+ )} + +
+ + + Full Name + + + + + + Email Address + + + + + + + + + +

+ Already have an account? + +

+
+ ); -} \ No newline at end of file +} diff --git a/apps/edr-freight-web/portal/src/pages/accounts/VerificationOtpPage.tsx b/apps/edr-freight-web/portal/src/pages/accounts/VerificationOtpPage.tsx index 091406df3..a09417c01 100644 --- a/apps/edr-freight-web/portal/src/pages/accounts/VerificationOtpPage.tsx +++ b/apps/edr-freight-web/portal/src/pages/accounts/VerificationOtpPage.tsx @@ -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; 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(null); + const [resentMessage, setResentMessage] = useState(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({ - 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 ( -
-
- {/* ------------------------------------------------------------------ */} - {/* Left Side */} - {/* ------------------------------------------------------------------ */} - -
-
- -
- {/* Logo */} -
-
- -
- -
-

- EDR Freight -

- -

- Railway Logistics - Platform -

-
-
- - {/* Hero */} -
-
- Secure - Verification -
- -

- Verify your - account securely -

- -

- 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", - ].map((item) => ( -
-
- -
- - - {item} - -
- ))} -
-
- - {/* Footer Stats */} -
-
-
-

- Verification - Security -

- -

- 99.9% -

-
- -
- Protected -
-
- -
-
-
-
+ +
+
+
- - {/* ------------------------------------------------------------------ */} - {/* Right Side */} - {/* ------------------------------------------------------------------ */} - -
-
- {/* Mobile Logo */} -
-
- -
- -
-

- EDR Freight -

- -

- Railway Logistics - Platform -

-
-
- - {/* OTP Card */} -
- {/* Header */} -
-
- -
- -

- OTP Verification -

- -

- Enter the - 6-digit code sent - to: -

- -
-

- {maskedPhone} -

-
-
- - {/* Success */} - {verifyMutation.isSuccess && ( -
- Verification - successful. -
- )} - - {/* Error */} - {verifyMutation.isError && ( -
- Invalid OTP - code. Please try - again. -
- )} - - {/* Resend Success */} - {resendMutation.isSuccess && ( -
- New OTP code sent - successfully. -
- )} - - {/* Form */} -
- {/* OTP */} -
- - - - -
- {errors.code ? ( -

- { - errors.code - .message - } -

- ) : ( -

- Enter the OTP - sent to your - phone -

- )} - - - { - otpValue.length - } - /6 - -
-
- - {/* Verify Button */} - - - {/* Resend */} - - - {/* Footer */} -

- Didn’t receive - the code? - - -

-
-
-
+

OTP Verification

+

Enter the 6-digit code sent to:

+
+

{maskedPhone}

-
+ + {error && ( +
+ {error} +
+ )} + + {resentMessage && ( +
+ {resentMessage} +
+ )} + +
+ + + Verification Code + +
+ {errors.code ? ( + + ) : ( +

Enter the OTP sent to your phone

+ )} + {otpValue.length}/6 +
+
+
+ + + + + +

+ Didn't receive the code? + +

+
+
); -} \ No newline at end of file +} diff --git a/apps/edr-freight-web/portal/src/pages/admin/DeleteDropdownSettingDialog.tsx b/apps/edr-freight-web/portal/src/pages/admin/DeleteDropdownSettingDialog.tsx deleted file mode 100644 index 1ca4e0d23..000000000 --- a/apps/edr-freight-web/portal/src/pages/admin/DeleteDropdownSettingDialog.tsx +++ /dev/null @@ -1,77 +0,0 @@ -import { useState, type ReactNode } from "react"; - -import { - Dialog, - DialogClose, - DialogContent, - DialogDescription, - DialogFooter, - DialogHeader, - DialogTitle, - DialogTrigger, -} from "@/components/ui/dialog"; - -import { Button } from "@/components/ui/button"; - -export interface DeleteDropdownSettingDialogProps { - settingLabel: string; - settingCode: string; - onConfirm?: () => void; - children?: ReactNode; - open?: boolean; - onOpenChange?: (open: boolean) => void; -} - -export default function DeleteDropdownSettingDialog({ - settingLabel, - settingCode, - onConfirm, - children, - open: openProp, - onOpenChange, -}: DeleteDropdownSettingDialogProps) { - const isControlled = openProp !== undefined; - const [internalOpen, setInternalOpen] = useState(false); - const open = isControlled ? openProp : internalOpen; - const setOpen = (next: boolean) => { - if (!isControlled) setInternalOpen(next); - onOpenChange?.(next); - }; - - return ( - - {children ? {children} : null} - - - - - Delete dropdown setting? - - - - This will remove{" "} - {settingLabel}{" "} - ({settingCode}) and all - of its options. Forms referencing this code will fall back to - empty options. - - - - - - - - - - - - - - - ); -} diff --git a/apps/edr-freight-web/portal/src/pages/admin/DeleteFileUploadSettingDialog.tsx b/apps/edr-freight-web/portal/src/pages/admin/DeleteFileUploadSettingDialog.tsx deleted file mode 100644 index 84693fa28..000000000 --- a/apps/edr-freight-web/portal/src/pages/admin/DeleteFileUploadSettingDialog.tsx +++ /dev/null @@ -1,65 +0,0 @@ -import type { ReactNode } from "react"; - -import { - Dialog, - DialogClose, - DialogContent, - DialogDescription, - DialogFooter, - DialogHeader, - DialogTitle, - DialogTrigger, -} from "@/components/ui/dialog"; - -import { Button } from "@/components/ui/button"; - -export interface DeleteFileUploadSettingDialogProps { - settingLabel: string; - settingCode: string; - onConfirm?: () => void; - children: ReactNode; -} - -export default function DeleteFileUploadSettingDialog({ - settingLabel, - settingCode, - onConfirm, - children, -}: DeleteFileUploadSettingDialogProps) { - return ( - - {children} - - - - - Delete file upload setting? - - - - This will remove{" "} - {settingLabel}{" "} - ({settingCode}) and all - of its fields. Forms referencing this code will fall back to no - uploads. - - - - - - - - - - - - - - - ); -} diff --git a/apps/edr-freight-web/portal/src/pages/admin/DropdownSettingsPage.tsx b/apps/edr-freight-web/portal/src/pages/admin/DropdownSettingsPage.tsx deleted file mode 100644 index 1b77dcc59..000000000 --- a/apps/edr-freight-web/portal/src/pages/admin/DropdownSettingsPage.tsx +++ /dev/null @@ -1,468 +0,0 @@ -import { useEffect, useMemo, useState } from "react"; -import { - AlertCircle, - Boxes, - CheckCircle2, - Eye, - Filter, - ListOrdered, - Loader2, - MoreHorizontal, - Pencil, - Plus, - Search, - Settings, - Shield, - Sparkles, - Trash2, -} from "lucide-react"; - -import Breadcrumbs from "@/components/Breadcrumbs"; -import EditDropdownSettingDialog from "./EditDropdownSettingDialog"; -import ManageDropdownOptionsDialog from "./ManageDropdownOptionsDialog"; -import DeleteDropdownSettingDialog from "./DeleteDropdownSettingDialog"; -import { - useDeleteDropdownSetting, - useDropdownSettings, -} from "@/hooks/useDropdownSettings"; -import type { DropdownSetting } from "@/types/dropdownSettings"; -import { - DataTable, - DataTableFooter, - type ColumnDef, - usePagination, - Button, - Card, - CardHeader, - CardTitle, - CardDescription, - CardContent, - Input, - DropdownMenu, - DropdownMenuTrigger, - DropdownMenuContent, - DropdownMenuItem, - DropdownMenuSeparator, -} from "@edr/ui-common"; - -type ActiveDialog = "edit" | "options" | "delete"; - -export default function DropdownSettingsPage() { - const { pagination, setPagination } = usePagination({ pageSize: 10 }); - const [query, setQuery] = useState(""); - - const [activeDialog, setActiveDialog] = useState(null); - const [activeSetting, setActiveSetting] = useState( - null, - ); - - const openDialogFor = (dialog: ActiveDialog, setting: DropdownSetting) => { - // Defer past the DropdownMenu's close cycle. Radix's modal lock can leave - // `pointer-events: none` on when a menu closes and a dialog opens - // in the same frame — wait two RAFs and then explicitly reset the body - // style so the dialog interior is interactive. - requestAnimationFrame(() => { - requestAnimationFrame(() => { - document.body.style.pointerEvents = ""; - setActiveSetting(setting); - setActiveDialog(dialog); - }); - }); - }; - const closeDialog = () => { - setActiveDialog(null); - // Keep activeSetting briefly so dialog content doesn't flash empty during - // the close animation; cleared on next open. - }; - - // Belt-and-suspenders for the Radix pointer-events leak: any time the active - // dialog changes, schedule a body-style cleanup after the next paint. - useEffect(() => { - const id = requestAnimationFrame(() => { - if (document.body.style.pointerEvents === "none") { - document.body.style.pointerEvents = ""; - } - }); - return () => cancelAnimationFrame(id); - }, [activeDialog]); - - const { data, isLoading, isError, error } = useDropdownSettings(); - const deleteMutation = useDeleteDropdownSetting(); - - const dropdownSettings = useMemo( - () => (Array.isArray(data) ? data : []), - [data], - ); - - const filtered = useMemo(() => { - const q = query.trim().toLowerCase(); - if (!q) return dropdownSettings; - return dropdownSettings.filter( - (s) => - s.code.toLowerCase().includes(q) || - s.label.toLowerCase().includes(q) || - (s.description ?? "").toLowerCase().includes(q), - ); - }, [dropdownSettings, query]); - - const total = filtered.length; - const pageCount = Math.max(1, Math.ceil(total / pagination.pageSize)); - const start = pagination.pageIndex * pagination.pageSize; - const end = Math.min(start + pagination.pageSize, total); - - const paginatedData = useMemo( - () => filtered.slice(start, end), - [start, end, filtered], - ); - - const totalOptions = dropdownSettings.reduce( - (sum, s) => sum + (s.children?.length ?? 0), - 0, - ); - const multipleCount = dropdownSettings.filter((s) => s.multiple).length; - const searchableCount = dropdownSettings.filter( - (s) => s.meta?.searchable, - ).length; - - const status: "loading" | "error" | "success" = isLoading - ? "loading" - : isError - ? "error" - : "success"; - - const columns: ColumnDef[] = [ - { - id: "setting", - header: "Setting", - cell: ({ row }) => { - const s = row.original; - return ( -
-
- -
-
-

{s.label}

-

- {s.description ?? "No description"} -

-
-
- ); - }, - }, - { - id: "code", - header: "Code", - cell: ({ row }) => ( - - {row.original.code} - - ), - }, - { - id: "options", - header: "Options", - cell: ({ row }) => { - const s = row.original; - return ( -
- - {s.children?.length ?? 0} -
- ); - }, - }, - { - id: "behavior", - header: "Behavior", - cell: ({ row }) => { - const s = row.original; - return ( -
- {s.multiple ? ( - - ) : ( - - )} - {s.meta?.searchable ? : null} - {s.meta?.clearable ? : null} -
- ); - }, - }, - { - id: "permissions", - header: "Permissions", - cell: ({ row }) => { - const s = row.original; - const perms = s.meta?.permissions ?? []; - return ( -
- {perms.length === 0 ? ( - - ) : ( - perms.map((p) => ( - - - {p} - - )) - )} -
- ); - }, - }, - { - id: "actions", - size: 40, - cell: ({ row }) => { - const setting = row.original; - return ( -
e.stopPropagation()} - > - - - - - - - - View - - openDialogFor("options", setting)} - > - - Options - - - openDialogFor("edit", setting)} - > - - Edit - - - openDialogFor("delete", setting)} - variant="destructive" - > - - Delete - - - -
- ); - }, - }, - ]; - - return ( -
-
- - - -
-

- Dropdown Settings -

-

- Manage every dynamic dropdown across the platform — labels, - options, ordering, and permissions. -

-
- -
-
- - { - setQuery(e.target.value); - setPagination({ - pageIndex: 0, - pageSize: pagination.pageSize, - }); - }} - placeholder="Search by code, label, description..." - className="pl-8!" - /> -
- - - - -
-
- -
- } - /> - } - /> - } - /> - } - /> -
- - {isError ? ( - - - - Failed to load dropdown settings.{" "} - {error instanceof Error ? error.message : "Unknown error."} - - - ) : null} - - - -
- Registered Dropdowns - - Every dynamic dropdown the platform reads from. - -
- - -
- - - {isLoading ? ( -
- - Loading dropdown settings… -
- ) : ( - { }} - pagination={{ - pageIndex: pagination.pageIndex, - pageSize: pagination.pageSize, - pageCount: pageCount, - totalCount: total, - }} - tableOptions={{ - state: { pagination }, - onPaginationChange: setPagination, - }} - containerClassName="border-b shadow-none" - footer={DataTableFooter} - /> - )} -
-
-
- - {/* Controlled dialogs — hoisted out of the DropdownMenu so they can open - reliably after a menu item is selected. */} - {activeSetting ? ( - <> - (next ? null : closeDialog())} - /> - (next ? null : closeDialog())} - /> - deleteMutation.mutate(activeSetting.id)} - open={activeDialog === "delete"} - onOpenChange={(next) => (next ? null : closeDialog())} - /> - - ) : null} -
- ); -} - -function StatCard({ - label, - value, - icon, -}: { - label: string; - value: number; - icon: React.ReactNode; -}) { - return ( - - -
-

{label}

-

{value}

-
-
- {icon} -
-
-
- ); -} - -function BehaviorChip({ - label, - muted = false, -}: { - label: string; - muted?: boolean; -}) { - return ( - - {label} - - ); -} diff --git a/apps/edr-freight-web/portal/src/pages/admin/EditDropdownSettingDialog.tsx b/apps/edr-freight-web/portal/src/pages/admin/EditDropdownSettingDialog.tsx deleted file mode 100644 index 14922446c..000000000 --- a/apps/edr-freight-web/portal/src/pages/admin/EditDropdownSettingDialog.tsx +++ /dev/null @@ -1,336 +0,0 @@ -import { useState, type ReactNode } from "react"; -import { Hash, Loader2 } from "lucide-react"; - -import { - Dialog, - DialogClose, - DialogContent, - DialogDescription, - DialogHeader, - DialogTitle, - DialogTrigger, -} from "@/components/ui/dialog"; -import { Input } from "@/components/ui/input"; -import { Label } from "@/components/ui/label"; -import { Button } from "@/components/ui/button"; -import { Textarea } from "@/components/ui/textarea"; - -import type { - CreateDropdownSettingDto, - DropdownSetting, - UpdateDropdownSettingDto, -} from "@/types/dropdownSettings"; -import { - useCreateDropdownSetting, - useUpdateDropdownSetting, -} from "@/hooks/useDropdownSettings"; - -export interface EditDropdownSettingDialogProps { - mode?: "create" | "edit"; - setting?: DropdownSetting; - /** Optional trigger element. When omitted, the dialog renders content only and is fully controlled. */ - children?: ReactNode; - /** Controlled open state. When provided, internal state is ignored. */ - open?: boolean; - onOpenChange?: (open: boolean) => void; -} - -function parsePermissions(raw: string): string[] { - return raw - .split(",") - .map((s) => s.trim()) - .filter(Boolean); -} - -export default function EditDropdownSettingDialog({ - mode = "create", - setting, - children, - open: openProp, - onOpenChange, -}: EditDropdownSettingDialogProps) { - const isEdit = mode === "edit"; - const isControlled = openProp !== undefined; - - const [internalOpen, setInternalOpen] = useState(false); - const open = isControlled ? openProp : internalOpen; - const setOpen = (next: boolean) => { - if (!isControlled) setInternalOpen(next); - onOpenChange?.(next); - }; - const [code, setCode] = useState(setting?.code ?? ""); - const [label, setLabel] = useState(setting?.label ?? ""); - const [description, setDescription] = useState(setting?.description ?? ""); - const [icon, setIcon] = useState(setting?.meta?.icon ?? ""); - const [color, setColor] = useState(setting?.meta?.color ?? ""); - const [permissions, setPermissions] = useState( - setting?.meta?.permissions?.join(", ") ?? "", - ); - const [version, setVersion] = useState(setting?.meta?.version ?? "1.0"); - const [multiple, setMultiple] = useState(setting?.multiple ?? false); - const [searchable, setSearchable] = useState( - setting?.meta?.searchable ?? false, - ); - const [clearable, setClearable] = useState( - setting?.meta?.clearable ?? false, - ); - const [error, setError] = useState(null); - - const createMutation = useCreateDropdownSetting(); - const updateMutation = useUpdateDropdownSetting(); - const pending = createMutation.isPending || updateMutation.isPending; - - const reset = () => { - setCode(setting?.code ?? ""); - setLabel(setting?.label ?? ""); - setDescription(setting?.description ?? ""); - setIcon(setting?.meta?.icon ?? ""); - setColor(setting?.meta?.color ?? ""); - setPermissions(setting?.meta?.permissions?.join(", ") ?? ""); - setVersion(setting?.meta?.version ?? "1.0"); - setMultiple(setting?.multiple ?? false); - setSearchable(setting?.meta?.searchable ?? false); - setClearable(setting?.meta?.clearable ?? false); - setError(null); - }; - - const buildPayload = (): CreateDropdownSettingDto => ({ - code: code.trim(), - label: label.trim(), - description: description.trim() || undefined, - multiple, - meta: { - ...(icon.trim() ? { icon: icon.trim() } : {}), - ...(color.trim() ? { color: color.trim() } : {}), - searchable, - clearable, - ...(version.trim() ? { version: version.trim() } : {}), - permissions: parsePermissions(permissions), - }, - }); - - const handleSubmit = () => { - setError(null); - if (!code.trim() || !label.trim()) { - setError("Code and label are required."); - return; - } - if (!/^[a-z][a-z0-9_]*$/i.test(code.trim())) { - setError( - "Code must start with a letter and contain only letters, digits, or underscores.", - ); - return; - } - - const payload = buildPayload(); - - const onDone = () => { - setOpen(false); - if (!isEdit) reset(); - }; - const onError = (err: unknown) => { - setError( - err instanceof Error - ? err.message - : "Something went wrong. Try again.", - ); - }; - - if (isEdit && setting) { - // Update DTO omits `code` (immutable); strip it before sending. - const { code: _unused, ...updateDto } = payload; - void _unused; - updateMutation.mutate( - { id: setting.id, dto: updateDto as UpdateDropdownSettingDto }, - { onSuccess: onDone, onError }, - ); - } else { - createMutation.mutate(payload, { onSuccess: onDone, onError }); - } - }; - - return ( - { - setOpen(next); - if (!next) reset(); - }} - > - {children ? {children} : null} - - - - - {isEdit ? "Edit Dropdown Setting" : "New Dropdown Setting"} - - - {isEdit - ? "Update the metadata for this dropdown setting." - : "Define a new dynamic dropdown that admins can manage."} - - - -
-
- -
- - setCode(e.target.value)} - placeholder="e.g. cargo_type" - className="pl-10 font-mono" - disabled={isEdit} - /> -
-

- {isEdit - ? "Code is immutable after creation." - : "Stable identifier used in code. Use snake_case."} -

-
- -
- - setLabel(e.target.value)} - placeholder="e.g. Cargo Type" - /> -
- -
- -