@fayz-ai/admin 0.17.0 → 0.19.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/CommandPalette-GQ6SPITD.js +297 -0
- package/dist/CommandPalette-GQ6SPITD.js.map +1 -0
- package/dist/{ScheduleEditor-63TVSCJC.js → ScheduleEditor-YZPOCBTW.js} +6 -6
- package/dist/{ScheduleEditor-63TVSCJC.js.map → ScheduleEditor-YZPOCBTW.js.map} +1 -1
- package/dist/SubscriptionPage-JXJ56OOH.js +8 -0
- package/dist/{SubscriptionPage-5PJ25YAD.js.map → SubscriptionPage-JXJ56OOH.js.map} +1 -1
- package/dist/access/headless.d.ts +2 -2
- package/dist/access/limits-registry.d.ts +6 -3
- package/dist/access/limits-registry.d.ts.map +1 -1
- package/dist/app/AdminShell.d.ts.map +1 -1
- package/dist/app/admin-app.d.ts.map +1 -1
- package/dist/app/settings-tabs.store.d.ts +21 -0
- package/dist/app/settings-tabs.store.d.ts.map +1 -0
- package/dist/billing/index.js +2 -2
- package/dist/{chunk-7DFJEXCR.js → chunk-5GWUM4SM.js} +3 -3
- package/dist/{chunk-7DFJEXCR.js.map → chunk-5GWUM4SM.js.map} +1 -1
- package/dist/{chunk-ERDS4OJS.js → chunk-HYDNIBN6.js} +3 -3
- package/dist/{chunk-ERDS4OJS.js.map → chunk-HYDNIBN6.js.map} +1 -1
- package/dist/{chunk-WN6PGQSG.js → chunk-NB6X5O5L.js} +81 -10
- package/dist/chunk-NB6X5O5L.js.map +1 -0
- package/dist/{chunk-LZRLWKJ2.js → chunk-UHHEPU4A.js} +379 -88
- package/dist/chunk-UHHEPU4A.js.map +1 -0
- package/dist/{chunk-VTEP2AQX.js → chunk-WJ3H3RJN.js} +5 -3
- package/dist/chunk-WJ3H3RJN.js.map +1 -0
- package/dist/{chunk-G5PBC5OB.js → chunk-ZNV7Q2TO.js} +8 -8
- package/dist/chunk-ZNV7Q2TO.js.map +1 -0
- package/dist/components/GetStarted.d.ts +45 -0
- package/dist/components/GetStarted.d.ts.map +1 -0
- package/dist/components/RightRail.d.ts.map +1 -1
- package/dist/components/TeachMe.d.ts +83 -0
- package/dist/components/TeachMe.d.ts.map +1 -0
- package/dist/components/auth/SplitLogin.d.ts.map +1 -1
- package/dist/components/billing/SoftLimitProbes.d.ts +5 -0
- package/dist/components/billing/SoftLimitProbes.d.ts.map +1 -0
- package/dist/components/billing/SoftLimitWidget.d.ts +3 -0
- package/dist/components/billing/SoftLimitWidget.d.ts.map +1 -0
- package/dist/components/billing/index.d.ts +3 -1
- package/dist/components/billing/index.d.ts.map +1 -1
- package/dist/components/billing/soft-limit.store.d.ts +23 -0
- package/dist/components/billing/soft-limit.store.d.ts.map +1 -0
- package/dist/components/chat/ChatConversation.d.ts.map +1 -1
- package/dist/components/chat/ChatHistory.d.ts.map +1 -1
- package/dist/components/chat/ChatMessages.d.ts.map +1 -1
- package/dist/components/chat/ConfirmActionCard.d.ts +5 -1
- package/dist/components/chat/ConfirmActionCard.d.ts.map +1 -1
- package/dist/components/chat/index.d.ts +0 -1
- package/dist/components/chat/index.d.ts.map +1 -1
- package/dist/components/connect/ConnectorRuns.d.ts +1 -1
- package/dist/components/connect/ConnectorsPanel.d.ts.map +1 -1
- package/dist/components/connect/ConnectorsTab.d.ts.map +1 -1
- package/dist/components/connect/connector-status.d.ts +1 -1
- package/dist/components/connect/model.d.ts +1 -1
- package/dist/components/layout/CommandPalette.d.ts.map +1 -1
- package/dist/components/organization/PermissionProfilesTab.d.ts.map +1 -1
- package/dist/components/settings/LocationsCrudPage.d.ts.map +1 -1
- package/dist/components/settings/SettingsPage.d.ts.map +1 -1
- package/dist/components/shared/RecordPickerModal.d.ts +24 -1
- package/dist/components/shared/RecordPickerModal.d.ts.map +1 -1
- package/dist/components/survey/PublicSurveyPage.d.ts +8 -0
- package/dist/components/survey/PublicSurveyPage.d.ts.map +1 -0
- package/dist/crud/CrudDetailPage.d.ts.map +1 -1
- package/dist/crud/CrudFormPage.d.ts.map +1 -1
- package/dist/crud/CrudListView.d.ts +3 -1
- package/dist/crud/CrudListView.d.ts.map +1 -1
- package/dist/crud/CrudPage.d.ts.map +1 -1
- package/dist/crud/CrudRecordModal.d.ts.map +1 -1
- package/dist/crud/LookupCreateInline.d.ts.map +1 -1
- package/dist/crud/RelatedListTab.d.ts +10 -0
- package/dist/crud/RelatedListTab.d.ts.map +1 -0
- package/dist/crud/archetypes/BookableToggle.d.ts +12 -0
- package/dist/crud/archetypes/BookableToggle.d.ts.map +1 -0
- package/dist/crud/archetypes/DetailTabHeader.d.ts +23 -0
- package/dist/crud/archetypes/DetailTabHeader.d.ts.map +1 -0
- package/dist/crud/archetypes/KanbanBoard.d.ts +89 -0
- package/dist/crud/archetypes/KanbanBoard.d.ts.map +1 -0
- package/dist/crud/archetypes/OrderAmount.d.ts +25 -0
- package/dist/crud/archetypes/OrderAmount.d.ts.map +1 -0
- package/dist/crud/archetypes/OrderBoardView.d.ts +61 -0
- package/dist/crud/archetypes/OrderBoardView.d.ts.map +1 -0
- package/dist/crud/archetypes/OrderCreateScreen.d.ts +116 -0
- package/dist/crud/archetypes/OrderCreateScreen.d.ts.map +1 -0
- package/dist/crud/archetypes/OrderDetailPage.d.ts +35 -0
- package/dist/crud/archetypes/OrderDetailPage.d.ts.map +1 -0
- package/dist/crud/archetypes/OrderDetailRail.d.ts +97 -0
- package/dist/crud/archetypes/OrderDetailRail.d.ts.map +1 -0
- package/dist/crud/archetypes/OrderDetailView.d.ts.map +1 -1
- package/dist/crud/archetypes/OrderFormView.d.ts +20 -1
- package/dist/crud/archetypes/OrderFormView.d.ts.map +1 -1
- package/dist/crud/archetypes/OrderListView.d.ts +59 -1
- package/dist/crud/archetypes/OrderListView.d.ts.map +1 -1
- package/dist/crud/archetypes/OrderPaymentChip.d.ts +8 -0
- package/dist/crud/archetypes/OrderPaymentChip.d.ts.map +1 -0
- package/dist/crud/archetypes/PaymentStatusBadge.d.ts +47 -0
- package/dist/crud/archetypes/PaymentStatusBadge.d.ts.map +1 -0
- package/dist/crud/archetypes/PersonDetailTabs.d.ts.map +1 -1
- package/dist/crud/archetypes/orderVocabulary.d.ts +19 -0
- package/dist/crud/archetypes/orderVocabulary.d.ts.map +1 -0
- package/dist/crud/archetypes/useOrderEditor.d.ts +20 -0
- package/dist/crud/archetypes/useOrderEditor.d.ts.map +1 -0
- package/dist/crud/archetypes/useOrderReceivable.d.ts +46 -0
- package/dist/crud/archetypes/useOrderReceivable.d.ts.map +1 -0
- package/dist/crud/archetypes/useOrdersPaymentStatus.d.ts +15 -0
- package/dist/crud/archetypes/useOrdersPaymentStatus.d.ts.map +1 -0
- package/dist/crud/createCrudPage.d.ts +3 -0
- package/dist/crud/createCrudPage.d.ts.map +1 -1
- package/dist/crud/relation-field.d.ts.map +1 -1
- package/dist/directory/AppSwitcher.d.ts +48 -0
- package/dist/directory/AppSwitcher.d.ts.map +1 -0
- package/dist/directory/FamilyWordmark.d.ts +20 -0
- package/dist/directory/FamilyWordmark.d.ts.map +1 -0
- package/dist/directory/app-id.d.ts +21 -0
- package/dist/directory/app-id.d.ts.map +1 -0
- package/dist/directory/directory.store.d.ts +20 -0
- package/dist/directory/directory.store.d.ts.map +1 -0
- package/dist/directory/index.d.ts +7 -0
- package/dist/directory/index.d.ts.map +1 -0
- package/dist/directory/types.d.ts +43 -0
- package/dist/directory/types.d.ts.map +1 -0
- package/dist/directory/useAppDirectory.d.ts +14 -0
- package/dist/directory/useAppDirectory.d.ts.map +1 -0
- package/dist/hooks/useAITools.d.ts +7 -0
- package/dist/hooks/useAITools.d.ts.map +1 -1
- package/dist/hooks/useAppConfig.d.ts.map +1 -1
- package/dist/hooks/useChat.d.ts +4 -0
- package/dist/hooks/useChat.d.ts.map +1 -1
- package/dist/hooks/useTenant.d.ts +12 -12
- package/dist/hooks/useTenant.d.ts.map +1 -1
- package/dist/index.d.ts +43 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +25073 -21491
- package/dist/index.js.map +1 -1
- package/dist/lib/agent-staff.d.ts +46 -96
- package/dist/lib/agent-staff.d.ts.map +1 -1
- package/dist/lib/ai-tool-handlers.d.ts +24 -7
- package/dist/lib/ai-tool-handlers.d.ts.map +1 -1
- package/dist/lib/assistant-invite.d.ts.map +1 -1
- package/dist/lib/bookable-service.d.ts +7 -0
- package/dist/lib/bookable-service.d.ts.map +1 -0
- package/dist/lib/core-ai-tools.d.ts +0 -17
- package/dist/lib/core-ai-tools.d.ts.map +1 -1
- package/dist/lib/fayz-agent.d.ts +2 -0
- package/dist/lib/fayz-agent.d.ts.map +1 -1
- package/dist/lib/product-name.d.ts +38 -0
- package/dist/lib/product-name.d.ts.map +1 -0
- package/dist/lib/tool-search.d.ts +82 -0
- package/dist/lib/tool-search.d.ts.map +1 -0
- package/dist/onboarding/ActivationAgentSurface.d.ts.map +1 -1
- package/dist/onboarding/ActivationChecklistCard.d.ts +11 -1
- package/dist/onboarding/ActivationChecklistCard.d.ts.map +1 -1
- package/dist/onboarding/ActivationProvider.d.ts.map +1 -1
- package/dist/onboarding/WorkspaceSetupFlow.d.ts.map +1 -1
- package/dist/onboarding/business-profile.d.ts +67 -0
- package/dist/onboarding/business-profile.d.ts.map +1 -0
- package/dist/onboarding/checklist.d.ts +10 -0
- package/dist/onboarding/checklist.d.ts.map +1 -1
- package/dist/onboarding/decide.d.ts +23 -0
- package/dist/onboarding/decide.d.ts.map +1 -1
- package/dist/onboarding/guided-runner.d.ts +11 -0
- package/dist/onboarding/guided-runner.d.ts.map +1 -1
- package/dist/onboarding/guided.d.ts +21 -1
- package/dist/onboarding/guided.d.ts.map +1 -1
- package/dist/onboarding/index.d.ts +4 -2
- package/dist/onboarding/index.d.ts.map +1 -1
- package/dist/onboarding/packs/retail.d.ts.map +1 -1
- package/dist/onboarding/programs.d.ts +25 -1
- package/dist/onboarding/programs.d.ts.map +1 -1
- package/dist/onboarding/useWorkspaceSetupGate.d.ts.map +1 -1
- package/dist/onboarding/welcome.d.ts +27 -0
- package/dist/onboarding/welcome.d.ts.map +1 -0
- package/dist/org/WorkspaceChooser.d.ts +20 -0
- package/dist/org/WorkspaceChooser.d.ts.map +1 -0
- package/dist/org/WorkspaceChooserGate.d.ts +21 -0
- package/dist/org/WorkspaceChooserGate.d.ts.map +1 -0
- package/dist/org/WorkspaceSwitching.d.ts +25 -0
- package/dist/org/WorkspaceSwitching.d.ts.map +1 -0
- package/dist/org/WorkspaceSwitchingHost.d.ts +11 -0
- package/dist/org/WorkspaceSwitchingHost.d.ts.map +1 -0
- package/dist/org/adapters/supabase.d.ts +1 -1
- package/dist/org/adapters/supabase.d.ts.map +1 -1
- package/dist/org/choice.d.ts +41 -0
- package/dist/org/choice.d.ts.map +1 -0
- package/dist/org/context.d.ts +8 -0
- package/dist/org/context.d.ts.map +1 -1
- package/dist/org/index.d.ts +12 -1
- package/dist/org/index.d.ts.map +1 -1
- package/dist/org/index.js +4 -4
- package/dist/org/self.d.ts.map +1 -1
- package/dist/org/store.d.ts +2 -1
- package/dist/org/store.d.ts.map +1 -1
- package/dist/org/switching.store.d.ts +27 -0
- package/dist/org/switching.store.d.ts.map +1 -0
- package/dist/permissions/context.d.ts +26 -0
- package/dist/permissions/context.d.ts.map +1 -1
- package/dist/permissions/index.js +1 -1
- package/dist/projects/SeuSiteWidget.d.ts.map +1 -1
- package/dist/setup/SetupAgentSurface.d.ts +2 -0
- package/dist/setup/SetupAgentSurface.d.ts.map +1 -0
- package/dist/setup/format.d.ts +21 -0
- package/dist/setup/format.d.ts.map +1 -0
- package/dist/setup/registry.d.ts +29 -0
- package/dist/setup/registry.d.ts.map +1 -0
- package/dist/setup/validate.d.ts +26 -0
- package/dist/setup/validate.d.ts.map +1 -0
- package/dist/stores/chat.store.d.ts +15 -18
- package/dist/stores/chat.store.d.ts.map +1 -1
- package/dist/stores/createCrudStore.d.ts +2 -0
- package/dist/stores/createCrudStore.d.ts.map +1 -1
- package/dist/tasks/components/TaskDetail.d.ts.map +1 -1
- package/dist/units/UnitMenuSection.d.ts.map +1 -1
- package/dist/units/UnitSwitcher.d.ts.map +1 -1
- package/dist/units/UnitSwitching.d.ts +24 -0
- package/dist/units/UnitSwitching.d.ts.map +1 -0
- package/dist/units/UnitSwitchingHost.d.ts +11 -0
- package/dist/units/UnitSwitchingHost.d.ts.map +1 -0
- package/dist/units/data.d.ts +30 -4
- package/dist/units/data.d.ts.map +1 -1
- package/dist/units/index.d.ts +2 -0
- package/dist/units/index.d.ts.map +1 -1
- package/dist/units/switching.store.d.ts +31 -0
- package/dist/units/switching.store.d.ts.map +1 -0
- package/package.json +6 -6
- package/dist/CommandPalette-XY3VOEAV.js +0 -291
- package/dist/CommandPalette-XY3VOEAV.js.map +0 -1
- package/dist/SubscriptionPage-5PJ25YAD.js +0 -8
- package/dist/chunk-G5PBC5OB.js.map +0 -1
- package/dist/chunk-LZRLWKJ2.js.map +0 -1
- package/dist/chunk-VTEP2AQX.js.map +0 -1
- package/dist/chunk-WN6PGQSG.js.map +0 -1
- package/dist/components/billing/SoftLimitBanner.d.ts +0 -5
- package/dist/components/billing/SoftLimitBanner.d.ts.map +0 -1
- package/dist/components/chat/StaffHireView.d.ts +0 -21
- package/dist/components/chat/StaffHireView.d.ts.map +0 -1
- package/dist/components/chat/StaffPitchCard.d.ts +0 -15
- package/dist/components/chat/StaffPitchCard.d.ts.map +0 -1
- package/dist/components/chat/StaffSwitcher.d.ts +0 -23
- package/dist/components/chat/StaffSwitcher.d.ts.map +0 -1
- package/dist/lib/staff-cards.d.ts +0 -11
- package/dist/lib/staff-cards.d.ts.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/data/client.ts","../src/org/team-rows.ts","../src/directory/app-id.ts","../src/org/adapters/supabase.ts","../src/org/adapters/mock.ts","../src/org/WorkspaceChooser.tsx","../src/org/WorkspaceChooserGate.tsx","../src/org/switching.store.ts","../src/org/WorkspaceSwitching.tsx","../src/org/WorkspaceSwitchingHost.tsx"],"names":["capitalize","slugify","React","jsx","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AAA,EAAU,SAAA,EAAU,CAAA,EAC9C,CAAA;AAEJ;AC9JO,SAAS,sBAAA,GAAyB;AACvC,EAAA,MAAM,MAAA,GAAS,0BAAA,CAA2B,CAAC,CAAA,KAAM,EAAE,MAAM,CAAA;AACzD,EAAA,IAAI,CAAC,QAAQ,OAAO,IAAA;AAEpB,EAAA,uBACEN,GAAAA;AAAA,IAAC,kBAAA;AAAA,IAAA;AAAA,MACC,SAAS,MAAA,CAAO,OAAA;AAAA,MAChB,YAAY,MAAA,CAAO,UAAA;AAAA,MAKnB,MAAA,EAAQ,MAAM,MAAA,CAAO,QAAA,CAAS,MAAA;AAAO;AAAA,GACvC;AAEJ","file":"chunk-UHHEPU4A.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","/**\n * Which application THIS bundle is.\n *\n * The switcher needs it for one thing only: to know which tile is the one you\n * are already looking at. Everything else about an app — its name, icon, colour\n * and URL — comes from the `app.apps` registry, so a rename is a row and not a\n * release.\n *\n * Until now the only identity an app carried was `VITE_FAYZ_PROJECT_ID`, a\n * platform project uuid. That is a poor answer to \"which product is this\": the\n * ids for the shop already disagree between the app's own `.env` and the\n * platform's seed script, and nothing would have caught it, because a uuid does\n * not look wrong. `VITE_APP_ID` is the registry key instead — it matches\n * `app.apps.id`, and a typo shows up as \"nothing is highlighted\" on the first\n * run rather than as a wrong tile months later.\n *\n * Unset is a legitimate answer: the switcher lists every app the account runs\n * and highlights none, which is right for a bundle nobody has claimed yet.\n */\nexport function resolveAppId(): string | null {\n const env = (import.meta as unknown as { env?: Record<string, string | undefined> }).env\n const id = env?.VITE_APP_ID ?? env?.PUBLIC_APP_ID\n const trimmed = id?.trim()\n return trimmed ? trimmed : null\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 { resolveAppId } from '../../directory/app-id'\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 app.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 //\n // `manage` IS KEPT, not folded into `edit`. profileHasPermission answers\n // `actions.includes(action) || actions.includes('manage')` — manage is the\n // wildcard that implies the rest. Collapsing it here destroyed that meaning\n // BEFORE the engine ever saw it: a role granted `financial.manage` stored\n // `['edit']`, which contains neither `read` nor `manage`, so the Financeiro\n // role could not open the Financeiro module — the nav gates on `read`. Same\n // for every other `X.manage` grant in the catalog.\n const actionMap: Record<string, string> = {\n read: 'read',\n create: 'create',\n update: 'edit',\n manage: 'manage',\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('v_team_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 let rows = (data ?? []) as Array<Record<string, unknown>>\n\n // Narrow to the accounts that run THIS app (008). A beauty account\n // listed inside the restaurant product is not a shortcut — it opens a\n // rail whose screens its data cannot fill. The app you are looking at\n // is the bundle's own fact (VITE_APP_ID); the database cannot infer it,\n // because one account may run several apps at once.\n //\n // Best-effort on purpose: no app id, no view (a pool predating 008), or\n // any error at all leaves the list exactly as it was. Hiding an account\n // because a filter failed is worse than showing one too many.\n const appId = resolveAppId()\n if (appId && rows.length > 1) {\n const { data: scoped, error: scopeError } = await core()\n .from('v_tenant_apps')\n .select('tenant_id')\n .eq('app_id', appId)\n if (!scopeError && Array.isArray(scoped)) {\n const runsThisApp = new Set(scoped.map((r) => (r as { tenant_id: string }).tenant_id))\n const kept = rows.filter((row) => runsThisApp.has(row['tenant_id'] as string))\n // An empty result would leave the person with no workspace at all\n // and no way to say so; the unfiltered list is the safer answer.\n if (kept.length > 0) rows = kept\n }\n }\n\n // Every field here is nullable in practice and none of them is worth\n // the whole list. A pool on the pre-014 spine answers this query with\n // `tenant` and `role` NULL — the workspace picker has to read across\n // accounts, and until 014 the policies on public.tenants and app.roles\n // were scoped to the account you had not chosen yet. `capitalize(null)`\n // threw, took listUserOrgs with it, and left a seven-workspace account\n // looking at \"you belong to none\". A missing name is a bad row; it is\n // not a reason to lose the six good ones next to it.\n return rows.map((row) => {\n const tenant = (row['tenant'] as Record<string, unknown> | null) ?? {}\n const role = (row['role'] as string | null) ?? ''\n return {\n orgId: row['tenant_id'] as string,\n orgName: (tenant['name'] as string) ?? '',\n orgSlug: (tenant['slug'] as string) ?? '',\n orgLogoUrl: (tenant['logo_url'] as string | null) ?? undefined,\n profileId: role,\n profileName: capitalize(role),\n }\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('v_team_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('v_team_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 // Verbs, not writes into the projection: v_team_members is a JOINed view\n // and accepts neither UPDATE nor DELETE, and each RPC checks the permission\n // in one place. `_orgId` stays in the signature for the adapter contract —\n // the RPCs take the tenant from the session, not from a parameter.\n async updateMemberProfile(_orgId: string, memberId: string, profileId: string): Promise<void> {\n // member_set_role refuses to demote the last owner. This screen cannot\n // know it was the last one, which is exactly why the check moved.\n const { error } = await core().rpc('member_set_role', { p_membership: memberId, p_role: profileId })\n if (error) throw error\n },\n\n async removeMember(_orgId: string, memberId: string): Promise<void> {\n const { error } = await core().rpc('member_remove', { p_membership: memberId })\n if (error) throw error\n },\n\n // #136 moved authorization into app.*, reachable through the v_authz_*\n // views (security_invoker, so RLS still decides what a caller sees) and a\n // small set of RPCs. The four public mirrors this used to read and write —\n // permissions, role_permissions, tenant_roles, tenant_role_overrides — are\n // dropped by @fayz-ai/db 003.\n //\n // The RPCs take the tenant from the SESSION, not a parameter, so orgId is\n // asserted against the active tenant rather than passed down: writing to\n // one org while another is active was never possible and should fail\n // loudly rather than silently touch the wrong one.\n async listProfiles(orgId: string): Promise<PermissionProfile[]> {\n const [permsResult, rolesResult, grantsResult] = await Promise.all([\n core().from('v_authz_permissions').select('key, plugin'),\n core().from('v_authz_roles').select('id, key, name, description, is_system').eq('tenant_id', orgId),\n core().from('v_authz_role_permissions').select('role_id, permission').eq('tenant_id', orgId),\n ])\n\n if (permsResult.error) throw permsResult.error\n if (rolesResult.error) throw rolesResult.error\n if (grantsResult.error) throw grantsResult.error\n\n const dbRoles = (rolesResult.data ?? []) as Array<{\n id: string; key: string; name: string; description: string | null; is_system: boolean\n }>\n const keyOf = new Map(dbRoles.map((r) => [r.id, r.key]))\n\n // The app still declares its own role SET; the database now supplies the\n // custom ones a tenant created. A system role the DB knows and the app\n // does not is still shown — it holds grants either way.\n const declared: RoleIdentity[] = roles.map((r) => ({ ...r, isSystem: true }))\n const declaredIds = new Set(declared.map((r) => r.id))\n const fromDb: RoleIdentity[] = dbRoles\n .filter((r) => !declaredIds.has(r.key))\n .map((r) => ({ id: r.key, name: r.name, description: r.description ?? undefined, isSystem: r.is_system }))\n\n // app.role_permissions is per TENANT, so every grant is that tenant's own.\n // The global defaults table this used to read was documented as always\n // empty and measured empty in every pool, so there is no third source to\n // merge — the grants go in as overrides and the base layer is bare.\n const overrides = ((grantsResult.data ?? []) as Array<{ role_id: string; permission: string }>)\n .flatMap((g) => {\n const role = keyOf.get(g.role_id)\n return role ? [{ role, permission_id: g.permission, granted: true }] : []\n })\n\n return buildPermissionProfiles(\n [...declared, ...fromDb],\n ((permsResult.data ?? []) as Array<{ key: string; plugin: string }>)\n .map((p) => ({ id: p.key, category: p.plugin })),\n [],\n overrides,\n )\n },\n\n async createProfile(\n orgId: string,\n profile: Omit<PermissionProfile, 'id' | 'isSystem'>,\n ): Promise<PermissionProfile> {\n const existingRoles = await core().from('v_authz_roles').select('key, is_system').eq('tenant_id', orgId)\n if (existingRoles.error) throw existingRoles.error\n const rows = (existingRoles.data ?? []) as Array<{ key: string; is_system: boolean }>\n const existing = new Set(rows.map((r) => 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 // role_create_from_template always clones something — there is no \"empty\n // role\" verb. Cloning the narrowest role available and then setting the\n // grants explicitly lands on exactly the requested set either way, and\n // never on a role that briefly held more than it should.\n const seed = rows.find((r) => r.is_system && r.key === 'viewer')?.key\n ?? rows.find((r) => r.is_system)?.key\n ?? rows[0]?.key\n if (!seed) throw new Error('createProfile: the tenant has no role to clone from')\n\n const created = await core().rpc('role_create_from_template', {\n p_role_key: key,\n p_name: profile.name,\n p_template_role: seed,\n p_template: null,\n p_description: profile.description ?? null,\n })\n if (created.error) throw created.error\n const roleId = created.data as string\n\n const keys = Object.entries(profile.grants ?? {}).flatMap(([category, actions]) =>\n actions.map((action) => `${category}.${DB_ACTION[action] ?? action}`),\n )\n const set = await core().rpc('role_set_permissions', { p_role_id: roleId, p_keys: keys })\n if (set.error) throw set.error\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 // The RPCs address a role by its uuid; the matrix addresses it by key.\n const found = await core()\n .from('v_authz_roles').select('id, name, description, is_system')\n .eq('tenant_id', orgId).eq('key', profileId).maybeSingle()\n if (found.error) throw found.error\n if (!found.data) throw new Error(`Profile not found: ${profileId}`)\n const role = found.data as { id: string; name: string; description: string | null; is_system: boolean }\n\n if (data.name !== undefined || data.description !== undefined) {\n const { error } = await core().rpc('role_rename', {\n p_role_id: role.id,\n p_name: data.name ?? role.name,\n // Explicit, not coalesced: role_rename treats NULL as \"clear it\", so\n // an untouched description has to be sent back as it was.\n p_description: data.description !== undefined ? (data.description ?? null) : role.description,\n })\n if (error) throw error\n }\n\n if (data.grants) {\n const keys = Object.entries(data.grants).flatMap(([category, actions]) =>\n actions.map((action) => `${category}.${DB_ACTION[action] ?? action}`),\n )\n // One call, not delete-then-insert: role_set_permissions reconciles to\n // the given set inside one transaction, so the role is never briefly\n // holding nothing.\n const { error } = await core().rpc('role_set_permissions', { p_role_id: role.id, p_keys: keys })\n if (error) throw error\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 const found = await core()\n .from('v_authz_roles').select('id, is_system')\n .eq('tenant_id', orgId).eq('key', profileId).maybeSingle()\n if (found.error) throw found.error\n if (!found.data) throw new Error('System roles cannot be deleted.')\n const role = found.data as { id: string; is_system: boolean }\n if (role.is_system) throw new Error('System roles cannot be deleted.')\n\n // role_delete refuses a role an active member still holds, and says how\n // many. That refusal is the point: it used to demote them silently.\n const { error } = await core().rpc('role_delete', { p_role_id: role.id })\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('v_units')\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 .rpc('unit_create', {\n p_name: input.name,\n p_kind: input.isHeadquarters ? 'hq' : 'branch',\n p_parent_unit: null,\n // app.units keeps a unit's contact details in metadata; v_units reads\n // them back out under the flat names this screen already uses.\n p_metadata: {\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 },\n })\n\n if (error) throw error\n const created = await core().from('v_units').select('*').eq('id', data as string).single()\n if (created.error) throw created.error\n return mapLocationRow(created.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","import * as React from 'react'\nimport type { OrgMembership } from '@fayz-ai/core'\nimport { useTranslation } from '@fayz-ai/core'\nimport { Button, Checkbox, cn } from '@fayz-ai/ui'\nimport { Building2, Check } from 'lucide-react'\nimport { useTenant } from './context'\nimport { setAutoPick } from './choice'\n\nexport interface WorkspaceChooserProps {\n /** Every workspace this account can open in THIS app. */\n memberships: OrgMembership[]\n /** The last one this browser was in — pre-selected, not auto-entered. */\n suggestedId: string | null\n /** Present only when there is a workspace to go back to (the switcher route). */\n onCancel?: () => void\n}\n\n/**\n * \"Which of your workspaces?\" — asked once, on the way in.\n *\n * Deliberately a full screen rather than a dialog. Behind it the shell would be\n * rendering an account nobody has chosen yet, and every plugin on it would be\n * firing tenant-scoped requests against that guess; a dialog implies there is\n * something valid underneath, and there is not.\n */\nexport function WorkspaceChooser({ memberships, suggestedId, onCancel }: WorkspaceChooserProps) {\n const t = useTranslation()\n const tr = (key: string, fallback: string) => {\n const v = t(key)\n return !v || v === key ? fallback : v\n }\n\n const { switchOrg } = useTenant()\n const [selected, setSelected] = React.useState<string | null>(\n suggestedId ?? memberships[0]?.orgId ?? null,\n )\n // Off by default, deliberately, for as long as this flow is being validated:\n // asking every time is a second of friction, and silently opening the wrong\n // account is a support ticket. Opting out stays available; it is just not\n // something anyone gets handed without choosing it.\n const [remember, setRemember] = React.useState(false)\n const [entering, setEntering] = React.useState(false)\n\n const enter = async (orgId: string) => {\n if (entering) return\n setEntering(true)\n // The preference is written BEFORE the switch: switchOrg re-renders this\n // component out of existence, so anything queued after it may never run.\n setAutoPick(remember)\n try {\n await switchOrg(orgId)\n } finally {\n setEntering(false)\n }\n }\n\n return (\n <div className=\"flex min-h-screen items-center justify-center bg-background p-4\">\n <div className=\"w-full max-w-md\">\n <div className=\"mb-6 text-center\">\n <h1 className=\"text-xl font-semibold text-foreground\">\n {tr('organization.chooseWorkspace', 'Escolha uma área de trabalho')}\n </h1>\n <p className=\"mt-1 text-sm text-muted-foreground\">\n {tr(\n 'organization.chooseWorkspaceDescription',\n 'Você tem acesso a mais de uma. Selecione em qual deseja entrar.',\n )}\n </p>\n </div>\n\n <div\n role=\"radiogroup\"\n aria-label={tr('organization.workspaces', 'Workspaces')}\n className=\"space-y-2\"\n >\n {memberships.map((m) => {\n const isSelected = m.orgId === selected\n const isSuggested = m.orgId === suggestedId\n return (\n <button\n key={m.orgId}\n type=\"button\"\n role=\"radio\"\n aria-checked={isSelected}\n disabled={entering}\n onClick={() => setSelected(m.orgId)}\n // A double click should not have to become a click and a\n // journey down to the button.\n onDoubleClick={() => void enter(m.orgId)}\n className={cn(\n 'flex w-full items-center gap-3 rounded-lg border p-3 text-left transition-colors',\n 'disabled:opacity-60',\n isSelected\n ? 'border-primary bg-primary/5'\n : 'border-border hover:border-primary/50 hover:bg-muted/50',\n )}\n >\n <WorkspaceMark name={m.orgName} logoUrl={m.orgLogoUrl} />\n <span className=\"min-w-0 flex-1\">\n <span className=\"block truncate text-sm font-medium text-foreground\">\n {m.orgName || m.orgSlug || m.orgId}\n </span>\n <span className=\"block truncate text-xs text-muted-foreground\">\n {m.profileName}\n {isSuggested && ` · ${tr('organization.lastUsed', 'último acesso')}`}\n </span>\n </span>\n {isSelected && <Check className=\"h-4 w-4 shrink-0 text-primary\" />}\n </button>\n )\n })}\n </div>\n\n {/* Not a <label>: Checkbox renders a <button>, and a label does not\n forward its click to one. The text carries its own handler instead,\n outside the button, so neither click double-toggles the other. */}\n <div className=\"mt-5 flex items-center gap-2.5 text-sm text-muted-foreground\">\n <Checkbox\n checked={remember}\n onChange={setRemember}\n disabled={entering}\n aria-label={tr('organization.rememberChoice', 'Não perguntar novamente neste dispositivo')}\n />\n <span className=\"cursor-pointer select-none\" onClick={() => !entering && setRemember(!remember)}>\n {tr('organization.rememberChoice', 'Não perguntar novamente neste dispositivo')}\n </span>\n </div>\n\n <div className=\"mt-5 flex gap-2\">\n {onCancel && (\n <Button variant=\"outline\" className=\"flex-1\" onClick={onCancel} disabled={entering}>\n {tr('common.cancel', 'Cancelar')}\n </Button>\n )}\n <Button\n className=\"flex-1\"\n disabled={!selected || entering}\n onClick={() => selected && void enter(selected)}\n >\n {entering ? tr('common.loading', 'Entrando…') : tr('organization.enter', 'Entrar')}\n </Button>\n </div>\n\n {/* The escape hatch for the checkbox above: somebody who ticked it and\n later needs a different workspace has to be told where the question\n went, or \"do not ask again\" reads as \"never again\". */}\n <p className=\"mt-4 text-center text-xs text-muted-foreground\">\n {tr(\n 'organization.switchLaterHint',\n 'Você pode trocar a qualquer momento pelo seletor no topo da tela.',\n )}\n </p>\n </div>\n </div>\n )\n}\n\n/** The workspace's face, at picker size: its logo, or its initials. */\nfunction WorkspaceMark({ name, logoUrl }: { name: string; logoUrl?: string }) {\n if (logoUrl) {\n return <img src={logoUrl} alt=\"\" className=\"h-9 w-9 shrink-0 rounded-lg object-cover\" />\n }\n const initials = name\n .split(/\\s+/)\n .filter(Boolean)\n .slice(0, 2)\n .map((w) => w[0])\n .join('')\n .toUpperCase()\n return (\n <span className=\"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-xs font-semibold text-primary\">\n {initials || <Building2 className=\"h-4 w-4\" />}\n </span>\n )\n}\n","import * as React from 'react'\nimport { getPersistedOrgId } from './store'\nimport { useTenantOptional } from './context'\nimport { WorkspaceChooser } from './WorkspaceChooser'\n\nexport interface WorkspaceChooserGateProps {\n /** Held on screen while the membership list is still in flight. */\n fallback?: React.ReactNode\n children: React.ReactNode\n}\n\n/**\n * Puts the workspace picker in front of the shell when this account owes a\n * choice, and gets out of the way when it does not.\n *\n * There is no new state to keep: `decideWorkspaceChoice` already refuses to\n * pick for the provider in exactly this case, so \"a list we have read, more\n * than one row in it, and no active workspace\" IS the question being open.\n * A separate flag would be a second copy of that fact, free to disagree.\n *\n * Mounted between the setup gate and the shell: an account with NO workspace\n * belongs to the setup flow (there is nothing to choose from), and an account\n * with one never sees this at all.\n */\nexport function WorkspaceChooserGate({ fallback, children }: WorkspaceChooserGateProps) {\n const tenant = useTenantOptional()\n if (!tenant) return <>{children}</>\n\n const { org, userOrgs, orgsKnown, settled } = tenant\n\n // Already in a workspace — nothing to ask.\n if (org) return <>{children}</>\n\n // Hold rather than hand over, for the same reason the setup gate does: the\n // shell would paint an account-shaped app and fire every plugin's\n // tenant-scoped request against no tenant, then be replaced.\n if (!settled) return <>{fallback ?? null}</>\n\n // \"We asked and could not tell\" is not \"you have several\". Only a list we\n // actually read can raise this screen; anything else falls through to the\n // shell, which is where the existing empty-switcher behaviour already lives.\n if (!orgsKnown || userOrgs.length <= 1) return <>{children}</>\n\n return (\n <WorkspaceChooser\n memberships={userOrgs}\n suggestedId={\n userOrgs.some((m) => m.orgId === getPersistedOrgId()) ? getPersistedOrgId() : null\n }\n />\n )\n}\n","import { create } from 'zustand'\nimport { clearOrgSnapshot } from './cache'\nimport { markWorkspaceSwitch } from './choice'\nimport { persistOrgId } from './store'\n\nexport interface SwitchTarget {\n orgId: string\n orgName: string\n /** So the transition shows the same mark the switcher row did. */\n orgLogoUrl?: string\n}\n\nexport interface WorkspaceSwitchingStore {\n /** The workspace being entered, while the transition is on screen. */\n target: SwitchTarget | null\n /** Commit to a workspace and raise the transition. Ends in a reload. */\n begin: (target: SwitchTarget) => void\n cancel: () => void\n}\n\n/**\n * Changing workspace, as a two-phase move: commit now, rebuild on the far side\n * of a reload.\n *\n * Switching in place was the alternative and it does not work. `switchOrg`\n * swaps the active tenant and re-hydrates the org, but every plugin store, the\n * offline cache and whatever screen is open still hold the PREVIOUS tenant's\n * rows, and nothing invalidates them centrally. The result is a shell that says\n * one workspace while the table under it lists another's — a tenant boundary\n * failure as far as anyone reading the screen is concerned, even though the\n * database never leaked a row.\n */\nexport const useWorkspaceSwitchingStore = create<WorkspaceSwitchingStore>((set) => ({\n target: null,\n\n begin: (target) => {\n // Order matters, and all three have to happen BEFORE the reload:\n // the marker — so the picker does not re-ask what was just answered\n // the pin — so \"last used\" is the workspace being entered\n // the snapshot— or the cached bootstrap of the OLD workspace paints\n // first on the far side and the switch silently undoes\n // itself.\n markWorkspaceSwitch(target.orgId)\n persistOrgId(target.orgId)\n clearOrgSnapshot()\n set({ target })\n },\n\n cancel: () => set({ target: null }),\n}))\n","import * as React from 'react'\nimport { useTranslation } from '@fayz-ai/core'\nimport { Check, ShieldCheck, Building2 } from 'lucide-react'\nimport { cn } from '@fayz-ai/ui'\n\n/** How long each step holds before the next one starts. */\nconst STEP_MS = 850\n\nexport interface WorkspaceSwitchingProps {\n /** The workspace being entered, named — the one fact that makes this concrete. */\n orgName: string\n /** Its logo, when it has one. */\n orgLogoUrl?: string\n /** Runs once the last step has been shown. Reloads the page, in practice. */\n onDone: () => void\n}\n\n/**\n * The screen between two workspaces.\n *\n * Changing tenant ends in a full reload, because half the app holds the old\n * tenant's rows in plugin stores and caches that nothing else invalidates. A\n * reload with no cover reads as a crash — the app blanks, comes back, and the\n * numbers are different. This covers it and says what is happening, so the\n * second it costs is spent visibly rather than suspiciously.\n *\n * Sized like a moment, not a toast: the workspace name is the largest thing on\n * screen because it is the answer to the only question anyone has here — where\n * am I about to be. The steps are honest about the order of operations, and the\n * last one is a security claim, so it gets an icon rather than another dot.\n */\nexport function WorkspaceSwitching({ orgName, orgLogoUrl, onDone }: WorkspaceSwitchingProps) {\n const t = useTranslation()\n const tr = (key: string, fallback: string) => {\n const v = t(key)\n return !v || v === key ? fallback : v\n }\n\n const steps = React.useMemo(\n () => [\n tr('organization.switching.step1', 'Alterando organização'),\n tr('organization.switching.step2', 'Garantindo segurança dos dados'),\n tr('organization.switching.step3', 'Carregando suas informações'),\n ],\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [],\n )\n\n const [step, setStep] = React.useState(0)\n\n // One timer that advances, then hands over — not one timer per step, which\n // would leak a reload if the component unmounted between two of them.\n const doneRef = React.useRef(onDone)\n doneRef.current = onDone\n React.useEffect(() => {\n const id = window.setInterval(() => {\n setStep((s) => {\n if (s < steps.length - 1) return s + 1\n window.clearInterval(id)\n // Out of the interval callback: the reload tears down this tree, and\n // React does not want that happening inside a state updater.\n window.setTimeout(() => doneRef.current(), STEP_MS)\n return s\n })\n }, STEP_MS)\n return () => window.clearInterval(id)\n }, [steps.length])\n\n return (\n <div\n role=\"status\"\n aria-live=\"polite\"\n aria-label={`${steps[step]} — ${orgName}`}\n className=\"saas-switch-veil fixed inset-0 z-[100] flex items-center justify-center bg-background px-6\"\n >\n <div className=\"saas-switch-rise flex w-full max-w-sm flex-col items-center\">\n {/* The mark, with the loading indicator as a ring around it rather than\n a spinner beside it — one object doing both jobs. */}\n <div className=\"relative flex h-20 w-20 items-center justify-center\">\n <span\n aria-hidden\n className=\"saas-switch-pulse absolute inset-0 rounded-2xl bg-primary/25\"\n />\n <WorkspaceMark name={orgName} logoUrl={orgLogoUrl} />\n </div>\n\n <p className=\"mt-7 text-xs font-medium uppercase tracking-[0.14em] text-muted-foreground\">\n {tr('organization.switching.eyebrow', 'Entrando em')}\n </p>\n {/* The largest thing here on purpose. Balanced leading and a wrap\n rather than an ellipsis: a truncated workspace name is exactly the\n reassurance this screen exists to give, cut in half. */}\n <h1 className=\"mt-1.5 text-pretty text-center text-3xl font-semibold leading-tight tracking-tight text-foreground sm:text-4xl\">\n {orgName}\n </h1>\n\n {/* Reserved height, top-aligned: the rows are written one at a time,\n and without a floor for the full list each arrival would shove the\n name and mark upward. The block stays put; only the list fills. */}\n <ul className=\"mt-9 flex w-full min-h-[7.5rem] flex-col items-start sm:min-h-[8.5rem]\">\n {steps.slice(0, step + 1).map((label, i) => {\n const done = i < step\n const isSecurity = i === 1\n return (\n <li key={label} className=\"saas-switch-step flex w-full gap-3\">\n {/* The rail: a thread down from the step above, then this\n step's own marker. */}\n <span className=\"flex w-6 shrink-0 flex-col items-center\">\n {i > 0 && (\n // Tinted, not `bg-border`: on a light surface the border\n // token is invisible at 1px, and this thread is the part\n // that makes three rows read as one advancing sequence\n // rather than three unrelated lines.\n <span aria-hidden className=\"saas-switch-link h-5 w-0.5 rounded-full bg-primary/30\" />\n )}\n <span className=\"flex h-7 w-6 items-center justify-center\">\n {done ? (\n <Check className=\"h-5 w-5 text-primary\" strokeWidth={2.5} />\n ) : isSecurity ? (\n <ShieldCheck className=\"saas-switch-dot h-5 w-5 text-primary\" strokeWidth={2} />\n ) : (\n <span className=\"saas-switch-dot h-2 w-2 rounded-full bg-primary\" />\n )}\n </span>\n </span>\n <span\n className={cn(\n 'flex h-7 items-center text-base transition-colors duration-300 sm:text-lg',\n // Only ever two states now — done, or happening. Nothing is\n // on screen before its turn, so there is no \"ahead\" tone.\n done ? 'text-muted-foreground' : 'font-medium text-foreground',\n // Push the label down past the connector so it stays level\n // with its own marker rather than with the thread above it.\n i > 0 && 'mt-5',\n )}\n >\n {label}\n </span>\n </li>\n )\n })}\n </ul>\n </div>\n </div>\n )\n}\n\n/** The workspace's face, at hero size: its logo, or its initials. */\nfunction WorkspaceMark({ name, logoUrl }: { name: string; logoUrl?: string }) {\n if (logoUrl) {\n return (\n <img\n src={logoUrl}\n alt=\"\"\n className=\"relative h-16 w-16 rounded-2xl object-cover shadow-sm\"\n />\n )\n }\n const initials = name\n .split(/\\s+/)\n .filter(Boolean)\n .slice(0, 2)\n .map((w) => w[0])\n .join('')\n .toUpperCase()\n return (\n <span className=\"relative flex h-16 w-16 items-center justify-center rounded-2xl bg-primary text-xl font-semibold text-primary-foreground shadow-sm\">\n {initials || <Building2 className=\"h-7 w-7\" />}\n </span>\n )\n}\n","import * as React from 'react'\nimport { useWorkspaceSwitchingStore } from './switching.store'\nimport { WorkspaceSwitching } from './WorkspaceSwitching'\n\n/**\n * Renders the workspace transition over whatever is on screen, and performs the\n * reload it exists to cover.\n *\n * Mounted once, high in the shell: the switch can be started from the topbar\n * picker or from anywhere else that grows one, and none of those places should\n * own a full-screen overlay.\n */\nexport function WorkspaceSwitchingHost() {\n const target = useWorkspaceSwitchingStore((s) => s.target)\n if (!target) return null\n\n return (\n <WorkspaceSwitching\n orgName={target.orgName}\n orgLogoUrl={target.orgLogoUrl}\n // A full reload, not a router navigation: the point is to discard every\n // plugin store and cache still holding the previous tenant's rows, and\n // only a fresh document does that. `reload()` keeps the current URL, so\n // whoever switched lands on the same screen in the new workspace.\n onDone={() => window.location.reload()}\n />\n )\n}\n"]}
|
|
@@ -50,7 +50,7 @@ function mergeFeatures(pluginFeatures, appFeatures) {
|
|
|
50
50
|
}
|
|
51
51
|
var PermissionsContext = React.createContext(null);
|
|
52
52
|
function PermissionsProvider({ config, children }) {
|
|
53
|
-
const { setFeatures, startImpersonation, stopImpersonation, currentProfile, isImpersonating } = usePermissionsStore();
|
|
53
|
+
const { setFeatures, startImpersonation, stopImpersonation, currentProfile, profiles, isImpersonating } = usePermissionsStore();
|
|
54
54
|
const runtime = usePluginRuntimeOptional();
|
|
55
55
|
const pluginFeatures = runtime?.pluginFeatures;
|
|
56
56
|
React.useEffect(() => {
|
|
@@ -62,8 +62,10 @@ function PermissionsProvider({ config, children }) {
|
|
|
62
62
|
function hasPermission(feature, action) {
|
|
63
63
|
return profileHasPermission(currentProfile, feature, action);
|
|
64
64
|
}
|
|
65
|
+
const status = currentProfile || profiles.length > 0 ? "ready" : "loading";
|
|
65
66
|
const value = {
|
|
66
67
|
hasPermission,
|
|
68
|
+
status,
|
|
67
69
|
canImpersonate: !isImpersonating,
|
|
68
70
|
startImpersonation,
|
|
69
71
|
stopImpersonation
|
|
@@ -97,5 +99,5 @@ function usePermissions() {
|
|
|
97
99
|
}
|
|
98
100
|
|
|
99
101
|
export { PermissionsProvider, useHasPermission, usePermission, usePermissionOptional, usePermissions, usePermissionsStore };
|
|
100
|
-
//# sourceMappingURL=chunk-
|
|
101
|
-
//# sourceMappingURL=chunk-
|
|
102
|
+
//# sourceMappingURL=chunk-WJ3H3RJN.js.map
|
|
103
|
+
//# sourceMappingURL=chunk-WJ3H3RJN.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/permissions/store.ts","../src/permissions/context.tsx"],"names":[],"mappings":";;;;;;;AA2BO,IAAM,mBAAA,GAAsB,MAAA,CAAyB,CAAC,GAAA,EA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AAA,CAAC,kBAAA,CAAmB,QAAA,EAAnB,EAA4B,OAC1B,QAAA,EACH,CAAA;AAEJ;AAUO,SAAS,aAAA,GAA+D;AAC7E,EAAA,MAAM,GAAA,GAAY,iBAAW,kBAAkB,CAAA;AAC/C,EAAA,IAAI,CAAC,GAAA,EAAK;AACR,IAAA,MAAM,IAAI,MAAM,yDAAyD,CAAA;AAAA,EAC3E;AACA,EAAA,OAAO,GAAA,CAAI,aAAA;AACb;AAaO,SAAS,qBAAA,GAAuE;AACrF,EAAA,MAAM,GAAA,GAAY,iBAAW,kBAAkB,CAAA;AAC/C,EAAA,OAAO,GAAA,EAAK,kBAAkB,MAAM,IAAA,CAAA;AACtC;AAeO,SAAS,gBAAA,CAAiB,SAAiB,MAAA,EAA0B;AAC1E,EAAA,MAAM,GAAA,GAAY,iBAAW,kBAAkB,CAAA;AAC/C,EAAA,IAAI,CAAC,GAAA,EAAK;AACR,IAAA,MAAM,IAAI,MAAM,4DAA4D,CAAA;AAAA,EAC9E;AACA,EAAA,OAAO,GAAA,CAAI,aAAA,CAAc,OAAA,EAAS,MAAM,CAAA;AAC1C;AAMO,SAAS,cAAA,GAA0C;AACxD,EAAA,MAAM,GAAA,GAAY,iBAAW,kBAAkB,CAAA;AAC/C,EAAA,IAAI,CAAC,GAAA,EAAK;AACR,IAAA,MAAM,IAAI,MAAM,0DAA0D,CAAA;AAAA,EAC5E;AACA,EAAA,OAAO,GAAA;AACT","file":"chunk-WJ3H3RJN.js","sourcesContent":["import { create } from 'zustand'\nimport type { FeatureDeclaration, PermissionProfile } from '@fayz-ai/core'\n\n// ---------------------------------------------------------------------------\n// Store interface\n// ---------------------------------------------------------------------------\n\nexport interface PermissionsStore {\n features: FeatureDeclaration[]\n profiles: PermissionProfile[]\n /** The effective profile used for permission checks (may be impersonated) */\n currentProfile: PermissionProfile | null\n /** The user's actual profile (preserved during impersonation) */\n realProfile: PermissionProfile | null\n /** The profile being previewed, if any */\n impersonatedProfile: PermissionProfile | null\n /** Whether impersonation is active */\n isImpersonating: boolean\n\n setFeatures: (features: FeatureDeclaration[]) => void\n setProfiles: (profiles: PermissionProfile[]) => void\n setCurrentProfile: (profile: PermissionProfile | null) => void\n startImpersonation: (profile: PermissionProfile) => void\n stopImpersonation: () => void\n reset: () => void\n}\n\nexport const usePermissionsStore = create<PermissionsStore>((set, get) => ({\n features: [],\n profiles: [],\n currentProfile: null,\n realProfile: null,\n impersonatedProfile: null,\n isImpersonating: false,\n\n setFeatures: (features) => set({ features }),\n setProfiles: (profiles) => set({ profiles }),\n setCurrentProfile: (profile) =>\n set({\n currentProfile: profile,\n realProfile: profile,\n impersonatedProfile: null,\n isImpersonating: false,\n }),\n startImpersonation: (profile) =>\n set({\n currentProfile: profile,\n impersonatedProfile: profile,\n isImpersonating: true,\n }),\n stopImpersonation: () => {\n const { realProfile } = get()\n set({\n currentProfile: realProfile,\n impersonatedProfile: null,\n isImpersonating: false,\n })\n },\n reset: () =>\n set({\n features: [],\n profiles: [],\n currentProfile: null,\n realProfile: null,\n impersonatedProfile: null,\n isImpersonating: false,\n }),\n}))\n","import * as React from 'react'\nimport type { FeatureDeclaration, PermissionsConfig, PermissionProfile } from '@fayz-ai/core'\nimport { usePluginRuntimeOptional } from '@fayz-ai/core'\nimport { usePermissionsStore } from './store'\n\n// ---------------------------------------------------------------------------\n// Permission check helpers\n// ---------------------------------------------------------------------------\n\n// The role-side check moved to @fayz-ai/core/access (single implementation for\n// browser, headless and the Fayz broker). Re-exported to keep call-sites stable.\nimport { profileHasPermission } from '@fayz-ai/core/access'\nexport { profileHasPermission }\n\n/**\n * Merge plugin-declared features with the app's own, deduped by id. The app's\n * declaration wins on collision (it can override a plugin's label/actions).\n */\nfunction mergeFeatures(\n pluginFeatures: FeatureDeclaration[] | undefined,\n appFeatures: FeatureDeclaration[] | undefined,\n): FeatureDeclaration[] {\n const byId = new Map<string, FeatureDeclaration>()\n for (const f of pluginFeatures ?? []) byId.set(f.id, f)\n for (const f of appFeatures ?? []) byId.set(f.id, f) // app override wins\n return Array.from(byId.values())\n}\n\n// ---------------------------------------------------------------------------\n// Context\n// ---------------------------------------------------------------------------\n\n/**\n * Why a `hasPermission` answer can be trusted, in three states rather than two:\n *\n * - `loading` — the RBAC catalog has not arrived. Checks DENY (the engine\n * fails closed), but the answer is not final: render a\n * skeleton, not \"you don't have access\".\n * - `ready` — the catalog arrived. A denial is the real answer, including\n * for a member the org gave no role.\n * - `unmanaged` — no <PermissionsProvider> in the tree at all. Only reported\n * by the *Optional hooks, which allow everything: an SDK\n * component under a bare host shell has no RBAC runtime to\n * ask, and gating there is an enhancement, not a guarantee.\n */\nexport type PermissionsStatus = 'loading' | 'ready' | 'unmanaged'\n\ninterface PermissionsContextValue {\n hasPermission: (feature: string, action?: string) => boolean\n status: PermissionsStatus\n canImpersonate: boolean\n startImpersonation: (profile: PermissionProfile) => void\n stopImpersonation: () => void\n}\n\nconst PermissionsContext = React.createContext<PermissionsContextValue | null>(null)\n\n// ---------------------------------------------------------------------------\n// Provider\n// ---------------------------------------------------------------------------\n\nexport interface PermissionsProviderProps {\n config?: PermissionsConfig\n children: React.ReactNode\n}\n\nexport function PermissionsProvider({ config, children }: PermissionsProviderProps) {\n const { setFeatures, startImpersonation, stopImpersonation, currentProfile, profiles, isImpersonating } =\n usePermissionsStore()\n\n // Plugins declare their own permission features via `declaredFeatures`, which the\n // plugin runtime aggregates into `pluginFeatures`. Merging them here is what makes\n // a plugin \"born compatible\" — its features show up in the RBAC matrix and gate\n // checks without the app re-declaring them. The app's own `config.features` wins\n // on id collisions (app override), so an app can refine a plugin's declaration.\n const runtime = usePluginRuntimeOptional()\n const pluginFeatures = runtime?.pluginFeatures\n\n React.useEffect(() => {\n const merged = mergeFeatures(pluginFeatures, config?.features)\n if (merged.length > 0) {\n setFeatures(merged)\n }\n }, [config, pluginFeatures, setFeatures])\n\n function hasPermission(feature: string, action?: string): boolean {\n return profileHasPermission(currentProfile, feature, action)\n }\n\n // The org bootstrap writes `profiles` (the catalog) before it resolves the\n // member's own role, so a filled catalog — not a non-null profile — is what\n // says the load is over. Without that, a member with no role assigned would\n // look identical to a load that never finished.\n const status: PermissionsStatus = currentProfile || profiles.length > 0 ? 'ready' : 'loading'\n\n const value: PermissionsContextValue = {\n hasPermission,\n status,\n canImpersonate: !isImpersonating,\n startImpersonation,\n stopImpersonation,\n }\n\n return (\n <PermissionsContext.Provider value={value}>\n {children}\n </PermissionsContext.Provider>\n )\n}\n\n// ---------------------------------------------------------------------------\n// Hooks\n// ---------------------------------------------------------------------------\n\n/**\n * Returns a function that checks whether the current user has a given\n * permission. Throws if used outside <PermissionsProvider>.\n */\nexport function usePermission(): (feature: string, action?: string) => boolean {\n const ctx = React.useContext(PermissionsContext)\n if (!ctx) {\n throw new Error('usePermission must be used inside <PermissionsProvider>')\n }\n return ctx.hasPermission\n}\n\n/**\n * Like usePermission, but degrades to allow-all when no <PermissionsProvider>\n * is mounted — so SDK components (e.g. the CRUD engine's PermissionGate) work\n * under any host shell instead of throwing. Gating is an enhancement, not a\n * hard requirement at the component level.\n *\n * That fallback covers `unmanaged` ONLY. Under a provider this is the real\n * check, which denies until the profile resolves: a missing provider means\n * nobody asked for gating, while a missing profile means we cannot yet say yes.\n * Pair with {@link usePermissionsStatus} to show a skeleton while `loading`.\n */\nexport function usePermissionOptional(): (feature: string, action?: string) => boolean {\n const ctx = React.useContext(PermissionsContext)\n return ctx?.hasPermission ?? (() => true)\n}\n\n/**\n * Why the current answers are what they are — `unmanaged` outside a provider.\n * The signal a surface needs to avoid rendering a lock over a decision that has\n * not been made yet.\n */\nexport function usePermissionsStatus(): PermissionsStatus {\n return React.useContext(PermissionsContext)?.status ?? 'unmanaged'\n}\n\n/**\n * Convenience hook — returns true/false for a specific feature + action.\n * Example: `const canEdit = useHasPermission('clients', 'write')`\n */\nexport function useHasPermission(feature: string, action?: string): boolean {\n const ctx = React.useContext(PermissionsContext)\n if (!ctx) {\n throw new Error('useHasPermission must be used inside <PermissionsProvider>')\n }\n return ctx.hasPermission(feature, action)\n}\n\n/**\n * Convenience hook that surfaces the full permissions context, including\n * impersonation controls.\n */\nexport function usePermissions(): PermissionsContextValue {\n const ctx = React.useContext(PermissionsContext)\n if (!ctx) {\n throw new Error('usePermissions must be used inside <PermissionsProvider>')\n }\n return ctx\n}\n\n// Re-export feature declarations for use in feature flag checks\nexport type { FeatureDeclaration }\n"]}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { useTranslation } from './chunk-YUHCC7JY.js';
|
|
2
|
-
import { cn, useBillingStore, useTrial, effectivePlan, resolvePlanBadge } from './chunk-
|
|
3
|
-
import { useTenantOptional, useOrgAdapterOptional } from './chunk-
|
|
4
|
-
import { usePermissionsStore } from './chunk-
|
|
5
|
-
import { useOrganizationStore } from './chunk-
|
|
2
|
+
import { cn, useBillingStore, useTrial, effectivePlan, resolvePlanBadge } from './chunk-HYDNIBN6.js';
|
|
3
|
+
import { useTenantOptional, useOrgAdapterOptional } from './chunk-NB6X5O5L.js';
|
|
4
|
+
import { usePermissionsStore } from './chunk-WJ3H3RJN.js';
|
|
5
|
+
import { useOrganizationStore } from './chunk-5GWUM4SM.js';
|
|
6
6
|
import * as React from 'react';
|
|
7
7
|
import { Sparkles, Check, Crown, Minus } from 'lucide-react';
|
|
8
8
|
import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
|
|
@@ -24,8 +24,8 @@ function PlanFeatureItem({ feature, className, iconClassName }) {
|
|
|
24
24
|
] });
|
|
25
25
|
}
|
|
26
26
|
var CORE_LIMIT_DECLARATIONS = [
|
|
27
|
-
{ key: "users", label: "Users", table: "
|
|
28
|
-
{ key: "locations", label: "Locations", table: "
|
|
27
|
+
{ key: "users", label: "Users", table: "v_team_members" },
|
|
28
|
+
{ key: "locations", label: "Locations", table: "v_units" }
|
|
29
29
|
];
|
|
30
30
|
function entityDerivedLimitDeclarations(entities) {
|
|
31
31
|
const out = [];
|
|
@@ -527,5 +527,5 @@ function SubscriptionPage({ className }) {
|
|
|
527
527
|
}
|
|
528
528
|
|
|
529
529
|
export { AccessProvider, CORE_LIMIT_DECLARATIONS, PlanFeatureItem, SubscriptionPage, checkAccess, entityDerivedLimitDeclarations, featureDisplayName, getAccessSnapshot, getPlanEntitlements, guardLimit, invalidateLimit, resolvePlanCurrency, useAccess, useAccessOptional, useLimit, useLimitGuard, useModuleNavAccess, useUpgradeModalStore };
|
|
530
|
-
//# sourceMappingURL=chunk-
|
|
531
|
-
//# sourceMappingURL=chunk-
|
|
530
|
+
//# sourceMappingURL=chunk-ZNV7Q2TO.js.map
|
|
531
|
+
//# sourceMappingURL=chunk-ZNV7Q2TO.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/components/billing/plan-feature.tsx","../src/access/limits-registry.ts","../src/access/upgrade-modal-store.ts","../src/access/context.tsx","../src/access/headless.ts","../src/access/module-nav.ts","../src/components/billing/access-contract.ts","../src/components/billing/SubscriptionPage.tsx"],"names":["jsx","useAuthStore","resolveAccess","countByTenant","React2","React3","jsxs","Sparkles","Check"],"mappings":";;;;;;;;;;;;;;;AAQO,SAAS,iBAAiB,OAAA,EAA0D;AACzF,EAAA,OAAO,QAAQ,UAAA,CAAW,GAAG,IACzB,EAAE,KAAA,EAAO,QAAQ,KAAA,CAAM,CAAC,EAAE,IAAA,EAAK,EAAG,aAAa,IAAA,EAAK,GACpD,EAAE,KAAA,EAAO,OAAA,EAAS,aAAa,KAAA,EAAM;AAC3C;AAEO,SAAS,eAAA,CAAgB,EAAE,OAAA,EAAS,SAAA,EAAW,eAAc,EAIjE;AACD,EAAA,MAAM,EAAE,KAAA,EAAO,WAAA,EAAY,GAAI,iBAAiB,OAAO,CAAA;AACvD,EAAA,uBACE,IAAA,CAAC,QAAG,SAAA,EAAW,EAAA,CAAG,0BAA0B,SAAA,EAAW,WAAA,IAAe,0BAA0B,CAAA,EAC7F,QAAA,EAAA;AAAA,IAAA,WAAA,uBACE,QAAA,EAAA,EAAS,SAAA,EAAW,GAAG,8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C,IAAA,EAAA,EAAiB,SAAA,EAAU,yBAAA,EACzB,QAAA,EAAA,IAAA,CAAK,QAAA,CAAS,QAAA,CAAS,OAAO,CAAA,mBAC7BA,GAAAA,CAACQ,KAAAA,EAAA,EAAM,SAAA,EAAU,8BAAA,EAA+B,CAAA,mBAEhDR,GAAAA,CAAC,KAAA,EAAA,EAAM,SAAA,EAAU,0CAAA,EAA2C,CAAA,EAAA,EAJvD,IAAA,CAAK,EAMd,CACD;AAAA,SAAA,EAAA,EAVM,OAWT,CACD,CAAA,EAEL;AAAA,OAAA,EACF,CAAA,EACF;AAAA,KAAA,EACF,CAAA;AAAA,oBAIFA,GAAAA;AAAA,MAAC,aAAA;AAAA,MAAA;AAAA,QACC,MAAM,OAAA,KAAY,IAAA;AAAA,QAClB,SAAA,EAAW,MAAM,OAAA,IAAW,KAAK,YAAY,OAAO,CAAA;AAAA,QACpD,QAAA,EAAU,MAAM,UAAA,CAAW,IAAI,CAAA;AAAA,QAC/B,KAAA,EAAO,EAAA,CAAG,gCAAA,EAAkC,cAAc,CAAA;AAAA,QAC1D,WAAA,EACE,OAAA,GACI,EAAA,CAAG,+BAAA,EAAiC,wCAAwC,EAAE,OAAA,CAAQ,UAAA,EAAY,OAAA,CAAQ,IAAI,CAAA,GAC9G,MAAA;AAAA,QAEN,YAAA,EAAc,EAAA,CAAG,2BAAA,EAA6B,aAAa,CAAA;AAAA,QAC3D,WAAA,EAAa,EAAA,CAAG,eAAA,EAAiB,QAAQ,CAAA;AAAA,QACzC,OAAA,EAAS;AAAA;AAAA;AACX,GAAA,EACF,CAAA;AAEJ","file":"chunk-ZNV7Q2TO.js","sourcesContent":["import * as React from 'react'\nimport { Check, Sparkles } from 'lucide-react'\nimport { cn } from '../../lib/cn'\n\n// A plan feature string prefixed with `*` renders highlighted (Sparkles +\n// primary, medium weight) — the config-side seam for \"hero\" features like the\n// AI assistant. Shared by UpgradePrompt, PlanSelector and SubscriptionPage.\n\nexport function parsePlanFeature(feature: string): { label: string; highlighted: boolean } {\n return feature.startsWith('*')\n ? { label: feature.slice(1).trim(), highlighted: true }\n : { label: feature, highlighted: false }\n}\n\nexport function PlanFeatureItem({ feature, className, iconClassName }: {\n feature: string\n className?: string\n iconClassName?: string\n}) {\n const { label, highlighted } = parsePlanFeature(feature)\n return (\n <li className={cn('flex items-start gap-2', className, highlighted && 'font-medium text-primary')}>\n {highlighted ? (\n <Sparkles className={cn('mt-0.5 shrink-0 text-primary', iconClassName)} aria-hidden=\"true\" />\n ) : (\n <Check className={cn('mt-0.5 shrink-0 text-primary', iconClassName)} aria-hidden=\"true\" />\n )}\n <span>{label}</span>\n </li>\n )\n}\n","import type { LimitDeclaration, RegisteredEntity } from '@fayz-ai/core'\nimport { invalidateCount } from '@fayz-ai/core'\n\n/**\n * Module-level registry bridging React (the provider that knows the declarations)\n * and the plain `invalidateLimit(key)` function that create handlers call outside\n * any component. The AccessProvider publishes the merged declarations here on\n * mount; `useLimit`/`useLimitGuard` and `invalidateLimit` read from it.\n */\n\n/**\n * Shell built-in limit declarations. Unlike plugin/app limits (contributed via\n * `PluginManifest.declaredLimits` / `billing.limitDeclarations`), these count\n * core tenant tables that have no owning plugin: seats and units. Merged as the\n * LOWEST-priority layer by the AccessProvider, so a plugin or app may still\n * override a key (e.g. add a `kindFilter`).\n *\n * Counted through the public `v_*` bridges, not the base tables: the spine\n * moved memberships and units into schema `app`, which PostgREST cannot reach.\n */\nexport const CORE_LIMIT_DECLARATIONS: LimitDeclaration[] = [\n { key: 'users', label: 'Users', table: 'v_team_members' },\n { key: 'locations', label: 'Locations', table: 'v_units' },\n]\n\n/**\n * Entity-derived layer of the limit merge: any registered CRUD entity carrying\n * `limitKey` yields a declaration for free from its own data mapping (table +\n * archetype kind) — a cap without a countable binding is a dead cap. Shared by\n * the AccessProvider (live registry) and the manifest derivation (agent\n * contract), so both resolve the identical layer.\n */\nexport function entityDerivedLimitDeclarations(entities: RegisteredEntity[]): LimitDeclaration[] {\n const out: LimitDeclaration[] = []\n for (const e of entities) {\n const def = e.entityDef\n if (def?.limitKey && def.data?.table) {\n out.push({\n key: def.limitKey,\n label: e.labelPlural,\n table: def.data.table,\n kindFilter: def.data.archetypeKind,\n })\n }\n }\n return out\n}\n\nlet registry = new Map<string, LimitDeclaration>()\n\n/** Called by AccessProvider whenever the merged limit declarations change. */\nexport function setLimitRegistry(declarations: LimitDeclaration[]): void {\n const next = new Map<string, LimitDeclaration>()\n for (const decl of declarations) next.set(decl.key, decl)\n registry = next\n}\n\nexport function getLimitDeclaration(key: string): LimitDeclaration | undefined {\n return registry.get(key)\n}\n\n// --- Invalidation pub/sub -------------------------------------------------\n// useLimit subscribes per key; invalidateLimit(key) drops the cached count for\n// the declaration's table and notifies subscribers to re-fetch.\n\nconst listeners = new Map<string, Set<() => void>>()\n\nexport function subscribeLimit(key: string, cb: () => void): () => void {\n let set = listeners.get(key)\n if (!set) {\n set = new Set()\n listeners.set(key, set)\n }\n set.add(cb)\n return () => {\n set?.delete(cb)\n if (set && set.size === 0) listeners.delete(key)\n }\n}\n\n/**\n * Invalidate a limit after a create/delete so its next read is fresh, then wake\n * any mounted `useLimit(key)`. Safe to call from plain handlers (no React).\n */\nexport function invalidateLimit(key: string): void {\n const decl = registry.get(key)\n if (decl) invalidateCount(decl.table)\n listeners.get(key)?.forEach((cb) => cb())\n}\n","import { create } from 'zustand'\n\n/**\n * Payload describing WHY the upgrade modal opened, so the visual component (owned\n * by the shell/gates layer) can tailor its copy — a hit quantity cap\n * (`limitKey`) or a plan-gated feature (`feature`).\n */\nexport interface UpgradeModalPayload {\n limitKey?: string\n feature?: string\n}\n\nexport interface UpgradeModalStore {\n /** The active payload, or null when closed. */\n current: UpgradeModalPayload | null\n open(payload: UpgradeModalPayload): void\n close(): void\n}\n\n/**\n * Global, lightweight store for the single app-wide UpgradeModal. `useLimitGuard`\n * and imperative create handlers call `open(...)` when a limit blocks; the visual\n * modal (rendered once near the shell root by the gates layer) subscribes to\n * `current`. Kept as a zustand singleton so store + component share one instance.\n */\nexport const useUpgradeModalStore = create<UpgradeModalStore>((set) => ({\n current: null,\n open: (payload) => set({ current: payload }),\n close: () => set({ current: null }),\n}))\n","import * as React from 'react'\nimport type { LimitDeclaration, PermissionAction, Plan } from '@fayz-ai/core'\nimport { countByTenant, usePluginRuntimeOptional, getAllEntities } from '@fayz-ai/core'\nimport { useAuthStore } from '@fayz-ai/auth'\nimport { useOrganizationStore } from '../org/store'\nimport { usePermissionsStore } from '../permissions/store'\nimport { useBillingStore } from '../billing/store'\nimport { effectivePlan, useTrial } from '../billing/trial'\nimport { mergeLimitDeclarations } from '@fayz-ai/core/access'\nimport { resolveAccess, isEntitledByPlan, resolveLimit } from './resolver'\nimport { entityDerivedLimitDeclarations } from './limits-registry'\nimport { setLimitRegistry, getLimitDeclaration, subscribeLimit, CORE_LIMIT_DECLARATIONS } from './limits-registry'\nimport { useUpgradeModalStore } from './upgrade-modal-store'\nimport type { AccessApi, AccessDecision, AccessSession, LimitState } from './types'\n\n// ---------------------------------------------------------------------------\n// Context\n// ---------------------------------------------------------------------------\n\ninterface AccessContextValue extends AccessApi {\n session: AccessSession\n}\n\nconst AccessContext = React.createContext<AccessContextValue | null>(null)\n\n// ---------------------------------------------------------------------------\n// Provider\n// ---------------------------------------------------------------------------\n\nexport interface AccessProviderProps {\n children: React.ReactNode\n /**\n * App-level limit declarations layered ON TOP of the plugins' `declaredLimits`\n * (app wins on key collision). Sourced from `config.billing.limitDeclarations`.\n */\n limitDeclarations?: LimitDeclaration[]\n /** Plan the tenant is entitled to while its trial runs. See billing/trial.ts. */\n trialPlanId?: string\n}\n\n/**\n * Assembles the reactive {@link AccessSession} from the singleton stores and\n * exposes the composed access API (role × plan). Thin by design — mounts just\n * inside PermissionsProvider so it can reuse the live permission profile and the\n * plugin runtime. Also publishes the merged limit declarations to the module\n * registry so `invalidateLimit` works from non-React create handlers.\n */\nexport function AccessProvider({ children, limitDeclarations, trialPlanId }: AccessProviderProps) {\n const user = useAuthStore((s) => s.user)\n const org = useOrganizationStore((s) => s.currentOrg)\n const profile = usePermissionsStore((s) => s.currentProfile)\n const plans = useBillingStore((s) => s.plans)\n\n const runtime = usePluginRuntimeOptional()\n const pluginLimits = runtime?.pluginLimits\n\n // Merge limit declarations by priority (later wins by key): shell built-ins\n // (users/locations) < entity-derived < plugin `declaredLimits` < app\n // overrides. Then publish to the module registry consumed by\n // invalidateLimit / the limit hooks.\n //\n // Entity-derived: any registered CRUD entity carrying `limitKey` yields a\n // declaration for free from its own data mapping (table + archetype kind) —\n // this is what makes an app's `EntityDef.limitKey: 'clients'` enforceable\n // with ZERO extra wiring (a cap without a countable binding is a dead cap).\n React.useEffect(() => {\n setLimitRegistry(\n mergeLimitDeclarations(\n CORE_LIMIT_DECLARATIONS,\n entityDerivedLimitDeclarations(getAllEntities()),\n pluginLimits,\n limitDeclarations,\n ),\n )\n }, [pluginLimits, limitDeclarations])\n\n // The trial is resolved HERE and nowhere else: it changes which plan's\n // entitlements apply, and every gate in the product already reads that. A\n // per-feature \"…or on trial\" check would have to be repeated in the nav, the\n // gates, the caps and the assistant, and one of them would be forgotten.\n const trial = useTrial()\n const plan: Plan | null = React.useMemo(\n () => effectivePlan(org, plans, trial, trialPlanId),\n [plans, org?.plan, trial.status, trialPlanId],\n )\n\n const session: AccessSession = React.useMemo(\n () => ({ user, org, profile, plan }),\n [user, org, profile, plan],\n )\n\n const value = React.useMemo<AccessContextValue>(\n () => ({\n session,\n can: (feature, action) => resolveAccess(session, feature, action),\n entitled: (feature) => isEntitledByPlan(session.plan, feature),\n }),\n [session],\n )\n\n return <AccessContext.Provider value={value}>{children}</AccessContext.Provider>\n}\nAccessProvider.displayName = 'AccessProvider'\n\n// ---------------------------------------------------------------------------\n// Hooks\n// ---------------------------------------------------------------------------\n\nconst ALLOW_ALL: AccessApi = {\n can: () => ({ allowed: true }),\n entitled: () => true,\n}\n\n/**\n * The composed access API. Throws outside <AccessProvider> — use\n * {@link useAccessOptional} for SDK components that must degrade gracefully.\n */\nexport function useAccess(): AccessApi {\n const ctx = React.useContext(AccessContext)\n if (!ctx) throw new Error('useAccess must be used inside <AccessProvider>')\n return { can: ctx.can, entitled: ctx.entitled }\n}\n\n/**\n * Like {@link useAccess} but degrades to allow-all when no provider is mounted,\n * so components stay usable under a bare host shell (gating is an enhancement).\n */\nexport function useAccessOptional(): AccessApi {\n const ctx = React.useContext(AccessContext)\n return ctx ? { can: ctx.can, entitled: ctx.entitled } : ALLOW_ALL\n}\n\n/** Internal: the live session (for hooks that need tenant/plan directly). */\nfunction useAccessSession(): AccessSession | null {\n return React.useContext(AccessContext)?.session ?? null\n}\n\n// ---------------------------------------------------------------------------\n// Limits\n// ---------------------------------------------------------------------------\n\nfunction resolveCap(plan: Plan | null, key: string): number | undefined {\n return plan?.entitlements?.limits?.[key]\n}\n\n/**\n * Live usage of a quantity limit for the active tenant. Resolves the limit's\n * declaration (plugin manifest or app override) → a tenant-scoped `count(*)`,\n * capped by the current plan. No declaration or no cap (or `-1`) ⇒ unlimited.\n * Re-fetches when the tenant, plan cap, or an `invalidateLimit(key)` fires.\n */\nexport function useLimit(key: string): LimitState {\n const session = useAccessSession()\n const tenantId = session?.org?.id\n const cap = resolveCap(session?.plan ?? null, key)\n const declaration = getLimitDeclaration(key)\n\n const unlimited = !declaration || cap === undefined || cap === -1\n\n const [used, setUsed] = React.useState(0)\n const [loading, setLoading] = React.useState(!unlimited)\n const [version, setVersion] = React.useState(0)\n\n const refresh = React.useCallback(() => setVersion((v) => v + 1), [])\n\n // Wake on external invalidation (a create/delete elsewhere).\n React.useEffect(() => subscribeLimit(key, refresh), [key, refresh])\n\n React.useEffect(() => {\n if (unlimited || !declaration || !tenantId) {\n setUsed(0)\n setLoading(false)\n return\n }\n let active = true\n setLoading(true)\n countByTenant(declaration.table, {\n kind: declaration.kindFilter,\n period: declaration.period,\n tenantId,\n fresh: version > 0,\n })\n .then((n) => {\n if (active) {\n setUsed(n)\n setLoading(false)\n }\n })\n .catch(() => {\n if (active) setLoading(false)\n })\n return () => {\n active = false\n }\n }, [unlimited, declaration, tenantId, version])\n\n const bounds = resolveLimit({ cap, hasDeclaration: Boolean(declaration), used })\n\n return { key, ...bounds, loading, refresh }\n}\n\n/**\n * Imperative guard for create handlers: `await guard(n)` returns `'ok'` when\n * adding `n` more rows stays within the cap, or `'blocked'` (and opens the global\n * UpgradeModal) when it would exceed it. Always checks a FRESH count so it never\n * relies on stale hook state.\n */\nexport function useLimitGuard(key: string): (n?: number) => Promise<'ok' | 'blocked'> {\n const session = useAccessSession()\n const tenantId = session?.org?.id\n const plan = session?.plan ?? null\n const openModal = useUpgradeModalStore((s) => s.open)\n\n return React.useCallback(\n async (n = 1) => {\n const cap = resolveCap(plan, key)\n const declaration = getLimitDeclaration(key)\n // Unlimited / no declaration / no tenant ⇒ never block.\n if (!declaration || cap === undefined || cap === -1 || !tenantId) return 'ok'\n\n const used = await countByTenant(declaration.table, {\n kind: declaration.kindFilter,\n period: declaration.period,\n tenantId,\n fresh: true,\n })\n\n if (used + n > cap) {\n openModal({ limitKey: key })\n return 'blocked'\n }\n return 'ok'\n },\n [key, plan, tenantId, openModal],\n )\n}\n","import type { PermissionAction, Plan } from '@fayz-ai/core'\nimport { countByTenant } from '@fayz-ai/core'\nimport { resolveAccess, agentDenial, type AgentGuardResult } from '@fayz-ai/core/access'\nimport { useAuthStore } from '@fayz-ai/auth'\nimport { useOrganizationStore } from '../org/store'\nimport { usePermissionsStore } from '../permissions/store'\nimport { useBillingStore } from '../billing/store'\nimport { getLimitDeclaration } from './limits-registry'\nimport type { AccessSession } from './types'\n\n// ---------------------------------------------------------------------------\n// Headless access — the imperative counterpart of useAccess()/useLimitGuard()\n// for runtimes without React: the agent's client-plane tool executor, command\n// handlers, background sync. Reads the SAME singleton stores the providers\n// hydrate, and decides with the SAME engine (@fayz-ai/core/access), so a\n// decision here never diverges from what the UI shows.\n//\n// Denials come back as the structured AgentDenial (never a silent failure) so\n// an agent can explain the denial and offer the upgrade conversationally.\n// ---------------------------------------------------------------------------\n\n/**\n * Snapshot of the live session assembled from the singleton stores — the same\n * assembly AccessProvider does reactively. Values are as-hydrated: before\n * AuthProvider/OrgProvider finish, fields are null, and an unresolved profile\n * DENIES — same semantics as the providers.\n */\nexport function getAccessSnapshot(): AccessSession {\n const user = useAuthStore.getState().user\n const org = useOrganizationStore.getState().currentOrg\n const profile = usePermissionsStore.getState().currentProfile\n const plans = useBillingStore.getState().plans\n const plan: Plan | null = org?.plan ? plans.find((p) => p.id === org.plan) ?? null : null\n return { user, org, profile, plan }\n}\n\n/** Imperative role × plan check over the live snapshot. */\nexport function checkAccess(feature: string, action?: PermissionAction): AgentGuardResult {\n const session = getAccessSnapshot()\n const decision = resolveAccess(session, feature, action)\n if (decision.allowed) return { allowed: true }\n return agentDenial(decision.reason ?? 'role')\n}\n\n/**\n * Imperative plan-limit guard: would adding `n` rows exceed the cap for\n * `key`? Counts FRESH (never trusts stale hook state), mirrors useLimitGuard.\n * No declaration / no cap / `-1` / no tenant ⇒ allowed. Does NOT open the\n * UpgradeModal — the caller decides how to surface the denial (an agent turns\n * it into a conversational upgrade prompt).\n */\nexport async function guardLimit(key: string, n = 1): Promise<AgentGuardResult> {\n const session = getAccessSnapshot()\n const tenantId = session.org?.id\n const cap = session.plan?.entitlements?.limits?.[key]\n const declaration = getLimitDeclaration(key)\n\n if (!declaration || cap === undefined || cap === -1 || !tenantId) return { allowed: true }\n\n const used = await countByTenant(declaration.table, {\n kind: declaration.kindFilter,\n period: declaration.period,\n tenantId,\n fresh: true,\n })\n\n if (used + n > cap) {\n return agentDenial('limit', { key, max: cap, used })\n }\n return { allowed: true }\n}\n","import * as React from 'react'\nimport type { ModuleNavItem } from '@fayz-ai/ui'\nimport { usePermissionsStore } from '../permissions/store'\nimport { useAccessOptional } from './context'\nimport type { AccessApi } from './types'\n\n// ---------------------------------------------------------------------------\n// useModuleNavAccess — the LINK-side counterpart of EntitlementGate for a\n// plugin's INTERNAL navigation (ModulePage sub-nav). Mirrors the top-level\n// Sidebar/AdminShell rule so a premium sub-module link reads identically:\n//\n// • role denies (can(feature,'read').reason === 'role') → REMOVE the link\n// • plan denies (entitled(feature) === false) → keep, premium:true\n// (the click still navigates; the gated CONTENT shows the\n// UpgradePrompt via EntitlementGate)\n// • otherwise → keep as-is\n//\n// A feature id ABSENT from the RBAC catalog is treated as \"default allow\": the\n// role axis is skipped entirely for it (an undeclared feature can't be a role\n// denial), so apps that wire the plugin without declaring the sub-feature don't\n// lose the link. The plan axis is naturally safe already — `entitled` returns\n// true for any feature a plan never disables.\n//\n// Recursive over `children`. Degrades to allow-all when no <AccessProvider> is\n// mounted (bare host shell), exactly like `useAccessOptional`.\n// ---------------------------------------------------------------------------\n\n/**\n * Pure decoration used by {@link useModuleNavAccess}. Kept store-free so it is\n * directly unit-testable: pass the composed {@link AccessApi} and the set of\n * feature ids known to the RBAC catalog.\n */\nexport function applyNavAccess(\n items: ModuleNavItem[],\n access: AccessApi,\n knownFeatures: Set<string>,\n): ModuleNavItem[] {\n const decorate = (item: ModuleNavItem): ModuleNavItem | null => {\n const children = item.children\n ? item.children\n .map(decorate)\n .filter((c): c is ModuleNavItem => c !== null)\n : undefined\n\n if (!item.feature) {\n return children ? { ...item, children } : item\n }\n\n // Role axis — only meaningful for a feature the RBAC catalog actually\n // declares. An undeclared feature defaults to allow (never removed).\n if (knownFeatures.has(item.feature)) {\n const decision = access.can(item.feature, 'read')\n if (!decision.allowed && decision.reason === 'role') return null\n }\n\n // Plan axis — `entitled` is `false` only on an explicit plan denial; absent\n // features stay entitled, so no Crown appears for them.\n const premium = access.entitled(item.feature) === false\n\n return children ? { ...item, premium, children } : { ...item, premium }\n }\n\n return items.map(decorate).filter((i): i is ModuleNavItem => i !== null)\n}\n\n/**\n * Resolve a plugin's internal nav against role × plan: hides role-denied links,\n * badges plan-denied ones with a Crown (`premium`), and passes everything else\n * through unchanged. Recursive over children.\n */\nexport function useModuleNavAccess(items: ModuleNavItem[]): ModuleNavItem[] {\n const access = useAccessOptional()\n const features = usePermissionsStore((s) => s.features)\n const knownFeatures = React.useMemo(\n () => new Set(features.map((f) => f.id)),\n [features],\n )\n return React.useMemo(\n () => applyNavAccess(items, access, knownFeatures),\n [items, access, knownFeatures],\n )\n}\n","// ---------------------------------------------------------------------------\n// access-contract — the single import seam the billing UI uses for the\n// entitlements engine (UpgradePrompt, UpgradeModal, EntitlementGate, LimitGate,\n// SoftLimitWidget, the AdminShell route guard / nav badge, SubscriptionPage\n// matrix). Re-exports the core access engine (packages/saas/src/access) so the\n// billing layer has ONE stable path and the wiring (AccessProvider) stays in the\n// núcleo. `getPlanEntitlements` is a thin local reader — core's Plan carries the\n// entitlements, so this just narrows the access.\n//\n// (History: this file shipped as a temporary stub while the access engine landed\n// in parallel; now repointed to the real module. The public names/types below\n// match the fixed contract, so no billing-wave consumer changed.)\n// ---------------------------------------------------------------------------\nimport type { Plan, PlanEntitlements } from '@fayz-ai/core'\n\nexport {\n useAccessOptional,\n useLimit,\n useLimitGuard,\n invalidateLimit,\n useUpgradeModalStore,\n} from '../../access'\n\nexport type { AccessApi, AccessDecision } from '../../access'\n// The billing layer refers to the limit shape as `LimitInfo`; the engine calls\n// it `LimitState`. Same structure — alias to keep call sites stable.\nexport type { LimitState as LimitInfo } from '../../access'\nexport type { PlanEntitlements } from '@fayz-ai/core'\n\n/** Narrow a plan to its entitlements (undefined when the plan declares none). */\nexport function getPlanEntitlements(plan: Plan | undefined | null): PlanEntitlements | undefined {\n return plan?.entitlements\n}\n\n/**\n * Clean a feature's raw permission label into a display name for the upgrade\n * surfaces. Feature labels in an app's permissions config carry an access-scope\n * suffix — e.g. \"Marketing (acesso)\" / \"Reports (access)\" — which reads as noise\n * when interpolated into a headline (\"Unlock Marketing (acesso)\"). Strip a single\n * trailing parenthetical group and collapse surrounding whitespace. Shared by\n * UpgradePrompt AND UpgradeModal so the two surfaces stay in lockstep.\n */\nexport function featureDisplayName(label: string | null | undefined): string {\n if (!label) return ''\n return label.replace(/\\s*\\([^)]*\\)\\s*$/, '').trim() || label.trim()\n}\n\n/**\n * Which ISO-4217 code to price a plan in. `Plan.currency` is the source of\n * truth, but apps DO ship billing configs that omit it — and silently printing\n * \"$79\" to a tenant billed in reais is worse than any other failure mode here.\n * So the fallback follows the ACTIVE LOCALE's region rather than a hardcoded\n * 'USD'; only a locale we can't place at all lands on USD.\n */\nconst CURRENCY_BY_REGION: Record<string, string> = {\n BR: 'BRL', PT: 'EUR', ES: 'EUR', FR: 'EUR', DE: 'EUR', IT: 'EUR', NL: 'EUR', IE: 'EUR',\n GB: 'GBP', US: 'USD', CA: 'CAD', AU: 'AUD', MX: 'MXN', AR: 'ARS', CL: 'CLP', CO: 'COP',\n}\n\nexport function resolvePlanCurrency(planCurrency: string | undefined, locale: string | undefined): string {\n if (planCurrency) return planCurrency\n const region = locale?.split(/[-_]/)[1]?.toUpperCase()\n return (region && CURRENCY_BY_REGION[region]) || 'USD'\n}\n","import * as React from 'react'\nimport { Crown, Check, Minus, Sparkles } from 'lucide-react'\nimport { PlanFeatureItem, parsePlanFeature } from './plan-feature'\nimport { Button, Badge, Card, CardContent, CardHeader, ConfirmDialog, toast } from '@fayz-ai/ui'\nimport type { Plan } from '@fayz-ai/core'\nimport { cn } from '../../lib/cn'\nimport { useTranslation } from '../../hooks/useTranslation'\nimport { useBillingStore } from '../../stores/billing.store'\nimport { resolvePlanBadge } from '../../billing/plan-badge'\nimport { useTenantOptional, useOrgAdapterOptional } from '../../org/context'\nimport { useOrganizationStore } from '../../org/store'\nimport { usePermissionsStore } from '../../permissions'\nimport { getPlanEntitlements } from './access-contract'\n\n// ---------------------------------------------------------------------------\n// SubscriptionPage — the shell's self-serve subscription surface. Present as the\n// /settings/subscription tab whenever `config.billing` is configured. Reads the\n// plans seeded into the billing store from config, resolves the current plan\n// from `currentOrg.plan`, and changes plan via the checkout seam (Stripe/Pix) or,\n// when no seam is configured, an optimistic `adapter.updateOrg(orgId, { plan })`.\n// ---------------------------------------------------------------------------\n\nfunction formatPrice(plan: Plan, tr: (k: string, f: string) => string): string {\n if (plan.price <= 0) return tr('billing.free', 'Free')\n try {\n const isInteger = Number.isInteger(plan.price)\n return new Intl.NumberFormat(undefined, {\n style: 'currency',\n currency: plan.currency || 'USD',\n minimumFractionDigits: isInteger ? 0 : 2,\n }).format(plan.price)\n } catch {\n return `${plan.currency || ''} ${plan.price}`.trim()\n }\n}\n\nfunction intervalSuffix(plan: Plan, tr: (k: string, f: string) => string): string {\n if (plan.price <= 0) return ''\n return plan.interval === 'year'\n ? tr('billing.perYear', '/yr')\n : tr('billing.perMonth', '/mo')\n}\n\nexport function SubscriptionPage({ className }: { className?: string }) {\n const { t } = useTranslation()\n const tr = (key: string, fallback: string) => {\n const v = t(key)\n return !v || v === key ? fallback : v\n }\n\n const plans = useBillingStore((s) => s.plans)\n const checkout = useBillingStore((s) => s.checkout)\n const tenant = useTenantOptional()\n const adapter = useOrgAdapterOptional()\n const setCurrentOrg = useOrganizationStore((s) => s.setCurrentOrg)\n const currentOrg = useOrganizationStore((s) => s.currentOrg)\n\n const currentPlanId = currentOrg?.plan || 'free'\n const currentBadge = resolvePlanBadge(currentPlanId, plans)\n const currentPlan = plans.find((p) => p.id === currentPlanId)\n\n const [pending, setPending] = React.useState<Plan | null>(null)\n const [busy, setBusy] = React.useState(false)\n\n // Feature matrix — union of every plan's features, order-preserved.\n const allFeatures = React.useMemo(() => {\n const seen = new Set<string>()\n const out: string[] = []\n for (const plan of plans) {\n for (const f of plan.features) {\n if (!seen.has(f)) {\n seen.add(f)\n out.push(f)\n }\n }\n }\n return out\n }, [plans])\n\n // Real entitlements matrix — derived from plan.entitlements when any plan\n // declares them. Feature rows show ✓/— per plan; limit rows show \"Up to N\" /\n // \"Unlimited\". Falls back to the marketing-bullet matrix (allFeatures) below\n // when no plan carries entitlements.\n const featureCatalog = usePermissionsStore((s) => s.features)\n const entitlementsMatrix = React.useMemo(() => {\n const hasAny = plans.some((p) => getPlanEntitlements(p))\n if (!hasAny) return null\n\n const featureIds: string[] = []\n const featureSeen = new Set<string>()\n const limitKeys: string[] = []\n const limitSeen = new Set<string>()\n for (const plan of plans) {\n const ent = getPlanEntitlements(plan)\n for (const id of Object.keys(ent?.features ?? {})) {\n if (!featureSeen.has(id)) { featureSeen.add(id); featureIds.push(id) }\n }\n for (const key of Object.keys(ent?.limits ?? {})) {\n if (!limitSeen.has(key)) { limitSeen.add(key); limitKeys.push(key) }\n }\n }\n if (featureIds.length === 0 && limitKeys.length === 0) return null\n\n const labelForFeature = (id: string) => featureCatalog.find((f) => f.id === id)?.label ?? id\n const labelForLimit = (key: string) => {\n const v = t(`limit.label.${key}`)\n return !v || v === `limit.label.${key}` ? key : v\n }\n return { featureIds, limitKeys, labelForFeature, labelForLimit }\n }, [plans, featureCatalog, t])\n\n async function applyChange(plan: Plan) {\n setBusy(true)\n try {\n // Seam: a configured gateway (Stripe/Pix) owns the transition; the webhook\n // is the source of truth for the persisted plan, so we don't mutate here.\n if (checkout) {\n await checkout(plan.id)\n setPending(null)\n return\n }\n // No gateway: optimistic org update. Persist + swap the store so the plan\n // badge and CTAs re-render immediately.\n if (adapter && currentOrg) {\n const updated = await adapter.updateOrg(currentOrg.id, { plan: plan.id })\n setCurrentOrg(updated)\n } else if (currentOrg) {\n setCurrentOrg({ ...currentOrg, plan: plan.id })\n }\n toast.success(\n tr('billing.planChanged', 'Plan updated').replace('{{plan}}', plan.name),\n )\n setPending(null)\n } catch {\n toast.error(tr('billing.planChangeFailed', \"Couldn't change your plan. Please try again.\"))\n } finally {\n setBusy(false)\n }\n }\n\n if (plans.length === 0) {\n return (\n <div className={className ?? 'mx-auto max-w-5xl'}>\n <p className=\"text-sm text-muted-foreground\">\n {tr('billing.noPlans', 'No plans are configured.')}\n </p>\n </div>\n )\n }\n\n return (\n <div className={className ?? 'mx-auto max-w-5xl space-y-8'}>\n {/* Sem título nem descrição: a barra já escreve \"Assinatura\", e a frase\n embaixo custava uma linha para repetir o que os planos mostram. */}\n\n {/* Current plan highlight */}\n <Card\n className={cn(\n 'relative overflow-hidden',\n currentBadge.paid && 'border-amber-400/60 bg-gradient-to-br from-amber-50/60 to-transparent dark:from-amber-950/20',\n )}\n >\n <CardContent className=\"flex flex-wrap items-center justify-between gap-4 p-6\">\n <div className=\"flex items-center gap-4\">\n <div\n className={cn(\n 'flex h-12 w-12 shrink-0 items-center justify-center rounded-xl',\n currentBadge.paid ? 'bg-amber-400/20 text-amber-600 dark:text-amber-400' : 'bg-muted text-muted-foreground',\n )}\n >\n {currentBadge.paid ? <Crown className=\"h-6 w-6\" /> : <Sparkles className=\"h-6 w-6\" />}\n </div>\n <div>\n <p className=\"text-xs font-medium uppercase tracking-wide text-muted-foreground\">\n {tr('billing.currentPlan', 'Current Plan')}\n </p>\n <div className=\"flex items-center gap-2\">\n <span className=\"text-xl font-bold\">{currentBadge.label}</span>\n {currentBadge.paid && (\n // Paid marker only — a literal \"Pro\" here was misleading next\n // to non-Pro paid tiers (\"Starter / Pro\", QA finding).\n <Badge\n aria-label={tr('billing.paidPlan', 'Paid plan')}\n className=\"border-amber-400/40 bg-amber-400/15 text-amber-700 dark:text-amber-300\"\n >\n <Crown className=\"h-3 w-3\" />\n </Badge>\n )}\n </div>\n </div>\n </div>\n {currentPlan && (\n <div className=\"text-right\">\n <span className=\"text-2xl font-bold\">{formatPrice(currentPlan, tr)}</span>\n <span className=\"text-sm text-muted-foreground\">{intervalSuffix(currentPlan, tr)}</span>\n </div>\n )}\n </CardContent>\n </Card>\n\n {/* Plan cards */}\n <div className=\"grid gap-6 md:grid-cols-2 lg:grid-cols-3\">\n {plans.map((plan) => {\n const isCurrent = plan.id === currentPlanId\n const paid = plan.price > 0\n return (\n <Card\n key={plan.id}\n className={cn(\n 'relative flex flex-col',\n plan.highlighted && 'border-primary shadow-md',\n isCurrent && 'ring-2 ring-primary/40',\n )}\n >\n {plan.highlighted && (\n <div className=\"absolute -top-3 left-1/2 -translate-x-1/2\">\n <Badge>\n <Crown className=\"mr-1 h-3 w-3\" />\n {tr('billing.mostPopular', 'Most Popular')}\n </Badge>\n </div>\n )}\n <CardHeader className=\"pb-0\">\n <div className=\"flex items-center gap-2\">\n <h3 className=\"text-xl font-semibold\">{plan.name}</h3>\n {paid && <Crown className=\"h-4 w-4 text-amber-500\" />}\n </div>\n {plan.description && (\n <p className=\"text-sm text-muted-foreground\">{plan.description}</p>\n )}\n </CardHeader>\n <CardContent className=\"flex flex-1 flex-col pt-4\">\n <div className=\"mb-6\">\n <span className=\"text-4xl font-bold\">{formatPrice(plan, tr)}</span>\n <span className=\"text-muted-foreground\">{intervalSuffix(plan, tr)}</span>\n </div>\n <ul className=\"mb-6 flex-1 space-y-3\">\n {plan.features.map((feature) => (\n <PlanFeatureItem key={feature} feature={feature} className=\"text-sm\" iconClassName=\"h-4 w-4\" />\n ))}\n </ul>\n {isCurrent ? (\n <Button variant=\"outline\" className=\"w-full\" disabled>\n {tr('billing.currentPlan', 'Current Plan')}\n </Button>\n ) : (\n <Button\n className=\"w-full\"\n variant={plan.highlighted ? 'default' : 'outline'}\n onClick={() => setPending(plan)}\n >\n {tr('billing.changeToPlan', 'Switch to this plan')}\n </Button>\n )}\n </CardContent>\n </Card>\n )\n })}\n </div>\n\n {/* Feature matrix */}\n {(entitlementsMatrix || allFeatures.length > 0) && (\n <div className=\"space-y-3\">\n <h2 className=\"text-lg font-semibold\">\n {tr('billing.featureMatrix', 'Feature comparison')}\n </h2>\n <div className=\"overflow-x-auto rounded-lg border\">\n <table className=\"w-full border-collapse text-sm\">\n <thead>\n <tr className=\"border-b bg-muted/40\">\n <th className=\"px-4 py-3 text-left font-medium\">\n {tr('billing.features', 'Features')}\n </th>\n {plans.map((plan) => (\n <th key={plan.id} className=\"px-4 py-3 text-center font-medium\">\n <span className=\"inline-flex items-center gap-1\">\n {plan.price > 0 && <Crown className=\"h-3.5 w-3.5 text-amber-500\" />}\n {plan.name}\n </span>\n </th>\n ))}\n </tr>\n </thead>\n <tbody>\n {entitlementsMatrix ? (\n <>\n {entitlementsMatrix.featureIds.map((id, i) => (\n <tr key={`f:${id}`} className={cn(i % 2 === 1 && 'bg-muted/20')}>\n <td className=\"px-4 py-2.5 text-left\">{entitlementsMatrix.labelForFeature(id)}</td>\n {plans.map((plan) => {\n const entitled = getPlanEntitlements(plan)?.features?.[id] !== false\n return (\n <td key={plan.id} className=\"px-4 py-2.5 text-center\">\n {entitled ? (\n <Check className=\"mx-auto h-4 w-4 text-primary\" />\n ) : (\n <Minus className=\"mx-auto h-4 w-4 text-muted-foreground/40\" />\n )}\n </td>\n )\n })}\n </tr>\n ))}\n {entitlementsMatrix.limitKeys.map((key, i) => (\n <tr key={`l:${key}`} className={cn((entitlementsMatrix.featureIds.length + i) % 2 === 1 && 'bg-muted/20')}>\n <td className=\"px-4 py-2.5 text-left\">{entitlementsMatrix.labelForLimit(key)}</td>\n {plans.map((plan) => {\n const cap = getPlanEntitlements(plan)?.limits?.[key]\n const cell =\n cap === undefined\n ? '—'\n : cap < 0\n ? tr('billing.unlimited', 'Unlimited')\n : tr('billing.upTo', 'Up to {count}').replace('{count}', String(cap)).replace('{{count}}', String(cap))\n return (\n <td key={plan.id} className=\"px-4 py-2.5 text-center text-muted-foreground\">\n {cell}\n </td>\n )\n })}\n </tr>\n ))}\n </>\n ) : (\n allFeatures.map((feature, i) => (\n <tr key={feature} className={cn(i % 2 === 1 && 'bg-muted/20')}>\n <td className=\"px-4 py-2.5 text-left\">{parsePlanFeature(feature).label}</td>\n {plans.map((plan) => (\n <td key={plan.id} className=\"px-4 py-2.5 text-center\">\n {plan.features.includes(feature) ? (\n <Check className=\"mx-auto h-4 w-4 text-primary\" />\n ) : (\n <Minus className=\"mx-auto h-4 w-4 text-muted-foreground/40\" />\n )}\n </td>\n ))}\n </tr>\n ))\n )}\n </tbody>\n </table>\n </div>\n </div>\n )}\n\n {/* Change-plan confirm */}\n <ConfirmDialog\n open={pending !== null}\n onConfirm={() => pending && void applyChange(pending)}\n onCancel={() => setPending(null)}\n title={tr('billing.changePlanConfirmTitle', 'Change plan?')}\n description={\n pending\n ? tr('billing.changePlanConfirmBody', \"You're switching to the {{plan}} plan.\").replace('{{plan}}', pending.name)\n : undefined\n }\n confirmLabel={tr('billing.changePlanConfirm', 'Switch plan')}\n cancelLabel={tr('common.cancel', 'Cancel')}\n loading={busy}\n />\n </div>\n )\n}\n"]}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import * as React from 'react';
|
|
2
|
+
export interface GetStartedStep {
|
|
3
|
+
/** What is missing, in the owner's words: 'Uma conta de caixa físico'. */
|
|
4
|
+
label: string;
|
|
5
|
+
/** Where it lives, when it is somewhere else: 'Cadastros → Contas'. */
|
|
6
|
+
where?: string;
|
|
7
|
+
/** Send them there. */
|
|
8
|
+
onGo?: () => void;
|
|
9
|
+
/** Already satisfied — shown ticked, so progress is visible. */
|
|
10
|
+
done?: boolean;
|
|
11
|
+
}
|
|
12
|
+
export interface GetStartedProps {
|
|
13
|
+
/** Feature id, so the assistant door can carry the guide. */
|
|
14
|
+
feature?: string;
|
|
15
|
+
/** Name on screen, for the assistant: 'Caixas'. */
|
|
16
|
+
title?: string;
|
|
17
|
+
/** The headline: what is missing, said plainly. */
|
|
18
|
+
heading: string;
|
|
19
|
+
/** One line on why the screen is empty and what it unlocks. */
|
|
20
|
+
because?: string;
|
|
21
|
+
/** The prerequisites, when there is more than one. */
|
|
22
|
+
steps?: GetStartedStep[];
|
|
23
|
+
/** The main way out. */
|
|
24
|
+
action?: {
|
|
25
|
+
label: string;
|
|
26
|
+
onClick: () => void;
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* Plan does not include this. Swaps the setup door for the upgrade one —
|
|
30
|
+
* nobody can configure their way past a paywall, and offering it is a lie.
|
|
31
|
+
*/
|
|
32
|
+
locked?: {
|
|
33
|
+
reason?: string;
|
|
34
|
+
onUpgrade?: () => void;
|
|
35
|
+
};
|
|
36
|
+
className?: string;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* The standard answer to "this screen has nothing on it yet".
|
|
40
|
+
*
|
|
41
|
+
* Deliberately not a card: it sits inside whatever frame the screen already
|
|
42
|
+
* drew, so it reads as the content being absent rather than as a second panel.
|
|
43
|
+
*/
|
|
44
|
+
export declare function GetStarted({ feature, title, heading, because, steps, action, locked, className, }: GetStartedProps): React.JSX.Element;
|
|
45
|
+
//# sourceMappingURL=GetStarted.d.ts.map
|