Skip to main content

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.

Words used in this doc​

WordMeaning
DeliverableThe product record that one spend pays for, here one Ads::CampaignPlacement.
Own accountThe Account whose billing_accounts.org_company_id is the company.
Pre-checkThe credit check of Billing::SpendValidator before the transaction, with no lock, so the employer sees a clear error.
The reserve entryThe newest LedgerEntry with entry_type: :reserve for one deliverable.
The balance row locklock('FOR UPDATE') on the billing_entitlement_balances row of one account and one instrument.
Deliverable routeA 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 EntitlementLotServiceBilling::EntitlementLotService, the private class that moves credits between lots and writes ledger entries.
MarketingThe 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.

RuleApplies toExample
Ads code names only Billing::SpendService and Billing::SpendValidator from Billing when it spendsUS-1, US-6Ads::Campaigns::EmployersSubmitManager calls Billing::SpendService.reserve
Ads passes the company and the deliverable record, never a Billing::Account, source_type or source_idUS-1org_company: org_company, deliverable: campaign_placement
A write method returns nothing, so Ads never holds a Billing::LedgerEntryUS-1Billing::SpendService.reserve returns no ledger entry
Billing code never reads a product tableUS-2Ads::CampaignPlacements::ConsumeReservedCreditsJob lives in Ads and reads ads_campaign_placements
Billing code names no product classUS-2, US-6Billing::LedgerEntry::SOURCE_TYPES lists only Billing records
An Ads endpoint carries no Billing data, and the Team Portal campaign page reads Billing endpointsUS-2Ads::Campaigns::TeamShowManager calls no Billing class
The Ads submit validators run Billing::SpendValidator and merge its errorsUS-3One 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::InsufficientCreditsErrorUS-3Of two submits at the same moment, the second one gets the 422
Billing writes the credit error message under the key <instrument>_creditsUS-3placement_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 productalwaysA 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 namealwaysBilling::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 SentryalwaysAds::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 modelUS-4format(Ads::CampaignPlacement::BILLING_LEDGER_ENTRY_DESCRIPTION, ...) gives Ad: Hiring baristas, Homepage banner, Weekly
consume_reserved and release copy the description from the reserve entryUS-4The 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 emptyUS-4A :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 textUS-5The 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 lockalwaystarget_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 transactionalwaysOne placement that fails does not stop the other placements
A search for a boundary break prints nothingUS-6The 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​

  1. Acme has 40 placement credits, and its campaign 42 costs 50 credits.
  2. The first submit fails with one 422 under placement_credits, and Billing writes nothing.
  3. Sales grants Acme 100 credits, and the HQ manager submits again.
  4. Billing::SpendService.reserve reserves 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.
  5. The full walk-through is Billing Spend Interface — UC-1: Submit a campaign.

Database​

One column goes on the table billing_ledger_entries.

ColumnTypeMeaning
billing_ledger_entries.descriptionstring, 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 reserve entry and a consume_now entry.
  • consume_reserved and release copy the text from the reserve entry.
  • Billing writes the text of the entries it starts itself, such as a :grant and 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_type says 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.

PathFileWhat it does
Public serviceapp/domains/billing/spend_service.rbChecks the open transaction, reads org_company.billing_account and the entitlement, and calls EntitlementLotService; raises Errors::InternalServerError when the account is nil
Public validatorapp/domains/billing/spend_validator.rbChecks the units available on org_company.billing_account, and raises Errors::InternalServerError when the account is nil
Billing errorsapp/domains/billing/error.rb
app/domains/billing/insufficient_credits_error.rb
Billing::Error, with Billing::InsufficientCreditsError under it, one class per file
Lot logicapp/domains/billing/entitlement_lot_service.rbTakes the description, subtracts the consumed units after the lock, and raises Billing::InsufficientCreditsError
Source listapp/domains/billing/ledger_entry.rbSOURCE_TYPES lists only Billing records
Ads descriptionapp/domains/ads/campaign_placement.rbHolds the constant BILLING_LEDGER_ENTRY_DESCRIPTION
Submit validatorsapp/domains/ads/campaigns/employers_submit_validator.rb
app/domains/ads/campaigns/team_submit_validator.rb
Run Billing::SpendValidator with the campaign total and merge its errors
Submit managersapp/domains/ads/campaigns/employers_submit_manager.rb
app/domains/ads/campaigns/team_submit_manager.rb
Call Billing::SpendService.reserve per placement
Cancel and rejectapp/domains/ads/campaigns/employers_cancel_manager.rb
app/domains/ads/campaigns/team_cancel_manager.rb
app/domains/ads/campaigns/reject_service.rb
Call Billing::SpendService.release per placement
Team Portal campaign showapp/domains/ads/campaigns/team_show_manager.rbCalls no Billing class, and the page reads Billing endpoints, as jodapp-api#2204 sets out
Daily consumeapp/domains/ads/campaign_placements/consume_reserved_credits_job.rbAds::CampaignPlacements::ConsumeReservedCreditsJob calls Billing::SpendService.consume_reserved, with one transaction per placement
Scheduleconfig/sidekiq_scheduler.ymlSchedules Ads::CampaignPlacements::ConsumeReservedCreditsJob every hour at minute 20
Ledger listapp/domains/billing/ledger_entries/team_index_manager.rbJoins no product table
Ledger serializerapp/domains/billing/ledger_entries/team_base_serializer.rbSends description, source_type and source_id, and no Ads field
Ledger filterapp/domains/billing/ledger_entries/team_index_validator.rbAccepts any class name in source_type

EntitlementLotService keeps reserve, consume, release and expire, and stays private to Billing.

  • Billing::SpendService is a small public class that turns the product arguments into Billing records, then calls EntitlementLotService.
    • The company becomes the own account, from org_company.billing_account.
    • The deliverable becomes the source, from deliverable.class.name and deliverable.id.
    • The instrument becomes the Billing::Entitlement row.

The Billing errors keep Errors::UnprocessableContentError as their parent for now.

  • Billing::Error is a subclass of Errors::UnprocessableContentError, so ApplicationController renders each one as a 422.
  • Each error takes its code: and title: from Billing::Error::DEFINITIONS with fetch, such as not_enough_credits.
  • The parent becomes Errors::BaseError when ApplicationController maps each error class to its HTTP status.

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_consumed is round(credit_cost_snapshot × days_elapsed ÷ duration_days), the Ads daily formula.
    • days_elapsed is the number of full days since start_time, plus 1, and never more than duration_days.
  • Billing subtracts the units already consumed after the balance row lock, so the job reads no Billing table.
  • The job rescues StandardError for 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 StandardError rescue 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_typeLink targetLink text
Ads::CampaignPlacement/team/ads/campaign-placements/:source_id, which redirects to /team/ads/campaigns/:ads_campaign_idbilling_ledger_entries.description
A Billing source, such as Billing::InvoicePostingIts Billing page, such as /team/billing/invoices/:idIts 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::CampaignPlacement as 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_consumed and units_reserved_in_expired_lots from GET /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_now after this work.
    • This work builds consume_now and its tests in jodapp-api#2216, and no product code calls it yet.
  • 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-3 and feature/frontend-billing-phase-3 after the manual test plan.
  1. Add the column billing_ledger_entries.description and the DBML change.
  2. Add a skeleton of Billing::SpendService, Billing::SpendValidator and the Billing errors, with the final sigs.
    • Each method body raises Errors::UnimplementedError, and no product code calls it.
  3. Build one method per pull request, with its tests, and move the Ads submit, cancel and reject code onto it.
  4. Move the daily consume job to Ads, in the same pull request as its schedule change.
  5. Change the Team Portal ledger list and the web ledger table together.

The Team Portal campaign page moves to Billing endpoints before step 5.

Existing records​

  • The column billing_ledger_entries.description is NOT NULL, and no existing row gets a backfill text.
  • An old Ads entry on staging links to its deliverable route like a new entry.
    • The route needs only billing_ledger_entries.source_type and source_id, which every entry has.

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 watchHow oftenWho
Lines the boundary search prints, 0 after step 5On every pull request that touches Billing or a product domainThe code reviewer
Sentry errors from Ads::CampaignPlacements::ConsumeReservedCreditsJobDaily for one week after step 4Imam

Open questions​

QuestionWho answersStatus
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?Imamclosed: 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