nuxt-backend 0.4.0 → 0.5.1

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.
Files changed (76) hide show
  1. package/README.md +5 -2
  2. package/dist/chunks/catalog.mjs +1 -1
  3. package/dist/chunks/doctor.mjs +4 -4
  4. package/dist/chunks/email-previews.mjs +1 -1
  5. package/dist/chunks/health.mjs +2 -2
  6. package/dist/chunks/index.mjs +2 -2
  7. package/dist/chunks/install.mjs +8 -8
  8. package/dist/chunks/run.mjs +1 -1
  9. package/dist/chunks/server.mjs +4 -4
  10. package/dist/cli.mjs +13 -56
  11. package/dist/devtools-client/index.html +1 -1
  12. package/dist/module.js +2 -2
  13. package/dist/module.json +1 -1
  14. package/dist/runtime/vue/components/auth/InviteRedeem.vue +4 -22
  15. package/dist/runtime/vue/components/auth/WaitlistStatus.vue +7 -17
  16. package/dist/runtime/vue/components/billing/PricingTable.vue +17 -51
  17. package/dist/runtime/vue/components/billing/ReferralLanding.vue +1 -2
  18. package/dist/runtime/vue/components/workspaces/WorkspaceBilling.vue +15 -18
  19. package/dist/runtime/vue/components/workspaces/WorkspaceBillingPause.vue +1 -2
  20. package/dist/runtime/vue/components/workspaces/WorkspaceSettings.d.vue.ts +2 -2
  21. package/dist/runtime/vue/components/workspaces/WorkspaceSettings.vue +9 -22
  22. package/dist/runtime/vue/components/workspaces/WorkspaceSettings.vue.d.ts +2 -2
  23. package/dist/runtime/vue/components/workspaces/workspace-billing.d.ts +12 -16
  24. package/dist/runtime/vue/components/workspaces/workspace-billing.js +22 -37
  25. package/dist/runtime/vue/composables/use-access.d.ts +18 -0
  26. package/dist/runtime/vue/composables/use-access.js +33 -6
  27. package/dist/runtime/vue/composables/use-billing-section.d.ts +115 -0
  28. package/dist/runtime/vue/composables/use-billing-section.js +76 -0
  29. package/dist/runtime/vue/composables/use-gift-form.js +7 -24
  30. package/dist/runtime/vue/composables/use-gift-list.d.ts +18 -1
  31. package/dist/runtime/vue/composables/use-gift-list.js +6 -1
  32. package/dist/runtime/vue/composables/use-plan-change.d.ts +148 -0
  33. package/dist/runtime/vue/composables/use-plan-change.js +130 -0
  34. package/dist/runtime/vue/composables/use-pricing.d.ts +29 -0
  35. package/dist/runtime/vue/composables/use-pricing.js +53 -14
  36. package/dist/runtime/vue/composables/use-referral-invite.d.ts +7 -0
  37. package/dist/runtime/vue/composables/use-referral-invite.js +4 -1
  38. package/dist/runtime/vue/composables/use-waitlist.d.ts +18 -0
  39. package/dist/runtime/vue/composables/use-waitlist.js +24 -0
  40. package/dist/runtime/vue/pages/pricing.vue +1 -2
  41. package/dist/runtime/vue/plugins/checkout-return.js +9 -2
  42. package/dist/runtime/vue/utils/checkout-return.d.ts +11 -1
  43. package/dist/runtime/vue/utils/checkout-return.js +6 -2
  44. package/dist/runtime/vue/utils/gift-days.d.ts +20 -0
  45. package/dist/runtime/vue/utils/gift-days.js +32 -0
  46. package/dist/runtime/vue/utils/namespace.js +7 -2
  47. package/dist/runtime/vue/utils/page-open.d.ts +1 -0
  48. package/dist/runtime/vue/utils/page-open.js +12 -0
  49. package/dist/runtime/vue/utils/plan-change-confirm.d.ts +38 -26
  50. package/dist/runtime/vue/utils/plan-change-confirm.js +25 -16
  51. package/dist/runtime/vue/utils/pricing-checkout.d.ts +39 -0
  52. package/dist/runtime/vue/utils/pricing-checkout.js +22 -0
  53. package/dist/runtime/vue/utils/tab-keep.d.ts +3 -1
  54. package/dist/runtime/vue/utils/tab-keep.js +1 -1
  55. package/dist/shared/{nuxt-backend.CbR37s_c.mjs → nuxt-backend.0r1vvS1c.mjs} +24 -4
  56. package/dist/shared/{nuxt-backend.BjQoqNIu.mjs → nuxt-backend.BvKvJ1mo.mjs} +1 -1
  57. package/dist/shared/nuxt-backend.DRuHg-IQ.mjs +290 -0
  58. package/dist/shared/{nuxt-backend.9IVxzzft.mjs → nuxt-backend.suXOnqOQ.mjs} +163 -4
  59. package/dist/shared/{nuxt-backend.Baxb382E.mjs → nuxt-backend.zY6UDqDu.mjs} +1 -1
  60. package/package.json +2 -2
  61. package/skills/nuxt-backend/references/api.md +3 -1
  62. package/skills/nuxt-backend/references/install.md +9 -3
  63. package/skills/nuxt-backend/references/renames.json +8 -0
  64. package/skills/nuxt-backend/references/surface.json +2 -0
  65. package/skills/nuxt-backend-billing/SKILL.md +9 -0
  66. package/skills/nuxt-backend-billing/references/api.md +2 -0
  67. package/skills/nuxt-backend-upgrade/references/upgrade.md +6 -0
  68. package/src/runtime/vue/components/auth/InviteRedeem.vue +5 -26
  69. package/src/runtime/vue/components/auth/WaitlistStatus.vue +11 -20
  70. package/src/runtime/vue/components/billing/PricingTable.vue +25 -82
  71. package/src/runtime/vue/components/billing/ReferralLanding.vue +1 -2
  72. package/src/runtime/vue/components/workspaces/WorkspaceBilling.vue +21 -25
  73. package/src/runtime/vue/components/workspaces/WorkspaceBillingPause.vue +1 -2
  74. package/src/runtime/vue/components/workspaces/WorkspaceSettings.vue +16 -29
  75. package/src/runtime/vue/pages/pricing.vue +1 -4
  76. package/dist/shared/nuxt-backend.BCjeoX0x.mjs +0 -119
@@ -70,8 +70,9 @@ npx nuxt-backend init
70
70
  and the CLI that runs them. `init` writes the backend files (`backend/`, or into the existing
71
71
  functions folder), `convex.json` when that folder is not `convex/`, `.env.example`, an
72
72
  `AGENTS.md` section, `.mcp.json` and the agent skills in `.agents/skills/` for agents, adds `'nuxt-backend'` to `modules`, points the
73
- `dev` script at `nuxt-backend dev`, and swaps `<NuxtWelcome />` for `<NuxtPage />` in an untouched
74
- `app/app.vue` so the module's pages render. It never replaces a file that exists.
73
+ `dev` script at `nuxt-backend dev`, swaps `<NuxtWelcome />` for `<NuxtPage />` in an untouched
74
+ `app/app.vue` so the module's pages render, and writes `app/pages/index.vue` when no page answers
75
+ `/` and the app extends no layer. It never replaces a file that exists.
75
76
 
76
77
  Check what `init` printed:
77
78
 
@@ -104,12 +105,17 @@ the user before editing it; don't overwrite their code.
104
105
 
105
106
  pnpm notes:
106
107
 
107
- - pnpm 11 stops an install on dependency build scripts it has not been told about. Show the user
108
+ - pnpm 11 and later stop an install on dependency build scripts they have not been told about. Show the user
108
109
  the list and let them choose: approve or deny with `pnpm approve-builds`, or in `allowBuilds` in
109
110
  `pnpm-workspace.yaml`. `esbuild` works without its script. Don't turn off `strictDepBuilds`.
110
111
  - pnpm's default layout hides the Convex components nuxt-backend brings, and Convex needs to
111
112
  resolve them: add `publicHoistPattern: ['@convex-dev/*']` to `pnpm-workspace.yaml`, then install
112
113
  again. (Apps made from the starter carry both settings in `.pnpmfile.mjs`.)
114
+ - pnpm 12 lists nuxt-backend under "Agent skills awaiting approval" until its skills are approved
115
+ or denied. `init` already installed those skills in `.agents/skills`, and approving links a
116
+ second copy of each, so under pnpm 12.11 or later `init` denies them in `pnpm-workspace.yaml`
117
+ (`skills: false` under `permissions`). When pnpm still lists nuxt-backend (an app set up under
118
+ pnpm 11), run `npx nuxt-backend init --agents`, or suggest `pnpm approve '!nuxt-backend'`.
113
119
 
114
120
  ## 2. Start it: the deployment, its env, the generated code
115
121
 
@@ -1,6 +1,14 @@
1
1
  {
2
2
  "$comment": "Every public name a release renamed, reshaped or removed, with the Upgrade page section that explains it. `npx nuxt-backend upgrade` rewrites none of an app's code: the edit is yours. Generated by `pnpm generate` (scripts/agent-guidance.mjs). Do not edit: change the code it reads.",
3
3
  "renames": [
4
+ {
5
+ "from": "api",
6
+ "to": "_generated/api.d.ts",
7
+ "change": "reshaped",
8
+ "section": "A composable falls back when the app lacks its backend file",
9
+ "note": "the packaged plugin provides only the modules `_generated/api.d.ts` lists, so a namespace it doesn't list reads as absent and its composable falls back; an app that commits `_generated/` commits it again after adding a backend file",
10
+ "url": "https://nuxt-backend.dev/docs/ship/releases/upgrade#a-composable-falls-back-when-the-app-lacks-its-backend-file"
11
+ },
4
12
  {
5
13
  "from": "doctor --fix",
6
14
  "to": "--yes",
@@ -897,6 +897,7 @@
897
897
  "useBackendConfig",
898
898
  "useBackendPagePath",
899
899
  "useBilling",
900
+ "useBillingSection",
900
901
  "useCampaign",
901
902
  "useChat",
902
903
  "useConnectionState",
@@ -927,6 +928,7 @@
927
928
  "useOnboarding",
928
929
  "useOrders",
929
930
  "usePasskeys",
931
+ "usePlanChange",
930
932
  "usePricing",
931
933
  "usePushSubscription",
932
934
  "useReauthentication",
@@ -103,12 +103,21 @@ credits and gifts.
103
103
  Nothing is stored on the device.
104
104
  - Out of credits: `usePricing().packFor(refusal.data.need)` is the smallest pack that covers an
105
105
  `insufficient_credits` refusal; `<BackendNotices />` shows the low-credits notice on its own.
106
+ - A pricing page of your own checks out with `usePricing().checkout('plan' | 'pack', key)`, the
107
+ table's rules: the campaign's code or the page's promotion, one discount, retried without a
108
+ refused one, the price's currency. A subscriber switches through `usePlanChange({ pricing })`
109
+ (prices in the subscription's currency, words from `changeOf`, `confirm()` with
110
+ `proration: 'invoice'`), never a `changePlan` without it behind words that say "settled now".
111
+ `usePricing().structuredData` is the schema.org data.
106
112
 
107
113
  ## The billing section of /settings
108
114
 
109
115
  - `<WorkspaceSettings>` (its `billing` section, on the ready-made `/settings`) follows the
110
116
  subscription's state: past due, paused, set to cancel, change scheduled, trial, active (the
111
117
  first that holds), with the actions the subscription allows, plus the benefits and the history.
118
+ A billing page of your own reads `useBillingSection()`: `state` (`error` for a failed read,
119
+ never active), `actions` in order, `pausable` (none while one is scheduled), `switchable`,
120
+ `resumesAfter(months)` and `pause(months)`. Never re-derive them from `useBilling()`.
112
121
  - Cancelling is one step there and on `<PricingTable>`'s current plan: what ends when and one
113
122
  button, nothing else. Never add a save offer, a question or a field to that confirmation.
114
123
  The provider keeps a reason and comment only with the cancellation itself (it refuses a
@@ -15,6 +15,8 @@ core skill, `nuxt-backend`, lists every public name in its own `references/api.m
15
15
  | `useFeatures()` | Reactive feature-gating for the current user — the SaaS access primitive. |
16
16
  | `useCredits()` | Reactive prepaid-credit balance for the current user, plus a `topUp()` checkout and a `refresh()` re-sync. |
17
17
  | `usePricing()` | The app's plans and credit packs as a pricing page shows them — every plan with its monthly and yearly price, what a year saves, its trial and the credits it grants per cycle; every pack with its price per credit and which is the best value — read through the scaffolded `getPricing`, in the visitor's currency where the catalog prices it. |
18
+ | `usePlanChange()` | A subscriber's switch to another plan or billing period, without its markup: the prices it can move to, in the subscription's own currency, and one confirmation that says what the switch does before it does it — the price, when it happens (a yearly price left for a monthly one waits for the paid year's end) and how the period's difference is settled, or, in a trial, what becomes of it — then the switch itself, settling that difference at once (`proration: 'invoice'`), so the words stay true whatever the organization's default. |
19
+ | `useBillingSection()` | The billing section of `/settings` without its markup: the state the plan is in, in the order the section tries them (a gifted plan, a failed payment, a pause, a cancellation or a plan change set for the period's end, a trial, else active), a read that failed as a failure rather than a plan, a return from checkout still finishing as busy, and what each state calls for, with the rules each offer follows: a switch only while nothing is scheduled, a pause only while none is, and its resume date counted the way the provider counts months. |
18
20
  | `useOrders()` | The signed-in customer's billing history — past charges straight from the provider's orders API, plus the per-order invoice link. |
19
21
  | `useUsage()` | Consumption history for a credit meter, read from the provider's events API — the events your server ingested when it spent credits. |
20
22
  | `useWithdrawal()` | The EU withdrawal window: whether the signed-in billing manager's purchase is still inside the 14 days of the Consumer Rights Directive's Art. 9, until when, and the withdrawal itself, the withdrawal function of its Art. 11a — what `<WithdrawalButton>` is built on, for a section of your own around it. |
@@ -17,6 +17,12 @@ has the reasons and every step. The core skill's `references/renames.json`, in
17
17
  After it, run `npx nuxt-backend doctor`, and `npx nuxt-backend init --agents` to refresh the app's
18
18
  agent files and skills.
19
19
 
20
+ ## [A composable falls back when the app lacks its backend file](https://nuxt-backend.dev/docs/ship/releases/upgrade#a-composable-falls-back-when-the-app-lacks-its-backend-file)
21
+
22
+ | Was | Now | Change | Note |
23
+ |---|---|---|---|
24
+ | `api` | `_generated/api.d.ts` | reshaped | the packaged plugin provides only the modules `_generated/api.d.ts` lists, so a namespace it doesn't list reads as absent and its composable falls back; an app that commits `_generated/` commits it again after adding a backend file |
25
+
20
26
  ## [`doctor --fix` asks before it syncs email, and a deploy runs the package's migrations](https://nuxt-backend.dev/docs/ship/releases/upgrade#doctor---fix-asks-before-it-syncs-email-and-a-deploy-runs-the-packages-migrations)
21
27
 
22
28
  | Was | Now | Change | Note |
@@ -16,15 +16,15 @@
16
16
  *
17
17
  * @internal
18
18
  */
19
- import { computed, inject, nextTick, onMounted, ref, useId, useTemplateRef, watch } from 'vue'
19
+ import { computed, inject, nextTick, ref, useId, useTemplateRef } from 'vue'
20
20
  import { ConvexAuthStateKey } from 'nuxt-convex-module/client'
21
21
  import { useAccessPhase, useInvite } from '../../composables/use-access'
22
22
  import { useBackendPagePath } from '../../composables/use-backend-page-path'
23
23
  import { useLabels } from '../../composables/use-labels'
24
24
  import { useReturnPath } from '../../composables/use-return-path'
25
- import { keepInvite, takeInviteFromAddress } from '../../utils/kept-invite'
26
25
 
27
- const invite = useInvite()
26
+ // `fromAddress` takes the link's token off the address, waits for the session, then checks or forgets it.
27
+ const invite = useInvite({ fromAddress: true })
28
28
  const { phase } = useAccessPhase()
29
29
  const { t, errorMessage } = useLabels('auth')
30
30
  const waitlistPath = useBackendPagePath('waitlist')
@@ -33,35 +33,14 @@ const auth = inject(ConvexAuthStateKey, null)
33
33
  const signedIn = computed(() => auth != null && auth.isAuthenticated.value)
34
34
  const codeId = useId()
35
35
  const code = ref('')
36
- const checked = ref(false)
36
+ const checked = invite.linkChecked
37
37
  // Whether a ticket was asked about at all: a link brought one, the tab kept one, or a code was typed.
38
- const asked = ref(false)
38
+ const asked = invite.asked
39
39
  const continueLink = useTemplateRef<HTMLAnchorElement>('continueLink')
40
40
 
41
- onMounted(() => {
42
- // The link's token leaves the address at once, kept for the tab, so a reload while the session settles still has it.
43
- const taken = takeInviteFromAddress()
44
- if (taken) keepInvite(taken)
45
- // The session settles first: a signed-in visitor's link is neither checked nor kept.
46
- let started = false
47
- watch(() => auth != null && auth.isLoading.value, async (loading) => {
48
- if (loading || started) return
49
- started = true
50
- if (signedIn.value) {
51
- invite.forget()
52
- }
53
- else {
54
- asked.value = taken !== null || invite.isKept.value
55
- if (asked.value) await invite.check()
56
- }
57
- checked.value = true
58
- }, { immediate: true })
59
- })
60
-
61
41
  async function redeem() {
62
42
  const typed = code.value.trim()
63
43
  if (invite.isPending.value || !typed) return
64
- asked.value = true
65
44
  await invite.check(typed)
66
45
  // The form goes once the code checks: focus moves on to the way in, never back to the page's start.
67
46
  if (state.value !== 'valid') return
@@ -29,11 +29,11 @@ import { useAccessPhase } from '../../composables/use-access'
29
29
  import { useBackendPagePath } from '../../composables/use-backend-page-path'
30
30
  import { useLabels } from '../../composables/use-labels'
31
31
  import { useReturnPath } from '../../composables/use-return-path'
32
- import { useWaitlist, type WaitlistPlace } from '../../composables/use-waitlist'
33
- import { takeFragment, tabKeep } from '../../utils/tab-keep'
32
+ import { keptStatusToken, useWaitlist, type WaitlistPlace } from '../../composables/use-waitlist'
34
33
 
35
34
  // The place behind a status link: the link's own, never a friend's code.
36
- const waitlist = useWaitlist({ ref: null })
35
+ // `statusLink` takes the token off the address and keeps it for the tab.
36
+ const waitlist = useWaitlist({ ref: null, statusLink: true })
37
37
  const { phase, isLoading: phaseLoading } = useAccessPhase()
38
38
  const { t } = useLabels('waitlist')
39
39
  const loginPath = useBackendPagePath('login')
@@ -42,31 +42,22 @@ const home = useReturnPath()
42
42
  const auth = inject(ConvexAuthStateKey, null)
43
43
  const signedIn = computed(() => auth != null && auth.isAuthenticated.value)
44
44
  const authLoading = computed(() => auth != null && auth.isLoading.value)
45
- const opened = ref(false)
46
45
  const hadToken = ref(false)
47
46
  // The person left the list, here or through the form: the page says so above the join.
48
47
  const left = ref(false)
49
- // The status token this tab keeps, out of the address.
50
- const kept = tabKeep('nuxt-backend:waitlist')
48
+ // The join's own instance (the form's) keeps its token under the same key.
49
+ const kept = keptStatusToken()
51
50
 
51
+ // useWaitlist read the status link (or the tab's token) as the page mounted, before this.
52
52
  onMounted(() => {
53
- // A status link's token leaves the address at once; a reload reads the one the tab keeps.
54
- const taken = takeFragment()
55
- if (taken) kept.keep(taken)
56
- const token = taken ?? kept.read()
57
- if (token) {
58
- hadToken.value = true
59
- waitlist.status(token)
60
- }
61
- opened.value = true
53
+ hadToken.value = waitlist.step.value === 'status'
62
54
  })
63
55
 
64
- // Leave took the entry behind the token: a reload must not read it as a dead link.
65
- watch(() => waitlist.step.value, (step, before) => {
66
- if (before !== 'status' || step !== 'join') return
56
+ // Leave took the entry behind the token (useWaitlist().left); it dropped what the tab kept.
57
+ watch(() => waitlist.left.value, (now) => {
58
+ if (!now) return
67
59
  left.value = true
68
60
  hadToken.value = false
69
- kept.drop()
70
61
  })
71
62
 
72
63
  /** A join made here: its status token kept for the tab, over a dead one. */
@@ -85,7 +76,7 @@ function leftForm() {
85
76
  /** The `data-state` of the page: what the person reads now. */
86
77
  const state = computed(() => {
87
78
  // The fragment is the browser's alone, so the server renders the wait.
88
- if (!opened.value || authLoading.value || (phase.value === undefined && phaseLoading.value) || (hadToken.value && waitlist.isLoading.value)) return 'checking'
79
+ if (!waitlist.linkChecked.value || authLoading.value || (phase.value === undefined && phaseLoading.value) || (hadToken.value && waitlist.isLoading.value)) return 'checking'
89
80
  if (signedIn.value) return 'member'
90
81
  // Open to all, the line is over; invite only, a place already held stands.
91
82
  if (phase.value === 'public') return 'open'
@@ -9,15 +9,16 @@ import { useCampaign } from '../../composables/use-campaign'
9
9
  import { useCredits } from '../../composables/use-credits'
10
10
  import { useExperimentDiscount } from '../../composables/use-experiment'
11
11
  import { refusalText, useLabels, type BackendLabels, type LabelKey, type LabelOverrides } from '../../composables/use-labels'
12
+ import { usePlanChange } from '../../composables/use-plan-change'
12
13
  import { usePricing, type PricedOffer, type PricedPlan, type PricingInterval, type PricingSuccessUrls, type UsePricingReturn } from '../../composables/use-pricing'
13
14
  import { busyAttributes } from '../../a11y'
14
15
  import { useAuthSession } from '../../utils/auth-session'
15
- import { getBackendError } from '../../utils/backend-error'
16
16
  import { createCancelConfirm } from '../../utils/cancel-confirm'
17
- import { CONFIRMED_PRORATION, createPlanChangeConfirm, type PlanChangeTarget } from '../../utils/plan-change-confirm'
17
+ import { createPlanChangeConfirm } from '../../utils/plan-change-confirm'
18
18
  import { returnFocus } from '../../utils/focus-return'
19
19
  import { useMeterUnit } from '../../utils/meter-unit'
20
20
  import { pricingBindings, shownInterval } from '../../utils/pricing-bindings'
21
+ import { pricingCheckout } from '../../utils/pricing-checkout'
21
22
  import type { CreditPack, PricingContact, PricingPlan } from '../../../config'
22
23
  import { providePricingView, type PlanAction, type PlanTrial, type PricingSlotContext, type PricingTableSlots, type ResolvedPack, type ResolvedPlan } from './pricing-table'
23
24
 
@@ -130,8 +131,10 @@ const credits = useCredits()
130
131
  const campaign = useCampaign()
131
132
  // A price test's promotion for the person's variant, when the address carries no campaign code.
132
133
  const experimentDiscount = useExperimentDiscount()
134
+ /** The promotion the table shows: the prop's, else the campaign link's code, else a price test's. */
135
+ const asked = () => props.discount ?? campaign.discountCode.value ?? experimentDiscount.value
133
136
  const pricing = usePricing({
134
- discount: () => props.discount ?? campaign.discountCode.value ?? experimentDiscount.value,
137
+ discount: asked,
135
138
  actions: false,
136
139
  // Read when a checkout starts, so a changed prop counts.
137
140
  successUrl: {
@@ -140,19 +143,9 @@ const pricing = usePricing({
140
143
  },
141
144
  })
142
145
  // A subscriber's switch keeps the subscription's currency (the provider's
143
- // rule), so its confirmation states the price in it: read apart, in the
144
- // browser, only while the page shows another one.
145
- const subscriptionCurrency = computed(() => {
146
- const currency = billing.subscription.value?.currency
147
- return typeof currency === 'string' && currency !== '' ? currency.toLowerCase() : undefined
148
- })
149
- const switchPricing = usePricing({
150
- server: false,
151
- actions: false,
152
- currency: () => subscriptionCurrency.value,
153
- enabled: () => billing.isSubscribed.value && billing.pass.value === null && subscriptionCurrency.value !== undefined
154
- && pricing.currency.value !== undefined && subscriptionCurrency.value !== pricing.currency.value,
155
- })
146
+ // rule), so its confirmation states the price in it: the page's where it is
147
+ // in it, else read apart, in the browser, only while the page shows another.
148
+ const planChange = usePlanChange({ labels: () => props.labels, pricing })
156
149
  const route = useRoute()
157
150
  const { isAuthenticated } = useAuthSession()
158
151
  const config = useBackendConfig()
@@ -209,8 +202,7 @@ function resolvePlan(card: PricingPlan, offer: PricedPlan): ResolvedPlan | null
209
202
  const priceAt = offer.prices[at]!
210
203
  const isCurrent = Object.values(offer.prices).some(price => price?.productId === subscribedId.value)
211
204
  const comparable = !isCurrent && currentMonthly.value !== undefined
212
- const scheduled = billing.pendingChange.value
213
- const scheduledFor = scheduled?.productId === priceAt.productId ? scheduled.appliesAt : undefined
205
+ const scheduledFor = planChange.scheduledFor(priceAt.productId) ?? undefined
214
206
  // The free plan is free in every currency: in the page's, whatever its product's.
215
207
  const priceCurrency = offer.free ? pricing.currency.value ?? priceAt.currency : priceAt.currency
216
208
  return {
@@ -309,42 +301,18 @@ async function run(key: string, busy: () => string, action: () => Promise<unknow
309
301
  const planByKey = (key: string) => resolvedPlans.value.find(plan => plan.key === key)
310
302
 
311
303
  /**
312
- * The currency a card's price shows in, for its checkout to pay in it: a
313
- * product the catalog prices in one currency only shows, and is paid, in
314
- * that one whatever the page's. Named only where the catalog prices more
315
- * than one; a single-currency checkout keeps the provider's own.
304
+ * A checkout with the address's campaign, its discount code and UTM, in the
305
+ * currency the card's price shows in (`usePricing().checkout`'s rules): the
306
+ * table's own promotion (`discount`, else a price test's for a link with no
307
+ * code) goes in the code's place on a product it is offered on, one discount
308
+ * per checkout, and a discount the server refuses never blocks the purchase.
316
309
  */
317
- const payIn = (currency: string | undefined): { currency?: string } =>
318
- currency && pricing.currencies.value.length > 1 ? { currency } : {}
319
-
320
- /** A refusal of a checkout's discount: an expired, used-up or unknown campaign code, or a promotion no longer redeemed. */
321
- function refusedCode(failure: unknown): boolean {
322
- const refusal = getBackendError(failure)
323
- const field = (refusal?.data as { field?: unknown } | undefined)?.field
324
- return refusal?.code === 'invalid_input' && (field === 'discountCode' || field === 'discount')
325
- }
326
-
327
- /**
328
- * A checkout with the address's campaign: its discount code and UTM. The
329
- * table's own promotion (`discount`, else a price test's for a link with
330
- * no code) goes in the code's place on a product it is offered on (one
331
- * discount per checkout); elsewhere the campaign's code still goes. A discount the server refuses never blocks the purchase:
332
- * the checkout opens again without it, the attribution kept.
333
- */
334
- async function withCampaign<T>(offered: boolean, start: (campaignOptions: { discountCode?: string, discount?: string, utm?: typeof campaign.checkoutOptions.value.utm }) => Promise<T>): Promise<T> {
335
- const { discountCode, ...attribution } = campaign.checkoutOptions.value
336
- const promotion = props.discount ?? (discountCode ? undefined : experimentDiscount.value)
337
- const options = promotion && offered
338
- ? { ...attribution, discount: promotion }
339
- : { ...attribution, ...(discountCode ? { discountCode } : {}) }
340
- try {
341
- return await start(options)
342
- }
343
- catch (failure) {
344
- if (!('discountCode' in options || 'discount' in options) || !refusedCode(failure)) throw failure
345
- return start(attribution)
346
- }
347
- }
310
+ const { payIn, withCampaign } = pricingCheckout({
311
+ campaign,
312
+ asked,
313
+ active: () => pricing.activePromotion.value,
314
+ currencies: () => pricing.currencies.value,
315
+ })
348
316
 
349
317
  // The EU soft opt-in's box, under the checkout buttons while a topic takes it: ticked, the paid order joins no topic.
350
318
  const emailOptOut = ref(false)
@@ -366,7 +334,7 @@ async function checkOutFromPass(key: string): Promise<void> {
366
334
  const switchTo = (key: string) => run(key, () => t('changing'), async () => {
367
335
  const plan = planByKey(key)
368
336
  if (!plan) return
369
- await billing.changePlan(plan.priceAt.productId, { proration: CONFIRMED_PRORATION })
337
+ await planChange.switchTo(plan.priceAt.productId)
370
338
  change.settle()
371
339
  emit('plan-changed', key)
372
340
  // The step went with the switch: focus moves to the card's action, else the current plan's.
@@ -380,31 +348,6 @@ function returnTo(kind: 'plan' | 'pack', key: string): { successUrl?: string } {
380
348
  return url ? { successUrl: url } : {}
381
349
  }
382
350
 
383
- /**
384
- * The price a switch to a card's plan is about. A subscriber's is in the
385
- * subscription's currency: `null` while that price is read, `undefined`
386
- * when the plan has none in it, which no switch can move to. A gifted
387
- * plan's holder checks out, in the card's own.
388
- */
389
- function changeTarget(plan: ResolvedPlan): PlanChangeTarget | null | undefined {
390
- const price = billing.pass.value === null ? priceInSubscriptionCurrency(plan) : plan.price
391
- if (price === null) return null
392
- if (price === '') return undefined
393
- // Their own plan at the other period is named with it: "Pro, billed yearly".
394
- const name = plan.isCurrent ? t(`billedAt.${plan.interval}` as LabelKey<BackendLabels['pricing']>, { plan: plan.name }) : plan.name
395
- return { key: plan.key, productId: plan.priceAt.productId, plan: name, price: `${price}${t(`period.${plan.interval}` as LabelKey<BackendLabels['pricing']>)}` }
396
- }
397
-
398
- /** A card's price in the subscription's currency, formatted: `null` while it is read, `''` when the product has no price in it. */
399
- function priceInSubscriptionCurrency(plan: ResolvedPlan): string | null {
400
- const currency = subscriptionCurrency.value
401
- if (!currency || plan.priceAt.currency === currency) return plan.price
402
- const offers = switchPricing.plans.value
403
- if (offers === undefined) return null
404
- const at = offers.find(entry => entry.key === plan.key)?.prices[plan.interval]
405
- // A product with no price in it comes back in the catalog's currency.
406
- return at?.productId === plan.priceAt.productId && at.currency === currency ? formatBillingAmount(at.amount, at.currency, locale.value) : ''
407
- }
408
351
  const root = ref<HTMLElement | null>(null)
409
352
  // Cancelling the current plan takes one step: its button opens what ends
410
353
  // when and the one button that cancels, nothing else.
@@ -425,11 +368,11 @@ const change = createPlanChangeConfirm({
425
368
  titleTag: 'p',
426
369
  partId: part => `${uid}-change-${part}`,
427
370
  isBusy: () => pending.value !== null && pending.value === change.target.value?.key,
428
- preview: productId => billing.changeOf(productId),
371
+ change: planChange,
429
372
  confirm: target => (billing.pass.value === null ? switchTo(target.key) : checkOutFromPass(target.key)),
430
373
  t,
431
374
  date: value => formatBillingDate(value, { dateStyle: 'medium' }, locale.value) || null,
432
- gifted: target => (billing.pass.value === null ? null : t('changeGifted', { price: target.price })),
375
+ gifted: target => t('changeGifted', { price: target.price }),
433
376
  })
434
377
  function cancelPlan(key: string): Promise<void> {
435
378
  return run(key, () => t('canceling'), async () => {
@@ -539,7 +482,7 @@ function planAction(plan: ResolvedPlan): PlanAction {
539
482
  // checkout; one the preview cannot describe goes at once. One to a plan
540
483
  // with no price in the subscription's currency is none the provider
541
484
  // makes; one whose price in it is still being read waits.
542
- const target = changeTarget(plan)
485
+ const target = planChange.targetFor(plan.key, plan.interval)
543
486
  if (target === undefined) return { kind: 'none' }
544
487
  const asks = billing.pass.value !== null || billing.changeOf(plan.priceAt.productId) !== null
545
488
  const switching = (intent: string, idle: string): PlanAction => target === null
@@ -23,13 +23,12 @@ import { useApiNamespace } from '../../utils/namespace'
23
23
  const invite = useReferralInvite()
24
24
  const { t, errorMessage } = useLabels('referral')
25
25
  const home = useBackendPagePath('settings')
26
- const invitePath = useBackendPagePath('invite')
27
26
  const waitlistPath = useBackendPagePath('waitlist')
28
27
  // An app without backend/access.ts is open, and lacks no file: no warning for it.
29
28
  const { phase } = useAccessPhase({ api: useApiNamespace<AccessApiRefs>('access') ?? {} })
30
29
 
31
30
  /** The invite page, carrying this link's code: the sign-in it leads to comes back here to claim. */
32
- const inviteTo = computed(() => (invitePath.value ? `${invitePath.value}?ref=${encodeURIComponent(invite.code.value)}` : null))
31
+ const inviteTo = invite.inviteTo
33
32
  /** The visitor needs a ticket first: the app is not public, and nobody is signed in. */
34
33
  const needsTicket = computed(() => invite.state.value === 'ready' && invite.closed.value === true)
35
34
  /** A visitor's way in waits for the phase: neither the sign-up nor the ways to a ticket until it is read, or a few seconds pass. */
@@ -3,6 +3,7 @@ import { computed, resolveComponent, type Ref } from 'vue'
3
3
  import { busyAttributes } from '../../a11y'
4
4
  import { valueLabel } from '../../composables/use-labels'
5
5
  import type { EntitlementBenefit } from '../../composables/use-billing'
6
+ import type { BillingSectionAction } from '../../composables/use-billing-section'
6
7
  import type { WorkspaceBillingProps } from '../../parts'
7
8
  import CancelConfirmGroup from '../billing/CancelConfirmGroup.vue'
8
9
  import { IN_PORTAL, type PlanState } from './workspace-billing'
@@ -57,21 +58,17 @@ const words = computed(() => (section.state.value ? STATE_WORDS[section.state.va
57
58
  // Busy until the plan is known (its name reads "—" until then), unless the
58
59
  // read failed, and while a return from checkout is being finished.
59
60
  const finishing = computed(() => props.billing.isFinishingCheckout.value)
60
- const loading = computed(() => (props.billing.subscription.value === undefined && !props.billing.error.value) || finishing.value)
61
- const failed = computed(() => props.billing.subscription.value === undefined && props.billing.error.value)
61
+ const loading = section.plan.isLoading
62
+ const failed = computed(() => section.plan.state.value === 'error')
62
63
  const managing = computed(() => props.billing.canManage.value)
63
64
 
64
65
  /** A button of the section: busy while its own action runs, and keeping focus through it. */
65
66
  const pending = (key: string) => view.context.value.pending === key
66
67
  const press = (key: string, action: () => unknown) => (pending(key) ? undefined : action())
67
68
 
68
- const gifted = computed(() => section.state.value === 'gifted')
69
- const keepOffered = computed(() => gifted.value && managing.value)
70
69
  // A gifted plan has no card to cancel: the one offer is to keep it.
71
- const cancellable = computed(() => !gifted.value && !props.billing.cancelAtPeriodEnd.value && !props.billing.isPaused.value)
72
- /** The portal button comes first when a payment failed, its own action; then the plan's own ways back. A gifted plan has no card to manage. */
73
- const portalFirst = computed(() => section.state.value === 'past_due')
74
- const portalLast = computed(() => !portalFirst.value && !gifted.value)
70
+ const keepOffered = computed(() => section.actions.value.includes('keep-gifted'))
71
+ const cancellable = section.plan.cancellable
75
72
  /**
76
73
  * What "Cancel plan" opens: the one-step group, or, with save offers on,
77
74
  * `<CancelFlow>` (one optional question and at most one offer, "Cancel my
@@ -82,9 +79,6 @@ const cancelling = computed(() => {
82
79
  if (!section.confirm.isOpen.value) return { is: () => null, props: {} }
83
80
  return { is: resolveComponent('CancelFlow'), props: { id: view.partId('cancel', 'confirm'), onClose: () => section.confirm.close(), onCanceled: section.flowCanceled, onKept: section.flowKept } }
84
81
  })
85
- /** A scheduled plan change can be cancelled, unless the plan is set to end. */
86
- const changeCancellable = computed(() => props.billing.pendingChange.value !== null && !props.billing.cancelAtPeriodEnd.value)
87
-
88
82
  /** One button of the plan's row: its hook, what it carries and what it says, and where a group it opens gives focus back. */
89
83
  interface PlanButton { hook: string, attributes: Record<string, unknown>, text: string, element?: Ref<HTMLElement | null> }
90
84
  /** A button that opens and closes a group: the group's toggle, its element kept for the focus coming back. */
@@ -98,22 +92,24 @@ const runs = (hook: string, key: string, idle: string, busy: string, action: ()
98
92
  attributes: { ...busyAttributes(pending(key)), onClick: () => press(key, action) },
99
93
  text: pending(key) ? busy : idle,
100
94
  })
95
+ /** Each button of the plan's row, by what it offers; keeping a gifted plan has a row of its own. */
96
+ const BUTTONS: Record<Exclude<BillingSectionAction, 'keep-gifted'>, () => PlanButton> = {
97
+ // A failed payment's portal button says what it is for.
98
+ 'portal': () => runs('portal', 'portal', section.state.value === 'past_due' ? t('updatePayment') : t('portal'), t('openingPortal'), section.openPortal),
99
+ 'resume': () => runs('resume', 'resume', t('resume'), t('resuming'), section.resumePlan),
100
+ 'uncancel': () => runs('uncancel', 'uncancel', t('keepPlan'), t('keeping'), section.keepPlan),
101
+ 'cancel-change': () => runs('cancel-change', 'cancel-change', t('cancelChange'), t('cancelingChange'), section.cancelChange),
102
+ 'change-plan': () => opens('change-plan', t('changePlan'), section.switchToggleProps()),
103
+ 'pause': () => opens('pause', t('pause'), section.pauseToggleProps()),
104
+ 'cancel': () => opens('cancel', t('cancel'), section.confirm.toggleProps()),
105
+ }
101
106
  /**
102
- * The plan's buttons, in order. What they offer follows the subscription,
103
- * not only the state its line reads as: a plan set to cancel offers Keep
104
- * plan, and one with a change scheduled offers to cancel the change,
105
- * whatever else holds.
107
+ * The plan's buttons, in the order `useBillingSection().actions` offers
108
+ * them. What they offer follows the subscription, not only the state its
109
+ * line reads as: a plan set to cancel offers Keep plan, and one with a
110
+ * change scheduled offers to cancel the change, whatever else holds.
106
111
  */
107
- const actions = computed<PlanButton[]>(() => [
108
- portalFirst.value && runs('portal', 'portal', t('updatePayment'), t('openingPortal'), section.openPortal),
109
- props.billing.isPaused.value && runs('resume', 'resume', t('resume'), t('resuming'), section.resumePlan),
110
- props.billing.cancelAtPeriodEnd.value && runs('uncancel', 'uncancel', t('keepPlan'), t('keeping'), section.keepPlan),
111
- changeCancellable.value && runs('cancel-change', 'cancel-change', t('cancelChange'), t('cancelingChange'), section.cancelChange),
112
- portalLast.value && runs('portal', 'portal', t('portal'), t('openingPortal'), section.openPortal),
113
- section.switchable.value && opens('change-plan', t('changePlan'), section.switchToggleProps()),
114
- section.pausable.value && opens('pause', t('pause'), section.pauseToggleProps()),
115
- cancellable.value && opens('cancel', t('cancel'), section.confirm.toggleProps()),
116
- ].filter((button): button is PlanButton => button !== false))
112
+ const actions = computed<PlanButton[]>(() => section.actions.value.flatMap(action => (action === 'keep-gifted' ? [] : [BUTTONS[action]()])))
117
113
 
118
114
  /** One benefit: its name (else what it gives), what it gives, and what it holds. */
119
115
  const kind = (benefit: EntitlementBenefit) => valueLabel(labels, 'settings', 'benefitKinds', benefit.kind ?? 'other')
@@ -2,7 +2,6 @@
2
2
  import { computed } from 'vue'
3
3
  import { busyAttributes } from '../../a11y'
4
4
  import { closesOnEscape } from '../../utils/confirm-group'
5
- import { PAUSE_MONTHS } from './workspace-billing'
6
5
  import { useWorkspaceSettingsView } from './workspace-settings'
7
6
 
8
7
  /**
@@ -46,7 +45,7 @@ const busy = computed(() => view.context.value.pending === 'pause')
46
45
  {{ t('pauseFor') }}
47
46
  </legend>
48
47
  <label
49
- v-for="months in PAUSE_MONTHS"
48
+ v-for="months in section.plan.pauseLengths"
50
49
  :key="months"
51
50
  data-settings="pause-length"
52
51
  >
@@ -4,10 +4,10 @@ import { useBackendConfig } from '../../composables/use-backend-config'
4
4
  import { useBackendPagePath } from '../../composables/use-backend-page-path'
5
5
  import { formatBillingAmount } from '../../composables/billing-format'
6
6
  import { useBilling } from '../../composables/use-billing'
7
+ import { useBillingSection } from '../../composables/use-billing-section'
7
8
  import { useCredits } from '../../composables/use-credits'
8
9
  import { useFeatures } from '../../composables/use-features'
9
10
  import { refusalText, useLabels, type BackendLabels, type LabelKey, type LabelOverrides } from '../../composables/use-labels'
10
- import { usePricing } from '../../composables/use-pricing'
11
11
  import { useWorkspace, type Workspace } from '../../composables/use-workspace'
12
12
  import { inLocale } from '../../utils/intl'
13
13
  import { useSettingsMessage } from '../../utils/settings-message'
@@ -61,14 +61,11 @@ const workspace = useWorkspace()
61
61
  const billing = useBilling()
62
62
  const credits = useCredits()
63
63
  const features = useFeatures()
64
- // The prices a plan can switch to, read in the browser only, and only when the plan section shows,
65
- // in the subscription's own currency: the provider keeps it on a plan change, so a
66
- // subscriber who pays in dollars is shown dollars wherever they are.
67
- const subscriptionCurrency = () => {
68
- const currency = billing.subscription.value?.currency
69
- return typeof currency === 'string' ? currency : undefined
70
- }
71
- const pricing = usePricing({ server: false, actions: false, currency: subscriptionCurrency, enabled: () => props.sections.includes('billing') })
64
+ // The plan's state and its rules. The prices it can switch to are read in the
65
+ // browser only, only when the plan section shows, and in the subscription's own
66
+ // currency: the provider keeps it on a plan change, so a subscriber who pays in
67
+ // dollars is shown dollars wherever they are.
68
+ const plan = useBillingSection({ enabled: () => props.sections.includes('billing') })
72
69
  const config = useBackendConfig()
73
70
  const labels = useLabels('settings', () => props.labels)
74
71
  const { t, locale } = labels
@@ -161,38 +158,28 @@ const packs = computed<CreditPack[]>(() => config.billing.packs.length > 0
161
158
  : Object.entries(products.value).flatMap(([key, product]) => product?.isRecurring === false && product.isArchived !== true ? [{ key }] : []))
162
159
 
163
160
  /**
164
- * Every price on sale the plan can switch to: each plan at each period, but
165
- * the one the subscription is on, and any with no price in the
166
- * subscription's currency (it comes back in the catalog's), which the
167
- * provider would refuse to switch to.
161
+ * Every price on sale the plan can switch to (`useBillingSection().change.targets`),
162
+ * in the section's words: each named with its period, priced in the
163
+ * subscription's currency.
168
164
  */
169
165
  function switchOptions(): PlanSwitchOption[] {
170
- const current = billing.subscription.value?.productId
171
- const currency = subscriptionCurrency()?.toLowerCase()
172
- return (pricing.plans.value ?? []).flatMap((plan) => {
173
- if (plan.free || plan.retired) return []
174
- return (['month', 'year'] as const).flatMap((interval) => {
175
- const price = plan.prices[interval]
176
- if (!price || price.archived || price.productId === current || (currency !== undefined && price.currency !== currency)) return []
177
- return [{
178
- key: price.productId,
179
- productId: price.productId,
180
- plan: t(`billedAt.${interval}` as LabelKey<BackendLabels['settings']>, { plan: plan.name }),
181
- price: `${formatBillingAmount(price.amount, price.currency, locale.value)}${t(`period.${interval}` as LabelKey<BackendLabels['settings']>)}`,
182
- }]
183
- })
184
- })
166
+ return (plan.change.targets.value ?? []).map(target => ({
167
+ key: target.productId,
168
+ productId: target.productId,
169
+ plan: t(`billedAt.${target.interval}` as LabelKey<BackendLabels['settings']>, { plan: target.name }),
170
+ price: `${formatBillingAmount(target.amount, target.currency, locale.value)}${t(`period.${target.interval}` as LabelKey<BackendLabels['settings']>)}`,
171
+ }))
185
172
  }
186
173
 
187
174
  const section = createBillingSection({
188
175
  billing,
176
+ plan,
189
177
  features,
190
178
  labels,
191
179
  pending,
192
180
  run,
193
181
  partId,
194
182
  productName,
195
- giftedProduct: plan => products.value[plan]?.id,
196
183
  switchOptions,
197
184
  // One event per outcome; the union reads as each of them.
198
185
  notify: (event, argument) => (emit as (event: string, ...args: unknown[]) => void)(event, ...(argument === undefined ? [] : [argument])),