DJF was priced off a rate nobody could see or set. The rate itself worked —
CBE quotes DJF and the provider read it — but `exchange_settings` held a
single USD→ETB row, `getStatus()` hardcoded `rates.get("USD")`, and the
settings card was titled "Exchange rate (USD → ETB)". So an operator could
enable DJF billing, have invoices priced in francs, and have no way to see
which rate produced them and no way to override it during an outage. Those
are exactly the two levers they have for USD.
The original reasoning — DJF is pegged to USD, so a second stored number is
a second thing that goes stale — justified not storing a second FALLBACK.
It never justified not displaying the rate. Those got conflated.
`exchange_settings` becomes one row per currency. `fallback_rate` means the
same thing in every row: ETB per one unit of `currency`. The ETB row is 1
and exists so the table describes the whole set rather than "the others".
`enabled` generalises `djf_enabled` from 3790000000000 — availability is a
property of a currency, not a column named after one — and the migration
carries the old flag onto the DJF row so an operator who had already
switched it on does not find it off after deploying.
loadFallbackRate/saveFallbackRate take a currency. The provider persists
every quoted rate from the one payload it already fetched, so DJF has its
own last-known-good value to fall back on, and reads that currency's own
stored rate first — a rate an operator typed by hand during an outage must
not be silently re-derived from USD. The peg survives one rung lower: when
a currency has nothing stored, USD's stored rate through the peg still
beats the compiled-in default, which is a year-old number by definition.
The DTO's `@Min(1)` is now `@Min(0.0001)`. It would have rejected every
legitimate DJF rate — birr per franc is about 0.92.
Verified against the dev database: one live fetch stamped last_synced_at on
both the USD and DJF rows, which is the behaviour that was missing.
Exercising DJF through the portal means enabling the flag, building a
booking, and clicking through the wizard before a single franc figure
appears. This prices an existing booking three ways instead and prints the
lines side by side, so the rate feed, the conversion, the zero-decimal
rounding and the cross-currency parity are all visible in one command.
Read-only: computePriceForBooking persists nothing and the currency is
flipped on the in-memory entity, so it is safe against a shared database
and safe to re-run.
pnpm --filter @edr/freight-api exec ts-node -r tsconfig-paths/register \
src/scripts/check-djf-pricing.ts BK-2026-000221
The parity line is the check worth reading: the same freight quoted in ETB
and in DJF must come back to the same money once converted. Anything past
rounding drift means a rate or a conversion is wrong.
PROVIDER_CURRENCIES was permissive for everything except CBE_BILL, on the
reasoning that the adapters pass input.currency through verbatim and
nothing in them refuses a currency. That was the wrong place to look. The
configuration says otherwise, and so does the domain: Telebirr is Ethio
Telecom, CBE Birr is a Commercial Bank of Ethiopia wallet, and neither
settles Djiboutian francs. The table as written would have let a DJF
freight invoice be routed to one of them.
payments.service.ts already states the rule above its chargeCurrency
resolution — "WAAFI/DMONEY settle in DJF, CARD in USD, Ethiopian wallets
in ETB" — and fix-payment-method-currency.ts corrected exactly WAAFI to
DJF and CARD to USD, deliberately leaving the Ethiopian methods on the
schema's ETB default. eBirr is configured as one of those: seeded
region ETHIOPIA, never corrected.
So TELEBIRR, CBE_BIRR, CBE_BILL and EBIRR are ETB-only. WAAFI, DMONEY and
CAC_BANK stay open rather than pinned to DJF — that is their configured
settlement currency, not a refusal of anything else, and passenger
converts to each method's own currency before initiating regardless. CARD
stays open too; its /100 minor-unit handling is a separate problem.
Adds the spec that was missing: DJF must not reach a birr rail.
The portal's type-check script was `tsc --noEmit`, run against a
tsconfig.json whose "files" is [] and which only carries project
references. tsc checks zero files and exits 0, so
`pnpm turbo type-check --filter=@edr/freight-portal` has been reporting
success without compiling anything.
Switched to `tsc -b`, which the backoffice already uses and which follows
the references. The portal is clean under it.
Every currency picker decided for itself which currencies existed, from a
hardcoded pair, so an administrator's setting and the form could disagree
and the customer would only find out on submit. They now read
GET /exchange-settings/currencies.
CurrencySelector's allowUsd boolean becomes an allowed list. The caller is
choosing on two independent axes — trade direction (export and intercity
invoice in ETB whatever is picked) and what is switched on — so a second
boolean would have needed a third one next time.
Adds the DJF card and option with its own hint, the DJF tab on the finance
hub and the DJF row on the manual-payment settings card, both driven by
the per-currency flag rather than an if/else on two currencies. The
exchange-rate settings card gets the toggle itself, with the wording that
turning it off stops new choices rather than changing bookings already
priced in DJF.
The inline "ETB" | "USD" unions on the invoice filter and the customer
shipment and payment types are widened, so a DJF invoice is not mistyped
on arrival.
formatMoney needs no change — it already defaults to 0 fraction digits,
which is correct for DJF.
Two more hardcoded ETB/USD option lists, one on the shared revenue-report
filter and one on the contracts export dataset. A report that cannot be
filtered to a currency never shows that currency's revenue, which reads as
an empty result rather than an error. currencyOf() still defaults to ETB
when the caller picks nothing.
The only currency rule anywhere was CBE_BILL's, spelled out twice — once
inside initiateCbeBill and again in the freight API before it calls the
payment service. Two copies of one provider's rule, and no check at all
for the other seven. initiate-payment.dto accepted any 3-to-8 character
string as a currency.
Both copies now read PROVIDER_CURRENCIES, and the check sits once in
initiate() before any provider opens a session, so it covers all of them.
The DTO gets the whitelist it never had.
Amount precision follows the same rule. eBirr and D-Money formatted at a
fixed 2dp regardless of currency; D-Money would have sent "71088.00" for
a DJF order, and DJF has no centimes to send. Both now format at the
currency's own precision. CAC Bank already did this and documents it.
Waafi is deliberately left alone: its toAmount() truncates rather than
rounds, the comment says that is intentional, and changing it would alter
an existing money path for a reason unrelated to DJF. Same for the
amountMinor major/minor unit disagreement in cbe-birr and card — real,
pre-existing, and unreachable from DJF since both are ETB rails.
Seven selects in overview.repository sum payments with a literal currency
filter, one column for ETB and one for USD:
COALESCE(SUM(payment.amount) FILTER (WHERE payment.currency = 'USD'), 0)
Anything else is summed nowhere. A DJF payment would not appear as a
separate figure — it would simply be absent from revenue MTD, the payment
trend, the per-method breakdown and the direction and freight-type splits,
with no error and nothing to notice.
Adds the third column at each site, the matching response fields, and the
tiles and stacked bar that render them. The payment chart's tooltip now
derives the label from the series key instead of a ternary on
"amountUsd", so it does not need touching again.
ponytail: a third hardcoded currency is still the shorter diff. A fourth
should force these seven into a GROUP BY payment.currency returning
IOverviewCurrencyAmount[] — the shape getRevenueByCurrency already uses a
few lines below.
Note the ordering dependency: the DJF enum label must exist before these
run. payments.currency is enum-typed, so `= 'DJF'` against a database
where the migration has not been applied is a runtime error, not an empty
result. All three query shapes were EXPLAIN-checked against the dev
database.
Pricing carried one number, usdToEtb, gated on a boolean:
const isEtbBooking = paymentCurrency === 'ETB';
const usdToEtb = isEtbBooking ? await getRate('USD', 'ETB') : 1;
Four entry points repeated it, and every conversion was a ternary on that
boolean. A third currency has nowhere to go in that shape.
Replaced with a USD-to-x rate map resolved once per pass, and a small
moneyIn() helper returning the two conversions the line builders actually
use. A USD booking stays the identity case and is left unrounded exactly
as before — rounding it now would shift totals on bookings this change is
not meant to touch. Everything else rounds to its own currency's
precision, which is what makes DJF come out in whole francs.
frozenRateByCode took the same scalar and hardcoded USD to ETB and ETB to
USD, returning null for any other pair — which would have silently dropped
an agreed contract price on a DJF booking and re-priced it at live rates,
the exact bug the USD/ETB conversion was added to fix. It now crosses the
two USD legs, so any pair converts, and keeps the guard that returns null
on a missing or 0/NaN rate rather than zeroing a line.
booking-wagon-cancellation collapsed anything that was not ETB to USD:
const target = booking.paymentCurrency === 'ETB' ? 'ETB' : 'USD';
That billed a DJF booking's cancellation fee in dollars. It now uses the
booking's own currency, narrowed against the shared list.
warehouse-fee's normalizeCurrency did the same collapse, and rounded
conversions to 2dp regardless of target. Invoice totals and the gateway
amount round by currency too — a fractional franc is malformed, not
precise. round2 is left alone everywhere it already serves ETB and USD.
Adds DJF to the currencies a booking or shipment can be billed in, off by
default: going live with it is Finance's call, not a deploy's.
Schema. Every currency column in freight is already a varchar that fits
'DJF' except payments.currency, the schema's one enum-typed currency
column, which would reject the value outright — so the migration adds the
enum label. PG 12+ allows ADD VALUE inside a transaction (migrations run
with transaction mode 'each') as long as the new label is not used in the
same one, and nothing here inserts it. down() drops only the flags:
Postgres cannot remove an enum label, and trying would orphan any row
already written with it.
Two flags, because they answer different questions. exchange_settings
.djf_enabled gates whether DJF is offered at all and starts off.
manual_payment_settings.djf_enabled gates bank-transfer settlement and
starts on — a DJF invoice has to be settleable the day the first one is
raised, which is exactly why USD has always started on.
Enforcement. class-validator cannot see a database flag, so the static
whitelists admit DJF and ExchangeSettingsService.assertCurrencyAllowed()
decides whether it is live. It is called where a currency is chosen —
booking create and update, and shipment creation under a contract — not
where one is read. Only the requested currency is checked, never the
resolved one, so switching DJF off stops new choices instead of bricking
shipment creation on contracts already written in it. Contract creation
needs no check: contracts are always quoted in USD and ignore a
client-supplied currency.
resolveShipmentCurrency stays pure and synchronous; a checked async
wrapper sits beside it, resolved before the insert callbacks (which are
sync, and re-run on a reference collision) rather than inside them.
GET /exchange-settings/currencies is readable by customers as well as
staff, so the portal's picker can offer exactly what the API will accept
instead of a hardcoded pair that fails on submit. PATCH now leaves an
omitted field alone, so flipping the toggle does not re-stamp the fallback
rate as MANUAL as a side effect.
CbeExchangeProvider fetched the CBE daily-exchange-rates payload, read the
USD entry out of it and threw the other seventeen away — getBaseRate()
returned null for anything but USD to ETB. The feed already publishes DJF
in that same payload (0.9203 ETB per DJF today), so serving more than one
pair costs no extra request.
The provider now parses the whole record into a code to ETB map and caches
that, keyed by ISO code. Entries CBE publishes as 0 or null are skipped
rather than stored — a zero rate would silently zero an invoice line.
ExchangeService gains a fourth resolution step. DJF to USD is neither a
direct pair nor an inverse of one, because the provider only ever quotes
against ETB, so the two ETB legs are crossed instead of the pair being
declared unavailable.
Fallbacks stay a single stored number. DJF is hard-pegged to USD at
177.721, so the offline legs derive from the stored USD rate through the
peg — that reproduces CBE's own DJF quote to four decimals, and a second
persisted rate would only be a second thing that can go stale.
getRatesFromUsd() resolves a whole pricing pass's conversions up front so
line builders do not await inside a loop. Because it asks for several
codes concurrently, a cold cache would have opened one HTTP request per
currency for the same payload; an in-flight promise is now shared.
The spec lives in freight-api because api-common has no test setup of its
own, and adding one for a single file is not worth the framework.
PAYMENT_CURRENCIES was copy-pasted into six files — four freight DTOs and
two portal zod schemas — with no owner, and @edr/api-common's exchange
service kept a seventh copy of its own as a bare "USD" | "ETB" union. They
had already drifted: the DTOs and the exchange service did not agree on
what the platform could price in, so a form could offer a currency the
rate service had never heard of.
Adds PAYMENT_CURRENCIES (now including DJF), the PaymentCurrency type and
an isPaymentCurrency guard for the free-string currency columns the ORMs
hand back. Every existing list re-exports this one instead of becoming a
seventh copy.
Also carries the two rules that have to travel with the list:
CURRENCY_DECIMALS, because DJF is a zero-decimal currency — an amount with
centimes is not a more precise payment, it is a malformed one, and CAC
Bank rejects it. roundMoney() applies it.
PROVIDER_CURRENCIES, which gateway settles which currency. Only CBE_BILL
carries a restriction the code can evidence (CBE settles ETB, plan D8);
eBirr, Waafi and D-Money each pass input.currency to the provider verbatim
with an explicit comment saying so. The other rows are therefore
permissive on purpose rather than guessed — settlement currency is really
a property of the merchant account, not the provider brand, and tightening
a row on a hunch would break a live flow.
Every customer notice about a train said "your train" or nothing at all —
the customer had no way to tell which departure a dispatch, pay window,
cancellation or reschedule referred to. Only secured() named one, and it
quoted the schedule reference (S-YYYY-NNNNN) rather than the train number
that yards and customs actually use.
Adds trainNumber()/trainTag() beside the existing scheduleLabel(), reusing
the TrainSchedulesRepository already injected, and threads the number
through dispatched, arrived, payNow, payDeadlineApproaching, payNowPartial,
remainderPlaced, expired, displaced, rescheduled, allocatedOtherDay,
removedFromTrain, scheduleCancelled and maintenanceMoved. scheduleLabel now
prefers train_number over the schedule reference. Falls back to the
reference while a number is unassigned, and to the previous wording when
the schedule cannot be loaded — never a UUID.
Several of these fire after the booking has been detached from its
schedule (cancel, remove, expire all clear train_schedule_id before the
notice goes out), so each method takes an optional trailing scheduleId and
those callers pass the schedule the booking was just pulled off. Sync
signatures are preserved with the void-async wrapper secured() already
used, so no call site changes beyond the extra argument.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A481tjLb6zEkLnk4c4wtVR
A GENERAL + customs contract does not let the customer book directly: they
submit a shipment request, and initiateForShipmentRequest opens a BARE booking
from it — "the request itself carries the quantities; the instance carries
none". Between initiation and completeUnderContract the booking legitimately
holds no cargo, so the export reported 0 containers for a customer who had
declared, say, 2 x 20FT. 23 bookings on dev data are in that state.
Adds two columns and one filter reading booking_requests.requested_lines:
- "Requested cargo" — the declared lines as text ("2 x 20FT"), handling the
bulk shape too (tons / item count), not only containers.
- "Requested containers" — the declared box count, with a matching min/max
filter on the list and the export.
Deliberately a separate column rather than a fallback inside the real container
count: a declared 2 x 20FT is a request, not two boxes on a booking, and
merging them would overstate operational totals. The two compose instead —
Containers = 0 AND Requested containers >= 1 is exactly the set awaiting
completion after clearance.
requested_lines is free-form jsonb, so the container array is guarded by
jsonb_typeof before jsonb_array_elements; one malformed row would otherwise
500 the whole list.
Container filters on the booking-requests list:
- "Container type" — bookings carrying that type.
- "Containers" — a count of BOXES (booking_container is one row per line with
a quantity, so this sums quantity rather than counting rows), as an exact
value or a range. It reads the container-type filter when one is set, so the
one control answers both "10 containers in total" and "10 forty-footers".
Export gains a column per container type ("20FT containers", "40FT
containers"), plus the total "Containers" column and the two filters. Container
types are reference rows, not a constant, so `ExportDataset` gains an optional
`dynamicFields` resolver — DB-driven columns appended to the static list and
cached for the process, mirroring the existing `ExportFilterDef.optionsQuery`.
Adding a 45ft container type adds its column with no code change. The type id
is interpolated into raw SQL (ExportField.select has no parameter bag), so the
resolver drops any id that is not a uuid.
Also repoints the export's "Container VGM" column at the per-line sum. It was
projecting bookings.cargo_total_weight_vgm, which the portal wizard leaves at 0
for container freight — the same trap the tonnage fix addressed — so the column
read 0 for every portal-created container booking. Non-zero on dev data goes
from 54 to 170 of 208 container bookings.
The booking-requests list could filter by freight type but not by what is
actually in the booking, and the export's only cargo column showed the
commodity name — blank for every container booking, which stores no
commodity at all.
Adds one resolver, `bookingContentSql`, that answers "what did the customer
say is in this booking" per freight type: the container lines they entered
("2 × 40FT, 1 × 20FT") for container freight, since the wizard asks them for
no description; the commodity they picked from the cargo tree for bulk,
falling back to their free-text description.
List filters:
- "Content" — a single select flattening the cargo tree the same way the
booking wizard presents it (group, then each commodity as "Bulk → Wheat").
Picking a GROUP matches its whole subtree via a recursive walk, so "Bulk"
returns all 44 bulk bookings rather than the 0 that carry the group id
itself. This makes the existing, previously unexposed `cargoTypeId` param
group-aware.
- "Content contains" — a contains-search over the description, the commodity
name and the container types, so container bookings are reachable by "40FT"
even though they carry no words of the customer's own.
Both apply through `applyListFilters`, so the list, its summary tiles and its
facets agree, and both are declared on the bookings export dataset — the
export button already forwards the page's filters verbatim.
Export fields: "Content" (default), plus "Cargo description" as its own
column. The old `cargo` column is unchanged and still selectable, relabelled
"Cargo (commodity)"; it loses only its default tick, so saved presets that
name it keep working.
Every SQL tonnage in the export datasets and report definitions used
`COALESCE(b.bulk_total_weight_tons, b.cargo_total_weight_vgm)`. COALESCE
falls through on NULL, never on 0 — and the portal booking wizard stores
`cargo_total_weight_vgm = 0` for container freight on purpose, because VGM
is captured per container line, not as a booking-level figure. So every
portal-created container booking reported as weighing nothing. The
backoffice wizard does store a booking-level total, so the same table holds
both shapes and the numbers looked erratic rather than uniformly zero.
Extract the resolver the TypeScript side already has three copies of
(bookingCargoTons, cargoTonsAndItems, totalVgmTons) into one SQL helper:
NULLIF both booking-level columns, then fall back to
SUM(booking_container.total_vgm_tons). Applied to the bookings and
train-schedules export datasets, the cargo-summary, contract-utilization and
booking-status-breakdown reports, and the intercity booking list.
On dev data this recovers 116 of 154 zero-weight container bookings and
raises live booking tonnage from 42,973 t to 61,424 t.
Adds a free-form `types` CSV filter to the invoice list DTO and query
(same treatment as `paymentMethods` — each billing source mints its own
type string, so an IsIn would drop real values), carries it into the
invoices export dataset, and surfaces a Type column plus filter pill on
both the Invoices and Manual Payments tables.
The booking's freight invoice is looked up through the existing invoice
list endpoint (source=booking, sourceId matched by search), newest first
so a re-issue supersedes the old number.
- Added a reason field to train history entries for detach/maintenance actions.
- Updated TrainHistoryPanel to display the reason for wagon detachments.
- Introduced per-wagon load/unload functionality in ScheduleWorkspacePanel with a modal for managing individual wagons.
- Implemented API endpoints for loading and unloading specific wagons, including the ability to cancel remaining wagons with a reason.
- Refactored detach request handling in TrainBuilderDetailPage to streamline the process and remove the approval flow, requiring a reason for detachments.
- Updated types and services to support new wagon loading/unloading features and booking wagon retrieval.
The detail page showed the company's business contact details but not the
credentials anyone actually signs in with, and the two drift apart
routinely — so "the customer says they can't log in" was unanswerable
from this screen.
Adds `GET /backoffice/customers/:companyId/accounts`, joining each
external profile to its IAM account, primary contact first. Deliberately
not filtered to active accounts: a suspended or never-activated login is
exactly the case being looked into. The user query selects columns
explicitly — the entity's relations include credentials and sessions, and
this response reaches a browser.
Rendered as cards rather than a table: it is a handful of rows of
mostly-optional fields, which a table renders as a field of dashes.
"Password never set" is called out on its own, being the usual answer to
"they never got in", and a profile whose IAM user is gone reads as a red
fault rather than an inactive status.
Staff search with whatever is in front of them. Company name, TIN, email
and profile reference already matched; a TIN's licence number and the
trade name of the business a role operates as did not, which is most of
what appears on a customer's own paperwork.
Adds a Role filter alongside it. Distinct from the existing Type pill:
that is the company's own kind, this asks "who does X?" — one `customer`
company routinely holds importer and exporter at once.
Both are EXISTS subqueries rather than constraints on the joined
`companyProfiles` alias. Filtering the join would drop the company's
other profiles from the loaded entity, so an importer-and-exporter would
render as importer-only.
The reviewer approving a role had no way to see which business it claims
to operate as, so there was nothing to check the uploaded licence
document against. The Role profiles table now carries a column with the
trade name, the licensed activity (does it actually cover this role?),
the licence number (the only unambiguous handle — trade names repeat
across a TIN's licences) and the renewal date.
A role with nothing attached reads as a yellow "Not attached" rather than
a blank: it is a review finding. Yellow, not red, because a co-operative
or investment-licence company legitimately has none.
Two fixes alongside it:
- The profile reference was already rendered but is minted only on
approval, so every pending role drew an empty line. It now says so.
- `TableCard` gained an optional header section, so padding sits per
section and the table runs edge to edge. The header stays outside the
scroll region — inside, a title slides away from its own table.
An invoice is billed to one company profile, and that profile's eTrade
licence is usually a different business from the one the company
registered under — so the buyer's name alone does not say which business
was billed.
Both document paths gain a row: the shared invoice/receipt model reads it
off the already-loaded `companyProfile` relation, and the warehouse fee
invoice joins `company_profiles` through the booking.
`sameCompanyName` suppresses the row when it merely repeats the buyer
name, which is the common case. It compares loosely because eTrade spells
one legal suffix three ways (PLC / P L C / PRIVATE LIMITED COMPANY) and
pads names with double spaces; it decides whether a row is worth printing
and nothing else.
The EIMS buyer `LegalName` is deliberately untouched — a MoR filing
carries the registered entity, same rule as the seller side.
A TIN holds many business licences split by activity — export of coffee,
freight forwarding, import of vehicles — but the company picked one for
its whole record, so every operational role shared it. Each profile now
names the business it actually operates as.
Stored on `company_profiles.etrade_business` as a snapshot (licence
number, trade name, activity, renewal) rather than a bare licence number,
so the portal and backoffice can show it without an eTrade round-trip —
that API is slow, serves a broken TLS chain and is regularly down. Not
unique: one business may legitimately back several roles.
The licence number is a client input, so it is never stored as sent —
`ETradeService.findBusinessOption` looks it up under the company's own
TIN and persists eTrade's record, which makes another company's licence
simply unfindable.
Choosing one is required wherever the customer adds a role with a TIN
already on file. The onboarding wizard is the exception by necessity: it
picks roles on its first step, before a TIN exists, so there is nothing
to choose from yet. There it is enforced through
`getOnboardingRequirements` instead — an unattached role is reported
outstanding and blocks submission — and the picker sits on the documents
step beside that role's licence upload.
Lifted entirely for a co-operative or investment-licence company: eTrade
holds no record for its TIN, so the requirement would be unsatisfiable.
A TIN routinely trades under a name that is not its registered one, and
holds several licences with different trade names — of 58 TINs checked
against eTrade, 8 had at least one licence whose trade name differs from
the registered `BusinessName`, one of them across three licences.
`extractRegistrationData` now resolves `companyName` from the selected
licence's `TradeName`, falling back to `BusinessName` (16 of 309 licences
carry a blank trade name, so the fallback is load-bearing).
EIMS is pinned back to `BusinessName` for the seller's `LegalName`: an
invoice is a MoR tax filing and must carry the legal entity, not the
trade name. It is the only other caller.