All files / web/src/lib subscription.ts

33% Statements 67/203
100% Branches 0/0
0% Functions 0/6
33% Lines 67/203

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 2041x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x               1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                               1x 1x         1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                                                                                                   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                        
import { eq, inArray } from 'drizzle-orm'
import { db, schema } from '@/db'
import { getLinkedParentIds } from '@/lib/classroom/family-manager'
import { getParentedPlayerIds } from '@/lib/classroom/access-control'
import type { TierName, TierLimits } from './tier-limits'
import { TIER_LIMITS } from './tier-limits'
import type { Subscription } from '@/db/schema'
 
/** Tier ranking — higher index = better tier. */
const TIER_RANK: Record<TierName, number> = { guest: 0, free: 1, family: 2 }
 
/** Check if a subscription row represents an active family-tier subscription. */
function isActiveFamilyTier(sub?: Subscription | null): boolean {
  return (
    !!sub &&
    sub.plan === 'family' &&
    (sub.status === 'active' || sub.status === 'trialing' || sub.status === 'past_due')
  )
}
 
/**
 * Resolve a user's current subscription tier.
 *
 * Checks two paths:
 * 1. Direct subscription (user has their own subscription row)
 * 2. Household-inherited (user belongs to a household whose owner has a subscription)
 *
 * - No userId → 'guest'
 * - No subscription row or canceled (and no household coverage) → 'free'
 * - Active/trialing/past_due family subscription (direct or via household) → 'family'
 */
export async function getTierForUser(userId?: string): Promise<TierName> {
  if (!userId) return 'guest'

  // 1. Direct subscription (fast path, unchanged)
  const directSub = await db.query.subscriptions.findFirst({
    where: eq(schema.subscriptions.userId, userId),
  })

  if (isActiveFamilyTier(directSub)) return 'family'

  // 2. Household-inherited tier
  const memberships = await db
    .select({ ownerId: schema.households.ownerId })
    .from(schema.householdMembers)
    .innerJoin(schema.households, eq(schema.householdMembers.householdId, schema.households.id))
    .where(eq(schema.householdMembers.userId, userId))

  if (memberships.length > 0) {
    const ownerIds = [...new Set(memberships.map((m) => m.ownerId))]
    // Skip checking our own subscription again
    const otherOwnerIds = ownerIds.filter((id) => id !== userId)
    if (otherOwnerIds.length > 0) {
      const ownerSubs = await db.query.subscriptions.findMany({
        where: inArray(schema.subscriptions.userId, otherOwnerIds),
      })
      if (ownerSubs.some((s) => isActiveFamilyTier(s))) return 'family'
    }
  }

  return 'free'
}
 
/** Get the limits for a user's current tier. */
export async function getLimitsForUser(userId?: string): Promise<TierLimits> {
  const tier = await getTierForUser(userId)
  return TIER_LIMITS[tier]
}
 
/** Get the limits for a tier name (sync, no DB call). */
export function getLimitsForTier(tier: TierName): TierLimits {
  return TIER_LIMITS[tier]
}
 
export interface EffectiveTierResult {
  tier: TierName
  /** Non-null when a *different* user provides the best tier. */
  providedBy: { userId: string; name: string } | null
}
 
/**
 * Determine the best subscription tier available for a student,
 * considering all linked parents (not just the acting user).
 *
 * Returns the highest tier among:
 *  - the student's owner (players.userId)
 *  - every parent in the parent_child table
 *
 * If the best tier comes from someone other than `actingUserId`,
 * `providedBy` identifies who provides it.
 */
export async function getEffectiveTierForStudent(
  playerId: string,
  actingUserId: string
): Promise<EffectiveTierResult> {
  // 1. Gather all candidate user IDs: owner + linked parents
  const player = await db.query.players.findFirst({
    where: eq(schema.players.id, playerId),
    columns: { userId: true },
  })
  if (!player) {
    // Unknown player — fall back to the acting user's own tier
    const tier = await getTierForUser(actingUserId)
    return { tier, providedBy: null }
  }

  const linkedIds = await getLinkedParentIds(playerId)
  const candidateIds = [...new Set([player.userId, ...linkedIds])]

  // 2. Resolve tier for every candidate in one query
  const subs = await db.query.subscriptions.findMany({
    where: inArray(schema.subscriptions.userId, candidateIds),
  })

  const subByUser = new Map(subs.map((s) => [s.userId, s]))

  function tierFor(uid: string): TierName {
    const sub = subByUser.get(uid)
    if (!sub) return 'free'
    if (
      sub.plan === 'family' &&
      (sub.status === 'active' || sub.status === 'trialing' || sub.status === 'past_due')
    ) {
      return 'family'
    }
    return 'free'
  }

  // 3. Find the best tier and who provides it
  let bestTier: TierName = 'free'
  let bestUserId = actingUserId

  for (const uid of candidateIds) {
    const t = tierFor(uid)
    if (TIER_RANK[t] > TIER_RANK[bestTier]) {
      bestTier = t
      bestUserId = uid
    }
  }

  // 4. If someone else provides the tier, look up their name
  if (bestUserId !== actingUserId) {
    const provider = await db.query.users.findFirst({
      where: eq(schema.users.id, bestUserId),
      columns: { id: true, name: true },
    })
    return {
      tier: bestTier,
      providedBy: provider
        ? { userId: provider.id, name: provider.name ?? 'Another parent' }
        : null,
    }
  }

  return { tier: bestTier, providedBy: null }
}
 
// ---------------------------------------------------------------------------
// Family coverage: how many of a user's children are covered by another
// parent's family plan?
// ---------------------------------------------------------------------------
 
export interface FamilyCoverage {
  isCovered: boolean
  coveredBy: { userId: string; name: string } | null
  coveredChildCount: number
  totalChildCount: number
}
 
/**
 * For a given (typically free-tier) user, check whether any of their children
 * are covered by another parent's family subscription.
 *
 * This is used on pricing/settings pages to avoid confusing free-tier parents
 * who already have coverage through a co-parent.
 */
export async function getUserFamilyCoverage(userId: string): Promise<FamilyCoverage> {
  const playerIds = await getParentedPlayerIds(userId)

  if (playerIds.length === 0) {
    return { isCovered: false, coveredBy: null, coveredChildCount: 0, totalChildCount: 0 }
  }

  let coveredCount = 0
  let firstProvider: { userId: string; name: string } | null = null

  for (const pid of playerIds) {
    const result = await getEffectiveTierForStudent(pid, userId)
    if (result.tier === 'family' && result.providedBy !== null) {
      coveredCount++
      if (!firstProvider) {
        firstProvider = result.providedBy
      }
    }
  }

  return {
    isCovered: coveredCount > 0,
    coveredBy: firstProvider,
    coveredChildCount: coveredCount,
    totalChildCount: playerIds.length,
  }
}