Skip to content

Commit

Permalink
Refactor subscription management from PR feedback.
Browse files Browse the repository at this point in the history
  • Loading branch information
bLopata committed Dec 26, 2024
1 parent 09932a0 commit a9255f6
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 37 deletions.
24 changes: 18 additions & 6 deletions www/utils/supabase/actions.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,27 @@
'use server'; // This directive marks all exports as server actions

import {
createOrRetrieveFreeTrialSubscription,
decrementFreeMessages,
} from '@/utils/supabase/admin';
import { createFreeTrialSubscription, decrementFreeMessages } from './admin';
import { createClient } from './client';
import { getSubscription } from './queries';


export async function createOrRetrieveFreeTrialSubscription(userId: string) {
// Create server-side Supabase client
const supabase = createClient();

// First try to get existing subscription with user privileges
const existingSub = await getSubscription(supabase);
if (existingSub) return existingSub;

// If no subscription exists, create one with admin privileges
return createFreeTrialSubscription(userId);
}

export async function getFreeMessageCount(userId: string) {
const subscription = await createOrRetrieveFreeTrialSubscription(userId);
return (subscription.metadata as { freeMessages: number })?.freeMessages ?? 0;
return (subscription?.metadata as { freeMessages: number })?.freeMessages ?? 0;
}

export async function useFreeTrial(userId: string) {
return decrementFreeMessages(userId);
}
}
29 changes: 6 additions & 23 deletions www/utils/supabase/admin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,29 +22,14 @@ const supabaseAdmin = createClient<Database>(
process.env.SUPABASE_SERVICE_ROLE_KEY || ''
);

// Trial membership
const createOrRetrieveFreeTrialSubscription = async (userId: string) => {
// Check for existing trial subscription
const { data: existingSub, error: subError } = await supabaseAdmin
.from('subscriptions')
.select('*')
.eq('user_id', userId)
.eq('status', 'trialing')
.maybeSingle();

if (subError)
throw new Error(`Subscription lookup failed: ${subError.message}`);

// If trial subscription exists, return it
if (existingSub) return existingSub;

// Create a new trial subscription
const createFreeTrialSubscription = async (userId: string) => {
const subscriptionData: TablesInsert<'subscriptions'> = {
id: `free_trial_${userId}`,
user_id: userId,
status: 'trialing',
metadata: { freeMessages: FREE_MESSAGE_LIMIT },
price_id: null, // or your free tier price ID if you have one
price_id: null,
quantity: 1,
cancel_at_period_end: false,
created: new Date().toISOString(),
Expand All @@ -63,15 +48,13 @@ const createOrRetrieveFreeTrialSubscription = async (userId: string) => {
.from('subscriptions')
.insert([subscriptionData]);

if (insertError)
throw new Error(
`Trial subscription creation failed: ${insertError.message}`
);
if (insertError) {
throw new Error(`Trial subscription creation failed: ${insertError.message}`);
}

return subscriptionData;
};

// Add this function to decrement free messages
const decrementFreeMessages = async (userId: string) => {
const { data: subscription, error: subError } = await supabaseAdmin
.from('subscriptions')
Expand Down Expand Up @@ -384,7 +367,7 @@ export {
deletePriceRecord,
createOrRetrieveCustomer,
manageSubscriptionStatusChange,
createOrRetrieveFreeTrialSubscription,
createFreeTrialSubscription,
decrementFreeMessages,
FREE_MESSAGE_LIMIT,
};
24 changes: 16 additions & 8 deletions www/utils/supabase/queries.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,33 @@
import { cache } from 'react';
import { SupabaseClient } from '@supabase/supabase-js';
import { unstable_cache } from '../unstableCache';
import { createOrRetrieveFreeTrialSubscription } from './admin';
import { createFreeTrialSubscription } from './admin';

async function createOrRetrieveFreeTrialSubscription(supabase: SupabaseClient, userId: string) {
// First try to get existing subscription with user privileges
const existingSub = await getSubscription(supabase);
if (existingSub) return existingSub;

// If no subscription exists, create one with admin privileges
return createFreeTrialSubscription(userId);
}

export const getChatAccess = unstable_cache(
async (supabase: SupabaseClient, userId: string) => {
const subscription = await createOrRetrieveFreeTrialSubscription(userId);
const subscription = await createOrRetrieveFreeTrialSubscription(supabase, userId);

// Check if subscription is active (paid subscription)
// Rest of the function remains the same
const isSubscribed = subscription?.status === 'active' &&
!subscription.cancel_at_period_end;

// Check for trial status and free messages
const isTrialing = subscription?.status === 'trialing';
const trialEnded = subscription?.trial_end
? new Date(subscription.trial_end) < new Date()
: false;
? new Date(subscription.trial_end) < new Date()
: false;

const freeMessages = (isTrialing && !trialEnded)
? (subscription?.metadata as { freeMessages: number })?.freeMessages ?? 0
: 0;
? (subscription?.metadata as { freeMessages: number })?.freeMessages ?? 0
: 0;

return {
isSubscribed,
Expand Down

0 comments on commit a9255f6

Please sign in to comment.