fix(db): corrige 7 tabelas inexistentes após migração para BD unificado#541
Conversation
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
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (46)
WalkthroughRefatoraçã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. ChangesAccess Control Domain & Implementation
External Database Bridge & Improvements
UI Presentation & Component Updates
Type System & Test Infrastructure
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related issues
Possibly related PRs
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
|
This pull request has been ignored for the connected project Preview Branches by Supabase. |
- 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
There was a problem hiding this comment.
💡 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') |
There was a problem hiding this comment.
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 }) |
There was a problem hiding this comment.
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 👍 / 👎.
| addCity: (cityName: string, state?: string, countryCode = 'BR') => | ||
| addCountry(countryCode, cityName + (state ? `, ${state}` : '')), |
There was a problem hiding this comment.
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} |
There was a problem hiding this comment.
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 ( | |||
There was a problem hiding this comment.
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 ( | |||
There was a problem hiding this comment.
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 👍 / 👎.
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
ip_whitelistip_access_controlcity_whitelistgeo_allowed_countriesaccess_blocked_logrls_denial_loguser_allowed_ipsuser_ip_allowlistsales_goalspersonalization_simulationsbitrix_clients(direto)client_nameinlineMigrações aplicadas (Supabase doufsxqlfjyuvxuezpln)
create_sales_goals_table— tabela de metas de vendas com RLSuser_id = auth.uid()create_personalization_simulations_table— simulações salvas com RLSseller_id = auth.uid(); remove dependência debitrix_clientscreate_user_ip_allowlist_table— allowlist de IP por usuário (diferente daip_access_controlglobal), com RLS admin/leitura própriaMudanças no código
Hooks:
useAllowedIPs.ts:user_allowed_ips→user_ip_allowlistuseAccessSecurity.ts: reescrito para usar tabelas reais; interfaces atualizadasuseSimulation.ts: remove joinbitrix_clients(CRM externo inacessível aqui)Componentes:
IpWhitelistTab: campolabel→reason(nome real emip_access_control)CityWhitelistTab: reescrito para países (geo_allowed_countries) — a tabela real é país-level, não cidade-levelBlockedLogsTab: reescrito pararls_denial_logcom campos reaisQuotesKanbanPage:supabase.from('bitrix_clients')→selectCrm('companies')MockupCompareDialog: interfacebitrix_clients→client_nameTest plan
ip_access_control)rls_denial_loguser_ip_allowlist)sales_goalsexiste)personalization_simulationsexiste)npx tsc --noEmitsem erros nos arquivos modificadoshttps://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
ip_access_control(reason,list_type,expires_at),geo_allowed_countries, andrls_denial_log(user_email,operation,table_name,error_message); per‑user IPs moved touser_ip_allowlist, and the UI showsreason.bitrix_clients:useSimulationstops joining CRM,MockupCompareDialogreadsclient_name, and Quotes Kanban fetches companies viaselectCrm('companies').types.tswithsales_goals,personalization_simulations,user_ip_allowlist; PromoFlix test expects nocrossOrigin(Cloudflare Stream); Supabase mocks exportSUPABASE_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
sales_goalswith RLSuser_id = auth.uid().personalization_simulationswithclient_nameand RLSseller_id = auth.uid().user_ip_allowlistwith RLS for admin management and per‑user access.Written for commit 703d69f. Summary will update on new commits.
Summary by CodeRabbit
Release Notes
New Features
Bug Fixes
Improvements