()
| 27 | } |
| 28 | |
| 29 | export function useSubscriptionUpgrade() { |
| 30 | const { data: session } = useSession() |
| 31 | const betterAuthSubscription = useSubscription() |
| 32 | const queryClient = useQueryClient() |
| 33 | |
| 34 | const handleUpgrade = useCallback( |
| 35 | async (targetPlan: TargetPlan, options?: UpgradeOptions) => { |
| 36 | const creditTier = options?.creditTier ?? CONSTANTS.DEFAULT_CREDIT_TIER |
| 37 | const annual = options?.annual ?? false |
| 38 | const planName = buildPlanName(targetPlan, creditTier) |
| 39 | const userId = session?.user?.id |
| 40 | if (!userId) { |
| 41 | throw new Error('User not authenticated') |
| 42 | } |
| 43 | |
| 44 | let currentSubscriptionRowId: string | undefined |
| 45 | let currentStripeSubscriptionId: string | undefined |
| 46 | let allSubscriptions: any[] = [] |
| 47 | try { |
| 48 | const listResult = await client.subscription.list() |
| 49 | allSubscriptions = listResult.data || [] |
| 50 | const activePersonalSub = allSubscriptions.find( |
| 51 | (sub: any) => hasPaidSubscriptionStatus(sub.status) && sub.referenceId === userId |
| 52 | ) |
| 53 | currentSubscriptionRowId = activePersonalSub?.id |
| 54 | currentStripeSubscriptionId = activePersonalSub?.stripeSubscriptionId |
| 55 | } catch (_e) { |
| 56 | currentSubscriptionRowId = undefined |
| 57 | currentStripeSubscriptionId = undefined |
| 58 | } |
| 59 | |
| 60 | if (currentSubscriptionRowId && !currentStripeSubscriptionId) { |
| 61 | logger.error('Active paid subscription is missing its Stripe subscription ID', { |
| 62 | userId, |
| 63 | subscriptionRowId: currentSubscriptionRowId, |
| 64 | targetPlan, |
| 65 | }) |
| 66 | throw new Error( |
| 67 | 'We could not match your current plan with our payment provider. Please contact support before upgrading so you are not charged twice.' |
| 68 | ) |
| 69 | } |
| 70 | |
| 71 | let referenceId = userId |
| 72 | |
| 73 | if (targetPlan === 'team') { |
| 74 | try { |
| 75 | let orgsData |
| 76 | try { |
| 77 | orgsData = await requestJson(listCreatorOrganizationsContract, {}) |
| 78 | } catch (err) { |
| 79 | if (err instanceof ApiClientError) { |
| 80 | throw new Error('Failed to check organization status') |
| 81 | } |
| 82 | throw err |
| 83 | } |
| 84 | const existingOrg = orgsData.organizations?.find((org) => isOrgAdminRole(org.role)) |
| 85 | |
| 86 | if (existingOrg) { |
no test coverage detected