feat: enhance the new booking form with RHC

This commit is contained in:
ghost2023
2026-05-22 15:43:20 +03:00
parent 6287022a53
commit 4691f5ad3f
5 changed files with 2124 additions and 1586 deletions

View File

@@ -0,0 +1,41 @@
import { Fragment } from "react";
import { Check } from "lucide-react";
import { STEPS } from "./schema";
export function StepIndicator({ step }: { step: number }) {
return (
<div className="flex items-center">
{STEPS.map((item, index) => (
<Fragment key={item.id}>
<div className="flex shrink-0 flex-col items-center gap-1">
<div
className={`flex h-7 w-7 items-center justify-center rounded-full text-xs font-semibold transition-colors ${
step > item.id
? "bg-primary text-primary-foreground"
: step === item.id
? "border-2 border-primary text-primary"
: "bg-muted text-muted-foreground"
}`}
>
{step > item.id ? <Check className="h-3.5 w-3.5" /> : item.id}
</div>
<span
className={`hidden text-[10px] font-medium lg:block ${
step >= item.id ? "text-foreground" : "text-muted-foreground"
}`}
>
{item.short}
</span>
</div>
{index < STEPS.length - 1 && (
<div
className={`mx-1 h-0.5 flex-1 rounded-full transition-colors ${
step > item.id ? "bg-primary" : "bg-border"
}`}
/>
)}
</Fragment>
))}
</div>
);
}

View File

@@ -0,0 +1,491 @@
import * as z from "zod";
export const STATIONS = [
"Addis Ababa",
"Adama",
"Mojo",
"Awash",
"Mieso",
"Dire Dawa",
"Aysha",
"Ali Sabieh",
"Holhol",
"Djibouti City",
] as const;
export const ETHIOPIA_STATIONS = new Set<string>([
"Addis Ababa",
"Adama",
"Mojo",
"Awash",
"Mieso",
"Dire Dawa",
]);
export const BULK_COMMODITIES = [
"Coffee",
"Beans",
"Fertilizer",
"Sugar",
"Oil",
"Livestock",
"Steel",
"Others",
] as const;
export const BREAK_BULK_TYPES = ["Machinery", "Ro-Ro", "Others"] as const;
export const MOCK_VALID_CONTRACTS = [
"EDR-2024-10001",
"EDR-2024-10002",
"EDR-2023-88123",
"EDR-2022-55442",
];
export const REQUIRED_DOC_KEYS = [
"tin_certificate",
"business_license",
"business_registration",
"national_id",
] as const;
export const STEPS = [
{ id: 1, label: "Contract Type", short: "Contract" },
{ id: 2, label: "Service Type", short: "Service" },
{ id: 3, label: "First & Last Mile", short: "Mile" },
{ id: 4, label: "Route", short: "Route" },
{ id: 5, label: "Cargo Details", short: "Cargo" },
{ id: 6, label: "Wagon Allocation", short: "Wagons" },
{ id: 7, label: "Documents", short: "Docs" },
{ id: 8, label: "Review & Submit", short: "Submit" },
] as const;
export const BOOKING_DOCS_SETTING = {
id: "booking-compliance",
createdAt: "",
updatedAt: "",
deletedAt: null,
code: "booking_compliance_docs",
label: "Compliance Documents",
description:
"Upload your company's legal credentials. All mandatory documents must be submitted before the contract request can be reviewed by EDR Line Staff.",
entity: "booking" as const,
fields: [
{
id: "f1",
createdAt: "",
updatedAt: "",
deletedAt: null,
settingId: "booking-compliance",
fileKey: "tin_certificate",
fileLabel: "TIN Certificate",
helpText:
"Tax Identification Number certificate issued by ERCA (10-digit TIN).",
isRequired: true,
isMultiple: false,
maxFiles: 1,
allowedExtensions: ["pdf", "jpg", "jpeg", "png"],
maxSizeMb: 5,
order: 1,
},
{
id: "f2",
createdAt: "",
updatedAt: "",
deletedAt: null,
settingId: "booking-compliance",
fileKey: "business_license",
fileLabel: "Business / Investment License",
helpText:
"Current business or investment license issued by the relevant government authority.",
isRequired: true,
isMultiple: false,
maxFiles: 1,
allowedExtensions: ["pdf", "jpg", "jpeg", "png"],
maxSizeMb: 5,
order: 2,
},
{
id: "f3",
createdAt: "",
updatedAt: "",
deletedAt: null,
settingId: "booking-compliance",
fileKey: "business_registration",
fileLabel: "Business Registration Certificate",
helpText: "Certificate of registration from the relevant authority.",
isRequired: true,
isMultiple: false,
maxFiles: 1,
allowedExtensions: ["pdf", "jpg", "jpeg", "png"],
maxSizeMb: 5,
order: 3,
},
{
id: "f4",
createdAt: "",
updatedAt: "",
deletedAt: null,
settingId: "booking-compliance",
fileKey: "national_id",
fileLabel: "National ID / Passport",
helpText:
"Valid government-issued ID or passport of the authorized signatory.",
isRequired: true,
isMultiple: false,
maxFiles: 1,
allowedExtensions: ["pdf", "jpg", "jpeg", "png"],
maxSizeMb: 5,
order: 4,
},
{
id: "f5",
createdAt: "",
updatedAt: "",
deletedAt: null,
settingId: "booking-compliance",
fileKey: "power_of_attorney",
fileLabel: "Power of Attorney (PoA)",
helpText:
"Required only if a representative is signing on behalf of the company.",
isRequired: false,
isMultiple: false,
maxFiles: 1,
allowedExtensions: ["pdf", "jpg", "jpeg", "png"],
maxSizeMb: 5,
order: 5,
},
],
};
const requiredString = (message: string) =>
z.string().trim().min(1, { message });
const fileValueSchema = z.union([
z.custom<File>(),
z.array(z.custom<File>()),
z.null(),
]);
export const bookingFormSchema = z
.object({
contractType: z.enum(["new", "renewal", ""]),
previousContractRef: z.string(),
draftContractId: z.string(),
serviceType: z.enum(["rail", "rail_forwarding", ""]),
firstMileEnabled: z.boolean(),
pickUpAddress: z.string(),
lastMileEnabled: z.boolean(),
deliveryAddress: z.string(),
equipmentReturn: z.enum(["with_return", "without_return"]),
originYard: z.string(),
destinationYard: z.string(),
cargoType: z.enum(["container", "bulk", ""]),
cargoWeight: z.string(),
freightType: z.enum(["bulk", "break_bulk", ""]),
bulkCommodity: z.string(),
bulkCommodityOther: z.string(),
breakBulkType: z.string(),
breakBulkTypeOther: z.string(),
isHazardous: z.boolean(),
isRefrigerated: z.boolean(),
containerType: z.enum(["20ft", "40ft", ""]),
quantity: z.string(),
vgm: z.string(),
consolidationEnabled: z.boolean(),
documents: z.record(z.string(), fileValueSchema),
notes: z.string(),
termsAccepted: z.boolean(),
})
.superRefine((data, ctx) => {
if (!data.contractType) {
ctx.addIssue({
code: "custom",
path: ["contractType"],
message: "Select a contract type.",
});
}
if (data.contractType === "new" && !data.draftContractId.trim()) {
ctx.addIssue({
code: "custom",
path: ["draftContractId"],
message: "A draft contract ID is required.",
});
}
if (data.contractType === "renewal" && !data.previousContractRef.trim()) {
ctx.addIssue({
code: "custom",
path: ["previousContractRef"],
message: "Enter a previous contract reference.",
});
}
if (!data.serviceType) {
ctx.addIssue({
code: "custom",
path: ["serviceType"],
message: "Select a service type.",
});
}
if (data.firstMileEnabled && !data.pickUpAddress.trim()) {
ctx.addIssue({
code: "custom",
path: ["pickUpAddress"],
message: "Enter the pick-up address.",
});
}
if (data.lastMileEnabled && !data.deliveryAddress.trim()) {
ctx.addIssue({
code: "custom",
path: ["deliveryAddress"],
message: "Enter the delivery address.",
});
}
if (!data.originYard) {
ctx.addIssue({
code: "custom",
path: ["originYard"],
message: "Select an origin yard.",
});
}
if (!data.destinationYard) {
ctx.addIssue({
code: "custom",
path: ["destinationYard"],
message: "Select a destination yard.",
});
}
if (
data.originYard &&
data.destinationYard &&
data.originYard === data.destinationYard
) {
ctx.addIssue({
code: "custom",
path: ["destinationYard"],
message: "Destination must be different from origin.",
});
}
if (!data.cargoType) {
ctx.addIssue({
code: "custom",
path: ["cargoType"],
message: "Select a cargo type.",
});
}
if (data.cargoType === "bulk") {
if (!data.freightType) {
ctx.addIssue({
code: "custom",
path: ["freightType"],
message: "Select a freight type.",
});
}
if (data.freightType === "bulk") {
if (!data.bulkCommodity) {
ctx.addIssue({
code: "custom",
path: ["bulkCommodity"],
message: "Select a commodity.",
});
}
if (
data.bulkCommodity === "Others" &&
!data.bulkCommodityOther.trim()
) {
ctx.addIssue({
code: "custom",
path: ["bulkCommodityOther"],
message: "Specify the commodity.",
});
}
}
if (data.freightType === "break_bulk") {
if (!data.breakBulkType) {
ctx.addIssue({
code: "custom",
path: ["breakBulkType"],
message: "Select a break-bulk type.",
});
}
if (
data.breakBulkType === "Others" &&
!data.breakBulkTypeOther.trim()
) {
ctx.addIssue({
code: "custom",
path: ["breakBulkTypeOther"],
message: "Specify the break-bulk type.",
});
}
}
const cargoWeight = Number(data.cargoWeight);
if (!data.cargoWeight || Number.isNaN(cargoWeight) || cargoWeight <= 0) {
ctx.addIssue({
code: "custom",
path: ["cargoWeight"],
message: "Enter a cargo weight greater than 0.",
});
}
}
if (data.cargoType === "container") {
if (!data.containerType) {
ctx.addIssue({
code: "custom",
path: ["containerType"],
message: "Select a container type.",
});
}
const quantity = Number(data.quantity);
if (!data.quantity || !Number.isInteger(quantity) || quantity < 1) {
ctx.addIssue({
code: "custom",
path: ["quantity"],
message: "Enter at least 1 container.",
});
}
const vgm = Number(data.vgm);
if (!data.vgm || Number.isNaN(vgm) || vgm <= 0) {
ctx.addIssue({
code: "custom",
path: ["vgm"],
message: "Enter VGM greater than 0.",
});
}
}
for (const key of REQUIRED_DOC_KEYS) {
const value = data.documents[key];
const hasFile = Array.isArray(value) ? value.length > 0 : Boolean(value);
if (!hasFile) {
ctx.addIssue({
code: "custom",
path: ["documents", key],
message: "Upload this required document.",
});
}
}
if (!data.termsAccepted) {
ctx.addIssue({
code: "custom",
path: ["termsAccepted"],
message: "Accept the freight contract terms to submit.",
});
}
});
export type BookingFormValues = z.infer<typeof bookingFormSchema>;
export const initialBookingFormValues: BookingFormValues = {
contractType: "",
previousContractRef: "",
draftContractId: "",
serviceType: "",
firstMileEnabled: false,
pickUpAddress: "",
lastMileEnabled: false,
deliveryAddress: "",
equipmentReturn: "with_return",
originYard: "",
destinationYard: "",
cargoType: "",
cargoWeight: "",
freightType: "",
bulkCommodity: "",
bulkCommodityOther: "",
breakBulkType: "",
breakBulkTypeOther: "",
isHazardous: false,
isRefrigerated: false,
containerType: "",
quantity: "1",
vgm: "",
consolidationEnabled: false,
documents: {},
notes: "",
termsAccepted: false,
};
export const stepFields: Record<number, Array<keyof BookingFormValues>> = {
1: ["contractType", "previousContractRef", "draftContractId"],
2: ["serviceType"],
3: [
"firstMileEnabled",
"pickUpAddress",
"lastMileEnabled",
"deliveryAddress",
"equipmentReturn",
],
4: ["originYard", "destinationYard", "isHazardous", "isRefrigerated"],
5: [
"cargoType",
"cargoWeight",
"freightType",
"bulkCommodity",
"bulkCommodityOther",
"breakBulkType",
"breakBulkTypeOther",
"containerType",
"quantity",
"vgm",
],
6: ["consolidationEnabled"],
7: ["documents"],
8: ["notes", "termsAccepted"],
};
export type RouteDirection = "import" | "export" | "domestic" | null;
export interface WagonCalcResult {
totalWagons: number;
hasOddUnit: boolean;
sharedWagons: number;
}
export function genContractId(): string {
const yr = new Date().getFullYear();
const n = Math.floor(10000 + Math.random() * 90000);
return `EDR-DRAFT-${yr}-${n}`;
}
export function getRouteDirection(
origin: string,
dest: string,
): RouteDirection {
if (!origin || !dest) return null;
const oEth = ETHIOPIA_STATIONS.has(origin);
const dEth = ETHIOPIA_STATIONS.has(dest);
if (oEth && !dEth) return "export";
if (!oEth && dEth) return "import";
if (oEth && dEth) return "domestic";
return null;
}
export function calcWagons(
type: BookingFormValues["containerType"],
qty: number,
): WagonCalcResult {
if (type === "40ft") {
return { totalWagons: qty, hasOddUnit: false, sharedWagons: qty };
}
const pairs = Math.floor(qty / 2);
const odd = qty % 2;
return { totalWagons: pairs + odd, hasOddUnit: odd > 0, sharedWagons: pairs };
}

View File

@@ -0,0 +1,157 @@
import type { ReactNode } from "react";
import type {
ControllerRenderProps,
FieldError as RhfFieldError,
} from "react-hook-form";
import {
AlertTriangle,
Check,
CheckCircle2,
Info,
XCircle,
} from "lucide-react";
import {
Field,
FieldDescription,
FieldError,
FieldLabel,
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@edr/ui-common";
import type { BookingFormValues } from "./schema";
import { cn } from "@/lib/utils";
export function OptionCard({
selected,
onClick,
disabled,
children,
}: {
selected: boolean;
onClick?: () => void;
disabled?: boolean;
children: ReactNode;
}) {
return (
<button
type="button"
onClick={onClick}
disabled={disabled}
className={`relative w-full rounded-xl border-2 p-4 text-left transition ${disabled
? "cursor-not-allowed border-border bg-muted opacity-60"
: selected
? "border-primary bg-primary/5"
: "border-border bg-card hover:border-primary/40"
}`}
>
{selected && !disabled && (
<span className="absolute right-3 top-3 flex h-5 w-5 items-center justify-center rounded-full bg-primary">
<Check className="h-3 w-3 text-primary-foreground" />
</span>
)}
{children}
</button>
);
}
export function AlertBox({
tone,
children,
}: {
tone: "warning" | "error" | "success" | "info";
children: ReactNode;
}) {
const styles = {
warning: "bg-amber-50 border-amber-200 text-amber-800",
error: "bg-red-50 border-red-200 text-red-800",
success: "bg-emerald-50 border-emerald-200 text-emerald-800",
info: "bg-sky-50 border-sky-200 text-sky-800",
};
const icons = {
warning: <AlertTriangle className="h-4 w-4 shrink-0 text-amber-500" />,
error: <XCircle className="h-4 w-4 shrink-0 text-red-500" />,
success: <CheckCircle2 className="h-4 w-4 shrink-0 text-emerald-600" />,
info: <Info className="h-4 w-4 shrink-0 text-sky-500" />,
};
return (
<div
className={`flex items-start gap-3 rounded-xl border p-3 text-sm ${styles[tone]}`}
>
{icons[tone]}
<div>{children}</div>
</div>
);
}
export function StepLabel({ children }: { children: ReactNode }) {
return (
<p className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
{children}
</p>
);
}
export function StepHeader({
title,
description,
}: {
title: string;
description: string;
}) {
return (
<div>
<h2 className="text-xl font-bold tracking-tight">{title}</h2>
<p className="mt-1 text-sm text-muted-foreground">{description}</p>
</div>
);
}
export function SelectField({
field,
error,
label,
placeholder,
children,
}: {
field: ControllerRenderProps<BookingFormValues>;
error?: RhfFieldError;
label: string;
placeholder: string;
children: ReactNode;
}) {
return (
<Field data-invalid={Boolean(error)}>
<FieldLabel>{label}</FieldLabel>
<Select value={String(field.value)} onValueChange={field.onChange}>
<SelectTrigger
className={cn("w-full ", error ? "border-destructive!" : "")}
aria-invalid={Boolean(error)}
>
<SelectValue placeholder={placeholder} />
</SelectTrigger>
<SelectContent>{children}</SelectContent>
</Select>
<FieldError errors={[error]} />
</Field>
);
}
export function SelectOptions({ options }: { options: readonly string[] }) {
return (
<>
{options.map((option) => (
<SelectItem key={option} value={option}>
{option}
</SelectItem>
))}
</>
);
}
export function FormFieldDescription({ children }: { children: ReactNode }) {
return <FieldDescription>{children}</FieldDescription>;
}

File diff suppressed because it is too large Load Diff