diff --git a/.env.example b/.env.example index 06f9aa7..faf89f5 100644 --- a/.env.example +++ b/.env.example @@ -1,11 +1,9 @@ ADMIN_USERNAME=admin ADMIN_PASSWORD=troque-por-uma-senha-forte ADMIN_SESSION_SECRET=troque-este-segredo-longo-e-aleatorio -GITHUB_TOKEN=ghp_troque_por_um_token_com_repo_contents_write_e_pull_requests_write -GITHUB_REPO_OWNER=ArielAio -GITHUB_REPO_NAME=Li-Rilko -GITHUB_REPO_BRANCH=main -GITHUB_ATTENDANTS_PATH=data/attendants.json -GITHUB_ATTENDANTS_WORK_BRANCH=bot/attendants-admin -GITHUB_ATTENDANTS_AUTO_MERGE=true -GITHUB_ATTENDANTS_AUTO_MERGE_METHOD=squash +NEXT_PUBLIC_GA_MEASUREMENT_ID= +NEXT_PUBLIC_SITE_URL=localhost +NEXT_PUBLIC_SUPABASE_URL= +NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY= +SUPABASE_SERVICE_ROLE_KEY= +SUPABASE_STORAGE_BUCKET_PRODUCTS=product-images diff --git a/TESTING.md b/TESTING.md index 88df3e3..22a0cbe 100644 --- a/TESTING.md +++ b/TESTING.md @@ -4,6 +4,7 @@ - Unit/Integration: Vitest + Testing Library - E2E smoke: Playwright (Chromium) - CI pipeline: GitHub Actions (`.github/workflows/quality-gate.yml`) +- Admin persistence does not use GitHub anymore; CI only validates tests/builds. ## Commands - `npm run test:unit` @@ -11,6 +12,12 @@ - `npm run test:e2e:smoke` - `npm run test:known-issues` - `npm run test:gate` (unit + integration + build + e2e smoke) +- `npm run supabase:seed` (importa catálogo inicial, atendentes e imagens no projeto Supabase configurado no ambiente) + +## Supabase bootstrap +- Migration inicial: [supabase/migrations/20260319_000001_catalog_phase1.sql](/Users/arielaio/Desktop/Arquivos/Projetos/Projetos%20com%20Siconeli/Li%20Rilko/supabase/migrations/20260319_000001_catalog_phase1.sql) +- Seed local: [scripts/supabase-seed.cjs](/Users/arielaio/Desktop/Arquivos/Projetos/Projetos%20com%20Siconeli/Li%20Rilko/scripts/supabase-seed.cjs) +- O bucket `product-images` precisa existir no projeto antes do seed. ## Gate policy `test:gate` is the blocking suite for important deploys (push/merge to `main`). diff --git a/app/api/admin/attendants/route.js b/app/api/admin/attendants/route.js index dc79159..cb35ccb 100644 --- a/app/api/admin/attendants/route.js +++ b/app/api/admin/attendants/route.js @@ -1,135 +1,55 @@ -import { NextResponse } from "next/server"; -import { ADMIN_SESSION_COOKIE, isAdminSessionValid } from "@/lib/admin-auth"; +import { adminJson, requireAdminRequest } from "@/lib/admin-route"; import { - AttendantsGitHubSyncError, - AttendantsValidationError, - readAttendantsFromRepositoryFile, - updateAttendantsInRepository, -} from "@/lib/attendants-store"; + CatalogRepositoryConfigError, + CatalogRepositoryValidationError, + getAdminBootstrapSnapshot, + saveAttendantsInCatalog, +} from "@/lib/catalog-repository"; export const runtime = "nodejs"; -function isAuthenticated(request) { - const sessionToken = request.cookies.get(ADMIN_SESSION_COOKIE)?.value ?? ""; - return isAdminSessionValid(sessionToken); -} - -function unauthorizedResponse() { - return NextResponse.json( - { error: "Acesso negado. Faça login no painel admin." }, - { - status: 401, - headers: { - "Cache-Control": "no-store", - }, - }, - ); -} - export async function GET(request) { - if (!isAuthenticated(request)) { - return unauthorizedResponse(); + const unauthorized = requireAdminRequest(request); + if (unauthorized) { + return unauthorized; } try { - const attendants = await readAttendantsFromRepositoryFile(); - - return NextResponse.json( - { attendants }, - { - status: 200, - headers: { - "Cache-Control": "no-store", - }, - }, - ); + const catalog = await getAdminBootstrapSnapshot(); + return adminJson({ attendants: catalog.attendants }); } catch { - return NextResponse.json( - { error: "Não foi possível carregar atendentes agora." }, - { - status: 500, - headers: { - "Cache-Control": "no-store", - }, - }, - ); + return adminJson({ error: "Não foi possível carregar atendentes agora." }, 500); } } export async function PUT(request) { - if (!isAuthenticated(request)) { - return unauthorizedResponse(); + const unauthorized = requireAdminRequest(request); + if (unauthorized) { + return unauthorized; } let payload; try { payload = await request.json(); } catch { - return NextResponse.json( - { error: "Payload inválido. Envie JSON no formato correto." }, - { - status: 400, - headers: { - "Cache-Control": "no-store", - }, - }, - ); + return adminJson({ error: "Payload inválido. Envie JSON no formato correto." }, 400); } try { - const result = await updateAttendantsInRepository(payload?.attendants); - - return NextResponse.json( - { - attendants: result.attendants, - commitSha: result.commitSha, - pullRequestUrl: result.pullRequestUrl, - pullRequestNumber: result.pullRequestNumber, - workBranch: result.workBranch, - unchanged: result.unchanged, - autoMergeRequested: result.autoMergeRequested, - autoMergeStatusMessage: result.autoMergeStatusMessage, - }, - { - status: 200, - headers: { - "Cache-Control": "no-store", - }, - }, - ); + const result = await saveAttendantsInCatalog(payload?.attendants); + return adminJson({ + attendants: result.catalog.attendants, + catalog: result.catalog, + }); } catch (error) { - if (error instanceof AttendantsValidationError) { - return NextResponse.json( - { error: error.message }, - { - status: 400, - headers: { - "Cache-Control": "no-store", - }, - }, - ); + if (error instanceof CatalogRepositoryValidationError) { + return adminJson({ error: error.message }, 400); } - if (error instanceof AttendantsGitHubSyncError) { - return NextResponse.json( - { error: error.message }, - { - status: 502, - headers: { - "Cache-Control": "no-store", - }, - }, - ); + if (error instanceof CatalogRepositoryConfigError) { + return adminJson({ error: error.message }, 503); } - return NextResponse.json( - { error: "Erro interno ao salvar atendentes." }, - { - status: 500, - headers: { - "Cache-Control": "no-store", - }, - }, - ); + return adminJson({ error: "Erro interno ao salvar atendentes." }, 500); } } diff --git a/app/api/admin/bootstrap/route.js b/app/api/admin/bootstrap/route.js new file mode 100644 index 0000000..a158f56 --- /dev/null +++ b/app/api/admin/bootstrap/route.js @@ -0,0 +1,18 @@ +import { adminJson, requireAdminRequest } from "@/lib/admin-route"; +import { getAdminBootstrapSnapshot } from "@/lib/catalog-repository"; + +export const runtime = "nodejs"; + +export async function GET(request) { + const unauthorized = requireAdminRequest(request); + if (unauthorized) { + return unauthorized; + } + + try { + const catalog = await getAdminBootstrapSnapshot(); + return adminJson({ catalog }); + } catch { + return adminJson({ error: "Não foi possível carregar os dados administrativos agora." }, 500); + } +} diff --git a/app/api/admin/categories/route.js b/app/api/admin/categories/route.js new file mode 100644 index 0000000..80ba6df --- /dev/null +++ b/app/api/admin/categories/route.js @@ -0,0 +1,37 @@ +import { adminJson, requireAdminRequest } from "@/lib/admin-route"; +import { + CatalogRepositoryConfigError, + CatalogRepositoryValidationError, + saveCategoriesInCatalog, +} from "@/lib/catalog-repository"; + +export const runtime = "nodejs"; + +export async function PUT(request) { + const unauthorized = requireAdminRequest(request); + if (unauthorized) { + return unauthorized; + } + + let payload; + try { + payload = await request.json(); + } catch { + return adminJson({ error: "Payload inválido. Envie JSON no formato correto." }, 400); + } + + try { + const result = await saveCategoriesInCatalog(payload?.categories); + return adminJson({ catalog: result.catalog }); + } 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 salvar categorias." }, 500); + } +} diff --git a/app/api/admin/contact-channels/route.js b/app/api/admin/contact-channels/route.js new file mode 100644 index 0000000..4ad4ff8 --- /dev/null +++ b/app/api/admin/contact-channels/route.js @@ -0,0 +1,37 @@ +import { adminJson, requireAdminRequest } from "@/lib/admin-route"; +import { + CatalogRepositoryConfigError, + CatalogRepositoryValidationError, + saveContactChannelsInCatalog, +} from "@/lib/catalog-repository"; + +export const runtime = "nodejs"; + +export async function PUT(request) { + const unauthorized = requireAdminRequest(request); + if (unauthorized) { + return unauthorized; + } + + let payload; + try { + payload = await request.json(); + } catch { + return adminJson({ error: "Payload inválido. Envie JSON no formato correto." }, 400); + } + + try { + const result = await saveContactChannelsInCatalog(payload?.contactChannels); + return adminJson({ catalog: result.catalog }); + } 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 salvar canais." }, 500); + } +} diff --git a/app/api/admin/products/[id]/images/[imageId]/route.js b/app/api/admin/products/[id]/images/[imageId]/route.js new file mode 100644 index 0000000..fb8085f --- /dev/null +++ b/app/api/admin/products/[id]/images/[imageId]/route.js @@ -0,0 +1,32 @@ +import { adminJson, requireAdminRequest } from "@/lib/admin-route"; +import { + CatalogRepositoryConfigError, + CatalogRepositoryValidationError, + deleteProductImageAsset, +} from "@/lib/catalog-repository"; + +export const runtime = "nodejs"; + +export async function DELETE(request, context) { + const unauthorized = requireAdminRequest(request); + if (unauthorized) { + return unauthorized; + } + + const { id, imageId } = await context.params; + + try { + await deleteProductImageAsset(id, imageId); + return adminJson({ ok: true }); + } 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 imagem do produto." }, 500); + } +} diff --git a/app/api/admin/products/[id]/images/route.js b/app/api/admin/products/[id]/images/route.js new file mode 100644 index 0000000..9c7b590 --- /dev/null +++ b/app/api/admin/products/[id]/images/route.js @@ -0,0 +1,41 @@ +import { adminJson, requireAdminRequest } from "@/lib/admin-route"; +import { + CatalogRepositoryConfigError, + CatalogRepositoryValidationError, + uploadProductImageAsset, +} from "@/lib/catalog-repository"; + +export const runtime = "nodejs"; + +export async function POST(request, context) { + const unauthorized = requireAdminRequest(request); + if (unauthorized) { + return unauthorized; + } + + const { id } = await context.params; + let formData; + + try { + formData = await request.formData(); + } catch { + return adminJson({ error: "Payload inválido. Envie multipart/form-data corretamente." }, 400); + } + + const file = formData.get("file"); + + try { + const image = await uploadProductImageAsset(id, file); + return adminJson({ image }); + } 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 enviar imagem do produto." }, 500); + } +} diff --git a/app/api/admin/products/[id]/route.js b/app/api/admin/products/[id]/route.js new file mode 100644 index 0000000..f4bee57 --- /dev/null +++ b/app/api/admin/products/[id]/route.js @@ -0,0 +1,64 @@ +import { adminJson, requireAdminRequest } from "@/lib/admin-route"; +import { + CatalogRepositoryConfigError, + CatalogRepositoryValidationError, + deleteProductFromCatalog, + updateProductInCatalog, +} from "@/lib/catalog-repository"; + +export const runtime = "nodejs"; + +export async function PUT(request, context) { + const unauthorized = requireAdminRequest(request); + if (unauthorized) { + return unauthorized; + } + + const { id } = await context.params; + + let payload; + try { + payload = await request.json(); + } catch { + return adminJson({ error: "Payload inválido. Envie JSON no formato correto." }, 400); + } + + try { + const result = await updateProductInCatalog(id, payload); + return adminJson({ catalog: result.catalog }); + } 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 atualizar produto." }, 500); + } +} + +export async function DELETE(request, context) { + const unauthorized = requireAdminRequest(request); + if (unauthorized) { + return unauthorized; + } + + const { id } = await context.params; + + try { + const result = await deleteProductFromCatalog(id); + return adminJson({ catalog: result.catalog }); + } 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 produto." }, 500); + } +} diff --git a/app/api/admin/products/route.js b/app/api/admin/products/route.js new file mode 100644 index 0000000..769d9d8 --- /dev/null +++ b/app/api/admin/products/route.js @@ -0,0 +1,40 @@ +import { adminJson, requireAdminRequest } from "@/lib/admin-route"; +import { + CatalogRepositoryConfigError, + CatalogRepositoryValidationError, + createProductInCatalog, +} 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 inválido. Envie JSON no formato correto." }, 400); + } + + try { + const result = await createProductInCatalog(payload); + return adminJson({ + catalog: result.catalog, + productId: result.productId, + }); + } 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 criar produto." }, 500); + } +} diff --git a/app/api/admin/site-settings/route.js b/app/api/admin/site-settings/route.js new file mode 100644 index 0000000..94f299b --- /dev/null +++ b/app/api/admin/site-settings/route.js @@ -0,0 +1,37 @@ +import { adminJson, requireAdminRequest } from "@/lib/admin-route"; +import { + CatalogRepositoryConfigError, + CatalogRepositoryValidationError, + saveSiteSettingsInCatalog, +} from "@/lib/catalog-repository"; + +export const runtime = "nodejs"; + +export async function PUT(request) { + const unauthorized = requireAdminRequest(request); + if (unauthorized) { + return unauthorized; + } + + let payload; + try { + payload = await request.json(); + } catch { + return adminJson({ error: "Payload inválido. Envie JSON no formato correto." }, 400); + } + + try { + const result = await saveSiteSettingsInCatalog(payload?.siteSettings); + return adminJson({ catalog: result.catalog }); + } 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 salvar configurações do site." }, 500); + } +} diff --git a/app/carrinho/page.js b/app/carrinho/page.js index bb4c313..85369a7 100644 --- a/app/carrinho/page.js +++ b/app/carrinho/page.js @@ -12,13 +12,12 @@ import { buildAttendantWhatsAppLink, buildWhatsAppMessage, formatCurrency } from import { openWhatsAppLink, resolveWhatsAppAttendantAction } from "@/lib/whatsapp-attendant-flow"; export default function CartPage() { - const { siteSettings } = useCatalog(); + const { attendants, siteSettings } = useCatalog(); const { items, total, count, addItem, decreaseItem, removeItem, clearCart } = useCart(); const { showToast } = useToast(); const [isPickerOpen, setIsPickerOpen] = useState(false); const [pendingMessage, setPendingMessage] = useState(""); - const attendantFlow = resolveAttendantFlow(); - const attendants = attendantFlow.attendants; + const attendantFlow = resolveAttendantFlow(attendants); const message = buildWhatsAppMessage(items, siteSettings); diff --git a/app/contato/page.js b/app/contato/page.js index 20631b2..2b97d2a 100644 --- a/app/contato/page.js +++ b/app/contato/page.js @@ -11,13 +11,12 @@ import { buildAttendantWhatsAppLink, buildWhatsAppMessage } from "@/lib/store-ut import { openWhatsAppLink, resolveWhatsAppAttendantAction } from "@/lib/whatsapp-attendant-flow"; export default function ContactPage() { - const { contactChannels, siteSettings } = useCatalog(); + const { attendants, contactChannels, siteSettings } = useCatalog(); const { items } = useCart(); const { showToast } = useToast(); const [isPickerOpen, setIsPickerOpen] = useState(false); const [pendingMessage, setPendingMessage] = useState(""); - const attendantFlow = resolveAttendantFlow(); - const attendants = attendantFlow.attendants; + const attendantFlow = resolveAttendantFlow(attendants); const message = buildWhatsAppMessage(items, siteSettings); function handleStartContact(event) { diff --git a/app/layout.js b/app/layout.js index fcd532e..298e88f 100644 --- a/app/layout.js +++ b/app/layout.js @@ -1,6 +1,7 @@ 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 "./globals.css"; const displayFont = Sora({ @@ -21,15 +22,16 @@ export const metadata = { "Loja Li Rilko: catálogo por categorias, carrinho multi-itens e finalização rápida via WhatsApp.", }; -export default function RootLayout({ children }) { +export default async function RootLayout({ children }) { + const initialCatalog = await getPublicCatalogSnapshot(); + return ( - + {children} ); } - diff --git a/components/admin/managers/admin-categories-manager.js b/components/admin/managers/admin-categories-manager.js index b7d8e04..e605e6f 100644 --- a/components/admin/managers/admin-categories-manager.js +++ b/components/admin/managers/admin-categories-manager.js @@ -4,15 +4,21 @@ import { useEffect, useRef, useState } from "react"; import { useCatalog } from "@/components/providers/catalog-provider"; import { useToast } from "@/components/providers/toast-provider"; -function toTextList(value) { - return String(value ?? "") - .split("\n") - .map((item) => item.trim()) - .filter(Boolean); +function createCategoryDraft(category = null) { + return { + id: category?.id || "", + name: category?.name || "", + subs: Array.isArray(category?.subs) + ? category.subs.map((sub) => ({ + id: sub.id || "", + name: sub.name || "", + })) + : [{ id: "", name: "" }], + }; } export default function AdminCategoriesManager() { - const { categories, saveCategories } = useCatalog(); + const { adminCategories, saveCategories } = useCatalog(); const { showToast } = useToast(); const [categoryDrafts, setCategoryDrafts] = useState([]); const [isEditMode, setIsEditMode] = useState(false); @@ -21,8 +27,8 @@ export default function AdminCategoriesManager() { const editorFormRef = useRef(null); useEffect(() => { - setCategoryDrafts(categories.map((category) => ({ name: category.name, subsText: category.subs.join("\n") }))); - }, [categories]); + setCategoryDrafts(adminCategories.map((category) => createCategoryDraft(category))); + }, [adminCategories]); useEffect(() => { if (!isEditMode || !shouldRevealEditorRef.current) { @@ -44,16 +50,68 @@ export default function AdminCategoriesManager() { function openEditor() { shouldRevealEditorRef.current = true; - setCategoryDrafts(categories.map((category) => ({ name: category.name, subsText: category.subs.join("\n") }))); + setCategoryDrafts(adminCategories.map((category) => createCategoryDraft(category))); setIsEditMode(true); } + function updateCategoryField(index, field, value) { + setCategoryDrafts((prev) => + prev.map((category, rowIndex) => (rowIndex === index ? { ...category, [field]: value } : category)), + ); + } + + function updateSubField(categoryIndex, subIndex, value) { + setCategoryDrafts((prev) => + prev.map((category, rowIndex) => { + if (rowIndex !== categoryIndex) { + return category; + } + + return { + ...category, + subs: category.subs.map((sub, currentIndex) => (currentIndex === subIndex ? { ...sub, name: value } : sub)), + }; + }), + ); + } + + function addSubcategory(categoryIndex) { + setCategoryDrafts((prev) => + prev.map((category, rowIndex) => + rowIndex === categoryIndex ? { ...category, subs: [...category.subs, { id: "", name: "" }] } : category, + ), + ); + } + + function removeSubcategory(categoryIndex, subIndex) { + setCategoryDrafts((prev) => + prev.map((category, rowIndex) => { + if (rowIndex !== categoryIndex || category.subs.length <= 1) { + return category; + } + + return { + ...category, + subs: category.subs.filter((_, currentIndex) => currentIndex !== subIndex), + }; + }), + ); + } + async function handleSaveCategories(event) { event.preventDefault(); const normalized = categoryDrafts .map((category) => ({ + id: category.id, name: String(category.name || "").trim(), - subs: toTextList(String(category.subsText || "")), + subs: Array.isArray(category.subs) + ? category.subs + .map((sub) => ({ + id: sub.id, + name: String(sub.name || "").trim(), + })) + .filter((sub) => sub.name) + : [], })) .filter((category) => category.name); @@ -77,12 +135,8 @@ export default function AdminCategoriesManager() { } setIsSubmitting(true); - let result = null; - try { - result = await saveCategories(normalized); - } finally { - setIsSubmitting(false); - } + const result = await saveCategories(normalized); + setIsSubmitting(false); if (!result.ok) { showToast({ @@ -124,47 +178,48 @@ export default function AdminCategoriesManager() { {isEditMode ? (
{categoryDrafts.map((category, index) => ( -
+
-