Design Plan: every product spends credits through one public Billing interface
Ads spends credits only through Billing::SpendService and Billing::SpendValidator, and Billing reads no Ads table.
- The rules are in Billing D18 — Product domains spend credits only through SpendService.
- The methods, arguments and errors are on Billing interface for product domains.
- The user stories are on Billing Spend Interface — Overview.
- This page shows the rules, the code and the rollout.
Words used in this doc
| Word | Meaning |
|---|---|
| Deliverable | The product record that one spend pays for, here one Ads::CampaignPlacement. |
| Own account | The Account whose billing_accounts.org_company_id is the company. |
| Pre-check | The credit check of Billing::SpendValidator before the transaction, with no lock, so the employer sees a clear error. |
| The reserve entry | The newest LedgerEntry with entry_type: :reserve for one deliverable. |
| The balance row lock | lock('FOR UPDATE') on the billing_entitlement_balances row of one account and one instrument. |
| Deliverable route | A Team Portal web route that loads one deliverable and redirects to the page that shows it, such as /team/ads/campaign-placements/:id. |
The service EntitlementLotService | Billing::EntitlementLotService, the private class that moves credits between lots and writes ledger entries. |
| Marketing | The one person at Jod who runs Ads campaigns for clients in the Team Portal. |
Rules
The rules below are the ones this work builds in Ads.
- The rules of the interface itself are on Billing interface for product domains.
| Rule | Applies to | Example |
|---|---|---|
Ads code names only Billing::SpendService and Billing::SpendValidator from Billing when it spends | US-1, US-6 | Ads::Campaigns::EmployersSubmitManager calls Billing::SpendService.reserve |
Ads passes the company and the deliverable record, never a Billing::Account, source_type or source_id | US-1 | org_company: org_company, deliverable: campaign_placement |
A write method returns nothing, so Ads never holds a Billing::LedgerEntry | US-1 | Billing::SpendService.reserve returns no ledger entry |
| Billing code never reads a product table | US-2 | Ads::CampaignPlacements::ConsumeReservedCreditsJob lives in Ads and reads ads_campaign_placements |
| Billing code names no product class | US-2, US-6 | Billing::LedgerEntry::SOURCE_TYPES lists only Billing records |
| An Ads endpoint carries no Billing data, and the Team Portal campaign page reads Billing endpoints | US-2 | Ads::Campaigns::TeamShowManager calls no Billing class |
The Ads submit validators run Billing::SpendValidator and merge its errors | US-3 | One 422 holds a requested_starts_at error and a placement_credits error |
Billing::SpendService checks the balance again under the balance row lock and raises Billing::InsufficientCreditsError | US-3 | Of two submits at the same moment, the second one gets the 422 |
Billing writes the credit error message under the key <instrument>_credits | US-3 | placement_credits: You need 50 placement credits, but you only have 40 available. ... |
A credit error from Billing::SpendService reaches the employer through ApplicationController, with no rescue in the product | always | A product with no Billing::SpendValidator still returns a 422 under placement_credits |
Billing takes every code: and title: from Billing::Error::DEFINITIONS, never from a class name | always | Billing::InsufficientCreditsError sends Billing::Error::DEFINITIONS.fetch(:not_enough_credits) |
| A job that spends credits rescues each record, rolls back that record, and reports the error to Sentry | always | Ads::CampaignPlacements::ConsumeReservedCreditsJob rescues StandardError for each placement, and reports the placement id |
reserve takes a description that Ads fills from a template constant on the deliverable model | US-4 | format(Ads::CampaignPlacement::BILLING_LEDGER_ENTRY_DESCRIPTION, ...) gives Ad: Hiring baristas, Homepage banner, Weekly |
consume_reserved and release copy the description from the reserve entry | US-4 | The banner's day-1 consume shows the banner's text |
Billing writes the description of the entries it starts itself, so billing_ledger_entries.description is never empty | US-4 | A :grant from invoice SG-INV-000042 reads Invoice SG-INV-000042: 200 placement credits |
| The Team Portal ledger links each spend to its deliverable route, with the description as the link text | US-5 | The banner's reserve links to /team/ads/campaign-placements/77 |
| The daily consume passes the total that the placement must reach, and Billing subtracts the units already consumed after the lock | always | target_units_consumed: 4 on day 1 of the banner, and a second run that day consumes 0 |
| The daily consume runs each placement in its own transaction | always | One placement that fails does not stop the other placements |
| A search for a boundary break prints nothing | US-6 | The two git grep searches of the boundary search print nothing on a clean branch |
Direction
Ads calls two public Billing classes, and Billing reads no Ads table.
- An HQ manager sees the credit error of a campaign submit in the same response as every other error.
- Sales and Finance see a description on each spend in the Team Portal ledger, linked to its deliverable route.
- Marketing sees the Team Portal campaign page, which loads its Billing data from Billing endpoints.
- No other screen changes.
Worked example: Acme submits an ad campaign
- Acme has 40 placement credits, and its campaign 42 costs 50 credits.
- The first submit fails with one 422 under
placement_credits, and Billing writes nothing. - Sales grants Acme 100 credits, and the HQ manager submits again.
Billing::SpendService.reservereserves 30 credits for the banner and 20 credits for the spotlight.- Each reserve ledger entry has a description, such as
Ad: Hiring baristas, Homepage banner, Weekly.
- Each reserve ledger entry has a description, such as
- The full walk-through is Billing Spend Interface — UC-1: Submit a campaign.
Database
One column goes on the table billing_ledger_entries.
| Column | Type | Meaning |
|---|---|---|
billing_ledger_entries.description | string, NOT NULL, with the CHECK btrim(description) <> '' | The line that the statement of account shows for this movement, copied when Billing writes the entry |
- The product writes the text of a
reserveentry and aconsume_nowentry. consume_reservedandreleasecopy the text from the reserve entry.- Billing writes the text of the entries it starts itself, such as a
:grantand an:expire. - The ledger stores no page record, because a deliverable route in the web finds the page.
- The column note of
billing_ledger_entries.source_typesays that a spend's source is the deliverable that the product passes. - Schema truth stays
jodapp-api/docs/db/billing.dbml.
Backend
The public classes sit on top of the private Billing classes.
| Path | File | What it does |
|---|---|---|
| Public service | app/domains/billing/spend_service.rb | Checks the open transaction, reads org_company.billing_account and the entitlement, and calls EntitlementLotService; raises Errors::InternalServerError when the account is nil |
| Public validator | app/domains/billing/spend_validator.rb | Checks the units available on org_company.billing_account, and raises Errors::InternalServerError when the account is nil |
| Billing errors | app/domains/billing/error.rbapp/domains/billing/insufficient_credits_error.rb | Billing::Error, with Billing::InsufficientCreditsError under it, one class per file |
| Lot logic | app/domains/billing/entitlement_lot_service.rb | Takes the description, subtracts the consumed units after the lock, and raises Billing::InsufficientCreditsError |
| Source list | app/domains/billing/ledger_entry.rb | SOURCE_TYPES lists only Billing records |
| Ads description | app/domains/ads/campaign_placement.rb | Holds the constant BILLING_LEDGER_ENTRY_DESCRIPTION |
| Submit validators | app/domains/ads/campaigns/employers_submit_validator.rbapp/domains/ads/campaigns/team_submit_validator.rb | Run Billing::SpendValidator with the campaign total and merge its errors |
| Submit managers | app/domains/ads/campaigns/employers_submit_manager.rbapp/domains/ads/campaigns/team_submit_manager.rb | Call Billing::SpendService.reserve per placement |
| Cancel and reject | app/domains/ads/campaigns/employers_cancel_manager.rbapp/domains/ads/campaigns/team_cancel_manager.rbapp/domains/ads/campaigns/reject_service.rb | Call Billing::SpendService.release per placement |
| Team Portal campaign show | app/domains/ads/campaigns/team_show_manager.rb | Calls no Billing class, and the page reads Billing endpoints, as jodapp-api#2204 sets out |
| Daily consume | app/domains/ads/campaign_placements/consume_reserved_credits_job.rb | Ads::CampaignPlacements::ConsumeReservedCreditsJob calls Billing::SpendService.consume_reserved, with one transaction per placement |
| Schedule | config/sidekiq_scheduler.yml | Schedules Ads::CampaignPlacements::ConsumeReservedCreditsJob every hour at minute 20 |
| Ledger list | app/domains/billing/ledger_entries/team_index_manager.rb | Joins no product table |
| Ledger serializer | app/domains/billing/ledger_entries/team_base_serializer.rb | Sends description, source_type and source_id, and no Ads field |
| Ledger filter | app/domains/billing/ledger_entries/team_index_validator.rb | Accepts any class name in source_type |
EntitlementLotService keeps reserve, consume, release and expire, and stays private to Billing.
Billing::SpendServiceis a small public class that turns the product arguments into Billing records, then callsEntitlementLotService.- The company becomes the own account, from
org_company.billing_account. - The deliverable becomes the source, from
deliverable.class.nameanddeliverable.id. - The instrument becomes the
Billing::Entitlementrow.
- The company becomes the own account, from
The Billing errors keep Errors::UnprocessableContentError as their parent for now.
Billing::Erroris a subclass ofErrors::UnprocessableContentError, soApplicationControllerrenders each one as a 422.- Each error takes its
code:andtitle:fromBilling::Error::DEFINITIONSwithfetch, such asnot_enough_credits. - The parent becomes
Errors::BaseErrorwhenApplicationControllermaps each error class to its HTTP status.- Billing interface for product domains — Future end state holds that design.
The four code blocks below are copied from the jodapp-api branch 2220-billing-names-no-ads-class, the last branch of this work.
The submit manager reserves each placement with one call.
# app/domains/ads/campaigns/employers_submit_manager.rb:61-74
credit_cost_snapshot = T.must(campaign_placement.credit_cost_snapshot)
::Billing::SpendService.reserve(
org_company: org_company,
instrument: :placement,
units: credit_cost_snapshot,
deliverable: campaign_placement,
description: format(
::Ads::CampaignPlacement::BILLING_LEDGER_ENTRY_DESCRIPTION,
campaign_name: campaign.name,
placement_name: T.must(campaign_placement.placement).name,
price_name: T.must(campaign_placement.placement_price).name
)
)
The deliverable model holds the text as a template constant.
# app/domains/ads/campaign_placement.rb:15
BILLING_LEDGER_ENTRY_DESCRIPTION = 'Ad: %{campaign_name}, %{placement_name}, %{price_name}'.freeze
The submit validator merges the errors of Billing::SpendValidator.
# app/domains/ads/campaigns/employers_submit_validator.rb:62-70
def sufficient_placement_credits
billing_spend_validator = ::Billing::SpendValidator.new(
org_company: campaign.org_company,
instrument: :placement,
units: campaign.total_credit_cost
)
errors.merge!(billing_spend_validator.errors) if billing_spend_validator.invalid?
end
The daily job holds the Ads formula, and passes the total that the placement must reach.
# app/domains/ads/campaign_placements/consume_reserved_credits_job.rb:36-41
::ActiveRecord::Base.transaction do
::Billing::SpendService.consume_reserved(
deliverable: campaign_placement,
target_units_consumed: target_units_consumed(campaign_placement: campaign_placement)
)
end
target_units_consumedisround(credit_cost_snapshot × days_elapsed ÷ duration_days), the Ads daily formula.days_elapsedis the number of full days sincestart_time, plus 1, and never more thanduration_days.
- Billing subtracts the units already consumed after the balance row lock, so the job reads no Billing table.
- The job rescues
StandardErrorfor each placement, and reports it to Sentry with the placement id. - A placement with no reserve entry makes Billing raise a plain error, so the
StandardErrorrescue reports it.
The boundary search has two parts, and both print nothing on a clean branch.
# 1. Product code names no Billing class except the public ones
git grep -n '::Billing::' app/domains/ads app/jobs/ads | grep -vE 'Billing::(SpendService|SpendValidator)'
# 2. Billing code names no product
git grep -nE '(Ads|Careers|Gig|Workforce)::' app/domains/billing app/jobs/billing
- The search reads no Org folder, because Org may call Billing, as Org is not a product domain.
- The search runs at review time, and whether CI runs it too is not decided.
Team Portal
The ledger table on the billing account page links each spend to its deliverable route.
source_type | Link target | Link text |
|---|---|---|
Ads::CampaignPlacement | /team/ads/campaign-placements/:source_id, which redirects to /team/ads/campaigns/:ads_campaign_id | billing_ledger_entries.description |
A Billing source, such as Billing::InvoicePosting | Its Billing page, such as /team/billing/invoices/:id | Its own text, such as Invoice #12 |
- The deliverable route loads the placement from
GET /team/ads/campaign_placements/:id, and redirects to the page of its campaign. - A product with a new deliverable adds one deliverable route in the web, and no Billing code.
- The source type filter has
Ads::CampaignPlacementas one of its options.
The Team Portal campaign page loads its Billing data from Billing endpoints.
- It loads the own account of the company from
GET /team/billing/org-companies/:org_company_id/account. - It loads
units_reserved,units_consumedandunits_reserved_in_expired_lotsfromGET /team/billing/spends, keyed by the placement ids.
Employer Dashboard
No screen changes.
- The web decides "Insufficient Placement Credits" from the balance endpoint, not from the error.
- The error toast prints every key, so the submit error shows as
placement_credits: You need 50 ....
Rejected options
The options that lost, and why, are part of Billing D18 — Product domains spend credits only through SpendService.
Out of scope
- Careers job posts, which call
consume_nowafter this work.- This work builds
consume_nowand its tests in jodapp-api#2216, and no product code calls it yet.
- This work builds
- The
org_outlet:argument for outlet budgets, which Gig adds. - A seat check for Workforce, because how Workforce reads its seats is not designed yet.
- The statement of account that an employer downloads in the Employer Dashboard.
- Separate Xero revenue lines per product, which Finance does not need.
Rollout
All pull requests target the jodapp-api branch feature/backend-billing-interface and the jodapp-web branch feature/frontend-billing-interface.
- These two branches merge into
feature/backend-billing-phase-3andfeature/frontend-billing-phase-3after the manual test plan.
- Add the column
billing_ledger_entries.descriptionand the DBML change. - Add a skeleton of
Billing::SpendService,Billing::SpendValidatorand the Billing errors, with the final sigs.- Each method body raises
Errors::UnimplementedError, and no product code calls it.
- Each method body raises
- Build one method per pull request, with its tests, and move the Ads submit, cancel and reject code onto it.
- Move the daily consume job to Ads, in the same pull request as its schedule change.
- Change the Team Portal ledger list and the web ledger table together.
The Team Portal campaign page moves to Billing endpoints before step 5.
- Step 5 removes
SOURCE_TYPES[:campaign_placement], so the campaign show code must stop naming it first. - The Billing Spend Interface — Implementation Plan lists this work and the other work that came first.
Existing records
- The column
billing_ledger_entries.descriptionisNOT NULL, and no existing row gets a backfill text.- Billing D13 — No Phase-3 grant backfill: Phase 1-3 billing data is reset applies before launch.
bin/rails billing:reset_phase_1_3_test_dataclears the old rows before the column is added.- jodapp-api#2210 says how, because a
NOT NULLcolumn needs an empty table or a default.
- An old Ads entry on staging links to its deliverable route like a new entry.
- The route needs only
billing_ledger_entries.source_typeandsource_id, which every entry has.
- The route needs only
Dry run
This work moves no data, so the check a person reads is the manual test plan and the boundary search.
- Before the merge, the engineer runs the Billing Spend Interface — Manual test plan on a local copy.
- The engineer runs the boundary search after step 5, and lists every line it prints.
- Each line is either fixed, or named in the pull request with its reason.
After release
| What we watch | How often | Who |
|---|---|---|
| Lines the boundary search prints, 0 after step 5 | On every pull request that touches Billing or a product domain | The code reviewer |
Sentry errors from Ads::CampaignPlacements::ConsumeReservedCreditsJob | Daily for one week after step 4 | Imam |
Open questions
| Question | Who answers | Status |
|---|---|---|
| Does the boundary search run in CI, or only in review? | Ali (CTO) | open |
Is Billing::NoBillingAccountError a warning or an error in Sentry? | Ali (CTO) | decided by Ali (CTO) on 2026-10-27: the class does not exist, and a missing account raises Errors::InternalServerError, which Sentry reports as an error |
What text does the migration give each ledger entry that exists before billing_ledger_entries.description, such as Reserve from entry_type? | Imam | closed: Phase 1-3 data is reset, as Billing D13 — No Phase-3 grant backfill: Phase 1-3 billing data is reset says, so the rows are cleared before the column is added and none gets a backfill text |
Should careers_job_prices.billing_entitlement_id become an instrument column, so Careers names no Billing table? | Imam, ruled by Ali (CTO) | decided for the Careers phase: the Careers phase drops the column, and Careers passes instrument: :placement from a constant |
Is Cannot use credits the title: of Billing::InsufficientCreditsError, in place of Cannot reserve credits? | Ali (CTO) | decided by Ali (CTO) on 2026-10-28: the title is Not enough credits, in Billing::Error::DEFINITIONS |