All files / lib/subscription check.ts

87.4% Statements 111/127
90.9% Branches 30/33
100% Functions 5/5
87.4% Lines 111/127

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 2101x                                                                           15x 15x 15x 15x     15x 15x 15x 15x 15x   15x   15x 15x     15x 15x 15x 15x 15x   12x 12x 15x 15x 15x   15x 15x 15x 15x 15x 2x 10x 15x 15x 2x 10x 15x   15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x         9x 9x 9x 9x 9x   9x 2x 2x   7x 7x 7x                                             9x   9x 9x 9x 9x 9x 9x         5x 5x 5x 5x 5x   5x 5x 5x 5x 5x   5x   5x 2x 2x     3x 3x   5x 7x 3x 3x 3x 7x   3x 3x         5x 5x   5x 5x 5x 5x 5x   5x 5x         4x 4x 4x 4x 4x   4x 1x 1x 1x 1x 1x   3x 3x  
/**
 * Subscription Check Functions
 *
 * Server-side functions to check subscription limits and features
 */
 
import { createClient } from '@/lib/supabase/server';
import {
  getTierLimits,
  canAddMore,
  hasFeature,
  type SubscriptionTier,
  type TierLimits,
} from './tiers';
 
export interface UserSubscriptionInfo {
  tier: SubscriptionTier;
  limits: TierLimits;
  counts: {
    samples: number;
    testimonials: number;
    packages: number;
  };
  canAdd: {
    samples: boolean;
    testimonials: boolean;
    packages: boolean;
  };
  remaining: {
    samples: number;
    testimonials: number;
    packages: number;
  };
}
 
/**
 * Get user's subscription info with current counts
 */
export async function getUserSubscriptionInfo(
  userId: string
): Promise<UserSubscriptionInfo | null> {
  const supabase = await createClient();
 
  // Get profile with subscription tier
  const { data: profile } = await supabase
    .from('profiles')
    .select('id, subscription_tier')
    .eq('user_id', userId)
    .single();
 
  if (!profile) return null;
 
  const tier = (profile.subscription_tier || 'free') as SubscriptionTier;
  const limits = getTierLimits(tier);
 
  // Get current counts
  const [samplesResult, testimonialsResult, packagesResult] = await Promise.all([
    supabase.from('samples').select('id', { count: 'exact' }).eq('profile_id', profile.id),
    supabase.from('testimonials').select('id', { count: 'exact' }).eq('profile_id', profile.id),
    supabase.from('packages').select('id', { count: 'exact' }).eq('profile_id', profile.id),
  ]);
 
  const counts = {
    samples: samplesResult.count || 0,
    testimonials: testimonialsResult.count || 0,
    packages: packagesResult.count || 0,
  };
 
  const remaining = {
    samples:
      limits.maxSamples === Infinity ? Infinity : Math.max(0, limits.maxSamples - counts.samples),
    testimonials:
      limits.maxTestimonials === Infinity
        ? Infinity
        : Math.max(0, limits.maxTestimonials - counts.testimonials),
    packages:
      limits.maxPackages === Infinity
        ? Infinity
        : Math.max(0, limits.maxPackages - counts.packages),
  };
 
  return {
    tier,
    limits,
    counts,
    canAdd: {
      samples: canAddMore(tier, 'samples', counts.samples),
      testimonials: canAddMore(tier, 'testimonials', counts.testimonials),
      packages: canAddMore(tier, 'packages', counts.packages),
    },
    remaining,
  };
}
 
/**
 * Check if user can add a specific item type
 */
export async function checkCanAdd(
  userId: string,
  itemType: 'samples' | 'testimonials' | 'packages'
): Promise<{ allowed: boolean; reason?: string; suggestedTier?: SubscriptionTier }> {
  const info = await getUserSubscriptionInfo(userId);
 
  if (!info) {
    return { allowed: false, reason: 'Profile not found' };
  }
 
  if (info.canAdd[itemType]) {
    return { allowed: true };
  }
 
  // Determine upgrade suggestion
  let suggestedTier: SubscriptionTier | undefined;
  const tierOrder: SubscriptionTier[] = ['basic', 'pro', 'premium'];
 
  for (const tier of tierOrder) {
    if (tier === info.tier) continue;
    const tierLimits = getTierLimits(tier);
 
    const maxField =
      itemType === 'samples'
        ? tierLimits.maxSamples
        : itemType === 'testimonials'
          ? tierLimits.maxTestimonials
          : tierLimits.maxPackages;
 
    if (maxField > info.counts[itemType]) {
      suggestedTier = tier;
      break;
    }
  }
 
  const itemName = itemType === 'samples' ? 'work samples' : itemType;
 
  return {
    allowed: false,
    reason: `You've reached the maximum ${itemName} for your ${info.tier} plan`,
    suggestedTier,
  };
}
 
/**
 * Check if user has access to a specific feature
 */
export async function checkFeatureAccess(
  userId: string,
  feature: keyof TierLimits['features']
): Promise<{ allowed: boolean; tier: SubscriptionTier; requiredTier?: SubscriptionTier }> {
  const supabase = await createClient();
 
  const { data: profile } = await supabase
    .from('profiles')
    .select('subscription_tier')
    .eq('user_id', userId)
    .single();
 
  const tier = (profile?.subscription_tier || 'free') as SubscriptionTier;
 
  if (hasFeature(tier, feature)) {
    return { allowed: true, tier };
  }
 
  // Find the minimum required tier for this feature
  const tierOrder: SubscriptionTier[] = ['basic', 'pro', 'premium'];
  let requiredTier: SubscriptionTier | undefined;
 
  for (const t of tierOrder) {
    if (hasFeature(t, feature)) {
      requiredTier = t;
      break;
    }
  }
 
  return { allowed: false, tier, requiredTier };
}
 
/**
 * Get user's current tier (quick lookup)
 */
export async function getUserTier(userId: string): Promise<SubscriptionTier> {
  const supabase = await createClient();
 
  const { data: profile } = await supabase
    .from('profiles')
    .select('subscription_tier')
    .eq('user_id', userId)
    .single();
 
  return (profile?.subscription_tier || 'free') as SubscriptionTier;
}
 
/**
 * Server action to validate item addition (use in API routes)
 */
export async function validateItemAddition(
  userId: string,
  itemType: 'samples' | 'testimonials' | 'packages'
): Promise<{ valid: boolean; error?: string }> {
  const check = await checkCanAdd(userId, itemType);
 
  if (!check.allowed) {
    return {
      valid: false,
      error: check.reason || `Cannot add more ${itemType}. Please upgrade your plan.`,
    };
  }
 
  return { valid: true };
}