Skip to content

Auditoria: corrige bugs latentes de tipos + cobertura de testes (rumo a produção)#364

Merged
adm01-debug merged 3 commits into
mainfrom
claude/project-comprehensive-audit-KhZcD
May 26, 2026
Merged

Auditoria: corrige bugs latentes de tipos + cobertura de testes (rumo a produção)#364
adm01-debug merged 3 commits into
mainfrom
claude/project-comprehensive-audit-KhZcD

Conversation

@adm01-debug
Copy link
Copy Markdown
Owner

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

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:

  • Simulação (~93 erros, 5 arquivos)SimulationOption/TechniqueSettings/SimulationProduct/SavedSimulation em src/types/domain/simulation.ts estavam com forma "documento" ({product, client, techniques[]}), mas simulationPriceFetcher produz a forma computada (grandTotal, techniqueId, priceSource, costPerUnit, …) consumida por clipboard, useSimulation, MockupPreview, ScenarioComparison. Redefinidos para a forma real (+ image_url no produto, + linha snake_case do DB em SavedSimulation).
  • adaptPriceResponse — parâmetro widened para unknown (interfaces como CustomizationPriceResponse não satisfazem Record<string,unknown>). Resolve ~7 call-sites.
  • QuotesQuote.status agora usa o QuoteStatus canônico (faltavam 'converted'/'viewed'), corrigindo comparações sempre-falsas no funil e nas quick-actions; QuotesListPage casta para QuoteStatus.
  • Auth.tsx — remove ramo morto loginStatus === 'success' (inalcançável: o card já é trocado pelo splash de sucesso no nível externo).
  • MFA — cast para detectar fatores TOTP 'unverified' (o SDK só tipa 'verified', mas fatores não-verificados existem em runtime após enroll interrompido).

Teste novo: contrato de simulationClipboard travando a forma computada de SimulationOption.

Verificação

  • npm run typecheck ✅ · npm run lint:baseline
  • Testes afetados: simulação + funil de quotes (18) + clipboard (3) ✅

Próximos passos (nesta branch)

  • Cluster useGlobalSearch/useContextualSuggestions (feature de sugestões escrita contra modelo de filtros obsoleto — routeContext inexistente, chaves singulares categoria/cor/precoMin).
  • Demais clusters TS2339 (inventory/risk, intelligence, advanced-price-search), null-safety (TS18048).
  • Build + Playwright E2E (smoke/critical/flows) como validação final.

⚠️ Anomalia a confirmar (não-bloqueante)

supabase/config.toml está base64-encoded no repo (decodifica para TOML válido com 24 verify_jwt=false). Nenhum outro fonte é base64. Provável artefato do tooling que é decodificado no deploy — mas se o pipeline não decodificar, os overrides verify_jwt podem 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

    • Simulação: redefine SimulationOption, TechniqueSettings, SimulationProduct e SavedSimulation para a forma computada (grandTotal, techniqueId, priceSource, width/height, positions, image_url, linha snake_case).
    • Quotes: Quote.status usa QuoteStatus canônico; ajuste de cast no QuotesListPage.
    • Preços: adaptPriceResponse(resp: unknown) delega ao adapter com meta.
    • Auth: remove ramo morto loginStatus === 'success'.
    • MFA: remove fatores TOTP unverified antes do enroll (cast explícito) e melhora feedback.
    • Sidebar: move // rls-allow para a linha imediatamente acima do .from(...).
    • Recomendações: extractErrorMessage adiciona “(HTTP )” ao fallback.
    • Supabase: decodifica supabase/config.toml e supabase/functions/deno.json, habilitando deno check e supabase serve/deploy.
  • Tests

    • Contrato do simulationClipboard fixando o shape computado e a ordenação por grandTotal; 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

@vercel
Copy link
Copy Markdown

vercel Bot commented May 25, 2026

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

Project Deployment Actions Updated (UTC)
we-dream-big Ready Ready Preview, Comment May 26, 2026 2:13am

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 25, 2026

Warning

Review limit reached

@adm01-debug, we couldn't start this review because you've reached your PR review rate limit.

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 @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 50f769f3-37a4-4594-ada9-457dc2001cb7

📥 Commits

Reviewing files that changed from the base of the PR and between e14f8f0 and d5e3b8f.

📒 Files selected for processing (11)
  • .tsc-baseline.json
  • src/components/layout/SidebarReorganized.tsx
  • src/components/security/MfaEnrollmentDialog.tsx
  • src/hooks/intelligence/useAIRecommendations.ts
  • src/hooks/quotes/quoteTypes.ts
  • src/lib/personalization/adapters/price-response.adapter.ts
  • src/pages/auth/Auth.tsx
  • src/pages/quotes/QuotesListPage.tsx
  • src/types/domain/simulation.ts
  • supabase/config.toml
  • tests/hooks/simulation/simulationClipboard.test.ts
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/project-comprehensive-audit-KhZcD

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

@supabase
Copy link
Copy Markdown

supabase Bot commented May 25, 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 ↗︎.

@adm01-debug adm01-debug marked this pull request as ready for review May 26, 2026 00:07
Copilot AI review requested due to automatic review settings May 26, 2026 00:07
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.

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 SavedSimulation para o shape persistido.
  • Padroniza Quote.status para o QuoteStatus canônico e ajusta chamada de bulk status update na listagem.
  • Amplia adaptPriceResponse para aceitar unknown e adiciona teste de contrato para simulationClipboard.

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.

Comment on lines +45 to +50
beforeEach(() => {
vi.clearAllMocks();
vi.useFakeTimers();
Object.assign(navigator, { clipboard: { writeText } });
});

Comment on lines +9 to +10
import { describe, it, expect, vi, beforeEach } from 'vitest';
import type { SimulationOption, Product } from '@/types/simulation';
Comment on lines +226 to 228
export function adaptPriceResponse(resp: unknown): CustomizationPriceFlat {
return adaptPriceResponseWithMeta(resp as Record<string, unknown> | null | undefined).flat;
}
Comment on lines 285 to 289
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++;
Comment on lines +58 to 64
// 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 });

Comment on lines +72 to +86
/** 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;
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: 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();
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 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 👍 / 👎.

claude added 3 commits May 25, 2026 23:12
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).
@adm01-debug adm01-debug force-pushed the claude/project-comprehensive-audit-KhZcD branch from 33de08f to d5e3b8f Compare May 26, 2026 02:12
@adm01-debug adm01-debug merged commit 0c4bb4b into main May 26, 2026
6 of 9 checks passed
adm01-debug pushed a commit that referenced this pull request May 26, 2026
…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
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