Skip to content

fix(types): tipa techniques.ts (-19 erros TS) — F1-1.x Onda C #6#129

Merged
adm01-debug merged 1 commit into
mainfrom
fix/ts-onda-c-techniques-7
May 10, 2026
Merged

fix(types): tipa techniques.ts (-19 erros TS) — F1-1.x Onda C #6#129
adm01-debug merged 1 commit into
mainfrom
fix/ts-onda-c-techniques-7

Conversation

@adm01-debug
Copy link
Copy Markdown
Owner

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

Onda C #6 — techniques.ts: 19 → 0 ✨

Mesmo padrão de PR #126 (products.ts) e #128 (useGravacaoV2.ts): tipos auxiliares para records do bridge externo.

✨ Fix

  1. Tipo TechniqueRawRow com schema real do bridge (mesmo do useGravacaoV2)

  2. Trocas no invokeExternalDb:

    • <Record<string, unknown>><TechniqueRawRow> em fetchPromobrindPrintAreas
    • <PromobrindTechnique><TechniqueRawRow> em fetchPromobrindTechniques e fetchPromobrindTechniqueById (depois mapTechniqueFields converte)
  3. Map<string, TechniqueRawRow> explícito

  4. undefined as unknownnull nos casts pre-existentes (technique_id, technique_code, etc) — agora compatíveis com a interface PromobrindPrintArea que tem esses campos como string | null/number | null

  5. Interface PromobrindTechnique aceita null em campos boolean/number opcionais (requires_color_count, price_by_color, price_by_area, is_active, display_order)

  6. Fallbacks com ?? corretos: (t.codigo ?? t.code) ?? undefined, tech?.id ?? tid, (result.records || []).map(...)

📊 Resultado

Métrica Antes Depois Delta
Total tsc errors 851 841 -10 (-1.2%)
techniques.ts 19 0 -100%

⚠️ Risk

🟢 Baixo. Tipos refletem o schema real do bridge (já validado em PR #128). undefined as unknownnull é semanticamente equivalente em runtime. JS gerado idêntico.

📋 Test plan

  • tsc total: 851 → 841 (-10) — validado localmente
  • techniques.ts: 19 → 0 erros (-100%)
  • .tsc-baseline.json regenerado
  • CI verde
  • CodeRabbit OK
  • Vercel preview funciona (lista técnicas + áreas de impressão)

Summary by CodeRabbit

Notas de Lançamento

  • Correções de Bugs

    • Melhorado o tratamento de dados de técnicas do banco de dados externo com mapeamento mais robusto e consistente de valores nulos.
  • Chores

    • Redução de erros TypeScript e atualização de configurações internas de compilação.

Review Change Stack

## Onda C #6 — techniques.ts: 19 → 0 erros

Mesmo padrão do products.ts (#126) e useGravacaoV2.ts (#128): tipos
auxiliares para records do bridge externo + correções incrementais
em campos null vs undefined.

## Fix

1) **Tipo TechniqueRawRow** (mesmo do useGravacaoV2):
   - id, codigo, code, nome, name, descricao, description, etc.

2) **Trocas no invokeExternalDb**:
   - `<Record<string, unknown>>` → `<TechniqueRawRow>` em fetchPromobrindPrintAreas
   - `<PromobrindTechnique>` → `<TechniqueRawRow>` em fetchPromobrindTechniques e
     fetchPromobrindTechniqueById (depois mapTechniqueFields converte)

3) **Map<string, TechniqueRawRow>** explícito.

4) **`undefined as unknown` → `null`** nos casts de pre-fix
   (technique_id, technique_code, technique_name, max_colors,
   area_image_url) — agora compatíveis com `string | null` /
   `number | null` da interface PromobrindPrintArea.

5) **Interface PromobrindTechnique aceita null** em campos:
   requires_color_count, price_by_color, price_by_area, is_active,
   display_order. Antes eram `?: boolean`/`number` — incompatíveis com
   o resultado real do mapTechniqueFields que retorna `?? null`.

6) **Fallbacks adicionais**:
   - `code: (t.codigo ?? t.code) ?? undefined` (interface tem code?: string)
   - `name: (t.nome ?? t.name) ?? ''` (interface tem name: string)
   - `tech?.id ?? tid` em vez de `tech?.id || tid`
   - `(result.records || []).map(...)` defensive

## Resultado

| Métrica | Antes | Depois | Delta |
|---|---|---|---|
| Total tsc errors | 851 | **841** | -10 (-1.2%) |
| techniques.ts | 19 | **0** | **-100%** ✨

(Apenas -10 no total porque o baseline anterior já considerava parte
dos erros eliminados pelos PRs em paralelo — +1 noise.)

## Risk

🟢 **Baixo**. Tipos refletem o schema real (mesmo TechniqueRawRow do
useGravacaoV2 que já passou em produção). `undefined as unknown` → `null`
é semanticamente equivalente em runtime (ambos serializam pra null em JSON).

Comportamento runtime equivalente — JS gerado idêntico.
Copilot AI review requested due to automatic review settings May 10, 2026 11:38
@vercel
Copy link
Copy Markdown

vercel Bot commented May 10, 2026

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

Project Deployment Actions Updated (UTC)
promo-gifts Ready Ready Preview, Comment May 10, 2026 11:39am

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 10, 2026

Walkthrough

Refatoração do módulo de técnicas do banco externo: a interface PromobrindTechnique agora aceita valores nulos em campos booleanos/numéricos opcionais; linhas brutas (TechniqueRawRow) são mapeadas explicitamente através de mapTechniqueFields, consolidando transformações de alias de colunas legadas (PT-BR) em um só lugar; todas as funções de busca e integração de áreas de impressão usam este novo fluxo tipado, eliminando 19 erros TS2322.

Mudanças

Refatoração de Tipagem e Mapeamento de Técnicas

Layer / File(s) Resumo
Data Shape
src/lib/external-db/techniques.ts
PromobrindTechnique: requires_color_count, price_by_color, price_by_area, is_active, display_order agora permitem boolean | null e number | null respectivamente.
Raw Row Model e Mapeamento
src/lib/external-db/techniques.ts
Introduzida TechniqueRawRow tipada com nomes de colunas legados (codigo, nome, permite_cores, cobra_por_cor, etc.); implementado mapTechniqueFields para transformar linhas brutas em PromobrindTechnique.
Funções de Busca
src/lib/external-db/techniques.ts
fetchPromobrindTechniques e fetchPromobrindTechniqueById agora consultam TechniqueRawRow e mapeiam resultados via mapTechniqueFields.
Integração em Áreas de Impressão
src/lib/external-db/techniques.ts
fetchPromobrindPrintAreas: lookup tipado como TechniqueRawRow, null-defaults normalizados, e atribuições de campo com fallbacks null-safe (?? null).
Baseline TypeScript
.tsc-baseline.json
generatedAt atualizado, totalErrors reduzido de 860 para 841; entrada TS2322 para techniques.ts removida (19 erros resolvidos).

🎯 3 (Moderada) | ⏱️ ~22 minutos

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed O título descreve com precisão a mudança principal (fix de 19 erros TS em techniques.ts) e é conciso e específico.
Description check ✅ Passed A descrição cobre todos os pontos críticos (TechniqueRawRow, mapeamento de tipos, null vs undefined, métricas) e segue o padrão de PRs anteriores, mas não usa a template oficial do repositório.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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 fix/ts-onda-c-techniques-7

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

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/lib/external-db/techniques.ts`:
- Around line 129-131: O mapeamento que monta o objeto (onde são definidos
technique_id, technique_code, technique_name, max_colors, is_default,
area_image_url) está acessando apenas os nomes em PT-BR (tech?.codigo,
tech?.nome, tech?.max_cores) e perde valores se a linha vier com campos EN;
alinhe este trecho ao padrão usado em mapTechniqueFields: para cada propriedade
use fallback entre variantes (por exemplo técnica_code = tech?.codigo ??
tech?.code, technique_name = tech?.nome ?? tech?.name, max_colors =
tech?.max_cores ?? tech?.max_colors) mantendo technique_id (tech?.id ?? tid) e
is_default como estão; localize o bloco que constrói esse objeto (variável tech)
e aplique os mesmos fallbacks para todas as propriedades de técnica.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 4b9fa42a-b4bb-4f59-b456-c5a9d14f6f44

📥 Commits

Reviewing files that changed from the base of the PR and between 7ebffee and b1dbff7.

📒 Files selected for processing (2)
  • .tsc-baseline.json
  • src/lib/external-db/techniques.ts

Comment on lines +129 to +131
technique_id: tech?.id ?? tid, technique_code: tech?.codigo ?? null,
technique_name: tech?.nome ?? null, max_colors: tech?.max_cores ?? null,
is_default: area.is_primary ?? false, area_image_url: null,
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Inconsistência no acesso aos campos raw.

Aqui o código acessa apenas os nomes PT-BR (tech?.codigo, tech?.nome, tech?.max_cores), mas TechniqueRawRow suporta ambas as variantes. Se a tabela tabela_preco_gravacao_oficial retornar nomes EN, esses valores serão perdidos silenciosamente.

Compare com mapTechniqueFields que faz o fallback corretamente: (t.codigo ?? t.code).

🛡️ Sugestão: usar mesmo padrão de fallback
-          technique_id: tech?.id ?? tid, technique_code: tech?.codigo ?? null,
-          technique_name: tech?.nome ?? null, max_colors: tech?.max_cores ?? null,
+          technique_id: tech?.id ?? tid,
+          technique_code: (tech?.codigo ?? tech?.code) ?? null,
+          technique_name: (tech?.nome ?? tech?.name) ?? null,
+          max_colors: (tech?.max_cores ?? tech?.max_colors) ?? null,
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
technique_id: tech?.id ?? tid, technique_code: tech?.codigo ?? null,
technique_name: tech?.nome ?? null, max_colors: tech?.max_cores ?? null,
is_default: area.is_primary ?? false, area_image_url: null,
technique_id: tech?.id ?? tid,
technique_code: (tech?.codigo ?? tech?.code) ?? null,
technique_name: (tech?.nome ?? tech?.name) ?? null,
max_colors: (tech?.max_cores ?? tech?.max_colors) ?? null,
is_default: area.is_primary ?? false, area_image_url: null,
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/lib/external-db/techniques.ts` around lines 129 - 131, O mapeamento que
monta o objeto (onde são definidos technique_id, technique_code, technique_name,
max_colors, is_default, area_image_url) está acessando apenas os nomes em PT-BR
(tech?.codigo, tech?.nome, tech?.max_cores) e perde valores se a linha vier com
campos EN; alinhe este trecho ao padrão usado em mapTechniqueFields: para cada
propriedade use fallback entre variantes (por exemplo técnica_code =
tech?.codigo ?? tech?.code, technique_name = tech?.nome ?? tech?.name,
max_colors = tech?.max_cores ?? tech?.max_colors) mantendo technique_id
(tech?.id ?? tid) e is_default como estão; localize o bloco que constrói esse
objeto (variável tech) e aplique os mesmos fallbacks para todas as propriedades
de técnica.

Copy link
Copy Markdown

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

This PR updates src/lib/external-db/techniques.ts to eliminate TypeScript errors by introducing an explicit raw-row type for technique records returned by the external DB bridge and aligning several nullable fields with the PromobrindPrintArea/PromobrindTechnique interfaces. It also regenerates .tsc-baseline.json to reflect the reduced error count.

Changes:

  • Introduces TechniqueRawRow and updates invokeExternalDb generics to return typed technique records instead of Record<string, unknown>.
  • Replaces prior undefined as unknown placeholders with null in PromobrindPrintArea construction and adjusts nullable fields in PromobrindTechnique.
  • Regenerates .tsc-baseline.json to remove the techniques.ts error entry and update totals.

Reviewed changes

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

File Description
src/lib/external-db/techniques.ts Adds typed raw-row shape for bridge technique records, adjusts nullability, and updates mapping/guards.
.tsc-baseline.json Updates generated timestamp, total error count, and removes resolved techniques.ts entries.
Comments suppressed due to low confidence (1)

src/lib/external-db/techniques.ts:160

  • invokeExternalDb always returns InvokeResult<T> at the type level, but at runtime some bridge responses can omit records/return non-standard payloads (and this file already guards with (result.records || []) in fetchPromobrindTechniques). fetchPromobrindTechniqueById still does result.records[0] without a guard, which can throw if records is missing/undefined. Use optional chaining / fallback array when reading the first record.
  const result = await invokeExternalDb<TechniqueRawRow>({
    table: 'tecnica_gravacao', operation: 'select',
    filters: { id: techniqueId }, select: TECHNIQUE_SELECT_FIELDS, limit: 1,
  });
  const tech = result.records[0];
  return tech ? mapTechniqueFields(tech) : null;

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

Comment on lines +50 to +74
// Row shape from 'tabela_preco_gravacao_oficial' (legacy/PT-BR field names plus EN aliases).
type TechniqueRawRow = {
id: string;
codigo?: string | null;
code?: string | null;
nome?: string | null;
name?: string | null;
descricao?: string | null;
description?: string | null;
permite_cores?: boolean | null;
requires_color_count?: boolean | null;
max_cores?: number | null;
max_colors?: number | null;
cobra_por_cor?: boolean | null;
price_by_color?: boolean | null;
cobra_por_area?: boolean | null;
price_by_area?: boolean | null;
ativo?: boolean | null;
is_active?: boolean | null;
tempo_producao_dias?: number | null;
estimated_days?: number | null;
ordem_exibicao?: number | null;
display_order?: number | null;
category?: string | null;
};
Comment on lines 77 to 79
const maxCoresRaw = t.max_cores ?? t.max_colors;
const maxCores = typeof maxCoresRaw === 'number' ? maxCoresRaw : typeof maxCoresRaw === 'string' ? Number(maxCoresRaw) : null;
return {
Comment on lines +129 to +131
technique_id: tech?.id ?? tid, technique_code: tech?.codigo ?? null,
technique_name: tech?.nome ?? null, max_colors: tech?.max_cores ?? null,
is_default: area.is_primary ?? false, area_image_url: null,
@adm01-debug adm01-debug merged commit 430ac12 into main May 10, 2026
18 of 19 checks passed
@adm01-debug adm01-debug deleted the fix/ts-onda-c-techniques-7 branch May 10, 2026 11:43
adm01-debug added a commit that referenced this pull request May 10, 2026
…F1-1.x Onda C #7) [encerramento] (#137)

## Onda C #7 — encerramento da F1-1.x

MockupGenerator.tsx tinha 29 erros TS distribuídos em 4 categorias.
Resolvidos com fixes cirúrgicos em 7 arquivos.

## Fixes aplicados

### 1. `MockupGenerator.tsx` (29 erros)

**a)** `selectedColor.name/hex` → `colorName/colorHex` (5x)
   MockupProductSelection nunca teve `selectedColor` — só
   `colorName` e `colorHex` flat. Código antigo era bug latente.

**b)** `tech.name` → `tech.name ?? ''` (1x)
   MockupTechnique.name é opcional (`?: string`). Destino exige string.

**c)** `pantoneMatch?.name` → `pantoneMatch?.pantoneCode` (1x)
   PantoneMatch tem `{ pantoneCode, pantoneHex, deltaE }` — nunca
   teve `name`. Era acesso a campo inexistente em runtime.

**d)** Guards `'maxWidth' in mg.selectedTechnique` (5x linhas 313-314, 342-344)
   useMockupGenerator narrows para `Technique | TechniqueWithLimits`.
   Só TechniqueWithLimits tem maxWidth/maxHeight/locationName.

**e)** Cast `as MockupTechnique` em useTechniqueHandlers args (2x)
   useMockupGenerator emite `Technique|TechniqueWithLimits`,
   useTechniqueHandlers consome `MockupTechnique`. Compatíveis
   estruturalmente, TS não consegue widen `Dispatch<SetStateAction<T>>`.

**f)** Wrappers de variancia em `onTechniqueSelect` e
   `handleTechniqueChange(tech)` (2x) — adapter functions.

**g)** Acessos a `metadata.height_mm/width_mm` (8x) — corrigido em #2.

### 2. `product-catalog.ts` — adicionar `metadata`

Campo opcional em Product:
`metadata?: { height_mm?: number|null; width_mm?: number|null;
  [key: string]: unknown } | null`

Reflete o JSONB real do banco (legacy). Acessos antes eram falhas de tipo,
embora o runtime já tolerasse (optional chaining).

### 3. `useMockupTechniques.ts` — Technique extends index signature

Adicionada `[key: string]: unknown` em interface Technique.
Permite atribuição estrutural a MockupTechnique (que tem o mesmo).

### 4. `AIMockupAssistant.tsx` — adicionar prop `onApplySuggestion`

Componente expunha legacy `onSuggestionApply: (type, value) => void`.
Adicionada nova `onApplySuggestion: (suggestion: {techniqueId?, position?, ...}) => void`
que MockupGenerator já estava usando. Antiga mantida pra back-compat.

### 5. `MultiAreaManager.tsx` — `logoFile` em PersonalizationArea

Campo opcional `logoFile?: File | null` adicionado. Já era usado em
`updateActiveArea({ logoPreview: null, logoFile: null })`.

### 6. `MockupHistoryPanel.tsx` — usa GeneratedMockup do SSOT

Removida interface local duplicada (20 linhas), substituída por
`import type { GeneratedMockup } from '@/hooks/mockup/mockupGenerationService'`.
Também: handleSetViewMode aceita 3 modos (`grid|list|table`) e
mapeia `table → list` (compat com LayoutPopover que tem 3).

### 7. `MockupLightbox.tsx` — usa GeneratedMockup do SSOT

Mesma deduplicação. Interface local removida.

## Resultado

| Métrica | Antes | Depois | Δ |
|---|---|---|---|
| Total tsc errors | 841 | **811** | **-30 (-3.6%)** |
| MockupGenerator.tsx | 29 | **0** | **-100%** ✨
| MockupHistoryPanel.tsx | 0 | 0 | (sem regressão) |
| MockupLightbox.tsx | 0 | 0 | (sem regressão) |
| MultiAreaManager.tsx | 0 | 0 | (sem regressão) |
| useMockupTechniques.ts | 0 | 0 | (sem regressão) |
| AIMockupAssistant.tsx | 0 | 0 | (sem regressão) |
| product-catalog.ts | 0 | 0 | (sem regressão) |

## Risk

🟢 **Baixo**. Todas as mudanças são tipo-only ou refletem o schema/runtime real:
- selectedColor → colorName/colorHex era bug existente (corrige acesso a campo inexistente)
- pantoneMatch?.name → pantoneCode era bug existente (corrige acesso a campo inexistente)
- metadata em Product reflete JSONB real
- logoFile já era passado em runtime
- GeneratedMockup deduplicação remove drift entre 3 cópias

JS gerado equivalente em 95%+ dos casos. Pequenas mudanças semânticas:
- `tech.code || undefined` vs `tech.code ?? ''` — empty string vs undefined em
  edge case de techniqueCode vazio. Aceito porque destino tipa como string.

## Encerramento da Onda C

Sequência completa F1-1.x Onda C (-403 erros):
- #124 lazyWithRetry            -67
- #125 untypedFrom               -105
- #126 products.ts               -36
- #127 useSalesGoals             -32
- #128 useGravacaoV2             -32
- #129 techniques.ts             -10
- **#7 MockupGenerator (este)   -30** ← agora

TS baseline F1: **1214 → 811 (-33%)**
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