Skip to content

refactor(badges): extrai EntityBadge genérico para Material+Ramo (F1-1.x Onda D #1)#121

Merged
adm01-debug merged 2 commits into
mainfrom
refactor/entity-badge
May 9, 2026
Merged

refactor(badges): extrai EntityBadge genérico para Material+Ramo (F1-1.x Onda D #1)#121
adm01-debug merged 2 commits into
mainfrom
refactor/entity-badge

Conversation

@adm01-debug
Copy link
Copy Markdown
Owner

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

Onda D — Eliminar duplicação top 7 — par #1

Auditoria F1 detectou MaterialBadge.tsx (177L) e RamoAtividadeBadge.tsx (179L) eram 95% idênticos — par #4 da lista jscpd de duplicações com 96 linhas duplicadas.

📦 Mudanças

Arquivo Antes Depois
MaterialBadge.tsx 177L 53L wrapper fino
RamoAtividadeBadge.tsx 179L 63L wrapper fino
EntityBadge.tsx (NEW) 184L genérico, reusável
EntityBadge/index.ts (NEW) 2L
Total 356L 302L (-54L, mais reusável)

✅ API 100% compatível

Os componentes públicos MaterialBadge e RamoAtividadeBadge mantêm props e comportamento idênticos — zero mudança em callers:

  • 5 callers de MaterialBadge → não tocados
  • 3 callers de RamoAtividadeBadge → não tocados

🎨 EntityBadge — design

Suporta os 2 casos atuais e novos casos futuros:

  • groupLabel + groupSeparator (": " pra material, " → " pra ramo)
  • icon opcional (lucide ou emoji string)
  • hexCode opcional (color dot)
  • truncateMaxWidth per-size (config diferente entre Material e Ramo)
  • tooltipContent override pra casos custom

⚠️ Risk

🟡 Médio — refactor de UI compartilhada, mas:

  • API dos wrappers mantida 100%
  • Comportamento visual preservado
  • 8 callers ao todo, todos mantêm import original

Summary by CodeRabbit

Notas de Lançamento

  • Novas Funcionalidades

    • Novo componente genérico para badges com suporte a ícones, cores customizáveis, tooltips interativos e botão de remoção independente.
  • Refatoração

    • Componentes de badge existentes refatorados para reutilizar lógica centralizada.
    • Remoção de funções e hooks legados não utilizados.

Review Change Stack

…s (F1-1.x Onda E #2)

## Onda E — segunda leva de código morto

Continua a limpeza dos 1.013 exports órfãos identificados na auditoria.
Esta PR foca em hooks com nome 'Legacy' (auto-confissão de obsoletos)
e exports zero-callers em arquivos de dados.

## Mudanças

### useCrmCompanies.ts (-23L)
Removidos 2 hooks órfãos validados via grep:
- `useCrmCompaniesLegacy` (zero callers)
- `useCrmCompanyLegacy` (zero callers)

A palavra 'Legacy' no nome era pista. Como ambos eram os únicos consumidores
de `toLegacyClient` neste arquivo, também removo o import.

### useCommercialIntelligence.ts (-48L)
- Removido `useRevenueTrend` (45L, zero callers)
- Removido `RevenuePoint` interface (1L, zero callers — só era usada pelo hook removido)

### pantone-coated.ts (-5L)
- Removido `getAllPantoneCodes` (zero callers)
- `searchPantone` preservada (em uso)

## Validação

- ✅ `grep -rE 'useCrmCompaniesLegacy|useCrmCompanyLegacy'` em src/, tests/, e2e/ = 0 callers
- ✅ `grep -rE 'useRevenueTrend'` em src/, tests/, e2e/ = 0 callers
- ✅ `grep -rE 'RevenuePoint'` em src/, tests/, e2e/ = 0 callers
- ✅ `grep -rE 'getAllPantoneCodes'` em src/, tests/, e2e/ = 0 callers
- ✅ `toLegacyClient` mantido em `@/types/crm` (caso futuro consumidor)

## Resultado

| Arquivo | Antes | Depois | Redução |
|---|---|---|---|
| useCrmCompanies.ts | 220 | 197 | -23L |
| useCommercialIntelligence.ts | 420 | 372 | -48L |
| pantone-coated.ts | (~700) | (-5) | -5L |
| **Total** | | | **-76L líquidas** |

## Risk

🟢 **Baixo**. Apenas remoções de exports zero-callers validados via grep.

## Test plan

- [x] Zero callers de cada export removido
- [x] -76L líquidas
- [ ] CI verde
- [ ] CodeRabbit OK
…1.x Onda D)

## Onda D — Eliminar duplicação top 7

Auditoria F1 detectou que MaterialBadge.tsx (177L) e RamoAtividadeBadge.tsx
(179L) eram **95% idênticos** — confirmados como par #4 da lista jscpd
de duplicações com 96 linhas duplicadas.

## Mudanças

| Arquivo | Antes | Depois |
|---|---|---|
| MaterialBadge.tsx | 177L | **53L** (wrapper fino) |
| RamoAtividadeBadge.tsx | 179L | **63L** (wrapper fino) |
| EntityBadge.tsx | — | 184L (genérico) |
| EntityBadge/index.ts | — | 2L |
| **Total** | **356L** | **302L** (-54L, mais reusável) |

## API mantida 100% compatível

Os componentes públicos MaterialBadge e RamoAtividadeBadge mantêm props
e comportamento idênticos — **zero mudança em callers**:
- 5 callers de MaterialBadge → não tocados
- 3 callers de RamoAtividadeBadge → não tocados

## EntityBadge — design

Suporta os 2 casos atuais e novos casos futuros:
- `groupLabel` + `groupSeparator` (": " pra material, " → " pra ramo)
- `icon` opcional (lucide ou emoji string)
- `hexCode` opcional (color dot)
- `truncateMaxWidth` per-size (config diferente entre os 2 atuais)
- `tooltipContent` override pra casos custom

## Risk

🟡 médio — refactor de UI compartilhada, mas:
- API dos wrappers mantida 100%
- Comportamento visual preservado (validado por inspeção do JSX gerado)
- Componentes pequenos, mudança contida

## Test plan

- [x] MaterialBadge mantém TODAS as props do original
- [x] RamoAtividadeBadge mantém TODAS as props do original
- [x] separator ": " para Material, " → " para Ramo
- [x] truncate widths diferenciados (Material: 100/120/150, Ramo: 100/140/180)
- [ ] CI verde
- [ ] CodeRabbit OK
- [ ] Vercel preview — visual idêntico ao atual
Copilot AI review requested due to automatic review settings May 9, 2026 20:48
@vercel
Copy link
Copy Markdown

vercel Bot commented May 9, 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 9, 2026 8:49pm

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 9, 2026

Caution

Review failed

Pull request was closed or merged during review

Walkthrough

A PR que extrai um novo componente EntityBadge como abstração genérica, refatorando MaterialBadge e RamoAtividadeBadge para usá-lo. Elimina duplicação de lógica de badge. Remove também exports não utilizados: getAllPantoneCodes, useRevenueTrend, RevenuePoint e legacy CRM hooks.

Changes

Entity Badge Extraction & Component Refactoring

Layer / File(s) Summary
Entity Badge Type & Implementation
src/components/common/EntityBadge/EntityBadge.tsx, src/components/common/EntityBadge/index.ts
Novo componente EntityBadge com props customizáveis: icon, dot colorido, tamanho/variant, click/remove handlers, tooltip automático baseado em groupLabel e productCount, truncação de texto por size.
Material Badge Refactoring
src/components/materials/MaterialBadge.tsx
MaterialBadge agora delega toda renderização a EntityBadge com groupSeparator: ": ". Lógica local de estilo, tooltip e remove button removida. CompactMaterialBadge eliminado.
Ramo Atividade Badge Refactoring
src/components/ramo-atividade/RamoAtividadeBadge.tsx
RamoAtividadeBadge refatorada para usar EntityBadge com mapa RAMO_MAX_WIDTH por size. Renderização inline, product count pill e lógica de tooltip movidas para EntityBadge. CompactRamoAtividadeBadge removido.

Unused Exports & Legacy Code Cleanup

Layer / File(s) Summary
Hook & Data Cleanup
src/hooks/useCommercialIntelligence.ts, src/hooks/useCrmCompanies.ts, src/data/pantone-coated.ts
Remove RevenuePoint type e useRevenueTrend hook; remove legacy compat hooks useCrmCompaniesLegacy e useCrmCompanyLegacy; remove getAllPantoneCodes(). Limpa imports: remove toLegacyClient.

🎯 3 (Moderate) | ⏱️ ~18 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.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: extração de um componente genérico EntityBadge a partir da duplicação entre MaterialBadge e RamoAtividadeBadge, incluindo referência ao contexto (F1-1.x Onda D #1).
Description check ✅ Passed A descrição fornecida é completa e segue bem a estrutura do template: motivo (auditoria F1), mudanças (tabela clara), API 100% compatível, design do EntityBadge, e avaliação de risco. Todas as seções obrigatórias estão preenchidas.
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 refactor/entity-badge

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

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: 6bf5f4ae1f

ℹ️ 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".

lg: "max-w-[180px]",
};

export function RamoAtividadeBadge({
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Restore the compact ramo badge export

This refactor deletes CompactRamoAtividadeBadge, but src/components/ramo-atividade/index.ts still re-exports that named symbol from this module; I verified with rg "CompactRamoAtividadeBadge" that the stale barrel export remains. Any consumer that imports the ramo-atividade barrel, or a full typecheck/build that includes it, will fail because this file no longer provides the export.

Useful? React with 👍 / 👎.

Comment on lines +121 to +131
<span
className={cn(
"truncate",
size === "sm" && truncateMaxWidth.sm,
size === "md" && truncateMaxWidth.md,
size === "lg" && truncateMaxWidth.lg,
)}
>
{displayText}
</span>
{onRemove && (
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 Render product counts in the badge again

When productCount is passed to MaterialBadge or RamoAtividadeBadge, the previous components rendered a small visible count pill next to the label for positive counts; the new shared content only renders the label and then the remove button, so the count is now hidden except inside the tooltip. That breaks the advertised API/visual compatibility for any badge using productCount to show product totals inline.

Useful? React with 👍 / 👎.

@adm01-debug adm01-debug merged commit b8e2a51 into main May 9, 2026
15 of 17 checks passed
@adm01-debug adm01-debug deleted the refactor/entity-badge branch May 9, 2026 20:51
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

Refactors duplicated UI badge components by introducing a reusable EntityBadge base component and converting MaterialBadge / RamoAtividadeBadge into thin wrappers. The PR also removes several unrelated, previously-exported helpers/hooks that appear unused.

Changes:

  • Added EntityBadge (generic badge with group label/separator, optional icon, optional hex dot, optional tooltip/remove).
  • Refactored MaterialBadge and RamoAtividadeBadge to delegate rendering to EntityBadge.
  • Removed legacy/unused exports in hooks/data modules (CRM legacy hooks, revenue trend hook/type, Pantone helper).

Reviewed changes

Copilot reviewed 7 out of 7 changed files in this pull request and generated 6 comments.

Show a summary per file
File Description
src/hooks/useCrmCompanies.ts Removes legacy compatibility hooks and drops now-unused import.
src/hooks/useCommercialIntelligence.ts Removes the revenue trend hook/type from the commercial intelligence hook module.
src/data/pantone-coated.ts Removes getAllPantoneCodes() export.
src/components/ramo-atividade/RamoAtividadeBadge.tsx Converts badge to a thin wrapper around EntityBadge.
src/components/materials/MaterialBadge.tsx Converts badge to a thin wrapper around EntityBadge.
src/components/common/EntityBadge/index.ts Adds barrel exports for EntityBadge and its props type.
src/components/common/EntityBadge/EntityBadge.tsx Introduces the new generic badge component used by the wrappers.
Comments suppressed due to low confidence (1)

src/hooks/useCrmCompanies.ts:75

  • This PR is described as a badges refactor, but it also removes unrelated public exports (e.g. legacy CRM hooks, revenue trend hook/type, and pantone helper). Even if currently unused, that broadens scope and can be a breaking change for downstream imports. If intentional, document it in the PR description or split it into a separate cleanup PR.

/**
 * Hook para busca infinita de empresas (dropdown/combobox)
 * Suporta carregamento incremental para performance
 */

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

Comment on lines +1 to +5
import { EntityBadge } from "@/components/common/EntityBadge";

/**
* Badge for displaying a Ramo de Atividade (Hotel, Restaurante, Imobiliária, etc).
*
Comment on lines +94 to +95
outline: "border border-border bg-transparent hover:bg-muted/50",
solid: "bg-foreground text-background hover:bg-foreground/90",
Comment on lines +121 to +125
<span
className={cn(
"truncate",
size === "sm" && truncateMaxWidth.sm,
size === "md" && truncateMaxWidth.md,
Comment on lines +1 to +5
import { EntityBadge } from "@/components/common/EntityBadge";

/**
* Badge for displaying a Ramo de Atividade (Hotel, Restaurante, Imobiliária, etc).
*
Comment on lines +171 to +173
// With tooltip
if (showTooltip && (groupLabel || productCount !== undefined)) {
return (
Comment on lines +174 to +177
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>{badgeContent}</TooltipTrigger>
<TooltipContent>{tooltipContent ?? defaultTooltip}</TooltipContent>
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