From 6a2d60413e6d398e7a83e4867163471696086140 Mon Sep 17 00:00:00 2001 From: ArielAio Date: Tue, 24 Mar 2026 17:53:25 -0300 Subject: [PATCH] =?UTF-8?q?refactor(admin):=20moderniza=C3=A7=C3=A3o=20da?= =?UTF-8?q?=20ux=20do=20portal=20e=20controles=20em=20linha?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - feat(admin): login redesenhado com estética 'Vanguard Secure Portal'. - feat(catalog): introduzido 'AdminProductModal' global para edição rápida de produtos. - ui(admin): simplificadas as abas de gerenciamento de Produtos, Categorias e Atendimento. - fix(mobile): padding condicional no Footer e BottomTabBar condicionada a rotas não-admin. - fix(mobile): admin topbar responsivo com flex-wrap e breakpoint mobile. - refactor(footer): link dinâmico focado no Instagram (@lirilkoimportscentro). - fix(ui): favicon migrado para icon.svg com clip-path circular nativo. - fix(a11y): role=dialog, aria-modal e Escape-to-close no AdminProductModal. - fix(ui): corrigido label de preço (à vista / a prazo) na página de produto. - chore: removidas importações e código morto. - chore: adicionado script npm generate:favicon. --- app/carrinho/page.js | 210 +- app/globals.css | 2465 ++++++++++++++++- app/icon.svg | 8 + app/layout.js | 7 +- app/page.js | 143 +- app/produto/[id]/page.js | 168 +- components/admin/admin-dashboard.js | 155 +- components/admin/admin-login-form.js | 130 +- components/admin/admin-product-modal.js | 362 +++ .../managers/admin-categories-manager.js | 335 ++- .../admin/managers/admin-products-manager.js | 723 +---- .../admin/managers/admin-service-manager.js | 145 +- components/app-shell.js | 6 +- components/bottom-tab-bar.js | 45 + components/catalog-page-content.js | 234 +- components/icons.js | 28 + components/product-card.js | 111 +- components/product-detail-actions.js | 49 +- components/providers/app-providers.js | 4 +- components/providers/catalog-provider.js | 36 +- components/site-footer.js | 41 +- components/site-header.js | 37 +- components/whatsapp-attendant-picker.js | 67 +- components/whatsapp-float-widget.js | 83 +- package.json | 3 +- public/li-rilko-icon-page.png | Bin 0 -> 37876 bytes scripts/create-svg-favicon.js | 18 + tests/e2e/smoke/checkout.smoke.spec.js | 20 +- 28 files changed, 3891 insertions(+), 1742 deletions(-) create mode 100644 app/icon.svg create mode 100644 components/admin/admin-product-modal.js create mode 100644 components/bottom-tab-bar.js create mode 100644 public/li-rilko-icon-page.png create mode 100644 scripts/create-svg-favicon.js diff --git a/app/carrinho/page.js b/app/carrinho/page.js index 85369a7..6dd8d9c 100644 --- a/app/carrinho/page.js +++ b/app/carrinho/page.js @@ -24,68 +24,33 @@ export default function CartPage() { function handleDecrease(item) { if (item.qty <= 1) { removeItem(item.id); - showToast({ - type: "warning", - title: "Item removido", - message: `${item.name} foi removido do carrinho.`, - }); + showToast({ type: "warning", title: "Item removido", message: `${item.name} saiu do carrinho.` }); return; } - decreaseItem(item.id, 1); } function handleIncrease(item) { const added = addItem(item.id, 1); if (!added) { - showToast({ - type: "warning", - title: "Produto indisponível", - message: `${item.name} não está disponível para aumentar quantidade agora.`, - }); - return; + showToast({ type: "warning", title: "Produto indisponível", message: `${item.name} esgotado.` }); } } function handleRemove(item) { removeItem(item.id); - showToast({ - type: "warning", - title: "Item removido", - message: `${item.name} saiu do carrinho.`, - }); - } - - function handleClearCart() { - clearCart(); - showToast({ - type: "warning", - title: "Carrinho limpo", - message: "Todos os itens foram removidos.", - }); + showToast({ type: "warning", title: "Item removido", message: `${item.name} saiu.` }); } function handleCheckoutClick(event) { event.preventDefault(); - - if (items.length === 0) { - showToast({ - type: "warning", - title: "Carrinho vazio", - message: "Adicione produtos antes de finalizar no WhatsApp.", - }); - return; - } + if (items.length === 0) return; const checkoutMessage = buildWhatsAppMessage(items, siteSettings); const action = resolveWhatsAppAttendantAction(attendants, checkoutMessage); if (action.mode === "blocked") { - showToast({ - type: "warning", - title: "Atendimento indisponível", - message: "Nenhum atendente com número válido foi configurado no admin.", - }); + showToast({ type: "warning", title: "Indisponível", message: "Nenhum atendente configurado." }); return; } @@ -96,11 +61,6 @@ export default function CartPage() { } openWhatsAppLink(action.link); - showToast({ - type: "success", - title: "Abrindo WhatsApp", - message: `Resumo pronto para finalizar com ${action.attendant.name}.`, - }); } function handleClosePicker() { @@ -110,109 +70,93 @@ export default function CartPage() { function handleSelectAttendant(attendant) { const link = buildAttendantWhatsAppLink(pendingMessage, attendant); - - if (!link) { - showToast({ - type: "warning", - title: "Atendimento indisponível", - message: "O número da atendente selecionada é inválido.", - }); - return; - } - + if (!link) return; openWhatsAppLink(link); - showToast({ - type: "success", - title: "Abrindo WhatsApp", - message: `Resumo pronto para finalizar com ${attendant.name}.`, - }); handleClosePicker(); } return ( <> -
+
-

Carrinho

-

Confira seus itens e finalize seu pedido.

-

Ajuste quantidades, veja o total e envie o pedido para atendimento no WhatsApp.

-
-
- -
-
-
-
-

Seu carrinho

- {count > 0 && ( - +
+

Revise seu Pedido

+ {count > 0 && } +
+ +
+
+ {items.length === 0 ? ( +
+

Seu carrinho está vazio.

+ Explorar Catálogo +
+ ) : ( +
    + {items.map((item) => ( +
  • + + {item.name} + + +
    +
    + + {item.name} + + +
    + +
    +
    + Qtd: +
    + + {item.qty} + +
    +
    + + {formatCurrency(item.subtotal)} +
    +
    +
  • + ))} +
)}
- {items.length === 0 ? ( -
- Seu carrinho está vazio. -

Volte para o catálogo e adicione os produtos que te interessam.

- - Ir para catálogo - +
+

Prévia da Mensagem do Pedido

+
+
+ +
+
{message || "Seu carrinho está vazio."}
- ) : ( -
    - {items.map((item) => ( -
  • -
    - {item.name} - - {item.category} • {formatCurrency(item.price)} cada - -
    - -
    -
    - - {item.qty} - -
    - - {formatCurrency(item.subtotal)} - - -
    -
  • - ))} -
- )} +

+ A mensagem acima será enviada diretamente para o seu Especialista via WhatsApp. +

+
+
+
+
-
- Total + {count > 0 && ( +
+
+
+ Subtotal {formatCurrency(total)}
- - - + +
-
+ )} label { + font-size: 0.85rem; + font-weight: 700; + color: var(--ink); +} + +.vg-switch { + position: relative; + display: inline-block; + width: 44px; + height: 24px; +} + +.vg-switch input { + opacity: 0; + width: 0; + height: 0; +} + +.vg-slider { + position: absolute; + cursor: pointer; + inset: 0; + background-color: #ccc; + transition: .4s; + border-radius: 34px; +} + +.vg-slider:before { + position: absolute; + content: ""; + height: 18px; + width: 18px; + left: 3px; + bottom: 3px; + background-color: white; + transition: .4s; + border-radius: 50%; +} + +.vg-switch input:checked + .vg-slider { + background-color: var(--brand); +} + +.vg-switch input:checked + .vg-slider:before { + transform: translateX(20px); +} + +.vg-slideover-footer { + margin-top: 1rem; + display: flex; + flex-direction: column; + gap: 1rem; +} + +.vg-discard-btn { + background: none; + border: none; + color: #6a5c5c; + font-size: 0.7rem; + font-weight: 800; + letter-spacing: 0.05em; + cursor: pointer; + opacity: 0.8; +} + +.vg-discard-btn:hover { + opacity: 1; +} + +/* Floating Edit Action on Product Cards */ +.vg-inline-edit-btn { + position: absolute; + top: 0.5rem; + right: 0.5rem; + background: var(--brand); + color: white; + border: none; + border-radius: 50%; + width: 36px; + height: 36px; + display: flex; + align-items: center; + justify-content: center; + cursor: pointer; + z-index: 10; + box-shadow: 0 4px 12px rgba(0,0,0,0.2); + transition: transform 0.2s; +} + +.vg-inline-edit-btn:hover { + transform: scale(1.1); +} + +/* --- VANGUARD ADMIN SECURE LOGIN --- */ +.vg-admin-login-wrapper { + max-width: 400px; + margin: 4rem auto; + display: flex; + flex-direction: column; + align-items: center; + padding: 2rem 1rem; +} + +.vg-secure-logo { + color: var(--brand); + margin-bottom: 1rem; +} + +.vg-admin-login-header { + text-align: center; + margin-bottom: 2rem; +} + +.vg-admin-login-header h1 { + font-family: var(--font-display); + font-size: 1.5rem; + font-weight: 800; + color: var(--ink); + margin-bottom: 0.25rem; +} + +.vg-admin-login-header p { + font-size: 0.85rem; + color: var(--muted); +} + +.vg-admin-login-card { + width: 100%; + background: #fff; + border-radius: var(--radius-md); + padding: 2rem; + box-shadow: 0 10px 30px rgba(0,0,0,0.05); + margin-bottom: 2rem; +} + +.vg-admin-form-inner { + display: flex; + flex-direction: column; + gap: 1.5rem; +} + +.vg-secure-field { + display: flex; + flex-direction: column; + gap: 0.5rem; +} + +.vg-secure-label, .vg-forgot-link { + font-size: 0.75rem; + font-weight: 800; + letter-spacing: 0.05em; + color: #6a5c5c; +} + +.vg-forgot-link { + background: none; + border: none; + color: var(--brand); + cursor: pointer; +} + +.vg-secure-label-row { + display: flex; + justify-content: space-between; + align-items: center; +} + +.vg-secure-input-wrap { + position: relative; + display: flex; + align-items: center; + background: #f4f7fb; + border-radius: var(--radius-sm); + padding: 0 1rem; + transition: box-shadow 0.2s; +} + +.vg-secure-input-wrap:focus-within { + box-shadow: 0 0 0 2px var(--brand); +} + +.vg-secure-icon { + color: var(--muted); + flex-shrink: 0; + width: 18px; + height: 18px; + display: flex; +} + +.vg-secure-input-wrap input { + flex: 1; + background: transparent; + border: none; + padding: 1rem 0.75rem; + font-size: 0.95rem; + color: var(--ink); + outline: none; +} + +.vg-secure-eye { + background: none; + border: none; + color: var(--muted); + cursor: pointer; + padding: 0.5rem; +} + +.vg-secure-submit { + background: var(--brand); + color: #fff; + border: none; + border-radius: var(--radius-sm); + padding: 1rem; + font-weight: 800; + letter-spacing: 0.05em; + cursor: pointer; + display: flex; + justify-content: center; + align-items: center; + gap: 0.5rem; + transition: opacity 0.2s; +} + +.vg-secure-submit:hover { + opacity: 0.9; +} + +.vg-secure-status { + display: flex; + justify-content: center; + align-items: center; + gap: 0.5rem; + margin-top: 1rem; + padding-top: 1.5rem; + border-top: 1px solid var(--line); + font-size: 0.65rem; + font-weight: 800; + letter-spacing: 0.05em; + color: #6a5c5c; +} + +.vg-secure-status .dot { + width: 6px; + height: 6px; + background: #25D366; + border-radius: 50%; +} + +.vg-admin-login-footer { + display: flex; + gap: 2rem; + margin-bottom: 2rem; +} + +.vg-support-btn { + background: none; + border: none; + color: #6a5c5c; + font-size: 0.75rem; + font-weight: 800; + letter-spacing: 0.05em; + display: flex; + align-items: center; + gap: 0.4rem; + cursor: pointer; + transition: color 0.2s; +} + +.vg-support-btn:hover { + color: var(--brand); +} + +.vg-secure-version { + font-size: 0.65rem; + font-weight: 800; + letter-spacing: 0.1em; + color: #a09797; +} + +/* --- VANGUARD ADMIN DASHBOARD --- */ +.vg-admin-wrapper { + min-height: 100vh; + background: var(--surface-bg); + display: flex; + flex-direction: column; +} + +.vg-admin-topbar { + background: #fff; + padding: 1rem 2rem; + display: flex; + justify-content: space-between; + align-items: center; + flex-wrap: wrap; + gap: 0.75rem; + border-bottom: 1px solid var(--line); +} + +@media (max-width: 600px) { + .vg-admin-topbar { + padding: 0.75rem 1rem; + flex-direction: column; + align-items: stretch; + gap: 0.5rem; + } +} + +.vg-admin-brand { + display: flex; + align-items: center; + gap: 0.75rem; + font-family: var(--font-display); + font-size: 1.1rem; + color: var(--ink); +} + +@media (max-width: 600px) { + .vg-admin-brand { + font-size: 0.95rem; + } +} + +.vg-admin-top-actions { + display: flex; + align-items: center; + gap: 0.75rem; +} + +@media (max-width: 600px) { + .vg-admin-top-actions { + justify-content: stretch; + } + .vg-admin-top-actions > * { + flex: 1; + text-align: center; + } +} + +.vg-outline-btn { + background: transparent; + border: 1px solid var(--line); + padding: 0.5rem 1rem; + border-radius: var(--radius-sm); + font-size: 0.75rem; + font-weight: 800; + letter-spacing: 0.05em; + color: var(--ink); + transition: all 0.2s; +} + +.vg-outline-btn:hover { + border-color: var(--brand); + color: var(--brand); +} + +.vg-logout-btn { + background: rgba(227, 25, 55, 0.1); + color: var(--brand); + border: none; + padding: 0.5rem 1rem; + border-radius: var(--radius-sm); + font-size: 0.75rem; + font-weight: 800; + letter-spacing: 0.05em; + cursor: pointer; + transition: background 0.2s; +} + +.vg-logout-btn:hover { + background: var(--brand); + color: #fff; +} + +.vg-admin-main { + flex: 1; + padding: 3rem 2rem; + max-width: 1200px; + margin: 0 auto; + width: 100%; +} + +.vg-admin-hero h1 { + font-size: 2rem; + font-family: var(--font-display); + color: var(--ink); + margin-bottom: 0.5rem; +} + +.vg-admin-hero p { + color: var(--muted); + font-size: 0.95rem; +} + +.vg-dashboard-summary { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); + gap: 1rem; + margin: 2rem 0 3rem; +} + +.vg-stat-card { + background: #fff; + padding: 1.5rem; + border-radius: var(--radius-md); + box-shadow: 0 4px 12px rgba(0,0,0,0.03); + display: flex; + flex-direction: column; + gap: 0.5rem; + border: 1px solid transparent; + transition: border-color 0.2s, transform 0.2s; +} + +.vg-stat-card:hover { + border-color: rgba(227, 25, 55, 0.2); + transform: translateY(-2px); +} + +.vg-stat-label { + font-size: 0.7rem; + font-weight: 800; + letter-spacing: 0.05em; + color: #6a5c5c; +} + +.vg-stat-value { + font-size: 2rem; + font-weight: 800; + color: var(--brand); + font-family: var(--font-display); +} + +.vg-section-label { + font-size: 0.85rem; + font-weight: 800; + letter-spacing: 0.05em; + color: var(--muted); + margin-bottom: 1.5rem; +} + +.vg-modules-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); + gap: 1.5rem; +} + +.vg-module-card { + background: #fff; + border: 1px solid var(--line); + padding: 2rem 1.5rem; + border-radius: var(--radius-md); + text-align: left; + display: flex; + flex-direction: column; + gap: 1.5rem; + cursor: pointer; + transition: all 0.2s; +} + +.vg-module-card:hover { + border-color: var(--brand); + box-shadow: 0 10px 30px rgba(227, 25, 55, 0.1); + transform: translateY(-4px); +} + +.vg-module-icon { + background: rgba(227, 25, 55, 0.05); + color: var(--brand); + width: 48px; + height: 48px; + border-radius: 50%; + display: flex; + align-items: center; + justify-content: center; +} + +.vg-module-content h3 { + font-size: 1.1rem; + font-weight: 700; + color: var(--ink); + margin-bottom: 0.5rem; +} + +.vg-module-content p { + font-size: 0.85rem; + color: var(--muted); + line-height: 1.4; +} diff --git a/app/icon.svg b/app/icon.svg new file mode 100644 index 0000000..01aeb15 --- /dev/null +++ b/app/icon.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/app/layout.js b/app/layout.js index 298e88f..69ddfa9 100644 --- a/app/layout.js +++ b/app/layout.js @@ -2,6 +2,8 @@ import { Manrope, Sora } from "next/font/google"; import AppShell from "@/components/app-shell"; import AppProviders from "@/components/providers/app-providers"; import { getPublicCatalogSnapshot } from "@/lib/catalog-repository"; +import { cookies } from "next/headers"; +import { ADMIN_SESSION_COOKIE, isAdminSessionValid } from "@/lib/admin-auth"; import "./globals.css"; const displayFont = Sora({ @@ -24,11 +26,14 @@ export const metadata = { export default async function RootLayout({ children }) { const initialCatalog = await getPublicCatalogSnapshot(); + const cookieStore = await cookies(); + const sessionToken = cookieStore.get(ADMIN_SESSION_COOKIE)?.value ?? ""; + const isAdmin = isAdminSessionValid(sessionToken); return ( - + {children} diff --git a/app/page.js b/app/page.js index 7593471..1fe83d5 100644 --- a/app/page.js +++ b/app/page.js @@ -4,12 +4,6 @@ import ProductCard from "@/components/product-card"; import { useCatalog } from "@/components/providers/catalog-provider"; import TransitionLink from "@/components/transition-link"; -const buyingSteps = [ - "1. Escolha a categoria", - "2. Adicione os itens no carrinho", - "3. Finalize o pedido no WhatsApp", -]; - function buildCatalogLink(categoryName, subName) { const query = new URLSearchParams(); query.set("categoria", categoryName); @@ -21,114 +15,109 @@ function buildCatalogLink(categoryName, subName) { export default function HomePage() { const { categories, publicProducts } = useCatalog(); + return ( <> -
-
-
-

Fernandópolis - SP | Li Rilko Imports

-

Importados, eletrônicos e acessórios com pedido rápido pelo WhatsApp.

-

- Explore o catálogo, compare preços à vista e a prazo, monte seu carrinho e conclua direto no atendimento - da loja. +

+
+
+ NOVA COLEÇÃO {new Date().getFullYear()} +

+ Li Rilko +

+

+ Seu destino para uma curadoria e estética impecáveis. + Encontre eletrônicos e importados selecionados com atendimento personalizado.

-
+
- Ver catálogo + Ver Catálogo > - - Atendimento no WhatsApp + + Falar com Especialista
-
- - +
+ +
+
+ Inverno 24 Lookbook +
+
-
+
-
-

Categorias

-

Entre pela categoria certa e encontre mais rápido o que precisa.

+
+

Categorias

+

Encontre exatamente o que você procura no nosso catálogo.

-
- {categories.map((category) => ( -
- -
-

- + +
+ {categories.map((category) => { + const capLetter = category.name.charAt(0).toUpperCase(); + return ( +
+
+ {capLetter} + {category.name} -

- -
    - {category.subs.slice(0, 4).map((sub) => ( + › +
+
    + {category.subs.slice(0, 3).map((sub) => (
  • - - {sub} + + • {sub}
  • ))}
- - Explorar categoria -
- - ))} + + ); + })}
-
+
-
-

Mais procurados

-

Produtos com maior saída para acelerar sua decisão de compra.

+
+

DESTAQUES

+
+

Os produtos mais desejados da loja, selecionados para agradar o seu estilo e curadoria.

+
- {publicProducts.slice(0, 8).map((product, index) => ( + {publicProducts.slice(0, 4).map((product, index) => (
- +
))}
-
- - Ver catálogo completo + +
+ + Ver Catálogo Completo
-
-
-
-

Pronto para finalizar?

-

Abra o WhatsApp e conclua seu pedido com atendimento direto da loja.

-
-
+
+
+
+

Gostou de algo?
Fale agora com um Especialista.

+

+ Tire suas dúvidas, consulte tamanhos e tenha a experiência de um + atendimento exclusivo da Li Rilko direto no seu WhatsApp. +

- Finalizar no WhatsApp - - - Ver produtos + Comprar via WhatsApp +

Tempo médio de resposta: 2 min

diff --git a/app/produto/[id]/page.js b/app/produto/[id]/page.js index a1feb2b..e21ea24 100644 --- a/app/produto/[id]/page.js +++ b/app/produto/[id]/page.js @@ -9,7 +9,7 @@ import { formatCurrency } from "@/lib/store-utils"; export default function ProductPage() { const params = useParams(); - const { publicProductMap } = useCatalog(); + const { publicProductMap, isAdmin, openEditModal } = useCatalog(); const id = Array.isArray(params?.id) ? params.id[0] : params?.id; const product = publicProductMap.get(id); const gallery = useMemo( @@ -17,23 +17,20 @@ export default function ProductPage() { [product], ); const [selectedImage, setSelectedImage] = useState(""); + const [activeTab, setActiveTab] = useState("description"); useEffect(() => { - if (!product) { - return; - } + if (!product) return; setSelectedImage(gallery[0] || ""); }, [gallery, product]); if (!product) { return ( -
-
-

Produto não encontrado

-

Esse item não está disponível no momento ou foi removido da vitrine.

- - Voltar para o catálogo - +
+
+

Product Not Found

+

This item is currently unavailable.

+ Return to Collection
); @@ -43,74 +40,105 @@ export default function ProductPage() { const priceInstallment = Number(product.priceInstallment ?? product.price ?? 0); return ( - <> -
-
-

Detalhe do produto

-

{product.name}

-

{product.shortDescription}

-
- Início +
+
+
+
+ Produto Exclusivo + {isAdmin && ( + + )} + {selectedImage ? ( + {product.name} + ) : ( +
{product.sub}
+ )} +
+
+ {gallery.map((imageUrl, idx) => ( + + ))} +
+
+ +
+
+ Home / - Catálogo + {product.category} / {product.name}
-
-
-
-
-
-
- {selectedImage ? ( - {product.name} - ) : ( - {product.sub} - )} -
-
- {gallery.slice(0, 3).map((imageUrl, index) => ( - - ))} -
-
+

{product.isAvailable === false ? "ESGOTADO" : product.badge}

+

+ {product.name} +

-
-

{product.isAvailable === false ? "Esgotado" : product.badge}

-

{product.name}

-

- {product.category} • {product.sub} -

-

{product.shortDescription}

+
+ {formatCurrency(priceCash)} à vista + {priceInstallment > 0 && priceInstallment !== priceCash && ( + ou {formatCurrency(priceInstallment)} a prazo + )} +
-
- Preço à vista: {formatCurrency(priceCash)} - Preço a prazo: {formatCurrency(priceInstallment)} -
+
+ + + +
-
    - {product.highlights.map((item) => ( -
  • {item}
  • - ))} -
+
+ {activeTab === "description" && ( + <> +

{product.shortDescription}

+
    + {product.highlights?.map((item) =>
  • {item}
  • )} +
+ + )} + {activeTab === "specs" && ( +

Materiais de alta qualidade adaptados para {product.sub}. Curadoria por Li Rilko no Brasil.

+ )} + {activeTab === "shipping" && ( +

Enviamos para todo o Brasil via Sedex. Frete grátis em pedidos acima de R$ 999. Fale com seu Especialista para opções de entrega expressa na nossa região.

+ )} +
- -
+
-
- +
+
); } diff --git a/components/admin/admin-dashboard.js b/components/admin/admin-dashboard.js index dd491e4..f175724 100644 --- a/components/admin/admin-dashboard.js +++ b/components/admin/admin-dashboard.js @@ -47,86 +47,95 @@ export default function AdminDashboard() { return ( <> -
-
-

Admin

-

Painel da Li Rilko Imports

-

Acesse somente o que precisa editar. Cada módulo abre em tela dedicada para manter a operação organizada.

-
-
+
+
+
+ + + + Li Rilko / Portal Seguro +
+
+ Ver Loja Pública +
+ +
+
+
-
-
-
-

Resumo rápido

-
-
- {summary.totalProducts} - produtos cadastrados +
+
+

Sistema Operacional

+

Selecione um módulo abaixo para gerenciar o conteúdo da vitrine.

+
+ +
+
+ CATÁLOGO ONLINE + {summary.visibleProducts} +
+
+ ESTOQUE ESGOTADO + {summary.unavailableProducts} +
+
+ RASCUNHOS / OCULTOS + {summary.hiddenProducts} +
+
+ DEPARTAMENTOS ATIVOS + {categories.length} +
+
+ +

MÓDULOS DISPONÍVEIS

+ +
+ + + + +
- -
-

Operação

-
-
-

Produtos

-

Crie, edite, oculte e altere disponibilidade dos itens do catálogo.

- -
- -
-

Categorias

-

Organize categorias e subcategorias exibidas no menu e filtros.

- -
- -
-

Atendimento

-

Gerencie atendentes no WhatsApp, canais adicionais e mensagens padrão em um único módulo.

- -
-
-
- - Ver site público - -
- -
-
-
-
-
+ +
+ +
-

Acesso restrito

-

Painel administrativo

-

- Entre com as credenciais de administrador para gerenciar produtos, categorias e dados de contato da loja. -

- - {showFallbackWarning && ( -

- Ambiente em modo de desenvolvimento: configure ADMIN_USERNAME, ADMIN_PASSWORD e{" "} - ADMIN_SESSION_SECRET no deploy. -

- )} +
+
+ + + +
+ +
+

Admin Li Rilko

+

Acesso Restrito ao Portal Seguro

+
+ + {showForgotState ? ( +
+
+ + + + +

Redefinição de Senha

+

+ Por questões de segurança, entre em contato com os administradores ou o desenvolvedor do sistema para redefinir as credenciais de acesso. +

+ +
+
+ ) : ( +
+
+ - - + - + {state?.error ?

{state.error}

: null} + {showFallbackWarning && ( +

Configure ADMIN_USERNAME e ADMIN_PASSWORD no deploy.

+ )} - {state?.error ?

{state.error}

: null} + + +
+ + SISTEMA ONLINE & CRIPTOGRAFADO +
+
+
+ )} - - +
+ + VER CATÁLOGO + + + + + + +
+ V-2.4.0_SECURE
); } diff --git a/components/admin/admin-product-modal.js b/components/admin/admin-product-modal.js new file mode 100644 index 0000000..628936a --- /dev/null +++ b/components/admin/admin-product-modal.js @@ -0,0 +1,362 @@ +"use client"; + +import { useEffect, useMemo, useCallback, useState } from "react"; +import { useCatalog } from "@/components/providers/catalog-provider"; +import { useToast } from "@/components/providers/toast-provider"; +import { formatCurrencyInput, formatCurrencyInputForEdit, parseCurrencyInputToNumber } from "@/lib/admin-input-formatters"; + + +const EMPTY_PRODUCT_FORM = { + id: "", + name: "", + categoryId: "", + subcategoryId: "", + priceCash: "", + priceInstallment: "", + badge: "", + shortDescription: "", + highlightsText: "", + isVisible: true, + isAvailable: true, +}; + +function toTextList(value) { + return String(value ?? "") + .split("\n") + .map((item) => item.trim()) + .filter(Boolean); +} + +function createDraftProductId() { + return typeof crypto !== "undefined" && typeof crypto.randomUUID === "function" + ? crypto.randomUUID() + : `draft-${Date.now()}`; +} + +function createEmptyProductForm(adminCategories) { + const firstCategory = adminCategories[0] || null; + const firstSub = firstCategory?.subs?.[0] || null; + + return { + ...EMPTY_PRODUCT_FORM, + id: createDraftProductId(), + categoryId: firstCategory?.id || "", + subcategoryId: firstSub?.id || "", + }; +} + +function productToForm(product) { + return { + ...product, + priceCash: formatCurrencyInput(product.priceCash ?? product.price ?? 0), + priceInstallment: formatCurrencyInput(product.priceInstallment ?? product.price ?? 0), + highlightsText: Array.isArray(product.highlights) ? product.highlights.join("\n") : "", + }; +} + +function normalizeImageItem(item, index) { + return { + id: item?.id || `image-${index + 1}`, + storagePath: item?.storagePath || "", + publicUrl: item?.publicUrl || item?.storagePath || "", + sortOrder: Number(item?.sortOrder ?? index), + }; +} + +export default function AdminProductModal() { + const { + editingProductId, + closeEditModal, + productMap, + adminCategories, + addProduct, + updateProduct, + uploadProductImage, + deleteProductImage, + } = useCatalog(); + const { showToast } = useToast(); + + const [productForm, setProductForm] = useState(() => createEmptyProductForm(adminCategories)); + const [productImages, setProductImages] = useState([]); + const [isSubmitting, setIsSubmitting] = useState(false); + const [isUploadingImages, setIsUploadingImages] = useState(false); + + const isOpen = editingProductId !== null; + const isNew = editingProductId === "new"; + + useEffect(() => { + if (!isOpen) return; + + if (isNew) { + setProductForm(createEmptyProductForm(adminCategories)); + setProductImages([]); + } else { + const product = productMap.get(editingProductId); + if (product) { + setProductForm(productToForm(product)); + setProductImages(Array.isArray(product.imageItems) ? product.imageItems.map(normalizeImageItem) : []); + } + } + + document.body.style.overflow = "hidden"; + + function handleEscape(event) { + if (event.key === "Escape") closeEditModal(); + } + window.addEventListener("keydown", handleEscape); + + return () => { + document.body.style.overflow = ""; + window.removeEventListener("keydown", handleEscape); + }; + }, [isOpen, isNew, editingProductId, productMap, adminCategories, closeEditModal]); + + const selectedCategory = useMemo( + () => adminCategories.find((category) => category.id === productForm.categoryId) || null, + [adminCategories, productForm.categoryId] + ); + const availableSubcategories = useMemo(() => selectedCategory?.subs || [], [selectedCategory]); + + function handleProductField(field, value) { + setProductForm((prev) => ({ ...prev, [field]: value })); + } + + function handleCategoryChange(categoryId) { + const category = adminCategories.find((item) => item.id === categoryId) || null; + setProductForm((prev) => ({ + ...prev, + categoryId, + subcategoryId: category?.subs?.[0]?.id || "", + })); + } + + function handlePriceFieldChange(field, value) { + setProductForm((prev) => ({ ...prev, [field]: value })); + } + + function handlePriceFieldFocus(field) { + setProductForm((prev) => ({ ...prev, [field]: formatCurrencyInputForEdit(prev[field]) })); + } + + function handlePriceFieldBlur(field) { + setProductForm((prev) => { + const rawValue = String(prev[field] ?? "").trim(); + if (!rawValue) return { ...prev, [field]: "" }; + return { ...prev, [field]: formatCurrencyInput(prev[field]) }; + }); + } + + function buildProductPayload() { + return { + id: productForm.id, + name: productForm.name, + categoryId: productForm.categoryId, + subcategoryId: productForm.subcategoryId, + priceCash: parseCurrencyInputToNumber(productForm.priceCash), + priceInstallment: parseCurrencyInputToNumber(productForm.priceInstallment), + badge: productForm.badge, + shortDescription: productForm.shortDescription, + highlights: toTextList(productForm.highlightsText), + isVisible: productForm.isVisible, + isAvailable: productForm.isAvailable, + imageItems: productImages.map((item) => ({ + id: item.id, + storagePath: item.storagePath, + })), + }; + } + + function validatePayload(payload) { + if (!payload.name || !payload.categoryId || !payload.subcategoryId) return "Nome, categoria e subcategoria são obrigatórios."; + if (!Array.isArray(payload.imageItems) || payload.imageItems.length === 0) return "Adicione ao menos uma imagem na galeria."; + return ""; + } + + async function handleUploadFiles(fileList) { + const files = Array.from(fileList || []).filter(Boolean); + if (files.length === 0) return; + setIsUploadingImages(true); + + const uploadedItems = []; + for (const file of files) { + const result = await uploadProductImage(productForm.id, file); + if (result.ok && result.image) { + uploadedItems.push(normalizeImageItem(result.image, uploadedItems.length)); + } else { + showToast({ type: "warning", title: "Falha no upload", message: result.error || "Não foi possível enviar a imagem." }); + } + } + + setProductImages((prev) => [...prev, ...uploadedItems].slice(0, 6).map(normalizeImageItem)); + setIsUploadingImages(false); + } + + async function handleRemoveImage(image, index) { + const result = await deleteProductImage(productForm.id, image.id); + if (!result.ok) { + showToast({ type: "warning", title: "Erro na exclusão", message: result.error || "Não foi possível excluir a imagem." }); + return; + } + setProductImages((prev) => prev.filter((_, i) => i !== index).map(normalizeImageItem)); + } + + async function handleSaveProduct(event) { + event.preventDefault(); + const payload = buildProductPayload(); + const error = validatePayload(payload); + if (error) { + showToast({ type: "warning", title: "Dados incompletos", message: error }); + return; + } + + setIsSubmitting(true); + try { + if (!isNew) { + const result = await updateProduct(editingProductId, payload); + if (result.ok) { + showToast({ type: "success", title: "Produto Salvo", message: "As informações foram atualizadas no catálogo." }); + closeEditModal(); + } else { + showToast({ type: "warning", title: "Erro ao salvar", message: result.error }); + } + } else { + const result = await addProduct(payload); + if (result.ok) { + showToast({ type: "success", title: "Produto Criado", message: "Novo produto adicionado à loja." }); + closeEditModal(); + } else { + showToast({ type: "warning", title: "Erro ao criar", message: result.error }); + } + } + } finally { + setIsSubmitting(false); + } + } + + if (!isOpen) return null; + + return ( + <> +
+
+
+
+

{isNew ? "Novo Produto" : "Editar Produto"}

+ PRODUCT ID: #{productForm.id.split("-").pop().substring(0,6).toUpperCase()} +
+ +
+ +
+
+ + handleProductField("name", e.target.value)} + required + /> +
+ +
+
+ + +
+
+ + handlePriceFieldChange("priceCash", e.target.value)} + onFocus={() => handlePriceFieldFocus("priceCash")} + onBlur={() => handlePriceFieldBlur("priceCash")} + required + /> +
+
+ +
+ + +
+ +
+ +