Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .env.local
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
ADMIN_USERNAME=admin
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
Comment on lines +2 to +8

Copilot AI Mar 27, 2026

Copy link

Choose a reason for hiding this comment

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

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.

Suggested change
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

Copilot uses AI. Check for mistakes.
SUPABASE_STORAGE_BUCKET_PRODUCTS=product-images
40 changes: 40 additions & 0 deletions app/api/admin/products/bulk-delete/route.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { adminJson, requireAdminRequest } from "@/lib/admin-route";
import {
CatalogRepositoryConfigError,
CatalogRepositoryValidationError,
deleteProductsFromCatalog,
} from "@/lib/catalog-repository";

export const runtime = "nodejs";

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);
}
}
Comment on lines +10 to +40

Copilot AI Mar 27, 2026

Copy link

Choose a reason for hiding this comment

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

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.

Copilot uses AI. Check for mistakes.
57 changes: 57 additions & 0 deletions app/api/admin/products/import-csv/route.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { adminJson, requireAdminRequest } from "@/lib/admin-route";
import { parseProductsCsvImport } from "@/lib/products-csv-import";
import {
CatalogRepositoryConfigError,
CatalogRepositoryValidationError,
importProductsCsvInCatalog,
} from "@/lib/catalog-repository";

export const runtime = "nodejs";

function getUploadedFile(formData) {
const file = formData.get("file");
if (!file || typeof file.text !== "function") {
throw new CatalogRepositoryValidationError("Selecione um arquivo CSV valido para importar.");
}

return file;
}

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",
});
Comment on lines +33 to +39

Copilot AI Mar 27, 2026

Copy link

Choose a reason for hiding this comment

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

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.

Copilot uses AI. Check for mistakes.
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);
}
}
Comment on lines +20 to +57

Copilot AI Mar 27, 2026

Copy link

Choose a reason for hiding this comment

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

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.

Copilot uses AI. Check for mistakes.
75 changes: 51 additions & 24 deletions app/carrinho/page.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,15 @@ import { useCart } from "@/components/providers/cart-provider";
import { useToast } from "@/components/providers/toast-provider";
import TransitionLink from "@/components/transition-link";
import WhatsAppAttendantPicker from "@/components/whatsapp-attendant-picker";
import { resolveAttendantFlow } from "@/lib/attendants-data";
import { buildAttendantWhatsAppLink, buildWhatsAppMessage, formatCurrency } from "@/lib/store-utils";
import { openWhatsAppLink, resolveWhatsAppAttendantAction } from "@/lib/whatsapp-attendant-flow";

export default function CartPage() {
const { attendants, siteSettings } = useCatalog();
const { items, total, count, addItem, decreaseItem, removeItem, clearCart } = useCart();
const { items, totalCash, totalInstallment, count, addItem, decreaseItem, removeItem, clearCart } = useCart();
const { showToast } = useToast();
const [isPickerOpen, setIsPickerOpen] = useState(false);
const [pendingMessage, setPendingMessage] = useState("");
const attendantFlow = resolveAttendantFlow(attendants);

const message = buildWhatsAppMessage(items, siteSettings);

Expand Down Expand Up @@ -80,16 +78,26 @@ export default function CartPage() {
<section className="vg-cart-page">
<div className="shell-container">
<header className="vg-cart-header">
<h1 className="vg-cart-title">Revise seu Pedido</h1>
{count > 0 && <button className="vg-filter-clear" onClick={clearCart}>Limpar tudo</button>}
<div>
<h1 className="vg-cart-title">Revise seu pedido</h1>
<p className="cart-page-subtitle">Ajuste os itens e envie o pedido no WhatsApp.</p>
</div>
{count > 0 && (
<button type="button" className="vg-filter-clear" onClick={clearCart}>
Limpar tudo
</button>
)}
</header>

<div className="vg-cart-grid">
<div className="vg-cart-items-col">
{items.length === 0 ? (
<div className="vg-empty-state">
<p>Seu carrinho está vazio.</p>
<TransitionLink className="btn btn-primary" href="/catalogo">Explorar Catálogo</TransitionLink>
<span>Adicione produtos para continuar.</span>
<TransitionLink className="btn btn-primary" href="/catalogo">
Explorar catálogo
</TransitionLink>
</div>
) : (
<ul className="vg-cart-list">
Expand All @@ -98,28 +106,36 @@ export default function CartPage() {
<TransitionLink href={`/produto/${item.id}`} className="vg-cart-item-img">
<img src={item.image} alt={item.name} />
</TransitionLink>

<div className="vg-cart-item-info">
<div className="vg-cart-item-top">
<TransitionLink href={`/produto/${item.id}`} className="vg-cart-item-title">
{item.name}
</TransitionLink>
<div>
<TransitionLink href={`/produto/${item.id}`} className="vg-cart-item-title">
{item.name}
</TransitionLink>
<p className="cart-item-meta">{item.category} • {item.sub}</p>
</div>
<button className="vg-cart-item-remove" onClick={() => handleRemove(item)}>
<IconTrash className="icon" />
</button>
</div>

<div className="vg-cart-item-bottom">
<div className="vg-cart-item-qty">
<span>Qtd:</span>
<div className="vg-qty-pill">
<button aria-label="Diminuir quantidade" onClick={() => handleDecrease(item)}>−</button>
<button aria-label="Diminuir quantidade" onClick={() => handleDecrease(item)}>-</button>
<strong>{item.qty}</strong>
<button aria-label="Aumentar quantidade" onClick={() => handleIncrease(item)}>+</button>
</div>
</div>

<strong className="vg-cart-item-price">{formatCurrency(item.subtotal)}</strong>

<div className="cart-price-stack">
<strong className="vg-cart-item-price">{formatCurrency(item.subtotalCash)}</strong>
{item.subtotalInstallment !== item.subtotalCash && (
<span>A prazo: {formatCurrency(item.subtotalInstallment)}</span>
)}
</div>
</div>
</div>
</li>
Expand All @@ -129,16 +145,27 @@ export default function CartPage() {
</div>

<div className="vg-cart-summary-col">
<h2 className="vg-summary-title">Prévia da Mensagem do Pedido</h2>
<div className="vg-mock-console">
<div className="vg-mock-header">
<span></span><span></span><span></span>
<div className="cart-summary-card">
<h2 className="vg-summary-title">Resumo do pedido</h2>
<div className="cart-summary-row">
<span>Itens no pedido</span>
<strong>{count}</strong>
</div>
<div className="cart-summary-row">
<span>Total à vista</span>
<strong>{formatCurrency(totalCash)}</strong>
</div>
<div className="cart-summary-row">
<span>Total a prazo</span>
<strong>{formatCurrency(totalInstallment)}</strong>
</div>
<div className="cart-summary-note">
Este resumo será enviado para a loja no WhatsApp.
</div>
<div className="cart-message-preview">
<pre className="vg-mock-text">{message || "Seu carrinho está vazio."}</pre>
</div>
<pre className="vg-mock-text">{message || "Seu carrinho está vazio."}</pre>
</div>
<p className="vg-summary-hint">
A mensagem acima será enviada diretamente para o seu Especialista via WhatsApp.
</p>
</div>
</div>
</div>
Expand All @@ -148,8 +175,8 @@ export default function CartPage() {
<div className="vg-cart-sticky-bottom">
<div className="shell-container vg-cart-sticky-inner">
<div className="vg-cart-subtotal">
<span>Subtotal</span>
<strong>{formatCurrency(total)}</strong>
<span>Total à vista</span>
<strong>{formatCurrency(totalCash)}</strong>
</div>
<button className="btn btn-primary vg-checkout-btn" onClick={handleCheckoutClick}>
Finalizar Compra <IconWhatsApp className="icon" />
Expand Down
11 changes: 10 additions & 1 deletion app/catalogo/page.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,19 @@ export default async function CatalogPage({ searchParams }) {
const categoria = typeof params?.categoria === "string" ? params.categoria.slice(0, 80) : "Todos";
const sub = typeof params?.sub === "string" ? params.sub : "";
const ordenacao = typeof params?.ordem === "string" ? params.ordem : "relevancia";
const busca = typeof params?.busca === "string" ? params.busca : "";

const initialCategory = categoria || "Todos";
const initialSub = sub.slice(0, 80);
const initialSort = ordenacao.slice(0, 40);
const initialSearch = busca.slice(0, 120);

return <CatalogPageContent initialCategory={initialCategory} initialSub={initialSub} initialSort={initialSort} />;
return (
<CatalogPageContent
initialCategory={initialCategory}
initialSub={initialSub}
initialSort={initialSort}
initialSearch={initialSearch}
/>
);
}
50 changes: 35 additions & 15 deletions app/contato/page.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,37 @@ import { resolveAttendantFlow } from "@/lib/attendants-data";
import { buildAttendantWhatsAppLink, buildWhatsAppMessage } from "@/lib/store-utils";
import { openWhatsAppLink, resolveWhatsAppAttendantAction } from "@/lib/whatsapp-attendant-flow";

function formatPhoneLabel(phone) {
const digits = String(phone || "").replace(/\D/g, "");
if (!digits) return "";

if (digits.length === 13) {
return `+55 (${digits.slice(2, 4)}) ${digits.slice(4, 9)}-${digits.slice(9)}`;
}

if (digits.length === 12) {
return `+55 (${digits.slice(2, 4)}) ${digits.slice(4, 8)}-${digits.slice(8)}`;
}

return phone;
}

export default function ContactPage() {
const { attendants, contactChannels, siteSettings } = useCatalog();
const { items } = useCart();
const { showToast } = useToast();
const [isPickerOpen, setIsPickerOpen] = useState(false);
const [pendingMessage, setPendingMessage] = useState("");
const attendantFlow = resolveAttendantFlow(attendants);
const message = buildWhatsAppMessage(items, siteSettings);
const message =
items.length > 0
? buildWhatsAppMessage(items, siteSettings)
: "Olá! Vim pelo site da Li Rilko e gostaria de atendimento para tirar dúvidas e finalizar uma compra.";

function handleStartContact(event) {
event.preventDefault();

const contactMessage = buildWhatsAppMessage(items, siteSettings);
const action = resolveWhatsAppAttendantAction(attendants, contactMessage);
const action = resolveWhatsAppAttendantAction(attendants, message);

if (action.mode === "blocked") {
showToast({
Expand All @@ -35,7 +52,7 @@ export default function ContactPage() {
}

if (action.mode === "picker") {
setPendingMessage(contactMessage);
setPendingMessage(message);
setIsPickerOpen(true);
return;
}
Expand Down Expand Up @@ -79,24 +96,27 @@ export default function ContactPage() {
<section className="section page-hero-small">
<div className="shell-container">
<p className="kicker">Contato</p>
<h1>Atendimento direto para tirar dúvidas e finalizar pedidos.</h1>
<p>Fale com nossa equipe e receba suporte rápido para escolher o melhor produto.</p>
<h1>Fale com a loja</h1>
<p>Tire dúvidas, confirme disponibilidade e finalize seu pedido no WhatsApp.</p>
</div>
</section>

<section className="section">
<div className="shell-container contact-layout">
<article className="contact-main-card reveal">
<h2>Fale agora com a Li Rilko</h2>
<p>
O WhatsApp é nosso principal canal de atendimento. Se você já montou seu carrinho, o resumo do pedido já
segue automaticamente na mensagem.
</p>
<p>Com duas ou mais atendentes disponíveis, você escolhe com quem falar em cada clique.</p>
<a className="btn btn-whatsapp" href="#" onClick={handleStartContact}>
<h2>Atendimento no WhatsApp</h2>
<p>Se você já montou seu carrinho, o resumo do pedido segue automaticamente na mensagem.</p>

<a className="btn btn-whatsapp contact-primary-button" href="#" onClick={handleStartContact}>
<IconWhatsApp className="icon" />
{attendantFlow.mode === "blocked" ? "WhatsApp indisponível" : "Iniciar conversa no WhatsApp"}
</a>

<div className="contact-benefit-list">
<span>Atendimento humano</span>
<span>Confirmação de disponibilidade</span>
<span>Fechamento pelo WhatsApp</span>
</div>
</article>

<aside className="contact-side-card reveal delay-1">
Expand All @@ -111,7 +131,7 @@ export default function ContactPage() {
<strong>{attendant.name}</strong>
{link ? (
<a href={link} target="_blank" rel="noreferrer">
{attendant.phone}
{formatPhoneLabel(attendant.phone)}
</a>
) : (
<span>Número inválido</span>
Expand All @@ -122,7 +142,7 @@ export default function ContactPage() {
) : (
<li>
<strong>Sem atendentes cadastrados</strong>
<span>Peça para o admin configurar ao menos 1 atendente no painel.</span>
<span>Peça para a loja configurar ao menos um número de atendimento.</span>
</li>
)}
</ul>
Expand Down
Loading
Loading