Billing domain decisions
This page records the ratified design decisions for the Billing domain. Read it before you design anything in this domain.
Each decision states what we decided, why, and where the evidence is. Decisions live only on this page. Other docs must link here instead of repeating the text. When a decision changes, update this page the same day.
Schema truth is jodapp-api/docs/db/billing.dbml. Verify columns there before you rely on this page.
D1 — Agreement ends_at is inclusive of the entered day (2026-07-15)
When an admin enters "effective to 4 July", the agreement covers all of 4 July. Invoices can still be issued on 4 July itself. Confirmed by ops (Ali, 2026-07-15) — see jodapp-api#1850.
How it is stored: the server anchors the entered day in the company's timezone, then stores the last moment of that day (parse_civil_date(...).end_of_day) in ends_at. Because the stored value already carries the inclusivity, read-side checks are plain instant comparisons — no timezone math when reading. The general anchoring mechanism lives in the datetime conventions.
Column names: renamed from effective_from / effective_to on 2026-08-04 (jodapp-api#1863).
D2 — All stored-value credits use entitlement lots; placement is not pooled (2026-08-06)
What we decided:
- Placement credits and gig credits use one lot mechanism (
billing_entitlement_lots). Every grant creates one lot. The lot carries units, the money attached to those units, and an optional expiry date. - The placement row in
billing_entitlementsbecomesallocation_policy: :lots(value renamed fromfifo_lots) andrecognition_policy: :lot_based. Thepooledandproportional_avgvalues are removed from the enums. The two policy columns stay — a future workforce instrument recognises revenue by time, not by consumed units, so it will need a new policy value, not lots. - Spend order: earliest
expires_atfirst (lots with no expiry last), then earliestpurchased_at, thenid. Gig lots have no expiry, so for gig this is plain first-in-first-out. - Credit expiry: when a lot passes
expires_at, anexpireledger entry removes the leftover available units. The lot's remaining money becomes revenue at that moment ("breakage"). We recognise breakage at the expiry date, not gradually by estimate, because we have no usage history to estimate with. Auditor confirmation is queued and must arrive before the first Xero export — see Xero Integration. - Free trial credits are lots with zero attached money and no invoice behind them. Consuming or expiring them recognises zero revenue.
- Reserved units never expire. Units released back into an expired lot expire immediately, in the same transaction.
- Gig lots keep
expires_atempty. Expiring refundable stored value is a legal question, not a schema default.
Why:
- Credit expiry is a confirmed product requirement (Ali, 2026-08-06): push employers to use their credits instead of refunding them or letting them sit idle. Expiry needs purchase batches — a single pool cannot say which credits die on which date.
- Free trial credits break pooled averaging even without expiry: zero-dollar credits inside a paid pool distort every later recognition.
- One mechanism for both instruments means one tested code path, and gig needs lots for per-purchase fee rates in the next phase anyway.
- We lose nothing that finance may still ask for: the pooled-average numbers can be recomputed exactly by replaying the ledger in per-account
idorder. The reverse is not true — pooled-only storage cannot recover lot-level answers.
Timing rule: the placement seed must be flipped before the first grant ledger entry ships. Policies cannot change once ledger history exists for an instrument. No grant entries exist in production today.
Evidence: adversarial architect review in the design session of 2026-08-06. This supersedes the pooled-placement specs in docs PR #84. The schema changes (expires_at, expire entry type, generalised lot money columns) ship with the entitlement engine work on branch billing-phase-3-placement-uses-entitlement-lots; until then billing.dbml still shows the old gig-only lot shape. Older pages in this domain that still say "placement is pooled" are being updated as part of that same work and must link here instead of repeating the rule.
D3 — Credit expiry mechanics: product validity, nightly cleanup, warning emails (2026-08-06)
D2 decided that credits expire and that breakage is recognised at the expiry date. This entry decides how expiry runs day to day.
What we decided:
- Products state how long their credits live. New column
billing_products.validity_months. NULL = never expires. At grant time the system adds the months to the purchase date in the company's timezone, then stores the end of that day as the lot'sexpires_at— the same civil-date convention as D1. We chose months over days because the customer promise is "valid 12 months". Month math lands on the same date every year. Day counts drift across leap years. Trial and goodwill lots do not use a product — the admin setsexpires_aton theCreditActiondirectly. - The spending code is the enforcement. On every reserve and consume, it refuses lots whose
expires_athas passed. The cleanup job is only bookkeeping. A late or broken job can never let dead credits be spent. - A nightly cleanup job closes expired lots. It runs shortly after midnight in the company's timezone (Singapore today). For each expired lot with leftover available units, in its own transaction: write one
expireledger entry, remove the units, recognise the lot's remaining attached money as revenue (breakage, per D2). One lot per transaction, so one bad row cannot block other companies. Safe to re-run: a closed lot has no available units left, and the entry carries an idempotency key. - Warning emails at 30, 7, 3, and 1 day(s) before expiry. Each night the sender computes the days left for every lot that still has credits and an expiry date. That number falls into exactly one window: 8–30 → the 30-day email, 4–7 → 7, 2–3 → 3, 0–1 → 1. It sends that window's email unless it was already sent. A short-lived lot simply enters at its window — no special cases. Each email states the current unit count, the exact date, and that unused credits are not refunded.
- Recipients today: all
hq_managermembers of the company. Temporary — the org membership roles are not firmed up yet. The addresses actually used are copied onto the notice row, so history stays explainable after the policy changes. - A send log records every warning:
billing_credit_expiry_notices— the lot, the stage (days_before), theexpires_atwarned about, the unit count stated, the recipient addresses, andsent_at. Unique on (lot, stage, warned date). A stage counts as sent only when a row matches the lot's currentexpires_at, so after an admin movesexpires_atlater, every stage counts as unsent and sends again for the new date. No cancel logic. - The sender and the cleanup are separate jobs. A mail outage must not delay breakage. A cleanup bug must not stop warnings.
Why:
- Employers do not log in daily. Expiry without warnings creates the refund fights the feature exists to avoid.
- With enforcement at spend time, job timing is only a bookkeeping question — so nightly is enough.
- A send log beats a send schedule: stored future plans go stale when lots are spent or extended; deriving what is due from the lot each night cannot go stale.
Evidence: design session 2026-08-06 (continuation of the D2 session). Schema: billing_products.validity_months and billing_credit_expiry_notices in jodapp-api/docs/db/billing.dbml, branch billing-phase-3-placement-uses-entitlement-lots.
D4 — Gig refunds are a full exit; outlet closures are transfers, not refunds (2026-08-06)
What we decided:
- No partial refunds. A refund pays back the company's whole remaining principal: every available gig credit, from every lot.
- Preconditions. Reserved units must be zero — scheduled shifts finish or are cancelled first, which releases their reserved credits. The refund process then deallocates all outlet budgets back to the company pool as its first step, so no credits are left labelled for an outlet.
- Ledger shape. One
refundentry for the whole exit, with one allocation row per lot. Each lot gives up all its available units. - The platform fee is not paid back. Per lot, the remaining fee money is recognised as revenue at refund time, using the standard recognition formula. Only the wage value goes back to the customer.
- The bank repayment is not a ledger amount. It is recorded by a commercial-layer refund record — the mirror of
billing_payments, with amount, bank proof, and verification. That record is thesourceof the refund ledger entry. The record itself is still to spec. - Nothing needs closing. After the refund the balance is zero and every lot is settled. There is no "refunded" account status. The company can buy credits again later.
- "The outlet closed, refund those credits" is not a refund. Outlet budgets are a label on company credits, not a separate wallet. The fix is a transfer (
billing_outlet_budget_transfers, typedeallocate) back to the company pool, or to another outlet. No ledger entry, no money movement, no revenue event. - Refunds do not touch GST. GST was charged on the fee only, and the fee is not returned. The principal never carried GST. So a refund needs no credit note and no tax reversal. Queued for auditor confirmation — see the Xero questions list.
Why:
- Business rule (Ali, 2026-08-06): partial refunds are not offered. Credits are used, or fully refunded when the company leaves.
- Full-exit refunds delete the draw-order problem. A partial refund must choose which lots give up units, and each gig lot has its own fee rate — so the choice decides which fee becomes revenue, a timing call someone must own and defend to an auditor. A full exit recognises every lot's remaining fee at once. No ordering, no gaming, no allocator code.
- Simple to tell customers: use your credits, or leave and get the wage value back. The fee is never returned.
Evidence: design session 2026-08-06. The schema already supports this with no changes: billing_entitlements.is_refundable, entry_type: :refund, units_refunded, and billing_entitlement_lot_allocations (committed d9adbcc6). Open work: the commercial refund record model, and the refund rows in the Xero mapping table. Update 2026-08-12: the hold table was removed — see D8 — no hold table: a deliverable's reserved credits are computed from the ledger. The refund rules in this entry are unchanged.
D5 — Spending mechanics: reservations name their lots, a daily amount from the campaign total, direct consume for instant delivery (2026-08-06)
What we decided:
- Reservations name their lots. Setting credits aside picks the exact lots at that moment, in the spend order (soonest expiry first, skipping expired lots). The per-lot split of a deliverable's reserved credits is derived from the allocation rows of the ledger entries naming that deliverable as source — it is not stored a second time.
- Why this matters: "reserved units never expire" (D2) must know which units are protected. A stored count alone cannot answer that.
- Every movement writes the same shape: one ledger entry, plus one allocation row per lot touched. A consume from reserved credits takes from the lots the deliverable reserved, soonest-dying first. Release returns units to the same lots they came from. Units returned to a lot that expired in the meantime expire immediately, in the same transaction (D3).
- The replay invariant: every ledger write happens while holding the account's balance row lock. Two movements can never run at the same moment for one account. This is what makes per-account id-order replay valid — the guarantee D2's "finance can still derive pooled numbers" promise stands on.
- A time-spread campaign consumes a daily amount computed from its total. For a campaign of
costcredits overdaysdays: consume today = round(cost × days elapsed ÷ days) − consumed so far. Whole numbers, the total is always exact, a re-run the same day consumes zero, and a missed day is caught up by the next run. - A normal day, run once, on time, can still consume zero. The rounding tracks the running total since the campaign started, not each day on its own. A campaign of 4 credits over 7 days consumes 1 credit on day 1, 0 on day 2, 1 on day 3, 0 on day 4, and so on — every other day looks like a "missed" day even though the job ran correctly each time. Nothing is lost: the shortfall carries forward inside the running total and is picked up automatically on whichever day the total next crosses a whole number, so day 7 always lands on exactly 4 consumed, no matter how the individual days split it.
- Instant delivery consumes directly. Careers posts and boosts deliver the moment they are paid, so they write one consume entry straight from available units. Nothing is ever reserved for them. Two documented spending patterns; each product uses the one that matches its delivery.
- Stuck campaigns are Ads's job, not billing's. A campaign that sits unfinished for 14 days (a config value) is rejected automatically by the Ads system. The rejection triggers a completely normal release. Reserved credits never expire on their own clock (D2). Careers posts reserve nothing; a gig shift has its own date and cannot be parked.
Why:
- Without the Ads timer, an employer can park expiring credits inside a reservation forever and defeat the expiry feature.
- Dividing cost by days strands fractional credits (10 ÷ 3 = 3.33) and breaks on re-runs and missed days. Computing from the total stores the goal, not the steps, so every failure mode is repaired by the same subtraction.
- Forcing Careers posts through reserve-then-consume writes two rows to tell a one-row story — and Careers is where the paying customers are today.
Evidence: design session 2026-08-06. No schema changes; two clarifying notes added to billing.dbml (reserved credits, entry_type: :consume). Follow-up work: the Ads campaign spec must state the 14-day auto-reject; the Careers direct-consume use case ships with the spec rewrite. Update 2026-08-12: the hold table was removed — see D8 — no hold table: a deliverable's reserved credits are computed from the ledger. The derivation rule in this entry is unchanged.
D6 — Opening balances: placement launches at zero; the gig flip carries the real balances (2026-08-07)
Background fact this decision rests on: there is no old placement system. jodapp is the new system. Until billing ships, business invoices job postings by hand (for example $99 per posting) and those invoices live in Xero only. The only real old system with credit balances is jodgig, and its migration is the Phase 4 gig flip.
What we decided for the placement launch:
- Everyone starts at zero credits. No migration, no opening lots.
- No history backfill of the manual careers invoices. Writing them into the ledger either attaches their money (which counts revenue twice — Xero already recognised it) or attaches $0 (which records that the postings were free — not true). Both are wrong stories. The ledger's first row for a company is the first event billing was actually responsible for. Everything earlier belongs to Xero.
- Companies with unused prepaid postings are handled manually, outside billing. They are few, and representing them as credits needs the pricing plan, which does not exist yet.
- Running free ad campaigns: pause and drain. Some days before launch, business stops accepting new free campaigns. Running ones finish naturally. Launch day has nothing in flight, so no migration code exists for it.
- New
action_type: :opening_grantonbilling_credit_actions— the balance a company carries in on the day an instrument goes live. At most one per company per instrument, ever. Rare on purpose.
What we decided for the gig flip (agreed in principle 2026-08-07; details to be walked again closer to Phase 4):
- One
opening_grantper company. Units come from the company's jodgig statement of account. Attached money is finance's stated share of the Xero "Deferred income" balance — in practice remaining credits × the company's latest fee rate, the same calculation finance already does monthly. Gig opening lots have no expiry date. - Before anything is written, two totals must be reconciled against Xero: all opening units against "Jod credits", all attached money against "Deferred income". The unexplained remainder (today's SGD 1k–5k drift) is written off by finance as one correcting journal — our per-company numbers become the truth, because each line is provable from a statement and the lump total never was. Per-company amounts are never scaled to force a match.
- Order per company: opening lot → outlet budget allocate transfers → reserve entries for scheduled shifts. Each step is a normal operation through the normal services; one transaction per company; idempotency keys so a crashed run resumes safely.
- Cut-off rule: jodgig finishes processing all deductions for worked shifts before statements are pulled. A shift worked after the flip consumes in the new system only. One shift, one system.
- The dry-run report (per company: units, money, source evidence, in-flight reservations) is signed by ops and finance before the live run, regenerated from the real rows after it, and kept. It is the audit evidence for the year-one opening balances the auditor said they will test.
Why:
- The placement launch should be a launch, not a migration. Draining short-lived campaigns by calendar costs nothing; migration tooling for them would be code we use once and keep forever.
- The gig flip is the one chance to turn an unexplainable lump difference into provable per-customer lines. Spreading the difference across customers would put fake cents into statements a customer can dispute.
Evidence: design session 2026-08-07, including the auditor's written audit requirements (see the audit schedules section in Xero Integration). Schema: opening_grant added to billing_credit_actions.action_type in billing.dbml. Update 2026-08-12: opening_grant was removed from billing_credit_actions. Everything this entry decided about opening balances still holds. Only the record that stores them is undecided again, and it is designed in Phase 4 — see D9.
D7 — Allocation rows are the complete history of a lot (2026-08-10)
What we decided:
- Every ledger entry writes one
billing_entitlement_lot_allocationsrow per lot the entry applies to — not only entries that move units:- A
grantwrites one row for the lot it creates. reserve,consume,release,expire, andrefundwrite one row per lot whose units move.- An
adjust— written when aBilling::CreditActionof typeexpiry_extensionruns — writes one row for the lot whoseexpires_atit moves, withunits_allocated = 0.
- A
allocation_typealways equals theentry_typeof the entry the row belongs to. The enum gainsgrant.- A database CHECK enforces the unit rule per type: an
adjustrow carries exactly zero units, and every other row carries at least one.CASE WHEN allocation_type = 'adjust' THEN units_allocated = 0 ELSE units_allocated > 0 END. recognised_revenue_centsis NULL ongrant,reserve,release, andadjustrows. It is set only where revenue is recognised:consume,expire, andrefund.
Why:
- A grant entry and its lot have no shared key without the allocation row. The entry's source is the
Billing::InvoicePosting. The lot's source is theBilling::InvoiceLine. An invoice with two principal lines produces two grant entries pointing at one posting, and two lots pointing at two different lines. Only the allocation rows state which entry created which lot. - One source of history. A lot's allocation rows, read in entry order, are everything that ever happened to it — the grant that created it, every spend, every
expires_atchange, and the entry that emptied it. Without the zero-unit adjust row,billing_credit_actionsbecomes a second source that every lot-history query has to union in. - One write path. Every ledger write is one entry plus its allocation rows, in one transaction. No branch per entry type, in the writer or in any reader. Every lot counter is replayable from allocation rows alone — the same way the balance projection is replayable from ledger entries (D5).
Evidence: design discussion of 2026-08-10 (allocation-spec session). Schema: billing_entitlement_lot_allocations in jodapp-api/docs/db/billing.dbml, branch billing-phase-3-placement-uses-entitlement-lots.
D8 — No hold table: a deliverable's reserved credits are computed from the ledger (2026-08-12)
What we decided:
- The
billing_entitlement_holdstable is removed from the design. No hold rows are stored. - The word hold is retired with the table. The concept's name is a deliverable's reserved credits: the credits currently set aside for one deliverable — here an ad campaign or a gig shift, the two deliverables that reserve. They are the net of the
Billing::LedgerEntryrows that name that deliverable as their source: reserves add, consumes and releases subtract. The name matches what the reader can grep in the schema:entry_type: :reserve,reserved_delta,units_reserved. - The per-lot split of a deliverable's reserved credits derives from those entries'
billing_entitlement_lot_allocationsrows, netted per lot. This is D5's rule with new words — the mechanics are unchanged. - A deliverable that still has reserved credits cannot reserve again. This is an application rule inside the reserve flow. The check runs under the account's balance row lock (D5), so two racing reserves cannot both pass. There is no database constraint for it.
- Account-level and batch-level reserved counts stay cached and instant:
billing_entitlement_balances.units_reserved— per account and instrumentbilling_entitlement_lots.units_reserved— per purchase batch
Why:
- The table was a cache from the start. Its original note (phase 1, jodapp-api#1378, 2026-03-31) says: "For convenience for reserved credits ... cache like billing_entitlement_balances." It was designed while placement was pooled — a placement reservation had no lots behind it then, so a summary row was the only handle.
- D2, D5, and D7 removed the need. Every reservation now writes allocation rows, and a deliverable's history is fully readable from the ledger. Every question the hold row answered is now a small indexed query.
- The row was not free. Its held count would change on every nightly consume, could drift, and would need its own repair job.
- The database uniqueness guard it carried was narrow. Races are already impossible — every ledger write holds the balance row lock. The guard only caught the normal reserve flow running twice. Even then the books self-heal: the release at campaign end returns everything still held, and no revenue number is ever touched.
- The daily campaign consume job never needed the row. Its formula needs "consumed so far", which is a sum over the campaign's consume entries — the hold row never stored that, so the job queries the ledger either way.
- Dropping is reversible. A hold row is a pure summary of ledger entries. If ops screens ever need one, a cache table can be added later and backfilled completely from history.
Evidence: design discussion of 2026-08-12 (hold-spec session). Schema: billing_entitlement_holds removed from jodapp-api/docs/db/billing.dbml, branch billing-phase-3-placement-uses-entitlement-lots.
D9 — The gig flip's opening balances are not credit actions (2026-08-12)
What we decided:
opening_grantis removed frombilling_credit_actions.action_type. Three action types remain:trial_grant,goodwill_grant, andexpiry_extension.- The record that carries a company's opening balance into billing is designed in Phase 4, together with the rest of the gig flip. Until then the schema says nothing about opening balances.
billing_credit_actionskeeps one job: the way anIdentities::Adminwrites a ledger entry when no commercial document exists.- Everything D6 decided about opening balances still holds. Only the place the record lives is undecided again.
Why:
opening_grantfailed the table's own test. The table exists for one authorised human decision, about one company, with no document behind it. An opening balance is none of those three. Nobody decides that a company has 4,312 credits — that number is read off a jodgig statement of account. The human act is approving a reconciliation report, not choosing an amount. And there is a document: D6 calls the signed dry-run report the audit evidence for the year-one opening balances.- It needed four things nothing else on the table needs. A money column, because an opening lot carries real deferred revenue while trial and goodwill lots carry SGD 0. A second meaning for
reason, which everywhere else is why the admin acted and here is which statement the number came from. A uniqueness rule of one per company per instrument. And a different approval shape — ops and finance signing one report for all companies, not one admin acting for one company. - D6's real controls cannot live on a per-company row. Reconciling total units against the Xero "Jod credits" balance, reconciling total deferred revenue against "Deferred income", writing off the unexplained remainder, and the ops and finance sign-off are all properties of one migration run.
billing_credit_actionshas no concept of a run, so the controls D6 cares most about had nowhere to live. Adding a money column would have hidden that, not fixed it. - Removing it costs nothing today. Placement launches at zero (D6), so no
opening_grantrow exists and none will before Phase 4. The enum value was dead in the schema. - Removing it is reversible. If the Phase 4 walkthrough concludes that a credit action row is the right home after all, the value and its column come back during a phase that is writing migrations anyway.
- Keeping it had a real cost. A nullable money column, a column note that taught the opposite of D6, a three-shape CHECK, and a stated purpose that was false — all carried for months to serve zero rows. Worse, Phase 4 would likely have designed around the shape because the shape was already there.
Evidence: design discussion of 2026-08-12 (credit action spec session). Schema: opening_grant removed from billing_credit_actions.action_type in jodapp-api/docs/db/billing.dbml, branch billing-phase-3-placement-uses-entitlement-lots. Follow-up work: the Phase 4 gig flip needs records for the migration run and the per-company opening balance, including the two Xero reconciliation totals and the ops and finance sign-off.
D10 — A credit action needs one admin, not two (2026-08-12)
What we decided:
- The
admin_approved_bycolumn is removed frombilling_credit_actions. There is no second-admin approval before a credit action is carried out. admin_created_byandreasonstay required. They are the record of who acted and why.- The control on manual credits is the audit review after the fact, not a gate before the write. The
(billing_account_id, created_at)index exists for exactly that review.
Why:
- The approval was never designed. The column carried the note "the approval policy itself lives in the application, not the schema". No policy was ever written. There is no status column and no approved-at time, so the schema could not tell a decision waiting for approval from one already carried out. A control nobody specified is not a control.
- The row cannot exist before approval anyway. A
billing_credit_actionsrow is written in the same transaction that writes its ledger entry. So the column could only ever record an approval that happened outside billing, before the write. Whether a company needs two people to agree before sales gives away credits is a question for the admin tool, not for this table. - The money at risk is small and it misstates nothing. A
trial_grantand agoodwill_grantboth create a lot with SGD 0 attached. Consuming or expiring those credits recognises no revenue. A wrong free grant costs us the service delivered, not a wrong number in the books. That is a very different risk from a wrong invoice. - The one revenue effect is a timing effect, and it is visible. An
expiry_extensiondelays breakage revenue by moving the date out. It never creates or destroys revenue. Every extension writes anadjustledger entry, so it appears in the statement of account and in the audit review list. - Sales uses
trial_grantoften. It is the type sales reaches for when approaching a potential customer. A second-approver gate on the most frequent action would be worked around, not followed.
Evidence: design discussion of 2026-08-12 (credit action spec session). Schema: admin_approved_by removed from billing_credit_actions in jodapp-api/docs/db/billing.dbml, branch billing-phase-3-placement-uses-entitlement-lots.
D11 — A row on an invoice is a line, not an item (2026-06-12)
What we decided:
- The model is
Billing::InvoiceLineand its table isbilling_invoice_lines. - The name
Billing::InvoiceItemand the tablebilling_invoice_itemsare not used anywhere.
Why:
- "Line" is the industry word for a row on a commercial document. Xero, Stripe and QuickBooks all call it a line. Our engineers read those APIs and their docs every week.
- "Item" sounds like a record that stands on its own. A row on an invoice never does. It exists only as part of its document, and the name should say that.
- Matching Xero's vocabulary removes a translation step. Every time someone maps our data to the accounting system, one fewer word has to be converted in their head.
Evidence: Phase 2 model spec work (Imam Septian, 2026-06-12). The rename shipped in jodapp-api on 2026-06-19, and both the schema and the code use billing_invoice_lines today.
D12 — A running service cannot be cancelled, and released credits get no extra time (2026-08-14)
What we decided:
- A service with a time duration cannot be cancelled once it is delivering. An ad campaign, a job boost, and a Careers job post all run to their end. The credits a delivering campaign reserved always end in a consume.
- Replaced for an admin cancelling an ad campaign by D15 — An admin can cancel a running ad campaign. An employer still cannot cancel a delivering campaign. A job boost and a Careers job post still run to their end.
- A campaign that has not started delivering can still end without consuming. It is rejected by an admin, cancelled while still pending, or auto-rejected by Ads after 14 days (D5 — spending mechanics and the 14-day auto-reject). Each of these ends in a completely normal release.
- A release into an expired lot follows the normal rule, with no softening. The released units expire immediately, in the same transaction (D2 — all stored-value credits use entitlement lots). There is no waiting period for released units, and no automatic extension.
- The rare unfair case is handled by an admin, not by a mechanism.
- Before rejecting: an admin extends the lot through a
Billing::CreditActionof typeexpiry_extension. The nightly cleanup job only closes lots that still have available units, so it can never close a fully reserved lot. The window to extend stays open for as long as the campaign is pending. - After the release: an admin gives a
goodwill_grant— the same remedy as for any lot the cleanup job already closed (D3 — how credit expiry runs day to day).
- Before rejecting: an admin extends the lot through a
- The Ads rejection screen states the consequence. When rejecting a campaign would release units into an expired lot, the screen says so. The admin can extend the lot first, or plan the goodwill grant. This rule ships with the Ads campaign spec.
Why:
- Releasing into a live balance would undo D5's protection. If released units came back spendable after the expiry date, an employer could park expiring credits inside a reservation, cancel it, and reserve again. Dead credits would stay usable forever, and the expiry feature would be defeated by its own reserve flow.
- A waiting period for released units needs a second clock. The lot stores counters, and its states are derived from them. Released units with their own private expiry date would be a new state, and a new job to close them.
- An automatic extension fails the credit action table's own test.
billing_credit_actionsrecords one authorised human decision with a stated reason (D10 — a credit action needs one admin, not two). A system-written extension has no admin and no reason. - The money at risk is small, and the books stay exact. The collision needs a lot to expire inside a pending window that the 14-day auto-reject bounds, and then a rejection. The shortest-lived lots are trial lots, whose credits carry SGD 0 — making the customer whole costs nothing. Every step writes ordinary ledger entries, and breakage keeps its expiry date.
Evidence: design discussion of 2026-08-14 (credit expiry notice spec review). No schema change. Follow-up work: the Ads campaign spec states the no-cancellation rule, the 14-day auto-reject, and the rejection-screen message.
D13 — No Phase-3 grant backfill: Phase 1-3 billing data is reset, not caught up (2026-09-15)
What we decided:
- The Phase-3 grant backfill is dropped. This use case granted entitlements once for any
Billing::InvoicePostingrow created before Phase 3's grant logic existed. Billing has not shipped to production yet, so every such posting today came from manual testing in development or QA, not from a real paying customer. jodapp-apishipsbin/rails billing:reset_phase_1_3_test_datainstead. It clears every Phase 1-3 billing table that only holds test data — legal entities, products, product prices, invoices, invoice lines, payments, invoice postings, ledger entries, credit actions, entitlement lots, entitlement lot allocations, credit expiry notices — and resetsBilling::EntitlementBalanceto zero, so an engineer can start a clean test or demo pass.Billing::Account,Billing::BillToProfile,Billing::Agreement,Billing::AgreementTerm, andBilling::Entitlementare untouched by the reset. A company's billing setup is not test data.- This holds only while nothing is live in production. The day a real paying customer's invoice posts, a reset task must never run against that data, and whether a genuine backfill is still needed becomes a real question again — the same distinction D6 already draws for the placement launch.
Why:
- A backfill task exists to make an already-created real row correct after the fact. Every row it would have touched here came from a manual test, not a real transaction — so removing the row is simpler and safer than repairing it.
- Keeping a backfill task around for data that is never real invites someone to run it later against a database that does hold real rows, without the review this decision had.
Evidence: engineering session 2026-09-14/15. jodapp-api PR #2030, issue #2022. Replaces lib/tasks/billing/backfill_phase_3_grants.rake with lib/tasks/billing/reset_phase_1_3_test_data.rake.
D14 — A credit-validity default lives in the create form, not the database column (2026-09-07)
What we decided:
billing_products.validity_monthscarries nodefault:in its migration, and never will. The system must keep acceptingnilfor any product, including future placement products.nilmeans the credits never expire (D3 — how credit expiry runs day to day).- The Team Portal create form pre-fills
12months for a new product, as a convenience for placement credits. The admin can still clear the field before submitting. The product is then created withvalidity_months: nil. - A default belongs in the layer a person can see and change, not in the schema. The form is that layer. Nobody reads a migration before creating a product.
- A future seed script sets
validity_months: 12explicitly, the same way the form does. No such script exists yet. When one is written to create placement credit products, it must not depend on a default that is not there.
Why:
- A database default is invisible and permanent. An admin filling in the create form cannot see it. A future product could silently inherit that default, even one that should never expire. Nobody can clear a value they cannot see.
- The form default is visible and reversible. The admin sees
12already filled in, decides whether it is right for this product, and can clear it in the same click that would have cleared any other field. - Twelve months is a fact about placement credits today, not a fact about the column. The customer promise is "valid 12 months" (D3) for the placement product line specifically. A future product sets its own value — a shorter promo pack might need six months, not twelve. A schema default would hide that this number is a per-product decision, not a system constant.
D15 — An admin can cancel a running ad campaign (2026-09-29)
What we decided:
- An admin can cancel an
Ads::Campaignthat is already delivering. "Delivering" means at least one of itsAds::CampaignPlacementrows hasstatus: :active. This replaces the first bullet of D12 — A running service cannot be cancelled, and released credits get no extra time for an admin cancelling an ad campaign. - The cancel releases only the credits that are still reserved.
Billing::EntitlementLotService.releasereturns each placement's reserved units to the lots they came from. The units the placement already consumed stay as recognised revenue. - The system does not refund the days that already ran. If Finance wants to make the company whole for those days, an admin gives a
Billing::CreditActionof typegoodwill_grant. A:refundledger entry is for gig only (D4 — Gig refunds are a full exit; outlet closures are transfers, not refunds). - The admin must write a reason when the campaign has an
activeplacement. The system saves every admin cancel as anAds::CampaignReviewrow withaction: :cancelled.notesholds the reason.notesis empty when the campaign has onlypendingorscheduledplacements. - A company cannot cancel a delivering campaign. The company contacts Jod. The employer cancel rule from D12 does not change.
- A job boost and a Careers job post do not change. D12 still applies to them.
What an admin cancel does, by placement:
Placement status | What the cancel does | Credits |
|---|---|---|
pending, scheduled | Sets status: :cancelled | Releases all reserved units |
active | Sets status: :cancelled. Reason needed | Releases the reserved units. Consumed units stay as revenue |
completed | Leaves the placement as it is | None |
cancelled, rejected | Leaves the placement as it is | None |
An admin cannot cancel a campaign when every placement is already completed, cancelled, or rejected. There is nothing left to cancel.
Why:
- An inappropriate ad must be able to stop. At the 2026-09-22 Finance/Ops demo call, the case was an ad that runs for 2 days, and then an admin finds it is not appropriate. Waiting for the campaign to end is not acceptable. The call asked for the credits not yet consumed to go back to the company.
- The reason for D12 still holds. D12 blocks a cancel so an employer cannot park expiring credits in a reservation, cancel it, and reserve again. Only an admin can cancel a delivering campaign, so an employer cannot repeat that cycle.
- A release into an expired lot follows the D12 rule. The released units expire at once, in the same transaction. The campaign detail response carries
would_release_expire_creditsfor both cancel and reject, so the Team Portal can tell the admin before they confirm. - Consumed credits are not given back by a mechanism. Making a company whole for the days that ran is one human decision with a stated reason. That is the
Billing::CreditActiontable's purpose (D10 — A credit action needs one admin, not two).
Evidence: the Finance/Ops demo call of 2026-09-22, and the decisions confirmed on 2026-09-29 in jodapp-api#2089. Code: jodapp-api PR #2100. No migration: ads_campaign_reviews.action is a string column, and its note in jodapp-api/docs/db/ads.dbml lists the new cancelled value.
D16 — A company spends only its own billing account, never its parent's (2026-10-12)
What we decided:
- Every
Org::Companyowns oneAccountand spends only that account.- "Own account" means the
Accountwhosebilling_accounts.org_company_idis the company. - Reserve, the submit credit checks and the employer balance read all use the own account.
- This rule is the same for a root company and a child company.
- "Own account" means the
- A child company never spends its parent company's account.
- FairPrice North spends North's account, and FairPrice East spends East's account.
- The parent company's account is spent only by the parent company itself.
- Every company has an account before it spends credits.
- A company created in Jod gets its account in the same transaction as the company.
- The JodGig company sync creates an account for every company it syncs, child companies included.
- A one-time backfill creates the account for each existing company that has none.
- An
Accountbelongs to exactly one company.- Billing code can assume this.
- The column
billing_accounts.org_company_idgets a unique index (jodapp-api#2132).
- Consume and release keep following the reserve ledger entry.
- This is already how
EntitlementLotServiceworks (Billing D5 — Spending mechanics: reservations name their lots, Billing D8 — No hold table: reserved credits are computed from the ledger).
- This is already how
- No credit transfer between accounts in this step.
- Each account is funded only by its own invoices and credit actions.
- A transfer between two accounts is planned for a later phase.
- A group that wants one shared pool of credits is one company.
- Its stores are
Org::Outletrecords of that one company. - It does not use child companies.
- Its stores are
Why:
- Divisions pay for their own credits.
- In JodGig, NTUC FairPrice tops up each division on its own.
- When a child spends its parent's account, one division can use credits another division paid for.
- A child company is an operational unit that runs its own billing.
- Each division handles the billing for its own outlets.
- So the account belongs to the division, not to the group.
- The entitlement engine already works per account.
- Lots, ledger entries, balances, invoices, credit actions and expiry notices all carry
billing_account_id. - Expiry, warning emails and revenue are then correct per division, with no new rule.
- Lots, ledger entries, balances, invoices, credit actions and expiry notices all carry
- One account per company is the simplest rule.
- There is no pointer column, no admin switch and no lock between a switch and a reserve.
- We weighed a pointer
org_companies.billing_account_idthat lets a child choose its own or its parent's account. - We weighed a budget per child inside the parent's account, like
OutletBudget. - A budget does not work for placement credits, because lots expire and a budget cannot tell whose credits expired.
- Now is the cheapest time to change.
- Phase 1-3 billing data is reset before launch (Billing D13 — No Phase-3 grant backfill: Phase 1-3 billing data is reset).
- No real credits sit on a parent's account for a child.
Evidence:
- Slack thread between Ali (CTO) and Imam, 2026-10-12.
- The Org design already gives each division its own account (
Org::Company— Enterprise Divisions). - This decision replaces the rule "a child company spends its parent's account" from jodapp-api#2101.
Billing::Accounts::Shared::ResolveServiceadded that rule in jodapp-api PR #2104.
- Full design: Billing Integration Phase 3.1 — Design Plan.
D17 — A Careers job post buys a job posting, paid by a direct consume (2026-10-15)
What we decided:
- Posting a
Careers::Jobconsumes placement credits from its company's own account.- The consume is direct: it takes available units and reserves nothing.
- Billing D5 — Spending mechanics: instant delivery consumes directly already states this for Careers posts.
- The own account follows Billing D16 — A company spends only its own billing account, never its parent's.
- Each payment buys one
Careers::JobPosting.- A
Careers::JobPostinglets theCareers::Jobbe shown on Careers from itsstarts_atto itsends_at. - The employer picks a price, and each price has a number of days and a credit cost.
- The first prices are 1 month (30 days) for 50 credits and 3 months (90 days) for 100 credits.
- 1 credit = SGD 1.
- The employer can close, hide and open the job again for free during the period.
- Hiding or closing a
Careers::Jobdoes not pause its period. - Example: a
Careers::Jobhidden from 20 Oct to 30 Oct still ends on 13 Nov, not 23 Nov. - The company buys calendar days, not days of being shown, and a
Careers::JobPostingrow never changes.
- A
- When the period ends, the hourly Sidekiq job
Careers::Jobs::CloseJobcloses theCareers::Job.- A
Careers::Jobwith aCareers::JobPostingstays open or hidden only while its latestCareers::JobPosting.ends_atis in the future. Careers::Jobs::CloseJobselects only aCareers::Jobthat has aCareers::JobPosting.
- A
- A renew buys a new period, before or after the period ends.
- A renew of a running
Careers::Jobstarts at its latestCareers::JobPosting.ends_at. - So no paid day is lost.
- A renew of an ended
Careers::Jobstarts now and opens theCareers::Job.
- A renew of a running
- A post and a renew never pay twice for one click.
- The job form sends an idempotency key, and a second request with the same key creates nothing.
- The key is unique per company, by a unique index on
careers_job_postings (org_company_id, idempotency_key). - The renew dialog sends the number of
Careers::JobPostingrows that it showed. - A renew with an old number fails with a 422 and pays nothing.
- The consume recognises the whole cost on the day the company pays.
- Revenue is not spread over the period, unlike an Ads campaign.
- A renew recognises its whole cost on the renew day, also when its period starts later.
- Each
Careers::JobPostingrow is the source of itsconsumeledger entry.- The row copies the price's days and credit cost, so a later price change never changes it.
- The row stores who created it in
created_by_typeandcreated_by_id, and the start and the end of its period. - The row copies
org_company_idfrom itsCareers::Job, so the key of the job form is unique per company. - The row does not store the account that paid, because the
consumeledger entry records it.
- The end of the period of a
Careers::Joblives only oncareers_job_postings.careers_jobsgets no new column.- The latest
Careers::JobPosting.ends_atof aCareers::Jobis the end of its period.
Careers::JobPostingPricenames its credit ininstrument, a string with no foreign key.- The default is
'placement', and Careers passes the value toBilling::SpendValidatorandconsume_now. - So Careers code keeps no
:placementconstant, and no Careers column points into a Billing table.
- The default is
Careers::JobPostingPriceandCareers::JobPostingbelong to the Careers domain.- The new tables are
careers_job_posting_pricesandcareers_job_postings. - Billing D18 — Product domains spend credits only through SpendService set these names on 2026-11-16.
- Careers decides when a
Careers::Jobpays, how much, and when to close it. - Billing only takes the credits.
- The new tables are
- An existing
Careers::Jobkeeps noCareers::JobPostingand no end date.- An existing
Careers::Jobis one created before Billing Phase 3.2 ships. - It has no
careers_job_postingsrow, so no rule of this entry closes it. - Its HQ manager hides it and opens it again any number of times, with no payment.
closedis its end state: after a close, it cannot open, hide or renew again.- It never gets a renew, also while it is
openorhidden. - A renew of a
Careers::Jobwith noCareers::JobPostingfails with a 422. - No task creates a
Careers::JobPostingwhen Billing Phase 3.2 ships. - So every
Careers::JobPostinghas a price and a credit cost above 0. - Ali sets an end date for existing
Careers::Jobrows later.
- An existing
- A
Careers::Jobnever changes company.- This holds for every
Careers::Job, also an existingCareers::Jobwith noCareers::JobPosting. - To hire for another company, the HQ manager posts a new
Careers::Jobfor that company.
- This holds for every
- The ledger text of a Careers row links to a read-only Team Portal page of the
Careers::Job.- The page shows the
Careers::Joband all itsCareers::JobPostingrows. - The ledger links to the deliverable route
/team/careers/job-postings/<id>, which redirects to the page, like an Ads placement. - Team Portal tools to post, renew or close a job for a company are outside this phase.
- The page shows the
- Closing a
Careers::Jobgives no credits back.- Billing D12 — A running service cannot be cancelled still applies to Careers jobs.
- When no price is active, the job form and the renew dialog show "Posting a job is not available right now. Please contact Jod support."
- Sales can deactivate every price, so the list can be empty.
- A seed file creates the first two prices, "1 Month" and "3 Months".
- So a company can post on the day Billing Phase 3.2 ships, before Sales enters any price.
- Sales practises entering and editing prices in QA.
- A Team price response holds
id,name,duration_days,unit_cost,instrumentandis_active.- The employer endpoints name a price by its
uuid.
- The employer endpoints name a price by its
- When credits are too low, the employer chats with us on WhatsApp to top up.
- Only Jod staff can top up credits today, from the Team Portal.
- Every company that the careers trial gate does not block pays credits.
- This includes a company with
careers_access_status: :trial. - The next step replaces the trial period with trial credits, and it reaches production together with this step.
- This includes a company with
- When Billing Phase 3.2 ships, every company that is not blocked gets free placement credits for one
Careers::JobPosting.- The credits pay one
Careers::JobPostingof 1 month, which costs 50 credits. - A company with
careers_access_status: :blockedgets none. - A rake task creates one
Billing::CreditActionwith these credits for each existing company. - A new company gets one
Billing::CreditActionwith the same credits when it signs up. - Each of these
Billing::CreditActionrows names theSystemadmin inadmin_created_by_id. - Its
reasonis "Sign up free credits". - Ali has not ruled on when these credits expire.
- On 2026-11-17, Ali noted that companies synced from JodGig would also get them, and he has not ruled on it.
- The credits pay one
careers_jobs.statushas three values:open,hiddenandclosed.- No code creates a draft
Careers::Job, but an update can setdrafttoday. - Production had no draft row on 2026-11-17.
- So the default of
careers_jobs.statusbecomes'open', and the migration does not check for draft rows. - A person checks by hand that production has no draft row, just before the deploy.
- No code creates a draft
- The Team Portal page addresses name a
Careers::JobPostingPriceby itsid, like the Team endpoints.- The employer endpoints name it by its
uuid, because they are public.
- The employer endpoints name it by its
Why:
- Marketing priced a job post per period.
- Alvin set 50 credits for 1 month and 100 credits for 3 months.
- A payment with no end date would let one payment keep a
Careers::Jobopen for years. - An employer could also edit a job that was paid once into a different job, and never pay again.
- The whole cost is recognised on the day the company pays, to keep this step small.
- Spreading revenue over the period needs a reserve and a daily consume per
Careers::Job, like an Ads campaign. - A renew pays and recognises on the same day, so one rule covers the post and the renew.
- Spreading revenue over the period needs a reserve and a daily consume per
- The columns
created_by_typeandcreated_by_idname who created theCareers::JobPosting.- Most tables in
jodapp-apiname the person who made a row withcreated_by, such asads_campaignsand the Gig tables. - A
Careers::JobPostingis created once and never changes, so "created by" is exact. - The pair is polymorphic, like
ads_campaigns.created_by_typeandcreated_by_id, and has no foreign key. - Ali wants admins to post or renew for a company later, when the company asks.
- So the pair names an
Org::Membershipnow, and anIdentities::Adminin that later phase, with no schema change. - Billing D18 took the word "charge" out of the table name and the model name.
- Most tables in
Careers::JobPostingPricestores itsinstrument, not abilling_entitlement_id.- Ali wants the price to carry its credit, so that Careers code keeps no constant to manage.
- A foreign key to
billing_entitlementswould make a Careers table point into Billing, which Billing D18 does not allow.
Careers::JobPostingdoes not store the paying account.consume_nowfinds the account fromorg_company:, so Careers never reads aBilling::Account.- The
consumeledger entry already records the account, and a second copy could disagree with it. - Since Billing D16, a company spends only its own account, so the company of the
Careers::Jobalways names the account.
- A
Careers::Jobnever changes company.- Otherwise a
Careers::Jobpaid by one company's account could move to another company. - Ali ruled on 2026-11-19 that no
Careers::Jobmoves company. - So the rule has no case for a
Careers::Jobthat has not paid.
- Otherwise a
- The end date lives only on the
Careers::JobPostingrows.- Ali ruled on 2026-11-16 to drop
careers_jobs.listing_ends_at. - One place holds the end, so no copy on
careers_jobscan disagree with it.
- Ali ruled on 2026-11-16 to drop
- A renew before the end extends the period.
- Otherwise the
Careers::Jobwould close between the end and the renew, and applicants would not see it.
- Otherwise the
- A request that pays can arrive twice.
- A double click, a retry after a timeout, or two HQ managers can send the same renew.
- Closing a
Careers::Jobgives no credits back, so Sales would repair each second payment by hand. - A new
Careers::Jobhas no record to compare, so the post needs a key. - A
Careers::Jobhas a known number ofCareers::JobPostingrows, so the count also stops two HQ managers.
- Existing
Careers::Jobrows stay, because they are all the jobs that a candidate can find today.- On 2026-11-17, Careers has 133 open jobs and 1 hidden job, from 72 companies.
- 118 of these 134 jobs are older than 30 days.
- A rule of 30 days from creation closes at least those 118 within an hour of Billing Phase 3.2 shipping.
- Ali does not want a public job search with no open jobs.
- Ali sets the end date later.
- An existing
Careers::Jobgets no freeCareers::JobPosting.- A row with a credit cost of 0 breaks the rule of Billing D18 that no product costs 0 credits.
- A free row also needs a
Careers::JobPostingwith no price, and a second way to create aCareers::JobPosting.
- No task pays for existing
Careers::Jobrows with credits when Billing Phase 3.2 ships.- Some companies paid Sales by invoice months ago.
- Ali would rather not backfill them, unless a backfill is simple and does not affect Billing.
- Until the end date, an existing
Careers::Jobis a free advert.- An employer can edit such a job into a different job and pay nothing.
- This lasts until Ali sets the end date, or until its HQ manager closes it.
- A closed existing
Careers::Jobstays closed, and an existingCareers::Jobnever renews.- A free open after a close would make the close take nothing away.
- A renew would give an existing
Careers::Joba "Job renew" ledger entry with no "Job post" entry before it. - Ali did not want a path that could affect the billing ledger entries.
- An existing
Careers::Jobthen stays fully outside Billing, and a new hire goes through the paid post.
- The key of the job form is unique per company, not across all companies.
- The client makes the key.
- So one company's key must never find or block another company's row.
- Billing makes every other
idempotency_keyon the server. - So a unique index across all rows is safe for those keys.
careers_job_postingshas no company column of its own, so it copiesorg_company_idfromcareers_jobs.- A
Careers::Jobnever changes company, so the copy cannot disagree withcareers_jobs.
- The table
careers_job_postings, notcareers_jobs, is the ledger source.- One
Careers::Jobhas oneCareers::JobPostingper payment, so it can have manyCareers::JobPostingrows. - The table
careers_job_postingsalso keeps the copied cost and the period dates out ofcareers_jobs.
- One
- The tables
careers_job_posting_pricesandcareers_job_postingsbelong to Careers, not to a generic Listings table.- Careers is the only product that sells a job post.
- Gig pays wages and a fee per shift, not a price per job post.
- Careers owns
Careers::Job, so it also owns when and how much a post costs. - A Careers table can have a foreign key to
careers_jobs, which a polymorphic table cannot.
- Careers owns
careers_jobs.status.- So
Careers::Jobs::CloseJoblives in Careers, as Ali asked.
- So
- The trial gate stays in this step.
- Replacing the trial with trial credits is the next step.
- Every Phase 3 step merges into the Phase 3 feature branch, so both steps reach production together.
- Charging trial companies now matches that direction, because trial credits will pay for their jobs.
Evidence:
- Design session of 2026-10-14 (Imam), built on the open questions for Alvin from the weekly sync of 2026-10-06.
- Slack thread of 2026-10-15 (Imam, Ali).
- Ali asked that Careers owns ending a
Careers::Job, and that the price and the period wait for marketing. - Ali asked to backfill existing
Careers::Jobrows so they expire, which his ruling of 2026-11-17 replaced.
- Ali asked that Careers owns ending a
- Design review of 2026-10-15 (Imam) chose Careers tables over generic Listings tables.
- Alvin's answers of 2026-10-15 in #sg-jodboard:
- 50 credits for 1 month and 100 credits for 3 months;
- competitor prices: FastJobs SGD 120 per post per month, JobStreet about SGD 100 to SGD 500 per month;
- Indeed charges per view, per click or per application, and MyCareersFuture is free;
- 50 to 100 trial credits for a new company, for the next step;
- trial credits last 2 weeks or 1 month, and work on Ads too;
- Sales decides what happens to companies in trial or blocked today, which Ali replaced on 2026-11-17;
- block the post and ask the company to contact Sales when credits run out.
- Design session of 2026-10-15 (Imam) after Alvin's answers chose the period rules:
- the whole cost is recognised on the day the company pays;
- the end date is on
Careers::Joband onCareers::JobPosting, which Ali replaced on 2026-11-16; - a renew before the end extends the period;
- existing
Careers::Jobrows that are open get 30 free days, which Ali replaced on 2026-11-17.
- Imam's answers of 2026-11-13 to the open questions on jod-app/docs#158:
- the columns
created_by_typeandcreated_by_id, and nobilling_account_id, the two names that Ali's guide had left open; - a renew recognises its whole cost on the renew day;
- the company of a paid
Careers::Jobcannot change.
- the columns
- Slack thread of 2026-11-13 (Imam, Ali) on the ledger link:
- Ali asked for the most minimal Team Portal page of a Careers job, for the ledger link;
- Ali ruled that Team Portal tools to manage jobs are handled outside this phase.
- Slack thread of 2026-11-16 (Imam, Ali) and jod-app/docs#207:
- Ali ruled the names
Careers::JobPostingandCareers::JobPostingPrice; - Ali ruled to drop
careers_jobs.listing_ends_at.
- Ali ruled the names
- Imam's answers of 2026-11-16, after Ali dropped
listing_ends_at:- the hourly job is
Careers::JobPostings::CloseEndedJob, which Ali renamed on 2026-11-18.
- the hourly job is
- Design session of 2026-11-16 (Ali):
- "we provide free placement credits for all companies to create a new job posting";
- the aim is to bring back companies that signed up and posted no second job;
- "we will remove the columns charlie created for the trial hotfix", and the trial becomes free credits that expire.
- Design session of 2026-11-17 (Ali):
- "old jobs stay until i set an end date later";
- "enough credits for a single job posting which is 50 credits i think (or whatever alvin from marketing provided)";
- on blocked companies, "we should not give them credits";
- on companies that paid by invoice, "i'd rather not have them backfilled (unless it's not complex and does not affect billing)";
- on JodGig, "they would also receive free placement credits", with no ruling.
- Design session of 2026-11-18 (Ali):
- "there's only one release, which is billing phase 3 which will include the careers job posting effort";
- "yes for key for the job posting, and count of job postings for renew";
- "let's remove
draftfromcareers_jobs.statusto make it simple"; - "create Billing::CreditAction for each new company signup with the free credits";
- "existing companies get a billing::Credit action created via a rake task";
- the name of the hourly Sidekiq job, "Careers::Jobs::CloseJob";
- "the /teams endpoints can use :id since that is internal to us";
- employer endpoints keep
uuid, because they are public; - the pages name records by their model:
Careers::JobPosting,Careers::JobPosting.ends_at, and "existing Careers::Job" for an old job.
- Design session of 2026-11-19 (Ali), on the rules listed in jod-app/docs#212:
- "once it's closed, it's closed. it also cannot be renewed (cause im scared it might affect billing ledger entries)";
- "exiting careers::job never gets a renew";
- an existing
Careers::Jobthat is open "can be hidden and opened again any number of times"; - "posted until, posting ended, the renew button is disabled and says "cannot renew"";
- "reading 1.", for no "Posted until" and no "Posting ended" on an existing
Careers::Job; - "yes" to a renew request that carries
job_postings_count, and fails with a 422 for an old count; - "yes" to the create manager looking for the key before the validator;
- "yes, option 2", for
org_company_idoncareers_job_postingsand a unique index on(org_company_id, idempotency_key); - "no, later admins be able to post/renew on behalf of the client if client requests. so why limit it only to org_memberships?";
- "A", to keep the polymorphic
created_by_typeandcreated_by_id, like Ads; - "yes", to no
billing_account_idoncareers_job_postings; - "well, it would be nicer if the model had the instrument saved on it, so i dont have manage constants";
- "yes" to
careers_job_posting_prices.instrumentin place ofbilling_entitlement_id; - "yes", to keep jodapp-web#1552 unchanged;
- "yes keep the long message for an empty price list.";
- "Like Ads, plus instrument", the option Ali picked, for a Team price response with
id,name,duration_days,unit_cost,instrumentandis_active; - "theres no draft jobs in production" and "yes default will be open";
- "we should get a jodapp-web item that removes draft";
- "yes team portal price page names :id in the address, like team api", and keep the hyphen in the address.
- Review of jod-app/docs#212 on 2026-11-19 (Imam, Ali):
- "Yes credit action assigned by system admin", for the free credits;
- "sign up free creditts" as the reason text, which the pages write as "Sign up free credits";
- "Can create seed. Sales can practice filling it Up and editing prices in QA";
- "I think no one will create draft so we can just have a simple manual check before deployment";
- "No jobs cannot move companies", for a company change on any
Careers::Job.
- Imam's decision of 2026-11-19: the free credits are built under jod-app/roadmap#103, together with Phase 3.2.
- Counts from production on 2026-11-17 (Ali):
- 133 open, 1 hidden and 11 closed Careers jobs;
- the 134 open or hidden jobs belong to 72 companies;
- 16 of the 134 were created in the last 30 days.
- Full design: Billing Integration Phase 3.2 — Design Plan.
D18 — Product domains spend credits only through SpendService (2026-10-20)
A product domain sells a service to employers and pays for it from the company's credits.
- The product domains are Careers, Ads, Gig and Workforce.
- The class
Billing::SpendServiceis the public Billing class that product code calls to spend those credits. - The class
Billing::SpendValidatoris the public Billing class that a product validator runs to check a spend before the transaction. - A deliverable is the product record that one payment buys, such as one
Ads::CampaignPlacement. - The reserve entry is the newest
LedgerEntrywithentry_type: :reservefor one deliverable. - The balance row lock is
lock('FOR UPDATE')on thebilling_entitlement_balancesrow of one account and one instrument.
Ali decided this between 2026-10-19 and 2026-11-16, and each row of the table below gives the date of its ruling.
What we decided
| Part | Decision | Ruled |
|---|---|---|
| Who owns prices | Each product domain owns a price list and a deliverable, and Billing owns the money and the credits | 2026-10-19 |
| The Careers records | careers_job_posting_prices and careers_job_postings belong to Careers; a product record and its price list are both named after the thing the company buys | 2026-10-19, the table names on 2026-11-16 |
| The public classes | Product code calls only SpendService and SpendValidator, and never rescues a Billing::Error; Billing never reads a product table or names a product | 2026-10-19, the validator on 2026-10-21, no product rescue on 2026-10-29 |
| The contract | Plain Ruby class methods, each with a sig, and no Sorbet interface! or abstract! module | 2026-10-19 |
| A deal for one company | A cheaper credit pack in money, so a credit price is the same for every company | 2026-10-19 |
| Finance | Finance needs no product split in Xero, and reads the revenue of each day in the Team Portal | 2026-10-19 |
| Workforce | Workforce seats are sold in money, at a price per seat per company, by invoice | 2026-10-19 |
| The order of work | Ads moves onto SpendService first, before Careers | 2026-10-19 |
| The statement of account | An employer downloads a statement of account on demand in the Employer Dashboard | 2026-10-19 |
| The description | reserve and consume_now take description:, and Billing copies it onto billing_ledger_entries.description | 2026-10-19, the argument on 2026-10-20 |
| Later entries | consume_reserved and release copy the description from the reserve entry | 2026-10-20 |
| Where the text lives | A template constant on the deliverable model, such as BILLING_LEDGER_ENTRY_DESCRIPTION, filled with format | 2026-10-20 |
| Billing's own entries | Billing writes the description of the entries it starts itself, such as a :grant from an invoice | 2026-10-20 |
| The pre-check | A product validator runs SpendValidator with the company, the instrument and the units, and merges its errors with errors.merge! | 2026-10-21 |
| The credit error | Billing writes the message under the key <instrument>_credits when the account has too few units | 2026-10-21, the one check on 2026-10-27 |
| No helper | SpendValidator takes values, never a product object, so validates_with is not used | 2026-10-21 |
| The paying account | SpendService and SpendValidator read org_company.billing_account; when it is nil, both raise Errors::InternalServerError, because every company is created with its own account | 2026-10-27 |
| The error class | Billing raises one class of its own, InsufficientCreditsError, under Billing::Error, which inherits Errors::UnprocessableContentError for now | 2026-10-21, the classes on 2026-10-27 |
| The error code | Billing keeps the code and the title of each error it sends in one frozen hash of Data objects, Billing::Error::DEFINITIONS, read with fetch: not_enough_credits and billing_account_missing; never a class name; the web matches a code with a constant in billing-constants.js when it must branch | 2026-10-21, the hash on 2026-10-27, the Data objects on 2026-10-28 |
| The error title | The title of not_enough_credits is Not enough credits, the heading of the error toast when the write under the balance row lock finds too few units | 2026-10-28 |
| A reserved consume | consume_reserved takes target_units_consumed:, the consumed total to reach, and Billing subtracts the units already consumed; a target below the total or above the reserved units raises | 2026-10-20, the name on 2026-10-21, the upper limit on 2026-10-27 |
| Locks | A ledger calculation that decides a write runs after the balance row lock | 2026-10-20 |
| Transactions | The caller opens the transaction, and each write method raises when none is open | 2026-10-20 |
| A direct consume | consume_now writes idempotency_key: "consume_now_<source_type>_<source_id>" | 2026-10-20 |
Building SpendService | A skeleton with the final sigs and bodies that raise Errors::UnimplementedError lives only on feature/backend-billing-interface; then one issue builds each method with its tests, and no product code ever calls a method that only raises | 2026-10-27 |
| Return values | reserve, consume_now, consume_reserved and release return nothing | 2026-10-20 |
| Billing data on a product page | A product endpoint carries no Billing record and no fact that only Billing tables compute, and the page loads them from a Billing endpoint | 2026-10-20 |
| The ledger link | Billing stores no link_type or link_id, and the Team Portal ledger links a deliverable through a web route that loads it and redirects to its page | 2026-10-22 |
| The Ads campaign response | The expire flag moves to GET /team/billing/spends, as units_reserved_in_expired_lots for each placement, which replaces where Billing D15 — An admin can cancel a running ad campaign puts it | 2026-10-20, the endpoint on 2026-10-30 |
| The spend read | A page reads the units of one or more deliverables of one type from GET /team/billing/spends, with one row for each deliverable that has ledger entries: units_reserved, units_consumed and units_reserved_in_expired_lots; every row comes back in one response, with no paging, and the same id twice gives one row | 2026-10-30, no paging on 2026-10-31, the repeated id on 2026-11-02 |
| A failed Billing call | A Billing error stops the product action: a failed write rolls the action back, and a failed read keeps the confirm button of the action disabled | 2026-11-02 |
| One way to pay per deliverable | A deliverable pays through a reserve or through consume_now, never both: reserve refuses a deliverable that has a direct spend, and consume_now refuses a deliverable that has a reserve entry; both check after the balance row lock, and both raise Errors::InternalServerError, because the write was called wrong | 2026-11-02 |
The code of a Billing bug | A Billing Errors::InternalServerError takes a code from Billing::Error::DEFINITIONS only when a program must tell it apart from other bugs; jod-app/roadmap#92 decides the final rule and the naming pattern | 2026-11-10 |
| A second direct spend | consume_now refuses a deliverable that already has a direct spend: it checks after the balance row lock and before the balance check, and raises Errors::InternalServerError; the unique index on billing_ledger_entries.idempotency_key stays as the second guard | 2026-11-10 |
| The units a spend counts | The balance check of reserve, consume_now and SpendValidator counts the units of the lots that are not past expires_at, the same lots that the spend takes from; it does not read billing_entitlement_balances.units_available, which still holds a lot that expired until Billing::ExpireEntitlementLotsJob runs | 2026-11-11 |
| The end of a reserved deliverable | A product ends a reserved deliverable only in the transaction that consumes or releases every unit it still holds: Ads sets a placement to completed in the transaction that consumes its whole cost; a deliverable with no reserve entry cannot end this way, and the rule has no exception | 2026-11-11 |
| A spend of 0 units | No product costs 0 credits: Billing::SpendValidator, reserve and consume_now raise Errors::InternalServerError for units of 0 or less, before any row is read or written; a product validator runs Billing::SpendValidator only when the product has something to pay for, so an Ads campaign with no placement keeps its 422; a free service keeps its price, and the company pays it with free credits that an admin grants with a Billing::CreditAction | 2026-11-11 |
Why
- One public class lets Billing change its lots, ledger and balances with no change in product code.
- Plain Ruby adds no new idea for the team to learn.
- A Sorbet interface module checks the return type only through a
sigon the model, and models carry nosig. - The static check
srb tcdoes not run in CI, so the module would add no check that runs.
- A Sorbet interface module checks the return type only through a
- A
description:argument keeps Billing code out of product models.- The caller knows the context, such as a post or a renew, and the deliverable row does not.
- A missing keyword fails at the call, before Billing writes any row.
- A copied description never changes, so a past line stays the same after a job title edit.
- The constant name says which column the text fills, because no model is called "statement".
- A target total moves the subtraction under the lock.
- Two overlapping runs of the daily job cannot both consume, and a repeated run consumes 0.
- Billing D5 — Spending mechanics says: "Computing from the total stores the goal, not the steps."
- A calculation under the lock cannot race with another write, and the ledger cannot drift from the balance.
- Only the caller knows which writes must succeed or fail together.
- The lock holds only until the transaction ends, so the Billing write needs a transaction.
- The check makes principle 3 of
jodapp-api/app/domains/AGENTS.mdfail loudly in a test, not silently in production.
- A direct consume has no reserve entry, so Billing must look for the earlier direct spend itself.
- The unique key alone answers only when the call reaches the
INSERT, and the balance check comes before it. - With 0 credits left, a second call would stop there, with "not enough credits" for a paid deliverable.
- The unique key alone answers only when the call reaches the
- A method that returns nothing keeps product code off Billing's columns.
- A return value can be added later and break no caller, but removing one can break callers.
- A product endpoint that embeds a Billing record couples two responses.
- The Ads Team campaign page read 3 of the 28 attributes of the
Billing::Accountthat its endpoint embedded. - Billing owns the rule "can this company pay" and the words of its error, so Billing code runs the check.
- A product that reads the balance and applies the rule itself copies Billing's rule, which Fowler calls "ask, don't tell".
- The two Ads submit validators held that copy twice, with a
rescueeach.
- A validator that takes values keeps the dependency one way, product to Billing.
validates_withhands Billing the product object and method names, so Billing would call into a product.- Keyword arguments carry a
sig, and a wrong value fails at the call in product code.
errors.merge!is theActiveModel::Errorsmethod for composing errors, so the rule needs no helper.- An error class is a handle for Ruby code, and
codeis a handle for the web.
- Each one is added when its caller appears.
ApplicationControlleris the Ruby code that catches aBilling::Error, and it renders the error as a 422.- Product code never rescues a
Billing::Error, so a job rescuesStandardErrorand reports it to Sentry as an error. - A class name as the wire
codemakes a Ruby rename break a web constant. Errors::UnprocessableContentErrorstays the parent untilApplicationControllermaps each error class to its status.- Billing interface for product domains — Future end state keeps that design.
- That end state is a temporary ruling of 2026-10-21.
- It waits for one check, that the web reads no field the end state removes.
- Which page shows a deliverable is a web decision.
- So it lives in a web route, not in a ledger column.
- A copied page record goes stale when the product changes how a deliverable belongs to its page.
- A derived link never goes stale.
- The resolution runs once, on the click, instead of once per row on every load of the list.
- Every company has one account, so the association
org_company.billing_accountis the paying account.
- Billing D16 — A company spends only its own billing account gives each company its own account.
- Before, only a company with
org_companies.parent_id IS NULLhad an account. - So
Billing::Accounts::Shared::ResolveServicefound the paying account, and jodapp-api PR #2206 removed it on 2026-11-04.
- A skeleton with the final sigs and bodies that raise
Errors::UnimplementedErrorputs the public shape in review first.
- Then one issue per method builds that method and its tests, and each issue is reviewed on its own.
- The PRs of those issues form a stack, each on the branch of the one before.
- The skeleton lives only on
feature/backend-billing-interface, so product code never calls a method that only raises.
- A spend is the word that Billing already uses for the units a deliverable uses.
- The note on
billing_ledger_entries.source_typesorts the causes of an entry into grants, spends, expiries, refunds and adjustments. SpendServicewrites the entries thatGET /team/billing/spendssums, so the write and the read share one word.- A source is any cause of an entry, such as an invoice posting.
- So the word "source" is too wide for this read.
- One row holds all three numbers of one deliverable.
- A release splits the held units into units that go back and units that expire.
- Two reads, one for each table, would hand the page 98 held units and one
true. - The page could then not work out how many units go back.
- A row for each deliverable lets any page build its own group.
- Examples of a group are a campaign, or the shifts of one job.
- An id with no ledger entries has no row, because a list returns the records that exist.
- The web reads a missing row as 0 for each number.
- Every row comes back in one response, because a request names at most 100 ids.
- A page asks for the deliverables of one record, such as the placements of one campaign.
- With paging, a page that leaves out
page_sizegets 10 rows for 11 ids, and no error. app/domains/AGENTS.md§1 injodapp-apipages every list, so this read is an exception.
- The same id twice gives one row, because the request names a set of deliverables.
- Each row carries
source_id, so a page finds a row by its id, not by its position.
- A Billing error stops the product action.
- Then we can find out whether it is a data bug or a code bug.
- It also stops more bad data from entering Billing.
- A release on top of a data bug writes more rows on the same bad data.
- So when the spends read fails, the Team reject and cancel dialogs open, show the failure, and keep confirm disabled.
- A company buys a posting of a job, so the record is
Careers::JobPostingand its price list isCareers::JobPostingPrice.
- "Posting" is the word that job portals and schema.org use for an advert that runs for a period.
- "Listing" already names the public search row,
Listings::Job. - A later product follows the same pair, such as
Careers::JobBoostwithCareers::JobBoostPrice. - "Post" and "renew" stay the two actions that create a
Careers::JobPosting. Billing::InvoicePostinguses "posting" in the accounting sense, so a page names both models in full.
Options not taken
Each option below was weighed against the design above and lost.
- A deliverable route is a Team Portal web route for one deliverable.
- It loads the deliverable and redirects to the page that shows it.
| Option | How it works | Why it lost |
|---|---|---|
| A service that also validates | The product calls only SpendService, and SpendService checks the balance inside the transaction | The employer sees a form error first, and the credit error only on the next try |
| One spend object that checks and then writes | The validator builds a Billing::Spend object and hands it to the manager | No code in jodapp-api passes an object from a validator to a manager, so the team learns a new pattern |
| No server pre-check | The web blocks the submit from the balance, and the server keeps only the check under the balance row lock | API clients and Team Portal actions get no early check, and each product's form repeats the check |
| A product validator that inherits from a Billing validator | EmployersSubmitValidator < Billing::SpendValidator | A Ruby class has one parent, and the parent ties Ads fields to Billing fields |
| A result object instead of an error | SpendService returns success or failure | A failed write must raise to roll back the caller's transaction, and jodapp-api raises an error for every failed rule |
Billing::NoBillingAccountError | A 422 with a message for a company with no account | Every company is created with its own account, so a missing account is a data bug the HQ manager cannot fix; a Billing::Error is only for a business rule that says no, and a missing account is a broken invariant |
Two hashes, CODES and TITLES | One hash for the codes and one for the titles, keyed by the code | One fact in two places, so a code with no title fails only when that error is first raised |
An OpenStruct for each error | The code and the title on an OpenStruct | A typo such as ttitle returns nil with no error, the values can change at run time, and ostruct leaves the default gems in Ruby 3.5 |
A product job rescues Billing::Error | The daily Ads consume job rescues Billing::Error first and reports it as a warning, then StandardError | No Billing::Error reaches the job, because consume_reserved raises only plain errors; so the rescue never runs, and a later Billing error would reach Sentry as a warning with no review |
| Events that Billing listens to | Ads publishes "campaign submitted", and Billing reserves | Billing cannot write inside the transaction that Ads opens, and jodapp-api uses no callbacks for side effects |
| One class per action | Billing::Spends::ReserveService.execute and three more | Four names to search for instead of one |
The description in billing_ledger_entries.metadata | Billing saves the text inside the existing jsonb column | The database cannot make a jsonb key NOT NULL, and the ledger reads the text on every row |
| A web path as the link | Ads passes link_path: '/team/ads/campaigns/42', and Billing stores it | The API must know web routes, and an old row breaks when a route changes |
| A link record on each ledger entry | Two columns billing_ledger_entries.link_type and link_id, a CHECK that sets both or neither, and a link_record: argument | Billing stores a web decision, and a copied page record goes stale when a deliverable moves to another page |
| The ledger page loader builds the link | The loader loads each placement by its source id, and builds the campaign link | The list pays one call per placement on every load, while a deliverable route pays one call on the click |
| No link | The description names the campaign, and the row is text only | Sales copies the campaign name into the search box, so Sales cannot open the campaign from the ledger |
| Two reads, one for each table | GET /team/billing/ledger-entries/units-by-source for the units, and GET /team/billing/entitlement-lots/expiry-check for one yes-or-no | The yes-or-no covers a whole campaign, which is an Ads idea, and the page cannot show how many units expire |
| A read named after the column | GET /team/billing/source-balances or GET /team/billing/source-summaries | A source is any cause of an entry, including an invoice posting or a credit action, so the name is wider than the read |
| A read named after the product record | GET /team/billing/deliverables | The name promises the product record, with its name and status, and Billing never reads a product table |
| A read named after the reservation | GET /team/billing/reservations | Billing D8 retired this idea as "hold", a consume_now spend has no reservation, and a resubmitted placement has two reserve entries |
| A row of zeros for an id with no ledger entries | The list returns one row for each id sent, in the same order | A list returns the records that exist, and the web already reads a missing row as 0 |
| A paged spend read | The read pages its rows through paginate_and_render, like other lists | A page that leaves out page_size misses rows with no error |
| A 422 for a repeated id | The validator rejects the same id twice | A read writes nothing, so a repeat does no harm, and the 422 only adds a way to fail |
Careers::JobListingPeriod with Careers::JobPrice | The names of 2026-10-20 | "A job price" does not say what the company buys, and "Period" has no match in Careers::JobBoost |
Careers::JobListing, and a new name for Listings::Job | The paid record takes the word "listing", and the public search row becomes Catalogue::Job | The rename touches 3 tables, the API paths and 32 files of jodapp-web, and job portals use "listing" for the public row |
Careers::JobPost | The shorter word | "Post" is also one of the two actions, so a renew would create a job post, and in British English a post is also a job |
| Warn, then allow the action | A failed spends read shows a warning, and the confirm button stays enabled | The action then runs on top of a possible data bug, and a release can write more bad rows |
Evidence
| Fact | Where |
|---|---|
| How the interface works | Billing interface for product domains |
| The daily Ads consume writes with no transaction | jodapp-api#2198 |
ActiveRecord::Base.current_transaction.open? is false inside a Rails test until the code opens a transaction | A probe test on 2026-10-20, activerecord 8.1.3.1 |
| PostgreSQL releases row locks at the end of the transaction | PostgreSQL — Explicit Locking |
"Support a current transaction, throw an exception if none exists" is Spring's MANDATORY | Spring — Propagation |
| The Ads Team campaign page read 3 of 28 embedded attributes | app/routes/team/ads-campaigns/team-ads-campaigns-detail-page.jsx:92-141 in jodapp-web |
| No other non-Billing endpoint carries Billing data | An audit of 168 jodapp-api endpoints on 2026-10-20 |
| The convention for every domain, in the code guides | jodapp-api#2200 |
ActiveModel::Errors#merge! composes the errors of another object | Rails API — ActiveModel::Errors#merge! |
| Reading another object's state to apply its rule is the smell | Fowler — Tell Don't Ask |
validates_with hands the validator the whole record and its options | Rails Guides — Performing Custom Validations |
| The validator shape and the error key come from Imam's design | docs PR #163 |
Identities marks one failure with code: 'invalid_login' on the shared class, and the web matches a constant | app/domains/identities/admin_sessions/create_manager.rb:85-87 in jodapp-api, app/routes/employers/employers-login-page.jsx:38 in jodapp-web |
ResolveService is removed because every company has one account | jodapp-api PR #2206 |
consume_reserved raises only plain errors | SpendService.consume_reserved and EntitlementLotService.consume in jodapp-api PR #2235 |
InsufficientCreditsError is raised only in reserve and consume_now | EntitlementLotService.reserve and EntitlementLotService.consume_now in jodapp-api PR #2237 |