@fayz-ai/admin 0.16.0 → 0.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{ScheduleEditor-A3SX6AYD.js → ScheduleEditor-63TVSCJC.js} +5 -4
- package/dist/ScheduleEditor-63TVSCJC.js.map +1 -0
- package/dist/SubscriptionPage-5PJ25YAD.js +8 -0
- package/dist/{SubscriptionPage-FE2B5ZXF.js.map → SubscriptionPage-5PJ25YAD.js.map} +1 -1
- package/dist/access/context.d.ts +3 -1
- package/dist/access/context.d.ts.map +1 -1
- package/dist/app/AdminShell.d.ts +6 -0
- package/dist/app/AdminShell.d.ts.map +1 -1
- package/dist/app/admin-app.d.ts.map +1 -1
- package/dist/app/config.d.ts +16 -0
- package/dist/app/config.d.ts.map +1 -1
- package/dist/app/scaffold.d.ts.map +1 -1
- package/dist/billing/TrialWidget.d.ts +25 -0
- package/dist/billing/TrialWidget.d.ts.map +1 -0
- package/dist/billing/index.d.ts +2 -0
- package/dist/billing/index.d.ts.map +1 -1
- package/dist/billing/index.js +2 -1
- package/dist/billing/trial.d.ts +48 -0
- package/dist/billing/trial.d.ts.map +1 -0
- package/dist/chunk-7DFJEXCR.js +48 -0
- package/dist/chunk-7DFJEXCR.js.map +1 -0
- package/dist/chunk-ERDS4OJS.js +194 -0
- package/dist/chunk-ERDS4OJS.js.map +1 -0
- package/dist/{chunk-IPWXA46H.js → chunk-G5PBC5OB.js} +10 -9
- package/dist/chunk-G5PBC5OB.js.map +1 -0
- package/dist/{chunk-OOWP6W2I.js → chunk-LZRLWKJ2.js} +3 -2
- package/dist/chunk-LZRLWKJ2.js.map +1 -0
- package/dist/{chunk-OB7ZSTQD.js → chunk-WN6PGQSG.js} +9 -51
- package/dist/chunk-WN6PGQSG.js.map +1 -0
- package/dist/components/billing/SoftLimitBanner.d.ts.map +1 -1
- package/dist/components/chat/ChatFab.d.ts.map +1 -1
- package/dist/crud/CrudAgentSurface.d.ts +7 -0
- package/dist/crud/CrudAgentSurface.d.ts.map +1 -1
- package/dist/crud/CrudPage.d.ts.map +1 -1
- package/dist/handbook/HandbookAgentSurface.d.ts +2 -0
- package/dist/handbook/HandbookAgentSurface.d.ts.map +1 -0
- package/dist/handbook/HandbookProvider.d.ts +7 -0
- package/dist/handbook/HandbookProvider.d.ts.map +1 -0
- package/dist/handbook/NotebookPanel.d.ts +5 -0
- package/dist/handbook/NotebookPanel.d.ts.map +1 -0
- package/dist/handbook/backend.d.ts +42 -0
- package/dist/handbook/backend.d.ts.map +1 -0
- package/dist/handbook/index.d.ts +10 -0
- package/dist/handbook/index.d.ts.map +1 -0
- package/dist/handbook/store.d.ts +36 -0
- package/dist/handbook/store.d.ts.map +1 -0
- package/dist/handbook/types.d.ts +124 -0
- package/dist/handbook/types.d.ts.map +1 -0
- package/dist/hooks/useAITools.d.ts.map +1 -1
- package/dist/hooks/useChat.d.ts.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5270 -3549
- package/dist/index.js.map +1 -1
- package/dist/lib/ai-tool-handlers.d.ts.map +1 -1
- package/dist/onboarding/ActivationAgentSurface.d.ts +6 -0
- package/dist/onboarding/ActivationAgentSurface.d.ts.map +1 -0
- package/dist/onboarding/ActivationChecklistCard.d.ts +23 -0
- package/dist/onboarding/ActivationChecklistCard.d.ts.map +1 -0
- package/dist/onboarding/ActivationProvider.d.ts +17 -0
- package/dist/onboarding/ActivationProvider.d.ts.map +1 -0
- package/dist/onboarding/GettingStartedWidget.d.ts +5 -5
- package/dist/onboarding/activation.store.d.ts +53 -0
- package/dist/onboarding/activation.store.d.ts.map +1 -0
- package/dist/onboarding/backend.d.ts +14 -0
- package/dist/onboarding/backend.d.ts.map +1 -1
- package/dist/onboarding/checklist.d.ts +23 -0
- package/dist/onboarding/checklist.d.ts.map +1 -1
- package/dist/onboarding/guided-runner.d.ts +87 -0
- package/dist/onboarding/guided-runner.d.ts.map +1 -0
- package/dist/onboarding/guided.d.ts +27 -0
- package/dist/onboarding/guided.d.ts.map +1 -0
- package/dist/onboarding/handbook-seed.d.ts +70 -0
- package/dist/onboarding/handbook-seed.d.ts.map +1 -0
- package/dist/onboarding/index.d.ts +12 -3
- package/dist/onboarding/index.d.ts.map +1 -1
- package/dist/onboarding/programs.d.ts +78 -0
- package/dist/onboarding/programs.d.ts.map +1 -0
- package/dist/onboarding/submit.d.ts +7 -2
- package/dist/onboarding/submit.d.ts.map +1 -1
- package/dist/onboarding/tasks.d.ts +7 -0
- package/dist/onboarding/tasks.d.ts.map +1 -1
- package/dist/onboarding/useActivationWatch.d.ts +2 -0
- package/dist/onboarding/useActivationWatch.d.ts.map +1 -0
- package/dist/org/adapters/supabase.d.ts.map +1 -1
- package/dist/org/index.js +3 -2
- package/dist/tasks/components/TaskCard.d.ts.map +1 -1
- package/package.json +5 -5
- package/dist/ScheduleEditor-A3SX6AYD.js.map +0 -1
- package/dist/SubscriptionPage-FE2B5ZXF.js +0 -7
- package/dist/chunk-IPWXA46H.js.map +0 -1
- package/dist/chunk-OB7ZSTQD.js.map +0 -1
- package/dist/chunk-OOWP6W2I.js.map +0 -1
- package/dist/chunk-VN5NTK26.js +0 -36
- package/dist/chunk-VN5NTK26.js.map +0 -1
- package/dist/components/notes/NotesPanel.d.ts +0 -13
- package/dist/components/notes/NotesPanel.d.ts.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/data/client.ts","../src/org/team-rows.ts","../src/org/adapters/supabase.ts","../src/org/adapters/mock.ts"],"names":["capitalize","slugify"],"mappings":";;;;;AAIA,IAAI,OAAA,GAAiC,IAAA;AAS9B,SAAS,WAAW,KAAA,EAAkC;AAC3D,EAAA,IAAI,OAAO,KAAA,KAAU,QAAA,EAAU,OAAO,KAAA;AACtC,EAAA,IAAI,KAAA,YAAiB,GAAA,EAAK,OAAO,KAAA,CAAM,QAAA,EAAS;AAChD,EAAA,OAAO,OAAO,GAAA,IAAO,EAA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AA,CAAU,IAAI,CAAA;AACd,MAAA,OAAO,MAAA;AAAA,IACT,CAAA;AAAA,IAEA,MAAM,cAAc,MAAA,EAAqC;AACvD,MAAA,OAAO,EAAC;AAAA,IACV,CAAA;AAAA,IAEA,MAAM,cAAA,CACJ,KAAA,EACA,KAAA,EASmB;AACnB,MAAA,OAAO;AAAA,QACL,EAAA,EAAI,OAAO,UAAA,EAAW;AAAA,QACtB,QAAA,EAAU,KAAA;AAAA,QACV,MAAM,KAAA,CAAM,IAAA;AAAA,QACZ,SAAS,KAAA,CAAM,OAAA;AAAA,QACf,MAAM,KAAA,CAAM,IAAA;AAAA,QACZ,OAAO,KAAA,CAAM,KAAA;AAAA,QACb,OAAA,EAAS,MAAM,OAAA,IAAW,IAAA;AAAA,QAC1B,OAAO,KAAA,CAAM,KAAA;AAAA,QACb,cAAA,EAAgB,MAAM,cAAA,IAAkB,KAAA;AAAA,QACxC,QAAA,EAAU,IAAA;AAAA,QACV,SAAA,EAAA,iBAAW,IAAI,IAAA,EAAK,EAAE,WAAA,EAAY;AAAA,QAClC,SAAA,EAAA,iBAAW,IAAI,IAAA,EAAK,EAAE,WAAA;AAAY,OACpC;AAAA,IACF;AAAA,GACF;AACF","file":"chunk-LZRLWKJ2.js","sourcesContent":["import { createClient, type SupabaseClient } from '@supabase/supabase-js'\nimport { setGlobalSupabaseClient, getActiveUnitId, getActiveTenantId } from '@fayz-ai/core'\nimport { createDedupedFetch } from '@fayz-ai/sdk'\n\nlet _client: SupabaseClient | null = null\n\n/**\n * Para onde a requisição vai, nos três formatos que `fetch` aceita.\n *\n * `input` pode ser uma string, uma URL ou um Request — e ler `.url` de uma\n * string devolve `undefined` em silêncio, que é como um filtro destes deixa\n * passar exatamente o que devia barrar.\n */\nexport function requestUrl(input: RequestInfo | URL): string {\n if (typeof input === 'string') return input\n if (input instanceof URL) return input.toString()\n return input?.url ?? ''\n}\n\n/** O caminho que o Supabase dá a toda função de borda. Exportada para o teste. */\nexport function isEdgeFunctionCall(input: RequestInfo | URL): boolean {\n return requestUrl(input).includes('/functions/v1/')\n}\n\n/**\n * Create (and cache) the Supabase client for the Fayz app.\n * Also registers it as the global client in @fayz-ai/core so data providers\n * can resolve it without prop-drilling.\n *\n * Idempotent — subsequent calls with the same URL return the cached client.\n */\nexport function createFayzSupabaseClient(url: string, anonKey: string): SupabaseClient {\n if (_client) return _client\n\n if (!url || !anonKey) {\n throw new Error(\n '[@fayz-ai/admin] Supabase URL and anon key are required. ' +\n 'Pass supabaseUrl and supabaseAnonKey to createFayzApp.',\n )\n }\n\n // Every read goes through this client — the one place that can see two\n // components asking the same thing at the same instant.\n const deduped = createDedupedFetch()\n\n _client = createClient(url, anonKey, {\n auth: { autoRefreshToken: true, persistSession: true },\n global: {\n // The active unit rides on every request so the DATABASE can stamp a\n // write with it (041's trigger reads this header). Reads are narrowed by\n // an explicit filter, not by this — a header cannot be trusted to narrow,\n // and it must never be able to widen: the policies resolve unit access\n // through `public.user_unit_ids()`, never through what was sent here.\n //\n // `x-fayz-unit` is in the dedupe vary list. Without that, two identical\n // URLs under different units collapse into one response.\n fetch: (input: RequestInfo | URL, init: RequestInit = {}) => {\n // Estes cabeçalhos são para o BANCO, e só para ele. Uma função de borda\n // recebe o tenant no corpo (`tenantId`) e nunca leu nenhum dos dois — o\n // que ela faz com um cabeçalho desconhecido é RECUSAR O PREFLIGHT, e o\n // navegador então bloqueia o POST antes de ele sair. Nenhuma requisição\n // chega ao log, e quem está usando vê a palavra \"CORS\".\n //\n // As vinte funções deste repositório declaram listas fixas de\n // `Access-Control-Allow-Headers` e nenhuma delas cita `x-fayz-tenant`.\n // Mandar o cabeçalho para lá não compra nada e derruba todas de uma vez.\n if (isEdgeFunctionCall(input)) return deduped(input, init)\n\n const unit = getActiveUnitId()\n // `x-fayz-tenant` rides the same way, for the reason 145 spells out:\n // the archetype policies resolve tenant through app.current_tenant_id(),\n // which knew only the signed JWT claim (nobody mints one) or \"your only\n // account\". A user with two accounts therefore read NOTHING from\n // public.people / orders / products — silently, and long before any\n // screen moved. This is the app finally saying which account it is in.\n //\n // Same rule as the unit header, and 145 enforces it: the value only\n // CHOOSES among the accounts the user already belongs to, validated\n // against app.memberships. It narrows; it can never widen.\n const tenant = getActiveTenantId()\n if (!unit && !tenant) return deduped(input, init)\n const headers = new Headers(init.headers)\n if (unit) headers.set('x-fayz-unit', unit)\n if (tenant) headers.set('x-fayz-tenant', tenant)\n return deduped(input, { ...init, headers })\n },\n },\n })\n\n // Register globally so @fayz-ai/core data providers can use it\n setGlobalSupabaseClient(_client)\n\n return _client\n}\n\n/** Get the cached client — throws if not initialised */\nexport function getFayzSupabaseClient(): SupabaseClient {\n if (!_client) {\n throw new Error(\n '[@fayz-ai/admin] Supabase client not initialised. Call createFayzApp with supabaseUrl and supabaseAnonKey first.',\n )\n }\n return _client\n}\n\n/** Safe getter — returns null if not initialised (mock/offline mode) */\nexport function getFayzSupabaseClientOptional(): SupabaseClient | null {\n return _client\n}\n","import type { TeamPerson } from '@fayz-ai/core'\n\n/** A `people` row as the team query selects it. */\nexport interface TeamPeopleRow {\n id: string\n name?: string | null\n kind?: string | null\n email?: string | null\n avatar_url?: string | null\n is_active?: boolean | null\n}\n\n/** A `tenant_members` row as the team query selects it. */\nexport interface TeamMemberRow {\n id: string\n user_id: string\n role?: string | null\n person_id?: string | null\n created_at?: string | null\n}\n\n/** A `profiles` row for a member's login. */\nexport interface TeamProfileRow {\n id: string\n full_name?: string | null\n email?: string | null\n avatar_url?: string | null\n}\n\n/** The signed-in user, used to name their own row when `profiles` has no row for them. */\nexport interface TeamCurrentUser {\n id: string\n email?: string | null\n fullName?: string | null\n}\n\nconst capitalize = (s: string) => (s ? s.charAt(0).toUpperCase() + s.slice(1) : s)\n\n/**\n * Fallback display name for a login with no person record. `profiles` is not\n * guaranteed to have a row (accounts created before the trigger, seeded demos),\n * and its RLS only ever exposes your own — so the session is the last resort for\n * your own row, and the email handle the one after that.\n */\nfunction loginName(profile: TeamProfileRow | undefined, session: TeamCurrentUser | undefined): string {\n const candidates = [profile?.full_name, session?.fullName, profile?.email, session?.email]\n for (const candidate of candidates) {\n const value = candidate?.trim()\n if (value) return value.includes('@') ? value.split('@')[0] : value\n }\n return ''\n}\n\n/**\n * Merges the two halves of the team into one list.\n *\n * People of the configured kinds are the roster; `tenant_members` is the access\n * overlay linked by `person_id`. But a login is not required to have a person\n * record — the owner who created the workspace never gets one — and dropping\n * those rows left the Team screen empty for every account that had not staffed\n * itself as a person. So memberships that match no listed person come back as\n * rows of their own, named from their login profile and carrying no `personId`.\n * Logins come first: whoever holds access is the answer to \"who is my team?\"\n * before the roster of people who may never sign in.\n */\nexport function buildTeamRows(\n people: TeamPeopleRow[],\n members: TeamMemberRow[],\n profiles: TeamProfileRow[],\n currentUser?: TeamCurrentUser | null,\n): TeamPerson[] {\n const personIds = new Set(people.map((p) => p.id))\n const byPerson = new Map<string, TeamMemberRow>()\n const unlinked: TeamMemberRow[] = []\n\n for (const m of members) {\n if (m.person_id && personIds.has(m.person_id)) byPerson.set(m.person_id, m)\n else unlinked.push(m)\n }\n\n const profileById = new Map(profiles.map((p) => [p.id, p]))\n\n const toMembership = (m: TeamMemberRow) => ({\n memberId: m.id,\n userId: m.user_id,\n profileId: (m.role as string) ?? '',\n profileName: capitalize((m.role as string) ?? ''),\n joinedAt: m.created_at ?? undefined,\n })\n\n const loginRows: TeamPerson[] = unlinked.map((m) => {\n const profile = profileById.get(m.user_id)\n const session = currentUser && currentUser.id === m.user_id ? currentUser : undefined\n return {\n name: loginName(profile, session),\n email: profile?.email ?? session?.email ?? undefined,\n avatarUrl: profile?.avatar_url ?? undefined,\n isActive: true,\n membership: toMembership(m),\n }\n })\n\n const personRows: TeamPerson[] = people.map((p) => {\n const m = byPerson.get(p.id)\n return {\n personId: p.id,\n name: p.name ?? '',\n kind: p.kind ?? undefined,\n email: p.email ?? undefined,\n avatarUrl: p.avatar_url ?? undefined,\n isActive: p.is_active ?? true,\n membership: m ? toMembership(m) : undefined,\n }\n })\n\n return [...loginRows, ...personRows]\n}\n","import type {\n OrgAdapter,\n Organization,\n OrgMember,\n OrgMembership,\n TeamPerson,\n CreateOrgOptions,\n Location,\n Invite,\n} from '@fayz-ai/core'\nimport type { PermissionProfile, SystemPermission, AuthAdapter } from '@fayz-ai/core'\nimport { getFayzSupabaseClient } from '../../data/client'\nimport { buildTeamRows } from '../team-rows'\nimport type { TeamMemberRow, TeamPeopleRow, TeamProfileRow } from '../team-rows'\n\n// ---------------------------------------------------------------------------\n// Request dedup — prevents duplicate in-flight requests (React StrictMode etc.)\n// ---------------------------------------------------------------------------\n\nconst inflightRequests = new Map<string, Promise<unknown>>()\n\nfunction dedup<T>(key: string, fn: () => Promise<T>): Promise<T> {\n const existing = inflightRequests.get(key)\n if (existing) return existing as Promise<T>\n\n const promise = fn().finally(() => {\n inflightRequests.delete(key)\n })\n inflightRequests.set(key, promise)\n return promise\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction slugify(name: string): string {\n return name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')\n}\n\nfunction capitalize(s: string): string {\n return s.charAt(0).toUpperCase() + s.slice(1)\n}\n\nfunction mapTenantToOrg(row: Record<string, unknown>): Organization {\n return {\n id: row['id'] as string,\n name: row['name'] as string,\n slug: row['slug'] as string,\n logoUrl: (row['logo_url'] as string | null) ?? undefined,\n verticalId: (row['vertical_id'] as string | null) ?? undefined,\n plan: (row['plan'] as string | null) ?? undefined,\n trialEndsAt: (row['trial_ends_at'] as string | null) ?? undefined,\n settings: (row['settings'] as Record<string, unknown> | null) ?? undefined,\n createdAt: row['created_at'] as string,\n updatedAt: row['updated_at'] as string,\n }\n}\n\nfunction mapMemberRow(row: Record<string, unknown>): OrgMember {\n const profile = (row['profile'] as Record<string, unknown>) ?? {}\n return {\n id: row['id'] as string,\n userId: row['user_id'] as string,\n orgId: row['tenant_id'] as string,\n profileId: row['role'] as string,\n profileName: capitalize(row['role'] as string),\n user: {\n id: row['user_id'] as string,\n email: (profile['email'] as string) ?? '',\n fullName: (profile['full_name'] as string) ?? '',\n avatarUrl: (profile['avatar_url'] as string | null) ?? undefined,\n },\n // tenant_members has no `joined_at` column — it's `created_at`.\n joinedAt: (row['joined_at'] ?? row['created_at']) as string,\n }\n}\n\nfunction mapLocationRow(row: Record<string, unknown>): Location {\n return {\n id: row['id'] as string,\n tenantId: row['tenant_id'] as string,\n name: row['name'] as string,\n address: (row['address'] as string | null) ?? undefined,\n city: (row['city'] as string | null) ?? undefined,\n state: (row['state'] as string | null) ?? undefined,\n country: (row['country'] as string | null) ?? undefined,\n phone: (row['phone'] as string | null) ?? undefined,\n isHeadquarters: (row['is_headquarters'] as boolean) ?? false,\n isActive: (row['is_active'] as boolean) ?? true,\n createdAt: row['created_at'] as string,\n updatedAt: row['updated_at'] as string,\n }\n}\n\nfunction mapInviteRow(row: Record<string, unknown>): Invite {\n return {\n id: row['id'] as string,\n orgId: row['tenant_id'] as string,\n email: row['email'] as string,\n profileId: row['role'] as string,\n profileName: capitalize(row['role'] as string),\n invitedBy: row['invited_by'] as string,\n token: row['token'] as string,\n status: (row['status'] as Invite['status']) ?? 'pending',\n createdAt: row['created_at'] as string,\n expiresAt: row['expires_at'] as string,\n }\n}\n\n/** Minimal role identity the adapter needs to build profiles. Grants come from\n * the DB catalog; id/name/order/description come from what the app declares. */\nexport interface RoleIdentity {\n id: string\n name: string\n description?: string\n /** System roles are app-defined and static (not user-editable). Custom roles\n * (duplicated by users, stored in tenant_roles) are false. Defaults true. */\n isSystem?: boolean\n}\n\n// Matrix emits read/create/edit/delete; map back to DB action verbs.\nconst DB_ACTION: Record<string, string> = {\n read: 'read', create: 'create', edit: 'update', write: 'create', manage: 'manage', delete: 'delete',\n}\n\nfunction slugifyRole(name: string): string {\n return name.toLowerCase().normalize('NFD').replace(/[\\u0300-\\u036f]/g, '')\n .replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'role'\n}\n\n// Fallback role set when the host app declares none. The SDK is domain-agnostic:\n// each app defines its OWN business roles (a salon's roles ≠ an agency's) via\n// config.permissions.defaultProfiles. These five are only a back-compat default.\nconst DEFAULT_ROLES: RoleIdentity[] = [\n { id: 'owner', name: 'Owner' },\n { id: 'admin', name: 'Admin' },\n { id: 'manager', name: 'Manager' },\n { id: 'staff', name: 'Staff' },\n { id: 'viewer', name: 'Viewer' },\n]\n\n// DB permission ids that confer an org-management system permission.\nconst SYSTEM_PERMISSION_MAP: Record<string, SystemPermission> = {\n 'team.read': 'manage_team',\n 'team.invite': 'manage_team',\n 'team.manage': 'manage_team',\n 'team.manage_roles': 'manage_permissions',\n 'billing.read': 'manage_billing',\n 'billing.manage': 'manage_billing',\n 'settings.read': 'manage_settings',\n 'settings.update': 'manage_settings',\n}\nconst ALL_SYSTEM_PERMISSIONS: SystemPermission[] = ['manage_team', 'manage_billing', 'manage_settings', 'manage_permissions']\n\n// Map DB permission ids to feature action grants\nfunction buildPermissionProfiles(\n roles: RoleIdentity[],\n permissions: Array<{ id: string; category: string }>,\n rolePerms: Array<{ role: string; permission_id: string }>,\n overrides: Array<{ role: string; permission_id: string; granted: boolean }>,\n): PermissionProfile[] {\n const overrideMap = new Map<string, boolean>()\n for (const o of overrides) {\n overrideMap.set(`${o.role}:${o.permission_id}`, o.granted)\n }\n\n // The role SET comes from what the app declares — the SDK no longer bakes it in.\n const rolePermMap = new Map<string, Set<string>>()\n for (const r of roles) {\n rolePermMap.set(r.id, new Set())\n }\n // Convention: an 'owner' role (if declared) gets every permission implicitly.\n if (rolePermMap.has('owner')) {\n for (const p of permissions) rolePermMap.get('owner')!.add(p.id)\n }\n for (const rp of rolePerms) {\n rolePermMap.get(rp.role)?.add(rp.permission_id)\n }\n\n // Apply overrides\n for (const [key, granted] of overrideMap) {\n const colonIdx = key.indexOf(':')\n const role = key.slice(0, colonIdx)\n const permId = key.slice(colonIdx + 1)\n const perms = rolePermMap.get(role)\n if (!perms) continue\n if (granted) {\n perms.add(permId)\n } else {\n perms.delete(permId)\n }\n }\n\n // Align DB actions with the matrix's action vocabulary (read/create/edit/delete).\n const actionMap: Record<string, string> = {\n read: 'read',\n create: 'create',\n update: 'edit',\n manage: 'edit',\n delete: 'delete',\n configure: 'edit',\n invite: 'create',\n }\n\n return roles.map(({ id: role, name, description, isSystem }) => {\n const permIds = rolePermMap.get(role)!\n const features: Record<string, string[]> = {}\n\n for (const permId of permIds) {\n // LAST dot, not the first: a feature id may contain dots (plugin-crm\n // declares `crm.leads`), an action never does. Splitting on the first one\n // read `crm.leads.read` as feature `crm` + action `leads.read`, which no\n // action map knows — so every dotted feature the matrix granted came back\n // empty on the next load, silently.\n const dotIdx = permId.lastIndexOf('.')\n if (dotIdx <= 0) continue\n const category = permId.slice(0, dotIdx)\n const action = permId.slice(dotIdx + 1)\n const mappedAction = actionMap[action]\n if (!mappedAction) continue\n\n if (!features[category]) features[category] = []\n if (!features[category].includes(mappedAction)) {\n features[category].push(mappedAction)\n }\n }\n\n // Org-management system permissions, derived from team/billing/settings\n // grants (owner gets all four). These gate the Equipe/Permissões tabs.\n const systemPermissions: SystemPermission[] = []\n const source = role === 'owner' ? ALL_SYSTEM_PERMISSIONS : [...permIds].map((id) => SYSTEM_PERMISSION_MAP[id])\n for (const sp of source) {\n if (sp && !systemPermissions.includes(sp)) systemPermissions.push(sp)\n }\n\n return {\n id: role,\n name: name || capitalize(role),\n description,\n isSystem: isSystem ?? true,\n systemPermissions,\n grants: features,\n }\n })\n}\n\n// ---------------------------------------------------------------------------\n// Adapter factory\n// ---------------------------------------------------------------------------\n\nexport interface SupabaseOrgAdapterConfig {\n /** Deprecated — core tables now live in the public schema; this field is ignored. */\n coreSchema?: string\n /** Business roles the host app declares (config.permissions.defaultProfiles).\n * Falls back to the generic five when omitted. */\n roles?: RoleIdentity[]\n /** Auth adapter used to actually DELIVER invites (send the e-mail + create the\n * auth user) — the org adapter only records the audit row. Injected by the app;\n * when omitted, invites are recorded but not delivered. */\n authAdapter?: AuthAdapter\n /** Canonical, deployment-fixed origin baked into invite/magic-link redirects\n * (e.g. https://beauty-saas.live.fayz.ai). The container injects it as\n * VITE_APP_URL; the app wiring passes it here. Falls back to\n * window.location.origin, which is wrong when an admin invites from a preview\n * or localhost origin. Note: whatever origin ends up here must ALSO be in the\n * Supabase project's Redirect URLs allow-list, or Supabase silently swaps it\n * for its Site URL (default http://localhost:3000). */\n siteUrl?: string\n}\n\nexport function createSupabaseOrgAdapter(config?: SupabaseOrgAdapterConfig): OrgAdapter {\n const roles: RoleIdentity[] = config?.roles && config.roles.length > 0 ? config.roles : DEFAULT_ROLES\n const authAdapter = config?.authAdapter\n const originBase =\n config?.siteUrl?.replace(/\\/+$/, '') ??\n (typeof window !== 'undefined' ? window.location.origin : undefined)\n const inviteRedirectTo = originBase ? `${originBase}/` : undefined\n\n function supabase() {\n return getFayzSupabaseClient()\n }\n\n function core() {\n return supabase()\n }\n\n return {\n async acceptPendingInvites(): Promise<number> {\n const { data, error } = await supabase().rpc('accept_pending_invitations')\n if (error) {\n // A pool still on the pre-022 spine has no such function. Not fatal —\n // the user just lands org-less, exactly as before this shipped.\n console.warn('[org] accept_pending_invitations failed:', error.message)\n return 0\n }\n return typeof data === 'number' ? data : 0\n },\n\n async listUserOrgs(userId: string): Promise<OrgMembership[]> {\n return dedup(`listUserOrgs:${userId}`, async () => {\n const { data, error } = await core()\n .from('tenant_members')\n .select('tenant_id, role, tenant:tenants(id, name, slug, logo_url)')\n .eq('user_id', userId)\n\n if (error) throw error\n\n return ((data ?? []) as Array<Record<string, unknown>>).map((row) => ({\n orgId: row['tenant_id'] as string,\n orgName: ((row['tenant'] as Record<string, unknown>)?.['name'] as string) ?? '',\n orgSlug: ((row['tenant'] as Record<string, unknown>)?.['slug'] as string) ?? '',\n orgLogoUrl: ((row['tenant'] as Record<string, unknown>)?.['logo_url'] as string | null) ?? undefined,\n profileId: row['role'] as string,\n profileName: capitalize(row['role'] as string),\n }))\n })\n },\n\n async getOrg(orgId: string): Promise<Organization> {\n const { data, error } = await core()\n .from('tenants')\n .select('*')\n .eq('id', orgId)\n .single()\n\n if (error) throw error\n return mapTenantToOrg(data as Record<string, unknown>)\n },\n\n async createOrg(name: string, userId: string, options?: CreateOrgOptions): Promise<Organization> {\n const { data: tenant, error } = await supabase()\n .rpc('create_tenant_with_owner', {\n p_name: name,\n p_slug: slugify(name),\n p_user_id: userId,\n p_vertical_id: options?.verticalId ?? null,\n p_plan: 'free',\n p_settings: {\n timezone: options?.timezone ?? 'America/Sao_Paulo',\n currency: options?.currency ?? 'BRL',\n locale: options?.locale ?? 'pt-BR',\n teamSize: options?.teamSize ?? undefined,\n branding: options?.branding ?? {},\n },\n })\n\n if (error) throw error\n return mapTenantToOrg(tenant as Record<string, unknown>)\n },\n\n async updateOrg(orgId: string, updates: Partial<Organization>): Promise<Organization> {\n const row: Record<string, unknown> = {}\n if (updates.name !== undefined) row['name'] = updates.name\n if (updates.slug !== undefined) row['slug'] = updates.slug\n if (updates.logoUrl !== undefined) row['logo_url'] = updates.logoUrl\n if (updates.verticalId !== undefined) row['vertical_id'] = updates.verticalId\n if (updates.plan !== undefined) row['plan'] = updates.plan\n if (updates.settings !== undefined) row['settings'] = updates.settings\n\n const { data, error } = await core()\n .from('tenants')\n .update(row)\n .eq('id', orgId)\n .select()\n .single()\n\n if (error) throw error\n return mapTenantToOrg(data as Record<string, unknown>)\n },\n\n async listMembers(orgId: string): Promise<OrgMember[]> {\n const { data, error } = await core()\n .from('tenant_members')\n .select('*')\n .eq('tenant_id', orgId)\n\n if (error) throw error\n\n const userIds = ((data ?? []) as Array<Record<string, unknown>>).map((m) => m['user_id'] as string)\n const { data: profiles } = userIds.length > 0\n ? await core().from('profiles').select('id, full_name, avatar_url, email').in('id', userIds)\n : { data: [] }\n\n const profileMap = new Map(\n ((profiles ?? []) as Array<Record<string, unknown>>).map((p) => [p['id'], p]),\n )\n\n return ((data ?? []) as Array<Record<string, unknown>>).map((row) => {\n const profile = profileMap.get(row['user_id'] as string) ?? {}\n return mapMemberRow({ ...row, profile })\n })\n },\n\n // Person-first team list: people of `personKinds` are the roster and\n // `tenant_members` (login + role) is the overlay linked by person_id — plus\n // every membership that links to no listed person, so an account with access\n // is never missing from its own Team screen. See buildTeamRows.\n async listTeam(orgId: string, personKinds: string[]): Promise<TeamPerson[]> {\n if (!personKinds || personKinds.length === 0) return []\n\n const [peopleResult, membersResult] = await Promise.all([\n core()\n .from('people')\n .select('id, name, kind, email, avatar_url, is_active')\n .eq('tenant_id', orgId)\n .in('kind', personKinds)\n // Only people still on the roster. `not is false` rather than\n // `eq true` so a row that never set the flag stays visible — the\n // same `?? true` reading buildTeamRows applies. A deactivated\n // person who still holds a login does not vanish: their membership\n // stops matching a listed person and comes back as a login row,\n // which is the invariant that keeps access auditable.\n .not('is_active', 'is', false),\n core()\n .from('tenant_members')\n .select('id, user_id, role, person_id, created_at')\n .eq('tenant_id', orgId),\n ])\n if (peopleResult.error) throw peopleResult.error\n\n const people = (peopleResult.data ?? []) as TeamPeopleRow[]\n const members = (membersResult.data ?? []) as TeamMemberRow[]\n\n // Login-only rows are named from their auth profile — there is no person\n // record to name them after. The session is the fallback for your own row:\n // `profiles` has no row for accounts predating its trigger.\n const userIds = members.map((m) => m.user_id).filter(Boolean)\n const [profilesResult, sessionResult] = await Promise.all([\n userIds.length > 0\n ? core().from('profiles').select('id, full_name, avatar_url, email').in('id', userIds)\n : Promise.resolve({ data: [] }),\n core().auth.getSession(),\n ])\n\n const sessionUser = sessionResult?.data?.session?.user\n const currentUser = sessionUser\n ? {\n id: sessionUser.id,\n email: sessionUser.email,\n fullName: (sessionUser.user_metadata?.['full_name'] as string | undefined) ?? undefined,\n }\n : null\n\n return buildTeamRows(people, members, (profilesResult.data ?? []) as TeamProfileRow[], currentUser)\n },\n\n async updateMemberProfile(orgId: string, memberId: string, profileId: string): Promise<void> {\n const { error } = await core()\n .from('tenant_members')\n .update({ role: profileId })\n .eq('id', memberId)\n .eq('tenant_id', orgId)\n\n if (error) throw error\n },\n\n async removeMember(orgId: string, memberId: string): Promise<void> {\n const { error } = await core()\n .from('tenant_members')\n .delete()\n .eq('id', memberId)\n .eq('tenant_id', orgId)\n\n if (error) throw error\n },\n\n async listProfiles(orgId: string): Promise<PermissionProfile[]> {\n const [permsResult, rolePermsResult, overridesResult, customResult] = await Promise.all([\n core().from('permissions').select('id, category'),\n core().from('role_permissions').select('role, permission_id'),\n core().from('tenant_role_overrides').select('role, permission_id, granted').eq('tenant_id', orgId),\n // Custom roles the tenant created by duplicating a system role. Tolerate a\n // missing table (pre-seed) — just show the system roles in that case.\n core().from('tenant_roles').select('key, name, description').eq('tenant_id', orgId),\n ])\n\n if (permsResult.error) throw permsResult.error\n if (rolePermsResult.error) throw rolePermsResult.error\n if (overridesResult.error) throw overridesResult.error\n\n const systemRoles: RoleIdentity[] = roles.map((r) => ({ ...r, isSystem: true }))\n const customRoles: RoleIdentity[] = customResult.error\n ? []\n : ((customResult.data ?? []) as Array<{ key: string; name: string; description: string | null }>).map((r) => ({\n id: r.key,\n name: r.name,\n description: r.description ?? undefined,\n isSystem: false,\n }))\n\n return buildPermissionProfiles(\n [...systemRoles, ...customRoles],\n (permsResult.data ?? []) as Array<{ id: string; category: string }>,\n (rolePermsResult.data ?? []) as Array<{ role: string; permission_id: string }>,\n (overridesResult.data ?? []) as Array<{ role: string; permission_id: string; granted: boolean }>,\n )\n },\n\n async createProfile(\n orgId: string,\n profile: Omit<PermissionProfile, 'id' | 'isSystem'>,\n ): Promise<PermissionProfile> {\n // Custom roles live in tenant_roles (identity/name) + tenant_role_overrides\n // (their grants). System roles stay app-defined and untouched.\n const existing = new Set(\n ((await core().from('tenant_roles').select('key').eq('tenant_id', orgId)).data ?? [])\n .map((r: { key: string }) => r.key),\n )\n let key = slugifyRole(profile.name)\n if (existing.has(key) || roles.some((r) => r.id === key)) {\n let n = 2\n while (existing.has(`${key}-${n}`) || roles.some((r) => r.id === `${key}-${n}`)) n++\n key = `${key}-${n}`\n }\n\n const insertRole = await core()\n .from('tenant_roles')\n .insert({ tenant_id: orgId, key, name: profile.name, description: profile.description ?? null })\n if (insertRole.error) throw insertRole.error\n\n const overrides = Object.entries(profile.grants ?? {}).flatMap(([category, actions]) =>\n actions.map((action) => ({\n tenant_id: orgId,\n role: key,\n permission_id: `${category}.${DB_ACTION[action] ?? action}`,\n granted: true,\n })),\n )\n if (overrides.length > 0) {\n const { error } = await core().from('tenant_role_overrides').insert(overrides)\n if (error) throw error\n }\n\n const profiles = await this.listProfiles(orgId)\n return profiles.find((p) => p.id === key) ?? {\n id: key, name: profile.name, description: profile.description, isSystem: false,\n systemPermissions: profile.systemPermissions ?? [], grants: profile.grants ?? {},\n }\n },\n\n async updateProfile(\n orgId: string,\n profileId: string,\n data: Partial<PermissionProfile>,\n ): Promise<PermissionProfile> {\n // Identity lives in tenant_roles, grants in tenant_role_overrides. Only\n // the grants half used to be written, so renaming a custom profile — from\n // the matrix editor or from the assistant — silently did nothing.\n if (data.name !== undefined || data.description !== undefined) {\n const patch: Record<string, unknown> = {}\n if (data.name !== undefined) patch.name = data.name\n if (data.description !== undefined) patch.description = data.description ?? null\n const { error } = await core()\n .from('tenant_roles')\n .update(patch)\n .eq('tenant_id', orgId)\n .eq('key', profileId)\n if (error) throw error\n }\n\n if (data.grants) {\n await core()\n .from('tenant_role_overrides')\n .delete()\n .eq('tenant_id', orgId)\n .eq('role', profileId)\n\n const overrides = Object.entries(data.grants).flatMap(([category, actions]) =>\n actions.map((action) => ({\n tenant_id: orgId,\n role: profileId,\n permission_id: `${category}.${DB_ACTION[action] ?? action}`,\n granted: true,\n })),\n )\n\n if (overrides.length > 0) {\n const { error } = await core().from('tenant_role_overrides').insert(overrides)\n if (error) throw error\n }\n }\n\n const profiles = await this.listProfiles(orgId)\n const updated = profiles.find((p) => p.id === profileId)\n if (!updated) throw new Error(`Profile not found: ${profileId}`)\n return updated\n },\n\n async deleteProfile(orgId: string, profileId: string): Promise<void> {\n // Only custom roles (present in tenant_roles) can be deleted; system roles\n // are app-defined and static.\n const found = await core()\n .from('tenant_roles')\n .select('key')\n .eq('tenant_id', orgId)\n .eq('key', profileId)\n .maybeSingle()\n if (found.error) throw found.error\n if (!found.data) throw new Error('System roles cannot be deleted.')\n\n await core().from('tenant_role_overrides').delete().eq('tenant_id', orgId).eq('role', profileId)\n const { error } = await core().from('tenant_roles').delete().eq('tenant_id', orgId).eq('key', profileId)\n if (error) throw error\n },\n\n async listInvites(orgId: string): Promise<Invite[]> {\n const { data, error } = await core()\n .from('invitations')\n .select('*')\n .eq('tenant_id', orgId)\n .order('created_at', { ascending: false })\n\n if (error) throw error\n return ((data ?? []) as Array<Record<string, unknown>>).map(mapInviteRow)\n },\n\n async createInvite(orgId: string, email: string, profileId: string, invitedBy: string): Promise<Invite> {\n const { data, error } = await core()\n .from('invitations')\n .insert({\n tenant_id: orgId,\n email,\n role: profileId,\n invited_by: invitedBy,\n })\n .select()\n .single()\n\n if (error) throw error\n // Deliver via the auth abstraction (sends the e-mail + creates the auth user,\n // stamping tenant_id/role on its metadata for the accept-time membership trigger).\n await authAdapter?.inviteUser?.(email, {\n redirectTo: inviteRedirectTo,\n data: { tenant_id: orgId, role: profileId, invited_by: invitedBy },\n })\n return mapInviteRow(data as Record<string, unknown>)\n },\n\n async bulkInvite(orgId: string, emails: string[], profileId: string, invitedBy: string): Promise<Invite[]> {\n const rows = emails.map((email) => ({\n tenant_id: orgId,\n email,\n role: profileId,\n invited_by: invitedBy,\n }))\n\n const { data, error } = await core().from('invitations').insert(rows).select()\n if (error) throw error\n await Promise.all(\n emails.map((email) =>\n authAdapter?.inviteUser?.(email, {\n redirectTo: inviteRedirectTo,\n data: { tenant_id: orgId, role: profileId, invited_by: invitedBy },\n }),\n ),\n )\n return ((data ?? []) as Array<Record<string, unknown>>).map(mapInviteRow)\n },\n\n async revokeInvite(orgId: string, inviteId: string): Promise<void> {\n const { error } = await core()\n .from('invitations')\n .update({ status: 'revoked' })\n .eq('id', inviteId)\n .eq('tenant_id', orgId)\n\n if (error) throw error\n },\n\n async resendInvite(orgId: string, inviteId: string): Promise<Invite> {\n const { data, error } = await core()\n .from('invitations')\n .update({\n status: 'pending',\n expires_at: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString(),\n })\n .eq('id', inviteId)\n .eq('tenant_id', orgId)\n .select()\n .single()\n\n if (error) throw error\n const row = data as Record<string, unknown>\n // Re-send the invite e-mail through the auth abstraction.\n await authAdapter?.inviteUser?.(row.email as string, {\n redirectTo: inviteRedirectTo,\n data: { tenant_id: orgId, role: row.role as string, invited_by: row.invited_by as string },\n })\n return mapInviteRow(row)\n },\n\n async listLocations(orgId: string): Promise<Location[]> {\n const { data, error } = await core()\n .from('locations')\n .select('*')\n .eq('tenant_id', orgId)\n .order('is_headquarters', { ascending: false })\n .order('name')\n\n if (error) throw error\n return ((data ?? []) as Array<Record<string, unknown>>).map(mapLocationRow)\n },\n\n async createLocation(\n orgId: string,\n input: {\n name: string\n address?: string\n city?: string\n state?: string\n country?: string\n phone?: string\n isHeadquarters?: boolean\n },\n ): Promise<Location> {\n const { data, error } = await core()\n .from('locations')\n .insert({\n tenant_id: orgId,\n name: input.name,\n address: input.address ?? null,\n city: input.city ?? null,\n state: input.state ?? null,\n country: input.country ?? 'BR',\n phone: input.phone ?? null,\n is_headquarters: input.isHeadquarters ?? false,\n })\n .select()\n .single()\n\n if (error) throw error\n return mapLocationRow(data as Record<string, unknown>)\n },\n }\n}\n","import type {\n OrgAdapter,\n Organization,\n OrgMember,\n OrgMembership,\n CreateOrgOptions,\n Location,\n Invite,\n} from '@fayz-ai/core'\nimport type { PermissionProfile } from '@fayz-ai/core'\n\nconst STORAGE_KEY = 'fayz:mock-orgs'\n\ninterface MockOrgData {\n orgs: Organization[]\n members: OrgMember[]\n profiles: Record<string, PermissionProfile[]>\n invites: Record<string, Invite[]>\n userOrgMap: Record<string, string[]>\n}\n\nfunction getStored(): MockOrgData {\n try {\n if (typeof localStorage === 'undefined') return empty()\n const raw = localStorage.getItem(STORAGE_KEY)\n if (raw) return JSON.parse(raw) as MockOrgData\n } catch {\n // ignore\n }\n return empty()\n}\n\nfunction empty(): MockOrgData {\n return { orgs: [], members: [], profiles: {}, invites: {}, userOrgMap: {} }\n}\n\nfunction setStored(data: MockOrgData): void {\n try {\n if (typeof localStorage === 'undefined') return\n localStorage.setItem(STORAGE_KEY, JSON.stringify(data))\n } catch {\n // ignore\n }\n}\n\nfunction slugify(name: string): string {\n return name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')\n}\n\nexport function createMockOrgAdapter(defaultProfiles?: PermissionProfile[]): OrgAdapter {\n function seedOrgForUser(userId: string, userName?: string): MockOrgData {\n const data = getStored()\n if (data.userOrgMap[userId]?.length) return data\n\n const orgId = crypto.randomUUID()\n const memberId = crypto.randomUUID()\n const firstProfile = defaultProfiles?.[0]\n\n const org: Organization = {\n id: orgId,\n name: 'My Organization',\n slug: 'my-organization',\n createdAt: new Date().toISOString(),\n updatedAt: new Date().toISOString(),\n }\n\n const member: OrgMember = {\n id: memberId,\n userId,\n orgId,\n profileId: firstProfile?.id ?? 'owner',\n profileName: firstProfile?.name ?? 'Owner',\n user: {\n id: userId,\n email: userName\n ? `${userName.toLowerCase().replace(/\\s+/g, '.')}@example.com`\n : 'user@example.com',\n fullName: userName ?? 'Current User',\n },\n joinedAt: new Date().toISOString(),\n }\n\n data.orgs.push(org)\n data.members.push(member)\n data.userOrgMap[userId] = [orgId]\n if (defaultProfiles) {\n data.profiles[orgId] = [...defaultProfiles]\n }\n data.invites[orgId] = []\n\n setStored(data)\n return data\n }\n\n return {\n async listUserOrgs(userId: string): Promise<OrgMembership[]> {\n const data = seedOrgForUser(userId)\n const orgIds = data.userOrgMap[userId] ?? []\n return orgIds.map((orgId) => {\n const org = data.orgs.find((o) => o.id === orgId)!\n const member = data.members.find((m) => m.orgId === orgId && m.userId === userId)\n return {\n orgId,\n orgName: org.name,\n orgSlug: org.slug,\n orgLogoUrl: org.logoUrl,\n profileId: member?.profileId ?? 'owner',\n profileName: member?.profileName ?? 'Owner',\n }\n })\n },\n\n async getOrg(orgId: string): Promise<Organization> {\n const data = getStored()\n const org = data.orgs.find((o) => o.id === orgId)\n if (!org) throw new Error(`Org not found: ${orgId}`)\n return org\n },\n\n async createOrg(name: string, userId: string, options?: CreateOrgOptions): Promise<Organization> {\n const data = getStored()\n const orgId = crypto.randomUUID()\n const firstProfile = defaultProfiles?.[0]\n\n const org: Organization = {\n id: orgId,\n name,\n slug: slugify(name),\n verticalId: options?.verticalId,\n plan: 'free',\n settings: {\n timezone: options?.timezone ?? 'America/Sao_Paulo',\n currency: options?.currency ?? 'BRL',\n locale: options?.locale ?? 'pt-BR',\n },\n createdAt: new Date().toISOString(),\n updatedAt: new Date().toISOString(),\n }\n\n const member: OrgMember = {\n id: crypto.randomUUID(),\n userId,\n orgId,\n profileId: firstProfile?.id ?? 'owner',\n profileName: firstProfile?.name ?? 'Owner',\n user: {\n id: userId,\n email: 'user@example.com',\n fullName: 'Current User',\n },\n joinedAt: new Date().toISOString(),\n }\n\n data.orgs.push(org)\n data.members.push(member)\n if (!data.userOrgMap[userId]) data.userOrgMap[userId] = []\n data.userOrgMap[userId].push(orgId)\n if (defaultProfiles) {\n data.profiles[orgId] = [...defaultProfiles]\n }\n data.invites[orgId] = []\n\n setStored(data)\n return org\n },\n\n async updateOrg(orgId: string, updates: Partial<Organization>): Promise<Organization> {\n const data = getStored()\n const idx = data.orgs.findIndex((o) => o.id === orgId)\n if (idx === -1) throw new Error(`Org not found: ${orgId}`)\n data.orgs[idx] = { ...data.orgs[idx], ...updates, updatedAt: new Date().toISOString() }\n setStored(data)\n return data.orgs[idx]\n },\n\n async listMembers(orgId: string): Promise<OrgMember[]> {\n const data = getStored()\n return data.members.filter((m) => m.orgId === orgId)\n },\n\n async updateMemberProfile(orgId: string, memberId: string, profileId: string): Promise<void> {\n const data = getStored()\n const member = data.members.find((m) => m.id === memberId && m.orgId === orgId)\n if (!member) throw new Error(`Member not found: ${memberId}`)\n const profiles = data.profiles[orgId] ?? []\n const profile = profiles.find((p) => p.id === profileId)\n member.profileId = profileId\n member.profileName = profile?.name ?? profileId\n setStored(data)\n },\n\n async removeMember(orgId: string, memberId: string): Promise<void> {\n const data = getStored()\n const memberIdx = data.members.findIndex((m) => m.id === memberId && m.orgId === orgId)\n if (memberIdx === -1) return\n const member = data.members[memberIdx]\n data.members.splice(memberIdx, 1)\n const userOrgs = data.userOrgMap[member.userId]\n if (userOrgs) {\n const orgIdx = userOrgs.indexOf(orgId)\n if (orgIdx !== -1) userOrgs.splice(orgIdx, 1)\n }\n setStored(data)\n },\n\n async listProfiles(orgId: string): Promise<PermissionProfile[]> {\n const data = getStored()\n return data.profiles[orgId] ?? defaultProfiles ?? []\n },\n\n async createProfile(\n orgId: string,\n profile: Omit<PermissionProfile, 'id' | 'isSystem'>,\n ): Promise<PermissionProfile> {\n const data = getStored()\n const newProfile: PermissionProfile = {\n ...profile,\n id: crypto.randomUUID(),\n isSystem: false,\n }\n if (!data.profiles[orgId]) {\n data.profiles[orgId] = defaultProfiles ? [...defaultProfiles] : []\n }\n data.profiles[orgId].push(newProfile)\n setStored(data)\n return newProfile\n },\n\n async updateProfile(\n orgId: string,\n profileId: string,\n updates: Partial<PermissionProfile>,\n ): Promise<PermissionProfile> {\n const data = getStored()\n const profiles = data.profiles[orgId] ?? []\n const idx = profiles.findIndex((p) => p.id === profileId)\n if (idx === -1) throw new Error(`Profile not found: ${profileId}`)\n profiles[idx] = { ...profiles[idx], ...updates }\n data.profiles[orgId] = profiles\n setStored(data)\n return profiles[idx]\n },\n\n async deleteProfile(orgId: string, profileId: string): Promise<void> {\n const data = getStored()\n const profiles = data.profiles[orgId] ?? []\n const profile = profiles.find((p) => p.id === profileId)\n if (profile?.isSystem) throw new Error('Cannot delete system profile')\n data.profiles[orgId] = profiles.filter((p) => p.id !== profileId)\n setStored(data)\n },\n\n async listInvites(orgId: string): Promise<Invite[]> {\n const data = getStored()\n return data.invites[orgId] ?? []\n },\n\n async createInvite(\n orgId: string,\n email: string,\n profileId: string,\n invitedBy: string,\n ): Promise<Invite> {\n const data = getStored()\n const profiles = data.profiles[orgId] ?? defaultProfiles ?? []\n const profile = profiles.find((p) => p.id === profileId)\n\n const invite: Invite = {\n id: crypto.randomUUID(),\n orgId,\n email,\n profileId,\n profileName: profile?.name ?? profileId,\n invitedBy,\n token: crypto.randomUUID(),\n status: 'pending',\n createdAt: new Date().toISOString(),\n expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString(),\n }\n\n if (!data.invites[orgId]) data.invites[orgId] = []\n data.invites[orgId].push(invite)\n setStored(data)\n return invite\n },\n\n async bulkInvite(\n orgId: string,\n emails: string[],\n profileId: string,\n invitedBy: string,\n ): Promise<Invite[]> {\n const results: Invite[] = []\n for (const email of emails) {\n results.push(await this.createInvite(orgId, email, profileId, invitedBy))\n }\n return results\n },\n\n async revokeInvite(orgId: string, inviteId: string): Promise<void> {\n const data = getStored()\n const invites = data.invites[orgId] ?? []\n const invite = invites.find((i) => i.id === inviteId)\n if (invite) {\n invite.status = 'expired'\n setStored(data)\n }\n },\n\n async resendInvite(orgId: string, inviteId: string): Promise<Invite> {\n const data = getStored()\n const invites = data.invites[orgId] ?? []\n const invite = invites.find((i) => i.id === inviteId)\n if (!invite) throw new Error(`Invite not found: ${inviteId}`)\n invite.expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString()\n invite.status = 'pending'\n setStored(data)\n return invite\n },\n\n async listLocations(_orgId: string): Promise<Location[]> {\n return []\n },\n\n async createLocation(\n orgId: string,\n input: {\n name: string\n address?: string\n city?: string\n state?: string\n country?: string\n phone?: string\n isHeadquarters?: boolean\n },\n ): Promise<Location> {\n return {\n id: crypto.randomUUID(),\n tenantId: orgId,\n name: input.name,\n address: input.address,\n city: input.city,\n state: input.state,\n country: input.country ?? 'BR',\n phone: input.phone,\n isHeadquarters: input.isHeadquarters ?? false,\n isActive: true,\n createdAt: new Date().toISOString(),\n updatedAt: new Date().toISOString(),\n }\n },\n }\n}\n"]}
|
|
@@ -1,53 +1,11 @@
|
|
|
1
1
|
import { usePermissionsStore } from './chunk-VTEP2AQX.js';
|
|
2
|
-
import {
|
|
3
|
-
import { setActiveTenantId } from '@fayz-ai/core';
|
|
2
|
+
import { useOrganizationStore, getPersistedOrgId } from './chunk-7DFJEXCR.js';
|
|
4
3
|
import * as React from 'react';
|
|
5
4
|
import { useAuthStore } from '@fayz-ai/auth';
|
|
6
5
|
import { jsx } from 'react/jsx-runtime';
|
|
7
6
|
|
|
8
|
-
var STORAGE_KEY = "fayz:current-org";
|
|
9
|
-
function getPersistedOrgId() {
|
|
10
|
-
try {
|
|
11
|
-
if (typeof localStorage === "undefined") return null;
|
|
12
|
-
return localStorage.getItem(STORAGE_KEY);
|
|
13
|
-
} catch {
|
|
14
|
-
return null;
|
|
15
|
-
}
|
|
16
|
-
}
|
|
17
|
-
function persistOrgId(orgId) {
|
|
18
|
-
try {
|
|
19
|
-
if (typeof localStorage === "undefined") return;
|
|
20
|
-
if (orgId) {
|
|
21
|
-
localStorage.setItem(STORAGE_KEY, orgId);
|
|
22
|
-
} else {
|
|
23
|
-
localStorage.removeItem(STORAGE_KEY);
|
|
24
|
-
}
|
|
25
|
-
} catch {
|
|
26
|
-
}
|
|
27
|
-
}
|
|
28
|
-
var useOrganizationStore = create((set) => ({
|
|
29
|
-
currentOrg: null,
|
|
30
|
-
userOrgs: [],
|
|
31
|
-
members: [],
|
|
32
|
-
teamPersonKinds: [],
|
|
33
|
-
loading: false,
|
|
34
|
-
setCurrentOrg: (org) => {
|
|
35
|
-
setActiveTenantId(org?.id);
|
|
36
|
-
persistOrgId(org?.id ?? null);
|
|
37
|
-
set({ currentOrg: org });
|
|
38
|
-
},
|
|
39
|
-
setUserOrgs: (orgs) => set({ userOrgs: orgs }),
|
|
40
|
-
setMembers: (members) => set({ members }),
|
|
41
|
-
setTeamPersonKinds: (kinds) => set({ teamPersonKinds: kinds }),
|
|
42
|
-
setLoading: (loading) => set({ loading }),
|
|
43
|
-
reset: () => {
|
|
44
|
-
setActiveTenantId(void 0);
|
|
45
|
-
set({ currentOrg: null, userOrgs: [], members: [], loading: false });
|
|
46
|
-
}
|
|
47
|
-
}));
|
|
48
|
-
|
|
49
7
|
// src/org/cache.ts
|
|
50
|
-
var
|
|
8
|
+
var STORAGE_KEY = "fayz:org-snapshot";
|
|
51
9
|
var VERSION = 1;
|
|
52
10
|
var ORG_CACHE_TTL_MS = 5 * 60 * 1e3;
|
|
53
11
|
var MAX_AGE_MS = 24 * 60 * 60 * 1e3;
|
|
@@ -64,12 +22,12 @@ function readOrgSnapshot() {
|
|
|
64
22
|
const store = storage();
|
|
65
23
|
if (!store) return null;
|
|
66
24
|
try {
|
|
67
|
-
const raw = store.getItem(
|
|
25
|
+
const raw = store.getItem(STORAGE_KEY);
|
|
68
26
|
if (!raw) return null;
|
|
69
27
|
const snapshot = JSON.parse(raw);
|
|
70
28
|
if (snapshot?.version !== VERSION || !snapshot.org?.id || !snapshot.userId) return null;
|
|
71
29
|
if (snapshotAge(snapshot) > MAX_AGE_MS) {
|
|
72
|
-
store.removeItem(
|
|
30
|
+
store.removeItem(STORAGE_KEY);
|
|
73
31
|
return null;
|
|
74
32
|
}
|
|
75
33
|
return snapshot;
|
|
@@ -94,7 +52,7 @@ function patchOrgSnapshot(input) {
|
|
|
94
52
|
}
|
|
95
53
|
function clearOrgSnapshot() {
|
|
96
54
|
try {
|
|
97
|
-
storage()?.removeItem(
|
|
55
|
+
storage()?.removeItem(STORAGE_KEY);
|
|
98
56
|
} catch {
|
|
99
57
|
}
|
|
100
58
|
}
|
|
@@ -104,7 +62,7 @@ function write(snapshot) {
|
|
|
104
62
|
try {
|
|
105
63
|
const raw = JSON.stringify(snapshot);
|
|
106
64
|
if (raw.length > MAX_BYTES) return;
|
|
107
|
-
store.setItem(
|
|
65
|
+
store.setItem(STORAGE_KEY, raw);
|
|
108
66
|
} catch {
|
|
109
67
|
}
|
|
110
68
|
}
|
|
@@ -320,6 +278,6 @@ function OrgProvider({
|
|
|
320
278
|
return /* @__PURE__ */ jsx(OrgAdapterContext.Provider, { value: adapter, children: /* @__PURE__ */ jsx(TenantContext.Provider, { value: tenantValue, children }) });
|
|
321
279
|
}
|
|
322
280
|
|
|
323
|
-
export { ORG_CACHE_TTL_MS, OrgProvider, clearOrgSnapshot,
|
|
324
|
-
//# sourceMappingURL=chunk-
|
|
325
|
-
//# sourceMappingURL=chunk-
|
|
281
|
+
export { ORG_CACHE_TTL_MS, OrgProvider, clearOrgSnapshot, readOrgSnapshot, useOrgAdapter, useOrgAdapterOptional, useTenant, useTenantOptional };
|
|
282
|
+
//# sourceMappingURL=chunk-WN6PGQSG.js.map
|
|
283
|
+
//# sourceMappingURL=chunk-WN6PGQSG.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/org/cache.ts","../src/org/context.tsx"],"names":[],"mappings":";;;;;;;AAaA,IAAM,WAAA,GAAc,mBAAA;AACpB,IAAM,OAAA,GAAU,CAAA;AAGT,IAAM,gBAAA,GAAmB,IAAI,EAAA,GAAK;AAEzC,IAAM,UAAA,GAAa,EAAA,GAAK,EAAA,GAAK,EAAA,GAAK,GAAA;AAElC,IAAM,YAAY,GAAA,GAAM,IAAA;AAiBxB,SAAS,OAAA,GAA0B;AACjC,EAAA,IAAI;AACF,IAAA,IAAI,OAAO,YAAA,KAAiB,WAAA,EAAa,OAAO,IAAA;AAChD,IAAA,OAAO,YAAA;AAAA,EACT,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,IAAA;AAAA,EACT;AACF;AAEO,SAAS,eAAA,GAAsC;AACpD,EAAA,MAAM,QAAQ,OAAA,EAAQ;AACtB,EAAA,IAAI,CAAC,OAAO,OAAO,IAAA;AACnB,EAAA,IAAI;AACF,IAAA,MAAM,GAAA,GAAM,KAAA,CAAM,OAAA,CAAQ,WAAW,CAAA;AACrC,IAAA,IAAI,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AAA,IACA;AAAA,GACF;AAEA,EAAA,uBACE,GAAA,CAAC,iBAAA,CAAkB,QAAA,EAAlB,EAA2B,KAAA,EAAO,OAAA,EACjC,QAAA,kBAAA,GAAA,CAAC,aAAA,CAAc,QAAA,EAAd,EAAuB,KAAA,EAAO,WAAA,EAC5B,UACH,CAAA,EACF,CAAA;AAEJ","file":"chunk-WN6PGQSG.js","sourcesContent":["import type { Organization, OrgMember, OrgMembership, PermissionProfile } from '@fayz-ai/core'\n\n/**\n * Snapshot of the org bootstrap (org + memberships + members + permission\n * profiles) so a page reload doesn't wait on the whole chain again.\n *\n * Every mount used to pay `acceptPendingInvites → listUserOrgs → getOrg →\n * listMembers + listProfiles` before `org.id` existed, and every screen keyed\n * off the tenant (Conectores, plugin tabs, permission gates) sat idle until\n * then. The snapshot paints that state synchronously and the network is only\n * touched again once it goes stale.\n */\n\nconst STORAGE_KEY = 'fayz:org-snapshot'\nconst VERSION = 1\n\n/** Served without touching the network. */\nexport const ORG_CACHE_TTL_MS = 5 * 60 * 1000\n/** Older than this and the snapshot is dropped instead of painted. */\nconst MAX_AGE_MS = 24 * 60 * 60 * 1000\n/** Bigger than this (huge member lists) and we skip persisting rather than blow the quota. */\nconst MAX_BYTES = 512 * 1024\n\nexport interface OrgSnapshot {\n version: number\n /** Who the snapshot belongs to — a different user gets a cold load. */\n userId: string\n /** When the data last came from the server (store patches don't move it). */\n savedAt: number\n org: Organization\n userOrgs: OrgMembership[]\n members: OrgMember[]\n profiles: PermissionProfile[]\n currentProfileId: string | null\n}\n\nexport type OrgSnapshotInput = Omit<OrgSnapshot, 'version' | 'savedAt'>\n\nfunction storage(): Storage | null {\n try {\n if (typeof localStorage === 'undefined') return null\n return localStorage\n } catch {\n return null\n }\n}\n\nexport function readOrgSnapshot(): OrgSnapshot | null {\n const store = storage()\n if (!store) return null\n try {\n const raw = store.getItem(STORAGE_KEY)\n if (!raw) return null\n const snapshot = JSON.parse(raw) as OrgSnapshot\n if (snapshot?.version !== VERSION || !snapshot.org?.id || !snapshot.userId) return null\n if (snapshotAge(snapshot) > MAX_AGE_MS) {\n store.removeItem(STORAGE_KEY)\n return null\n }\n return snapshot\n } catch {\n return null\n }\n}\n\nexport function snapshotAge(snapshot: OrgSnapshot): number {\n const age = Date.now() - snapshot.savedAt\n // A clock that moved backwards shouldn't hand out an eternally fresh cache.\n return age < 0 ? Number.POSITIVE_INFINITY : age\n}\n\nexport function isSnapshotFresh(snapshot: OrgSnapshot, ttlMs: number): boolean {\n return snapshotAge(snapshot) < ttlMs\n}\n\n/** Record a fresh server read — restarts the TTL window. */\nexport function saveOrgSnapshot(input: OrgSnapshotInput): void {\n write({ ...input, version: VERSION, savedAt: Date.now() })\n}\n\n/**\n * Keep the snapshot in step with store writes made outside the provider\n * (renaming the org in Settings, editing a role) WITHOUT restarting the TTL —\n * otherwise a UI-only change would push the next revalidation out forever.\n */\nexport function patchOrgSnapshot(input: OrgSnapshotInput): void {\n const current = readOrgSnapshot()\n if (!current || current.userId !== input.userId) return\n write({ ...input, version: VERSION, savedAt: current.savedAt })\n}\n\nexport function clearOrgSnapshot(): void {\n try {\n storage()?.removeItem(STORAGE_KEY)\n } catch {\n // ignore\n }\n}\n\nfunction write(snapshot: OrgSnapshot): void {\n const store = storage()\n if (!store) return\n try {\n const raw = JSON.stringify(snapshot)\n if (raw.length > MAX_BYTES) return\n store.setItem(STORAGE_KEY, raw)\n } catch {\n // Quota or serialization failure — the cache is an optimization, not state.\n }\n}\n","import * as React from 'react'\nimport type { OrgAdapter, Organization, OrgMembership } from '@fayz-ai/core'\nimport { useAuthStore } from '@fayz-ai/auth'\nimport { useOrganizationStore, getPersistedOrgId } from './store'\nimport { usePermissionsStore } from '../permissions'\nimport {\n ORG_CACHE_TTL_MS,\n clearOrgSnapshot,\n isSnapshotFresh,\n patchOrgSnapshot,\n readOrgSnapshot,\n saveOrgSnapshot,\n type OrgSnapshot,\n} from './cache'\n\n// ---------------------------------------------------------------------------\n// Adapter context\n// ---------------------------------------------------------------------------\n\nconst OrgAdapterContext = React.createContext<OrgAdapter | null>(null)\n\nexport function useOrgAdapter(): OrgAdapter {\n const adapter = React.useContext(OrgAdapterContext)\n if (!adapter) {\n throw new Error('useOrgAdapter must be used within an <OrgProvider>')\n }\n return adapter\n}\n\nexport function useOrgAdapterOptional(): OrgAdapter | null {\n return React.useContext(OrgAdapterContext)\n}\n\n// ---------------------------------------------------------------------------\n// Tenant / org hook\n// ---------------------------------------------------------------------------\n\nexport interface TenantContext {\n /** The currently active organization */\n org: Organization | null\n /** All orgs the current user belongs to */\n userOrgs: OrgMembership[]\n loading: boolean\n /**\n * The bootstrap has finished at least once, so `org === null` now MEANS\n * \"belongs to no workspace\" instead of \"we have not looked yet\".\n *\n * `loading` cannot answer that: it starts `false`, before the effect that\n * loads anything has run. Anything deciding what to render from an empty org\n * — the setup gate — reads this, or it decides during the gap and flips its\n * mind a frame later.\n */\n settled: boolean\n /** Switch the active org */\n switchOrg: (orgId: string) => Promise<void>\n /** Refresh the current org from the adapter */\n refreshOrg: () => Promise<void>\n}\n\nconst TenantContext = React.createContext<TenantContext | null>(null)\n\n/**\n * Access the current tenant / organization.\n * Must be used inside <OrgProvider>.\n */\nexport function useTenant(): TenantContext {\n const ctx = React.useContext(TenantContext)\n if (!ctx) {\n throw new Error('useTenant must be used inside <OrgProvider>')\n }\n return ctx\n}\n\nexport function useTenantOptional(): TenantContext | null {\n return React.useContext(TenantContext)\n}\n\n// ---------------------------------------------------------------------------\n// Provider\n// ---------------------------------------------------------------------------\n\nexport interface OrgProviderProps {\n adapter: OrgAdapter\n /** When true, automatically creates an org if the user has none */\n autoCreate?: boolean\n /**\n * How long the cached org bootstrap is served before the provider goes back\n * to the network (default 5 min). A cached load paints synchronously, so\n * screens that key off `org.id` don't wait a round trip on every reload.\n * `0` disables the cache and restores the always-fetch behaviour.\n */\n cacheTtlMs?: number\n children: React.ReactNode\n}\n\nconst useIsomorphicLayoutEffect =\n typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect\n\nexport function OrgProvider({\n adapter,\n autoCreate = false,\n cacheTtlMs = ORG_CACHE_TTL_MS,\n children,\n}: OrgProviderProps) {\n const { user, isLoading: authLoading } = useAuthStore()\n const { currentOrg, userOrgs, loading, setCurrentOrg, setUserOrgs, setMembers, setLoading, reset } =\n useOrganizationStore()\n const setProfiles = usePermissionsStore((s) => s.setProfiles)\n const setCurrentProfile = usePermissionsStore((s) => s.setCurrentProfile)\n\n const adapterRef = React.useRef(adapter)\n adapterRef.current = adapter\n\n const [snapshot] = React.useState<OrgSnapshot | null>(() =>\n cacheTtlMs > 0 ? readOrgSnapshot() : null,\n )\n // One load per signed-in user per mount — auth reports `isLoading` and `user`\n // in two separate store writes, so the effect would otherwise fire twice.\n const loadedForRef = React.useRef<string | null>(null)\n\n // WHOSE bootstrap has finished, not whether one has. A boolean could not tell\n // the difference between \"we know this account has no workspace\" and \"we knew\n // that about the account that just signed out\" — which is what flashed the\n // setup flow over every login: sign-out settled it, and sign-in kept the\n // stale `true` for the whole round trip.\n //\n // A painted snapshot is already an answer for its own user: that account HAS a\n // workspace, and revalidation will not turn that into \"has none\".\n const [settledFor, setSettledFor] = React.useState<string | null>(() =>\n snapshot?.org ? snapshot.userId : null,\n )\n // Signed out there is nothing to wait for; signed in, only this user's answer counts.\n const settled = user ? settledFor === user.id : !authLoading\n\n // Paint the last known org before the first child renders. The stores are\n // filled in a layout effect, so nothing gets a frame with `org === null`.\n useIsomorphicLayoutEffect(() => {\n if (!snapshot) return\n setUserOrgs(snapshot.userOrgs)\n setCurrentOrg(snapshot.org)\n setMembers(snapshot.members)\n setProfiles(snapshot.profiles)\n setCurrentProfile(snapshot.profiles.find((p) => p.id === snapshot.currentProfileId) ?? null)\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [])\n\n // Keep the snapshot in step with store writes made outside this provider —\n // renaming the org in Settings, editing a role — so the cache never serves a\n // value the user already changed on screen. Patching leaves `savedAt` alone:\n // a UI-only edit must not push the next revalidation further out.\n React.useEffect(() => {\n if (cacheTtlMs <= 0 || !user) return\n const uid = user.id\n const sync = () => {\n const org = useOrganizationStore.getState()\n if (!org.currentOrg) return\n const perms = usePermissionsStore.getState()\n patchOrgSnapshot({\n userId: uid,\n org: org.currentOrg,\n userOrgs: org.userOrgs,\n members: org.members,\n profiles: perms.profiles,\n // realProfile, not currentProfile: an impersonation preview is not\n // something to cache back as the user's own role.\n currentProfileId: perms.realProfile?.id ?? null,\n })\n }\n const unsubscribeOrg = useOrganizationStore.subscribe(sync)\n const unsubscribePerms = usePermissionsStore.subscribe(sync)\n return () => {\n unsubscribeOrg()\n unsubscribePerms()\n }\n }, [user?.id, cacheTtlMs])\n\n // Load the org's members + permission profiles into the shared stores whenever\n // an org resolves. This is what makes the role list, the invite dialog's role\n // dropdown, and permission checks work — previously nothing loaded them here,\n // so those surfaces came up empty. Also resolves the signed-in user's own role.\n const hydrateOrg = React.useCallback(\n async (org: Organization, memberships: OrgMembership[], uid: string | undefined) => {\n try {\n const [members, profiles] = await Promise.all([\n adapterRef.current.listMembers(org.id),\n adapterRef.current.listProfiles(org.id),\n ])\n setMembers(members)\n setProfiles(profiles)\n const myMembership = uid ? members.find((m) => m.userId === uid) : undefined\n const profile = profiles.find((p) => p.id === myMembership?.profileId) ?? null\n setCurrentProfile(profile)\n // Everything the next reload needs, stamped now — this is the only\n // place the TTL window restarts.\n if (cacheTtlMs > 0 && uid) {\n saveOrgSnapshot({\n userId: uid,\n org,\n userOrgs: memberships,\n members,\n profiles,\n currentProfileId: profile?.id ?? null,\n })\n }\n } catch {\n // Non-fatal — leave stores as-is if the load fails.\n }\n },\n [setMembers, setProfiles, setCurrentProfile, cacheTtlMs],\n )\n\n // Load orgs when user is authenticated\n React.useEffect(() => {\n if (!user) {\n // A cold load reports `user === null` while the session hydrates — that's\n // not a sign-out, so the painted snapshot stands until auth settles.\n if (authLoading) return\n loadedForRef.current = null\n reset()\n clearOrgSnapshot()\n setSettledFor(null)\n return\n }\n\n const cached = snapshot?.userId === user.id ? snapshot : null\n\n // Already painted and still inside its window: skip the whole bootstrap.\n if (cached && isSnapshotFresh(cached, cacheTtlMs)) { setSettledFor(user.id); return }\n\n // A snapshot from another account was painted — drop it before loading.\n if (snapshot && snapshot.userId !== user.id && loadedForRef.current === null) {\n reset()\n clearOrgSnapshot()\n }\n\n if (loadedForRef.current === user.id) return\n loadedForRef.current = user.id\n\n // Stale but painted: revalidate quietly, so screens keep the data they're\n // showing instead of flipping back to a skeleton.\n const silent = !!cached\n\n let cancelled = false\n\n async function loadOrgs() {\n if (!silent) setLoading(true)\n try {\n // Redeem invites first — an invitee has no membership until this runs,\n // and without it autoCreate below would hand them a personal org\n // instead of the one that invited them.\n let accepted = 0\n try {\n accepted = (await adapterRef.current.acceptPendingInvites?.()) ?? 0\n } catch {\n // Non-fatal: fall through and load whatever memberships exist.\n }\n\n if (cancelled) return\n\n let memberships = await adapterRef.current.listUserOrgs(user!.id)\n\n // An empty list right after accepting means the read was deduped onto a\n // request that started before the invite landed. Ask once more.\n if (memberships.length === 0 && accepted > 0) {\n memberships = await adapterRef.current.listUserOrgs(user!.id)\n }\n\n if (cancelled) return\n\n setUserOrgs(memberships)\n\n // Auto-create org if user has none\n if (memberships.length === 0 && accepted === 0 && autoCreate) {\n const newOrg = await adapterRef.current.createOrg(\n user!.fullName ? `${user!.fullName}'s Organization` : 'My Organization',\n user!.id,\n )\n if (!cancelled) {\n const ownMembership: OrgMembership[] = [\n {\n orgId: newOrg.id,\n orgName: newOrg.name,\n orgSlug: newOrg.slug,\n profileId: 'owner',\n profileName: 'Owner',\n },\n ]\n setUserOrgs(ownMembership)\n setCurrentOrg(newOrg)\n await hydrateOrg(newOrg, ownMembership, user!.id)\n }\n return\n }\n\n // Restore previously selected org or default to first\n const persistedId = getPersistedOrgId()\n const target =\n memberships.find((m) => m.orgId === persistedId) ?? memberships[0]\n\n if (target && !cancelled) {\n const org = await adapterRef.current.getOrg(target.orgId)\n if (!cancelled) {\n setCurrentOrg(org)\n await hydrateOrg(org, memberships, user!.id)\n }\n }\n } finally {\n if (!cancelled && !silent) setLoading(false)\n // Settled even when the load threw: the answer is then \"we asked and\n // could not tell\", and holding the screen forever is worse than showing\n // the app. It is about the wait being over, not about success.\n if (!cancelled) setSettledFor(user!.id)\n }\n }\n\n void loadOrgs()\n\n return () => {\n cancelled = true\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [user?.id, authLoading])\n\n async function switchOrg(orgId: string): Promise<void> {\n setLoading(true)\n try {\n const org = await adapterRef.current.getOrg(orgId)\n setCurrentOrg(org)\n await hydrateOrg(org, useOrganizationStore.getState().userOrgs, user?.id)\n } finally {\n setLoading(false)\n }\n }\n\n // Explicit refresh always goes to the network and restarts the cache window.\n async function refreshOrg(): Promise<void> {\n if (!currentOrg) return\n setLoading(true)\n try {\n const org = await adapterRef.current.getOrg(currentOrg.id)\n setCurrentOrg(org)\n await hydrateOrg(org, useOrganizationStore.getState().userOrgs, user?.id)\n } finally {\n setLoading(false)\n }\n }\n\n const tenantValue: TenantContext = {\n org: currentOrg,\n userOrgs,\n loading,\n settled,\n switchOrg,\n refreshOrg,\n }\n\n return (\n <OrgAdapterContext.Provider value={adapter}>\n <TenantContext.Provider value={tenantValue}>\n {children}\n </TenantContext.Provider>\n </OrgAdapterContext.Provider>\n )\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SoftLimitBanner.d.ts","sourceRoot":"","sources":["../../../src/components/billing/SoftLimitBanner.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;
|
|
1
|
+
{"version":3,"file":"SoftLimitBanner.d.ts","sourceRoot":"","sources":["../../../src/components/billing/SoftLimitBanner.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAsF9B,wBAAgB,eAAe,CAAC,EAAE,IAAI,EAAE,EAAE;IAAE,IAAI,EAAE,MAAM,EAAE,CAAA;CAAE,qBAuI3D"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ChatFab.d.ts","sourceRoot":"","sources":["../../../src/components/chat/ChatFab.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAe9B,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,sBAAsB,CAAA;AACrE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAA;AAEvD,UAAU,YAAY;IACpB,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,KAAK,CAAC,EAAE,yBAAyB,GAAG,KAAK,CAAA;IACzC,KAAK,CAAC,EAAE,eAAe,CAAA;CAIxB;AA2HD,wBAAgB,OAAO,CAAC,EAAE,SAAS,EAAE,WAAW,EAAE,YAAY,EAAE,KAAK,EAAE,KAAK,EAAE,EAAE,YAAY,
|
|
1
|
+
{"version":3,"file":"ChatFab.d.ts","sourceRoot":"","sources":["../../../src/components/chat/ChatFab.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAe9B,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,sBAAsB,CAAA;AACrE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAA;AAEvD,UAAU,YAAY;IACpB,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,KAAK,CAAC,EAAE,yBAAyB,GAAG,KAAK,CAAA;IACzC,KAAK,CAAC,EAAE,eAAe,CAAA;CAIxB;AA2HD,wBAAgB,OAAO,CAAC,EAAE,SAAS,EAAE,WAAW,EAAE,YAAY,EAAE,KAAK,EAAE,KAAK,EAAE,EAAE,YAAY,4BAoY3F"}
|
|
@@ -15,6 +15,13 @@ export interface CrudSurfaceInput {
|
|
|
15
15
|
instructions?: string;
|
|
16
16
|
/** Field keys whose values must not repeat. */
|
|
17
17
|
uniqueFields?: string[];
|
|
18
|
+
/**
|
|
19
|
+
* Where the record just written can be opened. Supplied by the page, because
|
|
20
|
+
* this kind of entity has no archetype and no table — the chat's route map
|
|
21
|
+
* has nothing to derive a destination from, and a reply about a record you
|
|
22
|
+
* cannot click through to is a dead end.
|
|
23
|
+
*/
|
|
24
|
+
recordPath?: (id: string) => string;
|
|
18
25
|
}
|
|
19
26
|
/**
|
|
20
27
|
* The contribution itself, built from a GETTER so the component can re-render
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CrudAgentSurface.d.ts","sourceRoot":"","sources":["../../src/crud/CrudAgentSurface.tsx"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAgB,MAAM,eAAe,CAAA;AAG5D,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,sBAAsB,CAAA;AAoEpE,UAAU,aAAa;IACrB,MAAM,EAAE,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,OAAO,CAAC;QAAE,EAAE,EAAE,MAAM,CAAA;KAAE,CAAC,CAAA;IAClE;8DAC0D;IAC1D,KAAK,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,GAAG,IAAI,CAAA;CAC9C;AAoBD,MAAM,WAAW,gBAAgB;IAC/B,SAAS,EAAE,SAAS,CAAC,GAAG,CAAC,CAAA;IACzB,KAAK,EAAE,aAAa,CAAA;IACpB,6DAA6D;IAC7D,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,+CAA+C;IAC/C,YAAY,CAAC,EAAE,MAAM,EAAE,CAAA;
|
|
1
|
+
{"version":3,"file":"CrudAgentSurface.d.ts","sourceRoot":"","sources":["../../src/crud/CrudAgentSurface.tsx"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAgB,MA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BAAgB,oBAAoB,SA2FnC"}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import * as React from 'react';
|
|
2
|
+
/**
|
|
3
|
+
* Loads the notebook for the active workspace and puts it in front of both
|
|
4
|
+
* readers: the rail tab and the assistant. Mounted once by the provider stack.
|
|
5
|
+
*/
|
|
6
|
+
export declare function HandbookProvider(): React.JSX.Element;
|
|
7
|
+
//# sourceMappingURL=HandbookProvider.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"HandbookProvider.d.ts","sourceRoot":"","sources":["../../src/handbook/HandbookProvider.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAQ9B;;;GAGG;AACH,wBAAgB,gBAAgB,sBAgB/B"}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import * as React from 'react';
|
|
2
|
+
export declare function NotebookPanel(): React.JSX.Element;
|
|
3
|
+
/** Registers the notebook as the rail's "Notas" tab. Renders nothing itself. */
|
|
4
|
+
export declare function NotebookRailPanel(): null;
|
|
5
|
+
//# sourceMappingURL=NotebookPanel.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"NotebookPanel.d.ts","sourceRoot":"","sources":["../../src/handbook/NotebookPanel.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAsE9B,wBAAgB,aAAa,sBAiM5B;AAohBD,gFAAgF;AAChF,wBAAgB,iBAAiB,SAiBhC"}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { type HandbookEntry, type HandbookPage, type WriteHandbookInput } from './types';
|
|
2
|
+
/**
|
|
3
|
+
* Everything this person can see, bodies included.
|
|
4
|
+
*
|
|
5
|
+
* The bodies come along on purpose: a notebook is a few dozen short markdown
|
|
6
|
+
* pages, the list needs a snippet from each of them anyway, and one round trip
|
|
7
|
+
* that answers every later question beats a second one per page opened. RLS is
|
|
8
|
+
* what keeps somebody else's private notes out of the answer.
|
|
9
|
+
*/
|
|
10
|
+
export declare function listHandbook(tenantId: string): Promise<HandbookPage[]>;
|
|
11
|
+
/** The tree rows, for whoever wants titles without bodies. */
|
|
12
|
+
export declare function toEntries(pages: HandbookPage[]): HandbookEntry[];
|
|
13
|
+
export declare function readHandbookPage(tenantId: string, path: string): Promise<HandbookPage | null>;
|
|
14
|
+
/**
|
|
15
|
+
* Save one page — by id when we have one, by path when we do not.
|
|
16
|
+
*
|
|
17
|
+
* The path upsert is what makes the assistant's writes safe: "is there already
|
|
18
|
+
* a page about delivery?" is a decision it would have to take on every write,
|
|
19
|
+
* and would take wrongly. A loose note has no path, so it is identified by id
|
|
20
|
+
* like any other row.
|
|
21
|
+
*/
|
|
22
|
+
export declare function writeHandbookPage(tenantId: string, userId: string | undefined, input: WriteHandbookInput): Promise<HandbookPage | null>;
|
|
23
|
+
/**
|
|
24
|
+
* Add to a page without rewriting it.
|
|
25
|
+
*
|
|
26
|
+
* The important half of the contract. The assistant learns one fact at a time;
|
|
27
|
+
* asking it to restate a whole page to add a line is how paragraphs quietly
|
|
28
|
+
* disappear. A missing page is created, so "append" is always safe to call.
|
|
29
|
+
*/
|
|
30
|
+
export declare function appendHandbookPage(tenantId: string, userId: string | undefined, input: {
|
|
31
|
+
path: string;
|
|
32
|
+
text: string;
|
|
33
|
+
heading?: string;
|
|
34
|
+
title?: string;
|
|
35
|
+
}): Promise<HandbookPage | null>;
|
|
36
|
+
/** Title, summary and body match. Cheap ILIKE — the tree is the real index. */
|
|
37
|
+
export declare function searchHandbook(tenantId: string, query: string): Promise<HandbookEntry[]>;
|
|
38
|
+
export declare function deleteHandbookPage(tenantId: string, target: {
|
|
39
|
+
id?: string;
|
|
40
|
+
path?: string;
|
|
41
|
+
}): Promise<boolean>;
|
|
42
|
+
//# sourceMappingURL=backend.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"backend.d.ts","sourceRoot":"","sources":["../../src/handbook/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|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export { HandbookProvider } from './HandbookProvider';
|
|
2
|
+
export { NotebookPanel, NotebookRailPanel } from './NotebookPanel';
|
|
3
|
+
export { NotebookPanel as HandbookPanel, NotebookRailPanel as HandbookRailPanel } from './NotebookPanel';
|
|
4
|
+
export { useHandbookStore } from './store';
|
|
5
|
+
export type { HandbookState } from './store';
|
|
6
|
+
export { HandbookAgentSurface } from './HandbookAgentSurface';
|
|
7
|
+
export { buildHandbookTree, normalizePath, parentOf, renderHandbookOutline, titleFromBody, summaryFromBody, slugFromTitle, } from './types';
|
|
8
|
+
export type { HandbookEntry, HandbookNode, HandbookPage, PageKind, PageVisibility, WriteHandbookInput } from './types';
|
|
9
|
+
export { listHandbook, readHandbookPage, searchHandbook, writeHandbookPage, appendHandbookPage, deleteHandbookPage } from './backend';
|
|
10
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/handbook/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAA;AACrD,OAAO,EAAE,aAAa,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAA;AAGlE,OAAO,EAAE,aAAa,IAAI,aAAa,EAAE,iBAAiB,IAAI,iBAAiB,EAAE,MAAM,iBAAiB,CAAA;AACxG,OAAO,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAA;AAC1C,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA;AAC5C,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAA;AAC7D,OAAO,EACL,iBAAiB,EAAE,aAAa,EAAE,QAAQ,EAAE,qBAAqB,EACjE,aAAa,EAAE,eAAe,EAAE,aAAa,GAC9C,MAAM,SAAS,CAAA;AAChB,YAAY,EAAE,aAAa,EAAE,YAAY,EAAE,YAAY,EAAE,QAAQ,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAA;AACtH,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,cAAc,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAA"}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { HandbookEntry, HandbookPage, WriteHandbookInput } from './types';
|
|
2
|
+
/**
|
|
3
|
+
* The notebook, once, for the panel and the assistant.
|
|
4
|
+
*
|
|
5
|
+
* Same reason the activation checklist has a store: the agent writes a page
|
|
6
|
+
* mid-conversation and the list on screen has to move. Two independent loads
|
|
7
|
+
* would leave the panel showing a notebook one turn out of date.
|
|
8
|
+
*
|
|
9
|
+
* Everything the person can see is held whole — a notebook is a few dozen short
|
|
10
|
+
* markdown pages, and RLS already decided which ones those are.
|
|
11
|
+
*/
|
|
12
|
+
export interface HandbookState {
|
|
13
|
+
tenantId?: string;
|
|
14
|
+
userId?: string;
|
|
15
|
+
/** null = never loaded for this tenant (render nothing, not "no pages yet"). */
|
|
16
|
+
pages: HandbookPage[] | null;
|
|
17
|
+
loading: boolean;
|
|
18
|
+
setUser: (userId: string | undefined) => void;
|
|
19
|
+
load: (tenantId: string) => Promise<void>;
|
|
20
|
+
entries: () => HandbookEntry[];
|
|
21
|
+
find: (id: string) => HandbookPage | undefined;
|
|
22
|
+
open: (path: string) => Promise<HandbookPage | null>;
|
|
23
|
+
write: (input: WriteHandbookInput) => Promise<HandbookPage | null>;
|
|
24
|
+
append: (input: {
|
|
25
|
+
path: string;
|
|
26
|
+
text: string;
|
|
27
|
+
heading?: string;
|
|
28
|
+
title?: string;
|
|
29
|
+
}) => Promise<HandbookPage | null>;
|
|
30
|
+
remove: (target: {
|
|
31
|
+
id?: string;
|
|
32
|
+
path?: string;
|
|
33
|
+
}) => Promise<void>;
|
|
34
|
+
}
|
|
35
|
+
export declare const useHandbookStore: import("zustand").UseBoundStore<import("zustand").StoreApi<HandbookState>>;
|
|
36
|
+
//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