Skip to main content

Billing Spend Interface — Use Cases

This page lists every flow that changes when Ads spends credits through the public Billing classes.

Words used in this doc​

WordMeaning
DeliverableThe product record that one spend pays for, here one Ads::CampaignPlacement.
Own accountThe Billing::Account whose billing_accounts.org_company_id is the company.
The reserve entryThe newest Billing::LedgerEntry with entry_type: :reserve for one deliverable.
Deliverable routeA Team Portal web route that loads one deliverable and redirects to the page that shows it.
MarketingThe 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​

IDUse caseActorSegment
UC-1Submit a campaignHQ manager (Org::Membership) or Marketing (Identities::Admin)Employer Dashboard, Team Portal
UC-2Two submits race for the same creditsTwo HQ managers of one companyEmployer Dashboard
UC-3A company with no billing account submitsHQ managerEmployer Dashboard
UC-4Cancel or reject a campaignHQ manager, Marketing (Identities::Admin), or the auto-reject jobEmployer Dashboard, Team Portal
UC-5Consume a running placement each daySystem, Ads::CampaignPlacements::ConsumeReservedCreditsJobScheduled job
UC-6Marketing opens a campaign in the Team PortalMarketing (Identities::Admin)Team Portal
UC-7Sales reads an account's ledgerSales or Finance (Identities::Admin)Team Portal
UC-8A new product spends creditsA Careers engineerCode
UC-9Complete a placement at its end timeSystem, the two Ads complete jobsScheduled job

UC-1: Submit a campaign​

FieldDetails
ActorAcme's HQ manager, or Marketing for Acme
TriggerThe actor submits campaign 42 for review

System behaviour:

  1. The submit validator runs its own checks, such as the requested start date.
  2. The submit validator runs Billing::SpendValidator with org_company: Acme, instrument: :placement and units: 50.
  3. Acme has 40 credits, so Billing::SpendValidator adds one error under placement_credits.
    • You need 50 placement credits, but you only have 40 available. Please contact us to top up your placement credits.
  4. The submit validator merges that error into its own errors with errors.merge!.
  5. The manager raises one 422 with every error, and the system writes nothing.
  6. Sales grants Acme 100 credits, so Acme has 140 credits.
  7. The actor submits again, and every check passes.
  8. The manager opens a transaction and calls Billing::SpendService.reserve once per placement.
    • The banner call passes units: 30 and deliverable: the banner.
    • The banner call passes description: 'Ad: Hiring baristas, Homepage banner, Weekly'.
    • The manager fills that text from Ads::CampaignPlacement::BILLING_LEDGER_ENTRY_DESCRIPTION with format.
  9. Billing checks that a transaction is open, finds Acme's own account, locks its balance row and picks the soonest-expiring lots.
  10. Billing writes one reserve ledger entry per placement, with the description, and returns nothing.
  11. 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 reserve ledger entry that names it as the source.

UC-2: Two submits race for the same credits​

FieldDetails
ActorTwo HQ managers of Acme
TriggerAfter 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:

  1. Both submit validators read 90 available credits with no lock, and each campaign needs 50, so both pass.
  2. The first manager's reserve for the banner of campaign 43 locks the balance row.
    • The lock stays until the transaction of campaign 43 commits.
  3. The first manager reserves 30 and 20 credits and commits, so Acme has 40 credits available.
  4. The second manager's reserve for the banner of campaign 44 waited for the lock.
    • It now reserves 30 of the 40 credits.
  5. The second manager's reserve for the spotlight of campaign 44 needs 20 credits and reads 10 available.
  6. Billing::SpendService raises Billing::InsufficientCreditsError under placement_credits, with code: 'not_enough_credits'.
    • You need 20 placement credits, but you only have 10 available. Please contact us to top up your placement credits.
  7. 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.

FieldDetails
ActorAn HQ manager of a company with no Billing::Account
TriggerThe HQ manager submits a campaign

System behaviour:

  1. Billing::SpendValidator reads org_company.billing_account, and it is nil.
  2. Billing::SpendValidator raises Errors::InternalServerError.
    • A raise inside SpendValidator#valid? reaches ApplicationController like any other exception.
  3. The request ends with a 500, and the system writes nothing.
  4. Sentry reports Errors::InternalServerError as an error, so an engineer sees the data bug.
  5. 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::CreateService calls Billing::Accounts::Shared::CreateService.
    • Org::Memberships::EmployersCreateManager calls Billing::Accounts::Shared::CreateService after it saves the membership.
    • JodGig::Companies::SyncService calls JodGig::Companies::BillingAccountUpsertAllService after 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::InternalServerError from reserve or consume_now.

UC-4: Cancel or reject a campaign​

FieldDetails
ActorAcme's HQ manager cancels, Marketing cancels or rejects, or Ads::AutoRejectCampaignJob rejects after 14 days
TriggerCampaign 42 is cancelled or rejected

System behaviour (one transaction):

  1. The manager, or Ads::Campaigns::RejectService, calls Billing::SpendService.release for each placement.
    • The call passes only deliverable:.
  2. Billing finds the account and the instrument on the reserve entry of the placement.
  3. Billing locks the balance row, then sums the units that the placement still holds reserved.
  4. Billing returns every reserved credit to the lot it came from.
  5. Billing writes one release ledger entry, and copies the description from the reserve entry.
  6. The manager sets the placement and the campaign statuses.

Business rules:


UC-5: Consume a running placement each day​

FieldDetails
ActorSystem, Ads::CampaignPlacements::ConsumeReservedCreditsJob
TriggerThe schedule in config/sidekiq_scheduler.yml, every hour at minute 20

System behaviour (one transaction per placement):

  1. The job finds every active campaign placement, here the banner and the spotlight of campaign 42.
    • An approved placement becomes active at its start_time, and the job skips it before that.
  2. 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_elapsed is the number of full days since start_time, plus 1, and never more than duration_days.
    • duration_days is the number of whole days from start_time to end_time of the placement, not the days of the price.
    • So a later edit of ads_placement_prices.duration_days changes no target of a running placement.
    • So day 1 is the first 24 hours after start_time, not a calendar day.
  3. The job calls Billing::SpendService.consume_reserved with the banner and target_units_consumed: 4.
  4. Billing locks the balance row, reads the 0 units that the banner has consumed, and consumes 4.
  5. Billing writes one consume ledger entry, and copies the description from the reserve entry.
  6. The transaction commits, and the job moves to the spotlight.
  7. 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 formula is the one in Billing D5 — Spending mechanics: consume now, or reserve first.

UC-6: Marketing opens a campaign in the Team Portal​

FieldDetails
ActorMarketing (Identities::Admin)
TriggerMarketing opens campaign 42 in the Team Portal

System behaviour:

  1. The page loader loads campaign 42 from GET /team/ads/campaigns/42, which carries no Billing data.
  2. The loader loads Acme's own account from GET /team/billing/org-companies/:org_company_id/account.
    • It gets the account id and its placement units_available.
    • A company with no account gets a 500 with the code billing_account_missing, because that is a data bug.
  3. 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_lots drives the warning on both dialogs.
    • A failed read keeps the confirm button of the dialog disabled.
  4. Ads::Campaigns::TeamShowManager calls 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​

FieldDetails
ActorSales or Finance (Identities::Admin)
TriggerSales opens Acme's billing account page in the Team Portal

System behaviour:

  1. The ledger list reads Acme's ledger entries, with no join on a product table.
  2. Each entry carries description, source_type and source_id.
  3. The web links the entry with source_type: 'Ads::CampaignPlacement' and source_id: 77 to /team/ads/campaign-placements/77.
  4. The row shows Ad: Hiring baristas, Homepage banner, Weekly as the link text.
  5. Sales clicks the link, and the route loads placement 77 from GET /team/ads/campaign_placements/77.
  6. The route reads ads_campaign_id: 42, and redirects Sales to /team/ads/campaigns/42.
  7. 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​

FieldDetails
ActorA Careers engineer
TriggerCareers charges 50 placement credits when an HQ manager posts a job

System behaviour:

  1. The Careers validator runs Billing::SpendValidator with units: 50, and merges its errors.
  2. The Careers manager opens a transaction and saves the Careers::Job.
  3. Careers::JobListingPeriods::Shared::CreateService saves Careers::JobListingPeriod 88 in the same transaction.
  4. The service calls Billing::SpendService.consume_now in the same transaction.
    • It passes the Careers::JobListingPeriod as deliverable:.
    • It passes description: 'Job post: Barista, 1 Month'.
    • It fills that text from Careers::JobListingPeriod::BILLING_LEDGER_ENTRY_DESCRIPTIONS.fetch(:post).
  5. Billing writes one consume ledger entry with the key consume_now_Careers::JobListingPeriod_88.
  6. consume_now returns 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_now for listing period 88 raises Errors::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​

FieldDetails
ActorSystem, Ads::CompleteCampaignPlacementsJob and Ads::BulkCompleteCampaignPlacementsJob
TriggerThe end_time of a placement, and the schedule in config/sidekiq_scheduler.yml, every hour at minute 10

System behaviour (one transaction per placement):

  1. The job finds every active placement whose end_time has passed, here the banner of campaign 42.
  2. Ads::CampaignPlacements::CompleteService locks the placement row, and stops when the placement is no longer active.
  3. The service calls Billing::SpendService.consume_reserved with the banner and target_units_consumed: 30, its whole cost.
  4. 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.
  5. The service sets the placement to completed.
  6. The transaction commits, and the job moves to the next placement.
  7. The job sets the campaign to completed when each of its placements is completed or cancelled.

Postconditions:

  • The banner is completed, with 30 units consumed and 0 units reserved.

Business rules:

  • A placement becomes completed only in the transaction that consumes its whole cost.
    • No cancel and no reject can reach a completed placement, so units that stay reserved would stay reserved for ever.
  • 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 approved while one of its placements is active.
    • No ad of that placement is shown after end_time, because Ads::CampaignPlacements::ShowManager checks end_time.
  • A placement with no reserve entry never completes, because Billing raises for it.
  • Units that the banner reserved from a lot that has expired are consumed like any other, because reserved units never expire.