Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(fe): Subscription tier update UI (#2666)

Evan Hutnik604ac322396d
diff --git a/js/app/packages/app/component/paywall/PaywallComponent.tsx b/js/app/packages/app/component/paywall/PaywallComponent.tsx
index 83e48f3e1d..a6392dba89 100644
--- a/js/app/packages/app/component/paywall/PaywallComponent.tsx
+++ b/js/app/packages/app/component/paywall/PaywallComponent.tsx
@@ -1,8 +1,12 @@
import { useHasPaidAccess } from '@core/auth';
+import { toast } from '@core/component/Toast/Toast';
import { type PaywallKey, PaywallMessages } from '@core/constant/PaywallState';
+import { usePermissions } from '@core/context/user';
import IconX from '@icon/regular/x.svg';
+import { invalidateUserInfo } from '@queries/auth/user-info';
import { stripeServiceClient } from '@service-stripe/client';
-import { createSignal, For, Show } from 'solid-js';
+import { createMemo, createSignal, For, Show } from 'solid-js';
+import { match } from 'ts-pattern';
import { useAnalytics } from '@app/component/analytics-context';
import { PLANS, type PlanTier } from './plans';
@@ -17,10 +21,34 @@ interface PaywallComponent {
const PaywallComponent = (props: PaywallComponent) => {
const analytics = useAnalytics();
-
- const [selectedTier, setSelectedTier] = createSignal<PlanTier>('sonnet');
+ const permissions = usePermissions();
const hasPaid = useHasPaidAccess();
+ // Tier a paying user is currently subscribed to, derived from RBAC permissions
+ // (sub_opus grants write:opus; sub_sonnet grants write:sonnet + write:haiku;
+ // sub_haiku grants write:haiku — so check highest-to-lowest).
+ const currentTier = createMemo((): PlanTier | undefined => {
+ if (!hasPaid()) return undefined;
+ const perms = permissions();
+ if (perms.includes('write:opus')) return 'opus';
+ if (perms.includes('write:sonnet')) return 'sonnet';
+ if (perms.includes('write:haiku')) return 'haiku';
+ return undefined;
+ });
+
+ // `userSelectedTier` is only set when the user explicitly clicks a plan card. Until
+ // then the UI derives its selection from `currentTier` (falling back to 'sonnet' for
+ // non-paying users). This avoids mirroring derived state into a signal via `createEffect`
+ // and also sidesteps the briefly-wrong-card window before permissions resolve.
+ const [userSelectedTier, setUserSelectedTier] = createSignal<PlanTier | null>(
+ null
+ );
+ const selectedTier = createMemo<PlanTier>(
+ () => userSelectedTier() ?? currentTier() ?? 'sonnet'
+ );
+
+ const [updating, setUpdating] = createSignal(false);
+
const handleCheckout = async (tier: PlanTier) => {
try {
await props.cb();
@@ -57,6 +85,47 @@ const PaywallComponent = (props: PaywallComponent) => {
handleCheckout(selectedTier());
};
+ const handleUpdateTier = async () => {
+ const next = selectedTier();
+ const prev = currentTier();
+ if (!prev || next === prev) return;
+ setUpdating(true);
+ try {
+ const result = await stripeServiceClient.updateSubscriptionTier(next);
+ if (!result.ok) {
+ // Messages mirror the backend's StripeOperationError `Display` impls, adapted
+ // to second-person for UI. `.exhaustive()` fails the build if the code union
+ // grows a new variant without a toast case.
+ const message = match(result.code)
+ .with('USER_IN_TEAM', () => 'Contact your team owner to update.')
+ .with(
+ 'UPDATE_IN_PROGRESS',
+ () =>
+ 'Another subscription update is already in progress. Please try again in a moment.'
+ )
+ .with(
+ 'NO_SUBSCRIPTION',
+ () => "You don't have an active subscription to update."
+ )
+ .with(
+ 'TIER_UNCHANGED',
+ () => 'Subscription is already on the requested tier.'
+ )
+ .with('UNKNOWN', () => 'Failed to update subscription.')
+ .exhaustive();
+ toast.failure(message);
+ return;
+ }
+ analytics.track('subscription_tier_updated', { from: prev, to: next });
+ // Refetches permissions so `currentTier` reflects the new tier and this button
+ // auto-hides (selectedTier === currentTier).
+ await invalidateUserInfo();
+ toast.success('Subscription updated!');
+ } finally {
+ setUpdating(false);
+ }
+ };
+
return (
<div class="space-y-6 sm:space-y-8 w-full">
<div class="relative w-full text-center">
@@ -89,8 +158,7 @@ const PaywallComponent = (props: PaywallComponent) => {
<For each={PLANS}>
{(plan) => (
<button
- inert={hasPaid()}
- onClick={() => setSelectedTier(plan.tier)}
+ onClick={() => setUserSelectedTier(plan.tier)}
class="p-4 sm:p-5 border flex flex-col transition-all relative text-left"
classList={{
'border-accent ring-1 ring-accent bg-active':
@@ -129,18 +197,31 @@ const PaywallComponent = (props: PaywallComponent) => {
</div>
<div class="mx-auto mt-8 max-w-2xl text-center">
- <button
- onClick={handleContinue}
- class={`w-full px-4 py-2 sm:px-6 sm:py-3 font-medium transition-none hover:transition text-sm sm:text-base border border-transparent ${
- hasPaid()
- ? 'bg-active text-ink border-edge hover:bg-hover hover:border-edge'
- : 'bg-accent text-page hover:bg-accent-ink'
- }`}
+ <Show
+ when={hasPaid() && currentTier() && selectedTier() !== currentTier()}
+ fallback={
+ <button
+ onClick={handleContinue}
+ class={`w-full px-4 py-2 sm:px-6 sm:py-3 font-medium transition-none hover:transition text-sm sm:text-base border border-transparent ${
+ hasPaid()
+ ? 'bg-active text-ink border-edge hover:bg-hover hover:border-edge'
+ : 'bg-accent text-page hover:bg-accent-ink'
+ }`}
+ >
+ <Show when={!hasPaid()} fallback={'Manage Subscription'}>
+ Get {PLANS.find((p) => p.tier === selectedTier())?.name}
+ </Show>
+ </button>
+ }
>
- <Show when={!hasPaid()} fallback={'Manage Subscription'}>
- Get {PLANS.find((p) => p.tier === selectedTier())?.name}
- </Show>
- </button>
+ <button
+ onClick={handleUpdateTier}
+ disabled={updating()}
+ class="w-full px-4 py-2 sm:px-6 sm:py-3 font-medium transition-none hover:transition text-sm sm:text-base border border-transparent bg-accent text-page hover:bg-accent-ink disabled:opacity-60"
+ >
+ {updating() ? 'Updating…' : 'Update Subscription'}
+ </button>
+ </Show>
<Show when={!hasPaid() && props.handleGuest}>
<button
onClick={() => props.handleGuest?.()}
diff --git a/js/app/packages/service-clients/service-auth/client.ts b/js/app/packages/service-clients/service-auth/client.ts
index d98cc68212..c3714aed1d 100644
--- a/js/app/packages/service-clients/service-auth/client.ts
+++ b/js/app/packages/service-clients/service-auth/client.ts
@@ -16,6 +16,7 @@ import { createSignal } from 'solid-js';
import { fetchWithAuth as _fetchWithAuth } from './fetch';
import type {
InitGithubLinkResponse,
+ PatchSubscriptionTierRequest,
PatchUserTutorialRequest,
SendMobileWelcomeEmailResponse,
UserQuota,
@@ -128,6 +129,12 @@ export async function getAccessToken(): Promise<string | null> {
export type { GetLegacyUserPermissionsResponse, UserOrganizationResponse };
+export type PatchSubscriptionTierErrorCode =
+ | 'TIER_UNCHANGED'
+ | 'USER_IN_TEAM'
+ | 'NO_SUBSCRIPTION'
+ | 'UPDATE_IN_PROGRESS';
+
export const authServiceClient = {
async logout() {
setAccessTokenData(null);
@@ -456,6 +463,65 @@ export const authServiceClient = {
);
},
+ /**
+ * Patches the current user's subscription tier. Backend swaps both the RBAC role and
+ * Stripe subscription line item; caller should invalidate user info afterwards so the
+ * new permissions are picked up.
+ *
+ * Maps each distinct backend failure (distinguished by HTTP status) to a semantic code
+ * the UI can switch on. Uses `_fetchWithAuth` directly so the `CustomErrorCode` generic
+ * survives the module-level `fetchWithAuth` cast.
+ */
+ async patchSubscriptionTier(args: PatchSubscriptionTierRequest) {
+ return _fetchWithAuth<{}, PatchSubscriptionTierErrorCode>(
+ `${authHost}/user/stripe/subscription`,
+ {
+ method: 'PATCH',
+ body: JSON.stringify(args),
+ errorResponseHandler: async (response) => {
+ // Custom handler fully replaces fetchWithAuth's default mapping, so preserve
+ // the base cases we still want (401/500) alongside our endpoint-specific codes.
+ switch (response.status) {
+ case 400:
+ return {
+ code: 'TIER_UNCHANGED',
+ message: 'Subscription is already on the requested tier',
+ };
+ case 401:
+ return { code: 'UNAUTHORIZED', message: 'Unauthorized access' };
+ case 403:
+ return {
+ code: 'USER_IN_TEAM',
+ message:
+ 'User is a member of a team; tier is managed by the team owner',
+ };
+ case 404:
+ return {
+ code: 'NO_SUBSCRIPTION',
+ message: 'User does not have an active subscription',
+ };
+ case 409:
+ return {
+ code: 'UPDATE_IN_PROGRESS',
+ message:
+ 'Another subscription update is already in progress for this user',
+ };
+ case 500:
+ return {
+ code: 'SERVER_ERROR',
+ message: 'Internal server error',
+ };
+ default:
+ return {
+ code: 'HTTP_ERROR',
+ message: `HTTP error! status: ${response.status}`,
+ };
+ }
+ },
+ }
+ );
+ },
+
/**
* Initializes the github account link for the user.
* Returns the url you need to redirect user to to start the link.
diff --git a/js/app/packages/service-clients/service-stripe/client.ts b/js/app/packages/service-clients/service-stripe/client.ts
index 0c242bdbf0..c2a8ca1f50 100644
--- a/js/app/packages/service-clients/service-stripe/client.ts
+++ b/js/app/packages/service-clients/service-stripe/client.ts
@@ -1,6 +1,11 @@
import { isOk } from '@core/util/maybeResult';
import { registerClient } from '@core/util/mockClient';
-import { authServiceClient } from '@service-auth/client';
+import {
+ authServiceClient,
+ type PatchSubscriptionTierErrorCode,
+} from '@service-auth/client';
+import type { StripeProductTier } from '@service-auth/generated/schemas/stripeProductTier';
+import { match, P } from 'ts-pattern';
/**
* Gets Meta _fbp (browser ID) and _fbc (click ID) values from cookies set by the Meta Pixel.
@@ -83,6 +88,40 @@ export const stripeServiceClient = {
return result[1];
},
+ /**
+ * Changes the current user's subscription tier. Returns a narrow discriminated union so
+ * callers get a type-checked error `code` without drilling into the MaybeResult tuple
+ * shape (`result[0]?.[0]?.code`), which would silently fall through to the default case
+ * if the shape ever changes. Callers should invalidate the user info query on success.
+ */
+ updateSubscriptionTier: async (
+ tier: StripeProductTier
+ ): Promise<UpdateSubscriptionTierResult> => {
+ const result = await authServiceClient.patchSubscriptionTier({
+ newTier: tier,
+ });
+ if (isOk(result)) return { ok: true };
+ // Narrow the first error's code to our known union; anything else (NETWORK_ERROR,
+ // UNAUTHORIZED, SERVER_ERROR, etc.) collapses to 'UNKNOWN'. `match` + the explicit
+ // P.union of `PatchSubscriptionTierErrorCode` members means adding a new backend
+ // code without widening this union is a compile error.
+ const code = match(result[0]?.code)
+ .with(
+ P.union(
+ 'TIER_UNCHANGED',
+ 'USER_IN_TEAM',
+ 'NO_SUBSCRIPTION',
+ 'UPDATE_IN_PROGRESS'
+ ),
+ (c) => c
+ )
+ .otherwise(() => 'UNKNOWN' as const);
+ return { ok: false, code };
+ },
};
+export type UpdateSubscriptionTierResult =
+ | { ok: true }
+ | { ok: false; code: PatchSubscriptionTierErrorCode | 'UNKNOWN' };
+
registerClient('stripe', stripeServiceClient);