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
@@ -0,0 +1,76 @@
1
+ import { computed, toValue } from "vue";
2
+ import { addMonths } from "../../../convex/catalog.js";
3
+ import { useActionState } from "../utils/action-state.js";
4
+ import { toBillingDate } from "./billing-format.js";
5
+ import { useBilling } from "./use-billing.js";
6
+ import { usePlanChange } from "./use-plan-change.js";
7
+ export const PLAN_STATES = ["gifted", "past_due", "paused", "canceling", "changing", "trialing", "active"];
8
+ export const PAUSE_MONTHS = [1, 2, 3];
9
+ export function useBillingSection(options = {}) {
10
+ const billing = useBilling();
11
+ const change = usePlanChange({ labels: () => toValue(options.labels), enabled: () => toValue(options.enabled) !== false });
12
+ const gifted = computed(() => billing.pass.value !== null);
13
+ const holds = {
14
+ gifted: () => gifted.value,
15
+ past_due: () => billing.isPastDue.value,
16
+ paused: () => billing.isPaused.value,
17
+ canceling: () => billing.cancelAtPeriodEnd.value,
18
+ changing: () => billing.pendingChange.value !== null,
19
+ trialing: () => billing.isTrialing.value,
20
+ active: () => true
21
+ };
22
+ const unknown = computed(() => billing.subscription.value === void 0);
23
+ const state = computed(() => {
24
+ if (unknown.value) return billing.error.value ? "error" : "loading";
25
+ if (!billing.isSubscribed.value) return "free";
26
+ return PLAN_STATES.find((key) => holds[key]()) ?? "active";
27
+ });
28
+ const running = computed(() => billing.isSubscribed.value && !gifted.value && !billing.cancelAtPeriodEnd.value && !billing.isPaused.value);
29
+ const switchable = computed(() => running.value && billing.pendingChange.value === null && (change.targets.value?.length ?? 0) > 0);
30
+ const pausable = computed(() => running.value && !billing.isPastDue.value && !billing.isTrialing.value && billing.resumesAt.value === null);
31
+ const actions = computed(() => {
32
+ const now = state.value;
33
+ if (!PLAN_STATES.includes(now) || !billing.canManage.value) return [];
34
+ const offered = [
35
+ gifted.value && "keep-gifted",
36
+ // A failed payment's first way back is the payment method.
37
+ now === "past_due" && "portal",
38
+ billing.isPaused.value && "resume",
39
+ billing.cancelAtPeriodEnd.value && "uncancel",
40
+ billing.pendingChange.value !== null && !billing.cancelAtPeriodEnd.value && "cancel-change",
41
+ // A gifted plan has no card to manage.
42
+ now !== "past_due" && !gifted.value && "portal",
43
+ switchable.value && "change-plan",
44
+ pausable.value && "pause",
45
+ running.value && "cancel"
46
+ ];
47
+ return offered.filter((action) => action !== false);
48
+ });
49
+ const resumesAfter = (months) => {
50
+ const end = toBillingDate(billing.subscription.value?.currentPeriodEnd);
51
+ return end ? new Date(addMonths(end.getTime(), months)) : null;
52
+ };
53
+ const { isPending, failure, run } = useActionState();
54
+ return {
55
+ state,
56
+ isLoading: computed(() => unknown.value && !billing.error.value || billing.isFinishingCheckout.value),
57
+ isPending,
58
+ error: computed(() => failure.value ?? (unknown.value ? billing.error.value : null)),
59
+ actions,
60
+ switchable,
61
+ pausable,
62
+ cancellable: running,
63
+ pauseLengths: PAUSE_MONTHS,
64
+ resumesAfter,
65
+ pause: (months) => {
66
+ const resumesAt = resumesAfter(months);
67
+ return run(() => billing.pause(resumesAt ? { resumesAt } : {}), { silent: true });
68
+ },
69
+ keepGifted: async (checkout = {}) => {
70
+ const plan = billing.pass.value?.plan;
71
+ const product = plan ? billing.products.value?.[plan]?.id : void 0;
72
+ if (product) await run(() => billing.checkout(product, { redirect: true, ...checkout }), { silent: true });
73
+ },
74
+ change
75
+ };
76
+ }
@@ -1,27 +1,16 @@
1
1
  import { computed, onMounted, ref } from "vue";
2
- import { navigateTo, tryUseNuxtApp, useRoute, useRouter } from "#imports";
3
- import { DELIVER_AHEAD_DAYS, MESSAGE_LENGTH } from "../../../convex/integrations/billing/gift-rules.js";
2
+ import { navigateTo, useRoute, useRouter } from "#imports";
3
+ import { MESSAGE_LENGTH } from "../../../convex/integrations/billing/gift-rules.js";
4
4
  import { useAuthSession } from "../utils/auth-session.js";
5
5
  import { useActiveLocale } from "../utils/active-locale.js";
6
6
  import { failureOf } from "../utils/backend-error.js";
7
- import { onSite, usePageClock } from "../utils/pricing-bindings.js";
7
+ import { giftDeliveryTime, useGiftDays } from "../utils/gift-days.js";
8
+ import { onSite } from "../utils/pricing-bindings.js";
8
9
  import { formatBillingAmount } from "./billing-format.js";
9
10
  import { useBackendPagePath } from "./use-backend-page-path.js";
10
11
  import { useGifts } from "./use-gifts.js";
11
12
  import { usePricing } from "./use-pricing.js";
12
13
  export const GIFT_MESSAGE_MAX = MESSAGE_LENGTH;
13
- const DAY_MS = 24 * 60 * 60 * 1e3;
14
- const DELIVERY_HOUR = 9;
15
- const isoDay = (at) => new Date(at).toISOString().slice(0, 10);
16
- function localDay(at) {
17
- const date = new Date(at);
18
- const pad = (value) => String(value).padStart(2, "0");
19
- return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
20
- }
21
- function deliveryTime(day) {
22
- const [year, month, date] = day.split("-").map(Number);
23
- return new Date(year, month - 1, date, DELIVERY_HOUR).getTime();
24
- }
25
14
  export function useGiftForm(options = {}) {
26
15
  const route = useRoute();
27
16
  const router = useRouter();
@@ -81,13 +70,7 @@ export function useGiftForm(options = {}) {
81
70
  const length = lengths.value.find((entry) => entry.months === months.value);
82
71
  return chosenPlan.value && length ? { kind: "pass", key: chosenPlan.value.key, name: chosenPlan.value.name, months: length.months, amount: length.amount, currency: length.currency, price: formatBillingAmount(length.amount, length.currency, locale()) } : null;
83
72
  });
84
- const clock = usePageClock();
85
- const ownCalendar = ref(import.meta.client && !tryUseNuxtApp()?.isHydrating);
86
- onMounted(() => {
87
- ownCalendar.value = true;
88
- });
89
- const today = computed(() => ownCalendar.value ? localDay(clock.value) : isoDay(clock.value));
90
- const lastDay = computed(() => isoDay(Date.parse(today.value) + (DELIVER_AHEAD_DAYS - 1) * DAY_MS));
73
+ const { firstDay, lastDay } = useGiftDays();
91
74
  onMounted(() => {
92
75
  if (route.query.sent === void 0) return;
93
76
  sent.value = true;
@@ -126,7 +109,7 @@ export function useGiftForm(options = {}) {
126
109
  recipientEmail: recipientEmail.value.trim(),
127
110
  ...note ? { message: note } : {},
128
111
  // The morning of the day picked, in the purchaser's time zone: a morning already past sends it at once.
129
- ...deliverOn.value ? { deliverAt: deliveryTime(deliverOn.value) } : {},
112
+ ...deliverOn.value ? { deliverAt: giftDeliveryTime(deliverOn.value) } : {},
130
113
  ...chosen.kind === "pass" ? { months: chosen.months } : {},
131
114
  ...pricing.currency.value ? { currency: pricing.currency.value } : {},
132
115
  ...returnTo ? { successUrl: returnTo } : {},
@@ -152,7 +135,7 @@ export function useGiftForm(options = {}) {
152
135
  recipientEmail,
153
136
  message,
154
137
  deliverOn,
155
- firstDay: computed(() => today.value),
138
+ firstDay,
156
139
  lastDay,
157
140
  choice,
158
141
  isSignedIn: computed(() => auth.isAuthenticated.value),
@@ -73,7 +73,24 @@ export interface UseGiftListReturn {
73
73
  claim: (giftId: string) => Promise<GiftClaimOutcome | null>;
74
74
  resend: (giftId: string) => Promise<void>;
75
75
  changeRecipient: (giftId: string, recipientEmail: string) => Promise<boolean>;
76
- reschedule: (giftId: string, deliverAt: string) => Promise<boolean>;
76
+ /**
77
+ * Move a scheduled gift's delivery, the way a new gift is dated: a day
78
+ * (`YYYY-MM-DD`, as a date input between `firstDay` and `lastDay`
79
+ * writes it) goes out at 09:00 the purchaser's time, as `useGiftForm`
80
+ * sends one; a moment (a `datetime-local` value, a `Date`) goes out
81
+ * then. A day now or past delivers it at once; one past the server's
82
+ * year ahead is refused (`invalid_input` on `deliverAt`, in `error`).
83
+ * Resolves whether it went through.
84
+ */
85
+ reschedule: (giftId: string, deliverAt: string | Date) => Promise<boolean>;
86
+ /**
87
+ * The first day a reschedule takes, `YYYY-MM-DD`: a date input's `min`.
88
+ * Today in the purchaser's own calendar once the page is on screen, as
89
+ * `useGiftForm().firstDay` reads it.
90
+ */
91
+ firstDay: ComputedRef<string>;
92
+ /** The last day it takes, a year after the first, inside the server's window: a date input's `max`. */
93
+ lastDay: ComputedRef<string>;
77
94
  cancel: (giftId: string) => Promise<void>;
78
95
  labels: ReturnType<typeof useLabels<'gift'>>;
79
96
  }
@@ -5,6 +5,7 @@ import { refusalText, useLabels } from "./use-labels.js";
5
5
  import { usePricing } from "./use-pricing.js";
6
6
  import { useReauthentication } from "./use-reauthentication.js";
7
7
  import { useWorkspace } from "./use-workspace.js";
8
+ import { giftDeliveryTime, isGiftDay, useGiftDays } from "../utils/gift-days.js";
8
9
  import { useMeterUnit } from "../utils/meter-unit.js";
9
10
  export function useGiftList(options = {}) {
10
11
  const gifts = useGifts();
@@ -14,6 +15,7 @@ export function useGiftList(options = {}) {
14
15
  const unit = useMeterUnit();
15
16
  const { t, locale } = labels;
16
17
  const { withReauthentication } = useReauthentication();
18
+ const { firstDay, lastDay } = useGiftDays();
17
19
  const target = ref({});
18
20
  const announcement = ref("");
19
21
  const busy = ref(null);
@@ -101,9 +103,12 @@ export function useGiftList(options = {}) {
101
103
  return done === true;
102
104
  },
103
105
  reschedule: async (giftId, deliverAt) => {
104
- const done = await act(giftId, "rescheduled", () => gifts.reschedule(giftId, new Date(deliverAt)).then(() => true));
106
+ const at = typeof deliverAt === "string" && isGiftDay(deliverAt) ? new Date(giftDeliveryTime(deliverAt)) : new Date(deliverAt);
107
+ const done = await act(giftId, "rescheduled", () => gifts.reschedule(giftId, at).then(() => true));
105
108
  return done === true;
106
109
  },
110
+ firstDay,
111
+ lastDay,
107
112
  // A cancel moves money back: the person confirms a recent sign-in first.
108
113
  cancel: async (giftId) => {
109
114
  await act(giftId, "canceled", () => withReauthentication(() => gifts.cancel(giftId)));
@@ -0,0 +1,148 @@
1
+ import { type ComputedRef, type MaybeRefOrGetter, type Ref } from 'vue';
2
+ import type { BackendError } from '../utils/backend-error.js';
3
+ import { type CheckoutOptions, type PlanChangePreview } from './use-billing.js';
4
+ import { type LabelGroupOverrides } from './use-labels.js';
5
+ import { type PricingInterval, type UsePricingReturn } from './use-pricing.js';
6
+ /** A price a subscription's switch moves to, as its confirmation names it. */
7
+ export interface PlanChangeTarget {
8
+ /** The product to switch to: one price of a plan. */
9
+ productId: string;
10
+ /** The plan as the confirmation names it: `Team`, `Pro, billed yearly`. */
11
+ plan: string;
12
+ /** Its price with its period, formatted: `$29/mo`. */
13
+ price: string;
14
+ /** Who opened the confirmation, to tell two openers apart: a plan card's key. Default: `productId`. */
15
+ key?: string;
16
+ }
17
+ /** One price the subscription can switch to, in its own currency ({@link UsePlanChangeReturn.targets}). */
18
+ export interface PlanSwitchTarget extends Required<PlanChangeTarget> {
19
+ /** Its plan's catalog key (`'team'`). */
20
+ key: string;
21
+ /** The plan's own name, as the provider lists it. */
22
+ name: string;
23
+ /** The interval the price bills at. */
24
+ interval: PricingInterval;
25
+ /** What one interval costs, in the currency's smallest unit. */
26
+ amount: number;
27
+ /** Lower-case ISO 4217 code: the subscription's own, where it is known. */
28
+ currency: string;
29
+ }
30
+ /**
31
+ * How a switch goes: `'now'` at once, `'period_end'` when the paid year
32
+ * runs out (`useBilling().changeOf` says which), `'checkout'` for a gifted
33
+ * plan's holder, whose switch is a checkout of the plan that ends the gift.
34
+ */
35
+ export type PlanChangeApplies = PlanChangePreview['applies'] | 'checkout';
36
+ /** Options for {@link usePlanChange}. */
37
+ export interface UsePlanChangeOptions {
38
+ /** Copy for the confirmation, over `appConfig.backend.labels.pricing` and the translations. */
39
+ labels?: MaybeRefOrGetter<LabelGroupOverrides<'pricing'> | undefined>;
40
+ /**
41
+ * The pricing your page reads already (`usePricing()`): its prices stand
42
+ * for the switch's wherever they are in the subscription's currency, so
43
+ * no second pricing is read for a page in it. A page in another currency
44
+ * still reads the subscription's. Its `currencies` and `error` count
45
+ * too where it has them: a gifted plan's checkout pays in the currency
46
+ * its card shows where the catalog prices more than one, and a failed
47
+ * read ends the wait.
48
+ */
49
+ pricing?: Pick<UsePricingReturn, 'plans' | 'currency'> & Partial<Pick<UsePricingReturn, 'currencies' | 'error'>>;
50
+ /** While this is `false` no pricing is read for the switch, and nothing is a target (default `true`). */
51
+ enabled?: MaybeRefOrGetter<boolean>;
52
+ }
53
+ /** What {@link usePlanChange} returns. */
54
+ export interface UsePlanChangeReturn {
55
+ /**
56
+ * Every price the subscription can switch to: each plan on sale at each
57
+ * interval in the subscription's own currency, which the provider keeps
58
+ * on a switch, the plan's own other period included. Never the price it
59
+ * is on, the free plan, a retired plan, an archived price, the price a
60
+ * scheduled change moves to (`scheduledFor`), nor one with no price in
61
+ * that currency, which the provider would refuse. For a gifted plan's
62
+ * holder, whose switch is a checkout, every paid plan's price as the
63
+ * pricing shows it. `[]` without a plan to switch from (none, the free
64
+ * plan, still loading); `undefined` while the prices are read.
65
+ */
66
+ targets: ComputedRef<PlanSwitchTarget[] | undefined>;
67
+ /**
68
+ * The target for one plan's card: the price of the plan `key` at
69
+ * `interval`, as `targets` lists it. `null` while its price in the
70
+ * subscription's currency is read; `undefined` when there is no switch
71
+ * to it, which a card shows no switch button for.
72
+ */
73
+ targetFor: (key: string, interval: PricingInterval) => PlanSwitchTarget | null | undefined;
74
+ /** When a change scheduled for the period's end moves the subscription to `productId`, else `null`: say when, rather than offer it again. */
75
+ scheduledFor: (productId: string) => Date | null;
76
+ /** The switch waiting on the person's confirmation, `null` while none is open. */
77
+ target: Ref<Required<PlanChangeTarget> | null>;
78
+ /** What that switch would do (`useBilling().changeOf`); `null` while none is open, for a gifted plan's, and for one there is nothing to preview. */
79
+ preview: ComputedRef<PlanChangePreview | null>;
80
+ /** How that switch goes; `null` while none is open, or for one there is nothing to say about. */
81
+ applies: ComputedRef<PlanChangeApplies | null>;
82
+ /** The confirmation's question, "Switch to Team?"; `''` while none is open. */
83
+ title: ComputedRef<string>;
84
+ /**
85
+ * When the switch happens and how the period's difference is settled, in
86
+ * the reader's words: at once with the difference settled now, when the
87
+ * paid year runs out, and in a trial, whether it carries over, ends with
88
+ * a first payment, or waits for its end; for a gifted plan's holder, that
89
+ * the checkout ends the gift. What the switch `confirm` makes does. `''`
90
+ * while none is open.
91
+ */
92
+ when: ComputedRef<string>;
93
+ /** Ask about a switch: `target`, `preview` and the words follow it. */
94
+ open: (target: PlanChangeTarget) => void;
95
+ /** Close the confirmation without switching. */
96
+ close: () => void;
97
+ /**
98
+ * Make the switch the confirmation is open for, then close it: a
99
+ * subscriber's `changePlan(productId, { proration: 'invoice' })`, so the
100
+ * difference settles now as `when` says, whatever the organization's
101
+ * default; a gifted plan's holder's checkout of the plan, which ends the
102
+ * gift, with the address's campaign (its code and attribution, a refused
103
+ * code dropped) and in the currency its price shows where the catalog
104
+ * prices more than one, as `<PricingTable>` checks it out (`options` go
105
+ * with it, over those, `{ redirect: true }` by default). Rejects
106
+ * with what the call threw, `error` holds it too, and the confirmation
107
+ * stays open.
108
+ */
109
+ confirm: (options?: CheckoutOptions) => Promise<void>;
110
+ /** Switch to `productId` at once, past any confirmation, settling the period's difference now (`proration: 'invoice'`): the switch `changeOf` describes. */
111
+ switchTo: (productId: string) => Promise<void>;
112
+ /** `true` until the switch's prices are known (`false` without a plan to switch from, and once the read failed). */
113
+ isLoading: ComputedRef<boolean>;
114
+ /** `true` while a switch or a gifted plan's checkout is on its way. */
115
+ isPending: ComputedRef<boolean>;
116
+ /** Why the last switch failed, else why the prices could not be read, else `null`. */
117
+ error: ComputedRef<BackendError | null>;
118
+ }
119
+ /**
120
+ * A subscriber's switch to another plan or billing period, without its
121
+ * markup: the prices it can move to, in the subscription's own currency,
122
+ * and one confirmation that says what the switch does before it does it —
123
+ * the price, when it happens (a yearly price left for a monthly one waits
124
+ * for the paid year's end) and how the period's difference is settled, or,
125
+ * in a trial, what becomes of it — then the switch itself, settling that
126
+ * difference at once (`proration: 'invoice'`), so the words stay true
127
+ * whatever the organization's default. A gifted plan's holder is asked
128
+ * too: their switch is a checkout of the new plan, which ends the gift.
129
+ * What `<PricingTable>` and the billing section of `/settings` confirm.
130
+ *
131
+ * @example
132
+ * ```vue
133
+ * <script setup lang="ts">
134
+ * const change = usePlanChange()
135
+ * </script>
136
+ * <template>
137
+ * <button v-for="target in change.targets.value" :key="target.productId" @click="change.open(target)">
138
+ * {{ target.plan }} · {{ target.price }}
139
+ * </button>
140
+ * <div v-if="change.target.value" role="group" :aria-label="change.title.value">
141
+ * <p>{{ change.title.value }} {{ change.when.value }}</p>
142
+ * <button :aria-disabled="change.isPending.value || undefined" @click="change.confirm()">Confirm switch</button>
143
+ * <button @click="change.close()">Not now</button>
144
+ * </div>
145
+ * </template>
146
+ * ```
147
+ */
148
+ export declare function usePlanChange(options?: UsePlanChangeOptions): UsePlanChangeReturn;
@@ -0,0 +1,130 @@
1
+ import { computed, ref, toValue } from "vue";
2
+ import { CATALOG_INTERVALS } from "../../../convex/catalog.js";
3
+ import { useActionState } from "../utils/action-state.js";
4
+ import { CONFIRMED_PRORATION, planChangeWhen } from "../utils/plan-change-confirm.js";
5
+ import { pricingCheckout } from "../utils/pricing-checkout.js";
6
+ import { formatBillingAmount, formatBillingDate } from "./billing-format.js";
7
+ import { useBilling } from "./use-billing.js";
8
+ import { useCampaign } from "./use-campaign.js";
9
+ import { useLabels } from "./use-labels.js";
10
+ import { usePricing } from "./use-pricing.js";
11
+ export function usePlanChange(options = {}) {
12
+ const billing = useBilling();
13
+ const { t, locale } = useLabels("pricing", () => toValue(options.labels));
14
+ const enabled = () => toValue(options.enabled) !== false;
15
+ const shown = options.pricing;
16
+ const gifted = computed(() => billing.pass.value !== null);
17
+ const currency = computed(() => {
18
+ const code = billing.subscription.value?.currency;
19
+ return !gifted.value && typeof code === "string" && code !== "" ? code.toLowerCase() : void 0;
20
+ });
21
+ const own = usePricing({
22
+ server: false,
23
+ actions: false,
24
+ currency: () => currency.value,
25
+ enabled: () => enabled() && billing.isSubscribed.value && (shown === void 0 || currency.value !== void 0 && shown.currency.value !== void 0 && shown.currency.value !== currency.value)
26
+ });
27
+ const plans = computed(() => (shown ?? own).plans.value);
28
+ function priceAt(key, interval) {
29
+ const page = shown?.plans.value;
30
+ if (shown && page === void 0) return null;
31
+ const offered = page?.find((plan) => plan.key === key)?.prices[interval];
32
+ if (shown) {
33
+ if (!offered) return void 0;
34
+ if (currency.value === void 0 || offered.currency === currency.value) return offered;
35
+ if (shown.currency.value === currency.value) return void 0;
36
+ }
37
+ const read = own.plans.value;
38
+ if (read === void 0) return null;
39
+ const at = read.find((plan) => plan.key === key)?.prices[interval];
40
+ return at && (currency.value === void 0 || at.currency === currency.value) && (!offered || at.productId === offered.productId) ? at : void 0;
41
+ }
42
+ const pending = computed(() => billing.pendingChange.value);
43
+ const ownPlan = (plan) => Object.values(plan.prices).some((price) => price?.productId === billing.subscription.value?.productId);
44
+ function targetOf(plan, interval, price) {
45
+ if (plan.free || plan.retired || price.archived) return void 0;
46
+ if (price.productId === billing.subscription.value?.productId || price.productId === pending.value?.productId) return void 0;
47
+ return {
48
+ key: plan.key,
49
+ productId: price.productId,
50
+ name: plan.name,
51
+ // Its own plan at the other period is named with it: "Pro, billed yearly".
52
+ plan: ownPlan(plan) ? t(`billedAt.${interval}`, { plan: plan.name }) : plan.name,
53
+ price: `${formatBillingAmount(price.amount, price.currency, locale.value)}${t(`period.${interval}`)}`,
54
+ interval,
55
+ amount: price.amount,
56
+ currency: price.currency
57
+ };
58
+ }
59
+ const switches = () => enabled() && billing.isSubscribed.value;
60
+ const targets = computed(() => {
61
+ if (!switches()) return [];
62
+ const list = plans.value;
63
+ if (list === void 0) return void 0;
64
+ const found = [];
65
+ for (const plan of list) {
66
+ if (plan.free || plan.retired) continue;
67
+ for (const interval of CATALOG_INTERVALS) {
68
+ if (!plan.prices[interval]) continue;
69
+ const price = priceAt(plan.key, interval);
70
+ if (price === null) return void 0;
71
+ const target2 = price && targetOf(plan, interval, price);
72
+ if (target2) found.push(target2);
73
+ }
74
+ }
75
+ return found;
76
+ });
77
+ const target = ref(null);
78
+ const preview = computed(() => target.value ? billing.changeOf(target.value.productId) : null);
79
+ const applies = computed(() => target.value === null ? null : gifted.value ? "checkout" : preview.value?.applies ?? null);
80
+ const { isPending, failure, run } = useActionState();
81
+ const { payIn, withCampaign } = pricingCheckout({
82
+ campaign: useCampaign(),
83
+ asked: () => void 0,
84
+ active: () => void 0,
85
+ currencies: () => shown?.currencies?.value ?? own.currencies.value
86
+ });
87
+ const currencyOf = (productId) => plans.value?.flatMap((entry) => Object.values(entry.prices)).find((price) => price?.productId === productId)?.currency;
88
+ const switchTo = (productId) => run(() => billing.changePlan(productId, { proration: CONFIRMED_PRORATION }), { silent: true });
89
+ return {
90
+ targets,
91
+ targetFor: (key, interval) => {
92
+ if (!switches()) return void 0;
93
+ const plan = plans.value?.find((entry) => entry.key === key);
94
+ if (!plan?.prices[interval]) return plans.value === void 0 ? null : void 0;
95
+ if (plan.free || plan.retired) return void 0;
96
+ const price = priceAt(key, interval);
97
+ return price === null ? null : price && targetOf(plan, interval, price);
98
+ },
99
+ scheduledFor: (productId) => pending.value?.productId === productId ? pending.value.appliesAt : null,
100
+ target,
101
+ preview,
102
+ applies,
103
+ title: computed(() => target.value ? t("changeTitle", { plan: target.value.plan }) : ""),
104
+ when: computed(() => target.value ? planChangeWhen({
105
+ applies: applies.value,
106
+ preview: preview.value,
107
+ price: target.value.price,
108
+ gifted: t("changeGifted", { price: target.value.price }),
109
+ t,
110
+ date: (value) => formatBillingDate(value, { dateStyle: "medium" }, locale.value) || null
111
+ }) : ""),
112
+ open: (next) => {
113
+ target.value = { ...next, key: next.key ?? next.productId };
114
+ },
115
+ close: () => {
116
+ target.value = null;
117
+ },
118
+ confirm: async (checkout = {}) => {
119
+ const chosen = target.value;
120
+ if (!chosen) return;
121
+ if (gifted.value) await run(() => withCampaign(false, (campaign) => billing.checkout(chosen.productId, { redirect: true, ...payIn(currencyOf(chosen.productId)), ...campaign, ...checkout })), { silent: true });
122
+ else await switchTo(chosen.productId);
123
+ if (target.value === chosen) target.value = null;
124
+ },
125
+ switchTo,
126
+ isLoading: computed(() => switches() && targets.value === void 0 && own.error.value === null && (shown?.error?.value ?? null) === null),
127
+ isPending,
128
+ error: computed(() => failure.value ?? own.error.value ?? shown?.error?.value ?? null)
129
+ };
130
+ }
@@ -4,6 +4,7 @@ import { type CatalogInterval } from '../../../convex/catalog.js';
4
4
  import type { PricedPack, PricedPlan, PricedPromotion, Pricing } from '../../../convex/integrations/billing/types/records.js';
5
5
  import { type BackendError } from '../utils/backend-error.js';
6
6
  import { type PricingBindings } from '../utils/pricing-bindings.js';
7
+ import { type CheckoutOptions } from './use-billing.js';
7
8
  export type { PricingBindings } from '../utils/pricing-bindings.js';
8
9
  export type { PricedCredits, PricedOffer, PricedPack, PricedPlan, PricedPlanPrice, PricedPromotion, PricedTrial, Pricing } from '../../../convex/integrations/billing/types/records.js';
9
10
  /** A billing interval a plan is priced at. */
@@ -148,6 +149,34 @@ export interface UsePricingReturn {
148
149
  packFor: (units: number, meter?: string) => PricedPack | undefined;
149
150
  /** Read the pricing again. It is live already; this is for a retry after a failure. */
150
151
  refresh: () => Promise<void>;
152
+ /**
153
+ * Check a plan out, at the price its card shows (the `interval` shown,
154
+ * else the one it sells at), or a credit pack, the way `<PricingTable>`
155
+ * does: with the address's campaign (`useCampaign`), the promotion this
156
+ * pricing shows (`discount`) in the place of the campaign link's code on
157
+ * a price it is offered on, one discount per checkout, and, when the
158
+ * server refuses that discount, once more without it, so a dead code never
159
+ * blocks the purchase; in the currency the price shows in where the
160
+ * catalog prices more than one; back where `successUrl` says. A plan's
161
+ * promotion is not offered to a paying subscriber, whose plan changes
162
+ * rather than checks out (`usePlanChange`). `options` go with it, over
163
+ * what it picks; a discount of their own goes in the campaign's place.
164
+ * Resolves the checkout's URL, opened in this tab unless `options` say
165
+ * `redirect: false`. Rejects with what the call threw, and as
166
+ * `invalid_input` (`field` `plan` or `pack`) for a key nothing on
167
+ * sale has. A visitor signs in first: `bind.planAction` takes them there.
168
+ */
169
+ checkout: (kind: 'plan' | 'pack', key: string, options?: CheckoutOptions) => Promise<string>;
170
+ /**
171
+ * The plans and packs on sale as schema.org `Product`s with an `Offer`
172
+ * per price, for a `<script type="application/ld+json">` of a pricing
173
+ * page of your own: each price in the currency's main unit with its own
174
+ * digits (19.99 USD, 1999 JPY), a plan's with its billing period. A
175
+ * retired plan and an archived price are left out, since nobody new can
176
+ * buy them. What the packaged `/pricing` page carries with an SEO module
177
+ * installed. `undefined` until the pricing loads.
178
+ */
179
+ structuredData: ComputedRef<Record<string, unknown> | undefined>;
151
180
  /**
152
181
  * The interval the plans show: the address's `?interval=` when a plan
153
182
  * sells at it, else monthly when a plan is priced by the month, until
@@ -2,6 +2,7 @@ import { computed, ref, toValue } from "vue";
2
2
  import { navigateTo, useRequestHeaders, useRoute, useState } from "#imports";
3
3
  import { useAsyncQuery } from "nuxt-convex-module/app";
4
4
  import { CATALOG_INTERVALS } from "../../../convex/catalog.js";
5
+ import { backendError } from "../../../convex/errors.js";
5
6
  import { failureOf } from "../utils/backend-error.js";
6
7
  import { useActiveLocale } from "../utils/active-locale.js";
7
8
  import { currencyCode, visitorCurrency } from "../utils/currency.js";
@@ -10,6 +11,8 @@ import { useBackendNamespace } from "../utils/namespace.js";
10
11
  import { askedInterval, onSite, pricingBindings, promotionRuns, shownInterval, usePageClock } from "../utils/pricing-bindings.js";
11
12
  import { useAuthSession } from "../utils/auth-session.js";
12
13
  import { CONFIRMED_PRORATION } from "../utils/plan-change-confirm.js";
14
+ import { pricingCheckout } from "../utils/pricing-checkout.js";
15
+ import { pricingStructuredData } from "../utils/pricing-seo.js";
13
16
  import { useBilling } from "./use-billing.js";
14
17
  import { useCampaign } from "./use-campaign.js";
15
18
  import { useBackendPagePath } from "./use-backend-page-path.js";
@@ -51,6 +54,8 @@ export function usePricing(options = {}) {
51
54
  packFor: () => void 0,
52
55
  refresh: async () => {
53
56
  },
57
+ checkout: async (kind, key) => offSale(kind, key),
58
+ structuredData: computed(() => void 0),
54
59
  ...intervalState(computed(() => []), () => void 0),
55
60
  bind: pricingBindings({ interval: ref("month"), setInterval: () => {
56
61
  }, pending: ref(null), manages: () => false, act: () => {
@@ -74,6 +79,7 @@ export function usePricing(options = {}) {
74
79
  const state = intervalState(intervals, () => route.query.interval);
75
80
  const now = usePageClock();
76
81
  const promotion = computed(() => read.data.value?.promotion);
82
+ const activePromotion = computed(() => promotion.value && promotionRuns(promotion.value, now.value) ? promotion.value : void 0);
77
83
  const successUrlFor = (kind, key) => {
78
84
  const wanted2 = options.successUrl?.[kind];
79
85
  if (wanted2 === void 0) return void 0;
@@ -82,13 +88,20 @@ export function usePricing(options = {}) {
82
88
  const url = typeof wanted2 === "string" ? wanted2 : wanted2(item);
83
89
  return onSite(url);
84
90
  };
91
+ const packs = computed(() => read.data.value?.packs);
92
+ const actions = options.actions === false ? null : planActions(state, plans, packs, {
93
+ asked: () => toValue(options.discount)?.trim() || void 0,
94
+ active: () => activePromotion.value,
95
+ currencies: () => read.data.value?.currencies ?? [],
96
+ successUrl: successUrlFor
97
+ });
85
98
  return {
86
99
  plans,
87
- packs: computed(() => read.data.value?.packs),
100
+ packs,
88
101
  currency: computed(() => read.data.value?.currency),
89
102
  currencies: computed(() => read.data.value?.currencies ?? []),
90
103
  promotion,
91
- activePromotion: computed(() => promotion.value && promotionRuns(promotion.value, now.value) ? promotion.value : void 0),
104
+ activePromotion,
92
105
  requested: computed(() => {
93
106
  const key = route.query.plan;
94
107
  return typeof key === "string" && (plans.value ?? []).some((plan) => plan.key === key) ? key : void 0;
@@ -105,11 +118,18 @@ export function usePricing(options = {}) {
105
118
  error: computed(() => read.error.value ? failureOf(read.error.value) : null),
106
119
  packFor: (units, meter) => smallestCovering(read.data.value?.packs ?? [], units, meter),
107
120
  refresh: () => read.refresh(),
121
+ checkout: actions?.checkout ?? (async () => {
122
+ throw new Error("[nuxt-backend] usePricing({ actions: false }): this pricing builds no checkout.");
123
+ }),
124
+ structuredData: computed(() => read.data.value ? pricingStructuredData(read.data.value) : void 0),
108
125
  ...state,
109
- bind: options.actions === false ? pricingBindings({ ...state, manages: () => false, act: () => {
110
- } }) : planActions(state, plans, toValue(options.discount), (key) => successUrlFor("plan", key))
126
+ bind: actions?.bind ?? pricingBindings({ ...state, manages: () => false, act: () => {
127
+ } })
111
128
  };
112
129
  }
130
+ function offSale(kind, key) {
131
+ throw backendError("invalid_input", { field: kind }, `[nuxt-backend] usePricing().checkout: the pricing has no ${kind} '${key}' on sale.`);
132
+ }
113
133
  function intervalState(intervals, query) {
114
134
  const picked = ref(null);
115
135
  const asked = () => {
@@ -127,7 +147,7 @@ function intervalState(intervals, query) {
127
147
  };
128
148
  return { interval, setInterval, pending: ref(null) };
129
149
  }
130
- function planActions(state, plans, discount, successUrl) {
150
+ function planActions(state, plans, packs, sale) {
131
151
  const billing = useBilling();
132
152
  const campaign = useCampaign();
133
153
  const auth = useAuthSession();
@@ -139,6 +159,15 @@ function planActions(state, plans, discount, successUrl) {
139
159
  const at = shownInterval(plan, state.interval.value, billing.subscription.value?.productId);
140
160
  return at && plan.prices[at];
141
161
  };
162
+ const { payIn, withCampaign } = pricingCheckout({ campaign, asked: sale.asked, active: sale.active, currencies: sale.currencies });
163
+ const start = (kind, key, price, offered2, options) => {
164
+ const back = sale.successUrl(kind, key);
165
+ const open = (campaignOptions) => billing.checkout(price.productId, { redirect: true, ...payIn(price.currency), ...back ? { successUrl: back } : {}, ...campaignOptions, ...options });
166
+ if (options.discount === void 0 && options.discountCode === void 0) return withCampaign(offered2, open);
167
+ const { discountCode: _code, ...attribution } = campaign.checkoutOptions.value;
168
+ return open(attribution);
169
+ };
170
+ const offered = (kind, price) => price.promotion !== void 0 && sale.active() !== void 0 && (kind === "pack" || !billing.isSubscribed.value);
142
171
  const act = async ({ key }) => {
143
172
  if (!auth.isAuthenticated.value) {
144
173
  if (login.value) await navigateTo(`${login.value}?redirect=${encodeURIComponent(route.fullPath)}`);
@@ -149,18 +178,28 @@ function planActions(state, plans, discount, successUrl) {
149
178
  state.pending.value = key;
150
179
  try {
151
180
  if (billing.isSubscribed.value && billing.pass.value === null) await billing.changePlan(price.productId, { proration: CONFIRMED_PRORATION });
152
- else {
153
- const back = successUrl(key);
154
- await billing.checkout(price.productId, { redirect: true, ...campaign.checkoutOptions.value, ...discount ? { discount } : {}, ...back ? { successUrl: back } : {} });
155
- }
181
+ else await checkout("plan", key);
156
182
  } catch {
157
183
  } finally {
158
184
  state.pending.value = null;
159
185
  }
160
186
  };
161
- return pricingBindings({
162
- ...state,
163
- manages: () => !auth.isAuthenticated.value || billing.canManage.value,
164
- act
165
- });
187
+ const checkout = async (kind, key, options = {}) => {
188
+ if (kind === "pack") {
189
+ const pack = packs.value?.find((entry) => entry.key === key);
190
+ if (!pack) offSale(kind, key);
191
+ return start(kind, key, pack, offered(kind, pack), options);
192
+ }
193
+ const price = priceOf(key);
194
+ if (!price) offSale(kind, key);
195
+ return start(kind, key, price, offered(kind, price), options);
196
+ };
197
+ return {
198
+ checkout,
199
+ bind: pricingBindings({
200
+ ...state,
201
+ manages: () => !auth.isAuthenticated.value || billing.canManage.value,
202
+ act
203
+ })
204
+ };
166
205
  }