Merge pull request #923 from Tria-plc/freight_feature/usermanagement

Freight feature/usermanagement
This commit is contained in:
marshal
2026-07-23 00:02:55 +03:00
committed by GitHub
39 changed files with 3644 additions and 362 deletions

View File

@@ -38,6 +38,7 @@ import {
} from "react-router-dom";
import useAuth from "@/hooks/useAuth";
import {
CONTAINER_SIZES,
CONTRACT_STEPS,
ContractFormInputValues,
contractFormSchema,
@@ -537,15 +538,15 @@ export default function NewContractPage({
const isContainer = data.cargoType === "container";
const isGeneral = data.contractKind === "general_contract";
// Cargo scope rows — no quantities (doc §5.4). Container: one row per enabled
// size; bulk: a single commodity row. Both GENERAL and ONE_TIME are uncapped
// (quantityCap omitted → NULL): the customer books repeatedly against a
// GENERAL contract until its validity expires.
// Cargo scope rows — no quantities (doc §5.4). Container: ALWAYS both sizes
// (rates quoted for both; per-booking quantities can zero a size out) and no
// description — that moved to booking time. Bulk: a single commodity row.
// Both GENERAL and ONE_TIME are uncapped (quantityCap omitted → NULL): the
// customer books repeatedly against a GENERAL contract until its validity
// expires.
const cargoScope: Freight.CreateContractCargoScopeDto[] = isContainer
? data.enabledContainerSizes.map((size) => ({
? CONTAINER_SIZES.map((size) => ({
containerSize: size,
// Required cargo description — what the containers carry.
cargoFreeText: data.cargoFreeText.trim() || undefined,
}))
: [
{

View File

@@ -346,6 +346,10 @@ function NewShipmentBookingForm({
// Equipment return is a container concern — bulk keeps the contract default.
...(isContainer
? {
// What the containers carry — captured per booking, not on the contract.
...(values.cargoDescription?.trim()
? { cargoFreeText: values.cargoDescription.trim() }
: {}),
containers: values.containers
.filter((l) => Number(l.quantity) >= 1)
.map((l) => ({
@@ -1295,6 +1299,26 @@ function CargoStep({
)}
{remainderNotice}
<ContractCapacityNotice contractId={contract.id} isContainer />
<Controller
name="cargoDescription"
control={form.control}
render={({ field, fieldState }) => (
<Textarea
label="Cargo description *"
description="What do the containers carry on this shipment?"
placeholder="e.g. Electronics, garments, machinery spare parts…"
value={field.value ?? ""}
onChange={(e) => field.onChange(e.currentTarget.value)}
onBlur={field.onBlur}
error={fieldState.error?.message}
radius={10}
autosize
minRows={2}
maxRows={4}
styles={fieldStyles}
/>
)}
/>
{lines.map((line, index) => (
<ContainerLineEditor
key={line.containerSize}
@@ -1648,7 +1672,7 @@ function ContainerLineEditor({
type="number"
onKeyDown={blockNegative}
label="Quantity *"
min={1}
min={0}
error={fieldState.error?.message}
radius={10}
styles={fieldStyles}

View File

@@ -58,12 +58,9 @@ export function contractToFormValues(
const scope = contract.cargoScope ?? [];
// Container scope: one row per enabled size, with per-size caps for GENERAL.
const enabledContainerSizes = isContainer
? scope
.map((s) => s.containerSize)
.filter((s): s is string => Boolean(s))
: [];
// Container scope: contracts now always cover both sizes — force both even
// for older single-size drafts so resubmitting upgrades them.
const enabledContainerSizes = isContainer ? ["20ft", "40ft"] : [];
const containerSizeCaps: Record<string, number> = {};
if (isContainer && isGeneral) {
for (const s of scope) {
@@ -119,10 +116,9 @@ export function contractToFormValues(
enabledContainerSizes as ContractFormInputValues["enabledContainerSizes"],
containerSizeCaps,
cargoTypePath,
// Bulk: the commodity free-text; container: the required cargo
// description (stored on every size row — read the first).
cargoFreeText:
(isContainer ? scope[0]?.cargoFreeText : bulkRow?.cargoFreeText) ?? "",
// Bulk commodity free-text only — the container cargo description is
// captured per booking now, not on the contract.
cargoFreeText: (isContainer ? "" : bulkRow?.cargoFreeText) ?? "",
bulkQuantityCap:
isGeneral && bulkRow?.quantityCap != null ? bulkRow.quantityCap : 0,
isHazardous: contract.isHazardous,

View File

@@ -160,8 +160,9 @@ export const contractFormSchema = z
// ── Cargo SCOPE (no quantities) ──
cargoType: z.enum(["container", "bulk"], "Select a cargo type."),
// Container scope: the enabled sizes (min 1). Each becomes a
// contract_cargo_scope row.
// Container scope: ALWAYS both sizes — the contract covers 20ft and 40ft
// (both rates shown); the customer picks quantities per booking, where a
// size can be 0. No picker in the UI; kept for review display/prefill.
enabledContainerSizes: z.array(z.enum(CONTAINER_SIZES)).default([]),
// GENERAL only: per-size container quantity cap (total bookable over the
// validity window). Keyed by size; must be > 0 for every enabled size
@@ -222,24 +223,8 @@ export const contractFormSchema = z
message: "Intercity contracts are priced in ETB.",
});
}
if (data.cargoType === "container") {
// Container scope: at least one enabled size.
if (data.enabledContainerSizes.length === 0) {
ctx.addIssue({
code: "custom",
path: ["enabledContainerSizes"],
message: "Enable at least one container size.",
});
}
// Containerized cargo must say WHAT is inside — required description.
if (!data.cargoFreeText.trim()) {
ctx.addIssue({
code: "custom",
path: ["cargoFreeText"],
message: "Describe the cargo carried in the containers.",
});
}
}
// Container scope needs no validation: both sizes are always in scope and
// the cargo description moved to booking time.
if (data.cargoType === "bulk") {
// Bulk scope: a commodity is required.
if (!data.cargoTypePath[0]) {
@@ -280,7 +265,7 @@ export const initialContractFormValues: DeepPartial<ContractFormValues> = {
customsClearingAgent: "",
cargoType: "container",
enabledContainerSizes: [],
enabledContainerSizes: [...CONTAINER_SIZES],
containerSizeCaps: {},
cargoTypePath: [],
cargoFreeText: "",

View File

@@ -152,10 +152,11 @@ export function Step1ContractType({
contract.freightType === "BULK" ? "bulk" : "container",
);
const scope = contract.cargoScope ?? [];
const sizes = scope
.map((s) => s.containerSize)
.filter((s): s is "20ft" | "40ft" => s === "20ft" || s === "40ft");
if (sizes.length > 0) form.setValue("enabledContainerSizes", sizes);
// Contracts always cover both sizes now — even when renewing an older
// single-size contract.
if (contract.freightType !== "BULK") {
form.setValue("enabledContainerSizes", ["20ft", "40ft"]);
}
const bulkScope = scope.find((s) => s.cargoTypeId);
if (bulkScope?.cargoTypeId) {
// Find the parent group for this commodity so the cascader prefills.

View File

@@ -1,6 +1,6 @@
import { useEffect, useMemo, useRef } from "react";
import { Controller, type UseFormReturn } from "react-hook-form";
import { Check, Container, Flame, RotateCcw, Snowflake } from "lucide-react";
import { Container, Flame, RotateCcw, Snowflake } from "lucide-react";
import {
Box,
Group,
@@ -9,33 +9,15 @@ import {
Stack,
Switch,
Text,
Textarea,
UnstyledButton,
} from "@mantine/core";
import type { Freight } from "@edr/types";
import {
CONTAINER_SIZES,
ContractFormInputValues,
type ContractFormValues,
} from "./schema";
import { fieldStyles, SelectField, StepLabel } from "./shared";
const CONTAINER_SIZE_OPTIONS: Array<{
value: "20ft" | "40ft";
label: string;
description: string;
}> = [
{
value: "20ft",
label: "20ft Container",
description: "Standard twenty-foot unit (TEU)",
},
{
value: "40ft",
label: "40ft Container",
description: "Standard forty-foot unit (FEU)",
},
];
const CARGO_TYPE_OPTIONS = [
{ value: "container", label: "Containerized (20ft / 40ft)" },
{ value: "bulk", label: "General / Bulk cargo" },
@@ -128,11 +110,17 @@ export function Step3CargoScope({
onChange={(v) => {
if (!v) return;
field.onChange(v);
// cargoFreeText is shared (bulk commodity label / container
// description) — clear it so text never carries across types.
// cargoFreeText is the bulk commodity label clear it so text
// never carries across types (container description is captured
// at booking time now).
form.setValue("cargoFreeText", "", { shouldDirty: true });
if (v === "container") {
form.setValue("cargoTypePath", [], { shouldDirty: true });
// Contracts always cover BOTH sizes; quantities are chosen per
// booking (a size can be 0 there).
form.setValue("enabledContainerSizes", [...CONTAINER_SIZES], {
shouldDirty: true,
});
} else {
form.setValue("enabledContainerSizes", [], {
shouldDirty: true,
@@ -152,74 +140,47 @@ export function Step3CargoScope({
</div>
{/* Container scope: enabled sizes as tick-cards — tap to toggle, one or
both can be in scope. Clearer than a multi-select for two options. */}
{/* Container scope: the contract always covers BOTH sizes and quotes both
rates. Quantities (a size can be 0) and the cargo description are
captured at booking time. */}
{cargoType === "container" && (
<Controller
name="enabledContainerSizes"
control={form.control}
render={({ field, fieldState }) => {
const selected = (field.value ?? []) as ("20ft" | "40ft")[];
const toggle = (size: "20ft" | "40ft") => {
field.onChange(
selected.includes(size)
? selected.filter((s) => s !== size)
: [...selected, size],
);
field.onBlur();
};
return (
<Box>
<StepLabel>Container sizes in scope *</StepLabel>
<Text fz={12} c="#6B7C8E" mt={2}>
Tick every size this contract should cover you can select
both.
</Text>
<div className="mt-3 grid gap-3 sm:grid-cols-2">
{CONTAINER_SIZE_OPTIONS.map((opt) => (
<SizeCard
key={opt.value}
label={opt.label}
description={opt.description}
checked={selected.includes(opt.value)}
hasError={Boolean(fieldState.error)}
onToggle={() => toggle(opt.value)}
/>
))}
</div>
{fieldState.error?.message && (
<Text fz={12} c="red.7" mt={6}>
{fieldState.error.message}
</Text>
)}
</Box>
);
<Group
gap={13}
align="center"
wrap="nowrap"
px={16}
py={13}
style={{
borderRadius: 14,
border: "1.5px solid #CDEBDD",
background: "#F6FBF8",
}}
/>
)}
{/* Container scope: required description of what the containers carry. */}
{cargoType === "container" && (
<Controller
name="cargoFreeText"
control={form.control}
render={({ field, fieldState }) => (
<Textarea
label="Cargo description *"
description="What will the containers carry under this contract?"
placeholder="e.g. Electronics, garments, machinery spare parts…"
value={field.value ?? ""}
onChange={(e) => field.onChange(e.currentTarget.value)}
onBlur={field.onBlur}
error={fieldState.error?.message}
radius={10}
autosize
minRows={2}
maxRows={4}
styles={fieldStyles}
/>
)}
/>
>
<Box
style={{
width: 38,
height: 38,
borderRadius: 11,
flexShrink: 0,
display: "flex",
alignItems: "center",
justifyContent: "center",
background: "#EAF6EC",
color: "#1E7B34",
}}
>
<Container size={18} />
</Box>
<Box>
<Text fz={14} fw={700} c="#10202F">
20ft &amp; 40ft containers covered
</Text>
<Text fz={12} c="#6B7C8E" style={{ lineHeight: 1.4 }}>
This contract quotes rates for both sizes. You choose the
quantities on each booking either size can be 0.
</Text>
</Box>
</Group>
)}
{/* Bulk scope: a single commodity (cargo type path). No tonnage. */}
@@ -330,85 +291,6 @@ export function Step3CargoScope({
);
}
/** Checkbox-style card for one container size. Whole card toggles. */
function SizeCard({
label,
description,
checked,
hasError,
onToggle,
}: {
label: string;
description: string;
checked: boolean;
hasError: boolean;
onToggle: () => void;
}) {
return (
<UnstyledButton
role="checkbox"
aria-checked={checked}
aria-label={label}
onClick={onToggle}
px={16}
py={13}
style={{
borderRadius: 14,
border: `1.5px solid ${
checked ? "#0A6F4D" : hasError ? "#E8B4AC" : "#E6ECF2"
}`,
background: checked ? "#F6FBF8" : "#fff",
transition: "all 150ms ease",
width: "100%",
}}
>
<Group gap={13} align="center" wrap="nowrap">
<Box
style={{
width: 22,
height: 22,
borderRadius: 7,
flexShrink: 0,
display: "flex",
alignItems: "center",
justifyContent: "center",
border: `1.5px solid ${checked ? "#0A6F4D" : "#C7D2DC"}`,
background: checked ? "#0A6F4D" : "#fff",
color: "#fff",
transition: "all 150ms ease",
}}
>
{checked && <Check size={14} strokeWidth={3} />}
</Box>
<Box
style={{
width: 38,
height: 38,
borderRadius: 11,
flexShrink: 0,
display: "flex",
alignItems: "center",
justifyContent: "center",
background: checked ? "#EAF6EC" : "#F1F5F8",
color: checked ? "#1E7B34" : "#6B7C8E",
transition: "all 150ms ease",
}}
>
<Container size={18} />
</Box>
<Box style={{ textAlign: "left" }}>
<Text fz={14} fw={700} c="#10202F">
{label}
</Text>
<Text fz={12} c="#6B7C8E" style={{ lineHeight: 1.4 }}>
{description}
</Text>
</Box>
</Group>
</UnstyledButton>
);
}
function ToggleRow({
icon,
iconBg,

View File

@@ -57,10 +57,13 @@ const containerUnitSchema = z.object({
const containerLineSchema = z.object({
containerSize: z.enum(["20ft", "40ft"]),
// 0 is allowed: the contract covers both sizes, so a booking that only needs
// one size zeroes the other line out. At least one line must be ≥ 1
// (enforced in the superRefine).
quantity: z
.string()
.refine((v) => v.trim().length > 0, "Quantity is required.")
.refine((v) => !Number.isNaN(Number(v)) && Number(v) >= 1, "At least 1."),
.refine((v) => !Number.isNaN(Number(v)) && Number(v) >= 0, "Enter 0 or more."),
hazardousQuantity: z.string().default("0"),
reeferQuantity: z.string().default("0"),
returnQuantity: z.string().default("0"),
@@ -74,6 +77,8 @@ const shipmentFormBase = z.object({
// unloading. Seeded from the contract's equipment return; bulk ignores it.
withReturn: z.boolean().default(false),
containers: z.array(containerLineSchema).default([]),
// What the containers carry — captured per booking (moved off the contract).
cargoDescription: z.string().default(""),
cargoWeightTons: z.string().default(""),
itemCount: z.string().default(""),
bulkHazardousQuantity: z.string().default("0"),
@@ -92,6 +97,28 @@ export function createShipmentFormSchema(ctx: ShipmentValidationContext) {
}
if (ctx.isContainer) {
// Containerized cargo must say WHAT is inside — required per booking.
if (!data.cargoDescription.trim()) {
refineCtx.addIssue({
code: "custom",
path: ["cargoDescription"],
message: "Describe the cargo carried in the containers.",
});
}
// Both sizes are always in contract scope and a line can be 0 — but the
// booking as a whole needs at least one container. Anchor the error on
// the first line's quantity so it renders in the field.
const totalQty = data.containers.reduce(
(sum, l) => sum + Math.max(0, Number(l.quantity) || 0),
0,
);
if (data.containers.length > 0 && totalQty < 1) {
refineCtx.addIssue({
code: "custom",
path: ["containers", 0, "quantity"],
message: "Book at least one container (either size).",
});
}
// Container numbers must be unique within this shipment (front-end only —
// the DB column is intentionally not unique). Duplicates block submit and
// price generation since both run through this same schema validation.
@@ -243,6 +270,7 @@ export const initialShipmentFormValues: DeepPartial<ShipmentFormValues> = {
scheduledDate: "",
withReturn: false,
containers: [],
cargoDescription: "",
cargoWeightTons: "",
itemCount: "",
bulkHazardousQuantity: "0",
@@ -257,6 +285,7 @@ export const shipmentStepFields: Record<
0: ["contractRouteId"],
1: [
"containers",
"cargoDescription",
"cargoWeightTons",
"itemCount",
"bulkHazardousQuantity",