Billing Spend Interface — Implementation Plan
This page splits the Billing spend interface into issues for jodapp-api and jodapp-web, in build order.
- The rules they implement are in Billing D18 — Product domains spend credits only through SpendService.
- The methods and the errors are on Billing interface for product domains.
- Every flow is described step by step on Billing Spend Interface — Use Cases.
Where the code goes
The Billing lot code is not on main yet, so this work has its own branches.
| Repo | Base branch for these PRs |
|---|---|
jodapp-api | feature/backend-billing-interface, which merges into feature/backend-billing-phase-3 |
jodapp-web | feature/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
mainwith the rest of the Billing lot code.
- They ship to
- Imam cut the work branches from the tips of jodapp-api PR #2207 and jodapp-web PR #1513.
- The first
jodapp-apiPR targetsfeature/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.
| Work | Owner | What it does | Merges before |
|---|---|---|---|
| jodapp-api PR #2206 | Imam | Every caller reads the own account from org_company.billing_account, because every company has one account | API-2, because Billing::SpendService reads the same association |
| jodapp-api#2204, built in jodapp-api PR #2207 | Imam | Ads::Campaigns::TeamShowManager calls no Billing class, and the Team Portal campaign page reads Billing endpoints | API-6, because API-6 removes the SOURCE_TYPES entry that the show code names |
| jodapp-api PR #2203 | Lintang | The daily consume job writes each placement in one transaction | API-2 and API-5, because they change the same files |
| jodapp-api PR #2202 | Lintang | A release into an expired lot writes the expire entry that recognises the revenue of the expired credits | API-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_entriesin the filejodapp-api/docs/db/billing.dbml, as Design Plan — Database shows. - The column is
NOT NULL, with the CHECKbtrim(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 asCareers::JobListingPeriod.
- A spend's source is the deliverable that the product passes to
- 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-interfaceuntil its method issue merges.- So no product code ever calls a method that only raises.
| Issue | PR | Builds |
|---|---|---|
| jodapp-api#2211 | jodapp-api PR #2224 | The skeleton, the open-transaction check, and Billing::Error and Billing::InsufficientCreditsError in full |
| jodapp-api#2212 | jodapp-api PR #2225 | Billing::SpendValidator, and the Ads submit validators run it |
| jodapp-api#2213 | jodapp-api PR #2226 | reserve, and the Ads submit managers call it |
| jodapp-api#2214 | jodapp-api PR #2227 | release, and the Ads cancel and reject code calls it |
| jodapp-api#2215 | jodapp-api PR #2235 | consume_reserved with a target total, and the daily consume job calls it |
| jodapp-api#2216 | jodapp-api PR #2237 | consume_now |
- Add the two public classes, as Billing interface for product domains describes.
Billing::SpendServicereads the own account withorg_company.billing_account, and the entitlement frominstrument:.- Then it calls
EntitlementLotService, and it never opens a transaction.
- Then it calls
- Build the four write methods
reserve,consume_now,consume_reservedandrelease, each with a Sorbetsig. - Each write method raises on its first line when
ActiveRecord::Base.current_transaction.open?is false. - Each write method returns nothing, with a
voidsig. consume_nowwritesidempotency_key: "consume_now_<source_type>_<source_id>".- A missing balance row counts as 0 units available, so
consume_nowraisesBilling::InsufficientCreditsError.
- A missing balance row counts as 0 units available, so
consume_reservedtakestarget_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::SpendServicehas no read method, because a page reads Billing endpoints.EntitlementLotService.reserveand the direct consume takedescription:, and save it on the ledger entry.EntitlementLotService.consumeandreleasecopydescriptionfrom the reserve entry.- Billing writes the description of its own entries, such as a
:grantfrom an invoice and an:expire. - Add
app/domains/billing/error.rbandapp/domains/billing/insufficient_credits_error.rb, one class per file.Billing::Error < Errors::UnprocessableContentError, for now.Billing::InsufficientCreditsError < Billing::Error, with thecodeandtitleofBilling::Error::DEFINITIONS.fetch(:not_enough_credits).Billing::Error::DEFINITIONSis one frozen hash ofDataobjects, each with acodeand atitle.Billing::Error::DEFINITIONSholdsnot_enough_creditsandbilling_account_missing.
- The parent of
Billing::ErrorbecomesErrors::BaseErrorwhenApplicationControllermaps each error class to its HTTP status.- Billing interface for product domains — Future end state holds that design.
EntitlementLotServiceraisesBilling::InsufficientCreditsErrorunder the key<instrument>_credits, such asplacement_credits.Billing::SpendServiceraisesErrors::InternalServerErrorwhenorg_company.billing_accountisnil.- Every company is created with its own account, so a
nilaccount is a data bug. - The error carries the
codeandtitleofBilling::Error::DEFINITIONS.fetch(:billing_account_missing).
- Every company is created with its own account, so a
Billing::SpendValidatorraisesErrors::InternalServerErrorin 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
EntitlementLotServiceprivate to Billing in its class comment. - Tests in
test/domains/billing/cover these cases:- The validator passes with enough credits.
- The validator raises
Errors::InternalServerErrorwhenunitsis 0 or less. - The validator fails under
placement_creditswith too few credits. - The validator,
reserveandconsume_nowraiseErrors::InternalServerErrorwhenorg_company.billing_accountisnil. - Each write method raises when no transaction is open.
reserveandconsume_nowsave the description.consume_reservedandreleasecopy the description from the reserve entry.consume_reservedwith a target that the deliverable already reached does nothing, and a lower target raises.consume_nowwrites its key, and a second call for the same deliverable raisesErrors::InternalServerError, also when the balance is 0.reserveandconsume_nowraiseBilling::InsufficientCreditsErrorwhen 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::EmployersSubmitValidatorandTeamSubmitValidatorrunBilling::SpendValidatorwith the campaign total.- They merge its errors with
errors.merge!, and they stop readingorg_company.billing_account,EntitlementandEntitlementBalance.
- They merge its errors with
Ads::Campaigns::EmployersSubmitManagerandTeamSubmitManagercallBilling::SpendService.reserveper placement, inside their transaction.- Add the constant
BILLING_LEDGER_ENTRY_DESCRIPTIONtoAds::CampaignPlacement.- The managers fill it with
format, so the text readsAd: Hiring baristas, Homepage banner, Weekly.
- The managers fill it with
- 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,TeamCancelManagerandRejectServicecallBilling::SpendService.release(deliverable: campaign_placement).- They stop looking up the placement
Billing::Entitlement.
- They stop looking up the placement
- 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::ConsumeEntitlementCreditsJobtoAds::CampaignPlacements::ConsumeReservedCreditsJobinapp/domains/ads/campaign_placements/consume_reserved_credits_job.rb. - Keep the Ads daily formula, and pass its result as
target_units_consumed:toBilling::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
StandardErrorfor 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
StandardErrorrescue reports it.
- A placement with no reserve entry makes Billing raise a plain error, so the
- Change
config/sidekiq_scheduler.ymlin 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::TeamIndexManagerdrops the join onads_campaign_placements.Billing::LedgerEntries::TeamBaseSerializeraddsdescription, and dropsads_campaign_id.Billing::LedgerEntries::TeamIndexValidatoraccepts any class name insource_type.- A class name is one or more capitalised words joined by
::.
- A class name is one or more capitalised words joined by
Billing::LedgerEntry::SOURCE_TYPESlosescampaign_placement.- Update
test/domains/billing/ledger_entries/team_index_manager_test.rbfor the new fields.
jodapp-web issues
WEB-1 — The ledger table links each spend to its deliverable route
jodapp-web#1514 builds this item, in jodapp-web PR #1535.
- Add the deliverable route
campaign-placements/:idunderadsinapp/team.routes.js.- Its
clientLoaderloads the placement withteamAdsCampaignPlacementsApi.show. - Then it redirects to
/team/ads/campaigns/:ads_campaign_id.
- Its
LedgerEntrySourceCellinapp/domains/billing-ledger-entry/billing-ledger-entry-table.jsxlinkssource_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::CampaignPlacementas 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.
| # | Step | Expected |
|---|---|---|
| 1 | Submit a campaign with a 30-credit banner and a 20-credit spotlight, and a start date that is too early | One 422 with a requested_starts_at error and a placement_credits error |
| 2 | Fix the date and submit again | One 422: you need 50 placement credits, but you only have 40 available |
| 3 | Grant Acme 100 credits in the Team Portal, then submit again | Two reserve ledger entries, and Acme has 90 available and 50 reserved |
| 4 | Open Acme's ledger in the Team Portal, and click a reserve | Each reserve shows Ad: Hiring baristas, <placement name>, Weekly, and the click opens the campaign page |
| 5 | Move ads_campaigns.requested_starts_at of the campaign to the past in a Rails console, then approve the campaign in the Team Portal | Both placements are active, because a late approval starts them at once |
| 6 | Run Ads::CampaignPlacements::ConsumeReservedCreditsJob | The banner consumes 4 credits and the spotlight consumes 3, and each consume entry shows the description of its placement |
| 7 | Run the job again within 24 hours | Nothing is written |
| 8 | Open the campaign in the Team Portal, and open the cancel dialog | The banner row shows 26 go back, 0 expire and 4 already used, and the spotlight row shows 17, 0 and 3 |
| 9 | Confirm the cancel with a reason | Two release ledger entries with the same descriptions, and Acme has 133 available and 0 reserved |
| 10 | Submit and reject a second campaign | The reject releases its credits, as in step 9 |
| 11 | Submit a campaign for a company with no billing account | One 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
scheduleduntil itsstart_time, and the job reads onlyactiveplacements.
- A placement that is approved on time stays
- Step 6 gives 4 and 3 credits, from
round(30 × 1 ÷ 7)andround(20 × 1 ÷ 7). - Step 9 needs a reason, because the cancel of a campaign with an
activeplacement returns a 422 without one.
Risks
| Risk | What we do |
|---|---|
| The Ads daily job runs twice on the switch day, once from each class | API-5 removes the old class and changes the schedule in one PR |
| The migration runs on a table that still has rows | The 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_credits | The web prints every key, so the employer still sees the message |
| A product engineer calls a private Billing class again | The boundary search of Design Plan — Backend prints the line in review |