import { asc, eq, isNull } from 'drizzle-orm'; import { db } from '$lib/server/db'; import { organizations, session } from '$lib/server/db/schema'; const DEFAULT_ORGANIZATION_ID = 'default-organization'; type SessionWithOrganization = { id: string; activeOrganizationId?: string | null; }; export async function loadOrganizationContext(locals: App.Locals) { const rows = await db .select() .from(organizations) .where(isNull(organizations.archivedAt)) .orderBy(asc(organizations.name)); if (rows.length === 0) { const now = new Date(); await db.insert(organizations).values({ id: DEFAULT_ORGANIZATION_ID, name: 'Steel City Stadium', workspace: 'Blueprint Workspace', createdAt: now, updatedAt: now }); rows.push({ id: DEFAULT_ORGANIZATION_ID, name: 'Steel City Stadium', workspace: 'Blueprint Workspace', addressLine1: null, addressLine2: null, city: null, region: null, postcode: null, country: 'United Kingdom', bankName: null, bankAccountName: null, bankAccountNumber: null, bankSortCode: null, bankIban: null, bankSwift: null, createdAt: now, updatedAt: now, archivedAt: null }); } const currentSession = locals.session as SessionWithOrganization | undefined; const activeOrganization = rows.find((organization) => organization.id === currentSession?.activeOrganizationId) ?? rows[0]; if (currentSession && currentSession.activeOrganizationId !== activeOrganization.id) { await db .update(session) .set({ activeOrganizationId: activeOrganization.id, updatedAt: new Date() }) .where(eq(session.id, currentSession.id)); currentSession.activeOrganizationId = activeOrganization.id; } return { organizations: rows, activeOrganization, activeOrganizationId: activeOrganization.id }; } export async function setActiveOrganization(locals: App.Locals, organizationId: string) { const [organization] = await db .select() .from(organizations) .where(eq(organizations.id, organizationId)) .limit(1); const currentSession = locals.session as SessionWithOrganization | undefined; if (!organization || organization.archivedAt || !currentSession) { return null; } await db .update(session) .set({ activeOrganizationId: organization.id, updatedAt: new Date() }) .where(eq(session.id, currentSession.id)); currentSession.activeOrganizationId = organization.id; return organization; }