Merge pull request #1146 from Tria-plc/freight/nati-2

Freight/nati 2
This commit is contained in:
Nathnael Wondisha
2026-08-07 01:41:42 +03:00
committed by GitHub
23 changed files with 1683 additions and 174 deletions

View File

@@ -668,3 +668,66 @@ describe("BillingService — CAC Bank (OTP debit)", () => {
expect(confirmOtp).toHaveBeenCalledWith("intent-1", "123456");
});
});
describe("BillingService — CBE bill amounts round UP to whole birr", () => {
// CBE bills whole birr. Ceil, never Math.round: a .40 balance rounded down
// settles 0.40 short while markInvoiceAsPaid still writes paidAmount =
// totalAmount — money missing from the bank with the books saying paid.
// payInvoice and billQuery must agree, or /cbe/payment sees a mismatch.
const invoice = {
id: "inv-1",
status: Freight.InvoiceStatus.Pending,
source: Freight.InvoiceSource.Booking,
sourceId: "booking-1",
type: "PREPAID",
invoiceNumber: "INV-20260101-00001",
currency: "ETB",
// .40 — the case Math.round gets wrong (rounds down, underpays).
balanceAmount: 12345.4,
totalAmount: 12345.4,
company: { name: "Acme PLC" },
paymentId: null,
dueAt: null,
};
const build = (payment: Record<string, unknown> = {}) => {
const repo = {
findOne: jest.fn().mockResolvedValue(invoice),
update: jest.fn().mockResolvedValue(undefined),
};
const service = new BillingService(
{ getRepository: () => repo } as never,
{} as never,
{} as never,
makeEvents() as never,
payment as never,
{} as never,
{} as never,
);
return { service, repo };
};
it("opens the intent for the ceiled balance, never below it", async () => {
const initiate = jest.fn().mockResolvedValue({
intentId: "intent-1",
immediateSuccess: false,
response: { intentId: "intent-1", status: "REQUIRES_ACTION" },
});
const { service } = build({ initiate });
await service.payInvoice("inv-1", { method: "CBE_BILL" });
expect(initiate).toHaveBeenCalledWith(
expect.objectContaining({ amountMinor: 12346 }),
);
});
it("quotes the same ceiled amount on bill-query as payInvoice opened", async () => {
const { service } = build();
await expect(service.billQuery("booking-1")).resolves.toMatchObject({
stillPayable: true,
currentAmountMinor: 12346,
});
});
});

View File

@@ -1191,7 +1191,11 @@ export class BillingService {
// service branches on a domain-specific reference type.
referenceType: PaymentReferenceType.SHIPMENT,
orderRef: invoice.invoiceNumber.replace(/-/g, "_"),
amountMinor: Math.round(Number(invoice.balanceAmount)),
// Whole birr, always UP. CBE bills this amount verbatim, so it must never
// land below the outstanding balance — Math.round would let a .40 balance
// settle 0.40 short. Ceil overcharges by <1 birr instead, and the same
// ceil in billQuery keeps the quoted and debited amounts identical.
amountMinor: Math.ceil(Number(invoice.balanceAmount)),
currency: invoice.currency,
reason: `Payment for invoice ${invoice.invoiceNumber}`,
method: opts.method ?? "TELEBIRR",
@@ -1336,7 +1340,9 @@ export class BillingService {
});
if (open) {
const balance = Math.round(Number(open.balanceAmount ?? open.totalAmount));
// Ceil, matching payInvoice — the amount CBE quotes at the counter has to
// be the amount the intent was opened for, or /cbe/payment sees a mismatch.
const balance = Math.ceil(Number(open.balanceAmount ?? open.totalAmount));
const expired = open.dueAt && open.dueAt.getTime() < Date.now();
return {
stillPayable: balance > 0 && !expired,
@@ -1371,7 +1377,7 @@ export class BillingService {
return {
stillPayable: false,
payerName: latest.company?.name ?? null,
currentAmountMinor: Math.round(Number(latest.totalAmount)),
currentAmountMinor: Math.ceil(Number(latest.totalAmount)),
currency: latest.currency,
paymentReason: `Freight invoice ${latest.invoiceNumber}`,
reason: closedInvoiceReason(latest.status),

View File

@@ -2057,6 +2057,11 @@ export class CompaniesService {
// replace it before the application counts as complete.
const flaggedDelegation = delegationDue && delegation.flagged;
// Mirrors `poaProven` in buildCompanyIdentityState — see the note there.
const poaProven = identity.faydaRequired
? identity.poa.verified
: identity.poa.verified || Boolean(identity.poa.name?.trim());
const outstanding = [
...missingInfo.map((f) => `Add your ${f.label.toLowerCase()}`),
...missingDocs.map((d) => `Upload your ${d.fileLabel}`),
@@ -2074,8 +2079,19 @@ export class CompaniesService {
...(identity.faydaRequired && !identity.owner.verified
? ["Verify the company owner's identity with Fayda"]
: []),
...((poaRequired || poaProvided) && !identity.poa.verified
? ["Verify your Power of Attorney's identity with Fayda"]
// Nationality-aware, exactly like `poaProven` in
// buildCompanyIdentityState and the check in `assertIdentityVerified`:
// Fayda is an Ethiopian national ID, so a foreign company's typed
// representative has to count. Demanding a verification here regardless
// made this list disagree with the rule actually enforced, and left a
// foreign freight forwarder unable to submit — asked for a Fayda
// verification its representative may have no way to obtain.
...((poaRequired || poaProvided) && !poaProven
? [
identity.faydaRequired
? "Verify your Power of Attorney's identity with Fayda"
: "Name your Power of Attorney, or verify them with Fayda",
]
: []),
...(identity.passportRequired && !identity.owner.passportNumber
? ["Add the company owner's passport number"]
@@ -2089,7 +2105,10 @@ export class CompaniesService {
const poaItemCount = delegationDue ? 1 : 0;
// One item per identity credential the company has to prove: the owner
// always (Fayda for Ethiopian, passport for foreign), plus the PoA once
// there is one — that one is Fayda whatever the nationality.
// there is one — Fayda for an Ethiopian company, a named representative
// for a foreign one, same rule as `poaProven` above. Counting a foreign
// company's typed PoA as unproven here left the progress bar permanently
// short of 100% on an item it had already satisfied.
const ownerCredentialDue =
identity.faydaRequired || identity.passportRequired;
const ownerCredentialProven = identity.faydaRequired
@@ -2099,7 +2118,7 @@ export class CompaniesService {
(ownerCredentialDue ? 1 : 0) + (delegationDue ? 1 : 0);
const missingIdentityCount =
(ownerCredentialDue && !ownerCredentialProven ? 1 : 0) +
(delegationDue && !identity.poa.verified ? 1 : 0);
(delegationDue && !poaProven ? 1 : 0);
const total =
requiredInfo.length +
requiredDocCount +
@@ -2767,7 +2786,13 @@ export class CompaniesService {
// The verified payload owns the person's details from here on.
...(result.fullName ? { [`${prefix}Name`]: result.fullName } : {}),
...(result.email ? { [`${prefix}Email`]: result.email } : {}),
...(result.phoneNumber ? { [`${prefix}Phone`]: result.phoneNumber } : {}),
// Fayda returns whatever the national registry holds, which is routinely a
// local number ("0911223344"). Every typed phone in this service is stored
// E.164, and `@IsValidPhone()` rejects anything else — so a raw claim here
// becomes a value the portal reads back and cannot resubmit.
...(result.phoneNumber
? { [`${prefix}Phone`]: normalizeE164(result.phoneNumber) }
: {}),
...(result.address ? { [`${prefix}Address`]: result.address } : {}),
};

View File

@@ -1,4 +1,12 @@
import { IsString, IsOptional, IsEmail, MaxLength, IsEnum, IsIn } from 'class-validator';
import {
IsString,
IsOptional,
IsEmail,
MaxLength,
IsEnum,
IsIn,
Matches,
} from 'class-validator';
import { ETHIOPIAN_REGIONS, type EthiopianRegion } from '@edr/types';
import { CompanyNationality } from '../entities/company.entity';
import { IsValidPhone } from '../../../common/validators/is-phone-number.validator';
@@ -39,9 +47,13 @@ export class UpdateProfileDto {
@IsTin({ message: 'TIN must be exactly 10 digits' })
tin?: string;
// Ethiopian VAT registration numbers are 10 digits, the same shape as the
// TIN. Both portal forms enforce that; without it here the API happily stored
// whatever a stale client sent, and the two layers disagreed about what the
// column may hold.
@IsOptional()
@IsString()
@MaxLength(50)
@Matches(/^\d{10}$/, { message: 'VAT number must be exactly 10 digits' })
vatNumber?: string;
// `fanNumber` is deliberately absent: the FAN is the Fayda number of the

View File

@@ -1,8 +1,8 @@
import {
IsEnum,
IsIn,
IsInt,
IsISO8601,
IsNumber,
IsOptional,
IsPositive,
IsString,
@@ -37,7 +37,9 @@ export class PaymentEventDto {
@ApiProperty() @IsString() referenceId!: string;
@ApiProperty() @IsString() merchantOrderId!: string;
@ApiProperty({ enum: ProviderMethod }) @IsEnum(ProviderMethod) provider!: string;
@ApiProperty() @IsInt() @IsPositive() amountMinor!: number;
// Major units, fractional (payment-api stores it as double precision) — an
// invoice of 12345.67 must not be rejected by an integer-only validator.
@ApiProperty() @IsNumber() @IsPositive() amountMinor!: number;
@ApiProperty() @IsString() currency!: string;
@ApiPropertyOptional() @IsOptional() @IsString() providerTxnId?: string;

View File

@@ -647,6 +647,8 @@ const DJ_CLEARANCE_HREF = "/dashboard/gl-djibouti/clearance";
const GL_WORKFLOW_PATH_PATTERNS: RegExp[] = [
/^\/dashboard\/contracts\/[^/]+\/create-booking(\/|$)/,
/^\/dashboard\/bookings\/[^/]+\/clearance(\/|$)/,
// The ET hub's rows open the shipment clearance detail at this URL.
/^\/dashboard\/clearance\/[^/]+(\/|$)/,
];
const isEtClearanceItem = (item: SidebarItem): boolean =>

View File

@@ -3,6 +3,7 @@ import { useDisclosure } from "@mantine/hooks";
import {
Home,
Layers,
LifeBuoy,
Loader2,
// MapPin,
Package,
@@ -58,6 +59,10 @@ import CheckPaymentPage from "./pages/payments/CheckPaymentPage";
import PaymentFailurePage from "./pages/payments/PaymentFailurePage";
import FaydaCallbackPage from "./pages/FaydaCallbackPage";
import PaymentSuccessPage from "./pages/payments/PaymentSuccessPage";
import FaqPage from "./pages/support/FaqPage";
import HelpPage from "./pages/support/HelpPage";
import PrivacyPolicyPage from "./pages/support/PrivacyPolicyPage";
import TermsPage from "./pages/support/TermsPage";
import TrackingPage from "./pages/tracking/TrackingPage";
function FullScreenSpinner() {
@@ -217,6 +222,12 @@ const sidebarItems: SidebarItem[] = [
href: "/settings",
icon: <Settings size={18} />,
},
{
section: "Account",
label: "Help & Support",
href: "/help",
icon: <LifeBuoy size={18} />,
},
];
const App = () => {
@@ -273,6 +284,14 @@ const App = () => {
<Route path="/payment/success" element={<PaymentSuccessPage />} />
<Route path="/payment/failure" element={<PaymentFailurePage />} />
{/* Help and legal pages. Public on purpose: the auth screens link to
them before a session exists, so they carry their own chrome rather
than sitting inside the authenticated app layout. */}
<Route path="/help" element={<HelpPage />} />
<Route path="/faq" element={<FaqPage />} />
<Route path="/privacy" element={<PrivacyPolicyPage />} />
<Route path="/terms" element={<TermsPage />} />
{/* Auth pages — inaccessible once logged in */}
<Route element={<RedirectIfAuthed />}>
<Route path="/login" element={<LoginPage />} />

View File

@@ -129,19 +129,19 @@ const FormFooter = () => (
<span className="shrink-0">© 2026 EDR Freight</span>
<div className="flex flex-wrap items-center justify-center gap-3 sm:justify-end sm:gap-6">
<Link
to="#"
to="/terms"
className="font-semibold text-gray-700 transition-colors hover:text-primary"
>
Terms &amp; Conditions
</Link>
<Link
to="#"
to="/privacy"
className="font-semibold text-gray-700 transition-colors hover:text-primary"
>
Privacy Policy
</Link>
<Link
to="#"
to="/help"
className="font-semibold text-gray-700 transition-colors hover:text-primary"
>
Help &amp; Support

View File

@@ -26,9 +26,22 @@ interface ETradeInfoProps {
onStatusChange?: (status: ETradeStatus) => void;
/** Called when the TIN changes away from the last fetched value — clear whatever it filled in. */
onReset?: () => void;
/**
* This TIN already passed eTrade in an earlier session (the saved profile
* carries its registration details), so adopt it on arrival instead of
* re-querying. Rehydration lands the TIN after the first render, which used
* to look exactly like the customer typing a new one: every reopen fired a
* live lookup that could fail on an outage, and re-marked eTrade's fields as
* freshly verified so they were resubmitted on the next save. "Get Data"
* stays available for a deliberate re-verify.
*/
alreadyVerified?: boolean;
}
const isValidTin = (tin: string) => tin.length === 10;
// Digits, not just length: a 10-character non-numeric TIN used to fire a lookup
// that could only fail, and the failure was then reported as "this TIN isn't
// registered with eTrade" instead of "that isn't a TIN".
const isValidTin = (tin: string) => /^\d{10}$/.test(tin);
export default function ETradeInfo({
tin,
@@ -37,6 +50,7 @@ export default function ETradeInfo({
onDataLoaded,
onStatusChange,
onReset,
alreadyVerified,
}: ETradeInfoProps) {
const mutation = useETradeData();
const isLoading = mutation.isPending;
@@ -63,6 +77,13 @@ export default function ETradeInfo({
// doesn't refire the lookup the moment this mounts.
const lastFetchedTin = useRef<string | null>(tin || null);
useEffect(() => {
// A rehydrated TIN that eTrade already accepted: adopt it silently. Doing
// this before the change-detection below also keeps `onReset` from firing,
// which would wipe the very registration details that prove it passed.
if (alreadyVerified && lastFetchedTin.current === null && isValidTin(tin)) {
lastFetchedTin.current = tin;
return;
}
if (tin !== lastFetchedTin.current) {
// TIN moved away from whatever we last fetched — that result (verified
// data, "taken", or an error) no longer describes this TIN. Drop it so
@@ -82,12 +103,17 @@ export default function ETradeInfo({
const apiError =
mutation.isError && mutation.error ? extractApiError(mutation.error) : null;
// A 400 here means eTrade simply has no record for this TIN.
const notFound = apiError?.statusCode === 400;
// A 400 here usually means eTrade has no record for this TIN — but the API
// also wraps its own transport failures as a 400 ("Failed to fetch company
// info from eTrade: …"), and reporting an outage as "this TIN isn't
// registered" sends the customer off to re-check a number that was fine.
const unreachable = /failed to fetch/i.test(apiError?.message ?? "");
const notFound = apiError?.statusCode === 400 && !unreachable;
const errorMessage =
apiError && !notFound
? apiError.message ||
"We couldn't reach eTrade to fetch your company information. Please try again."
? unreachable || !apiError.message
? "We couldn't reach eTrade to fetch your company information. Please try again in a moment."
: apiError.message
: null;
const status: ETradeStatus = isLoading

View File

@@ -584,7 +584,35 @@ export default function EDRFreightLandingPage() {
</div>
</div>
<div>© 2026 EDR Freight. All rights reserved.</div>
<div className="flex flex-col items-center gap-4 md:items-end">
<nav className="flex flex-wrap items-center justify-center gap-x-6 gap-y-2">
<Link
to="/help"
className="font-semibold text-foreground transition-colors hover:text-primary"
>
Help &amp; Support
</Link>
<Link
to="/faq"
className="font-semibold text-foreground transition-colors hover:text-primary"
>
FAQ
</Link>
<Link
to="/privacy"
className="font-semibold text-foreground transition-colors hover:text-primary"
>
Privacy Policy
</Link>
<Link
to="/terms"
className="font-semibold text-foreground transition-colors hover:text-primary"
>
Terms of Service
</Link>
</nav>
<div>© 2026 EDR Freight. All rights reserved.</div>
</div>
</div>
</footer>
</div>

View File

@@ -38,6 +38,10 @@ import {
} from "./companyProfileForm/schema";
import {
buildPayload,
firstPresent,
firstValidEmail,
firstValidPhone,
normalizeIdentityPhones,
stepPayload,
toFormValues,
} from "./companyProfileForm/helpers";
@@ -45,6 +49,7 @@ import FaydaVerifyPanel from "@/components/FaydaVerifyPanel";
import { verifaydaService } from "@/services/verifayda.service";
import type { CompanyIdentityState } from "@/services/verifayda.service";
import { LinkCheckboxCard } from "./companyProfileForm/LinkCheckboxCard";
import { ReadOnlyField } from "./companyProfileForm/ReadOnlyField";
import ETradeCompanyCard from "./companyProfileForm/ETradeCompanyCard";
import StepSection from "./companyProfileForm/StepSection";
@@ -67,7 +72,7 @@ export default function CompanyProfileForm({
submitError,
uploadedDocumentKeys,
onUploadDocuments,
identity,
identity: rawIdentity,
onIdentityChange,
}: {
documentSettingCode: string;
@@ -115,6 +120,15 @@ export default function CompanyProfileForm({
*/
onIdentityChange?: () => void;
}) {
// A Fayda claim carries the phone as the national registry holds it, which is
// often a local number the form's E.164 validation (and the API's
// `@IsValidPhone()`) would reject — for a value the customer never typed and
// has no field to correct. Normalize once, here, so every read below is safe.
const identity = useMemo(
() => normalizeIdentityPhones(rawIdentity),
[rawIdentity],
);
const [step, setStep] = useState<CompanyStep>(initialStep ?? "company");
const [saving, setSaving] = useState(false);
const [saveError, setSaveError] = useState<string | null>(null);
@@ -188,15 +202,20 @@ export default function CompanyProfileForm({
const {
register,
control,
handleSubmit,
trigger,
watch,
setValue,
formState: { errors },
getValues,
formState: { errors, dirtyFields },
} = useForm<FormData>({
resolver: zodResolver(
buildOnboardingSchema(identity?.passportRequired === true),
),
// `values` below re-seeds the form whenever the profile is refetched — and
// an in-page identity action (ticking "same as owner") refetches it. Without
// this, that reset silently throws away whatever the customer was part-way
// through typing on the current step.
resetOptions: { keepDirtyValues: true, keepErrors: true },
defaultValues: {
companyName: "",
companyEmail: "",
@@ -266,21 +285,28 @@ export default function CompanyProfileForm({
phone: string;
} | null>(null);
// `shouldDirty` is what marks the eTrade bundle as "re-verified this session";
// `stepPayload` sends those keys only when dirty, so an unchanged record is
// never echoed back to the API (which would make it re-query eTrade).
const handleETradeDataLoaded = (data: CompanyRegistrationData) => {
const dirty = { shouldDirty: true } as const;
if (data.companyName) {
setValue("companyName", data.companyName, { shouldValidate: true });
setValue("companyName", data.companyName, {
shouldValidate: true,
...dirty,
});
}
setValue("licenceNumber", data.licenceNumber);
setValue("statusDescription", data.statusDescription);
setValue("dateRegistered", data.dateRegistered);
setValue("renewedFrom", data.renewedFrom);
setValue("renewalDate", data.renewalDate);
setValue("renewedTo", data.renewedTo);
setValue("region", data.region);
setValue("zone", data.zone);
setValue("woreda", data.woreda);
setValue("kebele", data.kebele);
setValue("houseNo", data.houseNo);
setValue("licenceNumber", data.licenceNumber, dirty);
setValue("statusDescription", data.statusDescription, dirty);
setValue("dateRegistered", data.dateRegistered, dirty);
setValue("renewedFrom", data.renewedFrom, dirty);
setValue("renewalDate", data.renewalDate, dirty);
setValue("renewedTo", data.renewedTo, dirty);
setValue("region", data.region, dirty);
setValue("zone", data.zone, dirty);
setValue("woreda", data.woreda, dirty);
setValue("kebele", data.kebele, dirty);
setValue("houseNo", data.houseNo, dirty);
// companyAddress is composed reactively from the address fields below, so
// setting region/zone/woreda/kebele/houseNo above is enough — no need to
// compose it here. companyPhone is derived below (identity → eTrade →
@@ -292,6 +318,7 @@ export default function CompanyProfileForm({
setValue(
"etradePhone",
data.managerPhone || data.regularPhone || data.mobilePhone,
dirty,
);
setEtradeOwner({
@@ -321,28 +348,37 @@ export default function CompanyProfileForm({
setEtradeOwner(null);
};
// companyEmail/companyPhone are no longer typed — the Fayda-verified owner
// companyEmail/companyPhone are derived, not typed — the Fayda-verified owner
// is the highest-trust source (that's the whole point of verifying), eTrade's
// registered number and the account email/phone are the fallbacks used
// before verification happens.
//
// `firstValid*`, not `??`: these sources are optional AND unreliable. Fayda's
// email/phone claims can come back empty, and eTrade's registered phone is
// free text that arrives as things like "09 " (→ "+2519"). `??` stops
// at the first non-null, so a junk value became a field with no input and a
// 400 from the API on a value the customer never typed. Skip anything that
// isn't usable and fall through.
//
// When every source really is unusable the fields become editable below
// rather than blocking — the API requires a company email and phone at
// submit (REQUIRED_COMPANY_INFO), so leaving no way to supply them is a dead
// end.
const derivedEmail = firstValidEmail(identity?.owner.email, user.email);
const derivedPhone = firstValidPhone(
identity?.owner.phone,
etradeOwner?.phone,
user.phoneNumber,
);
useEffect(() => {
setValue("companyEmail", identity?.owner.email ?? user.email ?? "", {
shouldValidate: true,
});
if (derivedEmail) setValue("companyEmail", derivedEmail);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [identity?.owner.email, user.email, rehydrate]);
}, [derivedEmail, rehydrate]);
useEffect(() => {
setValue(
"companyPhone",
identity?.owner.phone ??
etradeOwner?.phone ??
toEthiopianE164(user.phoneNumber) ??
"",
{ shouldValidate: true },
);
if (derivedPhone) setValue("companyPhone", derivedPhone);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [identity?.owner.phone, etradeOwner?.phone, user.phoneNumber, rehydrate]);
}, [derivedPhone, rehydrate]);
// "Same as …" links. A checked card prefills the target step's fields from the
// source step and disables them (kept mirrored while linked); unchecking clears
@@ -352,6 +388,16 @@ export default function CompanyProfileForm({
const [gmSameAsOwner, setGmSameAsOwner] = useState(
identity?.gmSameAsOwner ?? false,
);
// `identity` is undefined on the first render (the requirements query is still
// in flight), so the initial state above freezes at `false` — adopt the
// server's declaration the moment it lands, or a resumed draft shows an
// unticked box over a GM that is linked server-side.
const identityLoaded = useRef(false);
useEffect(() => {
if (!identity || identityLoaded.current) return;
identityLoaded.current = true;
setGmSameAsOwner(identity.gmSameAsOwner);
}, [identity]);
const [contactSameAsGm, setContactSameAsGm] = useState(false);
// General Manager source. The company step's email/phone are seeded from
@@ -365,16 +411,26 @@ export default function CompanyProfileForm({
// A Fayda-verified owner outranks eTrade's registered owner — it's the
// higher-trust source, and the whole point of proving identity is to stop
// trusting typed/looked-up data for this.
const gmSourceName =
identity?.owner.name ?? etradeOwner?.name ?? user.name?.en ?? "";
const gmSourceEmail =
identity?.owner.email ?? (companyEmail || user.email || "");
const gmSourcePhone =
identity?.owner.phone ??
companyPhone ??
etradeOwner?.phone ??
toEthiopianE164(user.phoneNumber) ??
"";
const gmSourceName = firstPresent(
identity?.owner.name,
etradeOwner?.name,
user.name?.en,
);
const gmSourceEmail = firstValidEmail(
identity?.owner.email,
companyEmail,
user.email,
);
// Same reason as `derivedPhone`: this value is written into
// `generalManagerPhone`, which the API validates with `@IsValidPhone()`, so an
// unusable eTrade number here 400s the personnel step instead.
const gmSourcePhone = firstValidPhone(
identity?.owner.phone,
companyPhone,
etradeOwner?.phone,
user.phoneNumber,
);
useEffect(() => {
if (!gmSameAsOwner) return;
@@ -458,10 +514,24 @@ export default function CompanyProfileForm({
const gmEstablished =
gmVerified || (identity ? !identity.faydaRequired && gmTyped : gmTyped);
/** Same rule for the representative: verified, or typed where Fayda is optional. */
/**
* Same rule for the representative: verified, or entered where Fayda is
* optional.
*
* Matches the API's own rule (`REQUIRED_POA_FIELDS`): a typed representative
* counts once they have a name, an email and a phone. The step now renders
* inputs for all three, so this is something the customer can actually
* satisfy — previously it gated on `poaName`, for which no input existed
* anywhere, leaving a foreign freight forwarder permanently stuck.
*/
const poaTyped = Boolean(
watch("poaName")?.trim() &&
watch("poaEmail")?.trim() &&
watch("poaPhone")?.trim(),
);
const poaEstablished =
(identity?.poa.verified ?? false) ||
(identity ? !identity.faydaRequired && Boolean(watch("poaName")?.trim()) : false);
(identity ? !identity.faydaRequired && poaTyped : false);
// While linked, mirror the source values into the (disabled) target fields so
// the copy stays current even if the user goes back and edits the source.
@@ -616,8 +686,12 @@ export default function CompanyProfileForm({
// Until then the upload is hidden: there is no representative for the paper
// to authorise, and a freight forwarder is held on the verification gate
// below rather than on a file field it cannot yet fill.
const poaProvided = identity?.poa.verified ?? false;
const delegationRequired = poaProvided;
const poaProvided = (identity?.poa.verified ?? false) || poaTyped;
// A freight forwarder owes the paper whether or not its representative could
// verify with Fayda — the API demands it at completion either way. Keying
// this on the verification alone hid the upload from a foreign forwarder and
// then failed them on submit for a file they were never shown.
const delegationRequired = poaProvided || requirePoa;
const delegationPresent =
(uploadedDocumentKeys ?? []).includes(POA_DELEGATION_FILE_KEY) ||
(() => {
@@ -625,15 +699,63 @@ export default function CompanyProfileForm({
return Array.isArray(v) ? v.length > 0 : v != null;
})();
/**
* Collect the messages for a set of fields into one sentence.
*
* A failed `trigger()` used to return silently, so Continue simply did
* nothing — and every field whose input is conditionally rendered (or derived
* and never rendered at all) turned into an invisible dead end. Naming the
* failures is the whole point: the ones worth reporting are exactly the ones
* with no error text on screen to read.
*/
const describeErrors = (fields: (keyof FormData)[]): string => {
// Re-parse rather than read `errors`: that's the render-time snapshot, and
// this runs immediately after an `await trigger()` that has not re-rendered
// yet, so the closure would still be holding the previous attempt's state.
const parsed = buildOnboardingSchema(
identity?.passportRequired === true,
).safeParse(getValues());
const wanted = new Set<string>(fields as string[]);
const messages = parsed.success
? []
: parsed.error.issues
.filter((i) => wanted.has(String(i.path[0])))
.map((i) => i.message);
return messages.length > 0
? `Please fix: ${[...new Set(messages)].join(", ")}.`
: "Some details on this step are incomplete. Please review the fields above.";
};
/**
* The fields this step actually validates. `stepFields` covers what the step
* always renders; the company step additionally exposes company email/phone
* as inputs when nothing could be derived for them, and a field is validated
* exactly when the customer can see and fix it.
*/
const fieldsForStep = (s: CompanyStep): (keyof FormData)[] => {
if (s !== "company" || !identity) return stepFields[s];
return [
...stepFields.company,
...(derivedEmail ? [] : (["companyEmail"] as const)),
...(derivedPhone ? [] : (["companyPhone"] as const)),
];
};
/** Validate + persist the current step, returning whether we may advance. */
const saveCurrentStep = async (): Promise<boolean> => {
setSaveError(null);
const isValid = await trigger(stepFields[step]);
if (!isValid) return false;
const fields = fieldsForStep(step);
const isValid = await trigger(fields);
if (!isValid) {
setSaveError(describeErrors(fields));
return false;
}
if (!onSaveStep) return true;
setSaving(true);
try {
const res = await onSaveStep(stepPayload(step, watch()));
const res = await onSaveStep(
stepPayload(step, getValues(), dirtyFields),
);
if (!res.ok) {
setSaveError(res.error);
return false;
@@ -676,7 +798,14 @@ export default function CompanyProfileForm({
}
setSaveError(null);
handleSubmit((data) => onSubmit(buildPayload(data, user)))();
// Deliberately NOT `handleSubmit`: that re-validated all 34 schema fields
// — including every field belonging to a step that isn't on screen — and
// on failure did nothing at all, no alert and no navigation, which is the
// "Submit for review" button that appears dead. Each step has already
// validated and saved its own fields, and the API's `markOnboardingComplete`
// is the authority on what is still outstanding; its message reaches the
// customer through `submitError`.
onSubmit(buildPayload(getValues(), user));
return;
}
// The TIN must resolve to a real eTrade record before anything else on
@@ -728,15 +857,40 @@ export default function CompanyProfileForm({
setDocumentFieldErrors({
[POA_DELEGATION_FILE_KEY]: "DARS delegation paper is required",
});
// Validate the text fields too, so every problem shows at once.
const fieldsOk = await trigger(stepFields.poa);
setSaveError(
requirePoa
? "Freight forwarders must provide Power of Attorney details and the DARS delegation paper."
: "Upload the DARS delegation paper for the Power of Attorney you entered, or clear the PoA details to skip.",
[
requirePoa
? "Freight forwarders must provide Power of Attorney details and the DARS delegation paper."
: "Upload the DARS delegation paper for the Power of Attorney you entered, or clear the PoA details to skip.",
fieldsOk ? null : describeErrors(stepFields.poa),
]
.filter(Boolean)
.join(" "),
);
// Fall through to validate the text fields too, so every problem shows at once.
await trigger(stepFields.poa);
return;
}
// The API will not accept the PoA's details until the paper evidencing the
// delegation is actually on file, so the selection made on this step has to
// be uploaded before the save — not held back until the documents step,
// which is unreachable while this save keeps failing.
if (step === "poa" && delegationRequired && onUploadDocuments) {
const pending = documentFiles[POA_DELEGATION_FILE_KEY];
const hasPending = Array.isArray(pending) ? pending.length > 0 : pending != null;
if (hasPending) {
setSaving(true);
try {
const res = await onUploadDocuments();
if (!res.ok) {
setSaveError(res.error);
return;
}
} finally {
setSaving(false);
}
}
}
// Field steps validate + save before advancing.
const ok = await saveCurrentStep();
if (!ok) return;
@@ -812,6 +966,42 @@ export default function CompanyProfileForm({
{...register("ownerPassportNumber")}
/>
)}
{/* Normally derived from the verified owner (falling back
to eTrade and the account), and shown read-only. Fayda's
email and phone claims are optional though, so when
every source comes up empty these become typeable —
the API requires both at submit, and having no input
for them is otherwise an unrecoverable dead end. */}
<SimpleGrid cols={2} spacing="md">
{derivedEmail ? (
<ReadOnlyField
label="Company email"
value={derivedEmail}
/>
) : (
<TextInput
label="Company Email"
type="email"
description="We couldn't find one on your verified identity or account — please enter it."
placeholder="company@example.com"
error={errors.companyEmail?.message}
{...register("companyEmail")}
/>
)}
{derivedPhone ? (
<ReadOnlyField
label="Company phone"
value={derivedPhone}
/>
) : (
<ControlledPhoneField
control={control}
name="companyPhone"
label="Company Phone"
required
/>
)}
</SimpleGrid>
</>
)}
</StepSection>
@@ -835,6 +1025,7 @@ export default function CompanyProfileForm({
onDataLoaded={handleETradeDataLoaded}
onStatusChange={setTinStatus}
onReset={handleETradeReset}
alreadyVerified={hasRegistrationDetails}
/>
{tinVerified && (
<ETradeCompanyCard
@@ -924,7 +1115,10 @@ export default function CompanyProfileForm({
<Text fw={600} size="sm" c="edr-text">
Contact Person
</Text>
{watch("generalManagerName") && (
{/* `gmName`, not the raw form field: a Fayda-verified GM never
fills `generalManagerName`, so gating on it hid this card from
every Ethiopian company — the majority case. */}
{gmName && (
<LinkCheckboxCard
checked={contactSameAsGm}
onToggle={toggleContactSameAsGm}
@@ -983,21 +1177,51 @@ export default function CompanyProfileForm({
required={requirePoa}
/>
)}
{/* The address comes from the Fayda claim along with the name,
so it is shown on the panel rather than typed. Only a company
whose representative may hold no Fayda ID still types it. */}
{/* A verified representative's details come from the Fayda claim
and are shown on the panel above. Where Fayda cannot be
required — a foreign company whose representative may hold no
Fayda ID — they are typed here instead. They have to be: the
API refuses to save a freight forwarder's PoA without a name,
email and phone (`REQUIRED_POA_FIELDS`), and before this the
step rendered no input for any of them, so the customer was
told to "add the poa name, poa email, poa phone" with nowhere
to add them. */}
{!identity?.poa.verified && !identity?.faydaRequired && (
<TextInput
label="PoA Location"
placeholder="City, Country"
error={errors.poaLocation?.message}
{...register("poaLocation")}
/>
<>
<TextInput
label="Representative's Name"
placeholder="Abebe Bikila"
error={errors.poaName?.message}
{...register("poaName")}
/>
<SimpleGrid cols={2} spacing="md">
<TextInput
label="Representative's Email"
type="email"
placeholder="poa@company.com"
error={errors.poaEmail?.message}
{...register("poaEmail")}
/>
<ControlledPhoneField
control={control}
name="poaPhone"
label="Representative's Phone"
/>
</SimpleGrid>
<TextInput
label="PoA Location"
placeholder="City, Country"
error={errors.poaLocation?.message}
{...register("poaLocation")}
/>
</>
)}
{/* The paper authorises the representative the verification
named, so it only has meaning once one exists. */}
{poaProvided && poaDocumentSetting && (
{/* The paper authorises the representative, so it shows once one
exists — or straight away for a freight forwarder, who owes it
either way and must not be failed on submit for a file the
step never offered. */}
{delegationRequired && poaDocumentSetting && (
<>
<Divider my="sm" />
<SmartFileInput

View File

@@ -17,6 +17,11 @@ import { ReadOnlyField } from "./ReadOnlyField";
* supplied a value, but falls back to an editable input when eTrade left it
* blank — otherwise a gap in eTrade's own data would leave the field
* permanently empty and the user stuck (zod requires all of these).
*
* A value that fails validation unlocks the same way. eTrade (or a row saved
* before the current rules) can supply something the schema rejects, and a
* rejected value rendered read-only is a step that can never be completed and
* never says why.
*/
function LockedField({
label,
@@ -32,7 +37,7 @@ function LockedField({
errors: FieldErrors<FormData>;
}) {
const value = watch(name) as string | undefined;
if (value && value.trim()) {
if (value && value.trim() && !errors[name]) {
return <ReadOnlyField label={label} value={value} />;
}
return (
@@ -96,7 +101,12 @@ export default function ETradeCompanyCard({
<ReadOnlyField label="Renewal Date" value={watch("renewalDate")} />
<ReadOnlyField label="Renewed From" value={watch("renewedFrom")} />
<ReadOnlyField label="Renewed To" value={watch("renewedTo")} />
{region && region.trim() ? (
{/* Membership of the catalog, not mere presence: eTrade's normalizer
returns null for a region it doesn't recognise, and older rows can
hold a spelling that isn't in the list. Showing such a value
read-only left the customer with a required field they could not
correct. */}
{(ETHIOPIAN_REGIONS as readonly string[]).includes(region ?? "") ? (
<ReadOnlyField label="Region" value={region} />
) : (
<Controller

View File

@@ -1,8 +1,72 @@
import type { AuthUser } from "@/types/auth";
import type { CreateCompanyPayload } from "@/services/companies.service";
import type { ProfileResponse, UpdateProfilePayload } from "@/types/profile";
import type { CompanyIdentityState } from "@/services/verifayda.service";
import { isValidPhone, toEthiopianE164 } from "@/components/PhoneField";
import type { CompanyStep, FormData } from "./schema";
import { ETRADE_BUNDLE_FIELDS, type CompanyStep, type FormData } from "./schema";
/**
* First value that is actually present.
*
* `??` is wrong for these: an identity claim Fayda returned as an empty string
* is not a value, but it isn't null either, so `??` would stop there and hand
* the form a blank it has no input to fix.
*/
export const firstPresent = (...values: (string | null | undefined)[]): string =>
values.find((v) => v && v.trim())?.trim() ?? "";
/**
* First candidate that is actually a usable phone number, normalized to E.164.
*
* Presence is not enough here. eTrade's registered phone is free text and comes
* back as things like `"09 "`, which normalizes to `+2519` — non-empty,
* so a "first present" pick would take it, hand it to a field with no input,
* and have the API reject the whole save with
* "companyPhone must be a valid international phone number" for something the
* customer never typed. Skip a source that cannot produce a valid number and
* fall through to the next one.
*/
export const firstValidPhone = (
...values: (string | null | undefined)[]
): string => {
for (const raw of values) {
if (!raw || !raw.trim()) continue;
const e164 = toEthiopianE164(raw);
if (e164 && isValidPhone(e164)) return e164;
}
return "";
};
/** Same idea for email: a malformed claim must not become an unfixable field. */
export const firstValidEmail = (
...values: (string | null | undefined)[]
): string => {
const ok = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return values.find((v) => v && ok.test(v.trim()))?.trim() ?? "";
};
/**
* Fayda reports a person's phone as the national registry holds it, which is
* routinely a local number ("0911223344"). Every phone the forms validate and
* submit is E.164, so normalize on the way in — the API now stores new
* verifications normalized, but rows verified before that still hold raw claims.
*/
export function normalizeIdentityPhones(
identity?: CompanyIdentityState,
): CompanyIdentityState | undefined {
if (!identity) return identity;
const fix = <T extends { phone: string | null }>(person: T): T => ({
...person,
phone: person.phone ? toEthiopianE164(person.phone) : person.phone,
});
return {
...identity,
owner: fix(identity.owner),
poa: fix(identity.poa),
gm: fix(identity.gm),
};
}
/** Last 9 digits (Ethiopian national significant number) for tolerant compare. */
export const phoneDigits = (p?: string | null) =>
@@ -44,34 +108,35 @@ export function buildPayload(
};
}
/** Map one wizard step's form values to the profile-update payload it saves. */
/**
* Map one wizard step's form values to the profile-update payload it saves.
*
* `dirty` is react-hook-form's `dirtyFields`. The eTrade-owned keys (and the
* TIN) ride along only when the customer actually changed them this session —
* see `ETRADE_BUNDLE_FIELDS`. Everything else is unconditional: the API treats
* an absent key as "untouched", so omitting a field never clears it.
*/
export function stepPayload(
step: CompanyStep,
d: FormData,
dirty: Partial<Record<keyof FormData, unknown>> = {},
): Partial<UpdateProfilePayload> {
switch (step) {
case "company":
case "company": {
const etrade: Partial<UpdateProfilePayload> = {};
for (const key of ETRADE_BUNDLE_FIELDS) {
if (dirty[key]) (etrade as Record<string, unknown>)[key] = d[key];
}
if (dirty.tinNumber) etrade.tin = d.tinNumber;
return {
companyName: d.companyName,
companyEmail: d.companyEmail,
companyPhone: d.companyPhone,
companyAddress: d.companyAddress,
tin: d.tinNumber,
vatNumber: d.vatNumber,
ownerPassportNumber: d.ownerPassportNumber || undefined,
licenceNumber: d.licenceNumber,
statusDescription: d.statusDescription,
dateRegistered: d.dateRegistered,
renewedFrom: d.renewedFrom,
renewalDate: d.renewalDate,
renewedTo: d.renewedTo,
region: d.region,
zone: d.zone,
woreda: d.woreda,
kebele: d.kebele,
houseNo: d.houseNo,
etradePhone: d.etradePhone,
...etrade,
};
}
case "personnel":
return {
generalManagerName: d.generalManagerName,
@@ -86,7 +151,12 @@ export function stepPayload(
contactPersonPhone: d.contactPersonPhone,
};
case "poa":
return { poaLocation: d.poaLocation || undefined };
return {
poaName: d.poaName || undefined,
poaEmail: d.poaEmail || undefined,
poaPhone: d.poaPhone || undefined,
poaLocation: d.poaLocation || undefined,
};
default:
return {};
}

View File

@@ -0,0 +1,180 @@
import { describe, expect, it } from "vitest";
import { onboardingSchema, stepFields } from "./schema";
import {
firstPresent,
firstValidEmail,
firstValidPhone,
normalizeIdentityPhones,
stepPayload,
} from "./helpers";
import type { FormData } from "./schema";
import type { CompanyIdentityState } from "@/services/verifayda.service";
/** A minimally-valid form, so each case can vary one field at a time. */
const values = (over: Partial<FormData> = {}): FormData =>
({
companyName: "Acme PLC",
companyEmail: "acme@example.com",
companyPhone: "+251911223344",
companyAddress: "1, Bole, Bole, Addis Ababa",
etradePhone: "+251911223344",
tinNumber: "0012345678",
vatNumber: "0012345678",
ownerPassportNumber: "",
licenceNumber: "LIC-1",
statusDescription: "Active",
dateRegistered: "2020-01-01",
renewedFrom: "",
renewalDate: "",
renewedTo: "",
region: "Addis Ababa",
zone: "Bole",
woreda: "03",
kebele: "07",
houseNo: "1",
contactPersonName: "Jane Smith",
contactPersonPosition: "",
contactPersonEmail: "",
contactPersonPhone: "+251911223344",
generalManagerName: "",
generalManagerEmail: "",
generalManagerPhone: "",
poaName: "",
poaPhone: "",
poaAddress: "",
poaEmail: "",
poaLocation: "",
...over,
}) as FormData;
const errorFor = (data: FormData, field: keyof FormData) => {
const parsed = onboardingSchema.safeParse(data);
if (parsed.success) return undefined;
return parsed.error.issues.find((i) => i.path[0] === field)?.message;
};
describe("VAT number", () => {
it("accepts exactly ten digits", () => {
expect(errorFor(values({ vatNumber: "0012345678" }), "vatNumber")).toBeUndefined();
});
// `.length(10)` used to pass this, so a ten-letter string reached the API.
it("rejects ten non-digits", () => {
expect(errorFor(values({ vatNumber: "ABCDEFGHIJ" }), "vatNumber")).toBe(
"VAT number must be exactly 10 digits",
);
});
it("rejects blank", () => {
expect(errorFor(values({ vatNumber: "" }), "vatNumber")).toBe(
"VAT number is required",
);
});
});
describe("region", () => {
it("rejects a spelling outside the catalog", () => {
expect(errorFor(values({ region: "Addis Abeba City" }), "region")).toBe(
"Region is required",
);
});
});
describe("stepFields", () => {
// The regression this whole change exists to prevent: a step must not gate on
// a field it renders no input for, or Continue fails with the error attached
// to nothing on screen.
it("never gates the company step on a derived or read-only field", () => {
const unreachable = [
"companyEmail",
"companyPhone",
"companyAddress",
"etradePhone",
"licenceNumber",
"statusDescription",
"dateRegistered",
"renewedFrom",
"renewalDate",
"renewedTo",
];
expect(
stepFields.company.filter((f) => unreachable.includes(f)),
).toEqual([]);
});
});
describe("stepPayload (company)", () => {
it("omits the eTrade bundle when nothing was re-verified", () => {
const payload = stepPayload("company", values(), {});
expect(payload.tin).toBeUndefined();
expect(payload.region).toBeUndefined();
expect(payload.licenceNumber).toBeUndefined();
// The customer's own fields still save.
expect(payload.vatNumber).toBe("0012345678");
});
it("includes the bundle and the TIN once they are dirty", () => {
const payload = stepPayload("company", values(), {
tinNumber: true,
region: true,
});
expect(payload.tin).toBe("0012345678");
expect(payload.region).toBe("Addis Ababa");
// Still only the dirty ones.
expect(payload.licenceNumber).toBeUndefined();
});
});
describe("firstPresent", () => {
it("skips empty strings rather than stopping at them", () => {
expect(firstPresent("", " ", "second@example.com")).toBe(
"second@example.com",
);
expect(firstPresent(null, undefined, "")).toBe("");
});
});
describe("firstValidPhone", () => {
// Observed live: eTrade returned "09 " for a real TIN. It normalizes to
// "+2519", which is non-empty — so a presence check took it, put it in a field
// with no input, and the API rejected the whole step.
it("skips an eTrade number that cannot make a valid E.164", () => {
expect(firstValidPhone("09 ", "+251911223344")).toBe("+251911223344");
});
it("normalizes a local number it can use", () => {
expect(firstValidPhone("0911223344")).toBe("+251911223344");
});
it("returns empty when no source is usable, so the field falls back to an input", () => {
expect(firstValidPhone("09 ", "", null)).toBe("");
});
});
describe("firstValidEmail", () => {
it("skips a malformed claim", () => {
expect(firstValidEmail("not-an-email", "real@example.com")).toBe(
"real@example.com",
);
});
});
describe("normalizeIdentityPhones", () => {
it("converts a local Fayda phone claim to E.164", () => {
const identity = {
faydaRequired: true,
passportRequired: false,
owner: { verified: true, name: "A", phone: "0911223344", email: null, address: null, verifiedAt: null, passportNumber: null },
poa: { verified: false, name: null, phone: null, email: null, address: null, verifiedAt: null },
gm: { verified: false, name: null, phone: "251911223344", email: null, address: null, verifiedAt: null },
gmSameAsOwner: false,
complete: false,
} as CompanyIdentityState;
const fixed = normalizeIdentityPhones(identity)!;
expect(fixed.owner.phone).toBe("+251911223344");
expect(fixed.gm.phone).toBe("+251911223344");
expect(fixed.poa.phone).toBeNull();
});
});

View File

@@ -26,10 +26,11 @@ export const onboardingSchema = z.object({
// can diverge without the backend's eTrade-authenticity check misfiring.
etradePhone: z.string().optional(),
tinNumber: z.string().regex(/^\d{10}$/, "TIN must be exactly 10 digits"),
// `.length(10)` alone accepted "ABCDEFGHIJ" — the check has to be on digits.
vatNumber: z
.string()
.min(1, "VAT number is required")
.length(10, "VAT number must be exactly 10 digits"),
.regex(/^\d{10}$/, "VAT number must be exactly 10 digits"),
// The owner's passport number — the foreign-company identity credential
// (Fayda is an Ethiopian national ID). Required only for a foreign company;
// enforced in buildOnboardingSchema since that depends on `nationality`.
@@ -134,22 +135,47 @@ export function buildOnboardingSchema(
});
}
/**
* The keys eTrade owns. They are only resent when the customer actually
* re-verified the TIN this session: the API reacts to *any* of them by issuing
* a live eTrade lookup (`applyEtradeSourcedFields`) whose transport failures
* come back as a 400, so echoing unchanged values back would let an eTrade
* outage block a save the customer never made.
*/
export const ETRADE_BUNDLE_FIELDS = [
"companyName",
"licenceNumber",
"statusDescription",
"dateRegistered",
"renewedFrom",
"renewalDate",
"renewedTo",
"region",
"zone",
"woreda",
"kebele",
"houseNo",
"etradePhone",
] as const satisfies readonly (keyof FormData)[];
/**
* What each step validates before it may advance.
*
* Hard rule: a key belongs here only if that step renders an input the customer
* can actually correct it in. `companyEmail`/`companyPhone` are derived from the
* Fayda identity / eTrade / the account and have no input of their own, and the
* read-only eTrade fields cannot be edited at all — listing them meant a value
* the customer never typed could fail zod with its error message attached to
* nothing on screen, which reads as a Continue button that silently does
* nothing. The server still enforces its own required-field list at submit
* (`REQUIRED_COMPANY_INFO`), and reports it with a message.
*/
export const stepFields: Record<CompanyStep, (keyof FormData)[]> = {
company: [
"companyName",
"companyEmail",
"companyPhone",
"companyAddress",
"etradePhone",
"tinNumber",
"vatNumber",
"ownerPassportNumber",
"licenceNumber",
"statusDescription",
"dateRegistered",
"renewedFrom",
"renewalDate",
"renewedTo",
"region",
"zone",
"woreda",
@@ -167,7 +193,11 @@ export const stepFields: Record<CompanyStep, (keyof FormData)[]> = {
"contactPersonEmail",
"contactPersonPhone",
],
poa: ["poaLocation"],
// The API requires poaName/poaEmail/poaPhone from a freight forwarder
// (`REQUIRED_POA_FIELDS`), so the step has to offer them wherever the
// representative isn't proven by Fayda — otherwise the save is rejected
// naming fields the form never rendered.
poa: ["poaName", "poaEmail", "poaPhone", "poaLocation"],
documents: [],
additional: [],
};

View File

@@ -1,4 +1,4 @@
import { isValidPhone, toEthiopianE164 } from "@/components/PhoneField";
import { ControlledPhoneField, isValidPhone } from "@/components/PhoneField";
import { api } from "@/services/api";
import type {
CompanyProfileInput,
@@ -30,6 +30,12 @@ import FaydaVerifyPanel from "@/components/FaydaVerifyPanel";
import ETradeInfo, { type ETradeStatus } from "@/components/onboarding/ETradeInfo";
import { ReadOnlyField } from "@/pages/accounts/companyProfileForm/ReadOnlyField";
import StepSection from "@/pages/accounts/companyProfileForm/StepSection";
import { ETRADE_BUNDLE_FIELDS as SHARED_ETRADE_FIELDS } from "@/pages/accounts/companyProfileForm/schema";
import {
firstValidEmail,
firstValidPhone,
normalizeIdentityPhones,
} from "@/pages/accounts/companyProfileForm/helpers";
export const COMPANY_PROFILE_SCHEMA = z.object({
companyName: z.string().min(1, "Company name is required"),
@@ -43,12 +49,12 @@ export const COMPANY_PROFILE_SCHEMA = z.object({
// no standalone input.
companyAddress: z.string().optional(),
tinNumber: z.string().regex(/^\d{10}$/, "TIN must be exactly 10 digits"),
// Same rule as onboarding — the two forms write the same column, so they must
// not disagree about what is acceptable in it.
vatNumber: z
.string()
.trim()
.max(20, "VAT number is too long")
.optional()
.or(z.literal("")),
.min(1, "VAT number is required")
.regex(/^\d{10}$/, "VAT number must be exactly 10 digits"),
ownerPassportNumber: z.string().optional(),
// Registration/address fields are eTrade-sourced — locked once eTrade
// supplies a value, editable only as an escape hatch when it doesn't
@@ -72,21 +78,13 @@ export const COMPANY_PROFILE_SCHEMA = z.object({
export type CompanyProfileFormData = z.infer<typeof COMPANY_PROFILE_SCHEMA>;
/** UpdateProfilePayload keys eTrade owns — only resent when the customer re-verified them this session. */
const ETRADE_BUNDLE_FIELDS = [
"companyName",
"licenceNumber",
"statusDescription",
"dateRegistered",
"renewedFrom",
"renewalDate",
"renewedTo",
"region",
"zone",
"woreda",
"kebele",
"houseNo",
] as const satisfies readonly (keyof CompanyProfileFormData)[];
/**
* `etradePhone` is not on this form, so the shared list is filtered down to the
* keys it actually holds. Source of truth: `companyProfileForm/schema.ts`.
*/
const ETRADE_FIELDS = SHARED_ETRADE_FIELDS.filter(
(k): k is Exclude<typeof k, "etradePhone"> => k !== "etradePhone",
);
interface TabCompanyProfileProps {
profile?: ProfileResponse;
@@ -166,32 +164,39 @@ export default function TabCompanyProfile({
values: defaultValues,
});
const identity = profile?.identity;
// Fayda stores the phone as the national registry holds it (often a local
// number), which neither this form's E.164 validation nor the API's
// `@IsValidPhone()` accepts. Normalize on read — same as the wizard.
const identity = useMemo(
() => normalizeIdentityPhones(profile?.identity),
[profile?.identity],
);
const verifiedIdentity = identity?.faydaRequired === true;
// companyEmail/companyPhone are the owner's verified contact details, never
// typed — same derivation as the onboarding wizard, just fed from the saved
// profile instead of an in-progress form.
useEffect(() => {
if (!user) return;
setValue("companyEmail", identity?.owner.email ?? user.email ?? "", {
shouldValidate: true,
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [identity?.owner.email, user?.email]);
// profile instead of an in-progress form. `firstValid*` rather than `??`:
// these claims are optional AND unreliable — eTrade's registered phone is
// free text that arrives as things like "09 " — and `??` stops at the
// first non-null, so junk became a read-only field the customer could not
// fix and a 400 on save. When nothing usable can be derived the fields below
// become editable instead of blocking.
const derivedEmail = firstValidEmail(identity?.owner.email, user?.email);
const derivedPhone = firstValidPhone(
identity?.owner.phone,
profile?.etradePhone,
user?.phoneNumber,
);
useEffect(() => {
if (!user) return;
setValue(
"companyPhone",
identity?.owner.phone ??
profile?.etradePhone ??
toEthiopianE164(user.phoneNumber) ??
"",
{ shouldValidate: true },
);
if (derivedEmail) setValue("companyEmail", derivedEmail);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [identity?.owner.phone, profile?.etradePhone, user?.phoneNumber]);
}, [derivedEmail]);
useEffect(() => {
if (derivedPhone) setValue("companyPhone", derivedPhone);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [derivedPhone]);
// companyAddress is composed from the (locked) eTrade address parts, not
// typed directly.
@@ -249,7 +254,7 @@ export default function TabCompanyProfile({
// on every save would otherwise trigger the server's eTrade
// authenticity re-check for no reason.
const etradeBundle: Record<string, string | undefined> = {};
for (const key of ETRADE_BUNDLE_FIELDS) {
for (const key of ETRADE_FIELDS) {
if (dirtyFields[key]) etradeBundle[key] = data[key];
}
if (dirtyFields.tinNumber) etradeBundle.tin = data.tinNumber;
@@ -296,13 +301,32 @@ export default function TabCompanyProfile({
});
const onSubmit = (data: CompanyProfileFormData) => {
setValidationError(null);
if (isCreate && selectedRoles.length === 0) return;
mutation.mutate(data);
};
const saveErrorMessage = mutation.isError
? extractApiError(mutation.error).message
: null;
/**
* Without this, a failed validation made "Save Changes" a no-op: the fields
* the schema requires are largely eTrade-sourced and rendered read-only, so
* their error messages had nowhere to appear and the button simply did
* nothing. Name them instead.
*/
const [validationError, setValidationError] = useState<string | null>(null);
const onInvalid = (formErrors: typeof errors) => {
const messages = Object.values(formErrors)
.map((e) => e?.message)
.filter((m): m is string => Boolean(m));
setValidationError(
messages.length > 0
? `Please fix: ${[...new Set(messages)].join(", ")}.`
: "Some details are incomplete. Please review the fields above.",
);
};
const saveErrorMessage =
validationError ??
(mutation.isError ? extractApiError(mutation.error).message : null);
const pendingOwnerReview = Boolean(
(profile?.pendingChanges as { faydaIdentity?: Record<string, unknown> } | null)
@@ -333,7 +357,7 @@ export default function TabCompanyProfile({
: "Your registration and identity come from eTrade and Fayda — re-verify to refresh them."}
</Text>
<form onSubmit={handleSubmit(onSubmit)}>
<form onSubmit={handleSubmit(onSubmit, onInvalid)}>
<Stack gap="xl">
<StepSection
index={1}
@@ -341,9 +365,9 @@ export default function TabCompanyProfile({
status={watch("vatNumber") ? "done" : "todo"}
>
<TextInput
label="VAT Number (optional)"
label="VAT Number"
placeholder="e.g. 0012345678"
maxLength={20}
maxLength={10}
error={errors.vatNumber?.message}
{...register("vatNumber")}
/>
@@ -389,9 +413,33 @@ export default function TabCompanyProfile({
{...register("ownerPassportNumber")}
/>
)}
{/* Read-only while the verified owner (or eTrade, or the account)
supplies them. Fayda's email/phone claims are optional, so
when nothing can be derived these become typeable — the API
requires both, and showing an empty read-only field is a save
that can never succeed. */}
<SimpleGrid cols={2} spacing="md">
<ReadOnlyField label="Company email" value={watch("companyEmail")} />
<ReadOnlyField label="Company phone" value={watch("companyPhone")} />
{derivedEmail ? (
<ReadOnlyField label="Company email" value={derivedEmail} />
) : (
<TextInput
label="Company Email"
type="email"
description="We couldn't find one on your verified identity or account — please enter it."
error={errors.companyEmail?.message}
{...register("companyEmail")}
/>
)}
{derivedPhone ? (
<ReadOnlyField label="Company phone" value={derivedPhone} />
) : (
<ControlledPhoneField
control={control}
name="companyPhone"
label="Company Phone"
required
/>
)}
</SimpleGrid>
</StepSection>
)}
@@ -410,6 +458,7 @@ export default function TabCompanyProfile({
error={errors.tinNumber?.message}
onDataLoaded={handleETradeDataLoaded}
onStatusChange={setTinStatus}
alreadyVerified={hasRegistrationDetails}
/>
{tinVerified && (
<EtradeLockedCard
@@ -520,7 +569,9 @@ function EtradeLockedCard({
<ReadOnlyField label="Renewal Date" value={watch("renewalDate")} />
<ReadOnlyField label="Renewed From" value={watch("renewedFrom")} />
<ReadOnlyField label="Renewed To" value={watch("renewedTo")} />
{region?.trim() ? (
{/* Membership of the catalog, not mere presence — a stored spelling
outside the list is otherwise uncorrectable. */}
{(ETHIOPIAN_REGIONS as readonly string[]).includes(region ?? "") ? (
<ReadOnlyField label="Region" value={region} />
) : (
<RegionSelect control={control} error={errors.region?.message} />
@@ -548,7 +599,9 @@ function LockedField({
errors: ReturnType<typeof useForm<CompanyProfileFormData>>["formState"]["errors"];
}) {
const value = watch(name) as string | undefined;
if (value?.trim()) {
// A value that fails validation unlocks too — rendering a rejected value
// read-only is a save that can never succeed and never says why.
if (value?.trim() && !errors[name]) {
return <ReadOnlyField label={label} value={value} />;
}
return (

View File

@@ -0,0 +1,122 @@
import { ArrowLeft, Train } from "lucide-react";
import type { ReactNode } from "react";
import { Link } from "react-router-dom";
import type { Section } from "./content";
/** Public pages reachable from every doc page's header and footer. */
const DOC_LINKS = [
{ to: "/help", label: "Help & Support" },
{ to: "/faq", label: "FAQ" },
{ to: "/privacy", label: "Privacy Policy" },
{ to: "/terms", label: "Terms of Service" },
];
interface DocShellProps {
title: string;
subtitle: string;
/** Rendered under the title, e.g. "Last updated 6 August 2026". */
meta?: string;
/** Path of the current page, so it is not linked to itself. */
current: string;
children: ReactNode;
}
/**
* Chrome shared by the help, FAQ and legal pages. These routes are public —
* the auth screens link to them before a session exists — so the shell carries
* its own header instead of relying on the authenticated app layout.
*/
export function DocShell({
title,
subtitle,
meta,
current,
children,
}: DocShellProps) {
return (
<div className="min-h-screen bg-background text-foreground">
<header className="sticky top-0 z-50 border-b border-border bg-background/80 backdrop-blur-xl">
<div className="mx-auto flex max-w-4xl items-center justify-between gap-4 px-6 py-4">
<Link to="/" className="flex items-center gap-3">
<div className="flex size-10 items-center justify-center rounded-2xl bg-primary text-primary-foreground">
<Train className="size-5" />
</div>
<span className="font-bold">EDR Freight</span>
</Link>
<Link
to="/portal"
className="inline-flex items-center gap-2 rounded-2xl border border-border px-4 py-2 text-sm font-semibold transition hover:bg-accent"
>
<ArrowLeft className="size-4" />
Back to portal
</Link>
</div>
</header>
<main className="mx-auto max-w-4xl px-6 py-12">
<h1 className="text-4xl font-black tracking-tight">{title}</h1>
<p className="mt-4 text-lg leading-8 text-muted-foreground">
{subtitle}
</p>
{meta && (
<p className="mt-2 text-sm text-muted-foreground">{meta}</p>
)}
<div className="mt-10">{children}</div>
</main>
<footer className="border-t border-border py-8">
<div className="mx-auto flex max-w-4xl flex-col items-center justify-between gap-4 px-6 text-sm text-muted-foreground md:flex-row">
<span>© 2026 EDR Freight. All rights reserved.</span>
<nav className="flex flex-wrap items-center justify-center gap-x-6 gap-y-2">
{DOC_LINKS.filter((l) => l.to !== current).map((link) => (
<Link
key={link.to}
to={link.to}
className="font-semibold text-foreground transition-colors hover:text-primary"
>
{link.label}
</Link>
))}
</nav>
</div>
</footer>
</div>
);
}
/** Renders a legal document's numbered sections. */
export function DocSections({ sections }: { sections: Section[] }) {
return (
<div className="space-y-10">
{sections.map((section) => (
<section key={section.heading}>
<h2 className="text-xl font-bold tracking-tight">
{section.heading}
</h2>
{section.body?.map((paragraph) => (
<p
key={paragraph}
className="mt-4 leading-7 text-muted-foreground"
>
{paragraph}
</p>
))}
{section.bullets && (
<ul className="mt-4 list-disc space-y-2 pl-5 leading-7 text-muted-foreground">
{section.bullets.map((bullet) => (
<li key={bullet}>{bullet}</li>
))}
</ul>
)}
</section>
))}
</div>
);
}
export default DocShell;

View File

@@ -0,0 +1,59 @@
import { ChevronDown } from "lucide-react";
import { Link } from "react-router-dom";
import { DocShell } from "./DocShell";
import { FAQ_GROUPS, SUPPORT_CONTACT } from "./content";
export default function FaqPage() {
return (
<DocShell
current="/faq"
title="Frequently Asked Questions"
subtitle="Answers to the questions customers ask most about registering, booking cargo and settling invoices on EDR Freight."
>
<div className="space-y-10">
{FAQ_GROUPS.map((group) => (
<section key={group.title}>
<h2 className="text-xl font-bold tracking-tight">{group.title}</h2>
<div className="mt-4 space-y-3">
{group.items.map((item) => (
// Native disclosure: keyboard- and screen-reader-accessible
// without any state of our own.
<details
key={item.question}
className="group rounded-2xl border border-border bg-card px-5 py-4 transition hover:border-primary/40"
>
<summary className="flex cursor-pointer list-none items-center justify-between gap-4 font-semibold">
{item.question}
<ChevronDown className="size-5 shrink-0 text-muted-foreground transition-transform group-open:rotate-180" />
</summary>
<p className="mt-3 leading-7 text-muted-foreground">
{item.answer}
</p>
</details>
))}
</div>
</section>
))}
</div>
<div className="mt-12 rounded-[32px] border border-border bg-card p-8">
<h2 className="text-xl font-bold tracking-tight">
Still need a hand?
</h2>
<p className="mt-2 leading-7 text-muted-foreground">
Our team is on {SUPPORT_CONTACT.email} and {SUPPORT_CONTACT.phone}, or
you can start a chat from the support button inside the portal.
</p>
<Link
to="/help"
className="mt-6 inline-flex rounded-2xl bg-primary px-6 py-3 font-semibold text-primary-foreground transition hover:opacity-90"
>
Go to Help &amp; Support
</Link>
</div>
</DocShell>
);
}

View File

@@ -0,0 +1,183 @@
import {
Clock3,
FileText,
HelpCircle,
Mail,
MapPin,
MessageSquare,
Package,
Phone,
Receipt,
ShieldCheck,
} from "lucide-react";
import { Link } from "react-router-dom";
import { DocShell } from "./DocShell";
import { SUPPORT_CONTACT } from "./content";
const channels = [
{
icon: Mail,
title: "Email",
value: SUPPORT_CONTACT.email,
href: `mailto:${SUPPORT_CONTACT.email}`,
note: "Best for document issues and anything needing an attachment.",
},
{
icon: Phone,
title: "Phone",
value: SUPPORT_CONTACT.phone,
href: `tel:${SUPPORT_CONTACT.phone.replace(/\s/g, "")}`,
note: "Best for urgent problems with cargo already in transit.",
},
{
icon: MapPin,
title: "Head office",
value: SUPPORT_CONTACT.office,
note: "Walk-in support during working hours.",
},
{
icon: Clock3,
title: "Support hours",
value: SUPPORT_CONTACT.hours,
note: "Outside these hours, email us and we reply the next working day.",
},
];
const topics = [
{
icon: ShieldCheck,
title: "Account & onboarding",
body: "Registering your company, uploading your trade licence and TIN, and getting an operational profile approved.",
},
{
icon: FileText,
title: "Contracts",
body: "Requesting a freight contract, reviewing its terms and signing it with your saved signature and stamp.",
},
{
icon: Package,
title: "Bookings & tracking",
body: "Raising a booking against a contract, adding last-mile transport and following the consignment along the corridor.",
},
{
icon: Receipt,
title: "Invoices & payments",
body: "Finding invoices, paying through the bank channels and confirming a payment that has not yet settled.",
},
];
export default function HelpPage() {
return (
<DocShell
current="/help"
title="Help & Support"
subtitle="Get answers fast — browse the common topics, check the FAQ, or reach our team directly."
>
{/* Live chat is the fastest route, so lead with it. */}
<div className="rounded-[32px] border border-border bg-card p-8">
<div className="flex items-start gap-4">
<div className="rounded-2xl bg-accent p-3 text-primary">
<MessageSquare className="size-5" />
</div>
<div>
<h2 className="text-xl font-bold tracking-tight">
Chat with our team
</h2>
<p className="mt-2 leading-7 text-muted-foreground">
Signed-in customers can open a support conversation from the
headset button at the bottom right of every portal page. You can
send screenshots and documents in the chat, and replies appear
there and as a notification.
</p>
<Link
to="/portal"
className="mt-6 inline-flex rounded-2xl bg-primary px-6 py-3 font-semibold text-primary-foreground transition hover:opacity-90"
>
Open the portal
</Link>
</div>
</div>
</div>
<section className="mt-12">
<h2 className="text-xl font-bold tracking-tight">Contact us</h2>
<div className="mt-4 grid gap-4 sm:grid-cols-2">
{channels.map((channel) => (
<div
key={channel.title}
className="flex items-start gap-4 rounded-2xl border border-border bg-background p-5"
>
<div className="rounded-2xl bg-accent p-3 text-primary">
<channel.icon className="size-5" />
</div>
<div>
<p className="font-semibold">{channel.title}</p>
{channel.href ? (
<a
href={channel.href}
className="text-muted-foreground transition-colors hover:text-primary"
>
{channel.value}
</a>
) : (
<p className="text-muted-foreground">{channel.value}</p>
)}
<p className="mt-1 text-sm text-muted-foreground">
{channel.note}
</p>
</div>
</div>
))}
</div>
</section>
<section className="mt-12">
<h2 className="text-xl font-bold tracking-tight">Common topics</h2>
<div className="mt-4 grid gap-4 sm:grid-cols-2">
{topics.map((topic) => (
<Link
key={topic.title}
to="/faq"
className="rounded-2xl border border-border bg-background p-5 transition hover:border-primary/40"
>
<div className="inline-flex rounded-2xl bg-accent p-3 text-primary">
<topic.icon className="size-5" />
</div>
<p className="mt-4 font-semibold">{topic.title}</p>
<p className="mt-1 leading-7 text-muted-foreground">
{topic.body}
</p>
</Link>
))}
</div>
</section>
<section className="mt-12 rounded-[32px] border border-border bg-card p-8">
<div className="flex items-start gap-4">
<div className="rounded-2xl bg-accent p-3 text-primary">
<HelpCircle className="size-5" />
</div>
<div>
<h2 className="text-xl font-bold tracking-tight">
What to include when you contact us
</h2>
<ul className="mt-3 list-disc space-y-2 pl-5 leading-7 text-muted-foreground">
<li>Your company name and the email you sign in with.</li>
<li>
The reference of the contract, booking or invoice involved.
</li>
<li>What you expected to happen and what happened instead.</li>
<li>A screenshot of any error message the portal showed.</li>
</ul>
</div>
</div>
</section>
</DocShell>
);
}

View File

@@ -0,0 +1,15 @@
import { DocSections, DocShell } from "./DocShell";
import { LEGAL_LAST_UPDATED, PRIVACY_SECTIONS } from "./content";
export default function PrivacyPolicyPage() {
return (
<DocShell
current="/privacy"
title="Privacy Policy"
subtitle="How EDR Freight collects, uses, shares and protects the information you provide when you use the platform."
meta={`Last updated ${LEGAL_LAST_UPDATED}`}
>
<DocSections sections={PRIVACY_SECTIONS} />
</DocShell>
);
}

View File

@@ -0,0 +1,15 @@
import { DocSections, DocShell } from "./DocShell";
import { LEGAL_LAST_UPDATED, TERMS_SECTIONS } from "./content";
export default function TermsPage() {
return (
<DocShell
current="/terms"
title="Terms of Service"
subtitle="The terms on which EDR provides the EDR Freight platform and the freight services you request through it."
meta={`Last updated ${LEGAL_LAST_UPDATED}`}
>
<DocSections sections={TERMS_SECTIONS} />
</DocShell>
);
}

View File

@@ -0,0 +1,358 @@
/**
* Copy for the public help/FAQ/legal pages. Kept as data so the pages stay
* thin — the shell in `DocShell.tsx` renders any `Section[]` the same way.
*
* The privacy and terms text is the platform's working draft; legal counsel
* signs off on the final wording, and `LEGAL_LAST_UPDATED` is bumped with it.
*/
export const SUPPORT_CONTACT = {
email: "support@edrfreight.com",
phone: "+251 11 000 0000",
office: "Addis Ababa, Ethiopia",
hours: "Monday Saturday, 8:30 AM 5:30 PM (EAT)",
};
export const LEGAL_LAST_UPDATED = "6 August 2026";
export interface Section {
heading: string;
/** Paragraphs, rendered in order. */
body?: string[];
/** Optional bullet list, rendered after the paragraphs. */
bullets?: string[];
}
export interface FaqItem {
question: string;
answer: string;
}
export interface FaqGroup {
title: string;
items: FaqItem[];
}
export const FAQ_GROUPS: FaqGroup[] = [
{
title: "Getting started",
items: [
{
question: "How do I open an account on EDR Freight?",
answer:
"Sign up with your work email and verify the one-time code we send you. After you set a password, the onboarding wizard collects your company details, trade licence, TIN certificate and the operational services you need (importer, exporter, freight forwarder or transporter). Submit the wizard and our team reviews the application.",
},
{
question: "How long does account approval take?",
answer:
"Most complete applications are reviewed within two working days. You will see the status on your dashboard, and we email you when a profile is approved or when a document needs to be re-uploaded.",
},
{
question: "My profile was rejected. What now?",
answer:
"The rejection notice states the reason. Open Settings, correct the details or replace the document that was flagged, and re-apply — you do not need to create a new account.",
},
{
question: "Can one company hold several operational services?",
answer:
"Yes. A company can hold importer, exporter, freight forwarder and transporter profiles at the same time. Each is approved separately, and the header lets you switch between the ones you hold.",
},
],
},
{
title: "Contracts and bookings",
items: [
{
question: "What is the difference between a contract and a booking?",
answer:
"A contract is the commercial agreement covering a cargo movement — route, commodity, volume and rates. A booking is a single shipment executed under that contract. You create the contract once, then raise bookings against it for each consignment.",
},
{
question: "How do I create a booking?",
answer:
"Open the contract from the Contracts list and choose New Booking. Provide the consignment details, containers or tonnage, and the last-mile requirement if you need one. Bookings can also be started from the Bookings page, which routes you through contract selection first.",
},
{
question: "Why do I have to sign a contract before shipping?",
answer:
"The contract document is the binding agreement for the movement. You must scroll to the end, accept the terms, and sign it with your saved signature and stamp before EDR schedules any wagon against it.",
},
{
question: "Where do I set up my signature and stamp?",
answer:
"Under Signature & Stamp in the portal. It is saved once and reused for every contract you sign, so you do not have to upload it per document.",
},
{
question: "Can I change a booking after submitting it?",
answer:
"You can edit a booking while it is still pending review. Once EDR has confirmed it and allocated capacity, changes go through our operations team — contact support with the booking reference.",
},
{
question: "How do I track a consignment?",
answer:
"Open the booking and use the tracking panel, which shows the current milestone, the wagon or container assigned, and the timestamps recorded at each corridor point.",
},
],
},
{
title: "Invoices and payments",
items: [
{
question: "Where do I find my invoices?",
answer:
"The Invoices page lists every invoice raised against your company, with its status, due date and outstanding balance. Open any invoice to see its line items and download a PDF copy.",
},
{
question: "Which payment methods are supported?",
answer:
"Payments are made through the integrated bank channels shown at checkout. After you complete the payment on the bank's page you are returned to the portal, and the invoice status updates once the bank confirms the transaction.",
},
{
question: "My payment was deducted but the invoice still shows unpaid.",
answer:
"Bank confirmations can lag by a few minutes. Use the Check Payment Status page linked from your receipt; if it still has not settled after an hour, email support with the invoice number and the bank reference and we will reconcile it.",
},
{
question: "Why is my invoice amount rounded?",
answer:
"Some bank channels only accept whole-birr amounts, so invoices routed through them are rounded up to the nearest birr. The rounding is shown on the invoice detail page.",
},
],
},
{
title: "Account and security",
items: [
{
question: "How do I reset my password?",
answer:
"Use Forgot Password on the sign-in page. We email you a reset link that is valid for a limited time. If a member of our staff issued the link, it works the same way even if you are already signed in.",
},
{
question: "Can I add colleagues to my company account?",
answer:
"Yes. Company administrators can invite additional users from Settings. Each user signs in with their own credentials, and actions are recorded against the individual who performed them.",
},
{
question: "How do I update company details after approval?",
answer:
"Edit them in Settings. Changes to regulated fields — trade licence, TIN, legal name — are re-verified by our team before they take effect.",
},
],
},
];
export const PRIVACY_SECTIONS: Section[] = [
{
heading: "1. Introduction",
body: [
"The Ethio-Djibouti Standard Gauge Rail Share Company (\"EDR\", \"we\", \"us\") operates the EDR Freight platform, which lets customers register their business, agree freight contracts, raise bookings, track consignments and settle invoices online.",
"This policy explains what personal and business information we collect through the platform, why we collect it, how long we keep it and what rights you have over it. It applies to the EDR Freight customer portal and the services reached through it.",
],
},
{
heading: "2. Information we collect",
body: [
"We collect information you give us, information generated by your use of the platform, and information we receive from the regulators and financial institutions we work with.",
],
bullets: [
"Account details — name, work email address, phone number and the credentials used to sign in.",
"Company and compliance records — legal name, trade licence, TIN certificate, VAT registration, ownership and manager details, and the operational services you apply for.",
"Identity verification data — where you verify through a national identity service, the verification result and the attributes that service returns to us.",
"Operational data — contracts, bookings, consignment and cargo details, container and wagon assignments, tracking events and delivery confirmations.",
"Financial data — invoices, payment references, transaction status and settlement confirmations received from banks. We do not store your card numbers or online banking credentials.",
"Support data — the messages and files you send us through the in-app support chat or by email.",
"Technical data — IP address, device and browser information, and event logs generated when you use the platform.",
],
},
{
heading: "3. How we use your information",
bullets: [
"To create and administer your account and verify that your company is entitled to the services it applies for.",
"To perform the freight contracts and bookings you place, including allocating capacity and coordinating rail and last-mile movements.",
"To issue invoices, process payments and keep the accounting records the law requires us to keep.",
"To provide customer support and respond to the questions and complaints you raise.",
"To keep the platform secure, detect misuse and investigate incidents.",
"To meet our legal, tax, customs and regulatory obligations in Ethiopia and Djibouti.",
"To improve the platform — measuring which features are used and where users encounter errors, using aggregated and pseudonymised data wherever that is sufficient.",
],
},
{
heading: "4. Legal basis for processing",
body: [
"We process your information because it is necessary to perform the contract between you and EDR, because we have a legal obligation to do so (customs, tax and transport regulation), or because we have a legitimate interest in operating and securing the platform. Where we rely on your consent — for example, optional marketing messages — you can withdraw it at any time.",
],
},
{
heading: "5. Sharing your information",
body: [
"We do not sell your information. We share it only where it is necessary to deliver the service or where the law requires it.",
],
bullets: [
"Government and regulatory bodies — customs, revenue and transport authorities in Ethiopia and Djibouti, to the extent required for the movement of your cargo.",
"Ports, terminals and last-mile transporters involved in executing your bookings.",
"Banks and payment providers, to initiate and reconcile the payments you make.",
"Technology suppliers who host and maintain the platform on our behalf, under contracts that restrict them to processing data on our instructions.",
"Courts, law enforcement and other authorities where we are legally compelled to disclose.",
],
},
{
heading: "6. International transfers",
body: [
"Cross-border freight inherently involves parties in more than one country, so consignment and clearance information is shared with counterparties and authorities in Djibouti as well as Ethiopia. Where we transfer information outside Ethiopia, we do so only as far as the movement requires or the law permits, and we require recipients to protect it to a comparable standard.",
],
},
{
heading: "7. Data retention",
body: [
"We keep account and company records for as long as your account is active. Contract, booking, customs and financial records are kept for the period required by Ethiopian commercial, tax and customs law after the relevant transaction, because we are obliged to be able to produce them. Support conversations and technical logs are kept for a shorter period, sufficient to resolve disputes and investigate security incidents.",
],
},
{
heading: "8. Security",
body: [
"Access to the platform requires authentication, and staff access to customer records is limited to what each role needs. Data is transmitted over encrypted connections and stored on systems protected by access controls and logging. No system is perfectly secure, so please keep your credentials confidential and tell us immediately if you believe your account has been compromised.",
],
},
{
heading: "9. Your rights",
body: [
"Subject to Ethiopian law, you may ask us to give you a copy of the personal information we hold about you, correct it if it is inaccurate, restrict or object to certain processing, or delete it where we are not required to keep it. Requests are handled through the contact details below; we may need to verify your identity before acting.",
],
},
{
heading: "10. Cookies and similar technologies",
body: [
"The platform uses cookies and browser storage to keep you signed in, remember your interface preferences and measure how the product is used so we can fix problems. Essential cookies cannot be turned off without breaking sign-in. You can clear or block the rest through your browser settings.",
],
},
{
heading: "11. Children",
body: [
"The platform is a business service and is not directed at children. We do not knowingly collect information from anyone under 18.",
],
},
{
heading: "12. Changes to this policy",
body: [
"We may update this policy as the platform and the law change. Material changes are announced in the portal before they take effect, and the date at the top of this page always reflects the current version.",
],
},
{
heading: "13. Contact us",
body: [
`Questions about this policy or about how we handle your information can be sent to ${SUPPORT_CONTACT.email}, called in on ${SUPPORT_CONTACT.phone}, or addressed to our head office in ${SUPPORT_CONTACT.office}.`,
],
},
];
export const TERMS_SECTIONS: Section[] = [
{
heading: "1. These terms",
body: [
"These terms govern your use of the EDR Freight platform operated by the Ethio-Djibouti Standard Gauge Rail Share Company (\"EDR\"). By creating an account or using the platform, the company you represent agrees to them.",
"The platform is the channel through which you register, request and manage freight services. The commercial terms of each movement — routes, rates, volumes and payment terms — are set out in the freight contract you sign in the platform. Where a signed contract and these terms conflict, the signed contract governs that movement.",
],
},
{
heading: "2. Eligibility and accounts",
bullets: [
"The platform is for registered businesses. You confirm that you are authorised to act for the company you register and to bind it to these terms.",
"The information and documents you submit — trade licence, TIN, VAT registration, ownership details — must be accurate, current and genuine.",
"Accounts and operational profiles are activated only after EDR has reviewed and approved them, and approval may be refused or withdrawn.",
"You are responsible for keeping credentials confidential and for everything done under your account. Tell us at once if you suspect unauthorised use.",
],
},
{
heading: "3. Contracts and bookings",
bullets: [
"A freight contract takes effect when it is signed in the platform by you and countersigned by EDR.",
"A booking is a request for a specific movement under a contract. It becomes binding when EDR confirms it and allocates capacity — submission alone does not reserve a wagon or container.",
"You are responsible for the accuracy of consignment data: commodity description, weight, dimensions, container numbers, hazardous classification and consignee details.",
"Capacity is finite. EDR may decline, defer or reschedule a booking where capacity, safety, operating conditions or regulatory direction require it.",
],
},
{
heading: "4. Cargo, documents and compliance",
bullets: [
"You must obtain and provide every permit, customs declaration and clearance document the movement requires, and you warrant that the cargo may lawfully be carried.",
"Prohibited and restricted goods may not be tendered without EDR's prior written agreement and any licence the law requires.",
"Cargo must be packed, secured and, where applicable, labelled to the standard the mode of carriage requires. EDR may inspect, refuse or offload cargo that is misdeclared or unsafe.",
"You are liable for fines, demurrage, storage charges and losses arising from misdeclared cargo, missing documents or delays attributable to you.",
],
},
{
heading: "5. Rates, invoicing and payment",
bullets: [
"Charges are calculated from the rates in your contract, the tariffs published in the platform, and any accessorial services actually rendered.",
"Invoices are issued in the platform and are payable by the due date shown on them, through the payment channels the platform offers.",
"Payment is confirmed when the funds are confirmed by the bank, not when payment is initiated.",
"Overdue amounts may attract interest and may result in suspension of new bookings or of the account until the balance is cleared.",
"Taxes and statutory duties are your responsibility unless the contract expressly says otherwise.",
],
},
{
heading: "6. Delivery, delay and liability",
body: [
"Transit times shown in the platform are estimates based on planned schedules. They are not guarantees, and EDR is not liable for indirect or consequential loss, loss of profit or loss of market arising from delay.",
"EDR's liability for loss of or damage to cargo is limited to the extent set out in the applicable freight contract and in the transport law governing the carriage. Claims must be notified in writing within the period the contract specifies; late claims may be rejected.",
"Neither party is liable for failure to perform caused by events beyond its reasonable control, including natural disasters, industrial action, civil unrest, infrastructure failure, or acts of government and regulatory authorities.",
],
},
{
heading: "7. Acceptable use of the platform",
bullets: [
"Use the platform only for its intended purpose and in accordance with applicable law.",
"Do not attempt to gain unauthorised access, probe or disrupt the service, or interfere with other customers' data.",
"Do not scrape, resell or redistribute platform content, rates or data without written permission.",
"Do not upload malware or content that infringes the rights of others.",
],
},
{
heading: "8. Electronic signatures and records",
body: [
"You agree that contracts signed in the platform using your stored signature and stamp are validly executed, that the records the platform keeps of those signatures are admissible evidence of them, and that they carry the same effect as signatures on paper.",
],
},
{
heading: "9. Availability and changes to the service",
body: [
"We aim to keep the platform available, but it may be interrupted for maintenance, upgrades or reasons outside our control. We may add, change or withdraw features. Where a change materially affects how you use the platform, we will give reasonable notice in the portal.",
],
},
{
heading: "10. Suspension and termination",
body: [
"We may suspend or terminate access where these terms are breached, where documents prove to be false, where amounts remain unpaid, or where the law or a regulator requires it. You may stop using the platform at any time. Termination does not affect obligations already incurred — cargo in transit, invoices outstanding, or records we are required to retain.",
],
},
{
heading: "11. Intellectual property",
body: [
"The platform, its software, design and content belong to EDR or its licensors. You are granted a non-exclusive, non-transferable right to use it for your own freight operations. Your commercial and consignment data remains yours; you grant us the right to process it as needed to deliver the service and as described in the Privacy Policy.",
],
},
{
heading: "12. Confidentiality and data protection",
body: [
"Each party will keep the other's non-public commercial information confidential and use it only for the purposes of the services. Our handling of personal information is described in the Privacy Policy, which forms part of these terms.",
],
},
{
heading: "13. Governing law and disputes",
body: [
"These terms are governed by the laws of the Federal Democratic Republic of Ethiopia. The parties will first attempt to resolve any dispute amicably; failing that, the dispute is subject to the jurisdiction of the competent courts of Ethiopia, without prejudice to any arbitration clause agreed in a specific freight contract.",
],
},
{
heading: "14. Changes to these terms",
body: [
"We may update these terms as the service and the law change. Updates are published here and announced in the portal. Continuing to use the platform after an update takes effect means you accept the revised terms.",
],
},
{
heading: "15. Contact",
body: [
`For questions about these terms, write to ${SUPPORT_CONTACT.email} or call ${SUPPORT_CONTACT.phone}.`,
],
},
];

View File

@@ -34,6 +34,16 @@ function humanizeApiMessage(raw: string): string {
return raw;
}
/**
* NestJS's ValidationPipe reports every failed constraint at once, so `message`
* arrives as a string[] rather than a string. Flatten it — passing the array
* through left the UI rendering its entries run together with no separator.
*/
function asMessage(value: unknown): string {
if (Array.isArray(value)) return value.filter(Boolean).join(". ");
return typeof value === "string" ? value : "";
}
export function extractApiError(err: unknown): ApiError {
if (err && typeof err === "object") {
const obj = err as Record<string, unknown>;
@@ -41,13 +51,10 @@ export function extractApiError(err: unknown): ApiError {
if (response) {
const statusCode = response.status as number | undefined;
const data = response.data as Record<string, unknown> | undefined;
const raw = asMessage(data?.message) || asMessage(data?.error);
return {
code: (data?.message as string) || (data?.error as string) || "api_error",
message: humanizeApiMessage(
(data?.message as string) ||
(data?.error as string) ||
"An unexpected error occurred",
),
code: raw || "api_error",
message: humanizeApiMessage(raw || "An unexpected error occurred"),
statusCode,
};
}