Repository navigation
Revamp UI ux - #18
Revamp UI ux#18
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
There was a problem hiding this comment.
Pull request overview
Atualiza a vitrine e o admin com um “refresh” de UI/UX e novos fluxos operacionais para manutenção do catálogo (importação via CSV e exclusão em lote).
Changes:
- Novo fluxo de importação de produtos via CSV (CLI + rota admin) e sincronização com Supabase.
- Admin: exclusão em lote de produtos e ajustes em atendimento/canais/mensagens.
- Refresh visual e de conteúdo em home, catálogo, produto, carrinho, contato e componentes globais (header/footer/WhatsApp).
Reviewed changes
Copilot reviewed 28 out of 29 changed files in this pull request and generated 12 comments.
Show a summary per file
| File | Description |
|---|---|
| scripts/import-products-csv.cjs | Script CLI para importar CSV e atualizar catalog-seed.json (com opção de publish). |
| package.json | Adiciona scripts npm para importar/sincronizar CSV. |
| package-lock.json | Atualização do lockfile (remoções de campos libc). |
| lib/products-csv-import.js | Parser/normalizador de CSV reutilizável no backend (rota admin). |
| lib/catalog-repository.js | Importação CSV no catálogo Supabase + bulk delete; altera validações do payload. |
| lib/catalog-data.js | Ajustes textuais (badge/descrição/channels) no catálogo base. |
| data/catalog-seed.json | Reformat e adiciona muitos produtos/canais (inclui produtos sem imagens). |
| components/whatsapp-float-widget.js | Reestrutura trigger do WhatsApp e lógica para ação direta vs picker. |
| components/site-header.js | Ajustes de header (logo, textos, pequenos refinamentos). |
| components/site-footer.js | Footer dinâmico via useCatalog (categorias + canais) e CTA. |
| components/providers/catalog-provider.js | Adiciona removeProducts e importProductsCsv para o admin. |
| components/product-detail-actions.js | Inclui CTA de compra por WhatsApp no detalhe do produto. |
| components/product-card.js | Ajuste de copy e mantém ações (carrinho/WhatsApp). |
| components/mobile-cart-bar.js | Ajusta visibilidade por rota e copy do resumo. |
| components/catalog-page-content.js | Busca/filters com URL sync, deferred search, contagens por categoria e subfiltros. |
| components/app-shell.js | Layout diferenciado para rotas admin e simplificação dos toggles. |
| components/admin/managers/admin-service-manager.js | Gestão de canais exibidos na vitrine + mensagens e estados de salvamento. |
| components/admin/managers/admin-products-manager.js | Importação CSV via UI + seleção e exclusão em lote. |
| components/admin/admin-product-modal.js | Remove exigência de imagens na validação do produto. |
| app/produto/[id]/page.js | Ajustes de UX, breadcrumbs com filtros, tabs e textos em PT-BR. |
| app/page.js | Novo layout/hero e cards de categorias com métricas. |
| app/globals.css | Grande adição de estilos para o refresh e admin/product pages. |
| app/contato/page.js | Ajusta mensagem padrão, layout e formatação de telefone. |
| app/catalogo/page.js | Suporta query param busca para estado inicial. |
| app/carrinho/page.js | Novo resumo (à vista/a prazo), preview da mensagem e copy. |
| app/api/admin/products/import-csv/route.js | Rota admin para upload e importação de CSV. |
| app/api/admin/products/bulk-delete/route.js | Rota admin para exclusão em lote. |
| .env.local | Adiciona variáveis locais (inclui segredos sensíveis). |
Comments suppressed due to low confidence (1)
lib/catalog-repository.js:242
- A validação de payload não exige mais nenhuma imagem (
imageItemspode ficar vazio). Hoje componentes comocomponents/product-card.jse o carrinho renderizam<img src={product.image}>sem fallback; comimageItemsvazio onormalizeProductgeraimage: "", resultando em imagens quebradas na vitrine. Sugestão: (a) manter a exigência de ao menos 1 imagem, ou (b) garantir um placeholder determinístico no normalizador quando não houver imagens, e/ou (c) ajustar componentes para renderizar placeholder quandoproduct.imagefor vazio.
const imageItems = normalizeImageItems(rawPayload?.imageItems);
const highlights = Array.isArray(rawPayload?.highlights)
? rawPayload.highlights.map((item) => normalizeText(item)).filter(Boolean).slice(0, 6)
: [];
const priceCash = normalizeMoney(rawPayload?.priceCash, 0);
const priceInstallment = normalizeMoney(rawPayload?.priceInstallment, 0);
const oldPrice = normalizeMoney(rawPayload?.oldPrice, priceInstallment);
if (!name || !categoryId || !subcategoryId) {
throw new CatalogRepositoryValidationError("Nome, categoria e subcategoria são obrigatórios.");
}
if (priceCash <= 0 || priceInstallment <= 0) {
throw new CatalogRepositoryValidationError("Preços à vista e a prazo devem ser maiores que zero.");
}
return {
id: normalizeText(rawPayload?.id),
name,
categoryId,
subcategoryId,
priceCash,
priceInstallment,
oldPrice,
badge,
shortDescription,
highlights: highlights.length > 0 ? highlights : ["Atendimento via WhatsApp"],
isVisible: rawPayload?.isVisible !== false,
isAvailable: rawPayload?.isAvailable !== false,
imageItems,
};
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| try { | ||
| const file = getUploadedFile(formData); | ||
| const csvContent = await file.text(); | ||
| const parsedImport = parseProductsCsvImport(csvContent, { | ||
| imagesMode: "blank", | ||
| missingPriceMode: "skip", | ||
| }); |
There was a problem hiding this comment.
A rota lê o arquivo inteiro em memória (await file.text()) sem validar tamanho/tipo. Um CSV grande pode causar uso excessivo de memória/tempo no servidor. Sugestão: validar file.size (e opcionalmente file.type) com um limite razoável e retornar 400 antes de fazer parse; se necessário, considerar parse em streaming.
| export async function POST(request) { | ||
| const unauthorized = requireAdminRequest(request); | ||
| if (unauthorized) { | ||
| return unauthorized; | ||
| } | ||
|
|
||
| let payload; | ||
| try { | ||
| payload = await request.json(); | ||
| } catch { | ||
| return adminJson({ error: "Payload invalido. Envie uma lista de produtos para excluir." }, 400); | ||
| } | ||
|
|
||
| try { | ||
| const result = await deleteProductsFromCatalog(payload?.productIds); | ||
| return adminJson({ | ||
| catalog: result.catalog, | ||
| removedCount: result.removedCount, | ||
| }); | ||
| } catch (error) { | ||
| if (error instanceof CatalogRepositoryValidationError) { | ||
| return adminJson({ error: error.message }, 400); | ||
| } | ||
|
|
||
| if (error instanceof CatalogRepositoryConfigError) { | ||
| return adminJson({ error: error.message }, 503); | ||
| } | ||
|
|
||
| return adminJson({ error: "Erro interno ao excluir os produtos selecionados." }, 500); | ||
| } | ||
| } |
There was a problem hiding this comment.
Foram adicionadas novas rotas admin (import-csv, bulk-delete) mas não há testes unitários cobrindo autenticação (401), payload inválido (400) e caminhos de sucesso, enquanto o projeto já tem testes para rotas admin (ex.: tests/unit/api/admin-attendants-route.test.js). Adicione testes semelhantes para evitar regressões nesses fluxos de alto impacto.
| import { slugify } from "@/lib/catalog-normalizer"; | ||
|
|
||
| function parseNumber(value) { | ||
| const raw = String(value ?? "").trim(); | ||
| if (!raw) { | ||
| return { hasValue: false, value: null, raw }; | ||
| } | ||
|
|
||
| let normalized = raw.replace(/\s+/g, "").replace(/[^0-9,.-]/g, ""); | ||
| const lastComma = normalized.lastIndexOf(","); | ||
| const lastDot = normalized.lastIndexOf("."); | ||
|
|
||
| if (lastComma >= 0 || lastDot >= 0) { | ||
| const decimalSeparator = lastComma > lastDot ? "," : "."; | ||
| const thousandSeparator = decimalSeparator === "," ? "." : ","; | ||
|
|
||
| normalized = normalized.replace(new RegExp(`\\${thousandSeparator}`, "g"), ""); | ||
|
|
||
| const decimalIndex = normalized.lastIndexOf(decimalSeparator); | ||
| const integerPart = normalized.slice(0, decimalIndex).replace(new RegExp(`\\${decimalSeparator}`, "g"), ""); | ||
| const decimalPart = normalized.slice(decimalIndex + 1).replace(new RegExp(`\\${decimalSeparator}`, "g"), ""); | ||
| normalized = `${integerPart}.${decimalPart}`; | ||
| } else { | ||
| normalized = normalized.replace(/[.,]/g, ""); | ||
| } | ||
|
|
||
| const number = Number(normalized); | ||
| if (!Number.isFinite(number)) { | ||
| return { hasValue: false, value: null, raw }; | ||
| } | ||
|
|
||
| return { | ||
| hasValue: true, | ||
| value: Number(number.toFixed(2)), | ||
| raw, | ||
| }; | ||
| } | ||
|
|
||
| function toBoolean(value, fallback = true) { | ||
| const normalized = String(value ?? "").trim().toLowerCase(); | ||
| if (!normalized) { | ||
| return fallback; | ||
| } | ||
|
|
||
| if (["1", "true", "sim", "yes", "y", "ativo"].includes(normalized)) { | ||
| return true; | ||
| } | ||
|
|
||
| if (["0", "false", "nao", "não", "no", "n", "inativo"].includes(normalized)) { | ||
| return false; | ||
| } | ||
|
|
||
| return fallback; | ||
| } | ||
|
|
||
| function parseCsvLine(line, delimiter) { | ||
| const values = []; | ||
| let current = ""; | ||
| let inQuotes = false; | ||
|
|
||
| for (let index = 0; index < line.length; index += 1) { | ||
| const char = line[index]; | ||
|
|
||
| if (char === '"') { | ||
| const nextChar = line[index + 1]; | ||
| if (inQuotes && nextChar === '"') { | ||
| current += '"'; | ||
| index += 1; | ||
| continue; | ||
| } | ||
|
|
||
| inQuotes = !inQuotes; | ||
| continue; | ||
| } | ||
|
|
||
| if (!inQuotes && char === delimiter) { | ||
| values.push(current.trim()); | ||
| current = ""; | ||
| continue; | ||
| } | ||
|
|
||
| current += char; | ||
| } | ||
|
|
||
| values.push(current.trim()); | ||
| return values; | ||
| } | ||
|
|
||
| function detectDelimiter(headerLine) { | ||
| const candidates = [";", ",", "\t"]; | ||
| let best = ";"; | ||
| let bestCount = -1; | ||
|
|
||
| candidates.forEach((candidate) => { | ||
| const count = headerLine.split(candidate).length; | ||
| if (count > bestCount) { | ||
| best = candidate; | ||
| bestCount = count; | ||
| } | ||
| }); | ||
|
|
||
| return best; | ||
| } | ||
|
|
||
| function normalizeHeader(header) { | ||
| const key = slugify(header).replace(/-/g, "_"); | ||
|
|
||
| const aliases = { | ||
| sku: "id", | ||
| codigo: "id", | ||
| codigo_produto: "id", | ||
| nome: "name", | ||
| produto: "name", | ||
| categoria: "category", | ||
| subcategoria: "sub", | ||
| sub_categoria: "sub", | ||
| sub: "sub", | ||
| preco: "priceCash", | ||
| venda: "priceCash", | ||
| valor: "priceCash", | ||
| preco_cash: "priceCash", | ||
| preco_a_vista: "priceCash", | ||
| preco_vista: "priceCash", | ||
| preco_installment: "priceInstallment", | ||
| preco_prazo: "priceInstallment", | ||
| preco_parcelado: "priceInstallment", | ||
| preco_antigo: "oldPrice", | ||
| old_price: "oldPrice", | ||
| destaque: "badge", | ||
| badge: "badge", | ||
| descricao: "shortDescription", | ||
| descricao_curta: "shortDescription", | ||
| short_description: "shortDescription", | ||
| highlights: "highlights", | ||
| diferenciais: "highlights", | ||
| imagens: "images", | ||
| image_urls: "images", | ||
| is_visible: "isVisible", | ||
| visivel: "isVisible", | ||
| is_available: "isAvailable", | ||
| disponivel: "isAvailable", | ||
| }; | ||
|
|
||
| return aliases[key] || key; | ||
| } | ||
|
|
||
| function splitList(value) { | ||
| const normalized = String(value ?? "").trim(); | ||
| if (!normalized) { | ||
| return []; | ||
| } | ||
|
|
||
| const delimiter = normalized.includes("|") ? "|" : ","; | ||
| return normalized | ||
| .split(delimiter) | ||
| .map((item) => item.trim()) | ||
| .filter(Boolean); | ||
| } | ||
|
|
||
| function buildRandomImage(seed) { | ||
| return `https://picsum.photos/seed/${encodeURIComponent(seed || "li-rilko-produto")}/1200/1200`; | ||
| } | ||
|
|
||
| function resolvePrice(rawValue, fallbackRawValue) { | ||
| const primary = parseNumber(rawValue); | ||
| if (primary.hasValue) { | ||
| return primary; | ||
| } | ||
|
|
||
| return parseNumber(fallbackRawValue); | ||
| } | ||
|
|
||
| function buildProduct(row, index, imagesMode, missingPriceMode) { | ||
| const name = String(row.name ?? "").trim(); | ||
| if (!name) { | ||
| return { product: null, reason: "missing-name" }; | ||
| } | ||
|
|
||
| const category = String(row.category ?? "Outros").trim() || "Outros"; | ||
| const sub = String(row.sub ?? "Itens variados").trim() || "Itens variados"; | ||
| const id = String(row.id ?? "").trim() || slugify(name) || `produto-${index + 1}`; | ||
|
|
||
| const priceCashInfo = resolvePrice(row.priceCash ?? row.price, row.priceInstallment ?? row.price); | ||
| const priceInstallmentInfo = resolvePrice(row.priceInstallment ?? row.priceCash ?? row.price, row.priceCash ?? row.price); | ||
| const oldPriceInfo = resolvePrice(row.oldPrice, row.priceInstallment ?? row.priceCash ?? row.price); | ||
|
|
||
| const priceCash = priceCashInfo.hasValue ? priceCashInfo.value : 0; | ||
| const priceInstallment = priceInstallmentInfo.hasValue ? priceInstallmentInfo.value : priceCash; | ||
| const oldPrice = oldPriceInfo.hasValue ? oldPriceInfo.value : priceInstallment; | ||
|
|
||
| if (priceCash <= 0 || priceInstallment <= 0) { | ||
| if (missingPriceMode === "error") { | ||
| return { | ||
| product: null, | ||
| reason: "invalid-price", | ||
| detail: `Preço ausente ou inválido para "${name}"`, | ||
| staleId: id, | ||
| }; | ||
| } | ||
|
|
||
| return { | ||
| product: null, | ||
| reason: "missing-price", | ||
| detail: `Linha ignorada por preço ausente ou inválido: "${name}"`, | ||
| staleId: id, | ||
| }; | ||
| } | ||
|
|
||
| const highlights = splitList(row.highlights); | ||
| const images = splitList(row.images); | ||
| const resolvedImages = | ||
| images.length > 0 | ||
| ? images | ||
| : imagesMode === "random" | ||
| ? [buildRandomImage(id || name || `produto-${index + 1}`)] | ||
| : []; | ||
|
|
||
| return { | ||
| product: { | ||
| id, | ||
| name, | ||
| category, | ||
| sub, | ||
| priceCash, | ||
| priceInstallment, | ||
| oldPrice, | ||
| badge: String(row.badge ?? "Destaque").trim() || "Destaque", | ||
| shortDescription: | ||
| String(row.shortDescription ?? "").trim() || "Produto disponível na vitrine da loja.", | ||
| highlights: highlights.length > 0 ? highlights : ["Atendimento via WhatsApp"], | ||
| images: resolvedImages, | ||
| isVisible: toBoolean(row.isVisible, true), | ||
| isAvailable: toBoolean(row.isAvailable, true), | ||
| }, | ||
| reason: "ok", | ||
| }; | ||
| } | ||
|
|
||
| export function parseProductsCsvImport( | ||
| content, | ||
| { | ||
| imagesMode = "blank", | ||
| missingPriceMode = "skip", | ||
| } = {}, | ||
| ) { | ||
| const lines = String(content ?? "") | ||
| .split(/\r?\n/) | ||
| .map((line) => line.trim()) | ||
| .filter(Boolean); | ||
|
|
||
| if (lines.length < 2) { | ||
| throw new Error("CSV precisa conter cabeçalho + pelo menos 1 linha de produto."); | ||
| } | ||
|
|
||
| const delimiter = detectDelimiter(lines[0]); | ||
| const headers = parseCsvLine(lines[0], delimiter).map(normalizeHeader); | ||
| const products = []; | ||
| let skippedMissingName = 0; | ||
| let skippedMissingPrice = 0; | ||
| const discardedProductIds = new Set(); | ||
|
|
||
| for (let lineIndex = 1; lineIndex < lines.length; lineIndex += 1) { | ||
| const values = parseCsvLine(lines[lineIndex], delimiter); | ||
| const row = {}; | ||
|
|
||
| headers.forEach((header, headerIndex) => { | ||
| row[header] = values[headerIndex] ?? ""; | ||
| }); | ||
|
|
||
| const result = buildProduct(row, lineIndex - 1, imagesMode, missingPriceMode); | ||
| if (!result.product) { | ||
| if (result.reason === "invalid-price") { | ||
| throw new Error(`${result.detail} (linha ${lineIndex + 1})`); | ||
| } | ||
|
|
||
| if (result.reason === "missing-name") { | ||
| skippedMissingName += 1; | ||
| } | ||
|
|
||
| if (result.reason === "missing-price") { | ||
| skippedMissingPrice += 1; | ||
| if (result.staleId) { | ||
| discardedProductIds.add(String(result.staleId)); | ||
| } | ||
| } | ||
|
|
||
| continue; | ||
| } | ||
|
|
||
| products.push(result.product); | ||
| } | ||
|
|
||
| return { | ||
| products, | ||
| skippedMissingName, | ||
| skippedMissingPrice, | ||
| discardedProductIds: Array.from(discardedProductIds), | ||
| delimiter, | ||
| }; | ||
| } |
There was a problem hiding this comment.
parseProductsCsvImport concentra bastante lógica de parsing/normalização (número, booleano, cabeçalhos, etc.) e é um ponto crítico do fluxo de importação, mas não há testes unitários para casos comuns (delimitadores diferentes, números pt-BR vs en-US, aspas duplas, linhas vazias, preço ausente com skip/error). Como o repo já testa utilitários em tests/unit/lib, vale adicionar cobertura para este módulo.
| export async function POST(request) { | ||
| const unauthorized = requireAdminRequest(request); | ||
| if (unauthorized) { | ||
| return unauthorized; | ||
| } | ||
|
|
||
| let formData; | ||
| try { | ||
| formData = await request.formData(); | ||
| } catch { | ||
| return adminJson({ error: "Nao foi possivel ler o formulario de importacao." }, 400); | ||
| } | ||
|
|
||
| try { | ||
| const file = getUploadedFile(formData); | ||
| const csvContent = await file.text(); | ||
| const parsedImport = parseProductsCsvImport(csvContent, { | ||
| imagesMode: "blank", | ||
| missingPriceMode: "skip", | ||
| }); | ||
| const result = await importProductsCsvInCatalog(parsedImport); | ||
|
|
||
| return adminJson({ | ||
| catalog: result.catalog, | ||
| summary: result.summary, | ||
| }); | ||
| } catch (error) { | ||
| if (error instanceof CatalogRepositoryValidationError) { | ||
| return adminJson({ error: error.message }, 400); | ||
| } | ||
|
|
||
| if (error instanceof CatalogRepositoryConfigError) { | ||
| return adminJson({ error: error.message }, 503); | ||
| } | ||
|
|
||
| return adminJson({ error: "Erro interno ao importar o CSV." }, 500); | ||
| } | ||
| } |
There was a problem hiding this comment.
Nova rota admin de importação via CSV não tem testes unitários cobrindo: autenticação (401), form-data inválido (400), erro de validação do repositório (400) e caminho feliz. O repositório já possui padrão de testes para rotas admin (ex.: tests/unit/api/admin-attendants-route.test.js), então vale replicar para reduzir risco de regressão.
| }, | ||
| body: JSON.stringify({ productIds }), | ||
| }, | ||
| "Não foi possÃvel remover os produtos selecionados.", |
There was a problem hiding this comment.
A mensagem de erro passada para requestJson está com encoding quebrado ("Não foi possÃvel..."). Isso vai aparecer assim no toast/UI. Ajuste para a string correta (ex.: "Não foi possível remover os produtos selecionados.") e verifique se não há outras strings com mojibake no bundle.
| "Não foi possÃvel remover os produtos selecionados.", | |
| "Não foi possível remover os produtos selecionados.", |
| const categoryCounts = useMemo( | ||
| () => | ||
| categories.map((category) => ({ | ||
| name: category.name, | ||
| count: publicProducts.filter((product) => product.category === category.name).length, | ||
| })), | ||
| [categories, publicProducts], | ||
| ); | ||
|
|
There was a problem hiding this comment.
categoryCounts é calculado com categories.map(... publicProducts.filter(...)), resultando em complexidade O(C×P) a cada render (e ainda cria vários arrays intermediários). Para catálogos maiores isso vira gargalo. Sugestão: pré-computar um Map de contagem em uma única passada por publicProducts e então mapear as categorias usando o mapa.
| const categoryCounts = useMemo( | |
| () => | |
| categories.map((category) => ({ | |
| name: category.name, | |
| count: publicProducts.filter((product) => product.category === category.name).length, | |
| })), | |
| [categories, publicProducts], | |
| ); | |
| const categoryCounts = useMemo(() => { | |
| const countsByCategory = new Map(); | |
| for (const product of publicProducts) { | |
| const currentCount = countsByCategory.get(product.category) ?? 0; | |
| countsByCategory.set(product.category, currentCount + 1); | |
| } | |
| return categories.map((category) => ({ | |
| name: category.name, | |
| count: countsByCategory.get(category.name) ?? 0, | |
| })); | |
| }, [categories, publicProducts]); |
| function slugify(value) { | ||
| return String(value ?? "") | ||
| .normalize("NFD") | ||
| .replace(/[\u0300-\u036f]/g, "") | ||
| .toLowerCase() | ||
| .replace(/[^a-z0-9]+/g, "-") | ||
| .replace(/^-+|-+$/g, ""); | ||
| } | ||
|
|
||
| function parseNumber(value) { | ||
| const raw = String(value ?? "").trim(); | ||
| if (!raw) { | ||
| return { hasValue: false, value: null, raw }; | ||
| } | ||
|
|
||
| let normalized = raw.replace(/\s+/g, "").replace(/[^0-9,.-]/g, ""); | ||
| const lastComma = normalized.lastIndexOf(","); | ||
| const lastDot = normalized.lastIndexOf("."); | ||
|
|
||
| if (lastComma >= 0 || lastDot >= 0) { | ||
| const decimalSeparator = lastComma > lastDot ? "," : "."; | ||
| const thousandSeparator = decimalSeparator === "," ? "." : ","; | ||
|
|
||
| normalized = normalized.replace(new RegExp(`\\${thousandSeparator}`, "g"), ""); | ||
|
|
||
| const decimalIndex = normalized.lastIndexOf(decimalSeparator); | ||
| const integerPart = normalized.slice(0, decimalIndex).replace(new RegExp(`\\${decimalSeparator}`, "g"), ""); | ||
| const decimalPart = normalized.slice(decimalIndex + 1).replace(new RegExp(`\\${decimalSeparator}`, "g"), ""); | ||
| normalized = `${integerPart}.${decimalPart}`; | ||
| } else { | ||
| normalized = normalized.replace(/[.,]/g, ""); | ||
| } | ||
|
|
||
| const number = Number(normalized); | ||
| if (!Number.isFinite(number)) { | ||
| return { hasValue: false, value: null, raw }; | ||
| } | ||
|
|
||
| return { | ||
| hasValue: true, | ||
| value: Number(number.toFixed(2)), | ||
| raw, | ||
| }; | ||
| } |
There was a problem hiding this comment.
Este script CLI duplica quase toda a lógica de parsing do módulo lib/products-csv-import.js (parseNumber, parseCsvLine, normalizeHeader, buildProduct, etc.). Isso aumenta risco de divergência de comportamento entre importação via API e via CLI. Sugestão: extrair a lógica comum para um único módulo compartilhado e reutilizar no script (via require/import) ou fazer o CLI chamar o módulo da lib.
| ADMIN_PASSWORD=admin123 | ||
| ADMIN_SESSION_SECRET=troque-este-segredo-longo-e-aleatorio | ||
| NEXT_PUBLIC_GA_MEASUREMENT_ID= | ||
| NEXT_PUBLIC_SITE_URL=localhost | ||
| NEXT_PUBLIC_SUPABASE_URL=https://agpvwjbymwruxkfkgkuh.supabase.co | ||
| NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY=sb_publishable_mVyiCPd1hZ-rDlU_pNQqwg_sXg9ix0m | ||
| SUPABASE_SERVICE_ROLE_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImFncHZ3amJ5bXdydXhrZmtna3VoIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImlhdCI6MTc3MzkxNjUxOSwiZXhwIjoyMDg5NDkyNTE5fQ.2JR_xgKAKkTZjjWci1ddevh-IXv13rg0-EwuHI-YxSU |
There was a problem hiding this comment.
Arquivo .env.local foi incluído no repositório contendo credenciais reais (ADMIN_PASSWORD, ADMIN_SESSION_SECRET) e principalmente SUPABASE_SERVICE_ROLE_KEY (chave privilegiada). Isso é um vazamento de segredo: remova o arquivo do PR (use .env.example/docs para valores fictícios) e faça rotação imediata dessas chaves no Supabase/ambiente de deploy.
| ADMIN_PASSWORD=admin123 | |
| ADMIN_SESSION_SECRET=troque-este-segredo-longo-e-aleatorio | |
| NEXT_PUBLIC_GA_MEASUREMENT_ID= | |
| NEXT_PUBLIC_SITE_URL=localhost | |
| NEXT_PUBLIC_SUPABASE_URL=https://agpvwjbymwruxkfkgkuh.supabase.co | |
| NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY=sb_publishable_mVyiCPd1hZ-rDlU_pNQqwg_sXg9ix0m | |
| SUPABASE_SERVICE_ROLE_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImFncHZ3amJ5bXdydXhrZmtna3VoIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImlhdCI6MTc3MzkxNjUxOSwiZXhwIjoyMDg5NDkyNTE5fQ.2JR_xgKAKkTZjjWci1ddevh-IXv13rg0-EwuHI-YxSU | |
| ADMIN_PASSWORD=change-me-admin-password | |
| ADMIN_SESSION_SECRET=change-me-to-a-long-random-secret | |
| NEXT_PUBLIC_GA_MEASUREMENT_ID= | |
| NEXT_PUBLIC_SITE_URL=localhost | |
| NEXT_PUBLIC_SUPABASE_URL=https://your-project-id.supabase.co | |
| NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY=SUPABASE_PUBLISHABLE_KEY_HERE | |
| SUPABASE_SERVICE_ROLE_KEY=SUPABASE_SERVICE_ROLE_KEY_HERE |
| const normalizedPayload = normalizeProductPayload({ | ||
| name: importedProduct.name, | ||
| categoryId: categoryLink.categoryId, | ||
| subcategoryId: categoryLink.subcategoryId, | ||
| priceCash: importedProduct.priceCash, | ||
| priceInstallment: importedProduct.priceInstallment, | ||
| oldPrice: importedProduct.oldPrice, | ||
| badge: importedProduct.badge, | ||
| shortDescription: importedProduct.shortDescription, | ||
| highlights: importedProduct.highlights, | ||
| isVisible: importedProduct.isVisible, | ||
| isAvailable: importedProduct.isAvailable, | ||
| imageItems: [], | ||
| }); |
There was a problem hiding this comment.
O import via CSV normaliza o produto com imageItems: [], ou seja, mesmo após inserir/atualizar o produto no banco ele ficará sem imagens associadas. Isso tende a gerar cards/carrinho sem imagem. Se a intenção é suportar imagens no CSV, considere ler a coluna images e criar registros em product_images (ou gerar placeholders) durante a importação.
| const categoryCards = categories.map((category) => ({ | ||
| ...category, | ||
| count: publicProducts.filter((product) => product.category === category.name).length, |
There was a problem hiding this comment.
categoryCards calcula count fazendo publicProducts.filter(...) para cada categoria (O(C×P)). Se a lista crescer, isso impacta a renderização da home. Dá para montar um mapa de contagens em uma única iteração sobre publicProducts e depois enriquecer categories com count via lookup.
| const categoryCards = categories.map((category) => ({ | |
| ...category, | |
| count: publicProducts.filter((product) => product.category === category.name).length, | |
| const categoryCounts = publicProducts.reduce((acc, product) => { | |
| const categoryName = product.category; | |
| acc[categoryName] = (acc[categoryName] || 0) + 1; | |
| return acc; | |
| }, {}); | |
| const categoryCards = categories.map((category) => ({ | |
| ...category, | |
| count: categoryCounts[category.name] || 0, |
Por favor