Billing Spend Interface — Use Cases
This page lists every flow that changes when Ads spends credits through the public Billing classes.
- The rules are in Billing D18 — Product domains spend credits only through SpendService.
- The methods and the errors are on Billing interface for product domains.
- The rules table and the code that changes are on Billing Spend Interface — Design Plan.
Words used in this doc
| Word | Meaning |
|---|---|
| Deliverable | The product record that one spend pays for, here one Ads::CampaignPlacement. |
| Own account | The Billing::Account whose billing_accounts.org_company_id is the company. |
| The reserve entry | The newest Billing::LedgerEntry with entry_type: :reserve for one deliverable. |
| Deliverable route | A Team Portal web route that loads one deliverable and redirects to the page that shows it. |
| Marketing | The one person at Jod who runs Ads campaigns for clients in the Team Portal. |
Every use case below follows one company and one campaign.
- Acme Pte Ltd has 40 placement credits.
- Its campaign "Hiring baristas" is campaign 42.
- The Homepage banner, placement 77, runs 7 days for 30 credits at the price "Weekly".
- The Job board spotlight, placement 78, runs 7 days for 20 credits at the price "Weekly".
Summary
| ID | Use case | Actor | Segment |
|---|---|---|---|
| UC-1 | Submit a campaign | HQ manager (Org::Membership) or Marketing (Identities::Admin) | Employer Dashboard, Team Portal |
| UC-2 | Two submits race for the same credits | Two HQ managers of one company | Employer Dashboard |
| UC-3 | A company with no billing account submits | HQ manager | Employer Dashboard |
| UC-4 | Cancel or reject a campaign | HQ manager, Marketing (Identities::Admin), or the auto-reject job | Employer Dashboard, Team Portal |
| UC-5 | Consume a running placement each day | System, Ads::CampaignPlacements::ConsumeReservedCreditsJob | Scheduled job |
| UC-6 | Marketing opens a campaign in the Team Portal | Marketing (Identities::Admin) | Team Portal |
| UC-7 | Sales reads an account's ledger | Sales or Finance (Identities::Admin) | Team Portal |
| UC-8 | A new product spends credits | A Careers engineer | Code |
| UC-9 | Complete a placement at its end time | System, the two Ads complete jobs | Scheduled job |
UC-1: Submit a campaign
| Field | Details |
|---|---|
| Actor | Acme's HQ manager, or Marketing for Acme |
| Trigger | The actor submits campaign 42 for review |
System behaviour:
- The submit validator runs its own checks, such as the requested start date.
- The submit validator runs
Billing::SpendValidatorwithorg_company: Acme,instrument: :placementandunits: 50. - Acme has 40 credits, so
Billing::SpendValidatoradds one error underplacement_credits.You need 50 placement credits, but you only have 40 available. Please contact us to top up your placement credits.
- The submit validator merges that error into its own errors with
errors.merge!. - The manager raises one 422 with every error, and the system writes nothing.
- Sales grants Acme 100 credits, so Acme has 140 credits.
- The actor submits again, and every check passes.
- The manager opens a transaction and calls
Billing::SpendService.reserveonce per placement.- The banner call passes
units: 30anddeliverable:the banner. - The banner call passes
description: 'Ad: Hiring baristas, Homepage banner, Weekly'. - The manager fills that text from
Ads::CampaignPlacement::BILLING_LEDGER_ENTRY_DESCRIPTIONwithformat.
- The banner call passes
- Billing checks that a transaction is open, finds Acme's own account, locks its balance row and picks the soonest-expiring lots.
- Billing writes one
reserveledger entry per placement, with the description, and returns nothing. - The manager sets the campaign to
pending_review, and the transaction commits.
Postconditions:
- Acme has 90 credits available and 50 reserved.
- Each placement has one
reserveledger entry that names it as the source.
UC-2: Two submits race for the same credits
| Field | Details |
|---|---|
| Actor | Two HQ managers of Acme |
| Trigger | After UC-1 Acme has 90 credits available, and two HQ managers submit campaigns 43 and 44 at the same moment |
Campaigns 43 and 44 each have a banner for 30 credits and a spotlight for 20 credits, like campaign 42.
System behaviour:
- Both submit validators read 90 available credits with no lock, and each campaign needs 50, so both pass.
- The first manager's
reservefor the banner of campaign 43 locks the balance row.- The lock stays until the transaction of campaign 43 commits.
- The first manager reserves 30 and 20 credits and commits, so Acme has 40 credits available.
- The second manager's
reservefor the banner of campaign 44 waited for the lock.- It now reserves 30 of the 40 credits.
- The second manager's
reservefor the spotlight of campaign 44 needs 20 credits and reads 10 available. Billing::SpendServiceraisesBilling::InsufficientCreditsErrorunderplacement_credits, withcode: 'not_enough_credits'.You need 20 placement credits, but you only have 10 available. Please contact us to top up your placement credits.
- The second transaction rolls back, so the 30 credits of its banner return, and campaign 44 stays a draft.
Postconditions:
- Acme has 40 credits available, and campaign 43 holds 50 reserved credits.
Business rules:
- The second manager gets the same key and the same words as the pre-check.
- The numbers are the units of the placement that did not fit, and the credits left at that moment.
- The pre-check counts the whole campaign, so it would say 50 and 40.
- The race cannot reserve more credits than the account has.
UC-3: A company with no billing account submits
A company with no Billing::Account is a data bug, because every company is created with its own account.
| Field | Details |
|---|---|
| Actor | An HQ manager of a company with no Billing::Account |
| Trigger | The HQ manager submits a campaign |
System behaviour:
Billing::SpendValidatorreadsorg_company.billing_account, and it isnil.Billing::SpendValidatorraisesErrors::InternalServerError.- A raise inside
SpendValidator#valid?reachesApplicationControllerlike any other exception.
- A raise inside
- The request ends with a 500, and the system writes nothing.
- Sentry reports
Errors::InternalServerErroras an error, so an engineer sees the data bug. - An engineer creates the missing account with the rake task in
lib/tasks/billing/backfill_company_accounts.rake.
Business rules:
- Every company is created with its own
Billing::Account.Org::Companies::Shared::CreateServicecallsBilling::Accounts::Shared::CreateService.Org::Memberships::EmployersCreateManagercallsBilling::Accounts::Shared::CreateServiceafter it saves the membership.JodGig::Companies::SyncServicecallsJodGig::Companies::BillingAccountUpsertAllServiceafter it upserts companies.
- The HQ manager cannot fix a missing account, so the system shows no form error for it.
- A missing account never skips the credit check, because the raise stops the request.
- A caller that skips the validator gets
Errors::InternalServerErrorfromreserveorconsume_now.
UC-4: Cancel or reject a campaign
| Field | Details |
|---|---|
| Actor | Acme's HQ manager cancels, Marketing cancels or rejects, or Ads::AutoRejectCampaignJob rejects after 14 days |
| Trigger | Campaign 42 is cancelled or rejected |
System behaviour (one transaction):
- The manager, or
Ads::Campaigns::RejectService, callsBilling::SpendService.releasefor each placement.- The call passes only
deliverable:.
- The call passes only
- Billing finds the account and the instrument on the reserve entry of the placement.
- Billing locks the balance row, then sums the units that the placement still holds reserved.
- Billing returns every reserved credit to the lot it came from.
- Billing writes one
releaseledger entry, and copies the description from the reserve entry. - The manager sets the placement and the campaign statuses.
Business rules:
- A placement with no reserved credits gets no ledger entry, and
releasedoes nothing. releasereturns nothing in both cases.- Credits returned to an expired lot expire at once (Billing D12 — Released credits get no extra time).
UC-5: Consume a running placement each day
| Field | Details |
|---|---|
| Actor | System, Ads::CampaignPlacements::ConsumeReservedCreditsJob |
| Trigger | The schedule in config/sidekiq_scheduler.yml, every hour at minute 20 |
System behaviour (one transaction per placement):
- The job finds every
activecampaign placement, here the banner and the spotlight of campaign 42.- An approved placement becomes
activeat itsstart_time, and the job skips it before that.
- An approved placement becomes
- The job computes the banner's target for day 1 with the Ads formula:
round(30 × 1 ÷ 7) = 4.- The formula is
round(credit_cost_snapshot × days_elapsed ÷ duration_days). days_elapsedis the number of full days sincestart_time, plus 1, and never more thanduration_days.duration_daysis the number of whole days fromstart_timetoend_timeof the placement, not the days of the price.- So a later edit of
ads_placement_prices.duration_dayschanges no target of a running placement. - So day 1 is the first 24 hours after
start_time, not a calendar day.
- The formula is
- The job calls
Billing::SpendService.consume_reservedwith the banner andtarget_units_consumed: 4. - Billing locks the balance row, reads the 0 units that the banner has consumed, and consumes 4.
- Billing writes one
consumeledger entry, and copies the description from the reserve entry. - The transaction commits, and the job moves to the spotlight.
- The spotlight's target for day 1 is
round(20 × 1 ÷ 7) = 3, so Billing consumes 3 in a second transaction.
Postconditions:
- After day 1 the banner has 26 units reserved and 4 units consumed.
- After day 1 the spotlight has 17 units reserved and 3 units consumed.
Business rules:
- A later run in the same 24 hours passes the same target, so Billing consumes 0 and writes nothing.
- A target below the units already consumed raises an error, because Billing cannot un-consume.
- A target above the reserved units raises an error, because Billing never spends units that were not reserved.
- A placement that fails rolls back alone, and the job reports it to Sentry with the placement id.
- The job rescues
StandardError, so Sentry gets every failed placement as an error.
- The job rescues
- The formula is the one in Billing D5 — Spending mechanics: consume now, or reserve first.
UC-6: Marketing opens a campaign in the Team Portal
| Field | Details |
|---|---|
| Actor | Marketing (Identities::Admin) |
| Trigger | Marketing opens campaign 42 in the Team Portal |
System behaviour:
- The page loader loads campaign 42 from
GET /team/ads/campaigns/42, which carries no Billing data. - The loader loads Acme's own account from
GET /team/billing/org-companies/:org_company_id/account.- It gets the account
idand its placementunits_available. - A company with no account gets a 500 with the code
billing_account_missing, because that is a data bug.
- It gets the account
- The page reads the spends of placements 77 and 78 from
GET /team/billing/spends.- It reads them when Marketing opens the reject or cancel dialog, because only the dialogs show them.
- After day 1, the spend row of placement 77, the Homepage banner, has 26 units reserved and 4 units consumed.
- The spend row of placement 78, the Job board spotlight, has 17 units reserved and 3 units consumed.
- The cancel dialog shows the units that go back, the units that expire and the units already used.
- For placement 77 after day 1, that is 26 that go back, 0 that expire and 4 already used.
- The reject dialog shows only the first two, because a campaign in review has used no units.
- Marketing can reject only a campaign in review, so the numbers after day 1 never show in the reject dialog.
units_reserved_in_expired_lotsdrives the warning on both dialogs.- A failed read keeps the confirm button of the dialog disabled.
Ads::Campaigns::TeamShowManagercalls no Billing class.
Postconditions:
- The page shows the units available of the account.
- The cancel dialog shows the units that go back, expire and are already used, for each placement.
- The reject dialog shows the units that go back and expire, for each placement.
UC-7: Sales reads an account's ledger
| Field | Details |
|---|---|
| Actor | Sales or Finance (Identities::Admin) |
| Trigger | Sales opens Acme's billing account page in the Team Portal |
System behaviour:
- The ledger list reads Acme's ledger entries, with no join on a product table.
- Each entry carries
description,source_typeandsource_id. - The web links the entry with
source_type: 'Ads::CampaignPlacement'andsource_id: 77to/team/ads/campaign-placements/77. - The row shows
Ad: Hiring baristas, Homepage banner, Weeklyas the link text. - Sales clicks the link, and the route loads placement 77 from
GET /team/ads/campaign_placements/77. - The route reads
ads_campaign_id: 42, and redirects Sales to/team/ads/campaigns/42. - A Billing source, such as an invoice posting, shows its own link, such as
Invoice #12.
Business rules:
- Billing stores no page record, so a change to the page that shows a placement changes only the web.
- The list pays nothing for its links, because the route loads the placement only on the click.
UC-8: A new product spends credits
| Field | Details |
|---|---|
| Actor | A Careers engineer |
| Trigger | Careers charges 50 placement credits when an HQ manager posts a job |
System behaviour:
- The Careers validator runs
Billing::SpendValidatorwithunits: 50, and merges its errors. - The Careers manager opens a transaction and saves the
Careers::Job. Careers::JobListingPeriods::Shared::CreateServicesavesCareers::JobListingPeriod88 in the same transaction.- The service calls
Billing::SpendService.consume_nowin the same transaction.- It passes the
Careers::JobListingPeriodasdeliverable:. - It passes
description: 'Job post: Barista, 1 Month'. - It fills that text from
Careers::JobListingPeriod::BILLING_LEDGER_ENTRY_DESCRIPTIONS.fetch(:post).
- It passes the
- Billing writes one
consumeledger entry with the keyconsume_now_Careers::JobListingPeriod_88. consume_nowreturns nothing, and the transaction commits.
Business rules:
- Careers adds no Billing code, no source type and no table join.
- The web adds one deliverable route for
Careers::JobListingPeriod, which redirects to the page of its job. - A second
consume_nowfor listing period 88 raisesErrors::InternalServerError, so one listing period is never paid twice.- Billing checks for the first direct spend before the balance, so the error is the same with 0 credits left.
UC-9: Complete a placement at its end time
| Field | Details |
|---|---|
| Actor | System, Ads::CompleteCampaignPlacementsJob and Ads::BulkCompleteCampaignPlacementsJob |
| Trigger | The end_time of a placement, and the schedule in config/sidekiq_scheduler.yml, every hour at minute 10 |
System behaviour (one transaction per placement):
- The job finds every
activeplacement whoseend_timehas passed, here the banner of campaign 42. Ads::CampaignPlacements::CompleteServicelocks the placement row, and stops when the placement is no longeractive.- The service calls
Billing::SpendService.consume_reservedwith the banner andtarget_units_consumed: 30, its whole cost. - Billing consumes the units that are still reserved.
- The banner missed its last day, so it has 26 units consumed, and Billing consumes the last 4.
- A banner that consumed all 30 units on day 7 makes Billing write nothing.
- The service sets the placement to
completed. - The transaction commits, and the job moves to the next placement.
- The job sets the campaign to
completedwhen each of its placements iscompletedorcancelled.
Postconditions:
- The banner is
completed, with 30 units consumed and 0 units reserved.
Business rules:
- A placement becomes
completedonly in the transaction that consumes its whole cost.- No cancel and no reject can reach a
completedplacement, so units that stay reserved would stay reserved for ever.
- No cancel and no reject can reach a
- When Billing raises, the transaction rolls back, and the placement stays
active.- The job reports it to Sentry with the placement id, and the next hourly run tries again.
- The campaign stays
approvedwhile one of its placements isactive. - No ad of that placement is shown after
end_time, becauseAds::CampaignPlacements::ShowManagerchecksend_time.
- A placement with no reserve entry never completes, because Billing raises for it.
- The rule has no exception, as the row "The end of a reserved deliverable" of Billing D18 — Product domains spend credits only through SpendService rules.
- Units that the banner reserved from a lot that has expired are consumed like any other, because reserved units never expire.