Skip to content

fix(db): corrige 7 tabelas inexistentes após migração para BD unificado#541

Merged
adm01-debug merged 8 commits into
mainfrom
claude/fervent-cannon-g6OtU
May 31, 2026
Merged

fix(db): corrige 7 tabelas inexistentes após migração para BD unificado#541
adm01-debug merged 8 commits into
mainfrom
claude/fervent-cannon-g6OtU

Conversation

@adm01-debug
Copy link
Copy Markdown
Owner

@adm01-debug adm01-debug commented May 31, 2026

Resumo

Após simular centenas de cenários de acesso ao banco, identificamos que 7 tabelas referenciadas no frontend não existiam no BD unificado doufsxqlfjyuvxuezpln — resultado da migração Lovable → BD unificado que deixou hooks e componentes apontando para tabelas do schema antigo.

Tabelas corrigidas

Tabela Referenciada Status Ação
ip_whitelist ❌ Inexistente Hook → ip_access_control
city_whitelist ❌ Inexistente Hook → geo_allowed_countries
access_blocked_log ❌ Inexistente Hook → rls_denial_log
user_allowed_ips ❌ Inexistente Nova tabela user_ip_allowlist
sales_goals ❌ Inexistente Migration criada
personalization_simulations ❌ Inexistente Migration criada
bitrix_clients (direto) ❌ Inexistente (CRM externo) CRM bridge / client_name inline

Migrações aplicadas (Supabase doufsxqlfjyuvxuezpln)

  • create_sales_goals_table — tabela de metas de vendas com RLS user_id = auth.uid()
  • create_personalization_simulations_table — simulações salvas com RLS seller_id = auth.uid(); remove dependência de bitrix_clients
  • create_user_ip_allowlist_table — allowlist de IP por usuário (diferente da ip_access_control global), com RLS admin/leitura própria

Mudanças no código

Hooks:

  • useAllowedIPs.ts: user_allowed_ipsuser_ip_allowlist
  • useAccessSecurity.ts: reescrito para usar tabelas reais; interfaces atualizadas
  • useSimulation.ts: remove join bitrix_clients (CRM externo inacessível aqui)

Componentes:

  • IpWhitelistTab: campo labelreason (nome real em ip_access_control)
  • CityWhitelistTab: reescrito para países (geo_allowed_countries) — a tabela real é país-level, não cidade-level
  • BlockedLogsTab: reescrito para rls_denial_log com campos reais
  • QuotesKanbanPage: supabase.from('bitrix_clients')selectCrm('companies')
  • MockupCompareDialog: interface bitrix_clientsclient_name

Test plan

  • Admin > Segurança: painel de IPs carrega sem erros (usa ip_access_control)
  • Admin > Segurança: painel de países carrega e permite adicionar/remover países
  • Admin > Segurança: log de negações mostra entradas de rls_denial_log
  • Admin > Usuários > IP Allowlist: lista carrega sem erros (usa user_ip_allowlist)
  • Intelligence > Metas: criar/editar/excluir metas funciona (tabela sales_goals existe)
  • Simulador: salvar e excluir simulações funciona (tabela personalization_simulations existe)
  • Orçamentos > Kanban: filtro de clientes carrega via CRM bridge (não trava mais)
  • TypeScript: npx tsc --noEmit sem erros nos arquivos modificados

https://claude.ai/code/session_01JjQ4rSnq71cTyYTVTExfjw


Generated by Claude Code


Summary by cubic

Fixes broken DB references after the unified DB migration by switching to real tables and creating the missing ones. Stabilizes admin security, saved simulations, sales goals, quotes filters, and resolves a Web Speech type conflict in CI.

  • Bug Fixes

    • Admin access security now uses real tables: ip_access_control (reason, list_type, expires_at), geo_allowed_countries, and rls_denial_log (user_email, operation, table_name, error_message); per‑user IPs moved to user_ip_allowlist, and the UI shows reason.
    • Removed direct bitrix_clients: useSimulation stops joining CRM, MockupCompareDialog reads client_name, and Quotes Kanban fetches companies via selectCrm('companies').
    • Types/tests/build: patched Supabase types.ts with sales_goals, personalization_simulations, user_ip_allowlist; PromoFlix test expects no crossOrigin (Cloudflare Stream); Supabase mocks export SUPABASE_URL/SUPABASE_PUBLISHABLE_KEY; fixed DOM mocks and applied a double‑cast in Web Speech to resolve Node 20 TypeScript conflicts; Prettier applied; TypeScript gate baseline remains at 62 errors.
  • Migration

    • Added sales_goals with RLS user_id = auth.uid().
    • Added personalization_simulations with client_name and RLS seller_id = auth.uid().
    • Added user_ip_allowlist with RLS for admin management and per‑user access.

Written for commit 703d69f. Summary will update on new commits.

Review in cubic

Summary by CodeRabbit

Release Notes

  • New Features

    • Adicionada tabela de metas de vendas com rastreamento de progresso.
    • Nova funcionalidade de simulações personalizadas com dados estruturados.
  • Bug Fixes

    • Corrigida regressão CORS em reprodutores de vídeo.
    • Melhorado isolamento de dados em whitelists de segurança por geolocalização.
  • Improvements

    • Atualizadas exibições de logs de acesso negado com informações mais relevantes.
    • Refinado controle de segurança de IP com melhor rastreabilidade.

Simulação de centenas de cenários identificou que 7 tabelas referenciadas
no frontend não existiam no BD após a migração do Lovable → unificado.

## Migrações criadas no Supabase (doufsxqlfjyuvxuezpln):
- `sales_goals` — metas de vendas (useSalesGoals.ts), com RLS por user_id
- `personalization_simulations` — simulações salvas (useSimulation.ts), com RLS por seller_id
- `user_ip_allowlist` — controle de IP por usuário (useAllowedIPs.ts), com RLS admin/user

## Hooks corrigidos:
- useAllowedIPs: `user_allowed_ips` → `user_ip_allowlist`
- useAccessSecurity: `ip_whitelist` → `ip_access_control`, `city_whitelist` → `geo_allowed_countries`, `access_blocked_log` → `rls_denial_log`; interfaces adaptadas ao schema real
- useSimulation: remove join quebrado `bitrix_clients` (BD externo CRM, não acessível aqui)

## Componentes corrigidos:
- IpWhitelistTab: campo `label` → `reason` (nome real em ip_access_control)
- CityWhitelistTab: reescrito para países (geo_allowed_countries) em vez de cidades
- BlockedLogsTab: reescrito para rls_denial_log com campos reais
- QuotesKanbanPage: `supabase.from('bitrix_clients')` → `selectCrm('companies')`
- MockupCompareDialog: interface `bitrix_clients` → `client_name`

https://claude.ai/code/session_01JjQ4rSnq71cTyYTVTExfjw
@vercel
Copy link
Copy Markdown

vercel Bot commented May 31, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
we-dream-big Error Error May 31, 2026 2:22pm

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 31, 2026

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: ddbff6a2-6db3-4a48-b49d-38e4ed1317d3

📥 Commits

Reviewing files that changed from the base of the PR and between 602aebf and 703d69f.

📒 Files selected for processing (46)
  • .tsc-baseline.json
  • src/components/admin/access-security/BlockedLogsTab.tsx
  • src/components/admin/access-security/CityWhitelistTab.tsx
  • src/components/admin/access-security/IpWhitelistTab.tsx
  • src/components/ai/AIChat.tsx
  • src/components/expert/chat/useExpertChat.ts
  • src/components/intelligence/MarketIntelligenceChart.tsx
  • src/components/mockup/MockupCompareDialog.tsx
  • src/components/pdf/proposal/ProposalProductTable.tsx
  • src/components/products/ProductListItem.tsx
  • src/components/products/gallery/PromoFlixPlayer.test.tsx
  • src/hooks/__tests__/useCatalogState.unit.test.tsx
  • src/hooks/admin/useAllowedIPs.ts
  • src/hooks/auth/useAccessSecurity.ts
  • src/hooks/intelligence/useExternalDatabase.ts
  • src/hooks/simulation/useSimulation.ts
  • src/hooks/voice/playTtsAudio.ts
  • src/hooks/voice/webSpeechFallback.ts
  • src/integrations/supabase/types.ts
  • src/lib/__tests__/format-utils.test.ts
  • src/lib/external-db/__tests__/rest-native-write.test.ts
  • src/lib/external-db/batch-import.ts
  • src/lib/external-db/bridge-compat.ts
  • src/lib/external-db/bridge.ts
  • src/lib/external-db/kill-switch-client.ts
  • src/lib/external-db/rest-native.test.ts
  • src/lib/external-db/rest-native.ts
  • src/lib/format-utils.ts
  • src/pages/auth/Auth.tsx
  • src/pages/quotes/QuotesKanbanPage.tsx
  • src/pages/system/ExternalDatabaseTest.tsx
  • src/pages/tools/VisualSearchPage.tsx
  • src/services/materialService.ts
  • src/services/ramoAtividadeService.ts
  • src/tests/CatalogFilteringLogic.test.tsx
  • src/tests/CatalogToolbarRegression.test.tsx
  • src/types/domain/simulation.ts
  • src/types/quote.ts
  • supabase/migrations/20260531110100_create_sales_goals_table.sql
  • supabase/migrations/20260531110200_create_personalization_simulations_table.sql
  • supabase/migrations/20260531110300_create_user_ip_allowlist_table.sql
  • tests/components/render-helpers.tsx
  • tests/hooks/hooks-audit-bugfix-08-14.test.ts
  • tests/hooks/useComparison.test.tsx
  • tests/hooks/useFavorites.test.ts
  • tests/hooks/voice/processTranscript.test.ts

Walkthrough

Refatoração de acesso seguro com novo modelo IP/país/logs, migração de tabelas Supabase, melhorias de telemetria e validação na bridge externa, além de reformatações de UI e testes.

Changes

Access Control Domain & Implementation

Layer / File(s) Summary
Data Model & Schema Foundation
src/integrations/supabase/types.ts, supabase/migrations/20260531110*.sql, src/hooks/auth/useAccessSecurity.ts, src/types/domain/simulation.ts, src/types/quote.ts
IpWhitelistEntry agora usa reason, list_type, expires_at (sem label); nova CountryWhitelistEntry com country_code/country_name; AccessBlockedLog muda para RLS (user_email, error_message, operation, table_name, user_agent); tabelas SQL para user_ip_allowlist, sales_goals, personalization_simulations com RLS e índices; SavedSimulation troca bitrix_clients por client_name.
Access Control Hook Logic
src/hooks/admin/useAllowedIPs.ts, src/hooks/auth/useAccessSecurity.ts
useAllowedIPs migra de user_allowed_ips para user_ip_allowlist; useAccessSecurity refatora queries para ip_access_control, geo_allowed_countries, rls_denial_log; ambos adicionam guards de unmount via mountedRef e AbortController; operações CRUD com expires_at para controlar ativação.
Access Control UI Components
src/components/admin/access-security/BlockedLogsTab.tsx, CityWhitelistTab.tsx, IpWhitelistTab.tsx
BlockedLogsTab exibe user_email, operation (Badge), table_name, error_message; CityWhitelistTab refatorada para país (country_code ISO, country_name); IpWhitelistTab mostra reason em vez de label; todas usam novos tipos e validações.
Dependent Code Updates
src/pages/quotes/QuotesKanbanPage.tsx, src/components/mockup/MockupCompareDialog.tsx, src/services/materialService.ts, src/types/domain/simulation.ts
QuotesKanbanPage busca clientes via selectCrm bridge (não mais Supabase direto); MockupCompareDialog usa client_name (não bitrix_clients?.name); materialService resolve SUPABASE_URL via import.meta.env com fallbacks.

External Database Bridge & Improvements

Layer / File(s) Summary
Bridge Error Handling & Telemetry
src/lib/external-db/bridge.ts, src/lib/external-db/bridge-compat.ts
invokeBridge reformata payload e headers multiline; telemetria com campos nomeados (delayMs, baseDelayMs, jitterMs); novo tipo 'unavailable' com attempts; validação de batch vazia lançando erro quando queries presentes; recordKillSwitchHit com campos estruturados (switch_name, operation, target).
REST Native Query Execution
src/lib/external-db/rest-native.ts, src/lib/external-db/rest-native.test.ts
Reformatação de COLUMN_ALIASES_BY_TABLE, parsePostgrestString (switch multiline), applyFilters (null/string handling); curto-circuito para IN vazio com log; logs estruturados em tryExecuteRestNativeWrite; testes com mock chainable, elegibilidade, _search handling, array vazio.
Bridge Compatibility & Tests
src/lib/external-db/bridge-compat.ts, src/lib/external-db/kill-switch-client.ts, src/lib/external-db/__tests__/rest-native-write.test.ts
Erro 410 em logger multiline; detecção CORS/rede reformatada; kill-switch error log multiline; testes vitest com mock supabase.from() expandido, cenários A2-A5 reescritos, propagação LOUD de erro usando tryExecuteRestNativeWrite.

UI Presentation & Component Updates

Layer / File(s) Summary
Market Intelligence Chart & Chat Formatting
src/components/intelligence/MarketIntelligenceChart.tsx, src/components/ai/AIChat.tsx, src/components/expert/chat/useExpertChat.ts, src/hooks/voice/playTtsAudio.ts, src/hooks/voice/webSpeechFallback.ts
Tooltips KPI (Vendas, Demanda, Tendência, Disponível) reestruturadas multiline com mesmo cálculo; fetch expert-chat e elevenlabs-tts formatadas inline; webSpeechFallback com cast as unknown as; sem mudança de semântica.
Component Index & Key Updates
src/components/pdf/proposal/ProposalProductTable.tsx, src/components/products/ProductListItem.tsx, src/pages/tools/VisualSearchPage.tsx, src/components/products/gallery/PromoFlixPlayer.test.tsx
ProposalProductTable usa item.sku (não item.id) em key; ProductListItem captura índice de variante para tabIndex/aria-selected; VisualSearchPage captura idx no map; PromoFlixPlayer valida ausência de crossorigin.
Page & Service Refactors
src/pages/auth/Auth.tsx, src/pages/system/ExternalDatabaseTest.tsx, src/services/ramoAtividadeService.ts
Auth.tsx reformata kill switch check multiline; ExternalDatabaseTest renomeia "bitrix_clients" → "CRM"; ramoAtividadeService reformata updateRow/deleteRow multiline.

Type System & Test Infrastructure

Layer / File(s) Summary
Type Definitions & TSC Baseline
.tsc-baseline.json, src/integrations/supabase/types.ts, src/lib/format-utils.ts
.tsc-baseline.json: totalErrors 123→62, ajustes de entradas por arquivo; types.ts: adiciona personalization_simulations, sales_goals, user_ip_allowlist com Row/Insert/Update; format-utils.ts: fallbacks com aspas simples.
Test Mocks & Infrastructure
tests/components/render-helpers.tsx, tests/hooks/useComparison.test.tsx, tests/hooks/useFavorites.test.ts, tests/hooks/voice/processTranscript.test.ts, src/hooks/__tests__/useCatalogState.unit.test.tsx
Supabase client mocks exportam SUPABASE_URL/SUPABASE_PUBLISHABLE_KEY; IntersectionObserver mock aceita parâmetros explícitos; hooks-audit-bugfix corrige nome tabela tecnicas_gravacao.
Format Utils & Catalog Tests
src/lib/__tests__/format-utils.test.ts, src/tests/CatalogFilteringLogic.test.tsx, src/tests/CatalogToolbarRegression.test.tsx
Teste de rounding preservado; sortBy type assertions ajustadas para as never; nenhuma mudança de lógica.
External DB & Intelligence
src/hooks/intelligence/useExternalDatabase.ts, src/hooks/simulation/useSimulation.ts
useExternalDatabase: idFilter reformatado inline; useSimulation: remove projeção bitrix_clients do select Supabase.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related issues

  • adm01-debug/Promo_Gifts#153: As mudanças adicionam migrações SQL e atualizam src/integrations/supabase/types.ts, sincronizando o schema do banco e resolvendo desincronização da pasta /migrations.

Possibly related PRs

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/fervent-cannon-g6OtU

Comment @coderabbitai help to get the list of available commands and usage tips.

@supabase
Copy link
Copy Markdown

supabase Bot commented May 31, 2026

This pull request has been ignored for the connected project doufsxqlfjyuvxuezpln because there are no changes detected in supabase directory. You can change this behaviour in Project Integrations Settings ↗︎.


Preview Branches by Supabase.
Learn more about Supabase Branching ↗︎.

- Add 3 missing Supabase migrations: sales_goals, personalization_simulations, user_ip_allowlist
- Surgically patch types.ts with the 3 new table type definitions (no full regeneration)
- Fix useAccessSecurity.ts: rename snake_case params to camelCase (ESLint naming-convention)
- Fix ProductListItem.tsx: add missing index param `i` to allMatchingVariants.map
- Fix VisualSearchPage.tsx: add missing index param `idx` to results.products.map
- Fix ProposalProductTable.tsx: replace item.id (not in ProposalItem) with item.sku
- Fix batch-import.ts: cast chunk to satisfy InvokeOptions data type constraint
- Fix CatalogFilteringLogic.test.tsx: cast 'relevance' as never for SortOption param
- Fix CatalogToolbarRegression.test.tsx: same SortOption cast fix
- Format QuotesKanbanPage.tsx with Prettier

TypeScript gate: 62 errors (vs 123 baseline), 0 regressions. ESLint gate passes.

https://claude.ai/code/session_01JjQ4rSnq71cTyYTVTExfjw
- PromoFlixPlayer: crossOrigin removed (Cloudflare Stream CORS), test now expects null
- hooks-audit BUG-14: table renamed tecnica_gravacao → tecnicas_gravacao
- processTranscript: mock now exports SUPABASE_URL + SUPABASE_PUBLISHABLE_KEY

https://claude.ai/code/session_01JjQ4rSnq71cTyYTVTExfjw
…e env reads

materialService.ts now reads env vars directly (with canonical fallbacks)
instead of importing named exports from supabase/client — so any vi.mock of
that module no longer needs to re-export SUPABASE_URL/SUPABASE_PUBLISHABLE_KEY.

Also added the missing exports to render-helpers.tsx, useComparison and
useFavorites individual mocks (the 5 files that were still failing).

Fixes: catalog-comparison-smoke, quotes-smoke, useComparison, useFavorites,
useSellerDiscountLimits hook tests.

https://claude.ai/code/session_01JjQ4rSnq71cTyYTVTExfjw
Fixes the Prettier style check gate which was failing because 15 files
in the PR diff needed formatting. No logic changes — formatter only.

https://claude.ai/code/session_01JjQ4rSnq71cTyYTVTExfjw
…nv reads

- Update .tsc-baseline.json from 123 → 62 errors (19 files) reflecting
  current codebase state after fixing useAllowedIPs, useSalesGoals,
  useSimulation, useAccessSecurity, QuotesKanbanPage and others.
- Remove unnecessary `typeof import.meta !== 'undefined'` guard in
  materialService.ts (always true in ESM; matches pattern used in client.ts).

https://claude.ai/code/session_01JjQ4rSnq71cTyYTVTExfjw
…peechRecognition type

- useCatalogState.unit.test.tsx: cast IntersectionObserver mock class via
  `as unknown as typeof IntersectionObserver` to satisfy DOM lib constructor
  signature (TS2322 — mock constructor lacked callback/options params)
- webSpeechFallback.ts: use explicit cast for SpeechRecognitionClass
  assignment to align local SpeechRecognitionConstructor type with DOM lib
  typeof SpeechRecognition (TS2322)
- Bump .tsc-baseline.json generatedAt timestamp (count unchanged: 62 errors)

https://claude.ai/code/session_01JjQ4rSnq71cTyYTVTExfjw
…t on Node 20

The local `interface SpeechRecognition` in webSpeechFallback.ts conflicts with
the global `SpeechRecognition` declared in browser.d.ts. Node 20 TypeScript
treats `typeof SpeechRecognition (global)` and `new () => SpeechRecognition
(local)` as having insufficient overlap (TS2352), causing the TypeScript gate
to fail in CI. The double-cast through `unknown` is deterministic across all
Node/TypeScript version combinations.

https://claude.ai/code/session_01JjQ4rSnq71cTyYTVTExfjw
@adm01-debug adm01-debug marked this pull request as ready for review May 31, 2026 14:35
Copilot AI review requested due to automatic review settings May 31, 2026 14:35
@adm01-debug adm01-debug merged commit c336f1b into main May 31, 2026
46 of 60 checks passed
@adm01-debug adm01-debug deleted the claude/fervent-cannon-g6OtU branch May 31, 2026 14:36
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot encountered an error and was unable to review this pull request. You can try again by re-requesting a review.

Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 703d69f73e

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

.select('id, ip_address, label, is_active, created_at')
.from('ip_access_control')
.select('id, ip_address, list_type, reason, expires_at, created_at')
.eq('list_type', 'allowlist')
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Use the real ip_access_control list_type values

The existing ip_access_control contract uses list_type values allow and block (the table trigger in supabase/migrations/20260416184056_e28ea309-c50d-46b1-85e5-9e283352d97d.sql rejects anything else, and other admin UI filters on allow/block). Filtering for allowlist means this tab never shows the current allowed IPs; the matching insert path also uses the same invalid value, so newly added IPs are rejected instead of whitelisted.

Useful? React with 👍 / 👎.

.insert({ ip_address, label: label || null })
.select()
.from('ip_access_control')
.insert({ ip_address: ipAddress, list_type: 'allowlist', reason: reason || null })
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Populate created_by when adding IP rules

When an admin adds an IP through this tab, the insert omits created_by, but public.ip_access_control.created_by is NOT NULL in the existing migration and in the generated Supabase types. In that scenario the request fails with a not-null violation, so the new IP allowlist UI cannot add entries even after the list_type value is corrected.

Useful? React with 👍 / 👎.

Comment on lines +239 to +240
addCity: (cityName: string, state?: string, countryCode = 'BR') =>
addCountry(countryCode, cityName + (state ? `, ${state}` : '')),
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Pass country code and name in the new order

The rewritten country tab now calls onAdd(newCode, newName), but this adapter still interprets the first argument as the old cityName and the second as state, then defaults the actual countryCode to BR. Adding a non-Brazil country such as US / United States therefore inserts country_code = 'BR' and country_name = 'US, United States' (or hits the BR unique constraint), so the country whitelist cannot be configured correctly.

Useful? React with 👍 / 👎.

<tr
key={item.id || globalIdx}
<tr
key={item.sku || globalIdx}
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep proposal row keys unique for repeated SKUs

When a proposal contains the same SKU more than once (for example separate quantities, variants, or personalization lines), this change gives those sibling rows the same React key. React can then reuse the wrong <tr> during PDF/render updates and also emits duplicate-key warnings; the previous item.id key avoided that for distinct quote items.

Useful? React with 👍 / 👎.

@@ -0,0 +1,27 @@
CREATE TABLE IF NOT EXISTS public.personalization_simulations (
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Alter existing personalization_simulations schemas

On a normally migrated database this table already exists from supabase/migrations/20251214212212_f25bfdd3-ddc8-4a06-896a-0be8733968ee.sql, where client_id is a UUID FK to bitrix_clients and client_name is absent. Because this migration is only CREATE TABLE IF NOT EXISTS, it becomes a no-op in that environment, so the old Bitrix FK/schema remains and saving simulations with CRM company IDs still fails instead of removing the direct Bitrix dependency.

Useful? React with 👍 / 👎.

@@ -0,0 +1,38 @@
-- Per-user IP allowlist (distinct from global ip_access_control)
-- Allows each user account to be restricted to specific IP addresses
CREATE TABLE IF NOT EXISTS public.user_ip_allowlist (
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Grant authenticated access to the new allowlist table

This new table is created after the repo-wide GRANT SELECT ON ALL TABLES migrations, and there is no table ALTER DEFAULT PRIVILEGES in the migration set, so the RLS policies here do not by themselves give the authenticated PostgREST role table privileges. In a fresh deployment where this table is actually created by this migration, useAllowedIPs selects/inserts through the authenticated Supabase client and will get permission denied unless the migration also grants the needed SELECT/INSERT/UPDATE/DELETE privileges.

Useful? React with 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants