All files / web/src/lib household.ts

28.36% Statements 135/476
50% Branches 2/4
15.38% Functions 2/13
28.36% Lines 135/476

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 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 4771x 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 1x 1x 1x 1x                                                       1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 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 3x 3x 3x 3x 3x 3x 3x 3x 3x                                                  
/**
 * Household Management Module
 *
 * Core logic for creating and managing households.
 * A household groups multiple users under a single subscription —
 * the owner's subscription covers all household members.
 */
 
import { and, eq, inArray, ne, notInArray, sql } from 'drizzle-orm'
import { db } from '@/db'
import { households, householdMembers, parentChild, players, users } from '@/db/schema'
import { createId } from '@paralleldrive/cuid2'
 
/** Maximum number of members in a household */
export const MAX_HOUSEHOLD_SIZE = 10
 
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
 
export interface HouseholdSummary {
  id: string
  name: string
  ownerId: string
  role: 'owner' | 'member'
  memberCount: number
}
 
export interface HouseholdDetail {
  id: string
  name: string
  ownerId: string
  createdAt: Date
  members: Array<{
    userId: string
    name: string | null
    email: string | null
    image: string | null
    role: 'owner' | 'member'
    joinedAt: Date
  }>
}
 
// ---------------------------------------------------------------------------
// Queries
// ---------------------------------------------------------------------------
 
/**
 * Get all households a user belongs to, with member counts.
 */
export async function getUserHouseholds(userId: string): Promise<HouseholdSummary[]> {
  const rows = await db
    .select({
      id: households.id,
      name: households.name,
      ownerId: households.ownerId,
      role: householdMembers.role,
      memberCount: sql<number>`(
        SELECT COUNT(*) FROM household_members hm2
        WHERE hm2.household_id = ${households.id}
      )`,
    })
    .from(householdMembers)
    .innerJoin(households, eq(householdMembers.householdId, households.id))
    .where(eq(householdMembers.userId, userId))

  return rows.map((r) => ({
    id: r.id,
    name: r.name,
    ownerId: r.ownerId,
    role: r.role as 'owner' | 'member',
    memberCount: Number(r.memberCount),
  }))
}
 
/**
 * Get full details of a household including all members.
 */
export async function getHouseholdDetail(householdId: string): Promise<HouseholdDetail | null> {
  const household = await db.query.households.findFirst({
    where: eq(households.id, householdId),
  })

  if (!household) return null

  const members = await db
    .select({
      userId: householdMembers.userId,
      name: users.name,
      email: users.email,
      image: users.image,
      role: householdMembers.role,
      joinedAt: householdMembers.joinedAt,
    })
    .from(householdMembers)
    .innerJoin(users, eq(householdMembers.userId, users.id))
    .where(eq(householdMembers.householdId, householdId))

  return {
    id: household.id,
    name: household.name,
    ownerId: household.ownerId,
    createdAt: household.createdAt,
    members: members.map((m) => ({
      userId: m.userId,
      name: m.name,
      email: m.email,
      image: m.image,
      role: m.role as 'owner' | 'member',
      joinedAt: m.joinedAt,
    })),
  }
}
 
/**
 * Check if a user is a member of a specific household.
 */
export async function isHouseholdMember(householdId: string, userId: string): Promise<boolean> {
  const row = await db.query.householdMembers.findFirst({
    where: and(eq(householdMembers.householdId, householdId), eq(householdMembers.userId, userId)),
  })
  return !!row
}
 
/**
 * Suggest users who share children with household members but aren't in the household.
 */
export async function getHouseholdSuggestions(householdId: string): Promise<
  Array<{
    userId: string
    name: string | null
    email: string | null
    image: string | null
    sharedChildren: string[]
  }>
> {
  // 1. Get current household member IDs
  const members = await db
    .select({ userId: householdMembers.userId })
    .from(householdMembers)
    .where(eq(householdMembers.householdId, householdId))

  const memberIds = members.map((m) => m.userId)
  if (memberIds.length === 0) return []

  // 2. Find children of household members
  const memberChildren = await db
    .select({
      parentUserId: parentChild.parentUserId,
      childPlayerId: parentChild.childPlayerId,
    })
    .from(parentChild)
    .where(inArray(parentChild.parentUserId, memberIds))

  const childIds = [...new Set(memberChildren.map((r) => r.childPlayerId))]
  if (childIds.length === 0) return []

  // 3. Find other parents of those children who aren't in the household
  const coParents = await db
    .select({
      parentUserId: parentChild.parentUserId,
      childPlayerId: parentChild.childPlayerId,
    })
    .from(parentChild)
    .where(
      and(
        inArray(parentChild.childPlayerId, childIds),
        notInArray(parentChild.parentUserId, memberIds)
      )
    )

  if (coParents.length === 0) return []

  // 4. Group by parent, collect shared child IDs
  const parentChildMap = new Map<string, Set<string>>()
  for (const row of coParents) {
    if (!parentChildMap.has(row.parentUserId)) {
      parentChildMap.set(row.parentUserId, new Set())
    }
    parentChildMap.get(row.parentUserId)!.add(row.childPlayerId)
  }

  // 5. Look up user details
  const parentIds = [...parentChildMap.keys()]
  const parentUsers = await db
    .select({ id: users.id, name: users.name, email: users.email, image: users.image })
    .from(users)
    .where(inArray(users.id, parentIds))

  // 6. Resolve child player names
  const allChildIds = [...new Set([...parentChildMap.values()].flatMap((s) => [...s]))]
  const childPlayers =
    allChildIds.length > 0
      ? await db
          .select({ id: players.id, name: players.name })
          .from(players)
          .where(inArray(players.id, allChildIds))
      : []
  const childNameMap = new Map(childPlayers.map((p) => [p.id, p.name]))

  // Only suggest users with a name or email (skip anonymous guest accounts)
  return parentUsers
    .filter((u) => u.name || u.email)
    .map((u) => ({
      userId: u.id,
      name: u.name,
      email: u.email,
      image: u.image,
      sharedChildren: [...(parentChildMap.get(u.id) || [])].map(
        (id) => childNameMap.get(id) || 'Unknown'
      ),
    }))
}
 
// ---------------------------------------------------------------------------
// Mutations
// ---------------------------------------------------------------------------
 
/**
 * Create a new household with the given user as owner.
 * A user can only own one household.
 */
export async function createHousehold(
  ownerId: string,
  name: string
): Promise<{ id: string; name: string }> {
  // Enforce one-household-per-owner
  const existing = await findOwnedHousehold(ownerId)
  if (existing) {
    throw new Error('You already own a household')
  }

  const id = createId()

  await db.insert(households).values({
    id,
    name,
    ownerId,
  })

  // Add the owner as the first member
  await db.insert(householdMembers).values({
    householdId: id,
    userId: ownerId,
    role: 'owner',
  })

  return { id, name }
}
 
/**
 * Find a household owned by a specific user.
 * Returns the first one found (a user could own multiple).
 */
async function findOwnedHousehold(ownerId: string) {
  return db.query.households.findFirst({
    where: eq(households.ownerId, ownerId),
  })
}
 
/**
 * Get the current member count for a household.
 */
async function getHouseholdMemberCount(householdId: string): Promise<number> {
  const [row] = await db
    .select({ count: sql<number>`COUNT(*)` })
    .from(householdMembers)
    .where(eq(householdMembers.householdId, householdId))

  return Number(row?.count ?? 0)
}
 
/**
 * Add a user to a household if they're not already a member.
 * Idempotent — silently succeeds if already a member.
 */
async function addMemberIfNotExists(householdId: string, userId: string): Promise<void> {
  const existing = await db.query.householdMembers.findFirst({
    where: and(eq(householdMembers.householdId, householdId), eq(householdMembers.userId, userId)),
  })

  if (existing) return

  await db.insert(householdMembers).values({
    householdId,
    userId,
    role: 'member',
  })
}
 
/**
 * Add a member to a household (owner-initiated).
 * Enforces the size cap and uniqueness.
 */
export async function addHouseholdMember(
  householdId: string,
  userId: string
): Promise<{ success: boolean; error?: string }> {
  // Check size cap
  const count = await getHouseholdMemberCount(householdId)
  if (count >= MAX_HOUSEHOLD_SIZE) {
    return { success: false, error: `Household is full (max ${MAX_HOUSEHOLD_SIZE} members)` }
  }

  // Check if already a member
  const existing = await db.query.householdMembers.findFirst({
    where: and(eq(householdMembers.householdId, householdId), eq(householdMembers.userId, userId)),
  })

  if (existing) {
    return { success: false, error: 'User is already a member of this household' }
  }

  await db.insert(householdMembers).values({
    householdId,
    userId,
    role: 'member',
  })

  return { success: true }
}
 
/**
 * Remove a member from a household.
 *
 * Lifecycle rules:
 * - Non-owner members can leave freely.
 * - Owner with other members must transfer ownership first.
 * - Owner as sole member → dissolves the household entirely.
 */
export async function removeHouseholdMember(
  householdId: string,
  userId: string
): Promise<{ success: boolean; dissolved?: boolean; error?: string }> {
  const household = await db.query.households.findFirst({
    where: eq(households.id, householdId),
  })

  if (!household) {
    return { success: false, error: 'Household not found' }
  }

  if (household.ownerId === userId) {
    const memberCount = await getHouseholdMemberCount(householdId)

    if (memberCount > 1) {
      return { success: false, error: 'Transfer ownership before leaving the household' }
    }

    // Sole owner — dissolve the household (CASCADE deletes memberships)
    await db.delete(households).where(eq(households.id, householdId))
    return { success: true, dissolved: true }
  }

  await db
    .delete(householdMembers)
    .where(and(eq(householdMembers.householdId, householdId), eq(householdMembers.userId, userId)))

  return { success: true }
}
 
/**
 * Transfer household ownership to another member.
 * The new owner must already be a member of the household.
 */
export async function transferHouseholdOwnership(
  householdId: string,
  currentOwnerId: string,
  newOwnerId: string
): Promise<{ success: boolean; error?: string }> {
  const household = await db.query.households.findFirst({
    where: eq(households.id, householdId),
  })

  if (!household) {
    return { success: false, error: 'Household not found' }
  }

  if (household.ownerId !== currentOwnerId) {
    return { success: false, error: 'Only the current owner can transfer ownership' }
  }

  // Verify new owner is a member
  const newOwnerMembership = await db.query.householdMembers.findFirst({
    where: and(
      eq(householdMembers.householdId, householdId),
      eq(householdMembers.userId, newOwnerId)
    ),
  })

  if (!newOwnerMembership) {
    return { success: false, error: 'New owner must be a member of the household' }
  }

  // Update household owner
  await db
    .update(households)
    .set({ ownerId: newOwnerId, updatedAt: new Date() })
    .where(eq(households.id, householdId))

  // Update member roles
  await db
    .update(householdMembers)
    .set({ role: 'member' })
    .where(
      and(
        eq(householdMembers.householdId, householdId),
        eq(householdMembers.userId, currentOwnerId)
      )
    )

  await db
    .update(householdMembers)
    .set({ role: 'owner' })
    .where(
      and(eq(householdMembers.householdId, householdId), eq(householdMembers.userId, newOwnerId))
    )

  return { success: true }
}
 
/**
 * Update household name.
 */
export async function updateHouseholdName(householdId: string, name: string): Promise<void> {
  await db
    .update(households)
    .set({ name, updatedAt: new Date() })
    .where(eq(households.id, householdId))
}
 
// ---------------------------------------------------------------------------
// Auto-formation (called from family-manager on family code link)
// ---------------------------------------------------------------------------
 
/**
 * Automatically create or join a household when a parent links to a child.
 *
 * If the child's owner already has a household, add the new parent to it.
 * If not, create a household for the owner and add both.
 *
 * This is called from `linkParentToChild()` after a successful link.
 */
export async function autoFormHousehold(
  childOwnerUserId: string,
  newParentUserId: string
): Promise<void> {
  // Don't form a household with yourself
  if (childOwnerUserId === newParentUserId) return
 
  // 1. Find owner's existing household (where they are owner)
  let household = await findOwnedHousehold(childOwnerUserId)

  // 2. If none, create one
  if (!household) {
    // Look up owner's name for the household name
    const owner = await db.query.users.findFirst({
      where: eq(users.id, childOwnerUserId),
      columns: { name: true },
    })
    const householdName = owner?.name ? `${owner.name}'s Family` : 'My Family'

    const created = await createHousehold(childOwnerUserId, householdName)
    household = await db.query.households.findFirst({
      where: eq(households.id, created.id),
    })
    if (!household) return // shouldn't happen
  }

  // 3. Check size cap
  const memberCount = await getHouseholdMemberCount(household.id)
  if (memberCount >= MAX_HOUSEHOLD_SIZE) return // silently skip

  // 4. Add new parent (idempotent)
  await addMemberIfNotExists(household.id, newParentUserId)
}