fix(types): tipa techniques.ts (-19 erros TS) — F1-1.x Onda C #6#129
Conversation
## 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.
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
WalkthroughRefatoração do módulo de técnicas do banco externo: a interface MudançasRefatoração de Tipagem e Mapeamento de Técnicas
🎯 3 (Moderada) | ⏱️ ~22 minutos 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
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
📒 Files selected for processing (2)
.tsc-baseline.jsonsrc/lib/external-db/techniques.ts
| 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, |
There was a problem hiding this comment.
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.
| 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.
There was a problem hiding this comment.
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
TechniqueRawRowand updatesinvokeExternalDbgenerics to return typed technique records instead ofRecord<string, unknown>. - Replaces prior
undefined as unknownplaceholders withnullinPromobrindPrintAreaconstruction and adjusts nullable fields inPromobrindTechnique. - Regenerates
.tsc-baseline.jsonto remove thetechniques.tserror 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
invokeExternalDbalways returnsInvokeResult<T>at the type level, but at runtime some bridge responses can omitrecords/return non-standard payloads (and this file already guards with(result.records || [])infetchPromobrindTechniques).fetchPromobrindTechniqueByIdstill doesresult.records[0]without a guard, which can throw ifrecordsis 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.
| // 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; | ||
| }; |
| const maxCoresRaw = t.max_cores ?? t.max_colors; | ||
| const maxCores = typeof maxCoresRaw === 'number' ? maxCoresRaw : typeof maxCoresRaw === 'string' ? Number(maxCoresRaw) : null; | ||
| return { |
| 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, |
…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%)**
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
Tipo
TechniqueRawRowcom schema real do bridge (mesmo do useGravacaoV2)Trocas no
invokeExternalDb:<Record<string, unknown>>→<TechniqueRawRow>emfetchPromobrindPrintAreas<PromobrindTechnique>→<TechniqueRawRow>emfetchPromobrindTechniquesefetchPromobrindTechniqueById(depoismapTechniqueFieldsconverte)Map<string, TechniqueRawRow>explícitoundefined as unknown→nullnos casts pre-existentes (technique_id, technique_code, etc) — agora compatíveis com a interfacePromobrindPrintAreaque tem esses campos comostring | null/number | nullInterface
PromobrindTechniqueaceita null em campos boolean/number opcionais (requires_color_count, price_by_color, price_by_area, is_active, display_order)Fallbacks com
??corretos:(t.codigo ?? t.code) ?? undefined,tech?.id ?? tid,(result.records || []).map(...)📊 Resultado
🟢 Baixo. Tipos refletem o schema real do bridge (já validado em PR #128).
undefined as unknown→nullé semanticamente equivalente em runtime. JS gerado idêntico.📋 Test plan
.tsc-baseline.jsonregeneradoSummary by CodeRabbit
Notas de Lançamento
Correções de Bugs
Chores