@antelopejs/dms-saas 0.7.1 → 0.7.2

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.
@@ -37,6 +37,8 @@ const planIntervalLabel = usePlanIntervalLabel('saas.workspace.plan.interval')
37
37
  const preview = ref<PlanChangePreview | null>(null)
38
38
  const isLoading = ref(true)
39
39
  const loadFailure = ref<string | null>(null)
40
+ /** What the workspace holds beyond the target plan: the change is refused until it is brought within. */
41
+ const incompatibilities = ref<PlanChangeIncompatibility[] | null>(null)
40
42
  const isSubmitting = ref(false)
41
43
  const submitFailure = ref<string | null>(null)
42
44
 
@@ -82,12 +84,14 @@ const dueToday = computed(() => {
82
84
  })
83
85
 
84
86
  const headingCase = computed(() =>
85
- planChangeHeadingCase(
86
- preview.value,
87
- props.currentPlan,
88
- props.plan,
89
- props.isResubscription,
90
- ),
87
+ incompatibilities.value
88
+ ? 'incompatible'
89
+ : planChangeHeadingCase(
90
+ preview.value,
91
+ props.currentPlan,
92
+ props.plan,
93
+ props.isResubscription,
94
+ ),
91
95
  )
92
96
 
93
97
  const heading = computed(() => {
@@ -177,10 +181,15 @@ const canConfirm = computed(
177
181
  async function loadPreview(): Promise<void> {
178
182
  isLoading.value = true
179
183
  loadFailure.value = null
184
+ incompatibilities.value = null
180
185
  try {
181
186
  preview.value = await previewChange(props.plan._id)
182
187
  } catch (error) {
183
- loadFailure.value = resolveApiError(error, `${KEY_PREFIX}.load_failed`)
188
+ preview.value = null
189
+ incompatibilities.value = readPlanChangeIncompatibilities(error)
190
+ if (!incompatibilities.value) {
191
+ loadFailure.value = resolveApiError(error, `${KEY_PREFIX}.load_failed`)
192
+ }
184
193
  } finally {
185
194
  isLoading.value = false
186
195
  }
@@ -206,6 +215,12 @@ async function confirm(): Promise<void> {
206
215
  emit('done')
207
216
  } catch (error) {
208
217
  if (await offerPendingCheckout(error, props.plan._id)) return
218
+ // The inventory changed between the review and the confirmation.
219
+ incompatibilities.value = readPlanChangeIncompatibilities(error)
220
+ if (incompatibilities.value) {
221
+ preview.value = null
222
+ return
223
+ }
209
224
  submitFailure.value = resolveApiError(
210
225
  error,
211
226
  'saas.workspace.plan.change_error',
@@ -310,6 +325,36 @@ onMounted(() => void loadPreview())
310
325
  <USkeleton class="h-6 w-1/2" />
311
326
  </div>
312
327
 
328
+ <UAlert
329
+ v-else-if="incompatibilities"
330
+ color="warning"
331
+ variant="subtle"
332
+ icon="i-ph-prohibit"
333
+ :title="$t(`${KEY_PREFIX}.incompatible_list`, { plan: plan.name })"
334
+ >
335
+ <template #description>
336
+ <ul class="flex list-disc flex-col gap-1 ps-4">
337
+ <li
338
+ v-for="(issue, index) in incompatibilities"
339
+ :key="`${issue.code}-${issue.resource ?? index}`"
340
+ >
341
+ {{ issue.message }}
342
+ </li>
343
+ </ul>
344
+ </template>
345
+ <template #actions>
346
+ <UButton
347
+ color="warning"
348
+ variant="soft"
349
+ size="xs"
350
+ icon="i-ph-arrow-clockwise"
351
+ @click="loadPreview"
352
+ >
353
+ {{ $t(`${KEY_PREFIX}.check_again`) }}
354
+ </UButton>
355
+ </template>
356
+ </UAlert>
357
+
313
358
  <UAlert
314
359
  v-else-if="loadFailure"
315
360
  color="error"
@@ -399,6 +444,7 @@ onMounted(() => void loadPreview())
399
444
  {{ $t(`${KEY_PREFIX}.back`) }}
400
445
  </UButton>
401
446
  <UButton
447
+ v-if="!incompatibilities"
402
448
  :color="isDowngrade ? 'warning' : 'primary'"
403
449
  :icon="isDowngrade ? 'i-ph-calendar-check' : 'i-ph-lock-simple'"
404
450
  :disabled="!canConfirm"
@@ -154,6 +154,13 @@ function selectPlan(plan: CreatePlanOption): void {
154
154
  submitError.value = null
155
155
  }
156
156
 
157
+ // Not a `useApiData` read: each call creates a SetupIntent, whose client
158
+ // secret is the card form's alone, never cached nor shared.
159
+ async function createSetupIntent(): Promise<string> {
160
+ const setup = await $authFetch<SetupIntent>(SETUP_INTENT_ENDPOINT)
161
+ return setup.clientSecret
162
+ }
163
+
157
164
  async function initStripeElement(): Promise<void> {
158
165
  if (!publishableKey.value) {
159
166
  // A missing key would render an empty card box and fail every submit
@@ -161,12 +168,10 @@ async function initStripeElement(): Promise<void> {
161
168
  cardError.value = t(`${KEYS}.error.card_setup`)
162
169
  return
163
170
  }
164
- // Not a `useApiData` read: each call creates a SetupIntent, whose client
165
- // secret is the card form's alone, never cached nor shared.
166
- const setup = await $authFetch<SetupIntent>(SETUP_INTENT_ENDPOINT)
171
+ const clientSecret = await createSetupIntent()
167
172
  stripeHandle.value = useStripePaymentElement({
168
173
  publishableKey: publishableKey.value,
169
- clientSecret: setup.clientSecret,
174
+ clientSecret,
170
175
  containerId: PAYMENT_ELEMENT_ID,
171
176
  billingEmail: () => user.value?.email ?? '',
172
177
  })
@@ -240,13 +245,25 @@ function reportSubmitError(error: unknown): void {
240
245
  submitError.value = message
241
246
  }
242
247
 
248
+ // The card was confirmed, then the creation refused (another card is needed,
249
+ // a creation already running): its SetupIntent is spent, and confirming it
250
+ // again with the next card fails with a bare Stripe processing error.
251
+ async function renewCard(): Promise<void> {
252
+ try {
253
+ await stripeHandle.value?.renew(await createSetupIntent())
254
+ } catch (error) {
255
+ cardError.value = resolveApiError(error, `${KEYS}.error.card_setup`)
256
+ }
257
+ }
258
+
243
259
  async function submit(): Promise<void> {
244
260
  if (isSubmitting.value || !validate()) return
245
261
  cardError.value = null
246
262
  submitError.value = null
247
263
  isSubmitting.value = true
264
+ let payment: ConfirmedPayment | null = null
248
265
  try {
249
- const payment = await confirmCard()
266
+ payment = await confirmCard()
250
267
  if (!payment.isConfirmed) return
251
268
  const name = workspaceName.value.trim()
252
269
  const created = await $authFetch<CreatedWorkspace>(CREATE_ENDPOINT, {
@@ -260,6 +277,7 @@ async function submit(): Promise<void> {
260
277
  props.onSuccessCallback?.(created.tenantId, name)
261
278
  } catch (error) {
262
279
  reportSubmitError(error)
280
+ if (payment?.paymentMethodId) await renewCard()
263
281
  } finally {
264
282
  isSubmitting.value = false
265
283
  }
@@ -8,6 +8,8 @@ import { PLAN_UNLIMITED } from '../build/plan-catalog'
8
8
  /** Query parameter naming the plan to review on arrival on the billing page. */
9
9
  export const UPGRADE_QUERY_PARAM = 'upgrade'
10
10
 
11
+ const INCOMPATIBLE_CODE = 'saas.errors.plan.incompatible'
12
+
11
13
  const UNLIMITED_RANK = Number.POSITIVE_INFINITY
12
14
 
13
15
  /** One feature that differs between two plans. */
@@ -33,6 +35,29 @@ export interface OfferedPlans {
33
35
  tooSmall: OfferedPlanView[]
34
36
  }
35
37
 
38
+ /** Something the workspace holds that the target plan does not allow. */
39
+ export interface PlanChangeIncompatibility {
40
+ code: string
41
+ message: string
42
+ resource?: string
43
+ }
44
+
45
+ /**
46
+ * What the workspace must bring within the target plan before it can move,
47
+ * read from the 409 a plan change preview or confirmation answers with; null
48
+ * for any other failure.
49
+ */
50
+ export function readPlanChangeIncompatibilities(
51
+ error: unknown,
52
+ ): PlanChangeIncompatibility[] | null {
53
+ const data = (error as { data?: unknown } | undefined)?.data as
54
+ | { code?: unknown; incompatibilities?: unknown }
55
+ | undefined
56
+ if (data?.code !== INCOMPATIBLE_CODE) return null
57
+ const list = data.incompatibilities
58
+ return Array.isArray(list) ? (list as PlanChangeIncompatibility[]) : null
59
+ }
60
+
36
61
  /**
37
62
  * The plan id an arrival link asks to review (`?upgrade=<planId>`), or null.
38
63
  * A repeated parameter takes its first non-empty value.
@@ -460,16 +460,21 @@ export function useSaasRegistration(options: UseSaasRegistrationOptions = {}) {
460
460
  serverFieldErrors.value = rest
461
461
  }
462
462
 
463
+ // Not a `useApiData` read: each call creates a SetupIntent, whose client
464
+ // secret is the card form's alone, never cached nor shared.
465
+ async function createSetupIntent(): Promise<string | undefined> {
466
+ const setup = await $authFetch<SetupIntentResponse>(SETUP_INTENT_ENDPOINT)
467
+ return setup.clientSecret || undefined
468
+ }
469
+
463
470
  async function mountPaymentElement(): Promise<void> {
464
471
  const publishableKey = saasConfig?.stripePublishableKey
465
472
  if (!publishableKey) return
466
- // Not a `useApiData` read: each call creates a SetupIntent, whose client
467
- // secret is the card form's alone, never cached nor shared.
468
- const setup = await $authFetch<SetupIntentResponse>(SETUP_INTENT_ENDPOINT)
469
- if (!setup.clientSecret) return
473
+ const clientSecret = await createSetupIntent()
474
+ if (!clientSecret) return
470
475
  stripeHandle.value = useStripePaymentElement({
471
476
  publishableKey,
472
- clientSecret: setup.clientSecret,
477
+ clientSecret,
473
478
  containerId: paymentElementId,
474
479
  billingEmail: () => form.email,
475
480
  })
@@ -505,6 +510,18 @@ export function useSaasRegistration(options: UseSaasRegistrationOptions = {}) {
505
510
  }
506
511
  }
507
512
 
513
+ // A refusal after the card was confirmed leaves its SetupIntent spent:
514
+ // the next card must go through a fresh one, or Stripe refuses it with a
515
+ // bare processing error.
516
+ async function renewCard(): Promise<void> {
517
+ try {
518
+ const clientSecret = await createSetupIntent()
519
+ if (clientSecret) await stripeHandle.value?.renew(clientSecret)
520
+ } catch (error) {
521
+ errorMessage.value = resolveApiError(error, LOAD_ERROR_KEY)
522
+ }
523
+ }
524
+
508
525
  function reportFailure(error: unknown): void {
509
526
  const field = registrationFieldOf(readApiErrorKey(error))
510
527
  if (!field) {
@@ -549,11 +566,12 @@ export function useSaasRegistration(options: UseSaasRegistrationOptions = {}) {
549
566
 
550
567
  isSubmitting.value = true
551
568
  let tenantId: string | null = null
569
+ let paymentMethodId: string | null | undefined
552
570
  try {
553
571
  // Inside the guard: freezing the capture reads the consumer's object,
554
572
  // and a consumer's object is never guaranteed to be serialisable.
555
573
  const submission = captureSubmission()
556
- const paymentMethodId = isPaymentStepVisible.value
574
+ paymentMethodId = isPaymentStepVisible.value
557
575
  ? await confirmPaymentMethod()
558
576
  : undefined
559
577
  if (paymentMethodId === null) return null
@@ -570,6 +588,7 @@ export function useSaasRegistration(options: UseSaasRegistrationOptions = {}) {
570
588
  // through a flow that would create a second account.
571
589
  if (tenantId) return tenantId
572
590
  reportFailure(error)
591
+ if (paymentMethodId) await renewCard()
573
592
  return null
574
593
  } finally {
575
594
  isSubmitting.value = false
@@ -54,6 +54,12 @@ interface SetupConfirmation {
54
54
 
55
55
  interface StripePaymentElementHandle {
56
56
  confirmAndGetPaymentMethod: () => Promise<ConfirmResult>;
57
+ /**
58
+ * Swap in a fresh SetupIntent. A confirmed SetupIntent is spent: Stripe
59
+ * refuses to confirm it again with another card, so a form that keeps the
60
+ * visitor after a confirmed card was refused must call this first.
61
+ */
62
+ renew: (clientSecret: string) => Promise<void>;
57
63
  }
58
64
 
59
65
  const UNKNOWN_STRIPE_ERROR = "Stripe could not confirm the card";
@@ -99,20 +105,15 @@ export function useStripePaymentElement(
99
105
  ): StripePaymentElementHandle {
100
106
  let stripeInstance: any = null;
101
107
  let elementsInstance: any = null;
108
+ let paymentElement: any = null;
102
109
 
103
- async function init(): Promise<void> {
104
- const { loadStripe } = await import("@stripe/stripe-js");
105
- stripeInstance = await loadStripe(options.publishableKey);
106
- if (!stripeInstance) {
107
- return;
108
- }
110
+ function mountPaymentElement(clientSecret: string): void {
111
+ paymentElement?.destroy();
109
112
  // Payment method types are fixed server-side on the SetupIntent: Stripe
110
113
  // rejects `paymentMethodTypes` next to a `clientSecret`, since it only
111
114
  // applies to an Elements instance created in deferred-intent `mode`.
112
- elementsInstance = stripeInstance.elements({
113
- clientSecret: options.clientSecret,
114
- });
115
- const paymentElement = elementsInstance.create("payment", {
115
+ elementsInstance = stripeInstance.elements({ clientSecret });
116
+ paymentElement = elementsInstance.create("payment", {
116
117
  wallets: { applePay: "never", googlePay: "never" },
117
118
  fields: {
118
119
  billingDetails: { address: "auto", name: "auto", email: "never" },
@@ -121,6 +122,20 @@ export function useStripePaymentElement(
121
122
  paymentElement.mount(`#${options.containerId}`);
122
123
  }
123
124
 
125
+ async function init(): Promise<void> {
126
+ const { loadStripe } = await import("@stripe/stripe-js");
127
+ stripeInstance = await loadStripe(options.publishableKey);
128
+ if (!stripeInstance) {
129
+ return;
130
+ }
131
+ mountPaymentElement(options.clientSecret);
132
+ }
133
+
134
+ async function renew(clientSecret: string): Promise<void> {
135
+ await ready;
136
+ if (stripeInstance) mountPaymentElement(clientSecret);
137
+ }
138
+
124
139
  async function confirmAndGetPaymentMethod(): Promise<ConfirmResult> {
125
140
  if (!stripeInstance || !elementsInstance) {
126
141
  return { error: { message: "Stripe not initialized" } };
@@ -139,11 +154,12 @@ export function useStripePaymentElement(
139
154
  }
140
155
 
141
156
  onUnmounted(() => {
157
+ paymentElement = null;
142
158
  elementsInstance = null;
143
159
  stripeInstance = null;
144
160
  });
145
161
 
146
- void init();
162
+ const ready = init();
147
163
 
148
- return { confirmAndGetPaymentMethod };
164
+ return { confirmAndGetPaymentMethod, renew };
149
165
  }
@@ -178,15 +178,20 @@ async function loadPendingRegistration(): Promise<void> {
178
178
  }
179
179
  }
180
180
 
181
+ async function createSetupIntent(): Promise<string | undefined> {
182
+ const setup = await publicFetch<SetupIntentResponse>(SETUP_INTENT_ENDPOINT)
183
+ return setup.clientSecret || undefined
184
+ }
185
+
181
186
  async function mountPaymentElement(): Promise<void> {
182
187
  const publishableKey = saasConfig?.stripePublishableKey
183
188
  if (!publishableKey || paymentMethodPolicy === 'none') return
184
189
  try {
185
- const setup = await publicFetch<SetupIntentResponse>(SETUP_INTENT_ENDPOINT)
186
- if (!setup.clientSecret) return
190
+ const clientSecret = await createSetupIntent()
191
+ if (!clientSecret) return
187
192
  stripeHandle.value = useStripePaymentElement({
188
193
  publishableKey,
189
- clientSecret: setup.clientSecret,
194
+ clientSecret,
190
195
  containerId: PAYMENT_ELEMENT_ID,
191
196
  billingEmail: () => pending.value?.email ?? '',
192
197
  })
@@ -195,6 +200,18 @@ async function mountPaymentElement(): Promise<void> {
195
200
  }
196
201
  }
197
202
 
203
+ // A refusal after the card was confirmed leaves its SetupIntent spent: the
204
+ // next card must go through a fresh one, or Stripe refuses it with a bare
205
+ // processing error.
206
+ async function renewCard(): Promise<void> {
207
+ try {
208
+ const clientSecret = await createSetupIntent()
209
+ if (clientSecret) await stripeHandle.value?.renew(clientSecret)
210
+ } catch (error) {
211
+ cardError.value = resolveApiError(error, 'saas.public.register.error.load')
212
+ }
213
+ }
214
+
198
215
  /** The confirmed card, undefined when none is collected, null on failure. */
199
216
  async function confirmPaymentMethod(): Promise<string | undefined | null> {
200
217
  if (!isPaymentStepVisible.value) return undefined
@@ -219,8 +236,9 @@ function validate(): boolean {
219
236
  async function submit(): Promise<void> {
220
237
  if (isSubmitting.value || !validate()) return
221
238
  isSubmitting.value = true
239
+ let paymentMethodId: string | undefined | null
222
240
  try {
223
- const paymentMethodId = await confirmPaymentMethod()
241
+ paymentMethodId = await confirmPaymentMethod()
224
242
  if (paymentMethodId === null) return
225
243
  await $fetch(SESSION_ESTABLISH_ENDPOINT, {
226
244
  method: 'POST',
@@ -241,6 +259,7 @@ async function submit(): Promise<void> {
241
259
  error,
242
260
  'saas.public.register.error.failed',
243
261
  )
262
+ if (paymentMethodId) await renewCard()
244
263
  } finally {
245
264
  isSubmitting.value = false
246
265
  }