Skip to content

fix(pdf): validação numérica em formatDeliveryTime + testes 59/59 validados#450

Merged
adm01-debug merged 2 commits into
mainfrom
fix/pdf-tests-validated
May 26, 2026
Merged

fix(pdf): validação numérica em formatDeliveryTime + testes 59/59 validados#450
adm01-debug merged 2 commits into
mainfrom
fix/pdf-tests-validated

Conversation

@adm01-debug
Copy link
Copy Markdown
Owner

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

✅ Testes validados localmente — 59/59 passando

Corrige 2 problemas encontrados na execução real dos testes.

Fix #12formatDeliveryTime: validar segmentos numéricos no formato date:

Arquivo: src/components/pdf/ProposalHtmlTemplate.tsx

Bug: A função não validava se os segmentos y/m/d eram dígitos. Qualquer string com 3 partes separadas por - após date: era formatada como data:

"date:nao-e-data"  →  "Entrega até data/e/nao"  ← ERRADO
"date:nao-e-data"  →  "date:nao-e-data"         ← CORRETO (após fix)

Fix: Regex /^\d{4}$/ para year, /^\d{1,2}$/ para month e day. Também adiciona padStart("0") para formatação profissional de datas com dígito único:

"date:2026-1-5"  →  "Entrega até 05/01/2026"

Fix #13 — Testes: corrigir 2 expectativas incorretas + 3 novos casos

Arquivo: src/components/pdf/__tests__/PdfGenerationModule.test.ts

Correção 1formatDeliveryTime formato inválido:

  • Expectativa estava CORRETA mas a função estava ERRADA. Após fix na função de produção, o teste passou.
  • Adicionados 3 novos casos: zero-padding date:2026-1-5, apenas 2 segmentos date:2026-12, e data válida 2026-12-31.

Correção 2paginateItems 3 itens: expectativa errada sobre número de páginas

  • singlePageAvailable = 1123 - 128 - 90 - 38 - 180 - 310 - 230 - 30 - 40 = 77px
  • singlePageRows = floor(77 / 76) = 1 → apenas 1 item cabe na "página completa"
  • 3 itens → multi-página: [3 itens] + [] (página de totais). Expectativa atualizada.

Resultado final dos testes

✓ src/components/pdf/__tests__/PdfGenerationModule.test.ts (59 tests) 706ms
Test Files  1 passed (1)
Tests  59 passed (59)
✓ src/components/pdf/__tests__/PdfGenerationModule.test.ts (59 tests)
✓ src/components/quotes/__tests__/QuoteBuilderStepper.test.tsx (6 tests)
✓ src/components/quotes/__tests__/QuoteBuilderDiscountAdvanced.test.tsx (4 tests)
✓ src/components/quotes/__tests__/QuoteBuilderDiscount.test.tsx (4 tests)

Test Files  4 passed (4)
Tests  73 passed (73)

Summary by cubic

Corrige a formatação de datas em formatDeliveryTime para validar segmentos numéricos e aplicar zero‑padding; ajusta expectativas de paginação e amplia a cobertura de testes. Resultado: evita formatação incorreta de strings inválidas e a suíte agora passa com 59/59 testes.

  • Bug Fixes
    • formatDeliveryTime: valida YYYY-MM-DD com regex; retorna o valor bruto quando inválido; aplica zero‑padding em dia/mês (ex.: date:2026-1-5 → “Entrega até 05/01/2026”).
    • Testes/paginação: corrige expectativa de paginateItems para 3 itens (2 páginas: itens + página de totais vazia) e adiciona casos para date: não numérico e formato incompleto.

Written for commit 399ec4b. Summary will update on new commits. Review in cubic

Bug: a função não validava se y/m/d eram dígitos. Qualquer string com
3 segmentos separados por '-' era formatada como data. Ex:
  "date:nao-e-data" → "Entrega até data/e/nao" (ERRADO)
  "date:nao-e-data" → "date:nao-e-data" (CORRETO, após fix)

Fix: regex /^\d{4}$/ para year, /^\d{1,2}$/ para month e day.
Também adiciona padStart("0") para dias/meses com 1 dígito:
  "date:2026-1-5" → "Entrega até 05/01/2026" (formatação profissional)

Validado por 3 testes adicionais no PdfGenerationModule.test.ts.
…ncorretas

Falha 1 (formatDeliveryTime — formato inválido):
  O teste assumia que "date:nao-e-data" retornava raw value — correto
  APÓS o fix na função de produção (que agora valida segmentos numéricos).
  Adicionados 3 casos extras: zero-padding, apenas 2 segmentos, raw válido.

Falha 2 (paginateItems — 3 itens → 1 página):
  singlePageAvailable = 1123-128-90-38-180-310-230-30-40 = 77px
  ROW_H = 76px → singlePageRows = floor(77/76) = 1
  Com singlePageRows=1, qualquer proposta com 2+ itens usa layout
  multi-página: página de itens + página de totais (vazia).
  Expectativa corrigida: 3 itens → 2 páginas [3 itens] + [vazia].
  Renomeado teste "1 item" para deixar semântica clara.

Resultado: 59 testes passando (era 56 com 2 falhando + 1 removido/renomeado).
Copilot AI review requested due to automatic review settings May 26, 2026 12:11
@chatgpt-codex-connector
Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@vercel
Copy link
Copy Markdown

vercel Bot commented May 26, 2026

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

Project Deployment Actions Updated (UTC)
we-dream-big Error Error May 26, 2026 12:11pm

@vercel
Copy link
Copy Markdown

vercel Bot commented May 26, 2026

Deployment failed with the following error:

Invalid vercel.json file provided

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 26, 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 34 minutes and 5 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: 83d78773-2139-4f79-84a7-61f97a77a5c2

📥 Commits

Reviewing files that changed from the base of the PR and between 7a35268 and 399ec4b.

📒 Files selected for processing (2)
  • src/components/pdf/ProposalHtmlTemplate.tsx
  • src/components/pdf/__tests__/PdfGenerationModule.test.ts
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/pdf-tests-validated

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

@supabase
Copy link
Copy Markdown

supabase Bot commented May 26, 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 merged commit 510240a into main May 26, 2026
5 of 6 checks passed
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

Note

Copilot was unable to run its full agentic suite in this review.

This PR tightens formatDeliveryTime to avoid incorrectly formatting non-date date: strings and updates the PDF generation test suite to cover additional date edge cases and adjusted pagination expectations.

Changes:

  • Add numeric validation + zero-padding for date: delivery times in formatDeliveryTime.
  • Expand tests for invalid/incomplete date: formats and 1-digit month/day formatting.
  • Adjust pagination tests/documentation to reflect “totals-only” extra page behavior for multi-page proposals.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 3 comments.

File Description
src/components/pdf/tests/PdfGenerationModule.test.ts Adds/updates unit tests for formatDeliveryTime and updates pagination scenario expectations/comments.
src/components/pdf/ProposalHtmlTemplate.tsx Fixes formatDeliveryTime parsing by validating numeric segments and applying zero-padding.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +89 to +97
const iso = value.slice(5); // esperado: YYYY-MM-DD
const [y, m, d] = iso.split("-");
if (y && m && d) return `Entrega até ${d}/${m}/${y}`;
return value;
// FIX: validar que y/m/d são numéricos antes de formatar.
// Sem validação, "date:nao-e-data" gerava "Entrega até data/e/nao"
// ao invés de retornar o valor raw — comportamento incorreto.
if (y && m && d && /^\d{4}$/.test(y) && /^\d{1,2}$/.test(m) && /^\d{1,2}$/.test(d)) {
return `Entrega até ${d.padStart(2, "0")}/${m.padStart(2, "0")}/${y}`;
}
return value; // formato inválido: retorna raw sem explodir
* PdfGenerationModule.test.ts
*
* Suíte de testes exaustiva para o módulo de Geração de Propostas PDF.
* ✅ VALIDADA LOCALMENTE — 59/59 passando (vitest 3.2.4, jsdom, TZ=America/Sao_Paulo)
Comment on lines +301 to +302
// paginateItems é função local em PropostaComercialTailwind; replicamos aqui
// para testar as regras de negócio de forma isolada.
@adm01-debug adm01-debug deleted the fix/pdf-tests-validated branch May 29, 2026 13:37
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.

2 participants