@hjam91/billing 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/config.d.ts CHANGED
@@ -69,10 +69,23 @@ export interface PlanSpec {
69
69
  items?: Record<string, ItemSpec>;
70
70
  /** 0.10: what the quantity counts ("students"), shown on the pricing page. */
71
71
  unit?: string;
72
+ /**
73
+ * 0.12: the Stripe product tax code of the plan's product (txcd_10103001 = SaaS, business use). Stripe Tax and
74
+ * Managed Payments (on by default for new Stripe accounts; Stripe is the merchant of record and refuses a Checkout
75
+ * whose product has no tax code) compute tax from it. Changing it updates the product; it is never a new price.
76
+ */
77
+ tax_code?: string;
78
+ /** 0.12: 'exclusive' (tax added on top of the price) or 'inclusive' (tax inside it), on every price the kit makes for the plan. */
79
+ tax_behavior?: 'exclusive' | 'inclusive';
72
80
  }
73
81
  export interface BillingConfig {
74
82
  automatic_tax?: boolean;
75
83
  collect_tax_id?: boolean;
84
+ /**
85
+ * 0.12: Stripe Managed Payments (Stripe as merchant of record: tax, disputes, support). Every subscription and
86
+ * one-time Checkout asks for it; automatic_tax / collect_tax_id are then ignored; plans need a tax_code.
87
+ */
88
+ managed_payments?: boolean;
76
89
  collection_method?: 'charge_automatically' | 'send_invoice';
77
90
  days_until_due?: number;
78
91
  features?: Array<{
package/dist/react.d.ts CHANGED
@@ -237,10 +237,14 @@ type Draft = Record<string, {
237
237
  amount?: string;
238
238
  unit: string;
239
239
  hidden: boolean;
240
+ tax_code?: string;
240
241
  }>;
242
+ /** A Stripe product tax code (txcd_ and eight digits); the SaaS one is the usual choice for an app. */
243
+ export declare const TAX_CODE: RegExp;
244
+ export declare const TAX_CODE_SAAS = "txcd_10103001";
241
245
  /** Validates a draft the way the service will (so the message appears before a round trip). Returns the problem in words, or null. */
242
246
  export declare function pricingDraftProblem(plan: string, d: Draft[string]): string | null;
243
- /** The config document a draft turns into (only prices, units and hidden flags change; everything else is carried over). */
247
+ /** The config document a draft turns into (only prices, units, tax codes and hidden flags change; everything else is carried over). */
244
248
  export declare function pricingDraftToConfig(config: BillingConfig, draft: Draft): BillingConfig;
245
249
  /**
246
250
  * An unstyled editor for the app's plans: one card per plan; a tiered plan's rows (from, up to, price) can be
package/dist/react.js CHANGED
@@ -411,6 +411,9 @@ export function BillingPanel(props) {
411
411
  setPreview(null); }), button('Dismiss preview', () => setPreview(null))) : null, ...subscriptions.filter((s) => s.scheduled_change).map((s) => h('section', { key: s.id, className: 'bk-scheduled' }, h('p', null, `Scheduled: ${s.scheduled_change.plan ?? s.plan ?? 'Subscription'}${s.scheduled_change.quantity != null ? ` × ${s.scheduled_change.quantity}` : ''}${s.scheduled_change.effective_at ? ` on ${fmtDate(s.scheduled_change.effective_at, props.locale)}` : ' at renewal'}`), canManage ? button('Cancel scheduled change', () => b.cancelScheduledChange({ subscription_id: s.id })) : null)), ...subscriptions.filter((s) => s.invoice).map((s) => h('p', { key: `invoice:${s.id}`, className: 'bk-invoice' }, s.invoice.due_at ? `Invoice due ${fmtDate(s.invoice.due_at, props.locale)}. ` : 'Invoice available. ', s.invoice.hosted_invoice_url ? h('a', { href: s.invoice.hosted_invoice_url, target: '_blank', rel: 'noopener noreferrer' }, 'View and pay invoice') : null)), canManage && b.offers.length ? h('section', { className: 'bk-offers' }, h('h3', null, 'Available offers'), ...b.offers.map((offer) => h('div', { key: offer.id }, h('p', null, offer.headline ?? offer.name), h('p', null, offer.discount.label), button(offer.audience === 'canceling' ? 'Keep subscription with this offer' : 'Choose this offer', () => offer.audience === 'canceling' ? b.acceptOffer(offer.id) : b.checkout(offer.plans.find((p) => p.plan === selectedPlan)?.plan ?? offer.plans[0].plan, { offer_id: offer.id }), !offer.plans.length)))) : null, b.balances && Object.keys(b.balances.features).length ? h('section', { className: 'bk-balances' }, h('h3', null, 'Usage and credits'), ...Object.entries(b.balances.features).map(([id, balance]) => h('p', { key: id }, `${id}: ${balance.unlimited ? 'Unlimited' : `${balance.balance ?? 0} remaining`}${balance.resets_at ? `; resets ${fmtDate(balance.resets_at, props.locale)}` : ''}`)), canManage && packs.length ? h('fieldset', { disabled: b.busy }, h('legend', null, 'Buy credits'), h('label', null, 'Credit pack', h('select', { value: selectedProduct, onChange: (event) => setProduct(event.target.value) }, ...packs.map((p) => option(p.plan, `${p.plan}${p.price?.unit_amount != null ? ` — ${money(p.price.unit_amount, p.price.currency, props.locale)}` : ''}`)))), input('Number of packs', packQuantity, setPackQuantity, 'number', { min: 1, step: 1 }), button('Buy credits', () => b.purchaseCredits(selectedProduct, Number(packQuantity)), !validPack)) : null, canManage ? h('fieldset', { disabled: b.busy }, h('legend', null, 'Overage spending limit'), input('Currency', capCurrency, setCapCurrency), input('Maximum per period (leave empty for no cap)', cap, setCap, 'number', { min: 0, step: 'any' }), button('Save spending limit', () => b.saveUsageSettings({ spend_cap: cap.trim() === '' ? null : { amount: capMinor, currency: selectedCurrency } }), cap.trim() !== '' && (!Number.isSafeInteger(capMinor) || capMinor < 0))) : null, canManage && creditFeatures.length ? h('fieldset', { disabled: b.busy }, h('legend', null, 'Automatic credit top-ups'), h('label', null, 'Credit balance', h('select', { value: selectedFeature, onChange: (event) => setFeature(event.target.value) }, ...creditFeatures.map((id) => option(id)))), h('p', null, `Uses the ${selectedProduct} credit pack selected above.`), input('Top up below', threshold, setThreshold, 'number', { min: 0, step: 'any' }), input('Maximum purchases per month', monthlyMax, setMonthlyMax, 'number', { min: 1, step: 1 }), h('label', null, h('input', { type: 'checkbox', checked: auto, onChange: (event) => setAuto(event.target.checked) }), ' I authorize automatic charges to my saved payment method for this credit pack.'), button('Save automatic top-up', () => b.saveUsageSettings({ auto_topups: [...(b.balances?.auto_topups ?? []).filter((r) => r.feature_id !== selectedFeature).map(({ feature_id, threshold, product, auto, max_per_month }) => ({ feature_id, threshold, product, auto, max_per_month })), { feature_id: selectedFeature, product: selectedProduct, threshold: Number(threshold), auto, max_per_month: Number(monthlyMax) }] }), !Number.isFinite(Number(threshold)) || Number(threshold) < 0 || !Number.isSafeInteger(Number(monthlyMax)) || Number(monthlyMax) < 1 || !selectedPack?.grants?.some((g) => g.feature_id === selectedFeature))) : null) : null);
412
412
  }
413
413
  import { formatChanges } from "./config.js";
414
+ /** A Stripe product tax code (txcd_ and eight digits); the SaaS one is the usual choice for an app. */
415
+ export const TAX_CODE = /^txcd_\d{8}$/;
416
+ export const TAX_CODE_SAAS = 'txcd_10103001';
414
417
  const isSpec = (p) => !!p && typeof p === 'object' && ('tiers' in p || 'amount' in p);
415
418
  const toMajor = (minor, currency) => (minor / 10 ** currencyDigits(currency)).toString();
416
419
  const toMinor = (major, currency) => Math.round(Number(major) * 10 ** currencyDigits(currency));
@@ -433,9 +436,11 @@ export function pricingDraftProblem(plan, d) {
433
436
  return `${plan}: the price must be 0 or more.`;
434
437
  if (d.unit && !/^[A-Za-z][A-Za-z0-9 _-]{0,31}$/.test(d.unit))
435
438
  return `${plan}: the unit is a short word, like "students".`;
439
+ if (d.tax_code?.trim() && !TAX_CODE.test(d.tax_code.trim()))
440
+ return `${plan}: the tax code looks like ${TAX_CODE_SAAS} (Stripe's code for SaaS, business use).`;
436
441
  return null;
437
442
  }
438
- /** The config document a draft turns into (only prices, units and hidden flags change; everything else is carried over). */
443
+ /** The config document a draft turns into (only prices, units, tax codes and hidden flags change; everything else is carried over). */
439
444
  export function pricingDraftToConfig(config, draft) {
440
445
  const plans = {};
441
446
  for (const [name, spec] of Object.entries(config.plans ?? {})) {
@@ -453,6 +458,10 @@ export function pricingDraftToConfig(config, draft) {
453
458
  next.unit = d.unit;
454
459
  else
455
460
  delete next.unit;
461
+ if (d.tax_code?.trim())
462
+ next.tax_code = d.tax_code.trim();
463
+ else
464
+ delete next.tax_code;
456
465
  if (d.hidden)
457
466
  next.hidden = true;
458
467
  else
@@ -468,8 +477,8 @@ function draftOf(config) {
468
477
  continue;
469
478
  const currency = spec.price.currency;
470
479
  draft[name] = spec.price.tiers
471
- ? { tiers: spec.price.tiers.map((t) => ({ up_to: String(t.up_to), amount: toMajor(t.amount, currency) })), unit: spec.unit ?? '', hidden: !!spec.hidden }
472
- : { amount: toMajor(spec.price.amount ?? 0, currency), unit: spec.unit ?? '', hidden: !!spec.hidden };
480
+ ? { tiers: spec.price.tiers.map((t) => ({ up_to: String(t.up_to), amount: toMajor(t.amount, currency) })), unit: spec.unit ?? '', hidden: !!spec.hidden, tax_code: spec.tax_code ?? '' }
481
+ : { amount: toMajor(spec.price.amount ?? 0, currency), unit: spec.unit ?? '', hidden: !!spec.hidden, tax_code: spec.tax_code ?? '' };
473
482
  }
474
483
  return draft;
475
484
  }
@@ -566,7 +575,7 @@ export function PricingEditor(props) {
566
575
  }
567
576
  else
568
577
  body = field(`Price per ${interval} (${currency.toUpperCase()})`, d.amount ?? '', (value) => update(plan, (x) => ({ ...x, amount: value })), { type: 'number', min: 0, step: 'any' });
569
- return h('section', { key: plan, className: 'bk-plan' }, h('h3', null, plan), body, d ? field('Unit (what the quantity counts)', d.unit, (value) => update(plan, (x) => ({ ...x, unit: value }))) : null, d ? h('label', null, h('input', { type: 'checkbox', checked: d.hidden, disabled: busy, onChange: (event) => update(plan, (x) => ({ ...x, hidden: event.target.checked })) }), ' Hidden from the pricing page') : null, v && v.versioning ? h('p', { className: 'bk-versions' }, `Version ${v.current_version}${olderSubscribers ? `; ${olderSubscribers} subscriber${olderSubscribers === 1 ? '' : 's'} on older prices` : ''}`) : null, v && olderSubscribers ? h(Fragment, null, button('Move current subscribers at renewal', () => migrate(plan, 'period_end')), button('Move current subscribers now', () => migrate(plan, 'now'))) : null);
578
+ return h('section', { key: plan, className: 'bk-plan' }, h('h3', null, plan), body, d ? field('Unit (what the quantity counts)', d.unit, (value) => update(plan, (x) => ({ ...x, unit: value }))) : null, d ? field(`Tax code (Stripe product tax code; ${TAX_CODE_SAAS} = SaaS, business use)`, d.tax_code ?? '', (value) => update(plan, (x) => ({ ...x, tax_code: value })), { placeholder: TAX_CODE_SAAS }) : null, d ? h('label', null, h('input', { type: 'checkbox', checked: d.hidden, disabled: busy, onChange: (event) => update(plan, (x) => ({ ...x, hidden: event.target.checked })) }), ' Hidden from the pricing page') : null, v && v.versioning ? h('p', { className: 'bk-versions' }, `Version ${v.current_version}${olderSubscribers ? `; ${olderSubscribers} subscriber${olderSubscribers === 1 ? '' : 's'} on older prices` : ''}`) : null, v && olderSubscribers ? h(Fragment, null, button('Move current subscribers at renewal', () => migrate(plan, 'period_end')), button('Move current subscribers now', () => migrate(plan, 'now'))) : null);
570
579
  });
571
580
  return h('section', { className: cls, 'aria-busy': busy }, h('h2', null, 'Prices'), error ? h('p', { role: 'alert', className: 'bk-error' }, error) : null, message ? h('p', { role: 'status' }, message) : null, ...cards, problem ? h('p', { role: 'alert', className: 'bk-error' }, problem) : null, h('div', { className: 'bk-actions' }, button('Preview changes', preview, !!problem), button('Save', save, !!problem), button('Discard', () => { setDraft(draftOf(config)); setChanges(null); })), changes ? h('section', { className: 'bk-changes', 'aria-label': 'Change preview' }, h('h3', null, 'What will change'), h('pre', null, formatChanges(changes)), changes.some((c) => c.kind === 'price') ? h('p', null, config.plan_versioning ? 'A changed price becomes a new version: current subscribers keep their price until their next renewal, or until you move them.' : 'Current subscribers move to the changed price from their next renewal.') : null) : null);
572
581
  }
package/dist/types.d.ts CHANGED
@@ -482,7 +482,7 @@ export interface EntitlementChangedEvent {
482
482
  /** Error codes the API returns (stable; branch on these, not on messages). */
483
483
  export type BillingErrorCode = 'missing_credentials' | 'invalid_credentials' | 'app_disabled'
484
484
  /** 0.7 security: the service is locked down (only the owner key works). */
485
- | 'service_locked_down' | 'ip_not_allowed' | 'rate_limited' | 'too_many_auth_failures' | 'invalid_json' | 'invalid_response' | 'invalid_account_id' | 'invalid_field' | 'invalid_email' | 'invalid_url' | 'origin_not_allowed' | 'unknown_plan' | 'price_not_found' | 'exempt' | 'covered_by_account' | 'already_subscribed' | 'no_billing_customer' | 'no_subscription' | 'coverage_self' | 'coverage_chain' | 'trial_used' | 'trial_unavailable' | 'cancel_failed' | 'account_not_found' | 'portal_not_configured' | 'covers_self' | 'too_many_covers' | 'covered_elsewhere' | 'accounts_not_eligible' | 'not_launched' | 'promotion_code_not_supported' | 'parent_chain' | 'parent_self' | 'too_many_ids' | 'key_scope_denied' | 'invoice_not_found' | 'invoice_not_paid' | 'nothing_refundable' | 'over_refundable' | 'bad_amount' | 'no_charge' | 'feature_not_found' | 'feature_not_metered' | 'invalid_feature_id' | 'too_many_events' | 'plan_not_purchasable' | 'lock_not_found' | 'lock_not_held' | 'already_lifetime' | 'covers_not_supported' | 'resume_failed' | 'same_plan' | 'same_quantity' | 'custom_pricing_required' | 'operation_in_progress' | 'invoice_billing_disabled' | 'invoice_required' | 'purchase_not_found' | 'purchase_not_refundable' | 'purchase_credits_reserved' | 'refund_conflict' | 'add_on_requires_base' | 'not_an_add_on' | 'add_on_not_found' | 'already_entitled' | 'currency_mismatch' | 'pack_too_small'
485
+ | 'service_locked_down' | 'ip_not_allowed' | 'rate_limited' | 'too_many_auth_failures' | 'invalid_json' | 'invalid_response' | 'invalid_account_id' | 'invalid_field' | 'invalid_email' | 'invalid_url' | 'origin_not_allowed' | 'unknown_plan' | 'price_not_found' | 'exempt' | 'covered_by_account' | 'already_subscribed' | 'no_billing_customer' | 'no_subscription' | 'coverage_self' | 'coverage_chain' | 'trial_used' | 'trial_unavailable' | 'cancel_failed' | 'account_not_found' | 'portal_not_configured' | 'covers_self' | 'too_many_covers' | 'covered_elsewhere' | 'accounts_not_eligible' | 'not_launched' | 'promotion_code_not_supported' | 'parent_chain' | 'parent_self' | 'too_many_ids' | 'key_scope_denied' | 'invoice_not_found' | 'invoice_not_paid' | 'nothing_refundable' | 'over_refundable' | 'bad_amount' | 'no_charge' | 'feature_not_found' | 'feature_not_metered' | 'invalid_feature_id' | 'too_many_events' | 'plan_not_purchasable' | 'lock_not_found' | 'lock_not_held' | 'already_lifetime' | 'covers_not_supported' | 'resume_failed' | 'same_plan' | 'same_quantity' | 'custom_pricing_required' | 'tax_behavior_locked' | 'operation_in_progress' | 'invoice_billing_disabled' | 'invoice_required' | 'purchase_not_found' | 'purchase_not_refundable' | 'purchase_credits_reserved' | 'refund_conflict' | 'add_on_requires_base' | 'not_an_add_on' | 'add_on_not_found' | 'already_entitled' | 'currency_mismatch' | 'pack_too_small'
486
486
  /** 0.7 review / prerelease: codes the service answers that earlier unions missed. */
487
487
  | 'price_not_owned' | 'reason_required' | 'prune_refused' | 'storage_unavailable' | 'invalid_admin_key' | 'app_not_found' | 'not_found' | 'forbidden' | 'misconfigured' | 'stripe_not_configured' | 'stripe_permission' | 'stripe_key_unreadable' | 'no_stripe_key' | 'invalid_config' | 'invalid_items' | 'invalid_plans' | 'invalid_origin' | 'invalid_event' | 'invalid_signature' | 'invalid_app_id' | 'confirm_required' | 'feature_exists' | 'feature_in_use' | 'too_many_features' | 'plan_exists' | 'plan_not_found' | 'version_not_found' | 'key_not_found' | 'too_many_keys' | 'has_live_subscriptions' | 'mark_key_in_use' | 'no_accounts' | 'no_customer' | 'no_payment_method' | 'no_pending_setup' | 'no_subscription_item' | 'price_unreadable' | 'customer_owned_by_another_account' | 'different_customer_already_linked' | 'subscription_customer_mismatch' | 'subscription_missing_in_stripe' | 'subscription_owned_by_another_account' | 'webhook_not_found' | 'no_webhook_url' | 'no_webhook_secret' | 'invalid_webhook_secret' | 'invalid_stripe_key' | 'stripe_mode_mismatch' | 'endpoint_exists' | 'unsupported_media_type'
488
488
  /** 0.8 discounts and offers. `discount_invalid` carries `details.reason` (a DiscountReason). */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hjam91/billing",
3
- "version": "0.11.0",
3
+ "version": "0.12.0",
4
4
  "description": "Zero-dependency client for a billing-kit service: cached, fail-open entitlement and feature checks, usage tracking, Stripe Checkout / portal, signed webhook verification, a Hono gate and an optional React billing card.",
5
5
  "keywords": [
6
6
  "billing",