This commit is contained in:
Marshal
2026-08-08 14:02:58 +00:00
104 changed files with 8507 additions and 962 deletions

View File

@@ -172,19 +172,29 @@ EIMS_SELLER_LOCALITY=
# Tax treatment — REQUIRES FINANCE SIGN-OFF. The application models no tax at all
# (invoice.taxAmount is always 0), so nothing here is defaulted: registration fails
# locally, naming the missing variables, until these are set.
EIMS_TAX_CODE=0
# Required, and deliberately unset: the choice is a tax position, not a default.
# MoR's enum (from its own 400): TOT10 TOT2 VAT15 VWHT TWHT VATEX VATWH WHOP2 WTHOI VAT0 VWTH
# Pending finance confirmation of VAT0 (zero-rated) vs VATEX (exempt).
EIMS_TAX_CODE=
EIMS_TAX_RATE_PERCENT=0
EIMS_EXCISE_TAX_VALUE=0
EIMS_INCOME_WITHHOLD_VALUE=0
EIMS_TRANSACTION_WITHHOLD_VALUE=0
# Document classification and payment presentation.
EIMS_TRANSACTION_TYPE=B2B
EIMS_NATURE_OF_SUPPLIES=Service
# Lowercase constant: MoR's oneOf branches require exactly 'goods' or 'service'.
EIMS_NATURE_OF_SUPPLIES=service
EIMS_PAYMENT_MODE=CASH
EIMS_PAYMENT_TERM=IMMIDIATE
EIMS_UNIT_DEFAULT=PCS
# MoR numeric country code for the buyer; our companies store the country name.
EIMS_BUYER_COUNTRY_CODE=
# Buyer region name -> MoR numeric code. companies.region holds names; MoR wants ^[0-9]{1,3}$.
# An unmapped region fails locally rather than being filed with a guess.
EIMS_BUYER_REGION_CODES=Addis Ababa=13
# Same mechanism for Wereda. MoR has never named a Wereda regex in an error (only Region's is
# confirmed), so this is precautionary — but an unmapped name still fails locally, not filed as a guess.
EIMS_BUYER_WEREDA_CODES=
EIMS_CASHIER_NAME=
EIMS_SALESPERSON_NAME=
# Automatic filing of issued invoices (@Cron sweep, one invoice per tick).

View File

@@ -50,6 +50,7 @@ import { FileUploadSettingsModule } from "./modules/file-upload-settings/file-up
import { DropdownSettingsModule } from "./modules/dropdown-settings/dropdown-settings.module";
import { ExchangeSettingsModule } from "./modules/exchange-settings/exchange-settings.module";
import { ContractTemplatesModule } from "./modules/contract-templates/contract-templates.module";
import { SupportContentModule } from "./modules/support-content/support-content.module";
import { OtpModule } from "./modules/otp/otp.module";
import { HealthModule } from "./modules/health/health.module";
import { RuleEngineModule } from "./modules/rule-engine/rule-engine.module";
@@ -67,6 +68,7 @@ import { FreightPositionsSeeder } from "./seed/freight-positions.seeder";
import { PaymentModule } from "./modules/payment/payment.module";
// import { PricingDataSeeder } from "./seed/pricing-data.seeder";
import { FileUploadSettingsSeeder } from "./seed/file-upload-settings.seeder";
import { SupportContentSeeder } from "./seed/support-content.seeder";
// import { YardFacilitiesSeeder } from "./seed/yard-facilities.seeder";
// import { IndodeFacilitySeeder } from "./seed/indode-facility.seeder";
// import { Batch14TestDataSeeder } from "./seed/batch1-4-test-data.seeder";
@@ -220,6 +222,7 @@ if (!process.env.APPLICATION_NAME) {
DropdownSettingsModule,
ExchangeSettingsModule,
ContractTemplatesModule,
SupportContentModule,
OtpModule,
HealthModule,
RuleEngineModule,
@@ -260,6 +263,7 @@ if (!process.env.APPLICATION_NAME) {
EdrOrgSeeder,
FreightPositionsSeeder,
FileUploadSettingsSeeder,
SupportContentSeeder,
// YardFacilitiesSeeder,
FreightPermissionKeyMigrationSeeder,
FreightNotificationPermissionsSeeder,
@@ -291,6 +295,7 @@ export class AppModule implements OnApplicationBootstrap {
private readonly edrOrgSeeder: EdrOrgSeeder,
private readonly freightPositionsSeeder: FreightPositionsSeeder,
private readonly fileUploadSettingsSeeder: FileUploadSettingsSeeder,
private readonly supportContentSeeder: SupportContentSeeder,
// private readonly yardFacilitiesSeeder: YardFacilitiesSeeder,
private readonly freightPermissionKeyMigrationSeeder: FreightPermissionKeyMigrationSeeder,
private readonly freightNotificationPermissionsSeeder: FreightNotificationPermissionsSeeder,
@@ -349,6 +354,10 @@ export class AppModule implements OnApplicationBootstrap {
// File upload settings — keep enabled.
await this.fileUploadSettingsSeeder.run();
// Portal help/FAQ/legal copy — keep enabled. Idempotent by emptiness, so
// it fills an empty table once and never touches admin edits afterwards.
await this.supportContentSeeder.run();
// Flags which yards can load/unload cargo (Indode, Sebeta, Modjo, Adama,
// Dire Dawa). Idempotent; creates no yards.
// await this.yardFacilitiesSeeder.run();

View File

@@ -81,6 +81,14 @@ export interface EimsInvoiceConfig {
paymentTerm: string;
unitDefault: string;
buyerCountryCode: string | null;
/**
* Buyer region name → MoR numeric code, from `EIMS_BUYER_REGION_CODES`
* ("Addis Ababa=13,Oromia=4"). A buyer whose region is neither a code nor in this map fails
* locally rather than being filed with a guessed one.
*/
buyerRegionCodes: Record<string, string>;
/** Same mechanism as `buyerRegionCodes`, for `EIMS_BUYER_WEREDA_CODES` ("Yeka=574"). */
buyerWeredaCodes: Record<string, string>;
cashierName: string | null;
salesPersonName: string | null;
}
@@ -103,6 +111,16 @@ const positiveInt = (raw: string | undefined, fallback: number, name: string): n
return value;
};
/** "Addis Ababa=13,Oromia=4" → { "Addis Ababa": "13", Oromia: "4" }. */
const parseCodeMap = (raw: string | undefined): Record<string, string> => {
const map: Record<string, string> = {};
for (const pair of (raw ?? "").split(",")) {
const [name, code] = pair.split("=");
if (name?.trim() && code?.trim()) map[name.trim()] = code.trim();
}
return map;
};
/** Unset stays null so the registration-time check can name it; a set-but-bogus value throws. */
const optionalNumber = (raw: string | undefined, name: string): number | null => {
if (raw === undefined || raw === "") return null;
@@ -168,6 +186,8 @@ export default registerAs("eims", (): EimsConfig => {
paymentTerm: process.env.EIMS_PAYMENT_TERM ?? "",
unitDefault: process.env.EIMS_UNIT_DEFAULT ?? "",
buyerCountryCode: process.env.EIMS_BUYER_COUNTRY_CODE || null,
buyerRegionCodes: parseCodeMap(process.env.EIMS_BUYER_REGION_CODES),
buyerWeredaCodes: parseCodeMap(process.env.EIMS_BUYER_WEREDA_CODES),
cashierName: process.env.EIMS_CASHIER_NAME || null,
salesPersonName: process.env.EIMS_SALESPERSON_NAME || null,
},

View File

@@ -24,7 +24,7 @@ import { MigrationInterface, QueryRunner } from "typeorm";
* ("2025-03-21T08:33:32.707753413Z[Etc/UTC]") that no JS date parser accepts. It is stored
* verbatim so a compliance value is never mangled by a parse.
*/
export class EimsInvoiceRegistration3300000000000 implements MigrationInterface {
export class EimsInvoiceRegistration3330000000000 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`
ALTER TABLE freight.invoices

View File

@@ -0,0 +1,34 @@
import { MigrationInterface, QueryRunner } from "typeorm";
/**
* EIMS document numbering.
*
* MoR validates `DocumentDetails.DocumentNumber` against `^(0|[1-9][0-9]{0,8})$` — a plain integer
* of at most nine digits. Our own `INV-YYYYMMDD-NNNNN` can therefore never be sent, so EIMS needs
* its own sequence, allocated from the same locked state row as the invoice counter and recorded
* on the invoice so a filed document can be traced back to it.
*/
export class EimsDocumentNumberSequence3340000000000 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`
ALTER TABLE freight.eims_system_state
ADD COLUMN IF NOT EXISTS next_document_number bigint NOT NULL DEFAULT 1,
ADD COLUMN IF NOT EXISTS in_flight_document_number bigint
`);
await queryRunner.query(`
ALTER TABLE freight.invoices
ADD COLUMN IF NOT EXISTS eims_document_number varchar(16)
`);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`
ALTER TABLE freight.invoices DROP COLUMN IF EXISTS eims_document_number
`);
await queryRunner.query(`
ALTER TABLE freight.eims_system_state
DROP COLUMN IF EXISTS next_document_number,
DROP COLUMN IF EXISTS in_flight_document_number
`);
}
}

View File

@@ -0,0 +1,73 @@
import { MigrationInterface, QueryRunner } from "typeorm";
/**
* Editable customer-facing copy for the portal's public pages (/help, /faq,
* /terms, /privacy) plus the shared support-contact block, with an append-only
* version log behind it.
*
* `payload` is opaque jsonb: the five documents have genuinely different shapes
* and the help page's blocks change with the copy, so typed columns would mean
* a migration per wording tweak. The shape is enforced by per-slug DTOs on
* write instead.
*
* No rows are inserted here — `SupportContentSeeder` fills the table on first
* boot and skips whenever it is non-empty, so a redeploy never overwrites
* admin edits the way a migration-embedded INSERT eventually would.
*/
export class SupportContent3350000000000 implements MigrationInterface {
name = "SupportContent3350000000000";
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`
CREATE TABLE IF NOT EXISTS freight.support_documents (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
slug varchar(32) NOT NULL,
payload jsonb NOT NULL DEFAULT '{}'::jsonb,
version integer NOT NULL DEFAULT 1,
updated_by_id uuid,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz
);
`);
await queryRunner.query(`
CREATE UNIQUE INDEX IF NOT EXISTS uq_support_documents_slug
ON freight.support_documents (slug);
`);
await queryRunner.query(`
CREATE TABLE IF NOT EXISTS freight.support_document_versions (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
document_id uuid NOT NULL
REFERENCES freight.support_documents(id) ON DELETE CASCADE,
version integer NOT NULL,
payload jsonb NOT NULL,
actor_id uuid,
note varchar(255),
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz
);
`);
// Closes the concurrent-save race: two editors saving at once cannot both
// claim the same version number.
await queryRunner.query(`
CREATE UNIQUE INDEX IF NOT EXISTS uq_support_doc_version
ON freight.support_document_versions (document_id, version);
`);
await queryRunner.query(`
CREATE INDEX IF NOT EXISTS idx_support_doc_versions_document
ON freight.support_document_versions (document_id);
`);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`DROP TABLE IF EXISTS freight.support_document_versions;`,
);
await queryRunner.query(`DROP TABLE IF EXISTS freight.support_documents;`);
}
}

View File

@@ -0,0 +1,112 @@
import { MigrationInterface, QueryRunner } from "typeorm";
/**
* Converts the HELP document from its original fixed-block shape
* (`video` / `chat` / `channels` / `topics` / `checklist`) to the free-form
* `sections[]` builder, where every block is a heading plus markdown plus
* attached media.
*
* Only rows still in the old shape are touched — detected by the presence of a
* `channels` key — so this is a no-op on any environment seeded after the
* change, and re-running it does nothing.
*
* The payload literal is inlined rather than imported from
* `SUPPORT_CONTENT_DEFAULTS`: a migration must keep doing the same thing
* forever, and that constant will keep moving.
*
* The rewrite also bumps `version` and writes a matching history row. The live
* row's version always having a matching entry in
* `support_document_versions` is the invariant the history list and rollback
* both depend on, and a silent payload swap would break it.
*/
const HELP_SECTIONS = [
{
id: "help-walkthrough",
heading: "Portal walkthrough",
body: "A guided tour of the portal — registering your company, raising a booking against a contract, and settling an invoice.",
media: [
{
id: "help-walkthrough-video",
kind: "video",
src: "/assets/edr-portal-guide.webm",
caption: null,
},
],
},
{
id: "help-chat",
heading: "Chat with our team",
body: "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.\n\n[Open the portal](/portal)",
media: [],
},
{
id: "help-contact",
heading: "Contact us",
body: "- **Email** — [{{supportEmail}}](mailto:{{supportEmail}}). Best for document issues and anything needing an attachment.\n- **Phone** — [{{supportPhone}}](tel:{{supportPhoneTel}}). Best for urgent problems with cargo already in transit.\n- **Head office** — {{supportOffice}}. Walk-in support during working hours.\n- **Support hours** — {{supportHours}}. Outside these hours, email us and we reply the next working day.",
media: [],
},
{
id: "help-topics",
heading: "Common topics",
body: "- **[Account & onboarding](/faq)** — registering your company, uploading your trade licence and TIN, and getting an operational profile approved.\n- **[Contracts](/faq)** — requesting a freight contract, reviewing its terms and signing it with your saved signature and stamp.\n- **[Bookings & tracking](/faq)** — raising a booking against a contract, adding last-mile transport and following the consignment along the corridor.\n- **[Invoices & payments](/faq)** — finding invoices, paying through the bank channels and confirming a payment that has not yet settled.",
media: [],
},
{
id: "help-checklist",
heading: "What to include when you contact us",
body: "- Your company name and the email you sign in with.\n- The reference of the contract, booking or invoice involved.\n- What you expected to happen and what happened instead.\n- A screenshot of any error message the portal showed.",
media: [],
},
];
export class SupportHelpSections3360000000000 implements MigrationInterface {
name = "SupportHelpSections3360000000000";
public async up(queryRunner: QueryRunner): Promise<void> {
const rows: { id: string; version: number; payload: Record<string, unknown> }[] =
await queryRunner.query(`
SELECT id, version, payload
FROM freight.support_documents
WHERE slug = 'HELP' AND payload ? 'channels'
`);
for (const row of rows) {
const payload = {
title: row.payload.title ?? "Help & Support",
subtitle:
row.payload.subtitle ??
"Get answers fast — watch the walkthrough, browse the common topics, check the FAQ, or reach our team directly.",
sections: HELP_SECTIONS,
};
const version = row.version + 1;
await queryRunner.query(
`UPDATE freight.support_documents
SET payload = $1::jsonb, version = $2, updated_at = now()
WHERE id = $3`,
[JSON.stringify(payload), version, row.id],
);
await queryRunner.query(
`INSERT INTO freight.support_document_versions
(document_id, version, payload, actor_id, note)
VALUES ($1, $2, $3::jsonb, NULL, $4)`,
[
row.id,
version,
JSON.stringify(payload),
"Converted help page to free-form sections",
],
);
}
}
/**
* Not reversible: the old fixed blocks cannot be recovered from markdown
* sections an editor may since have rewritten. The version history holds the
* pre-conversion payload if it is ever genuinely needed.
*/
public async down(): Promise<void> {
// no-op
}
}

View File

@@ -60,6 +60,8 @@ const context = (over: Partial<EimsMapperContext> = {}): EimsMapperContext => ({
unitDefault: "PCS",
incomeWithholdValue: 0,
transactionWithholdValue: 0,
buyerRegionCodes: { "Addis Ababa": "13" },
buyerWeredaCodes: {},
...over,
});
@@ -130,7 +132,7 @@ describe("toEimsInvoice", () => {
ExciseTaxValue: 0,
TotalLineAmount: 11500,
Unit: "PCS",
NatureOfSupplies: "Service",
NatureOfSupplies: "service",
HarmonizationCode: null,
});
expect(doc.ItemList[1]).toMatchObject({
@@ -207,6 +209,77 @@ describe("toEimsInvoice", () => {
});
});
describe("toEimsInvoice — MoR field constraints", () => {
it("passes a buyer region through when it is already a MoR code", () => {
const doc = toEimsInvoice(invoice(), seller, context());
expect(doc.BuyerDetails.Region).toBe("13");
});
it("maps a region name to its code, ignoring case and spacing", () => {
const doc = toEimsInvoice(
invoice({ company: { ...invoice().company!, region: " addis ababa " } }),
seller,
context({ buyerRegionCodes: { "Addis Ababa": "13" } }),
);
expect(doc.BuyerDetails.Region).toBe("13");
});
it("refuses to file a buyer whose region has no mapping", () => {
expect(() =>
toEimsInvoice(
invoice({ company: { ...invoice().company!, region: "Somewhere Else" } }),
seller,
context(),
),
).toThrow(/not a MoR Region code and has no mapping/);
});
it("refuses a buyer with no region at all rather than guessing one", () => {
expect(() =>
toEimsInvoice(
invoice({ company: { ...invoice().company!, region: null } }),
seller,
context(),
),
).toThrow(/buyer Region \(unset\)/);
});
it("passes a buyer wereda through when it is already a MoR code", () => {
const doc = toEimsInvoice(invoice(), seller, context());
expect(doc.BuyerDetails.Wereda).toBe("574");
});
it("maps a wereda name to its code", () => {
const doc = toEimsInvoice(
invoice({ company: { ...invoice().company!, woreda: "Yeka" } }),
seller,
context({ buyerWeredaCodes: { Yeka: "99" } }),
);
expect(doc.BuyerDetails.Wereda).toBe("99");
});
it("refuses to file a buyer whose wereda has no mapping", () => {
expect(() =>
toEimsInvoice(
invoice({ company: { ...invoice().company!, woreda: "Yeka" } }),
seller,
context({ buyerWeredaCodes: {} }),
),
).toThrow(/buyer Wereda "Yeka".*EIMS_BUYER_WEREDA_CODES/);
});
it("emits NatureOfSupplies lowercase, whatever case it was configured in", () => {
const doc = toEimsInvoice(invoice(), seller, context({ natureOfSupplies: "Service" }));
expect(doc.ItemList[0].NatureOfSupplies).toBe("service");
});
it("rejects a NatureOfSupplies MoR does not accept", () => {
expect(() =>
toEimsInvoice(invoice(), seller, context({ natureOfSupplies: "Services" })),
).toThrow(/must be one of goods, service/);
});
});
describe("formatEimsDate", () => {
it("renders the observed dd-MM-yyyyTHH:mm:ss shape with zero padding", () => {
expect(formatEimsDate(new Date(2025, 2, 21, 0, 0, 0))).toBe("21-03-2025T00:00:00");

View File

@@ -210,6 +210,22 @@ export interface EimsMapperContext {
relatedDocument?: string | null;
/** MoR numeric country code for the buyer; our DB stores the country name. */
buyerCountryCode?: string | null;
/**
* Region name → MoR numeric code, for buyers whose stored region is free text.
*
* `companies.region` holds names ("Addis Ababa") while MoR validates `BuyerDetails.Region`
* against `^[0-9]{1,3}$`. A stored value that is already a code passes through; anything else
* must be in this map or the mapping **fails locally** — sending a guessed region code onto a
* tax document is worse than refusing to file.
*/
buyerRegionCodes: Record<string, string>;
/**
* Wereda name → MoR code, same shape as `buyerRegionCodes`. `companies.woreda` holds names
* ("Yeka") or codes inconsistently; unlike Region, MoR has never named a Wereda regex in an
* error, so this is precautionary rather than confirmed — but the fix is identical either way:
* fail locally on an unmapped name rather than file a guess.
*/
buyerWeredaCodes: Record<string, string>;
buyerIdType?: string | null;
buyerIdNumber?: string | null;
buyerCity?: string | null;
@@ -220,6 +236,22 @@ export interface EimsMapperContext {
formatDate?: (issuedAt: Date) => string;
}
/**
* MoR's own constraint on `Region`: one to three digits, confirmed by its 400 SCHEMA ERROR. Reused
* as the pass-through test for `Wereda` too — every Wereda value MoR has actually shown us (seller
* "12"/"13", the collection's "574") fits the same shape, though MoR has not named a Wereda regex
* the way it named Region's.
*/
const LOCATION_CODE = /^[0-9]{1,3}$/;
/**
* The only two values MoR accepts for `NatureOfSupplies`, lowercase.
*
* Its schema branches on this as a `oneOf` with a `const` per branch, so `"Service"` fails the
* whole `ItemList` — the error reads "must be the constant value 'service'".
*/
const NATURE_OF_SUPPLIES = ["goods", "service"] as const;
const num = (v: number | string): number => {
const n = Number(v);
if (!Number.isFinite(n)) throw new Error(`EIMS mapping: expected a numeric value, got ${String(v)}`);
@@ -240,6 +272,33 @@ export const formatEimsDate = (issuedAt: Date): string =>
* an unissued invoice, unresolved line tax, a line/total mismatch, or a non-ETB invoice with no
* exchange rate.
*/
/**
* A buyer's location value (Region or Wereda) as a MoR code: passed through when already numeric,
* otherwise looked up by name (case- and space-insensitive). Throws when neither applies — sending
* a guessed code onto a tax document is worse than refusing to file.
*/
function resolveLocationCode(
field: "Region" | "Wereda",
value: string | null | undefined,
codes: Record<string, string>,
envVar: string,
invoiceNumber: string,
): string {
const raw = (value ?? "").trim();
if (LOCATION_CODE.test(raw)) return raw;
const key = raw.toLowerCase().replace(/\s+/g, " ");
const mapped = Object.entries(codes).find(
([name]) => name.trim().toLowerCase().replace(/\s+/g, " ") === key,
)?.[1];
if (mapped && LOCATION_CODE.test(mapped)) return mapped;
throw new Error(
`EIMS mapping: invoice ${invoiceNumber} has buyer ${field} ${raw ? `"${raw}"` : "(unset)"}, ` +
`which is not a MoR ${field} code and has no mapping. Add it to ${envVar}.`,
);
}
export function toEimsInvoice(
invoice: EimsMapperInvoice,
seller: EimsSellerDetails,
@@ -266,6 +325,14 @@ export function toEimsInvoice(
throw new Error(`EIMS mapping: invoice ${invoice.invoiceNumber} has an unparseable issuedAt`);
}
const natureOfSupplies = context.natureOfSupplies.trim().toLowerCase();
if (!NATURE_OF_SUPPLIES.includes(natureOfSupplies as (typeof NATURE_OF_SUPPLIES)[number])) {
throw new Error(
`EIMS mapping: NatureOfSupplies must be one of ${NATURE_OF_SUPPLIES.join(", ")}, ` +
`got "${context.natureOfSupplies}"`,
);
}
const ItemList: EimsInvoiceItem[] = invoice.lines.map((line, index) => {
const lineNumber = index + 1;
const tax = context.taxForLine(line, lineNumber);
@@ -285,7 +352,7 @@ export function toEimsInvoice(
Discount: 0,
ExciseTaxValue,
HarmonizationCode: null,
NatureOfSupplies: context.natureOfSupplies,
NatureOfSupplies: natureOfSupplies,
ItemCode: line.chargeType,
ProductDescription: line.description?.trim() || line.chargeType,
PreTaxValue,
@@ -329,12 +396,24 @@ export function toEimsInvoice(
Tin: company.tin,
LegalName: company.name,
Phone: company.phone ?? null,
Region: company.region ?? null,
Region: resolveLocationCode(
"Region",
company.region,
context.buyerRegionCodes,
"EIMS_BUYER_REGION_CODES",
invoice.invoiceNumber,
),
Country: context.buyerCountryCode ?? null,
Zone: company.zone ?? null,
Kebele: company.kebele ?? null,
VatNumber: company.vatNumber ?? null,
Wereda: company.woreda ?? null,
Wereda: resolveLocationCode(
"Wereda",
company.woreda,
context.buyerWeredaCodes,
"EIMS_BUYER_WEREDA_CODES",
invoice.invoiceNumber,
),
},
DocumentDetails: {
DocumentNumber: context.documentNumber,

View File

@@ -115,6 +115,10 @@ export class Invoice extends BaseEntity {
@Column({ name: "eims_irn", type: "varchar", length: 64, nullable: true })
eimsIrn?: string | null;
/** The numeric `DocumentDetails.DocumentNumber` filed for this invoice. */
@Column({ name: "eims_document_number", type: "varchar", length: 16, nullable: true })
eimsDocumentNumber?: string | null;
/** The `SourceSystem.InvoiceCounter` this invoice consumed. */
@Column({ name: "eims_invoice_counter", type: "bigint", nullable: true })
eimsInvoiceCounter?: number | null;

View File

@@ -57,6 +57,37 @@ export function assertEimsInvoiceConfig(config: EimsConfig): void {
`(tax values need finance sign-off — they are deliberately not defaulted): ${missing.join(", ")}`,
});
}
assertSellerFormats(config.invoice);
}
/**
* MoR's own patterns for the seller fields, checked here rather than at the gateway.
*
* A placeholder like `_` is "set" but unfilable, and finding that out costs a real request and a
* consumed counter — these are the exact regexes its 400 SCHEMA ERROR quoted back at us.
*/
const SELLER_FORMATS: { env: string; value: (i: EimsConfig["invoice"]) => string; pattern: RegExp }[] = [
{ env: "EIMS_SELLER_PHONE", value: (i) => i.sellerPhone, pattern: /^\+?[0-9]{6,}$/ },
{
env: "EIMS_SELLER_EMAIL",
value: (i) => i.sellerEmail,
pattern: /^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$/,
},
{ env: "EIMS_SELLER_REGION", value: (i) => i.sellerRegion, pattern: /^[0-9]{1,3}$/ },
{ env: "EIMS_SELLER_WEREDA", value: (i) => i.sellerWereda, pattern: /^[0-9A-Za-z]{1,10}$/ },
];
function assertSellerFormats(invoice: EimsConfig["invoice"]): void {
const bad = SELLER_FORMATS.filter(({ value, pattern }) => !pattern.test(value(invoice))).map(
({ env, pattern }) => `${env} (must match ${pattern.source})`,
);
if (bad.length > 0) {
throw new BadRequestException({
code: "EIMS_INVOICE_CONFIG_INVALID",
message: `EIMS seller details would be rejected by MoR: ${bad.join("; ")}`,
});
}
}
export function buildEimsSeller(config: EimsConfig): EimsSellerDetails {
@@ -112,6 +143,8 @@ export function buildEimsContext(config: EimsConfig, input: EimsContextInput): E
incomeWithholdValue: invoice.incomeWithholdValue!,
transactionWithholdValue: invoice.transactionWithholdValue!,
buyerCountryCode: invoice.buyerCountryCode,
buyerRegionCodes: invoice.buyerRegionCodes,
buyerWeredaCodes: invoice.buyerWeredaCodes,
exchangeRate: input.exchangeRate ?? null,
};
}

View File

@@ -6,6 +6,7 @@ import { EimsConfig } from "../../config/eims.config";
import { Invoice } from "../billing/entities/invoice.entity";
import { EimsInvoiceRequest } from "../billing/eims-invoice.mapper";
import { eimsInvoiceConfig } from "./eims-test-fixtures";
import { NotificationInboxService } from "../notification-inbox/notification-inbox.service";
import { EimsAuthService } from "./eims-auth.service";
import { EimsClientService } from "./eims-client.service";
import { EimsApiException } from "./eims.errors";
@@ -91,9 +92,11 @@ class FakeDb {
id: "state-1",
systemNumber: SYSTEM_NUMBER,
nextInvoiceCounter: 7,
nextDocumentNumber: 5,
previousIrn: null,
inFlightInvoiceId: null,
inFlightCounter: null,
inFlightDocumentNumber: null,
blockedReason: null,
...state,
} as EimsSystemState;
@@ -130,7 +133,10 @@ class FakeDb {
return {
manager: this.manager,
getRepository: this.manager.getRepository,
query: async () => LINES,
query: async (sql: string) =>
sql.includes("eims_system_state")
? [{ in_flight_invoice_id: this.state?.inFlightInvoiceId ?? null }]
: LINES,
transaction: async (body: (m: unknown) => Promise<unknown>) => {
this.onTransaction?.();
return body(this.manager);
@@ -147,17 +153,26 @@ const build = (
postSigned: jest.Mock,
cfg: EimsConfig = config(),
postBearer: jest.Mock = jest.fn(),
getSessionContext: jest.Mock = jest.fn().mockResolvedValue(SESSION),
getSessionContext: jest.Mock | undefined = undefined,
notify: jest.Mock = jest.fn().mockResolvedValue(undefined),
) =>
new EimsInvoiceRegistrationService(
db.asDataSource(),
{ get: () => cfg } as unknown as ConfigService,
{ postSigned, postBearer } as unknown as EimsClientService,
{ getSessionContext } as unknown as EimsAuthService,
{
getSessionContext: getSessionContext ?? jest.fn().mockResolvedValue(SESSION),
} as unknown as EimsAuthService,
{ notify } as unknown as NotificationInboxService,
);
/** Document number the fixtures register under; `/v1/verify` must echo it back. */
const DOCUMENT_NUMBER = "INV-20260807-00042";
/**
* Document number the fixtures register under; `/v1/verify` must echo it back.
*
* A plain integer, not our `invoiceNumber`: MoR validates the field against
* `^(0|[1-9][0-9]{0,8})$`. It is allocated from `nextDocumentNumber` above.
*/
const DOCUMENT_NUMBER = "5";
/**
* `/v1/verify` success. The response spells the reference `Irn` while the request sends lowercase
@@ -220,7 +235,7 @@ describe("EimsInvoiceRegistrationService.registerInvoiceWithEims", () => {
const request = postSigned.mock.calls[0][1] as EimsInvoiceRequest;
expect(request.SourceSystem.InvoiceCounter).toBe(42);
expect(request.ReferenceDetails.PreviousIrn).toBe("PRIOR-IRN");
expect(request.DocumentDetails.DocumentNumber).toBe("INV-20260807-00042");
expect(request.DocumentDetails.DocumentNumber).toBe(DOCUMENT_NUMBER);
expect(request.SourceSystem.SystemNumber).toBe(SYSTEM_NUMBER);
});
@@ -345,7 +360,9 @@ describe("EimsInvoiceRegistrationService.registerInvoiceWithEims", () => {
inFlightInvoiceId: null,
blockedReason: null,
previousIrn: null,
nextInvoiceCounter: 8, // consumed: the attempt reached the gateway
// Returned, not consumed: MoR tracks the sequence and rejects a gap
// ("Invoice counter is not correct. expected : 1").
nextInvoiceCounter: 7,
});
});
@@ -391,7 +408,7 @@ describe("EimsInvoiceRegistrationService.registerInvoiceWithEims", () => {
expect(postSigned).toHaveBeenCalledTimes(1);
});
it("never reuses a counter once an attempt has begun", async () => {
it("returns the counter after a refusal, but keeps it after an ambiguous result", async () => {
const db = new FakeDb([invoiceRow(), invoiceRow({ id: OTHER_INVOICE_ID })]);
const postSigned = jest
.fn()
@@ -404,8 +421,72 @@ describe("EimsInvoiceRegistrationService.registerInvoiceWithEims", () => {
);
await service.registerInvoiceWithEims(OTHER_INVOICE_ID);
expect((postSigned.mock.calls[0][1] as EimsInvoiceRequest).SourceSystem.InvoiceCounter).toBe(7);
expect((postSigned.mock.calls[1][1] as EimsInvoiceRequest).SourceSystem.InvoiceCounter).toBe(8);
// The two numbers move differently, because MoR constrains them differently: the counter must
// not skip (it returns), the document number must not repeat (it is burned).
const first = postSigned.mock.calls[0][1] as EimsInvoiceRequest;
const second = postSigned.mock.calls[1][1] as EimsInvoiceRequest;
expect(first.SourceSystem.InvoiceCounter).toBe(7);
expect(second.SourceSystem.InvoiceCounter).toBe(7);
expect(first.DocumentDetails.DocumentNumber).toBe("5");
expect(second.DocumentDetails.DocumentNumber).toBe("6");
});
});
describe("EimsInvoiceRegistrationService staff alerting", () => {
it("raises a high-priority alert when a result is ambiguous, because all filing is blocked", async () => {
const db = new FakeDb([invoiceRow()]);
const notify = jest.fn().mockResolvedValue(undefined);
const postSigned = jest.fn().mockRejectedValue(apiError("TIMEOUT"));
await expect(
build(db, postSigned, config(), jest.fn(), undefined, notify).registerInvoiceWithEims(
INVOICE_ID,
),
).rejects.toBeInstanceOf(EimsApiException);
expect(notify).toHaveBeenCalledTimes(1);
const sent = notify.mock.calls[0][0];
expect(sent.priority).toBe("HIGH");
expect(sent.title).toMatch(/blocked/i);
expect(sent.recipients.permissionKeys).toContain("edr_freight_app:invoices:eims_resolve");
});
it("raises a normal-priority alert for a deterministic rejection", async () => {
const db = new FakeDb([invoiceRow()]);
const notify = jest.fn().mockResolvedValue(undefined);
const postSigned = jest.fn().mockRejectedValue(apiError("RULE_VALIDATION", 406));
await expect(
build(db, postSigned, config(), jest.fn(), undefined, notify).registerInvoiceWithEims(
INVOICE_ID,
),
).rejects.toBeInstanceOf(EimsApiException);
expect(notify.mock.calls[0][0].priority).toBe("NORMAL");
});
it("does not alert on a successful filing", async () => {
const db = new FakeDb([invoiceRow()]);
const notify = jest.fn();
await build(db, jest.fn().mockResolvedValue(okResponse()), config(), jest.fn(), undefined, notify)
.registerInvoiceWithEims(INVOICE_ID);
expect(notify).not.toHaveBeenCalled();
});
it("lets the filing outcome stand even if the alert itself fails", async () => {
const db = new FakeDb([invoiceRow()]);
const notify = jest.fn().mockRejectedValue(new Error("inbox down"));
const postSigned = jest.fn().mockRejectedValue(apiError("RULE_VALIDATION", 406));
await expect(
build(db, postSigned, config(), jest.fn(), undefined, notify).registerInvoiceWithEims(
INVOICE_ID,
),
).rejects.toThrow(/EIMS register failed \(406\)/);
expect(db.invoices.get(INVOICE_ID)!.eimsStatus).toBe(EimsInvoiceStatus.Failed);
});
});
@@ -447,7 +528,15 @@ describe("EimsInvoiceRegistrationService.verifyInvoiceWithEims", () => {
describe("EimsInvoiceRegistrationService.resolveEimsRegistration", () => {
const blocked = () =>
new FakeDb([invoiceRow({ eimsStatus: EimsInvoiceStatus.Unknown, eimsInvoiceCounter: 7 })], {
new FakeDb(
[
invoiceRow({
eimsStatus: EimsInvoiceStatus.Unknown,
eimsInvoiceCounter: 7,
eimsDocumentNumber: DOCUMENT_NUMBER,
}),
],
{
inFlightInvoiceId: INVOICE_ID,
inFlightCounter: 7,
nextInvoiceCounter: 8,
@@ -498,13 +587,13 @@ describe("EimsInvoiceRegistrationService.resolveEimsRegistration", () => {
const db = blocked();
const postBearer = jest.fn().mockResolvedValue(
verifyResponse({
DocumentDetails: { Type: "INV", DocumentNumber: "INV-20260807-99999" },
DocumentDetails: { Type: "INV", DocumentNumber: "99999" },
}),
);
await expect(
build(db, jest.fn(), config(), postBearer).resolveEimsRegistration(INVOICE_ID, { irn: IRN }),
).rejects.toThrow(/not INV-20260807-00042/);
).rejects.toThrow(/not 5/);
expect(db.invoices.get(INVOICE_ID)).toMatchObject({
eimsStatus: EimsInvoiceStatus.Unknown,
@@ -547,7 +636,10 @@ describe("EimsInvoiceRegistrationService.resolveEimsRegistration", () => {
it("refuses to resolve an invoice that is not the in-flight one", async () => {
const db = blocked();
db.invoices.set(OTHER_INVOICE_ID, invoiceRow({ id: OTHER_INVOICE_ID }));
db.invoices.set(
OTHER_INVOICE_ID,
invoiceRow({ id: OTHER_INVOICE_ID, eimsDocumentNumber: "6" }),
);
const postBearer = jest.fn().mockResolvedValue(verifyResponse());
await expect(

View File

@@ -17,6 +17,9 @@ import {
EimsMapperLine,
toEimsInvoice,
} from "../billing/eims-invoice.mapper";
import { NotificationAudience, NotificationPriority, NotificationType } from "@edr/types";
import { NotificationInboxService } from "../notification-inbox/notification-inbox.service";
import { FREIGHT_PERMS } from "../../seed/freight-permissions.registry";
import { EimsAuthService } from "./eims-auth.service";
import { EimsClientService } from "./eims-client.service";
import { EimsApiException } from "./eims.errors";
@@ -44,6 +47,8 @@ const DETERMINISTIC_KINDS = new Set(["SCHEMA_VALIDATION", "RULE_VALIDATION", "AU
interface Reservation {
stateId: string;
invoiceCounter: number;
/** MoR requires a plain integer here, so it cannot be our own `invoiceNumber`. */
documentNumber: string;
previousIrn: string;
}
@@ -72,6 +77,7 @@ export class EimsInvoiceRegistrationService {
private readonly config: ConfigService,
private readonly client: EimsClientService,
private readonly auth: EimsAuthService,
private readonly inbox: NotificationInboxService,
) {}
private get cfg(): EimsConfig {
@@ -98,8 +104,9 @@ export class EimsInvoiceRegistrationService {
invoice,
buildEimsSeller(cfg),
buildEimsContext(cfg, {
// Our own invoice number is the document number; EIMS only requires it to be unique.
documentNumber: invoice.invoiceNumber,
// Allocated from the system state, not our invoiceNumber: MoR validates DocumentNumber
// against ^(0|[1-9][0-9]{0,8})$, which "INV-20260807-00006" can never satisfy.
documentNumber: reservation.documentNumber,
invoiceCounter: reservation.invoiceCounter,
previousIrn: reservation.previousIrn,
session,
@@ -174,8 +181,9 @@ export class EimsInvoiceRegistrationService {
* Refuse a manual resolution unless the gateway confirms *both* halves of the claim: that this
* IRN is the one it holds, and that it belongs to this invoice.
*
* The document-number check is against `DocumentDetails.DocumentNumber`, which registration set
* from our own `invoiceNumber` — the only field tying an IRN back to a row in this database.
* The document-number check is against `DocumentDetails.DocumentNumber`, which registration
* allocated and stored on the invoice as `eimsDocumentNumber` — the only field tying an IRN back
* to a row in this database.
*
* Recording a wrong IRN is not a local mistake: it marks an unregistered invoice as filed and
* chains every later document to a stranger's reference, so both checks are refusals rather
@@ -231,11 +239,34 @@ export class EimsInvoiceRegistrationService {
});
}
// Cheap ownership check before touching the gateway: resolving an invoice that does not hold
// the reservation is a caller mistake, not something to spend a MoR round trip on. The
// authoritative re-check happens under lock in the transaction below.
const [preState]: { in_flight_invoice_id: string | null }[] = await this.dataSource.query(
`SELECT in_flight_invoice_id FROM freight.eims_system_state
WHERE system_number = $1 AND deleted_at IS NULL LIMIT 1`,
[(await this.auth.getSessionContext()).systemNumber],
);
if (preState?.in_flight_invoice_id && preState.in_flight_invoice_id !== invoiceId) {
throw new ConflictException({
code: "EIMS_RESOLVE_WRONG_INVOICE",
message: `The in-flight EIMS submission is invoice ${preState.in_flight_invoice_id}, not ${invoiceId}`,
});
}
// Outside the transaction: no lock is held across the wire, and a refused verification must
// leave the block exactly as it was.
if (irn) {
const invoice = await this.loadInvoiceRow(this.dataSource.manager, invoiceId);
await this.assertIrnBelongsToInvoice(irn, invoice.invoiceNumber);
if (!invoice.eimsDocumentNumber) {
throw new BadRequestException({
code: "EIMS_NO_DOCUMENT_NUMBER",
message:
`Invoice ${invoice.invoiceNumber} was never allocated an EIMS document number, so a ` +
"returned IRN cannot be tied back to it.",
});
}
await this.assertIrnBelongsToInvoice(irn, invoice.eimsDocumentNumber);
}
// Same source of truth as registration: the state row is keyed by the token's system number.
@@ -266,6 +297,7 @@ export class EimsInvoiceRegistrationService {
...(irn ? { previousIrn: irn } : {}),
inFlightInvoiceId: null,
inFlightCounter: null,
inFlightDocumentNumber: null,
blockedReason: null,
});
});
@@ -311,23 +343,27 @@ export class EimsInvoiceRegistrationService {
if (invoice.eimsIrn) return null;
const invoiceCounter = Number(state.nextInvoiceCounter);
const documentNumber = String(Number(state.nextDocumentNumber));
const previousIrn = state.previousIrn ?? "";
// Counter consumed here, not on success: once an attempt begins it can never be reused,
// whatever happens next. A gap is harmless at MoR; a collision is not.
await manager.update(EimsSystemState, state.id, {
nextInvoiceCounter: invoiceCounter + 1,
nextDocumentNumber: Number(documentNumber) + 1,
inFlightInvoiceId: invoiceId,
inFlightCounter: invoiceCounter,
inFlightDocumentNumber: Number(documentNumber),
});
await manager.update(Invoice, invoiceId, {
eimsStatus: EimsInvoiceStatus.Submitting,
eimsInvoiceCounter: invoiceCounter,
eimsDocumentNumber: documentNumber,
eimsSubmittedAt: new Date(),
eimsLastError: null,
});
return { stateId: state.id, invoiceCounter, previousIrn };
return { stateId: state.id, invoiceCounter, documentNumber, previousIrn };
});
}
@@ -350,15 +386,26 @@ export class EimsInvoiceRegistrationService {
previousIrn: irn,
inFlightInvoiceId: null,
inFlightCounter: null,
inFlightDocumentNumber: null,
blockedReason: null,
});
});
}
/**
* TX2b. A deterministic rejection releases the reservation; an ambiguous result keeps it and
* blocks the system number, because `PreviousIrn` is now unknown for every later document.
* The counter stays consumed either way.
* TX2b. A deterministic rejection releases the reservation **and returns the counter**; an
* ambiguous result keeps both and blocks the system number, because `PreviousIrn` is now unknown
* for every later document.
*
* The two numbers move differently, because MoR constrains them differently:
*
* - `InvoiceCounter` must not **skip** — "Invoice counter is not correct. expected : 1". A
* document MoR definitively refused was never counted there, so ours must not advance either.
* - `DocumentNumber` must not **repeat** — the documented rule is "Document number is not
* unique". It is therefore spent by the attempt itself and never handed back, even for a
* refusal.
*
* An ambiguous result keeps both: MoR may have counted and stored the document.
*/
private async settleFailure(
invoiceId: string,
@@ -386,7 +433,15 @@ export class EimsInvoiceRegistrationService {
EimsSystemState,
reservation.stateId,
deterministic
? { inFlightInvoiceId: null, inFlightCounter: null, blockedReason: null }
? {
// Counter returns (MoR never counted a refused document); the document number does
// not (MoR requires it to be unique, so it is burned by the attempt).
nextInvoiceCounter: reservation.invoiceCounter,
inFlightInvoiceId: null,
inFlightCounter: null,
inFlightDocumentNumber: null,
blockedReason: null,
}
: {
blockedReason:
`Invoice ${invoiceId} was submitted with counter ${reservation.invoiceCounter} but ` +
@@ -397,6 +452,41 @@ export class EimsInvoiceRegistrationService {
});
this.logger.error(`Invoice ${invoiceId} EIMS registration ${status}: ${lastError.message}`);
await this.alertStaff(invoiceId, status, lastError, deterministic);
}
/**
* Tell the people who can act about a failed filing.
*
* An ambiguous result is the urgent one: it blocks *every* further invoice for this system
* number until a human resolves it, and nothing else in the system would surface that — the
* sweep just goes quiet. A deterministic rejection affects one invoice, so it is normal
* priority. Never throws: an alert that fails must not mask the filing outcome.
*/
private async alertStaff(
invoiceId: string,
status: EimsInvoiceStatus,
error: EimsInvoiceError,
deterministic: boolean,
): Promise<void> {
try {
await this.inbox.notify({
recipients: { permissionKeys: [FREIGHT_PERMS.invoices.eimsResolve] },
audience: NotificationAudience.BACKOFFICE,
type: NotificationType.GENERIC,
priority: deterministic ? NotificationPriority.NORMAL : NotificationPriority.HIGH,
title: deterministic
? "EIMS rejected an invoice"
: "EIMS filing unresolved — all further filing is blocked",
body: deterministic
? `MoR rejected the filing (${error.kind}): ${error.message}. The invoice is marked FAILED; correct it and file again.`
: `A submission was sent but never acknowledged (${error.kind}). Its IRN is unknown, so no further invoice can be filed until it is resolved with MoR.`,
link: `/dashboard/invoices/${invoiceId}`,
data: { invoiceId, eimsStatus: status, kind: error.kind, action: "EIMS_FILING_FAILED" },
});
} catch (err) {
this.logger.warn(`EIMS staff alert failed for invoice ${invoiceId}: ${(err as Error).message}`);
}
}
// ── internals ────────────────────────────────────────────────────────────────────────────────
@@ -488,6 +578,7 @@ export class EimsInvoiceRegistrationService {
invoiceNumber: invoice.invoiceNumber,
eimsStatus: invoice.eimsStatus ?? EimsInvoiceStatus.NotSubmitted,
eimsIrn: invoice.eimsIrn ?? null,
eimsDocumentNumber: invoice.eimsDocumentNumber ?? null,
eimsInvoiceCounter: counter === null || counter === undefined ? null : Number(counter),
eimsSubmittedAt: invoice.eimsSubmittedAt ?? null,
eimsAckDate: invoice.eimsAckDate ?? null,

View File

@@ -80,6 +80,8 @@ export interface EimsInvoiceStatusView {
invoiceNumber: string;
eimsStatus: EimsInvoiceStatus;
eimsIrn: string | null;
/** The numeric DocumentNumber filed with MoR; not our own invoiceNumber. */
eimsDocumentNumber: string | null;
eimsInvoiceCounter: number | null;
eimsSubmittedAt: Date | null;
eimsAckDate: string | null;

View File

@@ -33,6 +33,8 @@ export const eimsInvoiceConfig = (over: Partial<EimsInvoiceConfig> = {}): EimsIn
paymentTerm: "IMMIDIATE",
unitDefault: "PCS",
buyerCountryCode: null,
buyerRegionCodes: { "Addis Ababa": "13" },
buyerWeredaCodes: { Yeka: "99" }, // test-only, not a real MoR code
cashierName: null,
salesPersonName: null,
...over,

View File

@@ -3,6 +3,7 @@ import { Module } from "@nestjs/common";
import { TypeOrmModule } from "@nestjs/typeorm";
import { Invoice } from "../billing/entities/invoice.entity";
import { NotificationInboxModule } from "../notification-inbox/notification-inbox.module";
import { EimsAuthService } from "./eims-auth.service";
import { EimsAutoSubmitService } from "./eims-auto-submit.service";
import { EimsClientService } from "./eims-client.service";
@@ -22,6 +23,7 @@ import { EimsSystemState } from "./entities/eims-system-state.entity";
imports: [
HttpModule.register({ timeout: Number(process.env.EIMS_HTTP_TIMEOUT_MS) || 30_000 }),
TypeOrmModule.forFeature([EimsSystemState, Invoice]),
NotificationInboxModule,
],
controllers: [EimsInvoiceController],
providers: [

View File

@@ -18,6 +18,18 @@ export class EimsSystemState extends BaseEntity {
@Column({ name: "next_invoice_counter", type: "bigint", default: 1 })
nextInvoiceCounter!: number;
/**
* `DocumentDetails.DocumentNumber` for the next registration.
*
* Separate from our own `invoiceNumber`, which MoR cannot accept: it validates the field against
* `^(0|[1-9][0-9]{0,8})$`, a plain integer.
*/
@Column({ name: "next_document_number", type: "bigint", default: 1 })
nextDocumentNumber!: number;
@Column({ name: "in_flight_document_number", type: "bigint", nullable: true })
inFlightDocumentNumber?: number | null;
/** IRN of the last successful registration; null until the first one succeeds. */
@Column({ name: "previous_irn", type: "varchar", length: 64, nullable: true })
previousIrn?: string | null;

View File

@@ -1,13 +1,19 @@
import { ApiProperty } from '@nestjs/swagger';
import { ApiPropertyOptional } from '@nestjs/swagger';
import { Transform } from 'class-transformer';
import { IsNumber, Min } from 'class-validator';
import { IsNumber, IsOptional, Min } from 'class-validator';
export class ApproveLastMileRequestDto {
// The approve dialog prefills this from GET :id/price-estimate (rule-based),
// but the chief can still override — the typed value is what's invoiced.
@ApiProperty({ description: 'Advance amount the customer must pay before execution proceeds', example: 3000 })
@Transform(({ value }) => Number(value))
// Omitted = the rule-based last-mile rate estimate is the advance. The chief
// can still override with an explicit amount (required when no rate covers
// the job).
@ApiPropertyOptional({
description:
'Advance override. Omitted = the amount comes from the live last-mile rates (km × rate).',
example: 3000,
})
@IsOptional()
@Transform(({ value }) => (value === null || value === undefined || value === '' ? undefined : Number(value)))
@IsNumber()
@Min(0.01)
advanceAmount!: number;
advanceAmount?: number;
}

View File

@@ -114,7 +114,7 @@ export class LastMileRequestsController {
@Post(':id/approve')
@BookingStaff(FREIGHT_PERMS.lastMile.requestApprove)
@ApiOperation({ summary: 'Truck & Machinery chief approves the request — LM contract becomes signable; the advance invoice follows the customer signature' })
@ApiOperation({ summary: 'Truck & Machinery chief approves the request — the advance defaults to the live last-mile rate; LM contract becomes signable and the advance invoice follows the customer signature' })
approve(
@Param('id', ParseUUIDPipe) id: string,
@Body() dto: ApproveLastMileRequestDto,

View File

@@ -299,7 +299,11 @@ export class LastMileRequestsService {
return this.findById(id);
}
async approve(id: string, staffId: string | null, advanceAmount: number): Promise<LastMileRequest> {
async approve(
id: string,
staffId: string | null,
advanceOverride?: number | null,
): Promise<LastMileRequest> {
const request = await this.findById(id);
if (request.status !== LastMileRequestStatus.Submitted) {
throw new BadRequestException(`Only a submitted request can be approved (current status: ${request.status})`);
@@ -307,6 +311,18 @@ export class LastMileRequestsService {
const booking = request.booking ?? (await this.bookingsRepository.findById(request.bookingId));
if (!booking) throw new NotFoundException(`Booking ${request.bookingId} not found`);
// The live last-mile rates are the authority on the advance (km × rate);
// the chief's typed amount is only an override — and the only path when no
// rate covers the job. Snapshotted so the contract and invoice stay immune
// to later rate edits.
const estimate = await this.priceEstimate(id);
const advanceAmount = advanceOverride ?? estimate.total;
if (!advanceAmount || advanceAmount <= 0) {
throw new BadRequestException(
'No live last-mile rate covers this job — enter the advance amount manually.',
);
}
// Idempotent per booking — reuses the record if one already exists.
const lastMile = await this.lastMileService.create({
bookingId: request.bookingId,
@@ -316,10 +332,6 @@ export class LastMileRequestsService {
// No invoice yet: the advance is invoiced by LastMileContractService.sign()
// once the customer has signed the LM contract — doc first, then payment.
// Snapshot the rate estimate now so the contract shows the numbers the
// chief actually approved against, immune to later rate edits.
const estimate = await this.priceEstimate(id);
await this.requestsRepository.update(id, {
status: LastMileRequestStatus.Approved,
reviewedByStaffId: staffId,
@@ -364,7 +376,10 @@ export class LastMileRequestsService {
type: 'LAST_MILE_ADVANCE',
companyId: booking.companyId,
companyProfileId: booking.companyProfileId || '',
currency: booking.paymentCurrency || 'ETB',
// The advance is priced by the last-mile rate, so it bills in that
// rate's currency (birr for domestic trucking) — the booking's payment
// currency is only the fallback when the amount was a manual override.
currency: request.contractSummary?.currency || booking.paymentCurrency || 'ETB',
lines: [
{
chargeType: 'LAST_MILE_ADVANCE',

View File

@@ -60,14 +60,38 @@ export class RefundDto {
}
export class ClientActionDto {
// INVOKE_BRIDGE (SuperApp mini-app payload) is part of the shared ClientAction union and so
// must be assignable here, but freight never requests platform=inapp and therefore never
// receives one. Passenger owns that flow — see docs/telebirr-miniapp/.
@ApiProperty({
enum: ["REDIRECT", "LAUNCH_APP", "COLLECT_OTP", "SHOW_BILL_REFERENCE"],
enum: [
"REDIRECT",
"LAUNCH_APP",
"INVOKE_BRIDGE",
"COLLECT_OTP",
"SHOW_BILL_REFERENCE",
],
})
type!: "REDIRECT" | "LAUNCH_APP" | "COLLECT_OTP" | "SHOW_BILL_REFERENCE";
type!:
| "REDIRECT"
| "LAUNCH_APP"
| "INVOKE_BRIDGE"
| "COLLECT_OTP"
| "SHOW_BILL_REFERENCE";
@ApiPropertyOptional({ description: "Set when type=REDIRECT (web flow)" })
url?: string;
@ApiPropertyOptional({
description: "Set when type=INVOKE_BRIDGE (SuperApp mini app) — not used by freight",
})
bridge?: "TELEBIRR";
@ApiPropertyOptional({
description: "Set when type=INVOKE_BRIDGE (SuperApp mini app) — not used by freight",
})
rawRequest?: string;
@ApiPropertyOptional({ description: "Set when type=LAUNCH_APP (mobile flow)" })
appId?: string;

View File

@@ -0,0 +1,311 @@
import { SUPPORT_MEDIA_PREFIX, SupportDocSlug } from "@edr/types";
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import { Type } from "class-transformer";
import {
ArrayMaxSize,
IsArray,
IsIn,
IsObject,
IsOptional,
IsString,
Matches,
MaxLength,
MinLength,
ValidateNested,
} from "class-validator";
/**
* Markdown bodies are safe on read — the portal renders them with
* `react-markdown` and no `rehype-raw`, so any HTML in them is inert. The
* fields worth validating are these: they land in `href`/`src` attributes and
* bypass markdown entirely, which is where a `javascript:` URL would actually
* execute.
*
* Placeholders survive the check because they sit after the scheme
* (`mailto:{{supportEmail}}`, `tel:{{supportPhoneTel}}`).
*/
const LINK_PATTERN = /^(https?:\/\/|mailto:|tel:|\/)/;
const LINK_MESSAGE =
"$property must start with http(s)://, mailto:, tel: or /";
/**
* A media source is either an uploaded MinIO object key, a same-origin path, or
* an https URL. Anything else — notably `javascript:` — is refused, since this
* value lands in an `<img>`/`<video>` src.
*/
const MEDIA_SRC_PATTERN = new RegExp(
`^(https?:\\/\\/|\\/|${SUPPORT_MEDIA_PREFIX.replace("/", "\\/")})`,
);
const MEDIA_SRC_MESSAGE =
`$property must be an uploaded ${SUPPORT_MEDIA_PREFIX} key, a /path, or an http(s):// URL`;
/* ------------------------------- CONTACT ------------------------------- */
export class PortalSupportContactDto {
@ApiProperty()
@IsString()
@MinLength(3)
@MaxLength(200)
email!: string;
@ApiProperty()
@IsString()
@MinLength(3)
@MaxLength(60)
phone!: string;
@ApiProperty()
@IsString()
@MinLength(2)
@MaxLength(200)
office!: string;
@ApiProperty()
@IsString()
@MinLength(2)
@MaxLength(200)
hours!: string;
}
/* ---------------------------- PRIVACY / TERMS --------------------------- */
export class PortalDocSectionDto {
@ApiPropertyOptional({ description: "Stable id; generated when omitted" })
@IsOptional()
@IsString()
@MaxLength(64)
id?: string;
@ApiProperty()
@IsString()
@MinLength(1)
@MaxLength(200)
heading!: string;
@ApiProperty({ description: "Markdown" })
@IsString()
@MaxLength(20_000)
body!: string;
}
export class PortalLegalContentDto {
@ApiProperty()
@IsString()
@MinLength(1)
@MaxLength(200)
title!: string;
@ApiProperty()
@IsString()
@MaxLength(500)
subtitle!: string;
@ApiProperty({ description: 'Free text, e.g. "6 August 2026"' })
@IsString()
@MaxLength(60)
lastUpdated!: string;
@ApiProperty({ type: [PortalDocSectionDto] })
@IsArray()
@ArrayMaxSize(60)
@ValidateNested({ each: true })
@Type(() => PortalDocSectionDto)
sections!: PortalDocSectionDto[];
}
/* --------------------------------- FAQ --------------------------------- */
export class PortalCtaCardDto {
@ApiProperty()
@IsString()
@MinLength(1)
@MaxLength(200)
heading!: string;
@ApiProperty({ description: "Markdown" })
@IsString()
@MaxLength(2_000)
body!: string;
@ApiProperty()
@IsString()
@MinLength(1)
@MaxLength(100)
ctaLabel!: string;
@ApiProperty()
@IsString()
@Matches(LINK_PATTERN, { message: LINK_MESSAGE })
@MaxLength(500)
ctaTo!: string;
}
export class PortalFaqItemDto {
@ApiPropertyOptional({ description: "Stable id; generated when omitted" })
@IsOptional()
@IsString()
@MaxLength(64)
id?: string;
@ApiProperty()
@IsString()
@MinLength(1)
@MaxLength(300)
question!: string;
@ApiProperty({ description: "Markdown" })
@IsString()
@MaxLength(5_000)
answer!: string;
}
export class PortalFaqGroupDto {
@ApiPropertyOptional({ description: "Stable id; generated when omitted" })
@IsOptional()
@IsString()
@MaxLength(64)
id?: string;
@ApiProperty()
@IsString()
@MinLength(1)
@MaxLength(200)
title!: string;
@ApiProperty({ type: [PortalFaqItemDto] })
@IsArray()
@ArrayMaxSize(50)
@ValidateNested({ each: true })
@Type(() => PortalFaqItemDto)
items!: PortalFaqItemDto[];
}
export class PortalFaqContentDto {
@ApiProperty()
@IsString()
@MinLength(1)
@MaxLength(200)
title!: string;
@ApiProperty()
@IsString()
@MaxLength(500)
subtitle!: string;
@ApiProperty({ type: [PortalFaqGroupDto] })
@IsArray()
@ArrayMaxSize(20)
@ValidateNested({ each: true })
@Type(() => PortalFaqGroupDto)
groups!: PortalFaqGroupDto[];
@ApiPropertyOptional({ type: PortalCtaCardDto, nullable: true })
@IsOptional()
@ValidateNested()
@Type(() => PortalCtaCardDto)
footer?: PortalCtaCardDto | null;
}
/* --------------------------------- HELP -------------------------------- */
export class PortalMediaDto {
@ApiPropertyOptional({ description: "Stable id; generated when omitted" })
@IsOptional()
@IsString()
@MaxLength(64)
id?: string;
@ApiProperty({ enum: ["image", "video"] })
@IsIn(["image", "video"])
kind!: "image" | "video";
@ApiProperty({
description: `An uploaded ${SUPPORT_MEDIA_PREFIX} key, a same-origin /path, or an https:// URL`,
})
@IsString()
@Matches(MEDIA_SRC_PATTERN, { message: MEDIA_SRC_MESSAGE })
@MaxLength(500)
src!: string;
@ApiPropertyOptional({ nullable: true })
@IsOptional()
@IsString()
@MaxLength(300)
caption?: string | null;
}
export class PortalHelpSectionDto {
@ApiPropertyOptional({ description: "Stable id; generated when omitted" })
@IsOptional()
@IsString()
@MaxLength(64)
id?: string;
@ApiProperty()
@IsString()
@MinLength(1)
@MaxLength(200)
heading!: string;
@ApiProperty({ description: "Markdown" })
@IsString()
@MaxLength(20_000)
body!: string;
@ApiProperty({ type: [PortalMediaDto] })
@IsArray()
@ArrayMaxSize(12)
@ValidateNested({ each: true })
@Type(() => PortalMediaDto)
media!: PortalMediaDto[];
}
export class PortalHelpContentDto {
@ApiProperty()
@IsString()
@MinLength(1)
@MaxLength(200)
title!: string;
@ApiProperty()
@IsString()
@MaxLength(500)
subtitle!: string;
@ApiProperty({ type: [PortalHelpSectionDto] })
@IsArray()
@ArrayMaxSize(40)
@ValidateNested({ each: true })
@Type(() => PortalHelpSectionDto)
sections!: PortalHelpSectionDto[];
}
/* ------------------------------- request ------------------------------- */
export class UpdateSupportDocumentDto {
@ApiProperty({
description:
"The document's whole payload. Validated against the shape for its slug.",
type: Object,
})
@IsObject()
payload!: Record<string, unknown>;
@ApiPropertyOptional({ description: "Why this change was made" })
@IsOptional()
@IsString()
@MaxLength(255)
note?: string;
}
/** Which DTO class a slug's payload is validated against on write. */
export const PAYLOAD_DTO_BY_SLUG: Record<
SupportDocSlug,
new () => object
> = {
CONTACT: PortalSupportContactDto,
HELP: PortalHelpContentDto,
FAQ: PortalFaqContentDto,
PRIVACY: PortalLegalContentDto,
TERMS: PortalLegalContentDto,
};

View File

@@ -0,0 +1,69 @@
import { BaseEntity } from "@edr/api-common";
import type { SupportDocPayload, SupportDocSlug } from "@edr/types";
import { Column, Entity, Index, JoinColumn, ManyToOne } from "typeorm";
/**
* One editable customer-facing document for the freight portal's public pages
* (/help, /faq, /terms, /privacy) plus the support contact block they all
* quote. Five fixed rows, keyed by slug and seeded on first boot — there is no
* create/delete route.
*
* The payload is opaque jsonb because the five documents have genuinely
* different shapes and the help page's blocks keep changing; typed columns
* would mean a migration per copy tweak. Shape safety lives in the per-slug
* DTOs the service validates against on write, the same arrangement
* `contract_templates.articles` already uses.
*
* `version` is the live row's version and always equals `max(version)` in
* {@link SupportDocumentVersion} — the seeder writes v1 and its history row
* together, so the log is never missing the current state.
*/
@Entity({ schema: "freight", name: "support_documents" })
@Index(["slug"], { unique: true })
export class SupportDocument extends BaseEntity {
@Column({ name: "slug", type: "varchar", length: 32, unique: true })
slug!: SupportDocSlug;
@Column({ name: "payload", type: "jsonb", default: () => "'{}'::jsonb" })
payload!: SupportDocPayload;
@Column({ name: "version", type: "int", default: 1 })
version!: number;
@Column({ name: "updated_by_id", type: "uuid", nullable: true })
updatedById?: string | null;
}
/**
* Append-only history of every saved state of a document, written in the same
* transaction as the live row. Restoring is not a pointer reset: it re-saves an
* old payload through the normal write path, producing a *new* version, so a
* restore is itself undoable and the log only ever grows.
*
* Modelled on {@link CompanyRevision}, but snapshots the whole payload rather
* than a field diff — rollback needs the full state, not the delta.
*/
@Entity({ schema: "freight", name: "support_document_versions" })
@Index(["documentId"])
export class SupportDocumentVersion extends BaseEntity {
@Column({ name: "document_id", type: "uuid" })
documentId!: string;
@ManyToOne(() => SupportDocument, { onDelete: "CASCADE" })
@JoinColumn({ name: "document_id" })
document?: SupportDocument;
@Column({ name: "version", type: "int" })
version!: number;
@Column({ name: "payload", type: "jsonb" })
payload!: SupportDocPayload;
/** Who saved it. Null for the seeded initial version. */
@Column({ name: "actor_id", type: "uuid", nullable: true })
actorId?: string | null;
/** Optional "why" the editor typed, shown in the history list. */
@Column({ name: "note", type: "varchar", length: 255, nullable: true })
note?: string | null;
}

View File

@@ -0,0 +1,29 @@
import { Public } from "@edr/api-common";
import { Controller, Get, Header } from "@nestjs/common";
import { ApiOperation, ApiTags } from "@nestjs/swagger";
import { SupportContentService } from "./support-content.service";
/**
* The portal's /help, /faq, /terms and /privacy routes are deliberately outside
* its auth guard — the sign-up screen links to them before a session exists —
* so this read must work with no token. `@Public()` is class-level because that
* is the idiom the other genuinely-anonymous controllers here use; without it
* the globally registered `JwtGuard` would 401 every anonymous visitor.
*/
@ApiTags("support-content")
@Public()
@Controller("support-content")
export class PublicSupportContentController {
constructor(private readonly service: SupportContentService) {}
@Get()
// Hit on every anonymous page view, and the copy changes a few times a year.
@Header("Cache-Control", "public, max-age=300")
@ApiOperation({
summary: "Public help, FAQ, legal and support-contact copy for the portal",
})
getBundle() {
return this.service.getBundle();
}
}

View File

@@ -0,0 +1,135 @@
import { CurrentUser } from "@edr/api-common";
import { SUPPORT_MEDIA_MAX_BYTES } from "@edr/types";
import {
Body,
Controller,
Get,
Param,
ParseIntPipe,
Patch,
Post,
Query,
UploadedFile,
UseInterceptors,
} from "@nestjs/common";
import { FileInterceptor } from "@nestjs/platform-express";
import {
ApiBearerAuth,
ApiConsumes,
ApiOperation,
ApiQuery,
ApiTags,
} from "@nestjs/swagger";
import type { TCurrentUser } from "@tria-plc/api-common/modules/auth/types/current-user.type";
import { BookingStaff } from "../../common/booking-guards";
import { FREIGHT_PERMS } from "../../seed/freight-permissions.registry";
import { UpdateSupportDocumentDto } from "./dto/support-content.dto";
import { SupportContentService } from "./support-content.service";
const READ = [
FREIGHT_PERMS.settings.supportContent.view,
FREIGHT_PERMS.settings.supportContent.manage,
FREIGHT_PERMS.admin,
];
const WRITE = [
FREIGHT_PERMS.settings.supportContent.manage,
FREIGHT_PERMS.admin,
];
@ApiTags("support-content")
@ApiBearerAuth()
@Controller("support-content")
export class SupportContentController {
constructor(private readonly service: SupportContentService) {}
/**
* Stores a help-page image or video and returns its object key. The editor
* saves the key, not the returned URL — see `SupportContentService.uploadMedia`.
*
* The Multer limit duplicates the service-side type check on purpose: it
* stops reading the socket once the part is oversized instead of buffering
* the whole thing into memory first.
*/
@Post("media")
@BookingStaff(WRITE)
@UseInterceptors(
FileInterceptor("file", { limits: { fileSize: SUPPORT_MEDIA_MAX_BYTES } }),
)
@ApiConsumes("multipart/form-data")
@ApiOperation({ summary: "Upload an image or video for a help section" })
uploadMedia(@UploadedFile() file: Express.Multer.File) {
return this.service.uploadMedia(file);
}
/**
* Signs one stored key so the editor can preview an already-saved image.
* The editor stores `minio:<key>`, never a signed URL, so it needs somewhere
* to resolve those refs for display — this is it.
*/
@Get("media-url")
@BookingStaff(READ)
@ApiQuery({ name: "key", description: "MinIO object key" })
@ApiOperation({ summary: "Presigned URL for one stored media key" })
mediaUrl(@Query("key") key: string) {
return this.service.mediaUrl(key);
}
@Get("documents")
@BookingStaff(READ)
@ApiOperation({ summary: "List the five portal content documents (no payloads)" })
list() {
return this.service.list();
}
@Get("documents/:slug")
@BookingStaff(READ)
@ApiOperation({ summary: "Get one document with its payload" })
getBySlug(@Param("slug") slug: string) {
return this.service.getBySlug(slug);
}
@Patch("documents/:slug")
@BookingStaff(WRITE)
@ApiOperation({
summary: "Replace a document's payload, recording a new version",
})
update(
@Param("slug") slug: string,
@Body() dto: UpdateSupportDocumentDto,
@CurrentUser() user: TCurrentUser,
) {
return this.service.update(slug, dto, user?.id ?? null);
}
@Get("documents/:slug/versions")
@BookingStaff(READ)
@ApiOperation({ summary: "Version history, newest first (no payloads)" })
listVersions(@Param("slug") slug: string) {
return this.service.listVersions(slug);
}
@Get("documents/:slug/versions/:version")
@BookingStaff(READ)
@ApiOperation({ summary: "One historical version, with its payload" })
getVersion(
@Param("slug") slug: string,
@Param("version", ParseIntPipe) version: number,
) {
return this.service.getVersion(slug, version);
}
@Post("documents/:slug/versions/:version/restore")
@BookingStaff(WRITE)
@ApiOperation({
summary: "Restore a version — re-saves it as a new version, never destructive",
})
restore(
@Param("slug") slug: string,
@Param("version", ParseIntPipe) version: number,
@CurrentUser() user: TCurrentUser,
) {
return this.service.restore(slug, version, user?.id ?? null);
}
}

View File

@@ -0,0 +1,23 @@
import { Module } from "@nestjs/common";
import { TypeOrmModule } from "@nestjs/typeorm";
import { MinioModule } from "../minio/minio.module";
import {
SupportDocument,
SupportDocumentVersion,
} from "./entities/support-document.entity";
import { PublicSupportContentController } from "./public-support-content.controller";
import { SupportContentController } from "./support-content.controller";
import { SupportContentRepository } from "./support-content.repository";
import { SupportContentService } from "./support-content.service";
@Module({
imports: [
TypeOrmModule.forFeature([SupportDocument, SupportDocumentVersion]),
MinioModule,
],
controllers: [PublicSupportContentController, SupportContentController],
providers: [SupportContentRepository, SupportContentService],
exports: [SupportContentService],
})
export class SupportContentModule {}

View File

@@ -0,0 +1,71 @@
import { BaseRepository } from "@edr/api-common";
import type { SupportDocSlug } from "@edr/types";
import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import {
SupportDocument,
SupportDocumentVersion,
} from "./entities/support-document.entity";
@Injectable()
export class SupportContentRepository extends BaseRepository<SupportDocument> {
constructor(
@InjectRepository(SupportDocument)
repository: Repository<SupportDocument>,
@InjectRepository(SupportDocumentVersion)
private readonly versions: Repository<SupportDocumentVersion>,
) {
super(repository);
}
findBySlug(slug: SupportDocSlug): Promise<SupportDocument | null> {
return this.repository.findOne({ where: { slug } });
}
override findAll(): Promise<SupportDocument[]> {
return this.repository.find({ order: { slug: "ASC" } });
}
findVersions(documentId: string): Promise<SupportDocumentVersion[]> {
return this.versions.find({
where: { documentId },
order: { version: "DESC" },
});
}
findVersion(
documentId: string,
version: number,
): Promise<SupportDocumentVersion | null> {
return this.versions.findOne({ where: { documentId, version } });
}
/**
* Bump the live row and append its history entry atomically. Doing both in
* one transaction is what guarantees `document.version` always has a matching
* version row — the invariant the history list and rollback both rely on.
*/
async saveWithVersion(
document: SupportDocument,
actorId: string | null,
note: string | null,
): Promise<SupportDocument> {
return this.repository.manager.transaction(async (manager) => {
const saved = await manager.save(SupportDocument, document);
await manager.save(
manager.create(SupportDocumentVersion, {
documentId: saved.id,
version: saved.version,
payload: saved.payload,
actorId,
note,
}),
);
return saved;
});
}
}

View File

@@ -0,0 +1,237 @@
import {
SUPPORT_CONTENT_DEFAULTS,
SUPPORT_DOC_SLUGS,
SupportDocPayload,
SupportDocSlug,
} from "@edr/types";
import { BadRequestException, NotFoundException } from "@nestjs/common";
import { MinioService } from "../minio/minio.service";
import {
SupportDocument,
SupportDocumentVersion,
} from "./entities/support-document.entity";
import { SupportContentRepository } from "./support-content.repository";
import { SupportContentService, validatePayload } from "./support-content.service";
const ACTOR = "11111111-1111-4111-8111-111111111111";
/**
* In-memory stand-in for the repository: one seeded document plus its version
* log, with `saveWithVersion` doing what the real transaction does. Enough to
* assert the rollback contract without a database.
*/
function makeRepository(slug: SupportDocSlug) {
const document = {
id: "00000000-0000-0000-0000-000000000001",
slug,
payload: SUPPORT_CONTENT_DEFAULTS[slug],
version: 1,
updatedById: null,
} as SupportDocument;
const versions: SupportDocumentVersion[] = [
{
id: "v1",
documentId: document.id,
version: 1,
payload: document.payload,
actorId: null,
note: "Initial content",
} as SupportDocumentVersion,
];
const repository = {
findAll: jest.fn(async () => [document]),
findBySlug: jest.fn(async (s: SupportDocSlug) =>
s === slug ? document : null,
),
findVersions: jest.fn(async () => [...versions].reverse()),
findVersion: jest.fn(
async (_id: string, version: number) =>
versions.find((v) => v.version === version) ?? null,
),
saveWithVersion: jest.fn(
async (doc: SupportDocument, actorId: string | null, note: string | null) => {
versions.push({
id: `v${doc.version}`,
documentId: doc.id,
version: doc.version,
payload: doc.payload,
actorId,
note,
} as SupportDocumentVersion);
return doc;
},
),
};
// Signing is exercised only through getBundle; the write path never touches it.
const minio = {
getSignedUrl: jest.fn(async (key: string) => `https://minio.test/${key}?sig=x`),
uploadFile: jest.fn(),
};
return {
document,
versions,
minio,
service: new SupportContentService(
repository as unknown as SupportContentRepository,
minio as unknown as MinioService,
),
};
}
describe("SupportContentService.restore", () => {
it("rolls back to an older payload as a NEW version, leaving history intact", async () => {
const { document, versions, service } = makeRepository("CONTACT");
const original = SUPPORT_CONTENT_DEFAULTS.CONTACT;
await service.update(
"CONTACT",
{ payload: { ...original, phone: "+251 99 999 9999" } },
ACTOR,
);
expect(document.version).toBe(2);
expect(versions.map((v) => v.version)).toEqual([1, 2]);
const restored = await service.restore("CONTACT", 1, ACTOR);
expect(restored.payload).toEqual(original);
// The assertion that matters: restore is additive. If someone "optimises"
// it into a destructive pointer reset this drops back to 1 and rollback
// silently stops being undoable.
expect(restored.version).toBe(3);
expect(versions.map((v) => v.version)).toEqual([1, 2, 3]);
expect(versions[2].note).toBe("Restored version 1");
});
it("404s on a version that was never written", async () => {
const { service } = makeRepository("CONTACT");
await expect(service.restore("CONTACT", 99, ACTOR)).rejects.toBeInstanceOf(
NotFoundException,
);
});
it("rejects an unknown slug", async () => {
const { service } = makeRepository("CONTACT");
await expect(service.getBySlug("NOPE")).rejects.toBeInstanceOf(
BadRequestException,
);
});
});
describe("SupportContentService.getBundle", () => {
it("signs stored keys on read and leaves paths and URLs alone", async () => {
const { service, minio } = makeRepository("CONTACT");
const help = SUPPORT_CONTENT_DEFAULTS.HELP;
// findAll returns only CONTACT, so HELP falls back to the defaults — which
// is itself worth asserting: an unseeded row must not break the page.
const bundle = await service.getBundle();
expect(bundle.help.sections[0].media[0].src).toBe(
"/assets/edr-portal-guide.webm",
);
expect(minio.getSignedUrl).not.toHaveBeenCalled();
const withUpload = {
...help,
sections: [
{
...help.sections[0],
body: "See ![diagram](minio:support-content/d.png) below.",
media: [
{ id: "m1", kind: "image" as const, src: "support-content/a.png" },
],
},
],
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const signed = await (service as any).signMedia({
...bundle,
help: withUpload,
});
expect(signed.help.sections[0].media[0].src).toBe(
"https://minio.test/support-content/a.png?sig=x",
);
expect(signed.help.sections[0].body).toContain(
"https://minio.test/support-content/d.png?sig=x",
);
// The stored copy must never be mutated into a URL — that is what would rot.
expect(withUpload.sections[0].media[0].src).toBe("support-content/a.png");
});
});
describe("validatePayload", () => {
const help = SUPPORT_CONTENT_DEFAULTS.HELP;
it("accepts every shipped default", () => {
for (const slug of SUPPORT_DOC_SLUGS) {
expect(() =>
validatePayload(slug, SUPPORT_CONTENT_DEFAULTS[slug]),
).not.toThrow();
}
});
const sectionWithMedia = (src: string) => ({
...help,
sections: [{ ...help.sections[0], media: [{ kind: "video", src }] }],
});
it("rejects a javascript: media source", () => {
// The markdown renderer drops raw HTML, so src attributes like this one are
// the only place a script URL could still execute.
expect(() =>
validatePayload("HELP", sectionWithMedia("javascript:alert(1)")),
).toThrow(BadRequestException);
});
it("accepts an uploaded key, a rooted path and an https URL", () => {
for (const src of [
"support-content/9f1c.png",
"/assets/edr-portal-guide.webm",
"https://cdn.example.com/clip.mp4",
]) {
expect(() => validatePayload("HELP", sectionWithMedia(src))).not.toThrow();
}
});
it("rejects a media kind that is neither image nor video", () => {
expect(() =>
validatePayload("HELP", {
...help,
sections: [
{
...help.sections[0],
media: [{ kind: "pdf", src: "support-content/a.pdf" }],
},
],
}),
).toThrow(BadRequestException);
});
it("keeps placeholder links, which sit after the scheme", () => {
expect(() =>
validatePayload("FAQ", {
...SUPPORT_CONTENT_DEFAULTS.FAQ,
footer: {
...SUPPORT_CONTENT_DEFAULTS.FAQ.footer!,
ctaTo: "mailto:{{supportEmail}}",
},
}),
).not.toThrow();
});
it("generates ids for items saved without one", () => {
const legal = validatePayload("TERMS", {
...SUPPORT_CONTENT_DEFAULTS.TERMS,
sections: [{ heading: "1. New", body: "Body." }],
}) as Extract<SupportDocPayload, { sections: unknown }>;
expect(legal.sections[0].id).toEqual(expect.any(String));
expect(legal.sections[0].id.length).toBeGreaterThan(0);
});
});

View File

@@ -0,0 +1,368 @@
import {
PORTAL_MEDIA_URI_SCHEME,
PortalContentBundle,
PortalFaqContent,
PortalHelpContent,
PortalLegalContent,
PortalMediaKind,
SUPPORT_CONTENT_DEFAULTS,
SUPPORT_DOC_SLUGS,
SUPPORT_MEDIA_PREFIX,
SupportDocPayload,
SupportDocSlug,
} from "@edr/types";
import {
BadRequestException,
Injectable,
NotFoundException,
} from "@nestjs/common";
import { extname } from "path";
import { MinioService } from "../minio/minio.service";
import { plainToInstance } from "class-transformer";
import { validateSync, ValidationError } from "class-validator";
import { randomUUID } from "crypto";
import {
PAYLOAD_DTO_BY_SLUG,
UpdateSupportDocumentDto,
} from "./dto/support-content.dto";
import {
SupportDocument,
SupportDocumentVersion,
} from "./entities/support-document.entity";
import { SupportContentRepository } from "./support-content.repository";
/**
* A paste-bomb in one section would bloat the public bundle every anonymous
* visitor downloads, so the whole payload is capped as well as its fields.
*/
const MAX_PAYLOAD_BYTES = 200_000;
/**
* Comfortably longer than the 5-minute `Cache-Control` on the public bundle, so
* a cached response never outlives the URLs inside it.
*/
const MEDIA_URL_TTL_SECONDS = 6 * 60 * 60;
/** `minio:support-content/<file>` inside markdown. */
const MEDIA_REF = new RegExp(
`${PORTAL_MEDIA_URI_SCHEME}([A-Za-z0-9._\\-/]+)`,
"g",
);
/** Anything not already a URL or a rooted path is a MinIO object key. */
const isObjectKey = (src: string) => !/^(https?:\/\/|\/)/.test(src);
@Injectable()
export class SupportContentService {
constructor(
private readonly repository: SupportContentRepository,
private readonly minio: MinioService,
) {}
/**
* Stores an image or video for the help page and returns its object key.
*
* The key is what gets saved in the document — never the signed URL. A
* presigned URL expires, so persisting one would leave every embedded image
* broken a few hours later; signing happens per read instead.
*/
async uploadMedia(
file?: Express.Multer.File,
): Promise<{ key: string; kind: PortalMediaKind; url: string }> {
if (!file) throw new BadRequestException("No file uploaded");
const kind: PortalMediaKind | null = file.mimetype.startsWith("image/")
? "image"
: file.mimetype.startsWith("video/")
? "video"
: null;
if (!kind) {
throw new BadRequestException(
`Unsupported file type ${file.mimetype} — images and videos only`,
);
}
const key = `${SUPPORT_MEDIA_PREFIX}${randomUUID()}${extname(file.originalname).toLowerCase()}`;
await this.minio.uploadFile(key, file.buffer, file.mimetype);
return {
key,
kind,
url: await this.minio.getSignedUrl(key, MEDIA_URL_TTL_SECONDS),
};
}
/** Presigned URL for one stored key, for the backoffice editor's previews. */
async mediaUrl(key: string): Promise<{ url: string }> {
if (!key?.startsWith(SUPPORT_MEDIA_PREFIX)) {
throw new BadRequestException(
`key must be an uploaded ${SUPPORT_MEDIA_PREFIX} object`,
);
}
return { url: await this.minio.getSignedUrl(key, MEDIA_URL_TTL_SECONDS) };
}
/**
* The public bundle. Missing rows fall back to the shipped defaults so an
* unseeded or half-migrated environment still serves the legal pages rather
* than 404-ing the first thing an anonymous visitor sees.
*/
async getBundle(): Promise<PortalContentBundle> {
const documents = await this.repository.findAll();
const bySlug = new Map(documents.map((d) => [d.slug, d.payload]));
const payload = <S extends SupportDocSlug>(slug: S) =>
(bySlug.get(slug) ?? SUPPORT_CONTENT_DEFAULTS[slug]) as never;
return this.signMedia({
contact: payload("CONTACT"),
help: payload("HELP"),
faq: payload("FAQ"),
privacy: payload("PRIVACY"),
terms: payload("TERMS"),
});
}
/**
* Swaps every stored MinIO reference for a freshly signed URL: attachment
* `src` keys, and `minio:<key>` references embedded in markdown by the
* editor's image button.
*
* Each distinct key is signed once per request, and a signing failure
* degrades to MinIO's public URL rather than failing the whole page (see
* `MinioService.getSignedUrl`).
*/
private async signMedia(
bundle: PortalContentBundle,
): Promise<PortalContentBundle> {
const keys = new Set<string>();
for (const section of bundle.help.sections ?? []) {
for (const item of section.media ?? []) {
if (isObjectKey(item.src)) keys.add(item.src);
}
}
const collect = (value: unknown): void => {
if (typeof value === "string") {
for (const match of value.matchAll(MEDIA_REF)) keys.add(match[1]);
} else if (Array.isArray(value)) {
value.forEach(collect);
} else if (value && typeof value === "object") {
Object.values(value).forEach(collect);
}
};
collect(bundle);
if (keys.size === 0) return bundle;
const signed = new Map(
await Promise.all(
[...keys].map(
async (key) =>
[key, await this.minio.getSignedUrl(key, MEDIA_URL_TTL_SECONDS)] as const,
),
),
);
const rewrite = (value: unknown): unknown => {
if (typeof value === "string") {
return value.replace(MEDIA_REF, (whole, key: string) =>
signed.get(key) ?? whole,
);
}
if (Array.isArray(value)) return value.map(rewrite);
if (value && typeof value === "object") {
return Object.fromEntries(
Object.entries(value).map(([k, v]) => [k, rewrite(v)]),
);
}
return value;
};
const resolved = rewrite(bundle) as PortalContentBundle;
for (const section of resolved.help.sections ?? []) {
for (const item of section.media ?? []) {
if (isObjectKey(item.src)) item.src = signed.get(item.src) ?? item.src;
}
}
return resolved;
}
/** Admin list — metadata only, no payloads. */
async list(): Promise<Omit<SupportDocument, "payload">[]> {
const documents = await this.repository.findAll();
return documents.map(({ payload: _payload, ...rest }) => rest);
}
async getBySlug(rawSlug: string): Promise<SupportDocument> {
const slug = assertSlug(rawSlug);
const document = await this.repository.findBySlug(slug);
if (!document) {
throw new NotFoundException(`Support document ${slug} not found`);
}
return document;
}
/**
* Replace a document's whole payload. Writing the whole slice rather than
* patching fields is deliberate: one editorial change becomes exactly one
* version, which is what keeps the history readable.
*/
async update(
rawSlug: string,
dto: UpdateSupportDocumentDto,
actorId: string | null,
): Promise<SupportDocument> {
const document = await this.getBySlug(rawSlug);
const payload = validatePayload(document.slug, dto.payload);
document.payload = payload;
document.version += 1;
document.updatedById = actorId;
return this.repository.saveWithVersion(document, actorId, dto.note ?? null);
}
async listVersions(rawSlug: string): Promise<SupportDocumentVersion[]> {
const document = await this.getBySlug(rawSlug);
return this.repository.findVersions(document.id);
}
async getVersion(
rawSlug: string,
version: number,
): Promise<SupportDocumentVersion> {
const document = await this.getBySlug(rawSlug);
const found = await this.repository.findVersion(document.id, version);
if (!found) {
throw new NotFoundException(
`Version ${version} of ${document.slug} not found`,
);
}
return found;
}
/**
* Roll back to an earlier version by re-saving its payload through the normal
* write path. The result is a NEW version whose content equals the old one —
* never a destructive pointer reset — so the history only grows and a restore
* is itself undoable.
*/
async restore(
rawSlug: string,
version: number,
actorId: string | null,
): Promise<SupportDocument> {
const target = await this.getVersion(rawSlug, version);
return this.update(
rawSlug,
{
payload: target.payload as unknown as Record<string, unknown>,
note: `Restored version ${version}`,
},
actorId,
);
}
}
/* ------------------------------ helpers ------------------------------- */
export function assertSlug(raw: string): SupportDocSlug {
const slug = raw?.toUpperCase() as SupportDocSlug;
if (!SUPPORT_DOC_SLUGS.includes(slug)) {
throw new BadRequestException(
`Unknown support document "${raw}". Valid slugs: ${SUPPORT_DOC_SLUGS.join(", ")}`,
);
}
return slug;
}
/**
* Validate an incoming payload against the DTO registered for its slug, then
* fill in any missing item ids. Exported so the seeder's spec can assert the
* shipped defaults are themselves valid.
*/
export function validatePayload(
slug: SupportDocSlug,
raw: unknown,
): SupportDocPayload {
if (JSON.stringify(raw ?? null).length > MAX_PAYLOAD_BYTES) {
throw new BadRequestException(
`Payload for ${slug} exceeds ${MAX_PAYLOAD_BYTES} bytes`,
);
}
const instance = plainToInstance(PAYLOAD_DTO_BY_SLUG[slug], raw ?? {});
const errors = validateSync(instance as object, {
whitelist: true,
forbidNonWhitelisted: true,
});
if (errors.length) {
throw new BadRequestException(flattenErrors(errors));
}
return withGeneratedIds(slug, instance as SupportDocPayload);
}
function flattenErrors(errors: ValidationError[], path = ""): string[] {
return errors.flatMap((error) => {
const here = path ? `${path}.${error.property}` : error.property;
const own = Object.values(error.constraints ?? {}).map(
(message) => `${here}: ${message}`,
);
return [...own, ...flattenErrors(error.children ?? [], here)];
});
}
const withId = <T extends { id?: string }>(item: T): T => ({
...item,
id: item.id || randomUUID(),
});
/**
* Item ids are the React keys in the portal, and admin-authored headings and
* questions collide too easily to use as keys. Editors may omit them; the
* server mints one rather than making every client remember to.
*/
function withGeneratedIds(
slug: SupportDocSlug,
payload: SupportDocPayload,
): SupportDocPayload {
switch (slug) {
case "HELP": {
const help = payload as PortalHelpContent;
return {
...help,
sections: help.sections.map((section) => ({
...withId(section),
media: (section.media ?? []).map(withId),
})),
};
}
case "FAQ": {
const faq = payload as PortalFaqContent;
return {
...faq,
groups: faq.groups.map((group) => ({
...withId(group),
items: group.items.map(withId),
})),
};
}
case "PRIVACY":
case "TERMS": {
const legal = payload as PortalLegalContent;
return { ...legal, sections: legal.sections.map(withId) };
}
default:
return payload;
}
}

View File

@@ -21,7 +21,6 @@ import {
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { InjectDataSource } from '@nestjs/typeorm';
import { SCHEDULE_BOOKINGS_CTE } from '../../common/schedule-bookings.sql';
import {
DataSource,
EntityManager,
@@ -2522,63 +2521,6 @@ export class TrainSchedulingService {
return this.getTrainScheduleById(scheduleId);
}
/**
* EXPORT ONLY. An export train must not leave carrying nothing while its cargo
* sits in the shed: the goods are received into the origin warehouse, GRN'd and
* loaded onto the wagons allocated to the booking, so anything still in the
* warehouse at dispatch is being left behind. Blocks dispatch when an allocated
* booking has warehouse inventory that never made it onto a wagon (received /
* stored / ready but not LOADED) — either load it from the Load-to-Train queue,
* or drop the booking's wagon allocation so it rides a later train.
*
* Import/domestic are untouched: their cargo isn't loaded out of an origin
* warehouse, so warehouse inventory says nothing about what's aboard.
*
* Bookings with no warehouse inventory at all are NOT blocked — allocating a
* wagon before the goods arrive is normal planning; they simply aren't aboard.
*/
private async assertAllocatedCargoLoaded(scheduleId: string): Promise<void> {
const [route]: Array<{ originCountry: string | null; destinationCountry: string | null }> =
await this.dataSource.query(
`SELECT oy.country AS "originCountry", dy.country AS "destinationCountry"
FROM freight.train_schedules ts
LEFT JOIN freight.yards oy ON oy.id = ts.origin_station_id
LEFT JOIN freight.yards dy ON dy.id = ts.destination_station_id
WHERE ts.id = $1 AND ts.deleted_at IS NULL`,
[scheduleId],
);
if (!route) return;
const direction = deriveTradeDirection(
{ country: route.originCountry },
{ country: route.destinationCountry },
);
if (direction !== 'EXPORT') return;
// Only bookings boarding at the schedule's ORIGIN station gate dispatch —
// a mid-corridor boarder (origin B on an A→B→C→D run) is loaded when the
// train reaches its yard, so its warehouse state says nothing at departure.
const rows: Array<{ reference: string | null; status: string }> = await this.dataSource.query(
`WITH ${SCHEDULE_BOOKINGS_CTE}
SELECT DISTINCT b.reference AS "reference", inv.status AS "status"
FROM sched_bookings sb
JOIN freight.bookings b ON b.id = sb.booking_id AND b.deleted_at IS NULL
JOIN freight.train_schedules ts ON ts.id = sb.schedule_id
JOIN freight.warehouse_inventory inv
ON inv.booking_id = b.id AND inv.deleted_at IS NULL
WHERE sb.schedule_id = $1
AND b.origin_yard_id = ts.origin_station_id
AND inv.status IN ('RECEIVED', 'STORED', 'READY_FOR_LOADING')`,
[scheduleId],
);
if (rows.length) {
const refs = [...new Set(rows.map((r) => r.reference ?? '?'))].join(', ');
throw new BadRequestException(
`Cannot dispatch: cargo for booking(s) ${refs} is in the warehouse but not loaded onto a wagon. ` +
`Load it from the warehouse Load-to-Train queue, or remove the booking's wagon allocation so it travels on a later train.`,
);
}
}
async dispatchSchedule(scheduleId: string) {
const schedule = await this.trainSchedulesRepository.findByIdWithFullGraph(scheduleId);
if (!schedule) {
@@ -2588,8 +2530,8 @@ export class TrainSchedulingService {
throw new BadRequestException('Only SCHEDULED trains can be dispatched');
}
await this.assertImportDjiboutiMayDepart(schedule);
// Export only: don't leave received cargo behind in the warehouse.
await this.assertAllocatedCargoLoaded(scheduleId);
// Cargo readiness (in the warehouse, not inspected, not loaded onto a wagon)
// never blocks departure — the dispatch confirm dialog warns and staff decide.
// A locomotive may sit on many future schedules, but it can only pull one train
// at a time — block dispatch while any set locomotive is out on a dispatched train.
const setLocomotiveIds = this.locomotivesOfTrainSet(schedule.trainSet).map((l) => l.id);

View File

@@ -0,0 +1,56 @@
import { WarehouseInventoryService } from './warehouse-inventory.service';
/**
* Export self-haul has no separate "truck arrived" gate action the way import
* does (release()'s arrival branch, fired later when a truck shows up to
* COLLECT already-warehoused goods) — the truck delivering cargo TO the
* warehouse arrives and is received in the same act, so receive()/
* bulkReceive() must stamp customer_truck_assignments.arrived_at themselves.
*/
type Marker = (
manager: { query: jest.Mock },
bookingId: string,
plateNumber: string | null | undefined,
) => Promise<void>;
function makeMarker() {
const service = Object.create(WarehouseInventoryService.prototype) as Record<string, unknown>;
const marker = (
service as unknown as { markCustomerTruckArrived: Marker }
).markCustomerTruckArrived.bind(service);
return marker;
}
describe('markCustomerTruckArrived', () => {
it('stamps arrival matched by booking + plate', async () => {
const marker = makeMarker();
const manager = { query: jest.fn().mockResolvedValue(undefined) };
await marker(manager, 'b-1', 'AAA-2323');
expect(manager.query).toHaveBeenCalledTimes(1);
const [sql, params] = manager.query.mock.calls[0];
expect(sql).toMatch(/UPDATE freight\.customer_truck_assignments/);
expect(sql).toMatch(/UPPER\(a\.plate_number\) = UPPER\(\$2\)/);
expect(params).toEqual(['b-1', 'AAA-2323']);
});
it('trims the plate before matching', async () => {
const marker = makeMarker();
const manager = { query: jest.fn().mockResolvedValue(undefined) };
await marker(manager, 'b-1', ' AAA-2323 ');
expect(manager.query.mock.calls[0][1]).toEqual(['b-1', 'AAA-2323']);
});
it('no-ops on a missing/blank plate — no query, nothing to match on', async () => {
const marker = makeMarker();
const manager = { query: jest.fn() };
await marker(manager, 'b-1', undefined);
await marker(manager, 'b-1', ' ');
expect(manager.query).not.toHaveBeenCalled();
});
});

View File

@@ -1643,6 +1643,12 @@ export class WarehouseInventoryService {
[bookingId],
);
// Export self-haul: this receive IS the truck's arrival — see
// markCustomerTruckArrived / receive()'s single-booking mirror.
if (dto.direction === 'EXPORT') {
await this.markCustomerTruckArrived(manager, bookingId, truckEntrance?.truckPlateNumber);
}
await this.activityLog.record(
{
activityType: 'INVENTORY_RECEIVED',
@@ -1691,7 +1697,6 @@ export class WarehouseInventoryService {
/** EXPORT inventory rows at a given status (route-derived direction), with booking detail. */
private async exportInventoryByStatus(
status: WarehouseInventoryStatus,
requireInspectionPassed = false,
): Promise<ReadyToLoadRow[]> {
const rows: Array<
ReadyToLoadRow & { originCountry: string | null; destinationCountry: string | null }
@@ -1720,7 +1725,6 @@ export class WarehouseInventoryService {
LEFT JOIN freight.containers ct ON ct.id = inv.container_id
WHERE inv.deleted_at IS NULL
AND inv.status = $1
${requireInspectionPassed ? `AND inv.inspection_status = 'PASSED'` : ''}
ORDER BY inv.created_at DESC`,
[status],
);
@@ -1733,9 +1737,13 @@ export class WarehouseInventoryService {
.map(({ originCountry: _oc, destinationCountry: _dc, ...rest }) => rest);
}
/** EXPORT inventory that passed inspection and is waiting to be loaded (READY_FOR_LOADING). */
/**
* EXPORT inventory waiting to be loaded (READY_FOR_LOADING). Inspection state
* rides along on each row for the UI to show, but does not filter the queue —
* uninspected cargo must still be loadable.
*/
async readyToLoadExport(): Promise<ReadyToLoadRow[]> {
return this.exportInventoryByStatus('READY_FOR_LOADING', true);
return this.exportInventoryByStatus('READY_FOR_LOADING');
}
/** EXPORT inventory received at the facility and awaiting inspection. */
@@ -2886,6 +2894,13 @@ export class WarehouseInventoryService {
);
}
// Export self-haul: this receive IS the truck's arrival — stamp it on
// its own customer_truck_assignments row (mirror of import's arrival,
// see markCustomerTruckArrived).
if (dto.bookingId && bookingDirection === 'EXPORT') {
await this.markCustomerTruckArrived(manager, dto.bookingId, truckEntrance.truckPlateNumber);
}
await this.activityLog.record(
{
activityType: 'INVENTORY_RECEIVED',
@@ -3117,9 +3132,8 @@ export class WarehouseInventoryService {
if (!item.bookingId || !item.warehouseId || !item.yardId || !item.zoneId) {
throw new BadRequestException('Inventory must have booking, warehouse, yard and zone before loading prep');
}
if (item.inspectionStatus !== 'PASSED') {
throw new BadRequestException('Inventory must pass inspection before it can be marked ready for loading');
}
// Inspection is tracked, not enforced — uninspected cargo may still be
// marked ready and loaded so a train is never held for paperwork.
return this.transition(id, 'READY_FOR_LOADING', {
timestampField: 'readyForLoadingAt',
activityType: 'READY_FOR_LOADING',
@@ -6008,6 +6022,33 @@ export class WarehouseInventoryService {
};
}
/**
* EXPORT self-haul mirror of the customer truck lifecycle IMPORT already has:
* import stamps a truck's arrival on the SEPARATE gate action that comes
* later (release()'s arrival branch, when the customer's truck shows up to
* COLLECT already-warehoused goods). Export has no such separate step — the
* truck delivering cargo TO the warehouse arrives and is received in the
* same act, so receive()/bulkReceive() themselves are the arrival event.
* Matched by plate (not assignmentId — neither receive endpoint carries
* one), same as release()'s departure-branch self-haul UPDATE.
*/
private async markCustomerTruckArrived(
manager: EntityManager,
bookingId: string,
plateNumber: string | null | undefined,
): Promise<void> {
const plate = plateNumber?.trim();
if (!plate) return;
await manager.query(
`UPDATE freight.customer_truck_assignments a
SET arrived_at = COALESCE(a.arrived_at, NOW()), updated_at = NOW()
WHERE a.booking_id = $1
AND UPPER(a.plate_number) = UPPER($2)
AND a.deleted_at IS NULL`,
[bookingId, plate],
);
}
private async getBookingTruckEntranceSource(
manager: EntityManager,
bookingId: string,
@@ -6027,6 +6068,10 @@ export class WarehouseInventoryService {
firstMileDriverPhone?: string | null;
firstMileDriverLicenseNumber?: string | null;
firstMileTruckType?: string | null;
customerTruckPlateNumber?: string | null;
customerTruckDriverName?: string | null;
customerTruckType?: string | null;
customerTruckContainerNumber?: string | null;
}> {
const [booking] = await manager.query(
`SELECT b.reference AS "reference",
@@ -6046,7 +6091,24 @@ export class WarehouseInventoryService {
) AS "firstMileDriverName",
driver.phone_number AS "firstMileDriverPhone",
driver.license_number AS "firstMileDriverLicenseNumber",
v.vehicle_type AS "firstMileTruckType"
v.vehicle_type AS "firstMileTruckType",
-- Self-haul truck assigned via the portal — export delivering to
-- the warehouse or import collecting from it. Same pattern as
-- eligibleBookings/importQueueByStatuses: multi-truck self-haul
-- writes plates/drivers to customer_truck_assignments and leaves
-- the booking columns null, so read the assignments first and
-- keep the legacy column as the fallback for single-truck
-- bookings written before that table existed.
COALESCE((SELECT string_agg(DISTINCT cta.plate_number, ', ')
FROM freight.customer_truck_assignments cta
WHERE cta.booking_id = b.id AND cta.deleted_at IS NULL),
b.customer_truck_plate_number) AS "customerTruckPlateNumber",
COALESCE((SELECT string_agg(DISTINCT cta.driver_name, ', ')
FROM freight.customer_truck_assignments cta
WHERE cta.booking_id = b.id AND cta.deleted_at IS NULL),
b.customer_truck_driver_name) AS "customerTruckDriverName",
b.customer_truck_type AS "customerTruckType",
b.customer_truck_container_number AS "customerTruckContainerNumber"
FROM freight.bookings b
LEFT JOIN freight.companies company ON company.id = b.company_id
${primaryContactUserJoin('company')}

View File

@@ -1302,6 +1302,16 @@ export const GRANULAR_SPLIT_PERMISSIONS: FreightPermissionSeed[] = [
"edr_freight_app:settings:contract_templates:read",
"Read contract template data (API only)",
),
perm(
"b4f00001-0001-4000-8000-000000000001",
"edr_freight_app:settings:support_content:view",
"View portal help & legal content",
),
perm(
"b4f00001-0001-4000-8000-000000000002",
"edr_freight_app:settings:support_content:manage",
"Edit portal help, FAQ & legal content",
),
];
// N. Previously-ungated staff surfaces (support inbox, procurement, compliance,
@@ -1851,6 +1861,11 @@ export const FREIGHT_PERMS = {
delete: "edr_freight_app:settings:contract_templates:delete",
read: "edr_freight_app:settings:contract_templates:read",
},
// Portal-facing help/FAQ/legal copy, edited from Portal content.
supportContent: {
view: "edr_freight_app:settings:support_content:view",
manage: "edr_freight_app:settings:support_content:manage",
},
},
audit: {
view: "edr_freight_app:audit:view",

View File

@@ -0,0 +1,62 @@
import { SUPPORT_CONTENT_DEFAULTS, SUPPORT_DOC_SLUGS } from "@edr/types";
import { Injectable, Logger } from "@nestjs/common";
import { DataSource } from "typeorm";
import {
SupportDocument,
SupportDocumentVersion,
} from "../modules/support-content/entities/support-document.entity";
/**
* Puts the portal's shipped help/FAQ/legal copy into the database on first
* boot. Idempotent by emptiness, like the other reference-data seeders: once a
* row exists the content is admin-managed, so a redeploy must never clobber it.
*
* Each document is written together with its `version = 1` history row, which
* is what makes `max(version)` in the log always equal the live row — the
* invariant the version list and rollback both assume.
*/
@Injectable()
export class SupportContentSeeder {
private readonly logger = new Logger(SupportContentSeeder.name);
constructor(private readonly dataSource: DataSource) {}
async run() {
const documents = this.dataSource.getRepository(SupportDocument);
const versions = this.dataSource.getRepository(SupportDocumentVersion);
const existing = await documents.count({ withDeleted: true });
if (existing > 0) {
this.logger.log(
`support_documents already has ${existing} rows — skipping seed`,
);
return;
}
for (const slug of SUPPORT_DOC_SLUGS) {
const document = await documents.save(
documents.create({
slug,
payload: SUPPORT_CONTENT_DEFAULTS[slug],
version: 1,
updatedById: null,
}),
);
await versions.save(
versions.create({
documentId: document.id,
version: 1,
payload: document.payload,
actorId: null,
note: "Initial content",
}),
);
}
this.logger.log(
`Seeded ${SUPPORT_DOC_SLUGS.length} portal content documents`,
);
}
}

View File

@@ -12,3 +12,9 @@ VITE_TOKEN_REFRESH_INTERVAL_MINUTES=10
# observability stays off (the app works either way). Self-hosted instance.
VITE_POSTHOG_KEY=phc_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
VITE_POSTHOG_HOST=https://posthog.example.com
# Maps JavaScript API key (fleet TrackingPage). Required — the hardcoded
# fallback in TrackingPage.tsx is expired (ExpiredKeyMapError), so without
# this set the tracking map renders blank. Get a key from the Google Cloud
# Console (Maps JavaScript API + Places API + Geocoding API enabled).
VITE_GOOGLE_MAPS_API_KEY=

View File

@@ -20,6 +20,7 @@
"@mantine/core": "^9.3.0",
"@mantine/dates": "^9.3.0",
"@mantine/hooks": "^9.3.0",
"@mdxeditor/editor": "^4.2.0",
"@posthog/react": "^1.10.3",
"@radix-ui/react-accordion": "^1.2.13",
"@radix-ui/react-alert-dialog": "^1.1.16",
@@ -93,6 +94,7 @@
"react-icons": "^5.6.0",
"react-image-crop": "^11.0.10",
"react-intersection-observer": "^9.16.0",
"react-markdown": "^9.1.0",
"react-pdf": "^10.4.1",
"react-pdf-html": "^2.1.5",
"react-quill-new": "^3.8.3",

View File

@@ -57,6 +57,7 @@ import NoAccessPage from "./pages/NoAccessPage";
import FileUploadSettingsPage from "./pages/documents/FileUploadSettingsPage";
import DropdownSettingsPage from "./pages/dropdown_settings/DropdownSettingsPage";
import ContractTemplatesPage from "./pages/contract_templates/ContractTemplatesPage";
import PortalContentPage from "./pages/portal_content/PortalContentPage";
import ContractTemplateEditorPage from "./pages/contract_templates/ContractTemplateEditorPage";
import FleetResourcePage from "./pages/fleet/FleetResourcePage";
import WagonTransfersPage from "./pages/wagons/WagonTransfersPage";
@@ -773,7 +774,9 @@ const App = () => {
<Route
path="compliance"
element={
<RequirePermission permission={FREIGHT_PERMS.fleet.view}>
<RequirePermission
permission={[FREIGHT_PERMS.compliance.view, FREIGHT_PERMS.fleet.view]}
>
<CompliancePage />
</RequirePermission>
}
@@ -797,7 +800,9 @@ const App = () => {
<Route
path="procurement"
element={
<RequirePermission permission={FREIGHT_PERMS.fleet.view}>
<RequirePermission
permission={[FREIGHT_PERMS.procurement.view, FREIGHT_PERMS.fleet.view]}
>
<ProcurementPage />
</RequirePermission>
}
@@ -820,7 +825,9 @@ const App = () => {
<Route
path="file-settings"
element={
<RequirePermission permission={FREIGHT_PERMS.admin}>
<RequirePermission
permission={[FREIGHT_PERMS.settings.fileUpload.view, FREIGHT_PERMS.admin]}
>
<FileUploadSettingsPage />
</RequirePermission>
}
@@ -828,7 +835,9 @@ const App = () => {
<Route
path="dropdown-settings"
element={
<RequirePermission permission={FREIGHT_PERMS.admin}>
<RequirePermission
permission={[FREIGHT_PERMS.settings.dropdown.view, FREIGHT_PERMS.admin]}
>
<DropdownSettingsPage />
</RequirePermission>
}
@@ -867,6 +876,20 @@ const App = () => {
</RequirePermission>
}
/>
<Route
path="portal-content"
element={
<RequirePermission
permission={[
FREIGHT_PERMS.settings.supportContent.view,
FREIGHT_PERMS.settings.supportContent.manage,
FREIGHT_PERMS.admin,
]}
>
<PortalContentPage />
</RequirePermission>
}
/>
<Route
path="configuration"
@@ -885,7 +908,9 @@ const App = () => {
<Route
path="configuration/trade-access"
element={
<RequirePermission permission={FREIGHT_PERMS.admin}>
<RequirePermission
permission={[FREIGHT_PERMS.tradeAccess.view, FREIGHT_PERMS.admin]}
>
<TradeAccessPage />
</RequirePermission>
}
@@ -893,7 +918,9 @@ const App = () => {
<Route
path="configuration/exchange-rate"
element={
<RequirePermission permission={FREIGHT_PERMS.admin}>
<RequirePermission
permission={[FREIGHT_PERMS.settings.exchangeRate.view, FREIGHT_PERMS.admin]}
>
<div className="p-4">
<ExchangeRateSettingsCard />
</div>

View File

@@ -276,9 +276,8 @@ export default function GlCreateBookingForm() {
const [trainScheduleId, setTrainScheduleId] = useState("");
const [contractRouteId, setContractRouteId] = useState<string | null>(null);
const [notes, setNotes] = useState("");
// The customer states the billing currency on their shipment request — GL
// books in it. Intercity is always ETB (the API enforces this too).
const [paymentCurrency, setPaymentCurrency] = useState<"USD" | "ETB">("USD");
// ponytail: ETB-only for now — widen back to "USD" | "ETB" when multi-currency billing returns.
const [paymentCurrency, setPaymentCurrency] = useState<"USD" | "ETB">("ETB");
// What the containers carry — captured per booking (moved off the contract).
const [cargoDescription, setCargoDescription] = useState("");
const [containerLines, setContainerLines] = useState<ContainerLineDraft[]>([]);
@@ -449,9 +448,6 @@ export default function GlCreateBookingForm() {
}
if (bookingRequest.contractRouteId)
setContractRouteId(bookingRequest.contractRouteId);
if (bookingRequest.paymentCurrency === "USD" || bookingRequest.paymentCurrency === "ETB") {
setPaymentCurrency(bookingRequest.paymentCurrency);
}
if (bookingRequest.notes) setNotes(bookingRequest.notes);
}, [bookingRequest, prefilled]);
@@ -1761,11 +1757,7 @@ export default function GlCreateBookingForm() {
Billing currency
</Text>
<Text size="xs" c="dimmed" mb={8}>
{isIntercity
? "Intercity shipments are invoiced in ETB."
: bookingRequest?.paymentCurrency
? "Requested by the customer on their shipment request."
: "The contract is quoted in USD — pick the currency this shipment is invoiced in."}
Shipments are invoiced in ETB.
</Text>
<CurrencySelector
value={isIntercity ? "ETB" : paymentCurrency}

View File

@@ -0,0 +1,158 @@
import { Alert, Badge, Button, Card, Group, SimpleGrid, Stack, Text } from "@mantine/core";
import { useMutation, useQuery } from "@tanstack/react-query";
import { AlertTriangle, RefreshCw, Send, ShieldCheck } from "lucide-react";
import { useAuth } from "@/auth/useAuth";
import { FREIGHT_PERMS, hasPermission } from "@/lib/permissions";
import { api } from "@/services/api";
import type { EimsInvoiceStatus } from "@/types/eims";
import { useToast } from "@/hooks/use-toast";
const STATUS_COLOR: Record<EimsInvoiceStatus, string> = {
NOT_SUBMITTED: "gray",
SUBMITTING: "yellow",
REGISTERED: "edr-green",
FAILED: "red",
UNKNOWN: "orange",
};
const STATUS_LABEL: Record<EimsInvoiceStatus, string> = {
NOT_SUBMITTED: "Not filed",
SUBMITTING: "Filing…",
REGISTERED: "Filed",
FAILED: "Rejected",
UNKNOWN: "Unacknowledged",
};
function Field({ label, value }: { label: string; value?: string | number | null }) {
return (
<Stack gap={2}>
<Text size="xs" fw={600} c="edr-muted" tt="uppercase">
{label}
</Text>
<Text size="sm" c="edr-text" style={{ wordBreak: "break-all" }}>
{value === null || value === undefined || value === "" ? "—" : value}
</Text>
</Stack>
);
}
/**
* MoR EIMS filing state for one invoice, with the manual actions.
*
* Filing normally happens on the API's cron sweep, not here — these controls exist for controlled
* testing and for the exceptional cases the sweep deliberately refuses: a rejected invoice that
* needs re-filing, and an unacknowledged one that has blocked all further filing.
*/
export function EimsFilingCard({ invoiceId }: { invoiceId: string }) {
const { user } = useAuth();
const { toast } = useToast();
const canFile = hasPermission(user, FREIGHT_PERMS.invoices.eimsRegister);
const { data: eims, isLoading } = useQuery(
api.invoices.eimsStatus.queryOptions({ input: { id: invoiceId }, enabled: Boolean(invoiceId) }),
);
const register = useMutation(
api.invoices.eimsRegister.mutationOptions({
onSuccess: (result) =>
toast({
title: result.eimsIrn ? "Filed with MoR" : "Filing finished",
description: result.eimsIrn ? `IRN ${result.eimsIrn}` : `Status ${result.eimsStatus}`,
}),
}),
);
const verify = useMutation(
api.invoices.eimsVerify.mutationOptions({
onSuccess: (result) =>
toast({
title: "MoR confirmed the filing",
description: `Document ${result.body?.DocumentDetails?.DocumentNumber ?? "—"}`,
}),
}),
);
if (isLoading || !eims) return null;
const status = eims.eimsStatus;
const busy = register.isPending || verify.isPending;
return (
<Card>
<Stack gap="lg">
<Group justify="space-between">
<Text fw={600} c="edr-text">
MoR e-invoicing
</Text>
<Badge color={STATUS_COLOR[status] ?? "gray"} variant="light" size="sm" radius="md" fw={600}>
{STATUS_LABEL[status] ?? status}
</Badge>
</Group>
<SimpleGrid cols={{ base: 1, sm: 2, lg: 4 }} spacing="lg">
<Field label="IRN" value={eims.eimsIrn} />
<Field label="Invoice counter" value={eims.eimsInvoiceCounter} />
<Field
label="Submitted"
value={eims.eimsSubmittedAt ? new Date(eims.eimsSubmittedAt).toLocaleString() : null}
/>
<Field label="Acknowledged" value={eims.eimsAckDate} />
</SimpleGrid>
{status === "UNKNOWN" && (
<Alert color="orange" icon={<AlertTriangle size={16} />} title="All filing is blocked">
This invoice was sent but never acknowledged, so its IRN is unknown and no further
invoice can be filed. Confirm its status with MoR, then have a supervisor record the IRN
or discard the attempt.
</Alert>
)}
{eims.eimsLastError && (
<Alert
color={status === "FAILED" ? "red" : "orange"}
icon={<AlertTriangle size={16} />}
title={`MoR reported: ${eims.eimsLastError.kind}`}
>
{eims.eimsLastError.message}
</Alert>
)}
{canFile && (
<Group gap="sm">
{/* UNKNOWN is never re-filed from here: resubmitting risks a duplicate registration. */}
{status !== "REGISTERED" && status !== "UNKNOWN" && (
<Button
size="xs"
variant="light"
radius="md"
loading={register.isPending}
disabled={busy}
leftSection={status === "FAILED" ? <RefreshCw size={14} /> : <Send size={14} />}
onClick={() => register.mutate({ id: invoiceId })}
>
{status === "FAILED" ? "File again" : "File with MoR"}
</Button>
)}
{eims.eimsIrn && (
<Button
size="xs"
variant="light"
radius="md"
loading={verify.isPending}
disabled={busy}
leftSection={<ShieldCheck size={14} />}
onClick={() => verify.mutate({ id: invoiceId })}
>
Verify with MoR
</Button>
)}
</Group>
)}
</Stack>
</Card>
);
}
export default EimsFilingCard;

View File

@@ -1,5 +1,6 @@
import {
ArrowLeftRight,
BookOpen,
Boxes,
Building2,
BarChart3,
@@ -286,19 +287,21 @@ export const buildSidebarSections = (demoItems: SidebarItem[]): SidebarSection[]
label: "Compliance & Alerts",
href: "/dashboard/compliance",
icon: <ShieldCheck />,
permission: FREIGHT_PERMS.fleet.view,
permission: [FREIGHT_PERMS.compliance.view, FREIGHT_PERMS.fleet.view],
},
{
label: "Incidents",
href: "/dashboard/incidents",
icon: <FileText />,
// No dedicated backend key exists for incidents yet — stuck on the
// blanket fleet:view fallback until one is added.
permission: FREIGHT_PERMS.fleet.view,
},
{
label: "Procurement",
href: "/dashboard/procurement",
icon: <Package />,
permission: FREIGHT_PERMS.fleet.view,
permission: [FREIGHT_PERMS.procurement.view, FREIGHT_PERMS.fleet.view],
},
{
label: "Financial Reports",
@@ -483,13 +486,13 @@ export const buildSidebarSections = (demoItems: SidebarItem[]): SidebarSection[]
label: "File settings",
href: "/dashboard/file-settings",
icon: <Paperclip />,
permission: FREIGHT_PERMS.admin,
permission: [FREIGHT_PERMS.settings.fileUpload.view, FREIGHT_PERMS.admin],
},
{
label: "Dropdown settings",
href: "/dashboard/dropdown-settings",
icon: <Settings />,
permission: FREIGHT_PERMS.admin,
permission: [FREIGHT_PERMS.settings.dropdown.view, FREIGHT_PERMS.admin],
},
{
label: "Contract templates",
@@ -501,6 +504,16 @@ export const buildSidebarSections = (demoItems: SidebarItem[]): SidebarSection[]
FREIGHT_PERMS.admin,
],
},
{
label: "Portal content",
href: "/dashboard/portal-content",
icon: <BookOpen />,
permission: [
FREIGHT_PERMS.settings.supportContent.view,
FREIGHT_PERMS.settings.supportContent.manage,
FREIGHT_PERMS.admin,
],
},
{
label: "Audit logs",
href: "/dashboard/audit-logs",
@@ -521,12 +534,12 @@ export const buildSidebarSections = (demoItems: SidebarItem[]): SidebarSection[]
{
label: "Trade access",
href: "/dashboard/configuration/trade-access",
permission: FREIGHT_PERMS.admin,
permission: [FREIGHT_PERMS.tradeAccess.view, FREIGHT_PERMS.admin],
},
{
label: "Exchange rate",
href: "/dashboard/configuration/exchange-rate",
permission: FREIGHT_PERMS.admin,
permission: [FREIGHT_PERMS.settings.exchangeRate.view, FREIGHT_PERMS.admin],
},
],
},

View File

@@ -53,6 +53,7 @@ export const QUERY_KEYS = {
byId: (id: string) => ["invoices", "detail", id] as const,
offlineUsd: (filter?: InvoiceListFilter) =>
["invoices", "offline-usd", filter ?? {}] as const,
eimsStatus: (id: string) => ["invoices", "eims", id] as const,
},
BOOKINGS: {

View File

@@ -109,6 +109,14 @@ export const URL_CONSTANTS = {
CONFIRM_OFFLINE: (id: string) => `/billing/invoices/${id}/confirm-offline`,
},
// MoR EIMS filing. Mounted on /invoices, not /billing/invoices — see EimsInvoiceController.
EIMS: {
STATUS: (id: string) => `/invoices/${id}/eims/status`,
REGISTER: (id: string) => `/invoices/${id}/eims/register`,
VERIFY: (id: string) => `/invoices/${id}/eims/verify`,
RESOLVE: (id: string) => `/invoices/${id}/eims/resolve`,
},
CUSTOMERS_API: {
BASE: "/api/customers",
BY_ID: (id: string) => `/api/customers/${id}`,

View File

@@ -0,0 +1,78 @@
import type { SupportDocPayload, SupportDocSlug } from "@edr/types";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import toast from "react-hot-toast";
import { portalContentService } from "@/services/portal-content.service";
/**
* Every key shares the `portal-content` prefix so one invalidate after a save
* or a restore sweeps the document and its version list together.
*/
const KEYS = {
ROOT: ["portal-content"] as const,
bySlug: (slug: string) => ["portal-content", "detail", slug] as const,
versions: (slug: string) => ["portal-content", "versions", slug] as const,
};
export function usePortalDoc(slug: SupportDocSlug) {
return useQuery({
queryKey: KEYS.bySlug(slug),
queryFn: () => portalContentService.getBySlug(slug),
});
}
/** Version history. Stays idle until the history modal is opened. */
export function usePortalDocVersions(slug: SupportDocSlug, enabled: boolean) {
return useQuery({
queryKey: KEYS.versions(slug),
queryFn: () => portalContentService.listVersions(slug),
enabled,
});
}
/** One historical payload, fetched only when a version is previewed. */
export function usePortalDocVersion(
slug: SupportDocSlug,
version: number | null,
) {
return useQuery({
queryKey: [...KEYS.versions(slug), version],
queryFn: () => portalContentService.getVersion(slug, version as number),
enabled: version !== null,
});
}
function usePortalContentMutation<TVariables>(
mutationFn: (vars: TVariables) => Promise<unknown>,
successMessage: string,
) {
const queryClient = useQueryClient();
return useMutation({
mutationFn,
onSuccess: () => {
toast.success(successMessage);
void queryClient.invalidateQueries({ queryKey: KEYS.ROOT });
},
onError: (error: unknown) => {
const message =
(error as { response?: { data?: { message?: string } } })?.response?.data
?.message ?? "Something went wrong";
toast.error(Array.isArray(message) ? message.join(", ") : message);
},
});
}
export function useUpdatePortalDoc(slug: SupportDocSlug) {
return usePortalContentMutation(
(vars: { payload: SupportDocPayload; note?: string }) =>
portalContentService.update(slug, vars.payload, vars.note),
"Portal content saved",
);
}
export function useRestorePortalVersion(slug: SupportDocSlug) {
return usePortalContentMutation(
(version: number) => portalContentService.restore(slug, version),
"Version restored",
);
}

View File

@@ -129,6 +129,10 @@ export const FREIGHT_PERMS = {
view: "edr_freight_app:invoices:view",
export: "edr_freight_app:invoices:export",
confirmOffline: "edr_freight_app:invoices:confirm_offline",
// Filing with MoR EIMS. Held by named admins rather than a role preset: registration is
// irreversible at the tax authority, and resolving clears a system-wide filing block.
eimsRegister: "edr_freight_app:invoices:eims_register",
eimsResolve: "edr_freight_app:invoices:eims_resolve",
},
firstMile: {
view: "edr_freight_app:first_mile:view",
@@ -323,6 +327,11 @@ export const FREIGHT_PERMS = {
delete: "edr_freight_app:settings:contract_templates:delete",
read: "edr_freight_app:settings:contract_templates:read",
},
// Portal-facing help/FAQ/legal copy, edited from Portal content.
supportContent: {
view: "edr_freight_app:settings:support_content:view",
manage: "edr_freight_app:settings:support_content:manage",
},
},
audit: {
view: "edr_freight_app:audit:view",

View File

@@ -529,10 +529,7 @@ export default function NewBookingPage() {
/>
<Select
label="Payment currency"
data={[
{ value: "ETB", label: "ETB — Birr" },
{ value: "USD", label: "USD — Dollar" },
]}
data={[{ value: "ETB", label: "ETB — Birr" }]}
value={paymentCurrency}
onChange={(v) => setPaymentCurrency(v ?? "ETB")}
/>

View File

@@ -30,13 +30,17 @@ import { useToast } from "@/hooks/use-toast";
import { useAuth } from "@/auth/useAuth";
import { FREIGHT_PERMS, hasPermission } from "@/lib/permissions";
import { vehiclesService } from "@/services/vehicles.service";
import { gpsTrackingService, type GpsDevice } from "@/services/gps-tracking.service";
import {
gpsTrackingService,
type GpsDevice,
} from "@/services/gps-tracking.service";
import { freightBrand } from "@/theme/freight-brand";
// Same default key + env override the portal's LocationPicker uses.
const GOOGLE_MAPS_API_KEY =
import.meta.env.VITE_GOOGLE_MAPS_API_KEY ||
"AIzaSyBg4tN31-fgvH_2Ix_TPo6VSfOA2uA5CCI";
// Maps JavaScript API keys are public client-side keys — lock them down by
// HTTP-referrer in the Google Cloud console. No fallback: a hardcoded default
// used to live here and expired, turning a missing env var into a blank map
// that read as broken GPS rather than absent configuration.
const GOOGLE_MAPS_API_KEY = import.meta.env.VITE_GOOGLE_MAPS_API_KEY?.trim();
const DEFAULT_CENTER = { lat: 9.03, lng: 38.74 }; // Addis Ababa
const toNum = (v: number | string | null | undefined): number | null =>
@@ -55,8 +59,12 @@ const fmtTime = (iso?: string | null) => {
const StatBox = ({ label, value }: { label: string; value: string }) => (
<Box p="sm" style={{ backgroundColor: "#f8f9fa", borderRadius: 8 }}>
<Text size="xs" c="dimmed">{label}</Text>
<Text fw={600} size="sm">{value}</Text>
<Text size="xs" c="dimmed">
{label}
</Text>
<Text fw={600} size="sm">
{value}
</Text>
</Box>
);
@@ -95,11 +103,20 @@ function useAddress(lat: number, lng: number): string | null {
if (typeof google === "undefined" || !google.maps?.Geocoder) return;
setAddr(null);
let cancelled = false;
new google.maps.Geocoder().geocode({ location: { lat, lng } }, (res, status) => {
if (cancelled) return;
setAddr(status === "OK" && res?.[0] ? res[0].formatted_address : "Unknown location");
});
return () => { cancelled = true; };
new google.maps.Geocoder().geocode(
{ location: { lat, lng } },
(res, status) => {
if (cancelled) return;
setAddr(
status === "OK" && res?.[0]
? res[0].formatted_address
: "Unknown location",
);
},
);
return () => {
cancelled = true;
};
}, [lat, lng]);
return addr;
}
@@ -118,16 +135,24 @@ function HoverInfo({
}) {
const address = useAddress(lat, lng);
return (
<InfoWindow position={{ lat, lng }} pixelOffset={[0, -46]} onCloseClick={onClose}>
<InfoWindow
position={{ lat, lng }}
pixelOffset={[0, -46]}
onCloseClick={onClose}
>
<div style={{ minWidth: 190, fontSize: 13 }}>
<div style={{ fontWeight: 600, marginBottom: 2 }}>{deviceLabel(device)}</div>
<div style={{ fontWeight: 600, marginBottom: 2 }}>
{deviceLabel(device)}
</div>
<div style={{ fontFamily: "monospace" }}>
{lat.toFixed(5)}, {lng.toFixed(5)}
</div>
<div style={{ color: "#555" }}>
{toNum(device.lastSpeed) ?? 0} km/h · {device.lastCourse ?? 0}°
</div>
<div style={{ color: "#777", marginTop: 4 }}>{address ?? "Locating…"}</div>
<div style={{ color: "#777", marginTop: 4 }}>
{address ?? "Locating…"}
</div>
</div>
</InfoWindow>
);
@@ -182,7 +207,8 @@ export function TrackingPage() {
const { data: vehiclesData } = useQuery({
queryKey: ["vehicles", "all"],
queryFn: async () => (await vehiclesService.getAll({ limit: 1000 })).data ?? [],
queryFn: async () =>
(await vehiclesService.getAll({ limit: 1000 })).data ?? [],
});
const vehicleOptions = useMemo(
() =>
@@ -197,7 +223,10 @@ export function TrackingPage() {
() =>
devices
.map((d) => ({ d, lat: toNum(d.lastLat), lng: toNum(d.lastLng) }))
.filter((x): x is { d: GpsDevice; lat: number; lng: number } => x.lat != null && x.lng != null),
.filter(
(x): x is { d: GpsDevice; lat: number; lng: number } =>
x.lat != null && x.lng != null,
),
[devices],
);
@@ -207,19 +236,31 @@ export function TrackingPage() {
// Route history for the selected device's vehicle (chronological trail).
const { data: history = [] } = useQuery({
queryKey: ["gps", "history", selected?.vehicleId],
queryFn: async () => (await gpsTrackingService.history(selected!.vehicleId!, 300)).data ?? [],
queryFn: async () =>
(await gpsTrackingService.history(selected!.vehicleId!, 300)).data ?? [],
enabled: Boolean(selected?.vehicleId),
});
const trail = useMemo(
() => [...history].reverse().map((h) => ({ lat: Number(h.lat), lng: Number(h.lng) })),
() =>
[...history]
.reverse()
.map((h) => ({ lat: Number(h.lat), lng: Number(h.lng) })),
[history],
);
// Teardrop pin colored by state with a white truck glyph inside.
const markerIcon = (d: GpsDevice, selectedFlag: boolean): google.maps.Icon | undefined => {
const markerIcon = (
d: GpsDevice,
selectedFlag: boolean,
): google.maps.Icon | undefined => {
// Maps API loads async — Size/Point classes may not exist yet at first render.
if (typeof google === "undefined" || !google.maps?.Size || !mapsReady) return undefined;
const color = selectedFlag ? freightBrand.primary : d.online ? "#2f80ed" : "#95a5a6";
if (typeof google === "undefined" || !google.maps?.Size || !mapsReady)
return undefined;
const color = selectedFlag
? freightBrand.primary
: d.online
? "#2f80ed"
: "#95a5a6";
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="40" height="48" viewBox="0 0 40 48">
<path d="M20 2C10 2 2 10 2 20c0 12 18 26 18 26s18-14 18-26C38 10 30 2 20 2Z" fill="${color}" stroke="#ffffff" stroke-width="1.5"/>
<g transform="translate(8,7)" fill="none" stroke="#ffffff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
@@ -258,8 +299,13 @@ export function TrackingPage() {
},
onError: (err: unknown) => {
const description =
(err as { response?: { data?: { message?: string } } })?.response?.data?.message ?? "Failed";
toast({ title: editDevice ? "Update failed" : "Registration failed", description, variant: "destructive" });
(err as { response?: { data?: { message?: string } } })?.response?.data
?.message ?? "Failed";
toast({
title: editDevice ? "Update failed" : "Registration failed",
description,
variant: "destructive",
});
},
});
@@ -285,15 +331,25 @@ export function TrackingPage() {
return (
<Container size="xl" py="xl" px="lg">
<Breadcrumbs items={[{ label: "Fleet" }, { label: "Vehicle Tracking" }]} />
<Breadcrumbs
items={[{ label: "Fleet" }, { label: "Vehicle Tracking" }]}
/>
<Group justify="space-between" mb="xl">
<div>
<Text fw={700} size="xl">Real-Time Vehicle Tracking</Text>
<Text c="dimmed" size="sm">Live GPS positions from GT06 trackers</Text>
<Text fw={700} size="xl">
Real-Time Vehicle Tracking
</Text>
<Text c="dimmed" size="sm">
Live GPS positions from GT06 trackers
</Text>
</div>
{canManage && (
<Button leftSection={<Plus size={16} />} color="edr-green" onClick={openRegister}>
<Button
leftSection={<Plus size={16} />}
color="edr-green"
onClick={openRegister}
>
Register tracker
</Button>
)}
@@ -312,36 +368,82 @@ export function TrackingPage() {
</Group>
</Card.Section>
<Card.Section p="md">
<Box style={{ height: 500, width: "100%", borderRadius: 8, overflow: "hidden" }}>
<APIProvider apiKey={GOOGLE_MAPS_API_KEY}>
<GoogleMap
defaultCenter={DEFAULT_CENTER}
defaultZoom={7}
gestureHandling="greedy"
disableDefaultUI={false}
style={{ width: "100%", height: "100%" }}
<Box
style={{
height: 500,
width: "100%",
borderRadius: 8,
overflow: "hidden",
}}
>
{!GOOGLE_MAPS_API_KEY ? (
// Name the missing variable rather than showing an empty map: the
// device list beside this still works, so a blank panel reads as
// "no GPS fixes" instead of "no map key".
<Box
style={{
height: "100%",
display: "flex",
alignItems: "center",
justifyContent: "center",
padding: 24,
textAlign: "center",
border: "1px solid #F0D2A8",
borderRadius: 8,
background: "#FFF9F0",
}}
>
<ReadyProbe onReady={() => setMapsReady(true)} />
{positioned.map(({ d, lat, lng }) => (
<Marker
key={d.id}
position={{ lat, lng }}
title={`${deviceLabel(d)}\n${lat.toFixed(5)}, ${lng.toFixed(5)}`}
icon={markerIcon(d, d.id === selectedId)}
onClick={() => setSelectedId(d.id)}
onMouseOver={() => setHoverId(d.id)}
<Text fz="sm" c="#8A5A16">
Map unavailable <code>VITE_GOOGLE_MAPS_API_KEY</code> is
not set. Add a Google Maps key with the Maps JavaScript
API and Places API enabled to this app&apos;s{" "}
<code>.env</code>, then restart the dev server. Device
positions below are unaffected.
</Text>
</Box>
) : (
<APIProvider apiKey={GOOGLE_MAPS_API_KEY}>
<GoogleMap
defaultCenter={DEFAULT_CENTER}
defaultZoom={7}
gestureHandling="greedy"
disableDefaultUI={false}
style={{ width: "100%", height: "100%" }}
>
<ReadyProbe onReady={() => setMapsReady(true)} />
{positioned.map(({ d, lat, lng }) => (
<Marker
key={d.id}
position={{ lat, lng }}
title={`${deviceLabel(d)}\n${lat.toFixed(5)}, ${lng.toFixed(5)}`}
icon={markerIcon(d, d.id === selectedId)}
onClick={() => setSelectedId(d.id)}
onMouseOver={() => setHoverId(d.id)}
/>
))}
{(() => {
const h = positioned.find((p) => p.d.id === hoverId);
return h ? (
<HoverInfo
device={h.d}
lat={h.lat}
lng={h.lng}
onClose={() => setHoverId(null)}
/>
) : null;
})()}
<FitBounds
points={positioned.map((p) => ({
lat: p.lat,
lng: p.lng,
}))}
/>
))}
{(() => {
const h = positioned.find((p) => p.d.id === hoverId);
return h ? (
<HoverInfo device={h.d} lat={h.lat} lng={h.lng} onClose={() => setHoverId(null)} />
) : null;
})()}
<FitBounds points={positioned.map((p) => ({ lat: p.lat, lng: p.lng }))} />
{selected?.vehicleId && trail.length > 1 && <RouteTrail path={trail} />}
</GoogleMap>
</APIProvider>
{selected?.vehicleId && trail.length > 1 && (
<RouteTrail path={trail} />
)}
</GoogleMap>
</APIProvider>
)}
</Box>
{positioned.length === 0 && (
<Text size="sm" c="dimmed" ta="center" mt="sm">
@@ -361,11 +463,19 @@ export function TrackingPage() {
<Group justify="space-between">
<Text fw={500}>{deviceLabel(selected)}</Text>
<Group gap="xs">
<Badge color={selected.online ? "edr-green" : "gray"} leftSection={<Activity size={12} />}>
<Badge
color={selected.online ? "edr-green" : "gray"}
leftSection={<Activity size={12} />}
>
{selected.online ? "Live" : "Offline"}
</Badge>
{canManage && (
<ActionIcon variant="subtle" color="red" aria-label="Remove tracker" onClick={() => deleteMutation.mutate(selected.id)}>
<ActionIcon
variant="subtle"
color="red"
aria-label="Remove tracker"
onClick={() => deleteMutation.mutate(selected.id)}
>
<Trash2 size={16} />
</ActionIcon>
)}
@@ -373,21 +483,55 @@ export function TrackingPage() {
</Group>
<SimpleGrid cols={2} spacing="sm">
<StatBox label="Latitude" value={toNum(selected.lastLat)?.toFixed(5) ?? "—"} />
<StatBox label="Longitude" value={toNum(selected.lastLng)?.toFixed(5) ?? "—"} />
<StatBox label="Speed" value={`${toNum(selected.lastSpeed) ?? 0} km/h`} />
<StatBox label="Course" value={`${selected.lastCourse ?? 0}°`} />
<StatBox label="Voltage" value={selected.voltageLevel != null ? `${selected.voltageLevel}/6` : "—"} />
<StatBox label="GSM" value={selected.gsmLevel != null ? `${selected.gsmLevel}/4` : "—"} />
<StatBox
label="Latitude"
value={toNum(selected.lastLat)?.toFixed(5) ?? "—"}
/>
<StatBox
label="Longitude"
value={toNum(selected.lastLng)?.toFixed(5) ?? "—"}
/>
<StatBox
label="Speed"
value={`${toNum(selected.lastSpeed) ?? 0} km/h`}
/>
<StatBox
label="Course"
value={`${selected.lastCourse ?? 0}°`}
/>
<StatBox
label="Voltage"
value={
selected.voltageLevel != null
? `${selected.voltageLevel}/6`
: "—"
}
/>
<StatBox
label="GSM"
value={
selected.gsmLevel != null
? `${selected.gsmLevel}/4`
: "—"
}
/>
</SimpleGrid>
<div>
<Text size="xs" c="dimmed">IMEI</Text>
<Text fw={500} size="sm">{selected.imei}</Text>
<Text size="xs" c="dimmed">
IMEI
</Text>
<Text fw={500} size="sm">
{selected.imei}
</Text>
</div>
<div>
<Text size="xs" c="dimmed">Last fix</Text>
<Text fw={500} size="sm">{fmtTime(selected.lastFixAt)}</Text>
<Text size="xs" c="dimmed">
Last fix
</Text>
<Text fw={500} size="sm">
{fmtTime(selected.lastFixAt)}
</Text>
</div>
{selected.vehicleId && (
<Text size="xs" c="dimmed">
@@ -400,7 +544,9 @@ export function TrackingPage() {
placeholder="Unassigned"
data={vehicleOptions}
value={selected.vehicleId ?? null}
onChange={(v) => assignMutation.mutate({ id: selected.id, vehicleId: v })}
onChange={(v) =>
assignMutation.mutate({ id: selected.id, vehicleId: v })
}
disabled={!canManage}
searchable
clearable
@@ -418,24 +564,43 @@ export function TrackingPage() {
{devices.map((d) => (
<Table.Tr
key={d.id}
style={{ cursor: "pointer", backgroundColor: d.id === selectedId ? freightBrand.mutedBg : "transparent" }}
style={{
cursor: "pointer",
backgroundColor:
d.id === selectedId
? freightBrand.mutedBg
: "transparent",
}}
onClick={() => setSelectedId(d.id)}
>
<Table.Td>
<Stack gap={0}>
<Text size="sm" fw={600}>{deviceLabel(d)}</Text>
<Text size="xs" c="dimmed">{toNum(d.lastSpeed) ?? 0} km/h · {fmtTime(d.lastFixAt)}</Text>
<Text size="sm" fw={600}>
{deviceLabel(d)}
</Text>
<Text size="xs" c="dimmed">
{toNum(d.lastSpeed) ?? 0} km/h ·{" "}
{fmtTime(d.lastFixAt)}
</Text>
</Stack>
</Table.Td>
<Table.Td align="right">
<Group gap={6} justify="flex-end" wrap="nowrap">
<Badge color={d.online ? "edr-green" : "gray"} size="sm">{d.online ? "Live" : "Offline"}</Badge>
<Badge
color={d.online ? "edr-green" : "gray"}
size="sm"
>
{d.online ? "Live" : "Offline"}
</Badge>
{canManage && (
<ActionIcon
variant="subtle"
size="sm"
aria-label="Edit tracker"
onClick={(e) => { e.stopPropagation(); openEdit(d); }}
onClick={(e) => {
e.stopPropagation();
openEdit(d);
}}
>
<Pencil size={15} />
</ActionIcon>
@@ -447,7 +612,9 @@ export function TrackingPage() {
{devices.length === 0 && (
<Table.Tr>
<Table.Td colSpan={2}>
<Text size="sm" c="dimmed" ta="center" py="md">No trackers registered yet.</Text>
<Text size="sm" c="dimmed" ta="center" py="md">
No trackers registered yet.
</Text>
</Table.Td>
</Table.Tr>
)}
@@ -493,7 +660,9 @@ export function TrackingPage() {
clearable
/>
<Group justify="flex-end">
<Button variant="default" onClick={() => setModalOpen(false)}>Cancel</Button>
<Button variant="default" onClick={() => setModalOpen(false)}>
Cancel
</Button>
<Button
loading={saveMutation.isPending}
disabled={!form.imei.trim()}

View File

@@ -15,6 +15,7 @@ import { useQuery } from "@tanstack/react-query";
import { ArrowLeft, Download } from "lucide-react";
import { useAuth } from "@/auth/useAuth";
import { FREIGHT_PERMS, hasPermission } from "@/lib/permissions";
import { EimsFilingCard } from "@/components/invoices/EimsFilingCard";
import { useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
@@ -165,6 +166,8 @@ export default function InvoiceDetailPage() {
</Stack>
</Card>
<EimsFilingCard invoiceId={invoice.id} />
<Card>
<Stack gap="md">
<Text fw={600} c="edr-text">

View File

@@ -0,0 +1,95 @@
import { Accordion, ActionIcon, Center, Group, Text, Tooltip } from "@mantine/core";
import { ChevronDown, ChevronUp, Trash2 } from "lucide-react";
import type { ReactNode } from "react";
interface AccordionRowProps {
value: string;
/** Collapsed summary — the heading, question or card title. */
title: string;
/** Small dimmed line under the title, e.g. a body excerpt. */
subtitle?: string;
index: number;
length: number;
onMove: (delta: number) => void;
onRemove: () => void;
children: ReactNode;
}
/**
* One collapsible item with reorder and delete controls in its header.
*
* Collapsing is the point: a legal document has fifteen sections and the FAQ
* seventeen answers, and rendering every textarea expanded turned each tab into
* an unnavigable mile of boxes. Collapsed, the tab reads as the list of
* headings the customer actually sees.
*
* The buttons sit outside `Accordion.Control` so clicking one does not also
* toggle the panel.
*/
export function AccordionRow({
value,
title,
subtitle,
index,
length,
onMove,
onRemove,
children,
}: AccordionRowProps) {
return (
<Accordion.Item value={value}>
<Center>
<Accordion.Control>
<div style={{ minWidth: 0 }}>
<Text fw={500} truncate>
{title || <Text span c="dimmed">(untitled)</Text>}
</Text>
{subtitle && (
<Text size="xs" c="dimmed" truncate>
{subtitle}
</Text>
)}
</div>
</Accordion.Control>
<Group gap={2} wrap="nowrap" pr="sm">
<Tooltip label="Move up">
<ActionIcon
variant="subtle"
color="gray"
disabled={index === 0}
onClick={() => onMove(-1)}
>
<ChevronUp size={16} />
</ActionIcon>
</Tooltip>
<Tooltip label="Move down">
<ActionIcon
variant="subtle"
color="gray"
disabled={index === length - 1}
onClick={() => onMove(1)}
>
<ChevronDown size={16} />
</ActionIcon>
</Tooltip>
<Tooltip label="Remove">
<ActionIcon variant="subtle" color="red" onClick={onRemove}>
<Trash2 size={16} />
</ActionIcon>
</Tooltip>
</Group>
</Center>
<Accordion.Panel>{children}</Accordion.Panel>
</Accordion.Item>
);
}
/** First line of a markdown body, for an accordion subtitle. */
export function excerpt(markdown: string, max = 90): string {
const line = markdown.replace(/[#*`>-]/g, "").trim().split("\n")[0] ?? "";
return line.length > max ? `${line.slice(0, max)}` : line;
}
export default AccordionRow;

View File

@@ -0,0 +1,242 @@
import type { PortalFaqContent, PortalFaqGroup } from "@edr/types";
import {
Accordion,
Badge,
Button,
Card,
Group,
Stack,
Switch,
TextInput,
} from "@mantine/core";
import { Plus } from "lucide-react";
import { AccordionRow, excerpt } from "./AccordionRow";
import { moveAt, newId, removeAt, replaceAt } from "./array-helpers";
import { MarkdownEditor, MarkdownHint } from "./MarkdownEditor";
interface FaqEditorProps {
value: PortalFaqContent;
onChange: (next: PortalFaqContent) => void;
}
const EMPTY_FOOTER = {
heading: "Still need a hand?",
body: "",
ctaLabel: "Go to Help & Support",
ctaTo: "/help",
};
export function FaqEditor({ value, onChange }: FaqEditorProps) {
const setGroups = (groups: PortalFaqGroup[]) => onChange({ ...value, groups });
const setGroup = (index: number, next: PortalFaqGroup) =>
setGroups(replaceAt(value.groups, index, next));
return (
<Stack gap="lg">
<Card withBorder padding="md" radius="md">
<Stack gap="md">
<TextInput
label="Page title"
value={value.title}
onChange={(e) =>
onChange({ ...value, title: e.currentTarget.value })
}
/>
<TextInput
label="Subtitle"
value={value.subtitle}
onChange={(e) =>
onChange({ ...value, subtitle: e.currentTarget.value })
}
/>
</Stack>
</Card>
<MarkdownHint />
<Accordion variant="separated" radius="md" chevronPosition="left">
{value.groups.map((group, groupIndex) => (
<AccordionRow
key={group.id}
value={group.id}
title={group.title}
subtitle={`${group.items.length} question${group.items.length === 1 ? "" : "s"}`}
index={groupIndex}
length={value.groups.length}
onMove={(delta) => setGroups(moveAt(value.groups, groupIndex, delta))}
onRemove={() => setGroups(removeAt(value.groups, groupIndex))}
>
<Stack gap="md">
<TextInput
label="Group title"
value={group.title}
onChange={(e) =>
setGroup(groupIndex, {
...group,
title: e.currentTarget.value,
})
}
/>
<Accordion variant="contained" radius="sm" chevronPosition="left">
{group.items.map((item, itemIndex) => (
<AccordionRow
key={item.id}
value={item.id}
title={item.question}
subtitle={excerpt(item.answer, 70)}
index={itemIndex}
length={group.items.length}
onMove={(delta) =>
setGroup(groupIndex, {
...group,
items: moveAt(group.items, itemIndex, delta),
})
}
onRemove={() =>
setGroup(groupIndex, {
...group,
items: removeAt(group.items, itemIndex),
})
}
>
<Stack gap="md">
<TextInput
label="Question"
value={item.question}
onChange={(e) =>
setGroup(groupIndex, {
...group,
items: replaceAt(group.items, itemIndex, {
...item,
question: e.currentTarget.value,
}),
})
}
/>
<MarkdownEditor
label="Answer"
value={item.answer}
onChange={(answer) =>
setGroup(groupIndex, {
...group,
items: replaceAt(group.items, itemIndex, {
...item,
answer,
}),
})
}
/>
</Stack>
</AccordionRow>
))}
</Accordion>
<Button
variant="subtle"
size="xs"
leftSection={<Plus size={14} />}
style={{ alignSelf: "flex-start" }}
onClick={() =>
setGroup(groupIndex, {
...group,
items: [
...group.items,
{ id: newId(), question: "New question", answer: "" },
],
})
}
>
Add question
</Button>
</Stack>
</AccordionRow>
))}
</Accordion>
<Button
variant="light"
leftSection={<Plus size={16} />}
style={{ alignSelf: "flex-start" }}
onClick={() =>
setGroups([
...value.groups,
{ id: newId(), title: "New group", items: [] },
])
}
>
Add group
</Button>
<Card withBorder padding="md" radius="md">
<Stack gap="md">
<Group justify="space-between">
<Switch
label="Closing card"
checked={Boolean(value.footer)}
onChange={(e) =>
onChange({
...value,
footer: e.currentTarget.checked ? EMPTY_FOOTER : null,
})
}
/>
{!value.footer && <Badge variant="light" color="gray">Hidden</Badge>}
</Group>
{value.footer && (
<>
<TextInput
label="Heading"
value={value.footer.heading}
onChange={(e) =>
onChange({
...value,
footer: { ...value.footer!, heading: e.currentTarget.value },
})
}
/>
<MarkdownEditor
label="Body"
value={value.footer.body}
onChange={(body) =>
onChange({ ...value, footer: { ...value.footer!, body } })
}
/>
<Group grow>
<TextInput
label="Button label"
value={value.footer.ctaLabel}
onChange={(e) =>
onChange({
...value,
footer: {
...value.footer!,
ctaLabel: e.currentTarget.value,
},
})
}
/>
<TextInput
label="Button link"
description="A portal route (/help) or an https:// URL"
value={value.footer.ctaTo}
onChange={(e) =>
onChange({
...value,
footer: { ...value.footer!, ctaTo: e.currentTarget.value },
})
}
/>
</Group>
</>
)}
</Stack>
</Card>
</Stack>
);
}
export default FaqEditor;

View File

@@ -0,0 +1,125 @@
import type { PortalHelpContent, PortalHelpSection } from "@edr/types";
import { Accordion, Button, Card, Divider, Stack, TextInput } from "@mantine/core";
import { Plus } from "lucide-react";
import { AccordionRow, excerpt } from "./AccordionRow";
import { moveAt, newId, removeAt, replaceAt } from "./array-helpers";
import { MarkdownEditor, MarkdownHint } from "./MarkdownEditor";
import { MediaManager } from "./MediaManager";
interface HelpEditorProps {
value: PortalHelpContent;
onChange: (next: PortalHelpContent) => void;
}
/**
* The help page is built, not filled in: an ordered list of sections, each a
* heading plus free markdown plus any images or videos. Nothing about the page
* is fixed except its title, so support can add, reorder or drop a section
* without a code change.
*/
export function HelpEditor({ value, onChange }: HelpEditorProps) {
// A row written before the free-form conversion has no `sections` at all.
// Tolerate it rather than crashing the tab: the migration rewrites it, but
// an environment can be mid-deploy.
const sections = value.sections ?? [];
const setSections = (next: PortalHelpSection[]) =>
onChange({ ...value, sections: next });
return (
<Stack gap="lg">
<Card withBorder padding="md" radius="md">
<Stack gap="md">
<TextInput
label="Page title"
value={value.title}
onChange={(e) =>
onChange({ ...value, title: e.currentTarget.value })
}
/>
<TextInput
label="Subtitle"
value={value.subtitle}
onChange={(e) =>
onChange({ ...value, subtitle: e.currentTarget.value })
}
/>
</Stack>
</Card>
<MarkdownHint />
<Accordion variant="separated" radius="md" chevronPosition="left">
{sections.map((section, index) => (
<AccordionRow
key={section.id}
value={section.id}
title={section.heading}
subtitle={
section.media.length
? `${excerpt(section.body, 60)} · ${section.media.length} attachment${section.media.length === 1 ? "" : "s"}`
: excerpt(section.body)
}
index={index}
length={sections.length}
onMove={(delta) => setSections(moveAt(sections, index, delta))}
onRemove={() => setSections(removeAt(sections, index))}
>
<Stack gap="md">
<TextInput
label="Heading"
value={section.heading}
onChange={(e) =>
setSections(
replaceAt(sections, index, {
...section,
heading: e.currentTarget.value,
}),
)
}
/>
<MarkdownEditor
label="Body"
value={section.body}
onChange={(body) =>
setSections(
replaceAt(sections, index, { ...section, body }),
)
}
/>
<Divider />
<MediaManager
value={section.media}
onChange={(media) =>
setSections(
replaceAt(sections, index, { ...section, media }),
)
}
/>
</Stack>
</AccordionRow>
))}
</Accordion>
<Button
variant="light"
leftSection={<Plus size={16} />}
style={{ alignSelf: "flex-start" }}
onClick={() =>
setSections([
...sections,
{ id: newId(), heading: "New section", body: "", media: [] },
])
}
>
Add section
</Button>
</Stack>
);
}
export default HelpEditor;

View File

@@ -0,0 +1,110 @@
import type { PortalLegalContent } from "@edr/types";
import { Accordion, Button, Card, Group, Stack, TextInput } from "@mantine/core";
import { Plus } from "lucide-react";
import { AccordionRow, excerpt } from "./AccordionRow";
import { moveAt, newId, removeAt, replaceAt } from "./array-helpers";
import { MarkdownEditor, MarkdownHint } from "./MarkdownEditor";
interface LegalDocEditorProps {
value: PortalLegalContent;
onChange: (next: PortalLegalContent) => void;
}
/** Shared by the Privacy and Terms tabs — the two documents have one shape. */
export function LegalDocEditor({ value, onChange }: LegalDocEditorProps) {
const setSections = (sections: PortalLegalContent["sections"]) =>
onChange({ ...value, sections });
return (
<Stack gap="lg">
<Card withBorder padding="md" radius="md">
<Stack gap="md">
<Group grow align="flex-start">
<TextInput
label="Page title"
value={value.title}
onChange={(e) =>
onChange({ ...value, title: e.currentTarget.value })
}
/>
<TextInput
label="Last updated"
description="Free text, e.g. 6 August 2026"
value={value.lastUpdated}
onChange={(e) =>
onChange({ ...value, lastUpdated: e.currentTarget.value })
}
/>
</Group>
<TextInput
label="Subtitle"
value={value.subtitle}
onChange={(e) =>
onChange({ ...value, subtitle: e.currentTarget.value })
}
/>
</Stack>
</Card>
<MarkdownHint />
<Accordion variant="separated" radius="md" chevronPosition="left">
{value.sections.map((section, index) => (
<AccordionRow
key={section.id}
value={section.id}
title={section.heading}
subtitle={excerpt(section.body)}
index={index}
length={value.sections.length}
onMove={(delta) => setSections(moveAt(value.sections, index, delta))}
onRemove={() => setSections(removeAt(value.sections, index))}
>
<Stack gap="md">
<TextInput
label="Heading"
value={section.heading}
onChange={(e) =>
setSections(
replaceAt(value.sections, index, {
...section,
heading: e.currentTarget.value,
}),
)
}
/>
<MarkdownEditor
label="Body"
value={section.body}
onChange={(body) =>
setSections(
replaceAt(value.sections, index, { ...section, body }),
)
}
/>
</Stack>
</AccordionRow>
))}
</Accordion>
<Button
variant="light"
leftSection={<Plus size={16} />}
style={{ alignSelf: "flex-start" }}
onClick={() =>
setSections([
...value.sections,
{ id: newId(), heading: "New section", body: "" },
])
}
>
Add section
</Button>
</Stack>
);
}
export default LegalDocEditor;

View File

@@ -0,0 +1,24 @@
import ReactMarkdown from "react-markdown";
// Same preflight fix the editor needs — Mantine's `Typography` defines its list
// and margin rules with `:where()`, which Tailwind's preflight outranks, so
// bullets rendered without markers here too.
import "./markdown-editor.css";
/**
* Read-only markdown rendering for the version-history preview. Editing goes
* through `MarkdownEditor` (MDXEditor); this is only for showing what an old
* version said.
*
* Same options as the portal's renderer — no `rehype-raw`, no custom
* `urlTransform` — so neither app grows an HTML-injection surface.
*/
export function Markdown({ children }: { children: string }) {
return (
<div className="edr-md-content">
<ReactMarkdown>{children}</ReactMarkdown>
</div>
);
}
export default Markdown;

View File

@@ -0,0 +1,142 @@
import { PORTAL_MEDIA_URI_SCHEME } from "@edr/types";
import { Box, Stack, Text } from "@mantine/core";
import {
BlockTypeSelect,
BoldItalicUnderlineToggles,
CreateLink,
InsertImage,
InsertThematicBreak,
ListsToggle,
MDXEditor,
UndoRedo,
headingsPlugin,
imagePlugin,
linkDialogPlugin,
linkPlugin,
listsPlugin,
markdownShortcutPlugin,
quotePlugin,
thematicBreakPlugin,
toolbarPlugin,
} from "@mdxeditor/editor";
import "@mdxeditor/editor/style.css";
import { portalContentService } from "@/services/portal-content.service";
// Undoes Tailwind's preflight inside the editor's content area — see the file.
import "./markdown-editor.css";
interface MarkdownEditorProps {
label: string;
value: string;
onChange: (next: string) => void;
description?: string;
}
/**
* Signed URLs are per-request and short-lived, so previews are memoised for the
* life of the page rather than re-signed on every keystroke re-render.
*/
const previewCache = new Map<string, Promise<string>>();
/**
* Inserted images are stored as `minio:<key>`, never as the signed URL the
* upload returns: a presigned URL expires, so persisting one would leave every
* embedded image broken a few hours later. `imagePreviewHandler` resolves the
* ref back to a temporary URL purely for display, on both sides of the wire.
*/
function resolvePreview(url: string): Promise<string> {
if (!url.startsWith(PORTAL_MEDIA_URI_SCHEME)) return Promise.resolve(url);
const key = url.slice(PORTAL_MEDIA_URI_SCHEME.length);
let pending = previewCache.get(key);
if (!pending) {
pending = portalContentService
.mediaUrl(key)
.catch(() => url); // show a broken image rather than blowing up the editor
previewCache.set(key, pending);
}
return pending;
}
export function MarkdownEditor({
label,
value,
onChange,
description,
}: MarkdownEditorProps) {
return (
<Stack gap={6}>
<Text size="sm" fw={500}>
{label}
</Text>
{description && (
<Text size="xs" c="dimmed">
{description}
</Text>
)}
<Box
style={{
border: "1px solid var(--mantine-color-gray-3)",
borderRadius: "var(--mantine-radius-sm)",
}}
>
<MDXEditor
markdown={value}
contentEditableClassName="edr-md-content"
// MDXEditor re-serialises the markdown once on mount, which differs
// harmlessly from what was stored (spacing, escaping). Reporting that
// as an edit made every tab open "unsaved" and let a Save write a
// no-op version, so the normalisation pass is ignored.
onChange={(markdown, initialMarkdownNormalize) => {
if (!initialMarkdownNormalize) onChange(markdown);
}}
plugins={[
headingsPlugin(),
listsPlugin(),
quotePlugin(),
linkPlugin(),
linkDialogPlugin(),
thematicBreakPlugin(),
imagePlugin({
imageUploadHandler: async (file) => {
const { key } = await portalContentService.uploadMedia(file);
return `${PORTAL_MEDIA_URI_SCHEME}${key}`;
},
imagePreviewHandler: resolvePreview,
}),
markdownShortcutPlugin(),
toolbarPlugin({
toolbarContents: () => (
<>
<UndoRedo />
<BoldItalicUnderlineToggles />
<BlockTypeSelect />
<ListsToggle />
<CreateLink />
<InsertImage />
<InsertThematicBreak />
</>
),
}),
]}
/>
</Box>
</Stack>
);
}
/** Reminder of the substitution tokens, rendered once per tab. */
export function MarkdownHint() {
return (
<Text size="xs" c="dimmed">
Placeholders resolve from the Contact tab, so one edit there updates every
page: <code>{"{{supportEmail}}"}</code> · <code>{"{{supportPhone}}"}</code>{" "}
· <code>{"{{supportOffice}}"}</code> · <code>{"{{supportHours}}"}</code> ·{" "}
<code>{"{{supportPhoneTel}}"}</code> (inside a tel: link).
</Text>
);
}
export default MarkdownEditor;

View File

@@ -0,0 +1,122 @@
import type { PortalMedia } from "@edr/types";
import {
ActionIcon,
Button,
Group,
Paper,
Stack,
Text,
TextInput,
Tooltip,
} from "@mantine/core";
import { Film, Image as ImageIcon, Trash2, Upload } from "lucide-react";
import { useRef, useState } from "react";
import toast from "react-hot-toast";
import { portalContentService } from "@/services/portal-content.service";
import { newId, removeAt, replaceAt } from "./array-helpers";
interface MediaManagerProps {
value: PortalMedia[];
onChange: (next: PortalMedia[]) => void;
}
/**
* Attachments for one help section. Uploads store the MinIO object *key*; the
* signed URL the upload returns is short-lived and is never persisted, so the
* list shows the key rather than pretending to be a gallery.
*/
export function MediaManager({ value, onChange }: MediaManagerProps) {
const inputRef = useRef<HTMLInputElement>(null);
const [uploading, setUploading] = useState(false);
const upload = async (file: File) => {
setUploading(true);
try {
const { key, kind } = await portalContentService.uploadMedia(file);
onChange([...value, { id: newId(), kind, src: key, caption: null }]);
} catch (error) {
const message =
(error as { response?: { data?: { message?: string } } })?.response?.data
?.message ?? "Upload failed";
toast.error(Array.isArray(message) ? message.join(", ") : message);
} finally {
setUploading(false);
if (inputRef.current) inputRef.current.value = "";
}
};
return (
<Stack gap="xs">
<Text size="sm" fw={500}>
Attachments
</Text>
{value.map((item, index) => (
<Paper key={item.id} withBorder p="xs" radius="sm">
<Group wrap="nowrap" align="center" gap="sm">
{item.kind === "video" ? (
<Film size={18} />
) : (
<ImageIcon size={18} />
)}
<Stack gap={2} style={{ flex: 1, minWidth: 0 }}>
<Text size="xs" c="dimmed" truncate>
{item.src}
</Text>
<TextInput
size="xs"
placeholder="Caption (optional)"
value={item.caption ?? ""}
onChange={(e) =>
onChange(
replaceAt(value, index, {
...item,
caption: e.currentTarget.value || null,
}),
)
}
/>
</Stack>
<Tooltip label="Remove attachment">
<ActionIcon
variant="subtle"
color="red"
onClick={() => onChange(removeAt(value, index))}
>
<Trash2 size={16} />
</ActionIcon>
</Tooltip>
</Group>
</Paper>
))}
<input
ref={inputRef}
type="file"
accept="image/*,video/*"
hidden
onChange={(e) => {
const file = e.currentTarget.files?.[0];
if (file) void upload(file);
}}
/>
<Button
variant="light"
size="xs"
loading={uploading}
leftSection={<Upload size={14} />}
style={{ alignSelf: "flex-start" }}
onClick={() => inputRef.current?.click()}
>
Upload image or video
</Button>
</Stack>
);
}
export default MediaManager;

View File

@@ -0,0 +1,261 @@
import type {
PortalFaqContent,
PortalHelpContent,
PortalLegalContent,
PortalSupportContact,
SupportDocPayload,
SupportDocSlug,
} from "@edr/types";
import {
Badge,
Button,
Card,
Group,
Loader,
Stack,
Tabs,
Text,
TextInput,
} from "@mantine/core";
import { History, RotateCcw, Save } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { PageContainer, PageHeader } from "@/components/page";
import {
usePortalDoc,
useUpdatePortalDoc,
} from "@/hooks/portal-content/usePortalContentAdmin";
import { FaqEditor } from "./FaqEditor";
import { HelpEditor } from "./HelpEditor";
import { LegalDocEditor } from "./LegalDocEditor";
import { VersionHistoryModal } from "./VersionHistoryModal";
const TABS: { slug: SupportDocSlug; label: string }[] = [
{ slug: "CONTACT", label: "Contact" },
{ slug: "HELP", label: "Help" },
{ slug: "FAQ", label: "FAQ" },
{ slug: "PRIVACY", label: "Privacy" },
{ slug: "TERMS", label: "Terms" },
];
/**
* Edits the copy on the freight portal's public pages — /help, /faq, /terms,
* /privacy — and the support contact block all four quote.
*
* Each tab is a local draft saved in one PATCH of the whole document, rather
* than a mutation per field. That is what makes one editorial change equal one
* version, which is the difference between a history you can read and a history
* of keystrokes.
*/
export default function PortalContentPage() {
const [active, setActive] = useState<SupportDocSlug>("CONTACT");
return (
<PageContainer>
<PageHeader
title="Portal content"
subtitle="Help, FAQ and legal copy shown to customers on the public portal pages. Body text is markdown, every save is versioned, and any version can be restored."
/>
<Tabs
value={active}
onChange={(value) => setActive(value as SupportDocSlug)}
keepMounted={false}
>
<Tabs.List mb="lg">
{TABS.map((tab) => (
<Tabs.Tab key={tab.slug} value={tab.slug}>
{tab.label}
</Tabs.Tab>
))}
</Tabs.List>
{TABS.map((tab) => (
<Tabs.Panel key={tab.slug} value={tab.slug}>
<DocumentTab slug={tab.slug} />
</Tabs.Panel>
))}
</Tabs>
</PageContainer>
);
}
function DocumentTab({ slug }: { slug: SupportDocSlug }) {
const { data, isLoading } = usePortalDoc(slug);
const update = useUpdatePortalDoc(slug);
const [draft, setDraft] = useState<SupportDocPayload | null>(null);
const [note, setNote] = useState("");
const [historyOpen, setHistoryOpen] = useState(false);
// Reseed only when the server's version number moves (load, save, restore).
// Keying off `data` itself would let a background refetch wipe edits that are
// still in progress.
const seededVersion = useRef<number | null>(null);
useEffect(() => {
if (data && seededVersion.current !== data.version) {
seededVersion.current = data.version;
setDraft(data.payload);
setNote("");
}
}, [data]);
if (isLoading || !data || !draft) return <Loader size="sm" />;
const dirty = JSON.stringify(draft) !== JSON.stringify(data.payload);
const reset = () => {
setDraft(data.payload);
setNote("");
};
return (
<Stack gap="lg">
{/* Sticky: these tabs are long lists, and a Save button that scrolls out
of reach is the fastest way to lose an edit. */}
<Card
withBorder
padding="sm"
radius="md"
style={{
position: "sticky",
top: 0,
zIndex: 2,
backgroundColor: "var(--mantine-color-body)",
}}
>
<Group justify="space-between" align="center" wrap="wrap" gap="sm">
<Group gap="xs">
<Badge variant="light" color={dirty ? "orange" : "gray"}>
v{data.version}
</Badge>
<Text size="sm" c={dirty ? "orange" : "dimmed"}>
{dirty ? "Unsaved changes" : "Saved"}
</Text>
</Group>
<Group gap="xs" align="center">
{dirty && (
<TextInput
size="sm"
placeholder="Change note (optional)"
value={note}
onChange={(e) => setNote(e.currentTarget.value)}
w={240}
/>
)}
<Button
variant="default"
leftSection={<History size={16} />}
onClick={() => setHistoryOpen(true)}
>
History
</Button>
<Button
variant="subtle"
leftSection={<RotateCcw size={16} />}
disabled={!dirty}
onClick={reset}
>
Reset
</Button>
<Button
leftSection={<Save size={16} />}
disabled={!dirty}
loading={update.isPending}
onClick={() =>
update.mutate({ payload: draft, note: note || undefined })
}
>
Save
</Button>
</Group>
</Group>
</Card>
<DocumentEditor slug={slug} value={draft} onChange={setDraft} />
<VersionHistoryModal
slug={slug}
opened={historyOpen}
onClose={() => setHistoryOpen(false)}
hasUnsavedChanges={dirty}
onRestored={reset}
/>
</Stack>
);
}
function DocumentEditor({
slug,
value,
onChange,
}: {
slug: SupportDocSlug;
value: SupportDocPayload;
onChange: (next: SupportDocPayload) => void;
}) {
switch (slug) {
case "CONTACT":
return (
<ContactEditor
value={value as PortalSupportContact}
onChange={onChange}
/>
);
case "HELP":
return (
<HelpEditor value={value as PortalHelpContent} onChange={onChange} />
);
case "FAQ":
return <FaqEditor value={value as PortalFaqContent} onChange={onChange} />;
case "PRIVACY":
case "TERMS":
return (
<LegalDocEditor
value={value as PortalLegalContent}
onChange={onChange}
/>
);
}
}
/**
* Four fields, so no separate file. These values feed the help page's contact
* cards and resolve the `{{supportEmail}}`-style placeholders used throughout
* the FAQ and legal copy — editing them here updates every page at once.
*/
function ContactEditor({
value,
onChange,
}: {
value: PortalSupportContact;
onChange: (next: PortalSupportContact) => void;
}) {
return (
<Stack gap="md" maw={640}>
<TextInput
label="Support email"
value={value.email}
onChange={(e) => onChange({ ...value, email: e.currentTarget.value })}
/>
<TextInput
label="Support phone"
description="Displayed as typed; tel: links strip the spacing automatically."
value={value.phone}
onChange={(e) => onChange({ ...value, phone: e.currentTarget.value })}
/>
<TextInput
label="Head office"
value={value.office}
onChange={(e) => onChange({ ...value, office: e.currentTarget.value })}
/>
<TextInput
label="Support hours"
value={value.hours}
onChange={(e) => onChange({ ...value, hours: e.currentTarget.value })}
/>
</Stack>
);
}

View File

@@ -0,0 +1,198 @@
import type { SupportDocSlug } from "@edr/types";
import {
Alert,
Badge,
Button,
Card,
Group,
Loader,
Modal,
Stack,
Text,
} from "@mantine/core";
import { AlertTriangle } from "lucide-react";
import { useState } from "react";
import {
usePortalDocVersion,
usePortalDocVersions,
useRestorePortalVersion,
} from "@/hooks/portal-content/usePortalContentAdmin";
import { Markdown } from "./Markdown";
import { summarizeVersion } from "./version-preview";
interface VersionHistoryModalProps {
slug: SupportDocSlug;
opened: boolean;
onClose: () => void;
/** True when the tab holds unsaved edits a restore would discard. */
hasUnsavedChanges: boolean;
onRestored: () => void;
}
function formatSavedAt(value: string): string {
return new Date(value).toLocaleString("en-GB", {
day: "numeric",
month: "short",
year: "numeric",
hour: "2-digit",
minute: "2-digit",
});
}
/**
* Version history for one document. Restoring re-saves the old payload as a new
* version server-side, so the list only ever grows and a restore is itself
* undoable — there is nothing here that can destroy history.
*/
export function VersionHistoryModal({
slug,
opened,
onClose,
hasUnsavedChanges,
onRestored,
}: VersionHistoryModalProps) {
const { data: versions, isLoading } = usePortalDocVersions(slug, opened);
const [previewing, setPreviewing] = useState<number | null>(null);
const [confirming, setConfirming] = useState<number | null>(null);
const { data: preview } = usePortalDocVersion(slug, previewing);
const restore = useRestorePortalVersion(slug);
const close = () => {
setPreviewing(null);
setConfirming(null);
onClose();
};
const latest = versions?.[0]?.version;
return (
<Modal
opened={opened}
onClose={close}
size="xl"
title={`Version history — ${slug}`}
>
<Stack gap="md">
{hasUnsavedChanges && (
<Alert
color="orange"
icon={<AlertTriangle size={16} />}
title="Unsaved changes"
>
This tab has edits that have not been saved. Restoring a version
discards them.
</Alert>
)}
{isLoading && <Loader size="sm" />}
{versions?.map((version) => (
<Card key={version.id} withBorder padding="md" radius="md">
<Group justify="space-between" align="flex-start" wrap="nowrap">
<Stack gap={2}>
<Group gap="xs">
<Text fw={600}>v{version.version}</Text>
{version.version === latest && (
<Badge size="sm" variant="light">
Current
</Badge>
)}
<Text size="sm" c="dimmed">
{formatSavedAt(version.createdAt)}
</Text>
</Group>
{version.note && (
<Text size="sm" c="dimmed">
{version.note}
</Text>
)}
</Stack>
{confirming === version.version ? (
<Group gap="xs" wrap="nowrap">
<Text size="sm">Restore v{version.version}?</Text>
<Button
size="xs"
color="red"
loading={restore.isPending}
onClick={() =>
restore.mutate(version.version, {
onSuccess: () => {
onRestored();
close();
},
})
}
>
Confirm
</Button>
<Button
size="xs"
variant="subtle"
onClick={() => setConfirming(null)}
>
Cancel
</Button>
</Group>
) : (
<Group gap="xs" wrap="nowrap">
<Button
size="xs"
variant="light"
onClick={() =>
setPreviewing(
previewing === version.version ? null : version.version,
)
}
>
{previewing === version.version ? "Hide" : "Preview"}
</Button>
<Button
size="xs"
variant="subtle"
disabled={version.version === latest}
onClick={() => {
setConfirming(version.version);
setPreviewing(null);
}}
>
Restore
</Button>
</Group>
)}
</Group>
{previewing === version.version && (
<Card mt="sm" withBorder padding="sm" radius="sm" bg="gray.0">
{preview ? (
<Stack gap="sm">
{summarizeVersion(slug, preview.payload).map((entry, i) => (
<Stack key={`${entry.label}-${i}`} gap={2}>
<Text size="sm" fw={600}>
{entry.label}
</Text>
<Markdown>{entry.body}</Markdown>
</Stack>
))}
</Stack>
) : (
<Loader size="xs" />
)}
</Card>
)}
</Card>
))}
{versions?.length === 0 && (
<Text size="sm" c="dimmed">
No history yet.
</Text>
)}
</Stack>
</Modal>
);
}
export default VersionHistoryModal;

View File

@@ -0,0 +1,24 @@
/** Immutable list edits shared by the three payload editors. */
export function replaceAt<T>(items: T[], index: number, next: T): T[] {
return items.map((item, i) => (i === index ? next : item));
}
export function removeAt<T>(items: T[], index: number): T[] {
return items.filter((_, i) => i !== index);
}
/**
* Swaps an item with its neighbour. Out-of-range moves return the list
* unchanged, so the ▲/▼ buttons need no disabled-state bookkeeping of their own.
*/
export function moveAt<T>(items: T[], index: number, delta: number): T[] {
const target = index + delta;
if (target < 0 || target >= items.length) return items;
const next = [...items];
[next[index], next[target]] = [next[target], next[index]];
return next;
}
export const newId = () => crypto.randomUUID();

View File

@@ -0,0 +1,109 @@
/*
* Tailwind's preflight zeroes margins on `p`, strips `list-style` from `ul`/`ol`
* and flattens heading sizes. MDXEditor's own stylesheet assumes browser
* defaults, so inside this app its content area renders as one undifferentiated
* block — paragraphs run together and bullets lose their markers.
*
* This restores the handful of element styles the editor needs, scoped to its
* content area so nothing leaks back into the rest of the backoffice. It is a
* deliberate alternative to pulling in @tailwindcss/typography for one widget.
*/
.edr-md-content p {
margin: 0 0 0.75rem;
line-height: 1.6;
}
.edr-md-content p:last-child {
margin-bottom: 0;
}
.edr-md-content ul,
.edr-md-content ol {
margin: 0 0 0.75rem;
padding-left: 1.5rem;
}
.edr-md-content ul {
list-style: disc;
}
.edr-md-content ol {
list-style: decimal;
}
.edr-md-content li {
margin: 0.25rem 0;
line-height: 1.6;
}
/* Nested lists — the editor's indent button produces these. */
.edr-md-content li > ul,
.edr-md-content li > ol {
margin: 0.25rem 0 0;
}
.edr-md-content h1,
.edr-md-content h2,
.edr-md-content h3,
.edr-md-content h4 {
font-weight: 700;
line-height: 1.3;
margin: 1rem 0 0.5rem;
}
.edr-md-content h1 {
font-size: 1.5rem;
}
.edr-md-content h2 {
font-size: 1.25rem;
}
.edr-md-content h3 {
font-size: 1.1rem;
}
.edr-md-content h4 {
font-size: 1rem;
}
.edr-md-content strong {
font-weight: 600;
}
.edr-md-content em {
font-style: italic;
}
.edr-md-content a {
color: var(--mantine-color-blue-6);
text-decoration: underline;
}
.edr-md-content blockquote {
margin: 0 0 0.75rem;
padding-left: 0.75rem;
border-left: 3px solid var(--mantine-color-gray-3);
color: var(--mantine-color-dimmed);
}
.edr-md-content hr {
border: 0;
border-top: 1px solid var(--mantine-color-gray-3);
margin: 1rem 0;
}
.edr-md-content code {
font-family: var(--mantine-font-family-monospace);
font-size: 0.875em;
background: var(--mantine-color-gray-1);
padding: 0.05rem 0.25rem;
border-radius: 3px;
}
.edr-md-content img {
max-width: 100%;
height: auto;
border-radius: 8px;
}

View File

@@ -0,0 +1,79 @@
import type {
PortalFaqContent,
PortalHelpContent,
PortalLegalContent,
PortalSupportContact,
SupportDocPayload,
SupportDocSlug,
} from "@edr/types";
export interface PreviewEntry {
label: string;
/** Markdown, rendered read-only. */
body: string;
}
/**
* Flattens a stored payload into labelled markdown blocks for the history
* modal. An editor deciding whether to roll back needs to read the wording of
* that version — a raw JSON dump technically shows it, but not in a form
* anyone can compare legal prose in.
*/
export function summarizeVersion(
slug: SupportDocSlug,
payload: SupportDocPayload,
): PreviewEntry[] {
switch (slug) {
case "CONTACT": {
const contact = payload as PortalSupportContact;
return [
{ label: "Email", body: contact.email },
{ label: "Phone", body: contact.phone },
{ label: "Head office", body: contact.office },
{ label: "Support hours", body: contact.hours },
];
}
case "HELP": {
const help = payload as PortalHelpContent;
return [
{ label: "Title", body: help.title },
{ label: "Subtitle", body: help.subtitle },
...help.sections.map((section) => ({
label: section.heading,
body: section.media.length
? `${section.body}\n\n_${section.media.length} attachment${section.media.length === 1 ? "" : "s"}: ${section.media.map((m) => m.src).join(", ")}_`
: section.body,
})),
];
}
case "FAQ": {
const faq = payload as PortalFaqContent;
return [
{ label: "Title", body: faq.title },
...faq.groups.flatMap((group) =>
group.items.map((item) => ({
label: `${group.title}${item.question}`,
body: item.answer,
})),
),
...(faq.footer
? [{ label: faq.footer.heading, body: faq.footer.body }]
: []),
];
}
case "PRIVACY":
case "TERMS": {
const legal = payload as PortalLegalContent;
return [
{ label: "Last updated", body: legal.lastUpdated },
...legal.sections.map((section) => ({
label: section.heading,
body: section.body,
})),
];
}
}
}

View File

@@ -149,6 +149,8 @@ import {
import { containerTypesService } from "./container-types.service";
import { containerService, type Container } from "./containerService";
import { customersService } from "./customers.service";
import { eimsService } from "./eims.service";
import type { EimsInvoiceStatusView, EimsVerifyResult } from "@/types/eims";
import { invoicesService } from "./invoices.service";
import { dropdownSettingsService } from "./dropdownSettings.service";
import { fileUploadSettingsService } from "./fileUploadSettings.service";
@@ -2938,6 +2940,36 @@ export const api = {
// Settling the invoice also advances the booking, so refresh both trees.
() => [QUERY_KEYS.INVOICES.ROOT, QUERY_KEYS.BOOKINGS.ROOT],
),
eimsStatus: endpoint<{ id: string }, EimsInvoiceStatusView>(
"invoices",
"eimsStatus",
({ id }) => eimsService.status(id),
({ id }) => QUERY_KEYS.INVOICES.eimsStatus(id),
),
// Both mutations refresh the filing panel; register also moves the invoice's own row.
eimsRegister: endpoint<{ id: string }, EimsInvoiceStatusView>(
"invoices",
"eimsRegister",
({ id }) => eimsService.register(id),
undefined,
({ id }) => [QUERY_KEYS.INVOICES.eimsStatus(id), QUERY_KEYS.INVOICES.byId(id)],
),
eimsVerify: endpoint<{ id: string }, EimsVerifyResult>(
"invoices",
"eimsVerify",
({ id }) => eimsService.verify(id),
),
eimsResolve: endpoint<{ id: string; irn?: string; discard?: boolean }, EimsInvoiceStatusView>(
"invoices",
"eimsResolve",
({ id, irn, discard }) => eimsService.resolve(id, { irn, discard }),
undefined,
({ id }) => [QUERY_KEYS.INVOICES.eimsStatus(id), QUERY_KEYS.INVOICES.byId(id)],
),
},
overview: {

View File

@@ -0,0 +1,39 @@
import { api as apiClient } from "@/auth/http";
import { URL_CONSTANTS } from "@/constants/URLS";
import type { EimsInvoiceStatusView, EimsVerifyResult } from "@/types/eims";
/**
* MoR EIMS filing actions on an invoice.
*
* Registration is irreversible at the tax authority, so these are admin actions rather than part
* of the ordinary invoice screen: the normal production path is the API's cron sweep.
*/
export const eimsService = {
status(invoiceId: string): Promise<EimsInvoiceStatusView> {
return apiClient
.get<EimsInvoiceStatusView>(URL_CONSTANTS.EIMS.STATUS(invoiceId))
.then((r) => r.data);
},
register(invoiceId: string): Promise<EimsInvoiceStatusView> {
return apiClient
.post<EimsInvoiceStatusView>(URL_CONSTANTS.EIMS.REGISTER(invoiceId))
.then((r) => r.data);
},
verify(invoiceId: string): Promise<EimsVerifyResult> {
return apiClient
.post<EimsVerifyResult>(URL_CONSTANTS.EIMS.VERIFY(invoiceId))
.then((r) => r.data);
},
/** Record an IRN confirmed with MoR, or discard the attempt. Clears the system-wide block. */
resolve(
invoiceId: string,
input: { irn?: string; discard?: boolean },
): Promise<EimsInvoiceStatusView> {
return apiClient
.post<EimsInvoiceStatusView>(URL_CONSTANTS.EIMS.RESOLVE(invoiceId), input)
.then((r) => r.data);
},
};

View File

@@ -0,0 +1,98 @@
import type {
PortalMediaKind,
SupportDocPayload,
SupportDocSlug,
SupportDocumentDetail,
SupportDocVersionDetail,
SupportDocVersionSummary,
} from "@edr/types";
import { api as client } from "../auth/http";
const ROOT = "/support-content";
const BASE = `${ROOT}/documents`;
/**
* Customer-facing help/FAQ/legal copy for the freight portal. The client's
* response interceptor already unwraps the `{ success, data }` envelope, so
* every method is a one-liner.
*/
export const portalContentService = {
async getBySlug(slug: SupportDocSlug): Promise<SupportDocumentDetail> {
const { data } = await client.get<SupportDocumentDetail>(`${BASE}/${slug}`);
return data;
},
/**
* Replaces the document's whole payload. Whole-payload rather than per-field
* on purpose: one Save becomes exactly one version, which is what keeps the
* history list readable.
*/
async update(
slug: SupportDocSlug,
payload: SupportDocPayload,
note?: string,
): Promise<SupportDocumentDetail> {
const { data } = await client.patch<SupportDocumentDetail>(
`${BASE}/${slug}`,
{ payload, note },
);
return data;
},
async listVersions(slug: SupportDocSlug): Promise<SupportDocVersionSummary[]> {
const { data } = await client.get<SupportDocVersionSummary[]>(
`${BASE}/${slug}/versions`,
);
return data;
},
async getVersion(
slug: SupportDocSlug,
version: number,
): Promise<SupportDocVersionDetail> {
const { data } = await client.get<SupportDocVersionDetail>(
`${BASE}/${slug}/versions/${version}`,
);
return data;
},
/**
* Uploads an image or video and returns its object *key*. The key is what
* gets saved in the document; `url` is only for showing the editor a preview
* right now, and expires.
*/
async uploadMedia(
file: File,
): Promise<{ key: string; kind: PortalMediaKind; url: string }> {
const form = new FormData();
form.append("file", file);
const { data } = await client.post<{
key: string;
kind: PortalMediaKind;
url: string;
}>(`${ROOT}/media`, form);
return data;
},
/** Resolves one stored key to a temporary URL, for editor previews. */
async mediaUrl(key: string): Promise<string> {
const { data } = await client.get<{ url: string }>(`${ROOT}/media-url`, {
params: { key },
});
return data.url;
},
/** Re-saves an old payload as a new version — never destructive. */
async restore(
slug: SupportDocSlug,
version: number,
): Promise<SupportDocumentDetail> {
const { data } = await client.post<SupportDocumentDetail>(
`${BASE}/${slug}/versions/${version}/restore`,
{},
);
return data;
},
};

View File

@@ -0,0 +1,44 @@
/**
* MoR EIMS filing state for one invoice.
*
* Mirrors `EimsInvoiceStatusView` in the freight API (`modules/eims/eims-registration.types.ts`).
* Kept local rather than in `@edr/types` because only the backoffice reads it.
*/
export type EimsInvoiceStatus =
| "NOT_SUBMITTED"
| "SUBMITTING"
| "REGISTERED"
| "FAILED"
| "UNKNOWN";
/** Sanitized gateway failure: MoR's own error fields, never our signed envelope. */
export interface EimsInvoiceError {
kind: string;
message: string;
httpStatus?: number;
details?: Record<string, unknown>;
at: string;
}
export interface EimsInvoiceStatusView {
invoiceId: string;
invoiceNumber: string;
eimsStatus: EimsInvoiceStatus;
eimsIrn: string | null;
eimsInvoiceCounter: number | null;
eimsSubmittedAt: string | null;
/** MoR returns a Java ZonedDateTime string, stored verbatim — display as-is. */
eimsAckDate: string | null;
eimsLastError: EimsInvoiceError | null;
}
/** `POST /v1/verify` response, echoed back from the gateway. */
export interface EimsVerifyResult {
statusCode?: number;
message?: string;
body?: {
Irn?: string;
DocumentDetails?: { Type?: string; DocumentNumber?: string; Date?: string };
[section: string]: unknown;
};
}

View File

@@ -85,14 +85,15 @@ export function getNextInventoryAction(item: WarehouseInventoryItem): InventoryA
if (isImport) return inspected ? 'ready-for-pickup' : null;
return 'store';
case 'STORED':
// Reserve is retired: a stored export item goes straight to loading prep
// once inspection passes. An import item parked back into storage returns
// to pickup — otherwise Store would strand it with no action.
// Reserve is retired: a stored export item goes straight to loading prep.
// An import item parked back into storage returns to pickup — otherwise
// Store would strand it with no action.
if (isImport) return inspected ? 'ready-for-pickup' : null;
return inspected ? 'ready-for-loading' : null;
return 'ready-for-loading';
case 'RESERVED':
// Export loading is gated on a passed inspection.
return inspected ? 'ready-for-loading' : null;
// Export loading is not gated on inspection — inspection is tracked, but a
// train is never held waiting for it.
return 'ready-for-loading';
case 'READY_FOR_PICKUP':
// Issue the DO / release order first, then hand over the goods.
return item.releaseDate ? 'deliver' : 'release';

View File

@@ -33,6 +33,7 @@
"react-dom": "19.2.6",
"react-hook-form": "^7.76.0",
"react-hot-toast": "^2.6.0",
"react-markdown": "^9.1.0",
"react-phone-number-input": "^3.4.17",
"react-router-dom": "^6.27.0",
"recharts": "^3.8.1",

View File

@@ -218,6 +218,11 @@ export const URL_CONSTANTS = {
PAY_ONLINE: (id: string) => `/api/warehouse-fee-invoices/${id}/pay-online`,
},
// Public — no session required; the sign-up screen links to these pages.
PORTAL_CONTENT: {
PUBLIC: "/api/support-content",
},
LAST_MILE_REQUESTS: {
BY_ID: (id: string) => `/last-mile-requests/${id}`,
SUBMIT: (id: string) => `/last-mile-requests/${id}/submit`,

View File

@@ -0,0 +1,39 @@
import type { PortalContentBundle } from "@edr/types";
import { useQuery } from "@tanstack/react-query";
import { URL_CONSTANTS } from "@/constants/URLS";
import {
FALLBACK_PORTAL_CONTENT,
withSupportVars,
} from "@/pages/support/portal-content";
import type { ApiResponse } from "@/types/apiResponse";
import { client } from "@/utils/api";
import { unwrap } from "@/utils/endpoint";
/**
* The whole public help/FAQ/legal bundle in one request, shared by the four
* public pages (react-query dedupes it across the routes).
*
* The endpoint is unauthenticated and the shared axios client attaches a token
* only when the cookie exists, so this works for anonymous visitors as-is.
*
* `placeholderData` means `data` is never undefined: the pages render the
* shipped copy immediately and swap in the live copy when the fetch resolves.
* That is deliberate — it is what lets the four public pages skip loading and
* error states entirely. If the fallback is ever removed, those states are
* owed back.
*/
export function usePortalContent() {
return useQuery({
queryKey: ["portal-content"],
queryFn: async (): Promise<PortalContentBundle> => {
const response = await client.get<ApiResponse<PortalContentBundle>>(
URL_CONSTANTS.PORTAL_CONTENT.PUBLIC,
);
return unwrap(response.data);
},
placeholderData: FALLBACK_PORTAL_CONTENT,
select: withSupportVars,
staleTime: 5 * 60_000,
});
}

View File

@@ -25,10 +25,14 @@ interface ProviderOption {
currencies: string[];
accent: string;
}
// Only Telebirr, Waafi, CAC Bank and CBE bill payment are enabled for now.
// ponytail: ETB pays via CBE bill only for now — restore the Telebirr entry
// ({ method: "TELEBIRR", currencies: ["ETB"] }) when mobile money returns.
const PROVIDERS: ProviderOption[] = [
// {
// {
// method: "TELEBIRR",
// label: "telebirr",
// description: "Ethiopian mobile money · ETB",
@@ -69,8 +73,8 @@ const OTP_LENGTH = 4;
const isBillMethod = (method: PaymentMethod) => method === "CBE_BILL";
/**
* Pick the provider that settles in the booking's currency. USD → Waafi,
* ETB → Telebirr. Falls back to the first provider when unknown.
* Pick the provider that settles in the booking's currency. USD → Waafi/CAC,
* ETB → CBE bill. Falls back to the full list when unknown.
*/
function providersForCurrency(currency?: string | null): ProviderOption[] {
const cur = currency?.trim().toUpperCase();
@@ -190,7 +194,7 @@ export function PaymentMethodModal({
onClose: () => void;
/** Human-readable total, e.g. "ETB 12,500". */
amountLabel?: string;
/** Booking payment currency — drives which provider is shown (USD → Waafi, ETB → Telebirr). */
/** Booking payment currency — drives which provider is shown (USD → Waafi/CAC, ETB → CBE bill). */
currency?: string | null;
onConfirm: (method: PaymentMethod, payerAccount?: string) => void;
processing?: boolean;

View File

@@ -157,8 +157,8 @@ function mapBookingToFormValues(
isRefrigerated: booking.isRefrigerated ?? false,
bulkHazardousQty: String(Number(booking.bulkHazardousQuantity ?? 0)),
bulkReeferQty: String(Number(booking.bulkReeferQuantity ?? 0)),
paymentCurrency:
booking.paymentCurrency === "ETB" ? "ETB" : "USD",
// ponytail: ETB-only for now — old USD drafts are re-billed in ETB on edit.
paymentCurrency: "ETB",
scheduledDate: booking.scheduledDate
? new Date(booking.scheduledDate).toISOString().slice(0, 10)
: "",

View File

@@ -45,11 +45,16 @@ interface PlacePrediction {
}
// Maps JavaScript API keys are public client-side keys (lock them down by
// HTTP-referrer in the Google Cloud console). The env var lets deployments
// override the default key without a code change.
const GOOGLE_MAPS_API_KEY =
import.meta.env.VITE_GOOGLE_MAPS_API_KEY ||
"AIzaSyBg4tN31-fgvH_2Ix_TPo6VSfOA2uA5CCI";
// HTTP-referrer in the Google Cloud console), so this one env var is the whole
// configuration. Requires BOTH "Maps JavaScript API" (tiles) and "Places API"
// (the address search) enabled on the key, or the map draws and the search box
// silently returns nothing.
//
// There is deliberately no fallback key. A hardcoded default used to live here
// and expired, which degraded a missing env var into a blank map with a search
// box that spun forever — indistinguishable from a broken picker. Absent config
// now says so on screen instead.
const GOOGLE_MAPS_API_KEY = import.meta.env.VITE_GOOGLE_MAPS_API_KEY?.trim();
// Centre of the EDR corridor (Addis Ababa) — a sensible default view.
const DEFAULT_CENTER = { lat: 9.03, lng: 38.74 };
@@ -191,10 +196,7 @@ async function resolvePrediction(
},
(place, status) => {
const loc = place?.geometry?.location;
if (
status !== google.maps.places.PlacesServiceStatus.OK ||
!loc
) {
if (status !== google.maps.places.PlacesServiceStatus.OK || !loc) {
resolve(null);
return;
}
@@ -309,6 +311,7 @@ export function LocationPicker(props: LocationPickerProps) {
lat: toFiniteNumber(props.value.lat),
lng: toFiniteNumber(props.value.lng),
};
if (!GOOGLE_MAPS_API_KEY) return <MapUnavailable label={props.label} />;
return (
<APIProvider apiKey={GOOGLE_MAPS_API_KEY}>
{props.variant === "modal" ? (
@@ -320,6 +323,42 @@ export function LocationPicker(props: LocationPickerProps) {
);
}
/**
* Stands in for the picker when the Maps key is absent. Says which variable is
* missing rather than rendering an empty map that reads as a broken feature —
* the failure this replaced took a live API request to diagnose.
*/
function MapUnavailable({ label }: { label?: string }) {
return (
<Box>
{label && (
<Text fz={13} fw={600} c="#10202F" mb={6}>
{label}
</Text>
)}
<Box
style={{
display: "flex",
alignItems: "center",
gap: 10,
borderRadius: 12,
padding: "12px 14px",
border: "1px solid #F0D2A8",
background: "#FFF9F0",
}}
>
<MapPin size={16} color="#B45309" style={{ flexShrink: 0 }} />
<Text fz={12.5} c="#8A5A16">
Map unavailable <code>VITE_GOOGLE_MAPS_API_KEY</code> is not set.
Add a Google Maps key with the Maps JavaScript API and Places API
enabled to this app&apos;s
<code> .env</code>, then restart the dev server.
</Text>
</Box>
</Box>
);
}
/** Compact trigger + modal wrapper around the inline picker. */
function LocationPickerModal({
value,
@@ -368,7 +407,12 @@ function LocationPickerModal({
>
<MapPin size={16} />
</Box>
<Text fz={13.5} c={hasPin ? "#10202F" : "#94A3B8"} lineClamp={1} style={{ flex: 1 }}>
<Text
fz={13.5}
c={hasPin ? "#10202F" : "#94A3B8"}
lineClamp={1}
style={{ flex: 1 }}
>
{hasPin ? value.address || "Pinned location" : placeholder}
</Text>
<Text fz={12.5} fw={600} c="#0A6F4D" style={{ flexShrink: 0 }}>

View File

@@ -81,11 +81,7 @@ export const PAYMENT_CURRENCY_OPTIONS: Array<{
label: string;
description: string;
}> = [
{
value: "USD",
label: "USD",
description: "US Dollar — international pricing and invoicing.",
},
// ponytail: ETB-only for now — re-add the USD option when multi-currency billing returns.
{
value: "ETB",
label: "ETB",
@@ -373,7 +369,7 @@ export const initialBookingFormValues: DeepPartial<BookingFormValues> = {
previousContractRef: "",
serviceTypeId: "",
paymentCurrency: "USD",
paymentCurrency: "ETB",
firstMile: {
enabled: false,
pickUpAddress: "",

View File

@@ -40,6 +40,11 @@ export function Step2ServiceType({
serviceType ?? {};
const firstMileEnabled = form.watch("firstMile.enabled");
const lastMileEnabled = form.watch("lastMile.enabled");
// The paid-mile service prices the road legs into the booking itself; every
// other service defers last-mile billing to after the Djibouti departure
// (confirm containers → sign supplementary LM contract → pay advance).
const deferredLastMileBilling =
serviceType?.code !== "RAIL_CONTAINER_PAID_MILE";
const prevServiceType = useRef(serviceType);
// Only clear a mile when the current service doesn't include it — this ran
@@ -205,7 +210,11 @@ export function Step2ServiceType({
<ServiceToggle
icon={<Truck size={18} />}
title="Last Mile — Delivery"
description="Truck delivery from the destination rail yard to the final address (Port to Door)."
description={
deferredLastMileBilling
? "Truck delivery from the destination rail yard to the final address (Port to Door). Nothing is paid now — last-mile billing starts after your train departs Djibouti."
: "Truck delivery from the destination rail yard to the final address (Port to Door)."
}
checked={field.value ?? false}
onChange={(value) => {
field.onChange(value);
@@ -224,6 +233,15 @@ export function Step2ServiceType({
>
{lastMileEnabled && (
<Box mt="md">
{deferredLastMileBilling && (
<Text size="xs" c="dimmed" mb={10}>
How it works: when your train departs Djibouti, you
will be asked to confirm which containers EDR should
deliver. Once truck availability is approved, you will
sign a short supplementary last-mile contract and pay
the delivery advance nothing is charged at booking.
</Text>
)}
<Controller
name="lastMile"
control={form.control}

View File

@@ -299,7 +299,7 @@ export function Step8Review({
<DetailRow label="Service" value={serviceType?.name ?? ""} />
<DetailRow
label="Payment currency"
value={values.paymentCurrency ?? "USD"}
value={values.paymentCurrency ?? "ETB"}
/>
<Button
type="button"

View File

@@ -281,7 +281,7 @@ function mapBookingToShipmentValues(
}>;
};
const values: Partial<ShipmentFormInputValues> = {
paymentCurrency: booking.paymentCurrency === "ETB" ? "ETB" : "USD",
paymentCurrency: "ETB",
withReturn: booking.equipmentReturn === "WITH_RETURN",
cargoDescription: b.cargoFreeText ?? "",
...(b.contractRouteId ? { contractRouteId: b.contractRouteId } : {}),
@@ -390,11 +390,8 @@ function NewShipmentBookingForm({
// Seed the equipment-return toggle from the contract; the customer can
// still flip it per shipment.
withReturn: contract.equipmentReturn === "WITH_RETURN",
// The contract quotes USD; the customer bills this shipment in the
// currency they pick here. Intercity is always ETB, so it is preset;
// everything else starts empty so the customer picks deliberately
// instead of silently inheriting USD.
paymentCurrency: contract.tradeDirection === "DOMESTIC" ? "ETB" : "",
// ponytail: ETB-only for now — preset since there is no other choice.
paymentCurrency: "ETB",
},
resolver: zodResolver(
createShipmentFormSchema({
@@ -1313,8 +1310,7 @@ function ScheduleStep({
<Box mb="lg">
<StepLabel>Billing currency *</StepLabel>
<Text fz={12.5} c="dimmed" mt={4} mb={10}>
Your contract is quoted in USD. Pick the currency this shipment is
invoiced in the total is converted for you.
Shipments are invoiced in ETB.
</Text>
<CurrencySelector
value={field.value || ""}

View File

@@ -254,6 +254,11 @@ export function Step2ServiceType({
(serviceType?.includesLastMile ?? false) && tradeDirection !== "EXPORT";
const firstMileEnabled = form.watch("firstMile.enabled");
const lastMileEnabled = form.watch("lastMile.enabled");
// The paid-mile service prices the road legs into the booking itself; every
// other service defers last-mile billing to after the Djibouti departure
// (confirm containers → sign supplementary LM contract → pay advance).
const deferredLastMileBilling =
serviceType?.code !== "RAIL_CONTAINER_PAID_MILE";
const prevServiceType = useRef(serviceType);
useEffect(() => {
@@ -471,7 +476,11 @@ export function Step2ServiceType({
<ServiceToggle
icon={<Truck size={18} />}
title="Last Mile — Delivery"
description="Truck delivery from the destination rail yard to the final address (Port to Door)."
description={
deferredLastMileBilling
? "Truck delivery from the destination rail yard to the final address (Port to Door). Nothing is paid now — last-mile billing starts after your train departs Djibouti."
: "Truck delivery from the destination rail yard to the final address (Port to Door)."
}
checked={field.value ?? false}
onChange={(value) => {
field.onChange(value);
@@ -492,6 +501,15 @@ export function Step2ServiceType({
>
{lastMileEnabled && (
<Stack mt="md" gap={12}>
{deferredLastMileBilling && (
<Text size="xs" c="dimmed">
How it works: when your train departs Djibouti, you
will be asked to confirm which containers EDR should
deliver. Once truck availability is approved, you will
sign a short supplementary last-mile contract and pay
the delivery advance nothing is charged at booking.
</Text>
)}
<Controller
name="lastMile"
control={form.control}

View File

@@ -1,8 +1,9 @@
import type { PortalDocSection } from "@edr/types";
import { ArrowLeft, Train } from "lucide-react";
import type { ReactNode } from "react";
import { Link } from "react-router-dom";
import type { Section } from "./content";
import { Markdown } from "./Markdown";
/** Public pages reachable from every doc page's header and footer. */
const DOC_LINKS = [
@@ -87,32 +88,21 @@ export function DocShell({
);
}
/** Renders a legal document's numbered sections. */
export function DocSections({ sections }: { sections: Section[] }) {
/**
* Renders a legal document's numbered sections. Bodies are markdown, so the
* paragraph and bullet arrays this used to walk are one string now — keyed by
* `id` rather than by heading, which admin-authored text can duplicate.
*/
export function DocSections({ sections }: { sections: PortalDocSection[] }) {
return (
<div className="space-y-10">
{sections.map((section) => (
<section key={section.heading}>
<section key={section.id}>
<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>
)}
<Markdown>{section.body}</Markdown>
</section>
))}
</div>

View File

@@ -1,19 +1,21 @@
import { ChevronDown } from "lucide-react";
import { Link } from "react-router-dom";
import { usePortalContent } from "@/hooks/usePortalContent";
import { DocShell } from "./DocShell";
import { FAQ_GROUPS, SUPPORT_CONTACT } from "./content";
import { Markdown } from "./Markdown";
export default function FaqPage() {
// Never undefined — see TermsPage.
const { data } = usePortalContent();
const faq = data!.faq;
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."
>
<DocShell current="/faq" title={faq.title} subtitle={faq.subtitle}>
<div className="space-y-10">
{FAQ_GROUPS.map((group) => (
<section key={group.title}>
{faq.groups.map((group) => (
<section key={group.id}>
<h2 className="text-xl font-bold tracking-tight">{group.title}</h2>
<div className="mt-4 space-y-3">
@@ -21,7 +23,7 @@ export default function FaqPage() {
// Native disclosure: keyboard- and screen-reader-accessible
// without any state of our own.
<details
key={item.question}
key={item.id}
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">
@@ -29,9 +31,7 @@ export default function FaqPage() {
<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>
<Markdown>{item.answer}</Markdown>
</details>
))}
</div>
@@ -39,21 +39,20 @@ export default function FaqPage() {
))}
</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>
{faq.footer && (
<div className="mt-12 rounded-[32px] border border-border bg-card p-8">
<h2 className="text-xl font-bold tracking-tight">
{faq.footer.heading}
</h2>
<Markdown>{faq.footer.body}</Markdown>
<Link
to={faq.footer.ctaTo}
className="mt-6 inline-flex rounded-2xl bg-primary px-6 py-3 font-semibold text-primary-foreground transition hover:opacity-90"
>
{faq.footer.ctaLabel}
</Link>
</div>
)}
</DocShell>
);
}

View File

@@ -1,208 +1,74 @@
import {
Clock3,
FileText,
HelpCircle,
Mail,
MapPin,
MessageSquare,
Package,
Phone,
Receipt,
ShieldCheck,
} from "lucide-react";
import { Link } from "react-router-dom";
import type { PortalMedia } from "@edr/types";
import { usePortalContent } from "@/hooks/usePortalContent";
import { DocShell } from "./DocShell";
import { SUPPORT_CONTACT } from "./content";
import { Markdown } from "./Markdown";
import { safeMediaSrc } from "./portal-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.",
},
];
/**
* An attached image or video. The API has already swapped stored MinIO keys for
* freshly signed URLs, so `src` is ready to render — `safeMediaSrc` is a last
* check that an admin-entered value is a path or an https URL.
*/
function Media({ item }: { item: PortalMedia }) {
const src = safeMediaSrc(item.src);
if (!src) return null;
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 — watch the walkthrough, browse the common topics, check the FAQ, or reach our team directly."
>
<section className="mb-12">
<h2 className="text-xl font-bold tracking-tight">
Portal walkthrough
</h2>
<p className="mt-2 leading-7 text-muted-foreground">
A guided tour of the portal registering your company, raising a
booking against a contract, and settling an invoice.
</p>
{/* preload="metadata" so the 28 MB file is not pulled on every visit;
the browser fetches it only once playback starts. */}
<figure className="mt-6">
{item.kind === "video" ? (
// preload="metadata" so a large file is not pulled on every visit; the
// browser fetches it only once playback starts.
<video
controls
preload="metadata"
className="mt-6 w-full rounded-[32px] border border-border bg-black"
className="w-full rounded-[32px] border border-border bg-black"
>
<source src="/assets/edr-portal-guide.webm" type="video/webm" />
Your browser cannot play this video. Download it at{" "}
<a href="/assets/edr-portal-guide.webm">
/assets/edr-portal-guide.webm
</a>
.
<source src={src} />
Your browser cannot play this video.{" "}
<a href={src}>Download it instead</a>.
</video>
</section>
) : (
<img
src={src}
alt={item.caption ?? ""}
loading="lazy"
className="w-full rounded-[32px] border border-border"
/>
)}
{/* 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>
{item.caption && (
<figcaption className="mt-2 text-sm text-muted-foreground">
{item.caption}
</figcaption>
)}
</figure>
);
}
<div>
export default function HelpPage() {
// Never undefined — see TermsPage.
const { data } = usePortalContent();
const help = data!.help;
return (
<DocShell current="/help" title={help.title} subtitle={help.subtitle}>
<div className="space-y-12">
{help.sections.map((section) => (
<section key={section.id}>
<h2 className="text-xl font-bold tracking-tight">
Chat with our team
{section.heading}
</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>
<Markdown>{section.body}</Markdown>
{section.media.map((item) => (
<Media key={item.id} item={item} />
))}
</section>
))}
</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,72 @@
import ReactMarkdown from "react-markdown";
/**
* Renders admin-authored markdown from the support-content API.
*
* Deliberately plain `react-markdown`: it builds React elements directly, so
* unlike a markdown→HTML-string library it needs no `dangerouslySetInnerHTML`
* and no sanitizer, and the portal keeps its zero HTML-injection surface.
*
* Two things must stay absent for that to hold:
* - `rehype-raw`, which would start rendering raw HTML embedded in the copy;
* - a custom `urlTransform`, which would override the built-in stripping of
* `javascript:` and `data:` hrefs.
*
* `remark-gfm` is also left out: tables and strikethrough are not used in the
* legal or FAQ copy, and CommonMark already covers lists, emphasis and links.
*
* The component map reproduces the Tailwind classes the pages used when this
* copy was hardcoded, so switching to markdown changed nothing visually.
*/
export function Markdown({ children }: { children: string }) {
return (
<ReactMarkdown
components={{
p: ({ children: content }) => (
<p className="mt-4 leading-7 text-muted-foreground">{content}</p>
),
ul: ({ children: content }) => (
<ul className="mt-4 list-disc space-y-2 pl-5 leading-7 text-muted-foreground">
{content}
</ul>
),
ol: ({ children: content }) => (
<ol className="mt-4 list-decimal space-y-2 pl-5 leading-7 text-muted-foreground">
{content}
</ol>
),
li: ({ children: content }) => <li>{content}</li>,
a: ({ href, children: content }) => (
<a
href={href}
className="font-semibold text-foreground transition-colors hover:text-primary"
>
{content}
</a>
),
strong: ({ children: content }) => (
<strong className="font-semibold text-foreground">{content}</strong>
),
em: ({ children: content }) => <em className="italic">{content}</em>,
h3: ({ children: content }) => (
<h3 className="mt-6 font-bold tracking-tight">{content}</h3>
),
// Images embedded by the editor. The API has already resolved these to
// signed URLs; react-markdown's default urlTransform still guards the
// scheme.
img: ({ src, alt }) => (
<img
src={typeof src === "string" ? src : undefined}
alt={alt ?? ""}
loading="lazy"
className="mt-4 w-full rounded-2xl border border-border"
/>
),
}}
>
{children}
</ReactMarkdown>
);
}
export default Markdown;

View File

@@ -1,15 +1,20 @@
import { usePortalContent } from "@/hooks/usePortalContent";
import { DocSections, DocShell } from "./DocShell";
import { LEGAL_LAST_UPDATED, PRIVACY_SECTIONS } from "./content";
export default function PrivacyPolicyPage() {
// Never undefined — see TermsPage.
const { data } = usePortalContent();
const privacy = data!.privacy;
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}`}
title={privacy.title}
subtitle={privacy.subtitle}
meta={`Last updated ${privacy.lastUpdated}`}
>
<DocSections sections={PRIVACY_SECTIONS} />
<DocSections sections={privacy.sections} />
</DocShell>
);
}

View File

@@ -1,15 +1,21 @@
import { usePortalContent } from "@/hooks/usePortalContent";
import { DocSections, DocShell } from "./DocShell";
import { LEGAL_LAST_UPDATED, TERMS_SECTIONS } from "./content";
export default function TermsPage() {
// Never undefined — the hook seeds it with the shipped copy, so this public
// page renders instantly and survives the API being unreachable.
const { data } = usePortalContent();
const terms = data!.terms;
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}`}
title={terms.title}
subtitle={terms.subtitle}
meta={`Last updated ${terms.lastUpdated}`}
>
<DocSections sections={TERMS_SECTIONS} />
<DocSections sections={terms.sections} />
</DocShell>
);
}

View File

@@ -1,358 +0,0 @@
/**
* 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

@@ -0,0 +1,84 @@
import { describe, expect, it } from "vitest";
import {
applyPortalVars,
FALLBACK_PORTAL_CONTENT,
safeMediaSrc,
withSupportVars,
} from "./portal-content";
const contact = {
email: "support@edrfreight.com",
phone: "+251 11 000 0000",
office: "Addis Ababa, Ethiopia",
hours: "Monday Saturday, 8:30 AM 5:30 PM (EAT)",
};
describe("applyPortalVars", () => {
it("substitutes every known token", () => {
expect(
applyPortalVars(
"Mail {{supportEmail}}, call {{supportPhone}}, visit {{supportOffice}}, open {{supportHours}}.",
contact,
),
).toBe(
"Mail support@edrfreight.com, call +251 11 000 0000, visit Addis Ababa, Ethiopia, open Monday Saturday, 8:30 AM 5:30 PM (EAT).",
);
});
it("strips spacing for the tel: variant", () => {
expect(applyPortalVars("tel:{{supportPhoneTel}}", contact)).toBe(
"tel:+251110000000",
);
});
it("leaves an unknown token verbatim so the typo is visible", () => {
expect(applyPortalVars("Mail {{supportEmial}}.", contact)).toBe(
"Mail {{supportEmial}}.",
);
});
it("does not let $& in a contact value corrupt the output", () => {
// Guards the replace-callback choice: with a replacement *string*, `$&`
// would expand to the matched token and the address would come out wrong.
expect(
applyPortalVars("Write to {{supportOffice}}.", {
...contact,
office: "Bole $& Road",
}),
).toBe("Write to Bole $& Road.");
});
});
describe("withSupportVars", () => {
it("resolves placeholders buried in the shipped legal copy", () => {
const resolved = withSupportVars(FALLBACK_PORTAL_CONTENT);
const contactSection = resolved.privacy.sections.at(-1)!;
expect(contactSection.body).toContain(contact.email);
expect(contactSection.body).not.toContain("{{");
});
it("leaves the contact block itself alone — it is the substitution source", () => {
expect(withSupportVars(FALLBACK_PORTAL_CONTENT).contact).toEqual(
FALLBACK_PORTAL_CONTENT.contact,
);
});
});
describe("safeMediaSrc", () => {
it("keeps same-origin paths and https sources", () => {
expect(safeMediaSrc("/assets/guide.webm")).toBe("/assets/guide.webm");
expect(safeMediaSrc("https://minio.internal/support-content/a.png?sig=x")).toBe(
"https://minio.internal/support-content/a.png?sig=x",
);
});
it("drops javascript: and protocol-relative sources", () => {
expect(safeMediaSrc("javascript:alert(1)")).toBeNull();
expect(safeMediaSrc("//evil.example.com/g.webm")).toBeNull();
// A bare object key means the API failed to sign it — render nothing
// rather than a broken relative URL.
expect(safeMediaSrc("support-content/a.png")).toBeNull();
});
});

View File

@@ -0,0 +1,103 @@
import {
SUPPORT_CONTENT_DEFAULTS,
type PortalContentBundle,
type PortalContentVar,
type PortalSupportContact,
} from "@edr/types";
/**
* Copy for the public help/FAQ/legal pages now lives in the database and is
* edited from the backoffice. This module holds what is left in the app: the
* shipped copy as a fallback, and the two pure helpers the pages need.
*
* The fallback matters because these four routes are public and linked from
* the sign-up screen — they are often the first thing an anonymous visitor
* sees. Rendering the shipped text while the request is in flight (or if the
* API is down) beats showing them a spinner or an error card, and it is why
* none of the four pages carry loading or error branches.
*/
export const FALLBACK_PORTAL_CONTENT: PortalContentBundle = {
contact: SUPPORT_CONTENT_DEFAULTS.CONTACT,
help: SUPPORT_CONTENT_DEFAULTS.HELP,
faq: SUPPORT_CONTENT_DEFAULTS.FAQ,
privacy: SUPPORT_CONTENT_DEFAULTS.PRIVACY,
terms: SUPPORT_CONTENT_DEFAULTS.TERMS,
};
const VAR_PATTERN =
/\{\{(supportEmail|supportPhone|supportPhoneTel|supportOffice|supportHours)\}\}/g;
function resolveVar(name: PortalContentVar, contact: PortalSupportContact) {
switch (name) {
case "supportEmail":
return contact.email;
case "supportPhone":
return contact.phone;
case "supportPhoneTel":
// tel: hrefs must not carry the display spacing.
return contact.phone.replace(/\s/g, "");
case "supportOffice":
return contact.office;
case "supportHours":
return contact.hours;
}
}
/**
* Substitutes `{{supportEmail}}`-style placeholders against the editable
* contact block. The support address used to be interpolated into the privacy
* and terms prose at build time, which meant editing it would have left those
* paragraphs quoting a stale one.
*
* Uses a replacement *callback* on purpose: with a replacement string, a `$&`
* or `$1` inside an admin-typed office address would be treated as a
* backreference and corrupt the output.
*
* Unknown tokens are left verbatim — the pattern only matches the four known
* names — so a typo shows up as `{{supportEmial}}` rather than a blank.
*/
export function applyPortalVars(
text: string,
contact: PortalSupportContact,
): string {
return text.replace(VAR_PATTERN, (_match, name: PortalContentVar) =>
resolveVar(name, contact),
);
}
/**
* Applies {@link applyPortalVars} to every string in the bundle except the
* contact block itself, which is the substitution source. Walking the whole
* object means a placeholder works in any field, including ones added later.
*/
export function withSupportVars(
bundle: PortalContentBundle,
): PortalContentBundle {
const { contact, ...rest } = bundle;
const walk = (value: unknown): unknown => {
if (typeof value === "string") return applyPortalVars(value, contact);
if (Array.isArray(value)) return value.map(walk);
if (value && typeof value === "object") {
return Object.fromEntries(
Object.entries(value).map(([key, inner]) => [key, walk(inner)]),
);
}
return value;
};
return { contact, ...(walk(rest) as Omit<PortalContentBundle, "contact">) };
}
/**
* Accepts only a same-origin path or an https URL for an attached image or
* video, returning null for anything else so the caller renders nothing.
*
* `(?!\/)` rejects protocol-relative `//host/...`, which would otherwise pass
* as a path. An `<img>`/`<source>` src is not a navigation, so a `javascript:`
* URL would not execute anyway — but the guard is cheaper than re-deriving
* that every time someone reads this file.
*/
export function safeMediaSrc(src: string): string | null {
return /^(https:\/\/|\/(?!\/))/.test(src) ? src : null;
}

View File

@@ -13,11 +13,17 @@ export const MAX_PAYMENT_HOURS = 2;
export const CUTOFF_MINUTES = 30;
/**
* payment_deadline = MIN(booking_time + MAX_PAYMENT_HOURS, segment_departure - checkinMinutes)
*
* checkinMinutes defaults to CUTOFF_MINUTES but callers should pass the route-level
* checkinMinutesBefore so that each route's own window is respected.
* How long a passenger is given to finish one provider payment session, once opened.
* 5 minutes of actual paying (redirect → PIN/OTP → provider callback) + 1 minute of slack.
*/
export const PAYMENT_SESSION_MINUTES = 6;
export const MIN_PAYMENT_WINDOW_MINUTES = 7;
export const PAYMENT_SETTLE_MARGIN_SECONDS = 60;
export function computePaymentDeadline(
createdAt: Date,
departureAt: Date,
@@ -27,3 +33,19 @@ export function computePaymentDeadline(
const cutoffDeadline = new Date(departureAt.getTime() - checkinMinutes * 60 * 1000);
return maxDeadline < cutoffDeadline ? maxDeadline : cutoffDeadline;
}
export function canOpenPaymentSession(
paymentDeadline: Date,
now: Date = new Date(),
): boolean {
return paymentDeadline.getTime() - now.getTime() >= MIN_PAYMENT_WINDOW_MINUTES * 60 * 1000;
}
export function computePaymentSessionExpiry(
paymentDeadline: Date,
now: Date = new Date(),
): Date {
const sessionEnd = new Date(now.getTime() + PAYMENT_SESSION_MINUTES * 60 * 1000);
return sessionEnd < paymentDeadline ? sessionEnd : paymentDeadline;
}

View File

@@ -56,7 +56,7 @@ class WaiveSupplementaryChargeDto {
class PaySupplementaryChargeDto {
@ApiProperty({ enum: PaymentMethodTypeEnum, example: 'TELEBIRR' }) @IsEnum(PaymentMethodTypeEnum) method: PaymentMethodTypeEnum;
@ApiPropertyOptional({ enum: ['web', 'mobile'], default: 'web' }) @IsOptional() @IsIn(['web', 'mobile']) platform?: 'web' | 'mobile';
@ApiPropertyOptional({ enum: ['web', 'mobile', 'inapp'], default: 'web' }) @IsOptional() @IsIn(['web', 'mobile', 'inapp']) platform?: PaymentPlatformDto;
}
@ApiTags("Payment")
@@ -307,7 +307,14 @@ export class PaymentsController {
})
@ApiQuery({ name: "bookingId", required: true })
@ApiQuery({ name: "method", enum: PaymentMethodTypeEnum, required: true })
@ApiQuery({ name: "platform", enum: ["web", "mobile"], required: false })
@ApiQuery({
name: "platform",
enum: ["web", "mobile"],
required: false,
description:
"Browser-only endpoint — `inapp` is not offered here. A mini-app payer has no browser " +
"to redirect and must go through POST /payments/initiate for the bridge payload.",
})
@ApiProduces("text/html")
async checkout(
@Query("bookingId") bookingId: string,

View File

@@ -28,7 +28,8 @@ export enum PaymentMethodTypeEnum {
CBE_BILL = "CBE_BILL", // Ethiopia (pay at any CBE channel by bill number)
}
export type PaymentPlatformDto = "web" | "mobile";
/** Mirrors `PaymentPlatform` in @edr/types — see there for what each surface means. */
export type PaymentPlatformDto = "web" | "mobile" | "inapp";
export class InitiatePaymentDto {
@ApiProperty({ example: "booking-uuid" }) @IsString() bookingId: string;
@@ -45,12 +46,14 @@ export class InitiatePaymentDto {
@IsString()
paymentMethodId?: string;
@ApiPropertyOptional({
enum: ["web", "mobile"],
enum: ["web", "mobile", "inapp"],
default: "web",
description: "Payment platform (web or mobile)",
description:
"Payer surface. `inapp` = the portal is running inside a SuperApp mini-app WebView " +
"(Telebirr), which cannot follow redirect flows and gets a bridge payload instead.",
})
@IsOptional()
@IsIn(["web", "mobile"])
@IsIn(["web", "mobile", "inapp"])
platform?: PaymentPlatformDto;
@ApiPropertyOptional({
description:
@@ -117,9 +120,20 @@ export class SupportedPaymentMethodDto {
export class ClientActionDto {
@ApiProperty({
enum: ["REDIRECT", "LAUNCH_APP", "COLLECT_OTP", "SHOW_BILL_REFERENCE"],
enum: [
"REDIRECT",
"LAUNCH_APP",
"INVOKE_BRIDGE",
"COLLECT_OTP",
"SHOW_BILL_REFERENCE",
],
})
type: "REDIRECT" | "LAUNCH_APP" | "COLLECT_OTP" | "SHOW_BILL_REFERENCE";
type:
| "REDIRECT"
| "LAUNCH_APP"
| "INVOKE_BRIDGE"
| "COLLECT_OTP"
| "SHOW_BILL_REFERENCE";
@ApiPropertyOptional({ description: "Set when type=REDIRECT (web flow)" })
url?: string;
@ApiPropertyOptional({
@@ -134,6 +148,18 @@ export class ClientActionDto {
description: "Set when type=LAUNCH_APP (mobile flow)",
})
shortCode?: string;
@ApiPropertyOptional({
description:
"Set when type=INVOKE_BRIDGE (telebirr mini app) — which SuperApp host bridge to call",
enum: ["TELEBIRR"],
})
bridge?: "TELEBIRR";
@ApiPropertyOptional({
description:
"Set when type=INVOKE_BRIDGE (telebirr mini app). Signed query string handed verbatim " +
"to the host bridge (js_fun_start_pay). NOT a URL — never navigate to it.",
})
rawRequest?: string;
@ApiPropertyOptional({ description: "Set when type=COLLECT_OTP (e.g. CAC Bank)" })
providerOrderId?: string;
@ApiPropertyOptional({ description: "Set when type=COLLECT_OTP" })
@@ -154,6 +180,10 @@ export class InitiateResponseDto {
@ApiPropertyOptional({ type: ClientActionDto })
clientAction?: ClientActionDto;
@ApiPropertyOptional() merchantOrderId?: string;
/** When this payment session stops being offered — PAYMENT_SESSION_MINUTES from initiation, capped at paymentDeadline. Drives the client-side countdown. */
@ApiPropertyOptional() sessionExpiresAt?: string;
/** The booking's payment deadline: after it, the booking is auto-cancelled. */
@ApiPropertyOptional() paymentDeadline?: string;
}
export class IntentStatusDto {

View File

@@ -16,6 +16,11 @@ import {
ProviderMethod,
ProviderPaymentStatus,
} from "@edr/types";
import {
MAX_PAYMENT_HOURS,
MIN_PAYMENT_WINDOW_MINUTES,
PAYMENT_SESSION_MINUTES,
} from "../../common/utils/payment-deadline.utils";
describe("PaymentsService", () => {
let service: PaymentsService;
@@ -163,6 +168,69 @@ describe("PaymentsService", () => {
).rejects.toThrow(BadRequestException);
});
/**
* A booking whose payment deadline lands exactly `minutesLeft` from now: the deadline is
* MIN(createdAt + MAX_PAYMENT_HOURS, departure - checkin), so back-date createdAt and keep
* departure far away. Derived from MAX_PAYMENT_HOURS so the test survives changes to it.
*/
const bookingWithDeadlineIn = (minutesLeft: number) => ({
...mockBooking,
createdAt: new Date(
Date.now() - (MAX_PAYMENT_HOURS * 60 - minutesLeft) * 60 * 1000,
),
originStationId: null,
schedule: {
departureAt: new Date(Date.now() + 10 * 60 * 60 * 1000),
stopTimes: [],
route: null,
},
});
it("should refuse to open a provider session that cannot finish before auto-cancel", async () => {
// 2 minutes left — the real incident: the session was opened, the provider captured the
// money, and the auto-cancel cron had already cancelled the booking by then.
mockPrisma.booking.findUnique.mockResolvedValue(bookingWithDeadlineIn(2));
await expect(
service.initiatePayment({
bookingId: "booking-1",
method: "TELEBIRR" as any,
}),
).rejects.toThrow(BadRequestException);
// Nothing may reach the provider — no session, no capture, no orphan payment.
expect(mockPaymentClient.initiate).not.toHaveBeenCalled();
});
it("should open a session and report its expiry when the window is wide enough", async () => {
const minutesLeft = MIN_PAYMENT_WINDOW_MINUTES + 3;
mockPrisma.booking.findUnique.mockResolvedValue(
bookingWithDeadlineIn(minutesLeft),
);
mockPaymentClient.initiate.mockResolvedValue(
requiresActionSnapshot(ProviderMethod.TELEBIRR),
);
mockPrisma.paymentIntent.upsert.mockResolvedValue({
id: "intent-1",
status: PaymentIntentStatus.REQUIRES_ACTION,
merchantOrderId: "PSG-MERCH-123",
});
const result = await service.initiatePayment({
bookingId: "booking-1",
method: "TELEBIRR" as any,
});
expect(mockPaymentClient.initiate).toHaveBeenCalled();
// Session ends PAYMENT_SESSION_MINUTES from now — before the deadline, not at it.
const sessionMs =
new Date(result.sessionExpiresAt!).getTime() - Date.now();
expect(sessionMs).toBeLessThanOrEqual(PAYMENT_SESSION_MINUTES * 60 * 1000);
expect(new Date(result.sessionExpiresAt!).getTime()).toBeLessThan(
new Date(result.paymentDeadline!).getTime(),
);
});
it("should initiate a provider payment through the payment microservice", async () => {
mockPrisma.booking.findUnique.mockResolvedValue(mockBooking);
mockPaymentClient.initiate.mockResolvedValue(

View File

@@ -29,7 +29,13 @@ import {
MarkPaidResponseDto,
BillQueryResponseDto,
} from "./internal-payments.dto";
import { computePaymentDeadline } from "../../common/utils/payment-deadline.utils";
import {
computePaymentDeadline,
computePaymentSessionExpiry,
canOpenPaymentSession,
MIN_PAYMENT_WINDOW_MINUTES,
PAYMENT_SETTLE_MARGIN_SECONDS,
} from "../../common/utils/payment-deadline.utils";
import {
PaymentClientService,
PaymentDiagnostic,
@@ -260,6 +266,27 @@ export class PaymentsService {
return this.initiateWalletPayment(booking);
}
// Refuse to open a provider session that cannot finish before auto-cancel. Everything below
// this point hands the passenger off to an external provider (redirect/HPP/OTP), which takes
// minutes; TasksService cancels the booking the first cron tick after its payment deadline.
// Opening a session with less than MIN_PAYMENT_WINDOW_MINUTES left produces the worst possible
// outcome — the provider captures the money and the booking is already CANCELLED when the
// capture lands. WALLET is exempt (returned above): it is an instant internal balance debit.
const paymentDeadline = await this.computeBookingPaymentDeadline(booking.id);
const sessionExpiresAt = paymentDeadline
? computePaymentSessionExpiry(paymentDeadline)
: undefined;
if (paymentDeadline && !canOpenPaymentSession(paymentDeadline)) {
const remainingMs = paymentDeadline.getTime() - Date.now();
throw new BadRequestException(
remainingMs <= 0
? "The payment window for this booking has expired. Please make a new booking."
: `Too little time is left to start a payment (${Math.ceil(remainingMs / 60000)} minute(s) ` +
`until this booking expires; at least ${MIN_PAYMENT_WINDOW_MINUTES} are required). ` +
`Please make a new booking.`,
);
}
// Free method changes: no reuse/blocking. Every initiate opens a fresh provider session; the
// single passenger projection row (upserted by bookingId below) tracks the latest session.
// Confirm-once is enforced when a payment succeeds (finalizePaymentSuccess), not here.
@@ -317,9 +344,7 @@ export class PaymentsService {
payerName =
booking.seats.find((s) => s.leg === 1)?.passengerName ??
booking.seats[0]?.passengerName;
expiresAt = (
await this.computeBookingPaymentDeadline(booking.id)
)?.toISOString();
expiresAt = paymentDeadline?.toISOString();
}
const snapshot = await this.paymentClient.initiate({
@@ -350,7 +375,11 @@ export class PaymentsService {
where: { id: intent.id },
});
}
return this.formatIntentResponse(intent);
return {
...this.formatIntentResponse(intent),
sessionExpiresAt: sessionExpiresAt?.toISOString(),
paymentDeadline: paymentDeadline?.toISOString(),
};
}
/**
@@ -436,8 +465,15 @@ export class PaymentsService {
if (booking.status !== "PENDING_PAYMENT") {
return { ...base, stillPayable: false, reason: "NOT_PAYABLE" };
}
// A CBE debit confirmed now lands in seconds, so this doesn't need the full
// MIN_PAYMENT_WINDOW_MINUTES that opening a session does — but it must not be confirmed so
// close to the deadline that the auto-cancel cron cancels the booking before the capture is
// registered. Refusing here is what keeps CBE from debiting a passenger for a dead booking.
const deadline = await this.computeBookingPaymentDeadline(booking.id);
if (deadline && deadline.getTime() < Date.now()) {
if (
deadline &&
deadline.getTime() - PAYMENT_SETTLE_MARGIN_SECONDS * 1000 < Date.now()
) {
return { ...base, stillPayable: false, reason: "EXPIRED" };
}
return { ...base, stillPayable: true, reason: null };

View File

@@ -5,6 +5,7 @@ import { SmsClientService } from '../notifications/sms-client.service';
import { EmailClientService } from '../notifications/email-client.service';
import { PaymentClientService } from './payment-client.service';
import { PaymentReferenceType, PaymentService as PaymentServiceEnum, ProviderMethod } from '@edr/types';
import { PaymentPlatformDto } from './payments.dto';
const CHARGE_TTL_MS = 72 * 60 * 60 * 1000; // 72 hours
@@ -119,7 +120,7 @@ export class SupplementaryChargesService {
async pay(
token: string,
method: string,
platform?: 'web' | 'mobile',
platform?: PaymentPlatformDto,
requestOrigin?: string | null,
) {
const charge = await this.getByToken(token); // validates status/expiry

View File

@@ -30,13 +30,26 @@ export default function ReportsPage() {
const getDateRange = () => {
const end = new Date();
end.setHours(23, 59, 59, 999);
const start = new Date();
if (dateRange === 'custom') {
if (startDate && endDate) {
return startDate <= endDate
? { startDate, endDate }
: { startDate: endDate, endDate: startDate };
}
const fallbackStart = new Date(end);
fallbackStart.setDate(end.getDate() - 30);
return {
startDate: fallbackStart.toISOString().split('T')[0],
endDate: end.toISOString().split('T')[0],
};
}
const start = new Date(end);
switch (dateRange) {
case '7': start.setDate(end.getDate() - 7); break;
case '30': start.setDate(end.getDate() - 30); break;
case '90': start.setDate(end.getDate() - 90); break;
default:
if (startDate && endDate) return { startDate, endDate };
}
return {
startDate: start.toISOString().split('T')[0],

View File

@@ -74,6 +74,7 @@ export default function PassengersReportPage() {
const [tab, setTab] = useState<Tab>("occupancy");
const [listSearch, setListSearch] = useState("");
const [filterOrigin, setFilterOrigin] = useState("");
const [filterDestination, setFilterDestination] = useState("");
const [filterSeatClass, setFilterSeatClass] = useState("");
const [filterCoachNumber, setFilterCoachNumber] = useState("");
@@ -110,17 +111,23 @@ export default function PassengersReportPage() {
const originOptions = [
...new Set(passengerList.map((p) => p.origin).filter(Boolean)),
].sort() as string[];
const destinationOptions = [
...new Set(passengerList.map((p) => p.destination).filter(Boolean)),
].sort() as string[];
const filteredList = passengerList
.filter((p) => {
if (filterCoachNumber && p.coachNumber !== filterCoachNumber) return false;
if (filterOrigin && p.origin !== filterOrigin) return false;
if (filterDestination && p.destination !== filterDestination) return false;
if (filterSeatClass && p.seatClassName !== filterSeatClass) return false;
if (listSearch.trim()) {
const q = listSearch.toLowerCase();
return (
p.passengerName.toLowerCase().includes(q) ||
p.bookingRef.toLowerCase().includes(q) ||
(p.origin ?? '').toLowerCase().includes(q) ||
(p.destination ?? '').toLowerCase().includes(q) ||
(p.idDocumentNumber ?? "").toLowerCase().includes(q) ||
(p.passportNumber ?? "").toLowerCase().includes(q)
);
@@ -207,6 +214,7 @@ export default function PassengersReportPage() {
setListSearch("");
setFilterCoachNumber("");
setFilterOrigin("");
setFilterDestination("");
setFilterSeatClass("");
}}
disabled={loadingSchedules}
@@ -499,6 +507,18 @@ export default function PassengersReportPage() {
</option>
))}
</select>
<select
className="input w-36"
value={filterDestination}
onChange={(e) => { setFilterDestination(e.target.value); resetListPage(); }}
>
<option value="">All destinations</option>
{destinationOptions.map((d) => (
<option key={d} value={d}>
{d}
</option>
))}
</select>
{passengerList.length > 0 && (
<ActionButton
icon={Download}

View File

@@ -6,7 +6,12 @@ import { usePaymentStore } from "@/lib/payment-store";
import { useMutation, useQuery } from "@tanstack/react-query";
import { apiClient } from "@/lib/api-client";
import { resolvePaymentRedirectUrl } from "@/lib/payment-redirect";
import { useState, useEffect } from "react";
import {
isTelebirrMiniApp,
onTelebirrPayResult,
startTelebirrPay,
} from "@/lib/telebirr-bridge";
import { useState, useEffect, useCallback, useMemo } from "react";
import { PaymentMethod } from "@/types";
import { format } from "date-fns";
import { formatTime, getTimePeriod, toZonedDate } from '@/utils/format';
@@ -55,6 +60,17 @@ export default function PaymentPage() {
} | null>(null);
const [billCopied, setBillCopied] = useState(false);
// Telebirr mini app: the SuperApp payment sheet is open (or just closed) and we're
// polling our own status endpoint for the webhook-backed outcome.
const [verifyingPayment, setVerifyingPayment] = useState(false);
// Resolved once on mount — SSR has no `window`, so this must not be read during render
// of the first (server) pass.
const [inMiniApp, setInMiniApp] = useState(false);
useEffect(() => {
setInMiniApp(isTelebirrMiniApp());
}, []);
const isRoundTrip = searchCriteria?.tripType === 'ROUND_TRIP';
// Use the same display currency as the review page — stored on the schedule at search time.
@@ -72,8 +88,26 @@ export default function PaymentPage() {
},
});
// Inside the telebirr SuperApp only telebirr can complete: every other method is a
// redirect/HPP flow, and the mini-app WebView cannot follow the scheme handoffs those
// gateways use. Offering them would strand the payer on a dead page.
// Memoised: this feeds an effect's dep array, and a fresh array identity every render
// would re-run that effect on every render.
const availableMethods = useMemo(
() => paymentMethods.filter((m) => m.enabled && (!inMiniApp || m.type === 'TELEBIRR')),
[paymentMethods, inMiniApp],
);
const selectedPaymentMethod = paymentMethods.find(m => m.type === selectedMethod) || null;
// A method chosen before the container was known (or carried over in state) may no longer
// be offerable — drop it rather than letting Pay fire against a hidden method.
useEffect(() => {
if (selectedMethod && !availableMethods.some((m) => m.type === selectedMethod)) {
setSelectedMethod(null);
}
}, [selectedMethod, availableMethods]);
// Derive charge currency directly from the selected method — no separate state that can lag.
const amountCurrency = (selectedPaymentMethod?.currency || 'ETB').toUpperCase();
@@ -128,6 +162,70 @@ export default function PaymentPage() {
}
}, [selectedMethod, dataReady, bookingAmountData, reviewedTotal, displayCurrency, setCurrency, setPaidAmount]);
/**
* Poll our own status endpoint until the payment reaches a terminal state.
*
* Used by the telebirr mini-app flow, where nothing navigates and therefore no return page
* ever runs. The bridge callback only tells us the sheet closed; the authoritative outcome
* is the webhook-backed status the API reports here.
*/
const pollPaymentStatus = useCallback(
async (attemptsLeft: number): Promise<void> => {
if (!bookingId) return;
try {
const res: any = await apiClient.get(`/payments/status/${bookingId}`);
if (res?.status === 'SUCCEEDED') {
setVerifyingPayment(false);
updateStatus("SUCCEEDED");
router.push("/booking/confirmation");
return;
}
if (res?.status === 'FAILED' || res?.status === 'CANCELLED') {
setVerifyingPayment(false);
setIsProcessing(false);
updateStatus("FAILED");
setPaymentError(res?.failureMessage || "Payment was not completed. Please try again.");
return;
}
} catch {
// Transient read failure — keep polling; the attempt budget bounds it.
}
if (attemptsLeft <= 0) {
// Don't call it failed: telebirr may have taken the money and the webhook is simply
// still in flight. Stop spinning, tell the truth, and let the payer re-check.
setVerifyingPayment(false);
setIsProcessing(false);
setPaymentError(
"We haven't received confirmation yet. If you completed the payment, your booking " +
"will be confirmed shortly — check My Bookings in a moment before paying again.",
);
return;
}
setTimeout(() => void pollPaymentStatus(attemptsLeft - 1), 1500);
},
[bookingId, router, updateStatus],
);
/**
* Telebirr mini app reports the sheet outcome on a global callback rather than a redirect.
* Registered on mount — the SuperApp can call back the moment the sheet closes, so it must
* already be installed before the bridge is invoked.
*/
useEffect(() => {
return onTelebirrPayResult((succeeded) => {
if (!succeeded) {
setVerifyingPayment(false);
setIsProcessing(false);
updateStatus("FAILED");
setPaymentError("Payment was cancelled or declined. Please try again.");
return;
}
setVerifyingPayment(true);
void pollPaymentStatus(15);
});
}, [pollPaymentStatus, updateStatus]);
const paymentMutation = useMutation({
mutationFn: async (data: any) => {
return await apiClient.post("/payments/initiate", {
@@ -135,7 +233,7 @@ export default function PaymentPage() {
method: data.method,
paymentMethodId: data.paymentMethodId,
payerAccount: data.payerAccount,
platform: 'web',
platform: isTelebirrMiniApp() ? 'inapp' : 'web',
});
},
onSuccess: async (data: any) => {
@@ -163,6 +261,23 @@ export default function PaymentPage() {
return;
}
// Telebirr mini app: hand the signed rawRequest to the SuperApp bridge. Nothing
// navigates — telebirr draws its payment sheet over the WebView and reports back on
// the global callback registered above, which starts the status polling.
if (data?.clientAction?.type === 'INVOKE_BRIDGE') {
setPaymentIntent(data.intentId);
updateStatus("REQUIRES_ACTION");
if (!startTelebirrPay(data.clientAction.rawRequest)) {
setIsProcessing(false);
updateStatus("FAILED");
setPaymentError(
"Couldn't open the telebirr payment sheet. Please reopen this page from the " +
"telebirr app and try again.",
);
}
return;
}
if ((selectedMethod === 'TELEBIRR' || selectedMethod === 'WAAFI' || selectedMethod === 'DMONEY') && data?.clientAction?.type === 'REDIRECT') {
setPaymentIntent(data.intentId);
updateStatus("REQUIRES_ACTION");
@@ -505,7 +620,15 @@ export default function PaymentPage() {
{isProcessing && (
<div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50">
<div className="bg-white dark:bg-gray-800 rounded-xl p-8 max-w-sm w-full mx-4 text-center shadow-2xl">
{paymentMutation.isSuccess ? (
{verifyingPayment ? (
<>
<Loader2 className="w-14 h-14 text-primary animate-spin mx-auto mb-4" />
<h3 className="text-lg font-bold mb-1 text-gray-900 dark:text-gray-100">Confirming payment</h3>
<p className="text-sm text-gray-500 dark:text-gray-400">
Checking with telebirr this only takes a moment.
</p>
</>
) : paymentMutation.isSuccess ? (
<>
<CheckCircle className="w-14 h-14 text-green-500 mx-auto mb-4" />
<h3 className="text-lg font-bold mb-4 text-gray-900 dark:text-gray-100">Loading...</h3>
@@ -688,13 +811,13 @@ export default function PaymentPage() {
<div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4">
<p className="text-red-800 dark:text-red-200 text-sm">Failed to load payment methods. Please refresh.</p>
</div>
) : paymentMethods.length === 0 ? (
) : availableMethods.length === 0 ? (
<div className="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg p-4">
<p className="text-yellow-800 dark:text-yellow-200 text-sm">No payment methods available at the moment.</p>
</div>
) : (
<div className="space-y-3">
{paymentMethods.filter(m => m.enabled).map((method) => {
{availableMethods.map((method) => {
const Icon = getIconForMethod(method.type);
const isSelected = selectedMethod === method.type;
return (

View File

@@ -0,0 +1,106 @@
/**
* Telebirr SuperApp mini-app bridge.
*
* When the portal runs inside the telebirr SuperApp, the ordinary web checkout is unusable:
* the H5 paygate page hands off to the native wallet with a custom scheme
* (`kcbconsumer://h5checkout?...`) that the SuperApp's WebView cannot resolve, so the payer
* only ever sees `net::ERR_UNKNOWN_URL_SCHEME`.
*
* The in-app flow never navigates. The API returns a signed `rawRequest` string
* (clientAction.type === "INVOKE_BRIDGE") which is handed to the host's JS bridge; telebirr
* renders its own payment sheet over the WebView and reports the outcome on a global callback.
*
* See docs/telebirr-miniapp/inapp-payment-plan.md.
*/
/** Name of the global the SuperApp calls back into. Must be a property of `window`. */
export const TELEBIRR_PAY_CALLBACK = "handleEdrPaymentCallback";
type ConsumerApp = { evaluate: (payload: string) => void };
declare global {
interface Window {
/** Injected by the telebirr SuperApp WebView. Absent everywhere else. */
consumerapp?: ConsumerApp;
[TELEBIRR_PAY_CALLBACK]?: (response: unknown) => void;
}
}
/**
* True only when the telebirr host bridge is actually present.
*
* Deliberately does NOT sniff the user agent. A UA match without `window.consumerapp` would
* make us request `platform: "inapp"` and get back a bare rawRequest we have no way to use —
* there is no navigating our way out of that, because by then the server has already committed
* to the bridge payload. Gating on the bridge object keeps the decision and the capability in
* sync: if we can't call it, we don't ask for it.
*/
export function isTelebirrMiniApp(): boolean {
return typeof window !== "undefined" && typeof window.consumerapp?.evaluate === "function";
}
/**
* Hand a signed rawRequest to the SuperApp to open its payment sheet.
*
* Register the callback (see `onTelebirrPayResult`) BEFORE calling this — the host may invoke
* it as soon as the sheet closes. Returns false when the bridge is missing or throws, so the
* caller can surface an error instead of leaving the payer on a dead spinner.
*/
export function startTelebirrPay(rawRequest: string): boolean {
if (!isTelebirrMiniApp()) return false;
try {
window.consumerapp!.evaluate(
JSON.stringify({
functionName: "js_fun_start_pay",
params: {
rawRequest,
functionCallBackName: TELEBIRR_PAY_CALLBACK,
},
}),
);
return true;
} catch (err) {
console.error("[telebirr] bridge evaluate failed:", err);
return false;
}
}
/**
* Install the global result callback; returns a disposer for effect cleanup.
*
* The result is a TRIGGER TO VERIFY, never proof of payment — the payer can close the sheet,
* the host can report success before settlement lands, and the payload shape is not a contract.
* Confirmation always comes from polling our own payment status (webhook-backed).
*/
export function onTelebirrPayResult(handler: (succeeded: boolean) => void): () => void {
if (typeof window === "undefined") return () => {};
window[TELEBIRR_PAY_CALLBACK] = (response: unknown) => {
handler(isSuccessResponse(response));
};
return () => {
delete window[TELEBIRR_PAY_CALLBACK];
};
}
/**
* Telebirr reports `code: 0` (number or string) for success. The payload arrives as either a
* JSON string or an object depending on host version, and an unparseable payload is treated as
* success on purpose: polling is what decides the outcome, and a false "failed" would strand a
* payer who actually paid.
*/
function isSuccessResponse(response: unknown): boolean {
let parsed: unknown = response;
if (typeof response === "string") {
try {
parsed = JSON.parse(response);
} catch {
return true;
}
}
if (parsed && typeof parsed === "object" && "code" in parsed) {
const code = (parsed as { code: unknown }).code;
if (code === undefined || code === null) return true;
return code === 0 || code === "0";
}
return true;
}

View File

@@ -62,9 +62,14 @@ export class InitiatePaymentRequestDto implements InitiatePaymentRequest {
@IsEnum(ProviderMethod)
provider!: ProviderMethod;
@ApiPropertyOptional({ enum: ["web", "mobile"] })
@ApiPropertyOptional({
enum: ["web", "mobile", "inapp"],
description:
"Payer surface. `inapp` = running inside a SuperApp mini-app WebView (Telebirr), " +
"which cannot follow redirect/HPP flows and gets a bridge payload instead.",
})
@IsOptional()
@IsIn(["web", "mobile"])
@IsIn(["web", "mobile", "inapp"])
platform?: PaymentPlatform;
@ApiPropertyOptional({

View File

@@ -353,7 +353,7 @@ export class DMoneyProvider implements PaymentProvider {
return this.config.get<string>("dmoney.returnUrl") ?? "";
}
private get timeoutExpress(): string {
return this.config.get<string>("dmoney.timeoutExpress") ?? "120m";
return this.config.get<string>("dmoney.timeoutExpress") ?? "5m";
}
private get language(): string {
return this.config.get<string>("dmoney.language") ?? "en";

View File

@@ -2,6 +2,8 @@ import { Injectable, Logger } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { HttpService } from "@nestjs/axios";
import {
ClientAction,
PaymentPlatform,
PaymentProvider,
ProviderInitiationInput,
ProviderInitiationResult,
@@ -67,15 +69,7 @@ export class TelebirrProvider implements PaymentProvider {
requestBody.biz_content.timeout_express,
);
const platform = input.platform ?? "web";
const clientAction =
platform === "mobile"
? {
type: "LAUNCH_APP" as const,
appId: this.merchantAppId,
receiveCode: response.biz_content?.receiveCode,
shortCode: this.merchantCode,
}
: { type: "REDIRECT" as const, url: this.buildCheckoutUrl(prepayId) };
const clientAction = this.buildClientAction(platform, prepayId, response);
return {
providerOrderId: prepayId,
@@ -199,6 +193,11 @@ export class TelebirrProvider implements PaymentProvider {
input: ProviderInitiationInput,
): CreateOrderRequest {
const totalAmount = String(input.amountMinor);
// In-app pays inside the SuperApp overlay and never navigates, so there is no browser
// to send back — telebirr's own in-app integration omits redirect_url entirely. Keep it
// absent rather than undefined: a signed-but-unsent field is what produced the earlier
// "verify sign failed" (see docs/payment-service + telebirr.crypto skip-undefined).
const wantsRedirect = input.platform !== "inapp" && !!input.redirectUrl;
const req = {
timestamp: createTimestamp(),
nonce_str: createNonceStr(),
@@ -214,7 +213,7 @@ export class TelebirrProvider implements PaymentProvider {
total_amount: totalAmount,
trans_currency: input.currency,
timeout_express: this.timeoutExpress,
...(input.redirectUrl ? { redirect_url: input.redirectUrl } : {}),
...(wantsRedirect ? { redirect_url: input.redirectUrl! } : {}),
},
};
const sign = signRequestObject(
@@ -245,6 +244,68 @@ export class TelebirrProvider implements PaymentProvider {
return { ...req, sign, sign_type: "SHA256WithRSA" };
}
/**
* Telebirr exposes the same pre-order three ways; only the launch payload differs.
*
* - `mobile` — native app hands off to the wallet app with a receiveCode.
* - `inapp` — the portal is running inside the telebirr SuperApp mini-app WebView. The
* H5 checkout page is unusable there: it deep-links to `kcbconsumer://…`,
* which the WebView cannot resolve (`net::ERR_UNKNOWN_URL_SCHEME`). The
* signed rawRequest goes to the host JS bridge instead — no navigation.
* - `web` — ordinary browser; redirect to the H5 checkout page.
*/
private buildClientAction(
platform: PaymentPlatform,
prepayId: string,
response: CreateOrderResponse,
): ClientAction {
switch (platform) {
case "mobile":
return {
type: "LAUNCH_APP",
appId: this.merchantAppId,
receiveCode: response.biz_content?.receiveCode,
shortCode: this.merchantCode,
};
case "inapp":
return {
type: "INVOKE_BRIDGE",
bridge: "TELEBIRR",
rawRequest: this.buildInAppRawRequest(prepayId),
};
default:
return { type: "REDIRECT", url: this.buildCheckoutUrl(prepayId) };
}
}
/**
* Signed request handed verbatim to the SuperApp bridge (`js_fun_start_pay`).
*
* Emits `appid, merch_code, nonce_str, prepay_id, timestamp, sign_type, sign` in that
* order — no `webBaseUrl` prefix and no `version`/`trade_type` tail, because the bridge
* takes the bare query string rather than a URL.
*
* `sign_type` sits in the map purely so it lands in the output in the right position;
* `buildCanonicalString` excludes it (as does telebirr's own reference implementation),
* so the signature covers the same five fields as the web checkout URL.
*
* Kept separate from `buildCheckoutUrl` rather than sharing a builder: the two payloads
* are consumed by different validators, and the web flow is live.
*/
private buildInAppRawRequest(prepayId: string): string {
const map: Record<string, string> = {
appid: this.merchantAppId,
merch_code: this.merchantCode,
nonce_str: createNonceStr(),
prepay_id: prepayId,
timestamp: createTimestamp(),
sign_type: "SHA256WithRSA",
};
const sign = signRequestObject(map, this.privateKey);
const fields = Object.entries(map).map(([k, v]) => `${k}=${v}`);
return [...fields, `sign=${sign}`].join("&");
}
private buildCheckoutUrl(prepayId: string): string {
const map: Record<string, string> = {
appid: this.merchantAppId,

View File

@@ -32,7 +32,8 @@ export enum ProviderMethod {
CBE_BILL = "CBE_BILL",
}
export type PaymentPlatform = "web" | "mobile";
export type PaymentPlatform = "web" | "mobile" | "inapp";
export type ClientAction =
| { type: "REDIRECT"; url: string }
@@ -42,6 +43,16 @@ export type ClientAction =
receiveCode?: string;
shortCode: string;
}
| {
type: "INVOKE_BRIDGE";
/** Which SuperApp host bridge the payload targets. */
bridge: "TELEBIRR";
/**
* Signed query string handed verbatim to the host bridge (`js_fun_start_pay`).
* NOT a URL — it has no scheme or host and must never be navigated to.
*/
rawRequest: string;
}
| {
type: "COLLECT_OTP";
providerOrderId: string;

View File

@@ -11,6 +11,8 @@ export * from "./ethiopian-regions.catalog";
export * from "./notifications";
export * from "./booking-window-ws";
export * from "./support-chat";
export * from "./portal-content";
export * from "./portal-content.defaults";
export enum TradeDirection {
IMPORT = "IMPORT",

View File

@@ -0,0 +1,375 @@
import type { SupportDocPayloadMap } from "./portal-content";
/**
* The copy the portal shipped with, transcribed from what used to be
* `edr-freight-web/portal/src/pages/support/content.ts` and the inline blocks
* of `HelpPage.tsx`.
*
* Two mechanical changes from the original:
*
* 1. `Section { body: string[]; bullets: string[] }` collapses to one markdown
* string — paragraphs separated by a blank line, bullets as `- ` lines.
* 2. The support email/phone/office, previously string-interpolated into the
* privacy and terms prose at build time, are now `{{supportEmail}}`-style
* placeholders resolved against the CONTACT document at read time. That is
* what stops the legal text keeping a stale phone number after an edit.
*
* It lives in the shared package because three consumers need the same bytes
* and any drift between them would only surface during an outage: the API
* seeds the database from it and serves it for any row still missing, and the
* portal renders it while the request is in flight or if the API is down.
* Once seeded, the database is authoritative and this is only a floor.
*/
export const SUPPORT_CONTENT_DEFAULTS: SupportDocPayloadMap = {
CONTACT: {
email: "support@edrfreight.com",
phone: "+251 11 000 0000",
office: "Addis Ababa, Ethiopia",
hours: "Monday Saturday, 8:30 AM 5:30 PM (EAT)",
},
HELP: {
title: "Help & Support",
subtitle:
"Get answers fast — watch the walkthrough, browse the common topics, check the FAQ, or reach our team directly.",
sections: [
{
id: "help-walkthrough",
heading: "Portal walkthrough",
body: "A guided tour of the portal — registering your company, raising a booking against a contract, and settling an invoice.",
media: [
{
id: "help-walkthrough-video",
kind: "video",
// Ships with the app rather than MinIO, so it is used verbatim.
src: "/assets/edr-portal-guide.webm",
caption: null,
},
],
},
{
id: "help-chat",
heading: "Chat with our team",
body: "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.\n\n[Open the portal](/portal)",
media: [],
},
{
id: "help-contact",
heading: "Contact us",
body: "- **Email** — [{{supportEmail}}](mailto:{{supportEmail}}). Best for document issues and anything needing an attachment.\n- **Phone** — [{{supportPhone}}](tel:{{supportPhoneTel}}). Best for urgent problems with cargo already in transit.\n- **Head office** — {{supportOffice}}. Walk-in support during working hours.\n- **Support hours** — {{supportHours}}. Outside these hours, email us and we reply the next working day.",
media: [],
},
{
id: "help-topics",
heading: "Common topics",
body: "- **[Account & onboarding](/faq)** — registering your company, uploading your trade licence and TIN, and getting an operational profile approved.\n- **[Contracts](/faq)** — requesting a freight contract, reviewing its terms and signing it with your saved signature and stamp.\n- **[Bookings & tracking](/faq)** — raising a booking against a contract, adding last-mile transport and following the consignment along the corridor.\n- **[Invoices & payments](/faq)** — finding invoices, paying through the bank channels and confirming a payment that has not yet settled.",
media: [],
},
{
id: "help-checklist",
heading: "What to include when you contact us",
body: "- Your company name and the email you sign in with.\n- The reference of the contract, booking or invoice involved.\n- What you expected to happen and what happened instead.\n- A screenshot of any error message the portal showed.",
media: [],
},
],
},
FAQ: {
title: "Frequently Asked Questions",
subtitle:
"Answers to the questions customers ask most about registering, booking cargo and settling invoices on EDR Freight.",
groups: [
{
id: "faq-getting-started",
title: "Getting started",
items: [
{
id: "faq-open-account",
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.",
},
{
id: "faq-approval-time",
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.",
},
{
id: "faq-rejected",
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.",
},
{
id: "faq-multiple-services",
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.",
},
],
},
{
id: "faq-contracts-bookings",
title: "Contracts and bookings",
items: [
{
id: "faq-contract-vs-booking",
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.",
},
{
id: "faq-create-booking",
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.",
},
{
id: "faq-sign-contract",
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.",
},
{
id: "faq-signature-setup",
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.",
},
{
id: "faq-change-booking",
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.",
},
{
id: "faq-track-consignment",
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.",
},
],
},
{
id: "faq-invoices-payments",
title: "Invoices and payments",
items: [
{
id: "faq-find-invoices",
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.",
},
{
id: "faq-payment-methods",
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.",
},
{
id: "faq-payment-not-settled",
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.",
},
{
id: "faq-rounding",
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.",
},
],
},
{
id: "faq-account-security",
title: "Account and security",
items: [
{
id: "faq-reset-password",
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.",
},
{
id: "faq-add-colleagues",
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.",
},
{
id: "faq-update-company",
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.",
},
],
},
],
footer: {
heading: "Still need a hand?",
body: "Our team is on {{supportEmail}} and {{supportPhone}}, or you can start a chat from the support button inside the portal.",
ctaLabel: "Go to Help & Support",
ctaTo: "/help",
},
},
PRIVACY: {
title: "Privacy Policy",
subtitle:
"How EDR Freight collects, uses, shares and protects the information you provide when you use the platform.",
lastUpdated: "6 August 2026",
sections: [
{
id: "privacy-1",
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.\n\nThis 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.',
},
{
id: "privacy-2",
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.\n\n- Account details — name, work email address, phone number and the credentials used to sign in.\n- Company and compliance records — legal name, trade licence, TIN certificate, VAT registration, ownership and manager details, and the operational services you apply for.\n- Identity verification data — where you verify through a national identity service, the verification result and the attributes that service returns to us.\n- Operational data — contracts, bookings, consignment and cargo details, container and wagon assignments, tracking events and delivery confirmations.\n- Financial data — invoices, payment references, transaction status and settlement confirmations received from banks. We do not store your card numbers or online banking credentials.\n- Support data — the messages and files you send us through the in-app support chat or by email.\n- Technical data — IP address, device and browser information, and event logs generated when you use the platform.",
},
{
id: "privacy-3",
heading: "3. How we use your information",
body: "- To create and administer your account and verify that your company is entitled to the services it applies for.\n- To perform the freight contracts and bookings you place, including allocating capacity and coordinating rail and last-mile movements.\n- To issue invoices, process payments and keep the accounting records the law requires us to keep.\n- To provide customer support and respond to the questions and complaints you raise.\n- To keep the platform secure, detect misuse and investigate incidents.\n- To meet our legal, tax, customs and regulatory obligations in Ethiopia and Djibouti.\n- To improve the platform — measuring which features are used and where users encounter errors, using aggregated and pseudonymised data wherever that is sufficient.",
},
{
id: "privacy-4",
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.",
},
{
id: "privacy-5",
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.\n\n- Government and regulatory bodies — customs, revenue and transport authorities in Ethiopia and Djibouti, to the extent required for the movement of your cargo.\n- Ports, terminals and last-mile transporters involved in executing your bookings.\n- Banks and payment providers, to initiate and reconcile the payments you make.\n- Technology suppliers who host and maintain the platform on our behalf, under contracts that restrict them to processing data on our instructions.\n- Courts, law enforcement and other authorities where we are legally compelled to disclose.",
},
{
id: "privacy-6",
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.",
},
{
id: "privacy-7",
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.",
},
{
id: "privacy-8",
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.",
},
{
id: "privacy-9",
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.",
},
{
id: "privacy-10",
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.",
},
{
id: "privacy-11",
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.",
},
{
id: "privacy-12",
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.",
},
{
id: "privacy-13",
heading: "13. Contact us",
body: "Questions about this policy or about how we handle your information can be sent to {{supportEmail}}, called in on {{supportPhone}}, or addressed to our head office in {{supportOffice}}.",
},
],
},
TERMS: {
title: "Terms of Service",
subtitle:
"The terms on which EDR provides the EDR Freight platform and the freight services you request through it.",
lastUpdated: "6 August 2026",
sections: [
{
id: "terms-1",
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.\n\nThe 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.',
},
{
id: "terms-2",
heading: "2. Eligibility and accounts",
body: "- 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.\n- The information and documents you submit — trade licence, TIN, VAT registration, ownership details — must be accurate, current and genuine.\n- Accounts and operational profiles are activated only after EDR has reviewed and approved them, and approval may be refused or withdrawn.\n- You are responsible for keeping credentials confidential and for everything done under your account. Tell us at once if you suspect unauthorised use.",
},
{
id: "terms-3",
heading: "3. Contracts and bookings",
body: "- A freight contract takes effect when it is signed in the platform by you and countersigned by EDR.\n- 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.\n- You are responsible for the accuracy of consignment data: commodity description, weight, dimensions, container numbers, hazardous classification and consignee details.\n- Capacity is finite. EDR may decline, defer or reschedule a booking where capacity, safety, operating conditions or regulatory direction require it.",
},
{
id: "terms-4",
heading: "4. Cargo, documents and compliance",
body: "- 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.\n- Prohibited and restricted goods may not be tendered without EDR's prior written agreement and any licence the law requires.\n- 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.\n- You are liable for fines, demurrage, storage charges and losses arising from misdeclared cargo, missing documents or delays attributable to you.",
},
{
id: "terms-5",
heading: "5. Rates, invoicing and payment",
body: "- Charges are calculated from the rates in your contract, the tariffs published in the platform, and any accessorial services actually rendered.\n- Invoices are issued in the platform and are payable by the due date shown on them, through the payment channels the platform offers.\n- Payment is confirmed when the funds are confirmed by the bank, not when payment is initiated.\n- Overdue amounts may attract interest and may result in suspension of new bookings or of the account until the balance is cleared.\n- Taxes and statutory duties are your responsibility unless the contract expressly says otherwise.",
},
{
id: "terms-6",
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.\n\nEDR'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.\n\nNeither 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.",
},
{
id: "terms-7",
heading: "7. Acceptable use of the platform",
body: "- Use the platform only for its intended purpose and in accordance with applicable law.\n- Do not attempt to gain unauthorised access, probe or disrupt the service, or interfere with other customers' data.\n- Do not scrape, resell or redistribute platform content, rates or data without written permission.\n- Do not upload malware or content that infringes the rights of others.",
},
{
id: "terms-8",
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.",
},
{
id: "terms-9",
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.",
},
{
id: "terms-10",
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.",
},
{
id: "terms-11",
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.",
},
{
id: "terms-12",
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.",
},
{
id: "terms-13",
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.",
},
{
id: "terms-14",
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.",
},
{
id: "terms-15",
heading: "15. Contact",
body: "For questions about these terms, write to {{supportEmail}} or call {{supportPhone}}.",
},
],
},
};

Some files were not shown because too many files have changed in this diff Show More