Skip to main content

Billing Spend Interface — Implementation Plan

This page splits the Billing spend interface into issues for jodapp-api and jodapp-web, in build order.

Where the code goes​

The Billing lot code is not on main yet, so this work has its own branches.

RepoBase branch for these PRs
jodapp-apifeature/backend-billing-interface, which merges into feature/backend-billing-phase-3
jodapp-webfeature/frontend-billing-interface, which merges into feature/frontend-billing-phase-3

EntitlementLotService and the Ads billing code exist only on feature/backend-billing-phase-3.

  • So the work branches merge into the phase 3 branches.
    • They ship to main with the rest of the Billing lot code.
  • Imam cut the work branches from the tips of jodapp-api PR #2207 and jodapp-web PR #1513.
  • The first jodapp-api PR targets feature/backend-billing-interface, and each later PR targets the branch of the PR before it.
  • Careers starts to charge for a job post after API-5, so Careers uses the public classes from its first PR.

Work that already exists​

Four pieces of work in jodapp-api come first, and all four are merged.

WorkOwnerWhat it doesMerges before
jodapp-api PR #2206ImamEvery caller reads the own account from org_company.billing_account, because every company has one accountAPI-2, because Billing::SpendService reads the same association
jodapp-api#2204, built in jodapp-api PR #2207ImamAds::Campaigns::TeamShowManager calls no Billing class, and the Team Portal campaign page reads Billing endpointsAPI-6, because API-6 removes the SOURCE_TYPES entry that the show code names
jodapp-api PR #2203LintangThe daily consume job writes each placement in one transactionAPI-2 and API-5, because they change the same files
jodapp-api PR #2202LintangA release into an expired lot writes the expire entry that recognises the revenue of the expired creditsAPI-2, because both change app/domains/billing/entitlement_lot_service.rb

Build order​

Legend: lavender = jodapp-api, grey = jodapp-web, dashed = work outside the issues of this plan.

API-6 and WEB-1 must ship together.

  • Otherwise the ledger table looks for ads_campaign_id, which API-6 removes, and loses its campaign links.

jodapp-api issues​

API-1 — The column billing_ledger_entries.description​

jodapp-api#2210 builds this item, in jodapp-api PR #2223.

  • Add the column to the table billing_ledger_entries in the file jodapp-api/docs/db/billing.dbml, as Design Plan — Database shows.
  • The column is NOT NULL, with the CHECK btrim(description) <> '', and the migration raises unless the table is empty.
  • Change the note of billing_ledger_entries.source_type.
    • A spend's source is the deliverable that the product passes to Billing::SpendService, such as Careers::JobListingPeriod.
  • Write the migration with the tag ActiveRecord::Migration[8.1].
  • Run bin/dbml_check, and check that it reports no difference for the new column.

API-2 — Billing::SpendService, Billing::SpendValidator and the Billing errors​

API-2 is built in two steps, so the public shape is in review before any logic.

  • jodapp-api#2211 adds a skeleton with the final sigs, and each method body raises Errors::UnimplementedError.
  • Five issues then build one method each, with its tests, as a stack of PRs on the skeleton.
  • The skeleton lives only on feature/backend-billing-interface until its method issue merges.
    • So no product code ever calls a method that only raises.
IssuePRBuilds
jodapp-api#2211jodapp-api PR #2224The skeleton, the open-transaction check, and Billing::Error and Billing::InsufficientCreditsError in full
jodapp-api#2212jodapp-api PR #2225Billing::SpendValidator, and the Ads submit validators run it
jodapp-api#2213jodapp-api PR #2226reserve, and the Ads submit managers call it
jodapp-api#2214jodapp-api PR #2227release, and the Ads cancel and reject code calls it
jodapp-api#2215jodapp-api PR #2235consume_reserved with a target total, and the daily consume job calls it
jodapp-api#2216jodapp-api PR #2237consume_now
  • Add the two public classes, as Billing interface for product domains describes.
  • Billing::SpendService reads the own account with org_company.billing_account, and the entitlement from instrument:.
    • Then it calls EntitlementLotService, and it never opens a transaction.
  • Build the four write methods reserve, consume_now, consume_reserved and release, each with a Sorbet sig.
  • Each write method raises on its first line when ActiveRecord::Base.current_transaction.open? is false.
  • Each write method returns nothing, with a void sig.
  • consume_now writes idempotency_key: "consume_now_<source_type>_<source_id>".
    • A missing balance row counts as 0 units available, so consume_now raises Billing::InsufficientCreditsError.
  • consume_reserved takes target_units_consumed:, and subtracts the units already consumed after the balance row lock.
    • A target below the units already consumed raises.
    • A target above the reserved units raises.
  • Billing::SpendService has no read method, because a page reads Billing endpoints.
  • EntitlementLotService.reserve and the direct consume take description:, and save it on the ledger entry.
  • EntitlementLotService.consume and release copy description from the reserve entry.
  • Billing writes the description of its own entries, such as a :grant from an invoice and an :expire.
  • Add app/domains/billing/error.rb and app/domains/billing/insufficient_credits_error.rb, one class per file.
    • Billing::Error < Errors::UnprocessableContentError, for now.
    • Billing::InsufficientCreditsError < Billing::Error, with the code and title of Billing::Error::DEFINITIONS.fetch(:not_enough_credits).
    • Billing::Error::DEFINITIONS is one frozen hash of Data objects, each with a code and a title.
    • Billing::Error::DEFINITIONS holds not_enough_credits and billing_account_missing.
  • The parent of Billing::Error becomes Errors::BaseError when ApplicationController maps each error class to its HTTP status.
  • EntitlementLotService raises Billing::InsufficientCreditsError under the key <instrument>_credits, such as placement_credits.
  • Billing::SpendService raises Errors::InternalServerError when org_company.billing_account is nil.
    • Every company is created with its own account, so a nil account is a data bug.
    • The error carries the code and title of Billing::Error::DEFINITIONS.fetch(:billing_account_missing).
  • Billing::SpendValidator raises Errors::InternalServerError in the same case, and adds no error.
  • One private method builds the "not enough credits" message, and both the validator and the error use it.
  • Mark EntitlementLotService private to Billing in its class comment.
  • Tests in test/domains/billing/ cover these cases:
    • The validator passes with enough credits.
    • The validator raises Errors::InternalServerError when units is 0 or less.
    • The validator fails under placement_credits with too few credits.
    • The validator, reserve and consume_now raise Errors::InternalServerError when org_company.billing_account is nil.
    • Each write method raises when no transaction is open.
    • reserve and consume_now save the description.
    • consume_reserved and release copy the description from the reserve entry.
    • consume_reserved with a target that the deliverable already reached does nothing, and a lower target raises.
    • consume_now writes its key, and a second call for the same deliverable raises Errors::InternalServerError, also when the balance is 0.
    • reserve and consume_now raise Billing::InsufficientCreditsError when the balance is too low.
    • Each Billing error carries its code.

API-3 — Ads submit uses the public classes​

jodapp-api#2217 is closed, because jodapp-api#2212 and jodapp-api#2213 build this work with their methods.

  • Ads::Campaigns::EmployersSubmitValidator and TeamSubmitValidator run Billing::SpendValidator with the campaign total.
    • They merge its errors with errors.merge!, and they stop reading org_company.billing_account, Entitlement and EntitlementBalance.
  • Ads::Campaigns::EmployersSubmitManager and TeamSubmitManager call Billing::SpendService.reserve per placement, inside their transaction.
  • Add the constant BILLING_LEDGER_ENTRY_DESCRIPTION to Ads::CampaignPlacement.
    • The managers fill it with format, so the text reads Ad: Hiring baristas, Homepage banner, Weekly.
  • No new automated test, because the team tests Ads campaigns by hand.
    • Fix the existing submit manager tests if they break.

API-4 — Ads cancel and reject use the public classes​

jodapp-api#2218 is closed, because jodapp-api#2214 builds this work with release.

  • Ads::Campaigns::EmployersCancelManager, TeamCancelManager and RejectService call Billing::SpendService.release(deliverable: campaign_placement).
    • They stop looking up the placement Billing::Entitlement.
  • The Team Portal campaign show is not in this issue, because jodapp-api#2204 moves its Billing data to Billing endpoints.

API-5 — The daily consume job moves to Ads​

jodapp-api#2219 builds this item, in jodapp-api PR #2238.

  • Move Billing::ConsumeEntitlementCreditsJob to Ads::CampaignPlacements::ConsumeReservedCreditsJob in app/domains/ads/campaign_placements/consume_reserved_credits_job.rb.
  • Keep the Ads daily formula, and pass its result as target_units_consumed: to Billing::SpendService.consume_reserved.
    • The job reads no Billing table, because Billing subtracts the units already consumed.
  • Keep the one transaction per placement that jodapp-api PR #2203 adds.
  • Rescue StandardError for each placement, and report 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.
  • Change config/sidekiq_scheduler.yml in the same PR, with the same time and the new class.

API-6 — The ledger list drops the join, and SOURCE_TYPES lists only Billing records​

jodapp-api#2220 builds this item, in jodapp-api PR #2254.

  • Billing::LedgerEntries::TeamIndexManager drops the join on ads_campaign_placements.
  • Billing::LedgerEntries::TeamBaseSerializer adds description, and drops ads_campaign_id.
  • Billing::LedgerEntries::TeamIndexValidator accepts any class name in source_type.
    • A class name is one or more capitalised words joined by ::.
  • Billing::LedgerEntry::SOURCE_TYPES loses campaign_placement.
  • Update test/domains/billing/ledger_entries/team_index_manager_test.rb for the new fields.

jodapp-web issues​

jodapp-web#1514 builds this item, in jodapp-web PR #1535.

  • Add the deliverable route campaign-placements/:id under ads in app/team.routes.js.
    • Its clientLoader loads the placement with teamAdsCampaignPlacementsApi.show.
    • Then it redirects to /team/ads/campaigns/:ads_campaign_id.
  • LedgerEntrySourceCell in app/domains/billing-ledger-entry/billing-ledger-entry-table.jsx links source_type: 'Ads::CampaignPlacement' to /team/ads/campaign-placements/:source_id.
  • The link text is description.
  • A Billing source shows its own link, such as Invoice #12.
  • An entry with no deliverable route and no Billing source shows its source type and id as plain text.
  • The source type filter keeps Ads::CampaignPlacement as an option.

Manual test plan​

Run these on a local copy of both work branches, with Acme Pte Ltd at 40 placement credits.

  • jodapp-api#2222 runs this plan, then merges the work branches into the phase 3 branches.
#StepExpected
1Submit a campaign with a 30-credit banner and a 20-credit spotlight, and a start date that is too earlyOne 422 with a requested_starts_at error and a placement_credits error
2Fix the date and submit againOne 422: you need 50 placement credits, but you only have 40 available
3Grant Acme 100 credits in the Team Portal, then submit againTwo reserve ledger entries, and Acme has 90 available and 50 reserved
4Open Acme's ledger in the Team Portal, and click a reserveEach reserve shows Ad: Hiring baristas, <placement name>, Weekly, and the click opens the campaign page
5Move ads_campaigns.requested_starts_at of the campaign to the past in a Rails console, then approve the campaign in the Team PortalBoth placements are active, because a late approval starts them at once
6Run Ads::CampaignPlacements::ConsumeReservedCreditsJobThe banner consumes 4 credits and the spotlight consumes 3, and each consume entry shows the description of its placement
7Run the job again within 24 hoursNothing is written
8Open the campaign in the Team Portal, and open the cancel dialogThe banner row shows 26 go back, 0 expire and 4 already used, and the spotlight row shows 17, 0 and 3
9Confirm the cancel with a reasonTwo release ledger entries with the same descriptions, and Acme has 133 available and 0 reserved
10Submit and reject a second campaignThe reject releases its credits, as in step 9
11Submit a campaign for a company with no billing accountOne 500, Sentry reports Errors::InternalServerError as an error, and the system writes nothing

Three steps depend on Ads rules that the table does not explain.

  • Step 5 uses the console, because a submit accepts only a start date at least two days ahead.
    • A placement that is approved on time stays scheduled until its start_time, and the job reads only active placements.
  • Step 6 gives 4 and 3 credits, from round(30 × 1 ÷ 7) and round(20 × 1 ÷ 7).
  • Step 9 needs a reason, because the cancel of a campaign with an active placement returns a 422 without one.

Risks​

RiskWhat we do
The Ads daily job runs twice on the switch day, once from each classAPI-5 removes the old class and changes the schedule in one PR
The migration runs on a table that still has rowsThe migration raises, so run bin/rails billing:reset_phase_1_3_test_data first, as Billing D13 says
The error key changes from base to placement_creditsThe web prints every key, so the employer still sees the message
A product engineer calls a private Billing class againThe boundary search of Design Plan — Backend prints the line in review