Auditoria: corrige bugs latentes de tipos + cobertura de testes (rumo a produção)#364
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Warning Review limit reached
More reviews will be available in 48 minutes and 10 seconds. Learn how PR review limits work. Your organization has run out of usage credits. Purchase more in the billing tab. ⌛ How to resolve this issue?After more reviews become available, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available. Please see our Fair Usage Limits Policy for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (11)
✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
|
This pull request has been ignored for the connected project Preview Branches by Supabase. |
There was a problem hiding this comment.
Pull request overview
Este PR faz uma auditoria de type-drift e ajustes de tipagem/lint para alinhar os tipos ao shape real em runtime (simulação, quotes, MFA), além de adicionar um teste de contrato para evitar regressões no clipboard da simulação.
Changes:
- Redefine tipos de simulação para refletirem a forma “computada” (pricing option) e ajusta
SavedSimulationpara o shape persistido. - Padroniza
Quote.statuspara oQuoteStatuscanônico e ajusta chamada de bulk status update na listagem. - Amplia
adaptPriceResponsepara aceitarunknowne adiciona teste de contrato parasimulationClipboard.
Reviewed changes
Copilot reviewed 12 out of 12 changed files in this pull request and generated 6 comments.
Show a summary per file
| File | Description |
|---|---|
| tests/hooks/simulation/simulationClipboard.test.ts | Novo teste de contrato para travar o shape consumido pelo clipboard da simulação. |
| src/types/domain/simulation.ts | Atualiza tipos de domínio da simulação (produto/opções/persistência) para alinhar com runtime. |
| src/pages/quotes/QuotesListPage.tsx | Ajusta tipagem do status em bulk update na lista de orçamentos. |
| src/pages/auth/Auth.tsx | Remove ramo morto no botão de login. |
| src/lib/personalization/adapters/price-response.adapter.ts | Widen de input em adaptPriceResponse para aceitar unknown. |
| src/hooks/quotes/quoteTypes.ts | Troca Quote.status para o QuoteStatus canônico. |
| src/components/security/MfaEnrollmentDialog.tsx | Ajuste de tipagem/format + detecção de fator TOTP unverified. |
| .tsc-baseline.json | Atualiza baseline do TSC com redução de erros. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| beforeEach(() => { | ||
| vi.clearAllMocks(); | ||
| vi.useFakeTimers(); | ||
| Object.assign(navigator, { clipboard: { writeText } }); | ||
| }); | ||
|
|
| import { describe, it, expect, vi, beforeEach } from 'vitest'; | ||
| import type { SimulationOption, Product } from '@/types/simulation'; |
| export function adaptPriceResponse(resp: unknown): CustomizationPriceFlat { | ||
| return adaptPriceResponseWithMeta(resp as Record<string, unknown> | null | undefined).flat; | ||
| } |
| onBulkStatusChange={async (ids, status) => { | ||
| let successCount = 0; | ||
| for (const id of ids) { | ||
| const ok = await updateQuoteStatus(id, status as string); | ||
| const ok = await updateQuoteStatus(id, status as QuoteStatus); | ||
| if (ok) successCount++; |
| // Limpa fatores não-verificados anteriores para evitar erro "factor already exists". | ||
| // O SDK tipa totp como status:"verified", mas fatores "unverified" aparecem em | ||
| // runtime (enroll interrompido) — cast para detectá-los e limpá-los. | ||
| const { data: existing } = await supabase.auth.mfa.listFactors(); | ||
| const stale = existing?.totp?.find((f) => f.status === "unverified"); | ||
| const stale = existing?.totp?.find((f) => (f.status as string) === 'unverified'); | ||
| if (stale) await supabase.auth.mfa.unenroll({ factorId: stale.id }); | ||
|
|
| /** Row of `public.personalization_simulations` (snake_case as stored in Supabase). */ | ||
| export interface SavedSimulation { | ||
| id: string; | ||
| name: string; | ||
| options: SimulationOption[]; | ||
| totalPrice: number; | ||
| status: 'draft' | 'sent' | 'approved' | 'rejected'; | ||
| createdAt: Date; | ||
| updatedAt: Date; | ||
| seller_id?: string; | ||
| client_id?: string | null; | ||
| product_id: string; | ||
| product_name?: string; | ||
| product_sku?: string; | ||
| quantity: number; | ||
| product_unit_price: number; | ||
| simulation_data: SimulationOption[]; | ||
| notes?: string | null; | ||
| created_at?: string; | ||
| updated_at?: string; | ||
| bitrix_clients?: { id: string; name: string; ramo?: string } | null; |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 05b664fe4d
ℹ️ 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".
|
|
||
| beforeEach(() => { | ||
| vi.clearAllMocks(); | ||
| vi.useFakeTimers(); |
There was a problem hiding this comment.
Restore real timers after clipboard tests
This suite enables fake timers in beforeEach but never switches back to real timers, so any test file executed later in the same worker can inherit mocked time and behave differently (timeouts, debounce logic, and async scheduling can stall). Because tests/setup.ts only runs cleanup() after each test and does not call vi.useRealTimers(), this file currently leaks timer state across suite boundaries.
Useful? React with 👍 / 👎.
Alinha tipos de domínio à forma real produzida/consumida em runtime, eliminando 107 erros TS latentes (baseline 486→379) sem regressão: - simulation: SimulationOption/TechniqueSettings/SimulationProduct/SavedSimulation redefinidos para a forma computada de simulationPriceFetcher (grandTotal, techniqueId, priceSource, image_url, linha do DB) — resolve ~93 erros nos 5 arquivos do simulador. - adaptPriceResponse: param widened para unknown (interfaces não satisfazem Record<string,unknown>) — resolve ~7 call-sites. - quotes: Quote.status usa QuoteStatus canônico (incluía-se sem 'converted'/ 'viewed') — corrige comparações sempre-falsas no funil e em quick-actions. - Auth.tsx: remove ramo morto loginStatus==='success' (inalcançável — o card é substituído pelo splash de sucesso no nível externo). - MFA: cast para detectar fatores totp 'unverified' (SDK tipa só 'verified'). Adiciona teste de contrato para simulationClipboard. Baseline TSC regenerado.
- SidebarReorganized: move a anotação `// rls-allow:` para imediatamente
acima do `.from('discount_approval_requests')` (o checker só inspeciona
a linha do .from e a anterior; o coment estava 2 linhas acima por causa
da quebra `const ... = await supabase`). Resolve "Lint, Typecheck & Test".
- useAIRecommendations: extractErrorMessage agora inclui `(HTTP <status>)`
no fallback de texto bruto/JSON-sem-message — erro fica diagnosticável e
o teste "retries 3x on 5xx" volta a passar. Resolve "Hook tests".
Ambos estavam armazenados em base64 no git, ilegíveis para o toolchain: - `deno check --config deno.json` falhava com "Failed deserializing config file ... Unexpected token" em TODAS as 82 edge functions (gate "Edge Functions — Deno typecheck"). Após decode: 82/82 typecheck limpo. - `supabase start/serve/deploy` lê config.toml como TOML; em base64 quebra o smoke "HTTP against supabase functions serve" e potencialmente o deploy. Conteúdo decodificado é válido e idêntico ao intent documentado (project_id + 24 overrides verify_jwt=false para webhooks/cron/bridges/públicas). Mesma classe de corrupção já corrigida antes (SidebarReorganized double-base64).
33de08f to
d5e3b8f
Compare
…merged) Os 3 commits remotos (decode config.toml, repara CI, type-drift) já estão na main via squash-merge do #364. Esta branch foi recriada a partir da main + as novas melhorias (regen de types, fix da busca, varredura de type-drift 486→9). Merge -s ours preserva a árvore local (as mudanças obsoletas já existem na main). https://claude.ai/code/session_01NajGAE8USvp7bsp7srMrvp
Contexto
Varredura de bugs latentes rastreados nos baselines TS/ESLint, focando type-drift real (formas de domínio divergentes da forma efetivamente produzida/consumida em runtime) — a mesma classe que já causou bugs no
compare/. Foco desta passada (decidido com o time): (1) corrigir bugs latentes de tipos/lint; (2) fechar gaps de testes. Mudanças de banco, se necessárias, virão como migration + PR (sem escrita direta em produção). Segurança/RLS e hardening pós-colapso ficaram fora desta passada.Progresso
Baseline TSC: 509 → 379 erros (medição real
tsc: 486 → 379, −107), zero regressão, ESLint baseline verde.Commit 1 —
fix(types)Alinha tipos de domínio à forma real de runtime:
SimulationOption/TechniqueSettings/SimulationProduct/SavedSimulationemsrc/types/domain/simulation.tsestavam com forma "documento" ({product, client, techniques[]}), massimulationPriceFetcherproduz a forma computada (grandTotal,techniqueId,priceSource,costPerUnit, …) consumida por clipboard,useSimulation,MockupPreview,ScenarioComparison. Redefinidos para a forma real (+image_urlno produto, + linha snake_case do DB emSavedSimulation).adaptPriceResponse— parâmetro widened paraunknown(interfaces comoCustomizationPriceResponsenão satisfazemRecord<string,unknown>). Resolve ~7 call-sites.Quote.statusagora usa oQuoteStatuscanônico (faltavam'converted'/'viewed'), corrigindo comparações sempre-falsas no funil e nas quick-actions;QuotesListPagecasta paraQuoteStatus.Auth.tsx— remove ramo mortologinStatus === 'success'(inalcançável: o card já é trocado pelo splash de sucesso no nível externo).'unverified'(o SDK só tipa'verified', mas fatores não-verificados existem em runtime após enroll interrompido).Teste novo: contrato de
simulationClipboardtravando a forma computada deSimulationOption.Verificação
npm run typecheck✅ ·npm run lint:baseline✅Próximos passos (nesta branch)
useGlobalSearch/useContextualSuggestions(feature de sugestões escrita contra modelo de filtros obsoleto —routeContextinexistente, chaves singularescategoria/cor/precoMin).supabase/config.tomlestá base64-encoded no repo (decodifica para TOML válido com 24verify_jwt=false). Nenhum outro fonte é base64. Provável artefato do tooling que é decodificado no deploy — mas se o pipeline não decodificar, os overridesverify_jwtpodem estar sendo ignorados (risco para webhooks/cron). Vale confirmar.Generated by Claude Code
Summary by cubic
Corrige type-drift em simulação, quotes, auth e MFA, reduzindo 107 erros TS (486 → 379) e liberando os gates de CI. Também decodifica configs do Supabase e melhora mensagens de erro nas recomendações, destravando typecheck e deploy.
Bug Fixes
SimulationOption,TechniqueSettings,SimulationProducteSavedSimulationpara a forma computada (grandTotal, techniqueId, priceSource, width/height, positions,image_url, linha snake_case).Quote.statususaQuoteStatuscanônico; ajuste de cast noQuotesListPage.adaptPriceResponse(resp: unknown)delega ao adapter com meta.loginStatus === 'success'.unverifiedantes do enroll (cast explícito) e melhora feedback.// rls-allowpara a linha imediatamente acima do.from(...).extractErrorMessageadiciona “(HTTP )” ao fallback.supabase/config.tomlesupabase/functions/deno.json, habilitandodeno checkesupabase serve/deploy.Tests
simulationClipboardfixando o shape computado e a ordenação porgrandTotal; baseline de typecheck/lint verde e testes de hook/edge functions passando.Written for commit d5e3b8f. Summary will update on new commits. Review in cubic