Merge pull request #54 from Tria-plc/freight/feature/ui-sync

onboarding and bookin ui page
This commit is contained in:
yaschalew10
2026-05-29 16:40:26 +03:00
committed by GitHub
13 changed files with 761 additions and 716 deletions

View File

@@ -20,9 +20,11 @@ import {
const userSchema = z.object({
email: z.string().email("Invalid email address"),
username: z.string().min(3, "Username must be at least 3 characters"),
countryCode: z.string().min(1, "Country code is required"),
phone: z.string().min(9, "Phone number is too short").max(9, "Phone number is too long"),
phone: z
.string()
.min(9, "Phone number is too short")
.max(9, "Phone number is too long"),
userType: z.string(),
name: z.object({
en: z.string().min(2, "Name is required"),
@@ -46,7 +48,6 @@ export default function SignupPage() {
resolver: zodResolver(userSchema),
defaultValues: {
email: "",
username: "",
countryCode: "+251",
phone: "",
userType: userType.individual,
@@ -58,10 +59,12 @@ export default function SignupPage() {
setError(null);
setLoading(true);
try {
const normalizedPhone = data.phone.startsWith("0") ? data.phone.slice(1) : data.phone;
const normalizedPhone = data.phone.startsWith("0")
? data.phone.slice(1)
: data.phone;
const payload: SignupPayload = {
email: data.email,
username: data.username,
username: data.email,
phoneNumber: `${data.countryCode}${normalizedPhone}`,
userType: data.userType,
name: { en: data.name.en, am: data.name.am ?? "" },
@@ -92,7 +95,12 @@ export default function SignupPage() {
"Enterprise-grade operations",
"Multi-corridor freight monitoring",
],
stats: { label: "Active Corridors", value: "24+", footer: "Operational", progress: "w-[95%]" },
stats: {
label: "Active Corridors",
value: "24+",
footer: "Operational",
progress: "w-[95%]",
},
}}
>
<div className="mb-6">
@@ -125,31 +133,17 @@ export default function SignupPage() {
<FieldError errors={[errors.name?.en]} />
</Field>
<div className="grid grid-cols-2 gap-4">
<Field data-invalid={Boolean(errors.username)}>
<FieldLabel>Username</FieldLabel>
<Input
type="text"
placeholder="john_doe"
disabled={loading}
aria-invalid={Boolean(errors.username)}
{...register("username")}
/>
<FieldError errors={[errors.username]} />
</Field>
<Field data-invalid={Boolean(errors.email)}>
<FieldLabel>Email Address</FieldLabel>
<Input
type="email"
placeholder="john@example.com"
disabled={loading}
aria-invalid={Boolean(errors.email)}
{...register("email")}
/>
<FieldError errors={[errors.email]} />
</Field>
</div>
<Field data-invalid={Boolean(errors.email)}>
<FieldLabel>Email Address</FieldLabel>
<Input
type="email"
placeholder="john@example.com"
disabled={loading}
aria-invalid={Boolean(errors.email)}
{...register("email")}
/>
<FieldError errors={[errors.email]} />
</Field>
<PhoneInput
disabled={loading}
@@ -160,12 +154,7 @@ export default function SignupPage() {
/>
</FieldGroup>
<Button
type="submit"
disabled={loading}
size="lg"
className="w-full"
>
<Button type="submit" disabled={loading} size="lg" className="w-full">
{loading ? (
<>
<Loader2 className="animate-spin" data-icon="inline-start" />

View File

@@ -1,15 +1,14 @@
import { useEffect, useMemo, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useMemo, useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { useNavigate } from "react-router-dom";
import { CheckCircle2, ChevronLeft, ChevronRight } from "lucide-react";
import { Check, CheckCircle2, ChevronLeft, ChevronRight } from "lucide-react";
import { Button } from "@edr/ui-common";
import Breadcrumbs from "@/components/Breadcrumbs";
import { api } from "@/services/api";
import type { CreateBookingPayload } from "@/services/bookings.service";
import {
MOCK_VALID_CONTRACTS,
STEPS,
bookingFormSchema,
calcWagons,
@@ -22,11 +21,8 @@ import { StepIndicator } from "./new-booking-form/StepIndicator";
import {
Step1ContractType,
Step2ServiceType,
Step3FirstLastMile,
Step4Route,
Step5CargoDetails,
Step6WagonAllocation,
Step7Documents,
Step8Review,
} from "./new-booking-form/steps";
import useAuth from "@/hooks/useAuth";
@@ -35,8 +31,6 @@ export default function NewBookingPage() {
const navigate = useNavigate();
const queryClient = useQueryClient();
const [step, setStep] = useState(1);
const [renewalValidating, setRenewalValidating] = useState(false);
const [renewalValid, setRenewalValid] = useState<boolean | null>(null);
const { customer } = useAuth();
const createMutation = useMutation({
mutationFn: (payload: CreateBookingPayload) =>
@@ -56,7 +50,6 @@ export default function NewBookingPage() {
const originYard = form.watch("originYard");
const destinationYard = form.watch("destinationYard");
const containers = form.watch("containers");
const previousContractRef = form.watch("previousContractRef");
const direction = useMemo(
() => getRouteDirection(originYard, destinationYard),
@@ -68,63 +61,18 @@ export default function NewBookingPage() {
return calcWagons(containers);
}, [containers]);
useEffect(() => {
setRenewalValid(null);
}, [previousContractRef]);
function validateRenewal() {
const previousContractRef = form.getValues("previousContractRef").trim();
if (!previousContractRef) {
form.setError("previousContractRef", {
type: "manual",
message: "Enter a previous contract reference.",
});
return;
}
setRenewalValidating(true);
setRenewalValid(null);
setTimeout(() => {
const valid = MOCK_VALID_CONTRACTS.includes(
previousContractRef.toUpperCase(),
);
setRenewalValidating(false);
setRenewalValid(valid);
if (!valid) {
form.setError("previousContractRef", {
type: "manual",
message: "Contract Reference Number not found or unauthorized.",
});
} else {
form.clearErrors("previousContractRef");
}
}, 1200);
}
async function handleContinue() {
const valid = await form.trigger(stepFields[step], { shouldFocus: true });
if (!valid) return;
if (step === 1 && form.getValues("contractType") === "renewal") {
if (renewalValid !== true) {
form.setError("previousContractRef", {
type: "manual",
message:
"Validate the previous contract reference before continuing.",
});
return;
}
}
setStep((currentStep) => Math.min(STEPS.length, currentStep + 1));
}
const handleSubmit = form.handleSubmit((data) => {
if (data.contractType === "renewal" && renewalValid !== true) {
if (data.contractType === "renewal" && !data.previousContractRef) {
form.setError("previousContractRef", {
type: "manual",
message: "Validate the previous contract reference before submitting.",
message: "Select a previous contract reference.",
});
setStep(1);
return;
@@ -149,19 +97,22 @@ export default function NewBookingPage() {
data.contractType.toUpperCase() as CreateBookingPayload["contractType"],
previousContractId: data.previousContractRef || undefined,
serviceType:
data.serviceType === "rail" ? "RAIL_ONLY" : "RAIL_AND_FORWARDING",
firstMileEnabled: data.firstMileEnabled,
firstMilePickupAddress: data.firstMileEnabled
? data.pickUpAddress
: undefined,
lastMileEnabled: data.lastMileEnabled,
lastMileDeliveryAddress: data.lastMileEnabled
? data.deliveryAddress
: undefined,
equipmentReturn:
data.equipmentReturn === "with_return"
? ("WITH_RETURN" as const)
: ("WITHOUT_RETURN" as const),
data.service.serviceType === "rail"
? "RAIL_ONLY"
: "RAIL_AND_FORWARDING",
...(data.service.serviceType === "rail"
? {}
: {
firstMileEnabled: data.firstMile.enabled,
firstMilePickupAddress: data.firstMile.pickUpAddress ?? undefined,
lastMileEnabled: data.lastMile.enabled,
lastMileDeliveryAddress: data.lastMile.deliveryAddress ?? undefined,
equipmentReturn:
data.equipmentReturn === "with_return"
? ("WITH_RETURN" as const)
: ("WITHOUT_RETURN" as const),
customsClearingEnabled: data.customsClearingEnabled,
}),
originStation: data.originYard,
destinationStation: data.destinationYard,
cargoTotalWeightVgm: totalWeight,
@@ -220,43 +171,22 @@ export default function NewBookingPage() {
className="flex flex-col"
onSubmit={handleSubmit}
>
<div className="sticky top-0 z-20 border-b border-border bg-background">
<div className="mx-auto max-w-4xl space-y-3 px-6 py-3">
<Breadcrumbs
items={[
{ label: "Bookings", href: "/bookings" },
{ label: "New Contract Request" },
]}
/>
<div className="sticky top-0 z-20">
<div className="mx-auto max-w-4xl space-y-3 px-6 pt-4">
<StepIndicator step={step} />
</div>
</div>
<div className="flex-1">
<div className="mx-auto max-w-4xl px-6 py-8">
{step === 1 && (
<Step1ContractType
form={form}
renewalValid={renewalValid}
renewalValidating={renewalValidating}
onValidate={validateRenewal}
/>
)}
{step === 1 && <Step1ContractType form={form} />}
{step === 2 && <Step2ServiceType form={form} />}
{step === 3 && <Step3FirstLastMile form={form} />}
{step === 4 && <Step4Route form={form} />}
{step === 5 && (
{step === 3 && <Step4Route form={form} />}
{step === 4 && (
<Step5CargoDetails form={form} direction={direction} />
)}
{step === 6 && <Step6WagonAllocation form={form} wagons={wagons} />}
{step === 7 && <Step7Documents form={form} />}
{step === 8 && (
<Step8Review
form={form}
setStep={setStep}
wagons={wagons}
direction={direction}
/>
{step === 5 && (
<Step8Review form={form} setStep={setStep} direction={direction} />
)}
</div>
</div>
@@ -277,11 +207,11 @@ export default function NewBookingPage() {
{step < STEPS.length ? (
<Button type="button" onClick={handleContinue}>
Continue
<ChevronRight className="ml-1 h-4 w-4" />
<ChevronRight />
</Button>
) : (
<Button type="submit" form="new-booking-form">
<CheckCircle2 className="mr-2 h-4 w-4" />
<Check />
Submit Contract Request
</Button>
)}

View File

@@ -1,3 +1,4 @@
import { DeepPartial, Path } from "react-hook-form";
import * as z from "zod";
export const STATIONS = [
@@ -42,123 +43,69 @@ export const MOCK_VALID_CONTRACTS = [
"EDR-2022-55442",
];
export const REQUIRED_DOC_KEYS = [
"tin_certificate",
"business_license",
"business_registration",
// "national_id",
export const CONTAINER_TYPES = [
"Dry Container",
"High Cubic",
"Reefer Container",
"Open Top",
"Flat Rack",
"Tank Container",
"Open Side",
] as const;
export const SHIPPING_LINES = [
"MSC",
"CMA CGM",
"Evergreen",
"COSCO",
"Hapag-Lloyd",
"ONE",
"Yang Ming",
"ZIM",
"Messina Line",
"Safmarine",
"Wan Hai",
"Ethiopian Shipping Lines (ESLSE)",
] 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" },
{ id: 2, label: "Service Type & Mile", short: "Service" },
{ id: 3, label: "Route", short: "Route" },
{ id: 4, label: "Cargo Details", short: "Cargo" },
{ id: 5, 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: "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 fileValueSchema = z.union([
z.custom<File>(),
z.array(z.custom<File>()),
z.null(),
]);
export const bookingFormSchema = z
.object({
contractType: z.enum(["new", "renewal"], "Select a contract type."),
previousContractRef: z.string(),
serviceType: z.enum(["rail", "rail_forwarding"], "Select a service type."),
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(),
firstMile: z
.object({
enabled: z.boolean().default(false),
pickUpAddress: z.string(),
})
.refine((data) => !(data.enabled && !data.pickUpAddress.trim()), {
message: "Enter the pick-up address.",
path: ["pickUpAddress"],
}),
lastMile: z
.object({
enabled: z.boolean().default(false),
deliveryAddress: z.string(),
})
.refine((data) => !(data.enabled && !data.deliveryAddress.trim()), {
message: "Enter the delivery address.",
path: ["deliveryAddress"],
}),
equipmentReturn: z
.enum(["with_return", "without_return"])
.default("with_return"),
customsClearingEnabled: z.boolean().default(false),
originYard: z.string().min(1, "Select an origin yard."),
destinationYard: z.string().min(1, "Select a destination yard."),
shippingLine: z.string(),
cargoType: z.enum(["container", "bulk"], "Select a cargo type."),
cargoWeight: z.string(),
freightType: z.enum(["bulk", "break_bulk"]).optional(),
@@ -171,142 +118,116 @@ export const bookingFormSchema = z
containers: z.array(
z.object({
type: z.enum(["20ft", "40ft"]),
containerType: z.string().min(1, "Select a container type."),
qty: z
.string()
.refine((q) => q.length !== 0, "Quantity is required.")
.refine((q) => !isNaN(+q), "Enter a valid Number")
.refine((qty) => Number(qty) >= 1, "Must be greater than 0"),
vgm: z
.string()
.refine((vgm) => vgm.length !== 0, "VGM is required.")
.refine((vgm) => !isNaN(+vgm), "Enter a valid Number")
.refine((vgm) => Number(vgm) >= 0, "Must be greater than 0"),
}),
),
consolidationEnabled: z.boolean(),
documents: z.record(z.string(), fileValueSchema),
notes: z.string(),
termsAccepted: z.boolean(),
})
.superRefine((data, ctx) => {
if (data.contractType === "renewal" && !data.previousContractRef.trim()) {
ctx.addIssue({
code: "custom",
path: ["previousContractRef"],
message: "Enter a previous contract reference.",
});
}
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 === "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.",
});
}
}
.refine(
(data) =>
!(data.contractType === "renewal" && !data.previousContractRef.trim()),
{
message: "Enter a previous contract reference.",
path: ["previousContractRef"],
},
)
.refine((data) => data.originYard !== "", {
message: "Select an origin yard.",
path: ["originYard"],
})
.refine((data) => data.destinationYard !== "", {
message: "Select a destination yard.",
path: ["destinationYard"],
})
.refine(
(data) =>
!(
data.originYard &&
data.destinationYard &&
data.originYard === data.destinationYard
),
{
message: "Destination must be different from origin.",
path: ["destinationYard"],
},
)
.refine((data) => !(data.cargoType === "bulk" && !data.freightType), {
message: "Select a freight type.",
path: ["freightType"],
})
.refine(
(data) =>
!(
data.cargoType === "bulk" &&
data.freightType === "bulk" &&
!data.bulkCommodity
),
{ message: "Select a commodity.", path: ["bulkCommodity"] },
)
.refine(
(data) =>
!(
data.cargoType === "bulk" &&
data.freightType === "bulk" &&
data.bulkCommodity === "Others" &&
!data.bulkCommodityOther.trim()
),
{ message: "Specify the commodity.", path: ["bulkCommodityOther"] },
)
.refine(
(data) =>
!(
data.cargoType === "bulk" &&
data.freightType === "break_bulk" &&
!data.breakBulkType
),
{ message: "Select a break-bulk type.", path: ["breakBulkType"] },
)
.refine(
(data) =>
!(
data.cargoType === "bulk" &&
data.freightType === "break_bulk" &&
data.breakBulkType === "Others" &&
!data.breakBulkTypeOther.trim()
),
{
message: "Specify the break-bulk type.",
path: ["breakBulkTypeOther"],
},
)
.refine(
(data) => {
if (data.cargoType !== "bulk") return true;
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.",
});
}
}
return (
!!data.cargoWeight && !Number.isNaN(cargoWeight) && cargoWeight > 0
);
},
{ message: "Enter a cargo weight greater than 0.", path: ["cargoWeight"] },
)
.refine(
(data) => !(data.cargoType === "container" && data.containers.length === 0),
{ message: "Add at least one container.", path: ["containers"] },
)
.refine((data) => data.termsAccepted, {
message: "Accept the freight contract terms to submit.",
path: ["termsAccepted"],
})
.superRefine((data, ctx) => {
if (data.cargoType === "container") {
if (data.containers.length === 0) {
ctx.addIssue({
code: "custom",
path: ["containers"],
message: "Add at least one container.",
});
}
data.containers.forEach((c, i) => {
if (!c.qty || +c.qty < 1) {
ctx.addIssue({
@@ -325,39 +246,26 @@ export const bookingFormSchema = z
}
});
}
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: Partial<BookingFormValues> = {
export const initialBookingFormValues: DeepPartial<BookingFormValues> = {
previousContractRef: "",
firstMileEnabled: false,
pickUpAddress: "",
lastMileEnabled: false,
deliveryAddress: "",
firstMile: {
enabled: false,
pickUpAddress: "",
},
lastMile: {
enabled: false,
deliveryAddress: "",
},
equipmentReturn: "with_return",
customsClearingEnabled: false,
originYard: "",
destinationYard: "",
shippingLine: "",
cargoWeight: "",
bulkCommodity: "",
bulkCommodityOther: "",
@@ -365,25 +273,29 @@ export const initialBookingFormValues: Partial<BookingFormValues> = {
breakBulkTypeOther: "",
isHazardous: false,
isRefrigerated: false,
containers: [{ type: "20ft", qty: "1", vgm: "" }],
containers: [{ type: "20ft", containerType: "", qty: "1", vgm: "" }],
consolidationEnabled: false,
documents: {},
notes: "",
termsAccepted: false,
};
export const stepFields: Record<number, Array<keyof BookingFormValues>> = {
export const stepFields: Record<number, Array<Path<BookingFormValues>>> = {
1: ["contractType", "previousContractRef"],
2: ["serviceType"],
3: [
"firstMileEnabled",
"pickUpAddress",
"lastMileEnabled",
"deliveryAddress",
2: [
"serviceType",
"firstMile",
"lastMile",
"equipmentReturn",
"customsClearingEnabled",
],
4: ["originYard", "destinationYard", "isHazardous", "isRefrigerated"],
5: [
3: [
"originYard",
"destinationYard",
"isHazardous",
"isRefrigerated",
"shippingLine",
],
4: [
"cargoType",
"cargoWeight",
"freightType",
@@ -392,16 +304,16 @@ export const stepFields: Record<number, Array<keyof BookingFormValues>> = {
"breakBulkType",
"breakBulkTypeOther",
"containers",
"consolidationEnabled",
],
6: ["consolidationEnabled"],
7: ["documents"],
8: ["notes", "termsAccepted"],
5: ["notes", "termsAccepted"],
};
export type RouteDirection = "import" | "export" | "domestic" | null;
export interface ContainerConfig {
type: "20ft" | "40ft";
containerType: string;
qty: string;
vgm: string;
}

View File

@@ -22,18 +22,8 @@ import {
SelectValue,
} from "@edr/ui-common";
import type { BookingFormValues } from "./schema";
import { REQUIRED_DOC_KEYS } from "./schema";
import { cn } from "@/lib/utils";
export function getUploadedRequiredCount(
documents: BookingFormValues["documents"],
) {
return REQUIRED_DOC_KEYS.filter((key) => {
const file = documents[key];
return Array.isArray(file) ? file.length > 0 : Boolean(file);
}).length;
}
export function OptionFieldError({ error }: { error?: { message?: string } }) {
return <FieldError errors={[error]} />;
}
@@ -160,6 +150,8 @@ export function SelectField({
);
}
export { SelectItem };
export function SelectOptions({ options }: { options: readonly string[] }) {
return (
<>

View File

@@ -1,22 +1,19 @@
import { Controller, type UseFormReturn } from "react-hook-form";
import { FileText, Loader2, RefreshCw } from "lucide-react";
import { Button, Field, FieldLabel, Input } from "@edr/ui-common";
import { type BookingFormValues } from "./schema";
import { AlertBox, OptionCard, OptionFieldError, StepHeader } from "./shared";
import { FileText, RefreshCw } from "lucide-react";
import { Field } from "@edr/ui-common";
import { MOCK_VALID_CONTRACTS, type BookingFormValues } from "./schema";
import {
AlertBox,
OptionCard,
OptionFieldError,
SelectField,
SelectItem,
StepHeader,
} from "./shared";
type BookingForm = UseFormReturn<BookingFormValues>;
export function Step1ContractType({
form,
renewalValid,
renewalValidating,
onValidate,
}: {
form: BookingForm;
renewalValid: boolean | null;
renewalValidating: boolean;
onValidate: () => void;
}) {
export function Step1ContractType({ form }: { form: BookingForm }) {
const contractType = form.watch("contractType");
const previousContractRef = form.watch("previousContractRef");
@@ -38,6 +35,7 @@ export function Step1ContractType({
onClick={() => {
field.onChange("new");
form.clearErrors(["contractType", "previousContractRef"]);
form.setValue("previousContractRef", "");
}}
>
<div className="mb-2 flex h-9 w-9 items-center justify-center rounded-lg bg-primary/10">
@@ -45,7 +43,7 @@ export function Step1ContractType({
</div>
<p className="font-semibold">New Contract</p>
<p className="mt-0.5 text-xs text-muted-foreground">
Blank contract form. A draft ID is auto-generated.
Create a new contract.
</p>
</OptionCard>
@@ -61,7 +59,7 @@ export function Step1ContractType({
</div>
<p className="font-semibold">Contract Renewal</p>
<p className="mt-0.5 text-xs text-muted-foreground">
Enter a previous reference to auto-populate historical
Select a previous reference to auto-populate historical
parameters.
</p>
</OptionCard>
@@ -77,46 +75,26 @@ export function Step1ContractType({
name="previousContractRef"
control={form.control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel htmlFor="previousContractRef">
Previous Contract Reference Number
</FieldLabel>
<div className="flex gap-2">
<Input
{...field}
id="previousContractRef"
aria-invalid={fieldState.invalid}
placeholder="e.g. EDR-2024-10001"
className="font-mono"
/>
<Button
type="button"
variant="outline"
onClick={onValidate}
disabled={!previousContractRef || renewalValidating}
>
{renewalValidating ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
"Validate"
)}
</Button>
</div>
</Field>
<SelectField
field={field}
error={fieldState.error}
label="Previous Contract Reference Number"
placeholder="Select a contract..."
>
{MOCK_VALID_CONTRACTS.map((ref) => (
<SelectItem key={ref} value={ref}>
{ref}
</SelectItem>
))}
</SelectField>
)}
/>
{renewalValid === true && (
{previousContractRef && (
<AlertBox tone="success">
<strong>Contract found.</strong> Company details, route, and wagon
preferences will be pre-filled.
</AlertBox>
)}
{renewalValid === false && (
<AlertBox tone="error">
Contract Reference Number not found or unauthorized. Try{" "}
<span className="font-mono">EDR-2024-10001</span>.
</AlertBox>
)}
</div>
)}
</div>

View File

@@ -1,6 +1,7 @@
import { useEffect, useRef } from "react";
import { Controller, type UseFormReturn } from "react-hook-form";
import { Package, Train } from "lucide-react";
import { Badge, Field, FieldError } from "@edr/ui-common";
import { FileText, Package, Train, Truck } from "lucide-react";
import { Badge, Field, FieldError, Input, Switch } from "@edr/ui-common";
import { type BookingFormValues } from "./schema";
import { OptionCard, OptionFieldError, StepHeader } from "./shared";
@@ -8,12 +9,67 @@ type BookingForm = UseFormReturn<BookingFormValues>;
export function Step2ServiceType({ form }: { form: BookingForm }) {
const serviceType = form.watch("serviceType");
const firstMileEnabled = form.watch("firstMile.enabled");
const lastMileEnabled = form.watch("lastMile.enabled");
const prevServiceType = useRef(serviceType);
useEffect(() => {
const prev = prevServiceType.current;
prevServiceType.current = serviceType;
if (!prev || prev === serviceType) return;
if (serviceType === "rail") {
form.setValue(
"firstMile",
{ enabled: false, pickUpAddress: "" },
{ shouldDirty: true, shouldValidate: true },
);
form.setValue(
"lastMile",
{ enabled: false, deliveryAddress: "" },
{ shouldDirty: true, shouldValidate: true },
);
form.setValue("equipmentReturn", "with_return", {
shouldDirty: true,
});
form.setValue("customsClearingEnabled", false, {
shouldDirty: true,
});
} else if (serviceType === "rail_forwarding") {
form.setValue(
"firstMile",
{
enabled: false,
pickUpAddress: "",
},
{
shouldDirty: false,
shouldValidate: false,
},
);
form.setValue(
"lastMile",
{
enabled: false,
deliveryAddress: "",
},
{
shouldDirty: false,
shouldValidate: false,
},
);
}
}, [serviceType, form]);
const showServiceSections = serviceType === "rail_forwarding";
return (
<div className="space-y-6">
<StepHeader
title="Service Type"
description="Select the service combination you require."
description="Select the service combination and configure trucking options."
/>
<Controller
@@ -46,9 +102,7 @@ export function Step2ServiceType({ form }: { form: BookingForm }) {
<div className="mb-2 flex h-9 w-9 items-center justify-center rounded-lg bg-primary/10">
<Package className="h-4 w-4 text-primary" />
</div>
<p className="font-semibold">
Rail Transport & Freight Forwarding
</p>
<p className="font-semibold">Logistics</p>
<p className="mt-0.5 text-xs text-muted-foreground">
Rail transport plus documentation, customs liaison, and a
dedicated coordinator.
@@ -63,10 +117,172 @@ export function Step2ServiceType({ form }: { form: BookingForm }) {
)}
/>
<p className="text-xs text-muted-foreground">
Customs and Clearance Service cannot be selected independently. It must
be bundled with a Rail Transport service.
</p>
{showServiceSections && (
<div className="divide-y divide-border rounded-xl border border-border">
<div className="p-4">
<Controller
name="firstMile.enabled"
control={form.control}
render={({ field }) => (
<div className="flex items-start justify-between gap-4">
<div className="flex items-start gap-3">
<Truck className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
<div>
<p className="text-sm font-medium">
First Mile - Pick-up
</p>
<p className="mt-0.5 text-xs text-muted-foreground">
Truck pick-up from your premises (Door to Port) to the
origin rail yard.
</p>
</div>
</div>
<Switch
checked={field.value}
onCheckedChange={(value) => {
field.onChange(value);
if (!value) {
form.setValue("firstMile.pickUpAddress", "", {
shouldDirty: true,
shouldValidate: true,
});
}
}}
/>
</div>
)}
/>
{firstMileEnabled && (
<Controller
name="firstMile.pickUpAddress"
control={form.control}
render={({ field, fieldState }) => (
<Field className="mt-3" data-invalid={fieldState.invalid}>
<Input
{...field}
aria-invalid={fieldState.invalid}
placeholder="Pick-up address *"
/>
<FieldError errors={[fieldState.error]} />
</Field>
)}
/>
)}
</div>
<div className="p-4">
<Controller
name="lastMile.enabled"
control={form.control}
render={({ field }) => (
<div className="flex items-start justify-between gap-4">
<div className="flex items-start gap-3">
<Truck className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
<div>
<p className="text-sm font-medium">
Last Mile - Delivery
</p>
<p className="mt-0.5 text-xs text-muted-foreground">
Truck delivery from the destination rail yard to the
final address (Port to Door).
</p>
</div>
</div>
<Switch
checked={field.value}
onCheckedChange={(value) => {
field.onChange(value);
if (!value) {
form.setValue("lastMile.deliveryAddress", "", {
shouldDirty: true,
shouldValidate: true,
});
form.setValue("equipmentReturn", "with_return", {
shouldDirty: true,
});
}
}}
/>
</div>
)}
/>
{lastMileEnabled && (
<Controller
name="lastMile.deliveryAddress"
control={form.control}
render={({ field, fieldState }) => (
<Field className="mt-3" data-invalid={fieldState.invalid}>
<Input
{...field}
aria-invalid={fieldState.invalid}
placeholder="Delivery address *"
/>
<FieldError errors={[fieldState.error]} />
</Field>
)}
/>
)}
</div>
{lastMileEnabled && (
<div className="p-4">
<Controller
name="equipmentReturn"
control={form.control}
render={({ field }) => (
<div className="flex items-start justify-between gap-4">
<div className="flex items-start gap-3">
<div>
<p className="text-sm font-medium">Equipment Return</p>
<p className="mt-0.5 text-xs text-muted-foreground">
{field.value === "with_return"
? "Container returned to EDR after unloading."
: "Container retained by the customer after delivery."}
</p>
</div>
</div>
<Switch
checked={field.value === "with_return"}
onCheckedChange={(value) => {
field.onChange(
value ? "with_return" : "without_return",
);
}}
/>
</div>
)}
/>
</div>
)}
<div className="p-4">
<Controller
name="customsClearingEnabled"
control={form.control}
render={({ field }) => (
<div className="flex items-start justify-between gap-4">
<div className="flex items-start gap-3">
<FileText className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
<div>
<p className="text-sm font-medium">
Customs Clearing Service
</p>
<p className="mt-0.5 text-xs text-muted-foreground">
EDR handles customs documentation and clearance on your
behalf.
</p>
</div>
</div>
<Switch
checked={field.value}
onCheckedChange={field.onChange}
/>
</div>
)}
/>
</div>
</div>
)}
</div>
);
}

View File

@@ -1,7 +1,7 @@
import { Controller, type UseFormReturn } from "react-hook-form";
import { Field, FieldError, Input, Switch } from "@edr/ui-common";
import { type BookingFormValues } from "./schema";
import { OptionCard, StepHeader } from "./shared";
import { StepHeader } from "./shared";
type BookingForm = UseFormReturn<BookingFormValues>;
@@ -27,7 +27,8 @@ export function Step3FirstLastMile({ form }: { form: BookingForm }) {
<div>
<p className="text-sm font-medium">First Mile - Pick-up</p>
<p className="mt-0.5 text-xs text-muted-foreground">
Truck pick-up from your premises to the origin rail yard.
Truck pick-up from your premises (Door to Port) to the
origin rail yard.
</p>
</div>
<Switch
@@ -73,7 +74,7 @@ export function Step3FirstLastMile({ form }: { form: BookingForm }) {
<p className="text-sm font-medium">Last Mile - Delivery</p>
<p className="mt-0.5 text-xs text-muted-foreground">
Truck delivery from the destination rail yard to the final
address.
address (Port to Door).
</p>
</div>
<Switch
@@ -107,40 +108,35 @@ export function Step3FirstLastMile({ form }: { form: BookingForm }) {
)}
/>
)}
</div>
<div className="p-4">
<p className="mb-3 text-sm font-medium">Equipment Return</p>
<p className="mb-3 text-xs text-muted-foreground">
Declare whether the container asset will be returned after
unloading.
</p>
<Controller
name="equipmentReturn"
control={form.control}
render={({ field }) => (
<div className="grid gap-2 sm:grid-cols-2">
<OptionCard
selected={equipmentReturn === "with_return"}
onClick={() => field.onChange("with_return")}
>
<p className="text-sm font-semibold">With Return</p>
<p className="mt-0.5 text-xs text-muted-foreground">
Container returned to EDR after unloading.
</p>
</OptionCard>
<OptionCard
selected={equipmentReturn === "without_return"}
onClick={() => field.onChange("without_return")}
>
<p className="text-sm font-semibold">Without Return</p>
<p className="mt-0.5 text-xs text-muted-foreground">
Container retained by the customer after delivery.
</p>
</OptionCard>
</div>
)}
/>
{lastMileEnabled && (
<div className="mt-4 border-t border-border pt-4">
<Controller
name="equipmentReturn"
control={form.control}
render={({ field }) => (
<div className="flex items-start justify-between gap-4">
<div>
<p className="text-sm font-medium">Equipment Return</p>
<p className="mt-0.5 text-xs text-muted-foreground">
{field.value === "with_return"
? "Container returned to EDR after unloading."
: "Container retained by the customer after delivery."}
</p>
</div>
<Switch
checked={field.value === "with_return"}
onCheckedChange={(value) => {
field.onChange(
value ? "with_return" : "without_return",
);
}}
/>
</div>
)}
/>
</div>
)}
</div>
</div>
</div>

View File

@@ -1,7 +1,12 @@
import { Controller, type UseFormReturn } from "react-hook-form";
import { Flame, MapPin, Snowflake } from "lucide-react";
import { Field, SelectItem, Separator, Switch } from "@edr/ui-common";
import { type BookingFormValues, getRouteDirection, STATIONS } from "./schema";
import {
SHIPPING_LINES,
type BookingFormValues,
getRouteDirection,
STATIONS,
} from "./schema";
import {
AlertBox,
SelectField,
@@ -11,6 +16,7 @@ import {
} from "./shared";
import { useDropdownSettingByCode } from "@/hooks/useDropdownSettings";
import { DropdownOption } from "@/types/dropdownSettings";
import { useEffect } from "react";
type BookingForm = UseFormReturn<BookingFormValues>;
@@ -39,6 +45,12 @@ export function Step4Route({ form }: { form: BookingForm }) {
};
const stationSelectDisabled = stationsLoading || stationOptions.length === 0;
useEffect(() => {
if (direction === "domestic") {
form.setValue("shippingLine", "", { shouldDirty: true });
}
}, [direction]);
return (
<div className="space-y-6">
<StepHeader
@@ -106,6 +118,22 @@ export function Step4Route({ form }: { form: BookingForm }) {
)}
</div>
{direction && direction != "domestic" && (
<Controller
name="shippingLine"
control={form.control}
render={({ field, fieldState }) => (
<SelectField
field={field}
error={fieldState.error}
label="Shipping Line"
placeholder="Select shipping line..."
>
<SelectOptions options={SHIPPING_LINES} />
</SelectField>
)}
/>
)}
<Separator />
<div className="space-y-0 divide-y divide-border">

View File

@@ -1,16 +1,11 @@
import { Controller, useFieldArray, type UseFormReturn } from "react-hook-form";
import { MapPin, Package, Plus, Trash2, Weight } from "lucide-react";
import {
Button,
Field,
FieldError,
FieldLabel,
Input,
Separator,
} from "@edr/ui-common";
import { Button, Field, FieldError, FieldLabel, Input } from "@edr/ui-common";
import {
BREAK_BULK_TYPES,
BULK_COMMODITIES,
CONTAINER_TYPES,
calcWagons,
type BookingFormValues,
type RouteDirection,
} from "./schema";
@@ -81,7 +76,6 @@ export function Step5CargoDetails({
form.setValue("freightType", undefined, {
shouldDirty: true,
});
form.setValue("cargoWeight", "", { shouldDirty: true });
}}
>
<div className="mb-2 flex h-9 w-9 items-center justify-center rounded-lg bg-primary/10">
@@ -96,11 +90,7 @@ export function Step5CargoDetails({
selected={cargoType === "bulk"}
onClick={() => {
field.onChange("bulk");
form.setValue(
"containers",
[{ type: "20ft", qty: "1", vgm: "0" }],
{ shouldDirty: true },
);
form.setValue("containers", [], { shouldDirty: true });
}}
>
<div className="mb-2 flex h-9 w-9 items-center justify-center rounded-lg bg-amber-100">
@@ -118,173 +108,162 @@ export function Step5CargoDetails({
/>
</div>
<div className="space-y-3">
<StepLabel>Weight</StepLabel>
<Controller
name="cargoWeight"
control={form.control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel htmlFor="cargoWeight">
Total Cargo Weight(Tons)*
</FieldLabel>
<div className="relative">
<Weight className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
{...field}
id="cargoWeight"
type="number"
aria-invalid={fieldState.invalid}
placeholder="0.00"
className="pl-9"
min="0"
step="0.01"
/>
</div>
<FieldError errors={[fieldState.error]} />
</Field>
)}
/>
</div>
{cargoType === "bulk" && (
<>
<Separator />
<div className="space-y-3">
<StepLabel>Freight Type *</StepLabel>
<Controller
name="freightType"
control={form.control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<div className="grid gap-3 sm:grid-cols-2">
<OptionCard
selected={freightType === "bulk"}
onClick={() => field.onChange("bulk")}
>
<p className="font-semibold">Bulk</p>
<p className="mt-0.5 text-xs text-muted-foreground">
Coffee, fertilizer, grain, ore, etc.
</p>
</OptionCard>
<OptionCard
selected={freightType === "break_bulk"}
onClick={() => field.onChange("break_bulk")}
>
<p className="font-semibold">Break-Bulk</p>
<p className="mt-0.5 text-xs text-muted-foreground">
Machinery, vehicles, project cargo, etc.
</p>
</OptionCard>
</div>
<FieldError errors={[fieldState.error]} />
</Field>
)}
/>
<div className="space-y-3">
<StepLabel>Freight Type *</StepLabel>
<Controller
name="freightType"
control={form.control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<div className="grid gap-3 sm:grid-cols-2">
<OptionCard
selected={freightType === "bulk"}
onClick={() => field.onChange("bulk")}
>
<p className="font-semibold">Bulk</p>
<p className="mt-0.5 text-xs text-muted-foreground">
Coffee, fertilizer, grain, ore, etc.
</p>
</OptionCard>
<OptionCard
selected={freightType === "break_bulk"}
onClick={() => field.onChange("break_bulk")}
>
<p className="font-semibold">Break-Bulk</p>
<p className="mt-0.5 text-xs text-muted-foreground">
Machinery, vehicles, project cargo, etc.
</p>
</OptionCard>
</div>
<FieldError errors={[fieldState.error]} />
</Field>
)}
/>
{freightType === "bulk" && (
<div className="space-y-2">
{freightType === "bulk" && (
<div className="space-y-2">
<Controller
name="bulkCommodity"
control={form.control}
render={({ field, fieldState }) => (
<SelectField
field={field}
error={fieldState.error}
label="Commodity *"
placeholder="Select commodity *"
>
<SelectOptions options={BULK_COMMODITIES} />
</SelectField>
)}
/>
{bulkCommodity === "Others" && (
<Controller
name="bulkCommodity"
name="bulkCommodityOther"
control={form.control}
render={({ field, fieldState }) => (
<SelectField
field={field}
error={fieldState.error}
label="Commodity *"
placeholder="Select commodity *"
>
<SelectOptions options={BULK_COMMODITIES} />
</SelectField>
<Field data-invalid={fieldState.invalid}>
<Input
{...field}
aria-invalid={fieldState.invalid}
placeholder="Specify commodity *"
/>
<FieldError errors={[fieldState.error]} />
</Field>
)}
/>
{bulkCommodity === "Others" && (
<Controller
name="bulkCommodityOther"
control={form.control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<Input
{...field}
aria-invalid={fieldState.invalid}
placeholder="Specify commodity *"
/>
<FieldError errors={[fieldState.error]} />
</Field>
)}
/>
)}
</div>
)}
)}
</div>
)}
{freightType === "break_bulk" && (
<div className="space-y-2">
{freightType === "break_bulk" && (
<div className="space-y-2">
<Controller
name="breakBulkType"
control={form.control}
render={({ field, fieldState }) => (
<SelectField
field={field}
error={fieldState.error}
label="Break-bulk type *"
placeholder="Select type *"
>
<SelectOptions options={BREAK_BULK_TYPES} />
</SelectField>
)}
/>
{breakBulkType === "Others" && (
<Controller
name="breakBulkType"
name="breakBulkTypeOther"
control={form.control}
render={({ field, fieldState }) => (
<SelectField
field={field}
error={fieldState.error}
label="Break-bulk type *"
placeholder="Select type *"
>
<SelectOptions options={BREAK_BULK_TYPES} />
</SelectField>
<Field data-invalid={fieldState.invalid}>
<Input
{...field}
aria-invalid={fieldState.invalid}
placeholder="Specify break-bulk type *"
/>
<FieldError errors={[fieldState.error]} />
</Field>
)}
/>
{breakBulkType === "Others" && (
<Controller
name="breakBulkTypeOther"
control={form.control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<Input
{...field}
aria-invalid={fieldState.invalid}
placeholder="Specify break-bulk type *"
/>
<FieldError errors={[fieldState.error]} />
</Field>
)}
/>
)}
</div>
)}
</div>
<Separator />
<div className="space-y-3">
<StepLabel>Weight</StepLabel>
<Controller
name="cargoWeight"
control={form.control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel htmlFor="cargoWeight">
Total Cargo Weight - VGM (Tons) *
</FieldLabel>
<div className="relative">
<Weight className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
{...field}
id="cargoWeight"
type="number"
aria-invalid={fieldState.invalid}
placeholder="0.00"
className="pl-9"
min="0"
step="0.01"
/>
</div>
<FieldError errors={[fieldState.error]} />
</Field>
)}
/>
</div>
</>
</div>
)}
</div>
)}
{cargoType === "container" && (
<>
<Separator />
<div className="space-y-4">
<div className="flex items-center justify-between">
<StepLabel>Container Configuration</StepLabel>
<StepLabel>Containers</StepLabel>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => append({ type: "20ft", qty: "1", vgm: "0" })}
onClick={() =>
append({
type: "20ft",
containerType: "",
qty: "1",
vgm: "",
})
}
>
<Plus className="mr-1 h-3.5 w-3.5" />
Add Container
</Button>
</div>
{direction && (
<p className="flex items-center gap-1.5 text-xs text-muted-foreground">
<MapPin className="h-3.5 w-3.5" />
Route detected as{" "}
<span className="font-medium capitalize text-foreground">
{direction}
</span>{" "}
workflow
</p>
)}
{fields.map((field, index) => {
const containerType = containers[index]?.type;
const vgm = containers[index]?.vgm ?? 0;
@@ -293,12 +272,9 @@ export function Step5CargoDetails({
return (
<div
key={field.id}
className="space-y-3 rounded-xl border border-border p-4"
className="rounded-xl flex flex-col border border-border p-3 gap-2"
>
<div className="flex items-center justify-between">
<p className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
Container #{index + 1}
</p>
{fields.length > 1 && (
<button
type="button"
@@ -315,7 +291,6 @@ export function Step5CargoDetails({
control={form.control}
render={({ field: typeField, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel>Container Type *</FieldLabel>
<div className="grid gap-2 sm:grid-cols-2">
{[
{
@@ -352,7 +327,7 @@ export function Step5CargoDetails({
)}
/>
<div className="grid gap-3 sm:grid-cols-2">
<div className="grid gap-3 sm:grid-cols-3">
<Controller
name={`containers.${index}.qty`}
control={form.control}
@@ -407,7 +382,7 @@ export function Step5CargoDetails({
control={form.control}
render={({ field: vgmField, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel>VGM (Tons) *</FieldLabel>
<FieldLabel>Tons*</FieldLabel>
<Input
value={vgmField.value ?? 0}
onChange={(e) => vgmField.onChange(e.target.value)}
@@ -422,6 +397,21 @@ export function Step5CargoDetails({
</Field>
)}
/>
<Controller
name={`containers.${index}.containerType`}
control={form.control}
render={({ field: ctField, fieldState }) => (
<SelectField
field={ctField}
error={fieldState.error}
label="Container Type *"
placeholder="Select type..."
>
<SelectOptions options={CONTAINER_TYPES} />
</SelectField>
)}
/>
</div>
{alert && (
@@ -433,6 +423,29 @@ export function Step5CargoDetails({
);
})}
</div>
{(() => {
const result = calcWagons(containers ?? []);
if (result.hasOddUnit) {
return (
<AlertBox tone="warning">
<div className="flex items-start gap-2">
<div>
<p className="font-semibold">Unpaired 20ft Container</p>
<p className="mt-1 text-xs">
One 20ft container occupies only half a wagon. The wagon
will depart once a co-loader is found to fill the
remaining slot, which{" "}
<strong>may delay departure</strong> beyond the standard
lead time.
</p>
</div>
</div>
</AlertBox>
);
}
return null;
})()}
</>
)}
</div>

View File

@@ -11,24 +11,21 @@ import {
Textarea,
} from "@edr/ui-common";
import {
REQUIRED_DOC_KEYS,
type BookingFormValues,
type RouteDirection,
type WagonCalcResult,
} from "./schema";
import { getUploadedRequiredCount, StepHeader } from "./shared";
import { StepHeader } from "./shared";
type BookingForm = UseFormReturn<BookingFormValues>;
export function Step8Review({
form,
setStep,
wagons,
direction,
}: {
form: BookingForm;
setStep: (step: number) => void;
wagons: WagonCalcResult | null;
direction: RouteDirection;
}) {
const values = form.watch();
@@ -63,13 +60,16 @@ export function Step8Review({
const containerSummary =
values.cargoType === "container" && values.containers.length > 0
? values.containers
.filter((c) => c.qty > 0)
.map((c) => `${c.qty} × ${c.type}`)
.join(", ")
.filter((c) => +c.qty > 0)
.map((c) => `${c.qty} × ${c.type}`)
.join(", ")
: "";
const totalVgm =
values.cargoType === "container"
? values.containers.reduce((sum, c) => sum + (c.qty || 0) * (c.vgm || 0), 0)
? values.containers.reduce(
(sum, c) => sum + (+c.qty || 0) * (+c.vgm || 0),
0,
)
: 0;
const cargoValue =
@@ -80,8 +80,6 @@ export function Step8Review({
: values.freightType === "break_bulk"
? `Break-Bulk - ${values.breakBulkType === "Others" ? values.breakBulkTypeOther : values.breakBulkType}`
: "";
const uploadedCount = getUploadedRequiredCount(values.documents);
return (
<div className="space-y-6">
<StepHeader
@@ -91,7 +89,7 @@ export function Step8Review({
<div className="grid gap-4 md:grid-cols-2">
<Card className="gap-0 overflow-hidden py-0">
<CardHeader className="border-b px-5 py-3">
<CardHeader className="border-b px-5 py-3!">
<CardTitle className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
Contract & Service
</CardTitle>
@@ -102,11 +100,6 @@ export function Step8Review({
value={values.contractType === "new" ? "New Contract" : "Renewal"}
target={1}
/>
<Row
label="Contract ID"
value={values.draftContractId || values.previousContractRef}
target={1}
/>
<Row
label="Service"
value={
@@ -122,7 +115,7 @@ export function Step8Review({
</Card>
<Card className="gap-0 overflow-hidden py-0">
<CardHeader className="border-b px-5 py-3">
<CardHeader className="border-b px-5 py-3!">
<CardTitle className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
First & Last Mile
</CardTitle>
@@ -131,18 +124,20 @@ export function Step8Review({
<Row
label="First Mile"
value={
values.firstMileEnabled ? values.pickUpAddress : "Not requested"
values.firstMile.enabled
? values.firstMile.pickUpAddress
: "Not requested"
}
target={3}
target={2}
/>
<Row
label="Last Mile"
value={
values.lastMileEnabled
? values.deliveryAddress
values.lastMile.enabled
? values.lastMile.deliveryAddress
: "Not requested"
}
target={3}
target={2}
/>
<Row
label="Equipment Return"
@@ -151,13 +146,20 @@ export function Step8Review({
? "With Return"
: "Without Return"
}
target={3}
target={2}
/>
<Row
label="Customs Clearing"
value={
values.customsClearingEnabled ? "Enabled" : "Not requested"
}
target={2}
/>
</CardContent>
</Card>
<Card className="gap-0 overflow-hidden py-0">
<CardHeader className="border-b px-5 py-3">
<CardHeader className="border-b px-5 py-3!">
<CardTitle className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
Route & Cargo
</CardTitle>
@@ -166,7 +168,7 @@ export function Step8Review({
<Row
label="Route"
value={`${values.originYard} -> ${values.destinationYard}`}
target={4}
target={3}
/>
<Row
label="Workflow"
@@ -175,14 +177,14 @@ export function Step8Review({
? direction.charAt(0).toUpperCase() + direction.slice(1)
: ""
}
target={4}
target={3}
/>
<Row
label="Weight (VGM)"
value={values.cargoWeight ? `${values.cargoWeight} tons` : ""}
target={5}
target={4}
/>
<Row label="Cargo" value={cargoValue} target={5} />
<Row label="Cargo" value={cargoValue} target={4} />
<Row
label="Modifiers"
value={
@@ -193,13 +195,13 @@ export function Step8Review({
.filter(Boolean)
.join(", ") || "None"
}
target={4}
target={3}
/>
</CardContent>
</Card>
<Card className="gap-0 overflow-hidden py-0">
<CardHeader className="border-b px-5 py-3">
<CardHeader className="border-b px-5 py-3!">
<CardTitle className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
Container & Wagons
</CardTitle>
@@ -208,26 +210,12 @@ export function Step8Review({
<Row
label="Containers"
value={containerSummary || "-"}
target={5}
target={4}
/>
<Row
label="Total VGM"
value={totalVgm > 0 ? `${totalVgm.toFixed(1)} tons` : ""}
target={5}
/>
<Row
label="Wagons"
value={
wagons
? `${wagons.totalWagons} wagon${wagons.totalWagons > 1 ? "s" : ""}`
: ""
}
target={6}
/>
<Row
label="Documents"
value={`${uploadedCount}/${REQUIRED_DOC_KEYS.length} mandatory uploaded`}
target={7}
target={4}
/>
</CardContent>
</Card>

View File

@@ -1,8 +1,5 @@
export { Step1ContractType } from "./step1-contract-type";
export { Step2ServiceType } from "./step2-service-type";
export { Step3FirstLastMile } from "./step3-first-last-mile";
export { Step4Route } from "./step4-route";
export { Step5CargoDetails } from "./step5-cargo-details";
export { Step6WagonAllocation } from "./step6-wagon-allocation";
export { Step7Documents } from "./step7-documents";
export { Step8Review } from "./step8-review";

View File

@@ -221,6 +221,7 @@ export interface CreateBookingDto {
lastMileDeliveryAddress?: string;
equipmentReturn: "WITH_RETURN" | "WITHOUT_RETURN";
customsClearingEnabled?: boolean;
originStation: string;
destinationStation: string;
cargoTotalWeightVgm: number;

5
tasks.md Normal file
View File

@@ -0,0 +1,5 @@
- In ./apps/edr-freight-web/portal/src/pages/bookings/new-booking-form/step1-contract-type.tsx the input field for the previous contract ref should be a select field with the list of contracts from the API
- the "Equipment Return" field in ./apps/edr-freight-web/portal/src/pages/bookings/new-booking-form/step3-first-last-mile.tsx should be a toggle like Last Mile - Delivery and should appear only if the last mile is toggled. and also add "( Door to Port)" to first mile description and vice versa to the last mile
- add Type of container- Dry container, high cubic containers , reefer containers, open top containers, flat rack, tank container, open side containers to ./apps/edr-freight-web/portal/src/pages/bookings/new-booking-form/step4-route.tsx
- merge the "Unpaired 20ft Container" from ./apps/edr-freight-web/portal/src/pages/bookings/new-booking-form/step6-wagon-allocation.tsx to step 4 and fully remove the step 5
- add Type of Shipping lines - MSC, CMA CGM, Evergreen, COSCO, Hapag-Lloyd, ONE, Yang Ming, ZIM, Messina Line, Safmarine, Wan Hai, Ethiopian Shipping Lines (ESLSE) to ./apps/edr-freight-web/portal/src/pages/bookings/new-booking-form/step4-route.tsx