Ingen beskrivning
  • TypeScript 99.3%
  • JavaScript 0.4%
  • Dockerfile 0.3%
Hitta en fil
Kodförråd filer (senaste incheckning först)
Filnamn Senaste incheckningsmeddelande Senaste incheckningsdatum
Bitborg Renovate 41b99361ed
Alla kontroller lyckades
ci / ci (push) Successful in 2m53s
chore(deps): update pnpm to v11.29.0 (#213)
2026-11-30 02:36:21 +00:00
.forgejo/workflows docs: fix readme claims that contradict the code (#202) 2026-11-15 11:02:19 +00:00
contract fix(deps): update dependency @trpc/server to v11.29.7 (#210) 2026-11-26 13:34:11 +00:00
drizzle feat: switch a one-time year to automatic renewal, price change notices (#190) 2026-10-19 22:53:20 +00:00
src docs: fix readme claims that contradict the code (#202) 2026-11-15 11:02:19 +00:00
.env.example feat(env): accept a live mollie key (#182) 2026-10-14 11:18:01 +00:00
.gitignore chore: drop private-repo and agent-tool references before going public (#97) 2026-10-05 14:15:14 +00:00
.markdownlint-cli2.jsonc build: add lefthook pre-commit and pre-push hooks (#2) 2026-07-29 12:34:58 +00:00
.prettierignore chore: scaffold bitborg-payment service (roadmap #5) 2026-07-29 12:06:55 +02:00
.prettierrc.json chore: scaffold bitborg-payment service (roadmap #5) 2026-07-29 12:06:55 +02:00
Containerfile chore(deps): update toolchain to v24.22.3 (#205) 2026-11-16 09:31:51 +00:00
drizzle.config.ts feat: bitborg_payment Drizzle schema + initial migration 2026-07-29 13:14:55 +02:00
eslint.config.mjs lint: type-checked eslint rules (#7) 2026-07-29 20:13:36 +00:00
lefthook.json chore(deps): pin sort-package-json instead of pnpm dlx (#171) 2026-10-13 08:25:59 +00:00
LICENSE chore: scaffold bitborg-payment service (roadmap #5) 2026-07-29 12:06:55 +02:00
package.json chore(deps): update pnpm to v11.29.0 (#213) 2026-11-30 02:36:21 +00:00
pnpm-lock.yaml chore(deps): lock file maintenance (#211) 2026-11-30 01:37:54 +00:00
pnpm-workspace.yaml chore(deps): set the pnpm release-age gate explicitly (#206) 2026-11-16 10:22:38 +00:00
README.md docs: fix readme claims that contradict the code (#202) 2026-11-15 11:02:19 +00:00
renovate.json fix(ci): pin the withdrawal test clock and group trpc bumps (#198) 2026-11-05 10:02:43 +00:00
tsconfig.build.json feat: http runtime with mollie checkout, webhook, withdrawal and gapless invoices (#59) 2026-09-30 21:08:47 +00:00
tsconfig.json chore: scaffold bitborg-payment service (roadmap #5) 2026-07-29 12:06:55 +02:00
vitest.config.ts feat: @bitborg/payment-contract skeleton (zod + router types) 2026-07-29 13:29:56 +02:00

bitborg-payment

The billing service for bitborg — subscriptions, VAT/pricing, and entitlements (roadmap #5).

What it does

bitborg-payment owns:

  • a vendor-agnostic PaymentProvider interface, with a single Mollie adapter behind it — application code never talks to the Mollie SDK directly, so swapping or adding a provider later doesn't touch pricing/entitlement logic;
  • pure VAT / pricing / entitlement logic (SE/NO/EU VAT rules, seats, trial → paid transitions);
  • a Drizzle schema + initial migration for its own Postgres database (bitborg_billing in production);
  • the publishable @bitborg/payment-contract package (zod schemas + router types) other services consume.

What runs

pnpm start serves, on PORT:

  • GET /healthz: 200 when Postgres answers.
  • POST /webhooks/mollie: Mollie posts only a payment id. The service re-fetches the payment, records each event once in provider_event and applies it once, so a replayed webhook changes nothing.
  • /trpc/*: the @bitborg/payment-contract router (startCheckout, subscriptionStatus, cancel, withdraw, updateBillingEmail, replaceCard, erase) behind a bearer token.

Present:

  • Mollie hosted checkout for the personal plan, in two ways at the same price, chosen by renewal:

    • auto (default): annual (default) or monthly. It offers only cards, Apple Pay and Google Pay, the methods that leave a card mandate for renewals.
    • none: a one-time annual payment. Mollie's checkout offers cards, Apple Pay and Swish, and the customer picks there. No Mollie customer, mandate or subscription, whichever method pays. Monthly is refused (one_time_needs_annual). The subscription is created with cancelAtPeriodEnd, so the sweep ends it at the period end with no grace. Paying again while the period runs extends it from its end, and the invoice covers the new period from that date. One such payment can be in progress at a time (payment_pending).
    • Both accept an optional locale (sv_SE or en_GB; omitted lets Mollie choose) and an optional cancelUrl (https, same origin as returnUrl; omitted returns a cancelling customer to returnUrl).
  • One Mollie customer per customer: the first renewing checkout creates it and stores its id in customer.provider_customer_ref. Later checkouts reuse it and send the current name and email, as does a billing email change. Migration 0012 fills the column from the newest stored payment method's Mollie customer. Each Mollie subscription description ends in a short subscription id, so a customer's subscriptions differ.

  • Countries: BILLING_SELL_COUNTRIES is the allowlist of countries billing sells to (ISO alpha-2, comma-separated). Unset means Sweden only. startCheckout takes an optional country, else the customer's stored country, else Sweden while Sweden is the only country listed. It refuses an unlisted country (country_not_sold) and a missing country when more than Sweden is listed (country_required). A non-Swedish checkout, one-time or not, offers cards only (no Apple Pay, no Swish) and asks Mollie to accept cards issued in the declared country. If the first payment still arrives with another or an unknown card country, it is refunded and not activated (card country mismatch). A Swedish checkout accepts any card. VAT is the destination country's standard rate (src/vat.ts, all EU-27, plus Norway, provisional), and the price stays the same gross. The service refuses to start when a listed country has no VAT rate.

  • subscriptionStatus.latestCharge reports the newest payment attempt as pending, paid, failed, canceled or expired, so the portal can show the outcome after the return. A subscription whose first payment has not completed reports status incomplete.

    A checkout while an auto-renew subscription is live is refused (already_subscribed). An auto-renew checkout while a one-time period runs switches to automatic renewal: its first payment sets up the mandate and pays the period that starts at the one-time period end, and the Mollie subscription starts one interval later. The one-time subscription is closed, so a one-time extension paid after the switch is refunded. Withdrawal applies to the switch as to a rebuy not started yet: it is refunded in full and access runs to the one-time period end. The switch opens once the one-time purchase's 14-day withdrawal period has passed and no paid one-time year is waiting to start. Until then it is refused (one_time_in_withdrawal_period), so the one-time purchase stays withdrawable.

    A past due subscription the provider has cancelled or suspended does not count: a checkout is accepted, and its payment closes the old subscription and starts the new period at the old period end. The consumer's request to start during the withdrawal period is required and stored. The billing name and email come from the caller (the portal's signed-in session); the service reads no person data from Keycloak. subscriptionStatus reports renewal and paidUntil, and nextCharge (day, amount, card or Apple Pay, last four digits) while an auto-renew subscription is active and not cancelled. The portal sends the renewal reminders from it. card (brand, last four digits) is the live subscription's payment method, past due included, and null for a one-time payment.

  • On payment: the renewal is scheduled as a Mollie subscription starting the day after the paid period (Amsterdam time, Mollie's calendar: an assumption, Mollie's docs only say a missing day of month falls back to the last day), tier_pro is granted in Keycloak (ADR 0017), and the invoice is issued with a gapless number as the last step of the transaction. A second paid checkout for a customer who is already subscribed is refunded, never activated. So is a paid auto-renew checkout that left no mandate to renew from. A one-time payment needs no mandate.

  • Renewals extend the period and are invoiced. A renewal arriving after cancellation is refunded. A renewal paid for another amount than the subscription's last charge is not applied. It is recorded in reconcile_orphan and handled as an orphan below. Resolve it by hand in the Mollie dashboard: extend the period locally or refund the payment, then close the orphan row as described below. A renewed period ends the day before Mollie's next charge day, read from the Mollie subscription after each renewal. After a successful retry Mollie counts the next charge from that payment. When the read fails, the period runs one interval from this renewal's charge day (the last day of a shorter month), which is Mollie's schedule while no retry moves it.

  • Replace the card: replaceCard returns a hosted page for a small first payment (1 SEK) on the customer's existing Mollie customer. It works while the subscription is active or past_due, renews automatically and the provider still has the subscription (else not_renewing, no_live_subscription, subscription_ended). One check may be open per subscription (payment_pending); one never completed is dropped after an hour. The check is a card_replacement row, not a charge: no invoice, period or VAT. When it is paid with a usable mandate, the Mollie subscription is moved to the new mandate, payment_method gets a new row, the old mandate is revoked and the check is refunded through the usual refund row. The subscription's status is left alone: a past_due one becomes active when Mollie's next attempt on the new mandate is paid. A check that cannot be applied (payment failed, invalid mandate, card country mismatch, the subscription ended meanwhile, the provider refused the move, or the start had expired) is refunded, its new mandate is revoked and the subscription is unchanged. It is logged as [card] card replacement <id> on <payment id> not applied: <why>. A check whose provider ref write was lost is matched by the cardReplacementId the payment carries. Only a failure that is not a refusal (a timeout, a 5xx) is retried: the webhook fails and Mollie or the reconcile pass sends it again.

  • Mandate check: when a first payment is paid, the adapter reads its mandate. The card expiry goes to payment_method.exp (YYYY-MM-DD) and the mandate's status to payment_method.status. Only valid (cards) and pending count as usable. A paid auto-renew checkout whose mandate is invalid is refunded and not activated, as one with no mandate is, and logged as paid but its mandate is not usable. A mandate that cannot be read is taken as valid, with no expiry stored.

  • Mandates: when a chargeback, a withdrawal or a full dashboard refund ends a subscription, its card mandate is revoked at Mollie, so nothing stays chargeable. So is the mandate of a paid checkout that is refunded without activating (duplicate, after a withdrawal, card country mismatch). payment_method.status goes valid, revoking, invalid. A revoke that fails is logged as [mandate] <id> not revoked and retried by the sweep. A cancellation at period end leaves the mandate alone.

  • Cancellation stops renewal at once; access runs to the end of the paid period. A sweep every 10 minutes ends subscriptions whose period is over (at once when cancelled, after an 8-day grace when no renewal came), retries refunds not yet issued and settles pending ones.

  • Every way access ends (sweep, withdrawal, chargeback) removes tier_pro and puts the user back in tier_participant, unless a live paid subscription or complimentary grant still gives pro. A failed tier_participant write is logged as [revoke] could not add tier_participant and does not undo the revoke: the reconciler treats a user with no tier as a participant.

  • Dunning: a failed renewal marks the subscription past_due. Mollie retries it daily, up to 5 times, and cancels its subscription when the retries run out. Some failure reasons cancel it after 3 attempts or at once. The last attempt is assumed to land within 7 days of the period end (Mollie's docs say only up to 5 daily retries, varying by method and reason), so the grace is 8 days. It counts Amsterdam calendar days and ends at the end of the eighth day after the period end. Access continues through the grace; subscriptionStatus reports graceEndsAt so the portal can warn the customer. A failure reported 3 or more days before the period end is a stale delivery and is ignored. A later successful payment makes it active again. At the end of the grace the sweep revokes tier_pro and cancels the Mollie subscription. A renewal paid after that is refunded, and the customer can check out again.

  • Mollie sends no webhook when it cancels or suspends a subscription, e.g. after the mandate is revoked. Once an hour the sweep reads the Mollie subscription of each active auto-renew subscription from the portal's first reminder (30 days before an annual period end, 7 before a monthly one) until the grace ends. A cancelled or suspended one is marked past_due and follows the dunning path above, so nextCharge is null.

  • Reconciliation after each sweep: every Mollie payment from the last 14 days that is paid but has no settled local charge is replayed through the webhook path. That repairs a first payment whose tier_pro grant kept failing past Mollie's webhook retries, and a checkout whose local charge write was lost after Mollie accepted the payment (matched by the subscription id in the payment's metadata and the recorded amount). A replayed checkout for a customer who has a live subscription, or any subscription started after it, is refunded and its Mollie subscription cancelled, as a second paid checkout always is.

  • A payment that is still unmatched, or that was refunded or charged back before it was applied, is logged once, when first recorded in reconcile_orphan, as [reconcile] <payment id> is paid at the provider with no settled local charge and left alone: no refund, cancellation or grant is automatic. The row survives restarts and stays listed after the 14-day window, but is no longer replayed there. Every pass also logs [reconcile] <n> unresolved orphan(s), oldest <payment id> since <time>; needs manual review while any is open. Review the payment in the Mollie dashboard. Either refund it there and cancel the customer's Mollie subscription that carries the same subscriptionId metadata, or fix the local rows and let the next pass replay it. A row resolves itself once the payment has a settled local charge. After the review, close one by hand: UPDATE reconcile_orphan SET resolved_at = now() WHERE payment_ref = '<payment id>';

  • Withdrawal within 14 days of the first purchase (Swedish calendar, moved past weekends and public holidays): revokes, stops renewal and refunds the unused share of the first period. A one-time period paid early that has not started yet is refunded in full. A one-time payment that lands after a withdrawal is refunded.

  • Chargeback on a payment that paid for a period: tier_pro is revoked, the Mollie subscription is cancelled and the subscription ends at once. Each chargeback is recorded once in chargeback, by its Mollie id. The invoice stays. A withdrawal of a charged-back purchase is refused (charged_back), and a refund claimed but not yet sent is cancelled. Once every chargeback on the subscription is reversed while the paid period runs, access is restored to the end of that period, and a cancelled refund is sent again. The renewal stays cancelled. A first payment with an open chargeback is never applied. Reconciliation also replays each chargeback from the last 14 days not yet recorded locally, and re-fetches the payment of each open chargeback from the last 180 days (up to 100) to see a reversal whose webhook was lost. Mollie sends no payment webhook when a chargeback is reversed, so a chargeback still open after 180 days is flagged once for review (open past the reversal window), which reopens a review closed earlier. Check the dispute in the Mollie dashboard.

  • A refund the provider moves to failed (for example the customer closed the bank account) cannot be issued again: its idempotency key finds the failed one. It is logged once, on the move, as [reconcile] refund <id> failed at the provider; customer still owed; needs manual review. Act on it promptly. Check the payment's refunds in the Mollie dashboard first. If a new dashboard refund is not possible or fails, ask the customer for new account details and pay by bank transfer. Note the manual payment on the Mollie payment so nobody pays twice. Leave the failed row as it is, apart from the review mark. A refund that fails while a chargeback is open is not logged: the bank already returned the money. Until a failed refund is reviewed, every reconcile pass also logs [reconcile] <n> failed refund(s) unreviewed, oldest <id> since <time>; needs manual review (one under an open chargeback is left out). After the customer has been paid: UPDATE refund SET reviewed_at = now() WHERE id = '<refund id>';

  • refund.provider_status keeps Mollie's own refund state (queued, processing, canceled, ...) beside the three-state status. A refund the dashboard cancelled is logged as canceled at the provider; customer still owed instead of failed, and is reviewed the same way. A refund webhook settles the row with the same update the sweep uses. A refund still pending 24 hours after it was claimed, for example queued for lack of balance, makes every reconcile pass log [reconcile] <n> refund(s) pending over 24 h, oldest <id> since <time>, provider status <state>; needs manual review. Top up the Mollie balance or look at the refund in the dashboard.

  • Never refund a settled charge in the Mollie dashboard. Use the withdrawal flow, which revokes, stops renewal and records the refund. A refund seen at the provider that matches no local refund is logged once per refund as [reconcile] refund <id> on <payment id> has no local record; needs manual review. If the payment is refunded in full and we issued no refund of our own on it (apart from failed ones), access ends and the renewal stops, but only when that charge pays the current period. A full refund of an older period is logged and changes nothing else. A partial refund changes nothing. A dashboard refund that is still pending already ends access, even if it later fails. Reconciliation re-reads refunded payments created in the last 14 days, so a lost webhook is caught.

  • A withdrawal refund the provider refuses, for example because the payment is already refunded, is marked failed and not retried. Only the provider's "already refunded" and "above the refundable amount" answers count as refused; any other error is retried. It is logged once as [reconcile] refund <id> refused by the provider: <why>; needs manual review, unless a chargeback is open. Settle it by hand.

  • A chargeback on refunded money or on a subscription already ended, one with an amount not in SEK, a reversal that cannot restore access or that lands on a payment never applied, or a re-owed refund the provider fails, is logged as [reconcile] chargeback <id> on <payment id>: <why>; needs manual review. While any is open, every reconcile pass also logs [reconcile] <n> unreviewed chargeback(s), oldest <id> since <time>; needs manual review. After the review in the Mollie dashboard: UPDATE chargeback SET reviewed_at = now() WHERE provider_ref = '<chargeback id>';

  • Chargeback evidence, kept per payment so a dispute is answered from stored data alone (chargebackEvidence in src/evidence.ts, keyed by the Mollie payment id):

    • charge: the consent shown at checkout (consent_text_hash, consent_shown_at, consent_language, from the optional consent input of startCheckout), and once paid paid_at, mandate_ref, card_security (3dsecure as Mollie reports it, card payments only) and card_country (the card issuer's country, card payments only). billing_country is the country declared at checkout, copied to renewals from the customer. consent_text holds each distinct sentence once, keyed by its sha256 (hex). Renewals carry no consent of their own: the first checkout charge holds it.
    • subscription: the renewal choice and the interval.
    • cancellation: each cancel or withdrawal, with when it was requested and when it takes effect.
    • charge rows are the renewal history: date, amount and mandate of each.
    • chargeback.evidence: chargebackEvidence for the payment, stored when the chargeback is first recorded and never overwritten. Read it with SELECT evidence FROM chargeback WHERE provider_ref = '<chargeback id>';. It is null, with an evidence not stored review, if building it failed. The needs manual review line says when the evidence is on the row.
    • All of this evidence (consent texts, charge fields, cancellation rows and chargeback snapshots) is kept with the invoice records (see Data).
    • chargebackEvidence is a library function; the operator reads the snapshot on the chargeback row. Charges paid before migration 0009 have no paid_at, mandate_ref or card_security, and charges before migration 0011 have no billing_country or card_country. None are backfilled.
  • Renewals are merchant-initiated and run without 3-D Secure, so they carry no liability shift. Only the first payment is authenticated. This is an accepted risk.

  • Every API error carries data.reason (see ErrorReasonSchema in the contract).

Absent:

  • Business status, VAT number and VIES in the contract. Checkout is for consumers only, so no address is collected (simplified invoice). A business pays destination VAT.
  • VAT rules for the UK, Switzerland and Iceland. Only Sweden, Norway and the EU-27 are priceable.
  • The org-seat plan and add-ons.
  • Invoice PDFs (#161) and credit notes (#63). Both are issued by hand at launch. The gapless number on the invoice row is an internal sales reference, not a customer invoice number.
  • Reminder emails for a failed renewal. The portal owns mail and reads graceEndsAt.
  • Mail for a price change notice. cli.js price notice prints the recipients; the operator sends the mail and marks it with cli.js price sent.
  • The pro-rata refund on termination after a price change notice.
  • A new card for a subscription the provider has already cancelled (subscription_ended). Such a customer checks out again after the grace.
  • Row-Level Security (a restricted application role plus a BYPASSRLS system role) and a deploy role. Designed, not built.
  • An immutable audit log of charge, refund and entitlement changes. Designed, not built. provider_event keeps the raw webhook payloads, which is not the same thing.

Org billing is decided: a flat org add-on, with members holding their own accounts. It is not sold at launch (#15). The code still carries a per-seat org_seat plan with a seat_assignment table (src/pricing.ts, src/db/schema.ts, the contract's PlanSchema). Nothing is built for either. Remove or keep them when org billing is built.

Complimentary subscriptions

An operator can give a user pro access for free, for a friend or a tester, and withdraw it later. A grant is a row in complimentary: the user, a reason, who granted it, when, and an optional end date. No end date means it runs until withdrawn. It has no customer, charge, invoice, VAT or provider object, and it is kept apart from subscription, which describes paid periods.

  • Grant: adds tier_pro and removes tier_participant, the same grant a paid activation makes, which kicks a reconcile. A second grant for the same user returns the live one unchanged and repeats the Keycloak write. A user with a live paid subscription is refused.
  • Withdraw now, or at the end date by the sweep (every 10 minutes, with payments disabled too): revokes as an ended paid subscription does. tier_pro is removed unless a live paid subscription still gives it, and the user goes back to tier_participant. No refund, invoice or credit note. A Keycloak failure rolls the change back. A withdrawal can be retried, and the sweep retries on its next pass.
  • A complimentary user can check out as normal. The grant stays live next to the paid subscription, so a later cancellation, withdrawal or chargeback of the payment leaves the user on pro. Only a withdrawal of the grant or its end date ends it (end_reason is withdrawn or expired). subscriptionStatus reports paid subscriptions only.
  • Grants and revokes for one user take a transaction-scoped advisory lock on the username, so a revoke never misses a payment or grant that commits at the same time.

There is no HTTP endpoint for this. Run the CLI inside the container, which holds the database and Keycloak credentials:

podman exec bitborg-billing node dist/src/cli.js comp grant <username> --reason "tester" --by <operator> [--until YYYY-MM-DD]
podman exec bitborg-billing node dist/src/cli.js comp list [--all]
podman exec bitborg-billing node dist/src/cli.js comp withdraw <username>

--until is the last day of access, Stockholm time. list prints one tab-separated line per grant: username, granted at, end, state, granted by, reason. --all includes ended grants. Usernames are matched as Keycloak stores them, in lower case, and the user must exist in Keycloak.

The Keycloak write happens before the database commit. If a grant fails after printing a Keycloak error, run comp list and run the grant again. If the user is in tier_pro with no live grant, remove them from tier_pro by hand.

Backfill for users given tier_pro by hand before this existed: list the members of the tier_pro group in the Keycloak admin console, leave out paying users (the grant refuses them), and run for each of the rest:

podman exec bitborg-billing node dist/src/cli.js comp grant <username> --reason "given by hand before complimentary records" --by <operator>

Price change

The Terms promise renewing subscribers 30 days' email notice before a price change, and a pro-rata refund if they terminate because of it. Prices live in src/pricing.ts.

  1. Release the new price in PLANS. New checkouts pay it from then on.

  2. List the notices for every renewing personal subscriber on that interval who pays another amount. The amount must equal the PLANS price for the interval, or the command refuses:

    podman exec bitborg-billing node dist/src/cli.js price notice <annual | monthly> <amount in öre> <YYYY-MM-DD>
    

    The date is the first day at the new price, in Amsterdam time (Mollie's calendar). It must be at least 30 days ahead. One line per notice is printed: notice id (dry-run until recorded), subscription id, billing email, old amount, new amount, effective time. Nothing is written.

  3. Run it again with --apply to record the notices, all in one transaction. A later run skips subscribers who already have an open notice, so run it again after a checkout that was in flight during step 1.

  4. Send the notice mail to each printed address, with the new price and the date. Then mark it sent, for one notice or every unsent one:

    podman exec bitborg-billing node dist/src/cli.js price sent <notice id | all>
    

    A notice can only be marked sent 30 days or more before its change; a later one is printed as late, will not apply. The price_notice table enforces both 30-day minimums.

  5. From the effective time the sweep sets the new amount on each Mollie subscription (PATCH /subscriptions/{id}) and closes the notice as applied. A notice whose subscriber cancelled, withdrew or was stopped by Mollie meanwhile closes as ended with no update. A notice never marked sent closes as unsent with no update, logged as [price] notice <id> on subscription <id> not applied: ...; needs manual review. Record a new notice with a later date for it. A failed update is logged as [price] notice <id>: <why> and retried on the next sweep.

price cancel <notice id> closes an open notice as canceled without applying it.

A renewal at the new amount is accepted once the notice is applied, with the VAT split of the new amount at the purchase's rate. One at the old amount stays accepted, for a payment Mollie made before the update: a charge Mollie creates on the effective day before the sweep has run is at the old price, in the customer's favour. Any other amount is parked as an orphan. nextCharge reports the new amount for a charge on or after the effective date once the notice is marked sent.

Provider choice

Mollie is a Dutch company and runs on Google Cloud, so it sits outside guiding principle 1 (hosted in Sweden, no US-owned infrastructure). It receives payment metadata only: no card data (see below). It was accepted because no EU-hosted provider met the need. The vendor-neutral PaymentProvider interface (src/provider/types.ts) is the exit: a second adapter replaces Mollie without touching pricing or entitlement logic.

Recurring billing uses Mollie managed subscriptions. The service has no scheduler of its own for renewals: Mollie charges, the webhook records it. The only timer is the sweep that ends expired subscriptions and settles refunds. Retries of a failed renewal are Mollie's too.

Sales report

cli.js sales <YYYY-Qn | YYYY> [--eur-rate <SEK per EUR>] prints tab-separated lines from the invoices issued in the period, on Stockholm calendar days:

podman exec bitborg-billing node dist/src/cli.js sales 2026-Q4 --eur-rate 11.2345

Rows are grouped by country, basis, rate and currency, in sections: oss (consumer sales to other EU countries), oss-total (one line per currency: the EU-wide threshold check, so use the YYYY form for the annual figure), reverse-charge (one row per buyer VAT number), domestic, other. Amounts are minor units. refunds lists succeeded refunds settled in the period, with the VAT part following the invoice they reduce. --eur-rate is the ECB rate the operator looks up. It adds EUR cents for SEK rows, half up per group. No network call is made. Rows in another currency stay unconverted.

Data

Invoices and payment records are kept until the end of the seventh year after the calendar year in which the financial year ended (bokföringslagen (1999:1078), 7 kap. 2 §), also after account deletion. Records that support an OSS return (charge, invoice, customer.country) are kept for ten years from the end of the year of the sale. Foreign keys do not cascade, so deleting a customer fails while charges or invoices reference it.

On account deletion the portal calls erase with the username, before the identity is deleted. It:

  • sets kanidm_ref to erased:<customer id>, so a username registered again later gets a new customer;
  • sets billing_name and billing_email to erased and clears vat_number and the address fields;
  • empties payment_method.provider_data and clears brand, last4 and exp;
  • deletes the user's complimentary rows (no money, so nothing to keep), revoking a live grant;
  • sets customer.erased_at, then deletes the provider's customer record and sets provider_erased_at.

The customer id, country, provider_customer_ref, charges, invoices (with their customer snapshot) and provider_event are kept. If the provider deletion fails, the local erase stays and an [erase] customer <id> line is logged. Erase the same customer id again to retry it; nothing else changes on a repeat. By username, a repeat finds no customer and returns null. It is refused with live_subscription while a subscription is active or past due, and with payment_pending while a payment, card replacement, refund or mandate revocation is still settling. Those settle by themselves, so retry later. It works with payments disabled. An operator runs the same step with:

podman exec bitborg-billing node dist/src/cli.js customer erase <customer id | username>

Before live keys

The service accepts a live_ Mollie key. Set one in production only after all of these are done:

  • The Swedish VAT rule is confirmed. The EU and Norway rules stay provisional (see src/vat.ts).
  • The business is registered for VAT in Sweden. Launch sells to Sweden only.
  • The Mollie account review (KYC) is complete.
  • The SAQ A self-assessment is completed and filed. Mollie cannot confirm SAQ A for a merchant.

Test mode

  • Mollie cancels a test subscription by itself after 10 payments.
  • SEK test payments work. Mollie's note that test mode is EUR-only covers the magic failure amounts only (probed 2026-10-05).
  • A one-time payment opens Mollie's test checkout, where the tester picks the outcome (paid, failed, canceled, expired) for any method. Only recurring payments skip it. A processed test card payment reports Mastercard whichever test card number is entered.

Migrations

The image ships drizzle/ and runs them with the drizzle-orm migrator (no drizzle-kit at runtime):

podman run --rm -e DATABASE_URL=... <image> node dist/src/migrate.js

Run it before starting a new image. Locally: pnpm build && pnpm migrate.

Card-data boundary (SAQ-A)

This service never stores or transmits card data. Checkout happens on Mollie's hosted payment page; bitborg-payment only ever sees Mollie's tokenised references (payment/subscription IDs, status webhooks) via its Mollie adapter — keeping the PCI-DSS scope at the lightest self-assessment tier, SAQ-A.

Configuration

See .env.example: MOLLIE_API_KEY, PAYMENTS_ENABLED (defaults off; the kill switch for every money-moving path), BILLING_SELL_COUNTRIES (optional; countries sold to, default SE), DATABASE_URL, KEYCLOAK_URL / KEYCLOAK_REALM / KEYCLOAK_CLIENT_ID / KEYCLOAK_CLIENT_SECRET, PUBLIC_URL (webhook base), PAYMENT_API_TOKEN, PORT, and the optional RECONCILE_TRIGGER_URL / RECONCILE_TRIGGER_TOKEN. Never commit a real value. Secrets come from the environment (Ansible Vault in production) only.

With payments enabled, the service checks at start that the key works and that creditcard, applepay and swish are enabled on the profile, and exits if not.

MOLLIE_API_KEY is optional while payments are disabled. Without it the service and the CLI start with no payment provider: every provider call fails, and only complimentary grants and subscriptionStatus work. PUBLIC_URL is then not read either. A set key must start with test_ or live_, whether payments are enabled or not.

KEYCLOAK_CLIENT_* are the bitborg-billing client credentials. That client may manage tier_pro and tier_participant membership and map the paid entitlement roles, nothing else. Users are found by exact username and the call fails if there is not exactly one match.

When both RECONCILE_TRIGGER_* variables are set, every successful tier_pro write (grant, revoke, withdrawal, sweep) is followed by a fire-and-forget POST to the reconcile auth shim (ADR 0037), bearer token only, 3 s timeout, and logs [reconcile-trigger] kick reason=payment. A failure is logged without the token and never affects the money path. When unset, the reconcile timer applies the change.

Development

pnpm install
pnpm test         # vitest; set TEST_DATABASE_URL to also run the Postgres tests
pnpm lint         # eslint + prettier
pnpm typecheck
pnpm build        # → dist/
pnpm dev          # run from source

Deployed as a pinned container image (built + pushed by Forgejo Actions on a v* tag); consumed by bitborg-infra, with Renovate opening the bump PR — the same mechanics as the other bitborg services (ADR 0033). No :latest. Release order: merge the version bump, verify main and package.json, then tag. A tag pushed before the bump merges builds the wrong commit.

Licence

AGPL-3.0.