Spaces:
Sleeping
Sleeping
Deploy ZippMart admin dashboard (Docker Space)
Browse filesFiles changed (24)
- DockerfileAdded+30
- README.md+19-8
- apps/admin-web/.env.exampleAdded+4
- apps/admin-web/app/admin/dashboard/page.tsxAdded+1141
- apps/admin-web/app/admin/page.tsxAdded+90
- apps/admin-web/app/components/BarcodeCameraScanner.tsxAdded+155
- apps/admin-web/app/components/StockAdjustModal.tsxAdded+136
- apps/admin-web/app/globals.cssAdded+1259
- apps/admin-web/app/layout.tsxAdded+16
- apps/admin-web/app/page.tsxAdded+13
- apps/admin-web/lib/adminAuth.tsAdded+35
- apps/admin-web/lib/api.tsAdded+1
- apps/admin-web/next-env.d.tsAdded+6
- apps/admin-web/next.config.tsAdded+13
- apps/admin-web/package.jsonAdded+25
- apps/admin-web/tsconfig.jsonAdded+15
- apps/admin-web/vercel.jsonAdded+6
- deploy/huggingface-admin/DockerfileAdded+30
- deploy/huggingface-admin/README.mdAdded+24
- deploy/huggingface-admin/push.ps1Added+52
- deploy/huggingface-admin/start.shAdded+3
- package-lock.jsonAdded
- package.jsonAdded+33
- tsconfig.base.jsonAdded+13
123456789101112131415161718192021222324252627282930FROM node:22-alpine AS buildWORKDIR /app
COPY package.json package-lock.json ./COPY tsconfig.base.json ./COPY apps/admin-web/package.json ./apps/admin-web/
RUN npm ci
COPY apps/admin-web ./apps/admin-web
ENV NEXT_PUBLIC_API_BASE_URL=https://adi576-zippmart.hf.space/checkout-apiRUN npm run build -w admin-web \ && test -f apps/admin-web/.next/BUILD_ID \ && test -d apps/admin-web/.next/standalone
FROM node:22-alpineWORKDIR /app
ENV NODE_ENV=productionENV PORT=7860ENV HOSTNAME=0.0.0.0
COPY --from=build /app/apps/admin-web/.next/standalone ./COPY --from=build /app/apps/admin-web/.next/static ./apps/admin-web/.next/staticCOPY deploy/huggingface-admin/start.sh /start.shRUN chmod +x /start.sh
EXPOSE 7860CMD ["/start.sh"]12345678910111213---title: Zippmart Adminemoji: 👁colorFrom: yellowcolorTo: purplesdk: gradiosdk_version: 6.14.0python_version: '3.13'app_file: app.pypinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference123456789101112131415161718192021222324---title: Zippmart Adminemoji: 📊colorFrom: purplecolorTo: redsdk: dockerapp_port: 7860pinned: false---# ZippMart Admin HQStaff and manager dashboard for catalogue, stock, orders, and store KPIs.Open **/admin** to sign in.Uses the API on the main ZippMart Space: `https://adi576-zippmart.hf.space/checkout-api`## Default loginsSet via secrets on the **main** API Space (`ADMIN_*` / `MANAGER_*`). Dev defaults if unchanged:- Staff: `admin` / `admin123`- Manager: `manager` / `manager123`
1234NEXT_PUBLIC_API_BASE_URL=http://localhost:4000
# Vercel: API_PROXY_TARGET=https://zippmart.onrender.com# Vercel: NEXT_PUBLIC_API_BASE_URL=/checkout-api1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141"use client";
import { useRouter } from "next/navigation";import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { BarcodeCameraScanner } from "../../components/BarcodeCameraScanner";import { StockAdjustModal } from "../../components/StockAdjustModal";import { adminFetchHeaders, clearAdminToken, getAdminRole, getAdminToken } from "../../../lib/adminAuth";
import { apiBase } from "../../../lib/api";
const CATEGORY_OPTIONS = [ "General", "Grocery", "Dairy", "Beverages", "Snacks", "Produce", "Frozen", "Bakery", "Meat & Seafood", "Personal Care", "Household", "Electronics"] as const;
type FormErrors = Partial<Record<"barcode" | "name" | "category" | "costPrice" | "sellingPrice" | "taxPercent" | "inStock" | "demandScore", string>>;
type AdminProduct = { id: string; name: string; barcode: string; category: string; unitPrice: number; costPrice: number; taxPercent: number; inStock: number; demandScore: number; imageUrl?: string | null; discountPercent: number; effectiveUnitPrice: number; profitPerUnitAtList: number; profitPerUnitAtSale: number;};
type Metrics = { orderCount: number; paidOrderCount: number; openOrderCount: number; totalRevenue: number; pendingOrderValue: number; averagePaidOrderValue: number; productCount: number; lowStockSkuCount: number; inventoryValueAtCost: number; inventoryValueAtList: number; activeDiscountCount: number;};
type DiscountRow = { productId: string; name: string; barcode: string; category: string; listPrice: number; discountPercent: number; effectiveUnitPrice: number; profitPerUnitAtList: number; profitPerUnitAtSale: number;};
type AdminOrderRow = { orderId: string; createdAt: string; storeCode: string; paid: boolean; voided: boolean; refunded: boolean; paymentMode: string; tokenNumber: number | null; grandTotal: number; lineCount: number;};
type AuditRow = { id: string; at: string; actor: string; role: string; action: string; detail: string;};
function money(n: number) { return `₹${n.toLocaleString("en-IN", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;}
export default function AdminDashboardPage() { const router = useRouter(); const [products, setProducts] = useState<AdminProduct[]>([]); const [metrics, setMetrics] = useState<Metrics | null>(null); const [discounts, setDiscounts] = useState<DiscountRow[]>([]); const [message, setMessage] = useState(""); const [loading, setLoading] = useState(false);
const [barcode, setBarcode] = useState(""); const [name, setName] = useState(""); const [category, setCategory] = useState("General"); const [costPrice, setCostPrice] = useState(""); const [sellingPrice, setSellingPrice] = useState(""); const [taxPercent, setTaxPercent] = useState("5"); const [inStock, setInStock] = useState("0"); const [demandScore, setDemandScore] = useState("0"); const [imageUrl, setImageUrl] = useState(""); const [imageUploading, setImageUploading] = useState(false); const [cameraOn, setCameraOn] = useState(false); const imageInputRef = useRef<HTMLInputElement>(null); const inventoryImageInputRef = useRef<HTMLInputElement>(null); const [imageTargetId, setImageTargetId] = useState<string | null>(null); const [formErrors, setFormErrors] = useState<FormErrors>({}); const [barcodeConflict, setBarcodeConflict] = useState<AdminProduct | null>(null); const nameInputRef = useRef<HTMLInputElement>(null);
const [discountProductId, setDiscountProductId] = useState(""); const [discountPct, setDiscountPct] = useState("10"); const [orders, setOrders] = useState<AdminOrderRow[]>([]); const [invFilter, setInvFilter] = useState(""); const [lowStockOnlyView, setLowStockOnlyView] = useState(false); const [storeFilter, setStoreFilter] = useState(""); const [adminRole, setAdminRole] = useState<string | null>(null); const [auditEntries, setAuditEntries] = useState<AuditRow[]>([]); const [authChecked, setAuthChecked] = useState(false); const [authed, setAuthed] = useState(false); const [stockModalProduct, setStockModalProduct] = useState<Pick<AdminProduct, "id" | "name" | "barcode" | "inStock"> | null>(null); const [stockModalBusy, setStockModalBusy] = useState(false);
const formProfit = useMemo(() => { const sell = Number(sellingPrice); const cost = Number(costPrice); if (!Number.isFinite(sell) || !Number.isFinite(cost) || sell <= 0) return null; return Math.round((sell - cost) * 100) / 100; }, [sellingPrice, costPrice]);
const filteredProducts = useMemo(() => { let list = products; if (lowStockOnlyView) { list = list.filter((p) => p.inStock < 15); } const t = invFilter.trim().toLowerCase(); if (!t) return list; return list.filter( (p) => p.name.toLowerCase().includes(t) || p.barcode.toLowerCase().includes(t) || p.category.toLowerCase().includes(t) ); }, [products, invFilter, lowStockOnlyView]);
const lowStockCount = useMemo(() => products.filter((p) => p.inStock < 15).length, [products]);
function resolveBarcodeConflict(code: string) { const trimmed = code.trim(); if (!trimmed) { setBarcodeConflict(null); return; } const existing = products.find((p) => p.barcode === trimmed); setBarcodeConflict(existing ?? null); }
function validateProductForm(): FormErrors { const errors: FormErrors = {}; const trimmedBarcode = barcode.trim(); const trimmedName = name.trim(); const trimmedCategory = category.trim(); const cost = Number(costPrice); const sell = Number(sellingPrice); const tax = Number(taxPercent); const stock = Number(inStock); const demand = Number(demandScore);
if (!trimmedBarcode) errors.barcode = "Barcode is required."; else if (trimmedBarcode.length < 4) errors.barcode = "Barcode must be at least 4 characters."; else if (products.some((p) => p.barcode === trimmedBarcode)) errors.barcode = "This barcode is already in the catalogue.";
if (!trimmedName) errors.name = "Product name is required."; if (!trimmedCategory) errors.category = "Category is required.";
if (!costPrice.trim()) errors.costPrice = "Unit cost is required."; else if (!Number.isFinite(cost) || cost < 0) errors.costPrice = "Enter a valid non-negative cost.";
if (!sellingPrice.trim()) errors.sellingPrice = "Selling price is required."; else if (!Number.isFinite(sell) || sell <= 0) errors.sellingPrice = "Selling price must be greater than zero."; else if (Number.isFinite(cost) && cost > sell) errors.sellingPrice = "Selling price must be at or above unit cost.";
if (!Number.isFinite(tax) || tax < 0 || tax > 100) errors.taxPercent = "Tax must be between 0 and 100."; if (!Number.isFinite(stock) || stock < 0 || !Number.isInteger(stock)) errors.inStock = "Stock must be a whole number ≥ 0."; if (!Number.isFinite(demand) || demand < 0 || demand > 100) errors.demandScore = "Demand score must be between 0 and 100.";
return errors; }
function resetProductForm() { setBarcode(""); setName(""); setCategory("General"); setCostPrice(""); setSellingPrice(""); setTaxPercent("5"); setInStock("0"); setDemandScore("0"); setImageUrl(""); setImageUploading(false); setFormErrors({}); setBarcodeConflict(null); setCameraOn(false); }
function handleBarcodeInput(value: string) { setBarcode(value); setFormErrors((prev) => ({ ...prev, barcode: undefined })); resolveBarcodeConflict(value); }
function handleBarcodeDecoded(text: string) { const code = text.trim(); if (!code) return; handleBarcodeInput(code); setCameraOn(false); setMessage(`Barcode captured: ${code}`); window.setTimeout(() => nameInputRef.current?.focus(), 80); }
useEffect(() => { const token = getAdminToken(); setAuthed(!!token); setAdminRole(getAdminRole()); setAuthChecked(true); if (!token) router.replace("/admin"); }, [router]);
const loadProducts = useCallback(async () => { const resp = await fetch(`${apiBase}/v1/admin/products`, { headers: adminFetchHeaders() }); if (resp.status === 401) { clearAdminToken(); router.replace("/admin"); return; } if (resp.ok) setProducts(await resp.json()); }, [router]);
const loadMetrics = useCallback(async () => { const qs = storeFilter.trim() ? `?storeCode=${encodeURIComponent(storeFilter.trim().toUpperCase())}` : ""; const resp = await fetch(`${apiBase}/v1/admin/metrics${qs}`, { headers: adminFetchHeaders() }); if (resp.status === 401) { clearAdminToken(); router.replace("/admin"); return; } if (resp.ok) setMetrics(await resp.json()); }, [router, storeFilter]);
const loadDiscounts = useCallback(async () => { const resp = await fetch(`${apiBase}/v1/admin/discounts`, { headers: adminFetchHeaders() }); if (resp.status === 401) { clearAdminToken(); router.replace("/admin"); return; } if (resp.ok) setDiscounts(await resp.json()); }, [router]);
const loadOrders = useCallback(async () => { const qs = new URLSearchParams({ limit: "30" }); if (storeFilter.trim()) qs.set("storeCode", storeFilter.trim().toUpperCase()); const resp = await fetch(`${apiBase}/v1/admin/orders?${qs.toString()}`, { headers: adminFetchHeaders() }); if (resp.status === 401) { clearAdminToken(); router.replace("/admin"); return; } if (resp.ok) setOrders(await resp.json()); }, [router, storeFilter]);
const loadAudit = useCallback(async () => { const resp = await fetch(`${apiBase}/v1/admin/audit`, { headers: adminFetchHeaders() }); if (resp.status === 401) { clearAdminToken(); router.replace("/admin"); return; } if (resp.ok) setAuditEntries(await resp.json()); }, [router]);
useEffect(() => { if (!authed) return; void loadProducts(); void loadMetrics(); void loadDiscounts(); void loadOrders(); }, [authed, loadProducts, loadMetrics, loadDiscounts, loadOrders]);
function logout() { clearAdminToken(); router.replace("/admin"); }
const isManager = adminRole === "manager";
async function voidOrder(orderId: string) { if (!confirm("Void this unpaid order? It will disappear from open totals.")) return; const resp = await fetch(`${apiBase}/v1/admin/orders/${encodeURIComponent(orderId)}/void`, { method: "POST", headers: adminFetchHeaders(true) }); if (resp.ok) { setMessage("Order voided."); await loadOrders(); await loadMetrics(); } else { const data = await resp.json().catch(() => ({})); setMessage((data as { message?: string }).message ?? "Void failed"); } }
async function refundOrder(orderId: string) { if (!confirm("Refund this paid order and put stock back on the shelf?")) return; const resp = await fetch(`${apiBase}/v1/admin/orders/${encodeURIComponent(orderId)}/refund`, { method: "POST", headers: adminFetchHeaders(true) }); if (resp.ok) { setMessage("Refund recorded."); await loadOrders(); await loadMetrics(); await loadProducts(); } else { const data = await resp.json().catch(() => ({})); setMessage((data as { message?: string }).message ?? "Refund failed"); } }
async function sendReceipt(orderId: string) { const to = window.prompt("Email or phone for receipt webhook"); if (!to?.trim()) return; const channel = to.includes("@") ? "email" : "sms"; const resp = await fetch(`${apiBase}/v1/admin/orders/${encodeURIComponent(orderId)}/receipt-send`, { method: "POST", headers: adminFetchHeaders(true), body: JSON.stringify({ channel, to: to.trim() }) }); const data = await resp.json().catch(() => ({})); setMessage((data as { message?: string; detail?: string }).detail ?? (resp.ok ? "Receipt queued" : "Send failed")); }
async function downloadOrdersCsv() { const qs = storeFilter.trim() ? `?storeCode=${encodeURIComponent(storeFilter.trim().toUpperCase())}` : ""; const resp = await fetch(`${apiBase}/v1/admin/export/orders.csv${qs}`, { headers: adminFetchHeaders() }); if (!resp.ok) { setMessage("CSV export failed (manager only for orders)."); return; } const blob = await resp.blob(); const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.download = `orders-export.csv`; a.click(); URL.revokeObjectURL(url); }
async function downloadProductsCsv() { const resp = await fetch(`${apiBase}/v1/admin/export/products.csv`, { headers: adminFetchHeaders() }); if (!resp.ok) { setMessage("CSV export failed."); return; } const blob = await resp.blob(); const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.download = `products-export.csv`; a.click(); URL.revokeObjectURL(url); }
async function uploadProductImage(file: File, onUrl?: (url: string) => void) { if (!file.type.startsWith("image/")) { setMessage("Choose a JPEG, PNG, or WebP image."); return; } setImageUploading(true); try { const dataUrl = await new Promise<string>((resolve, reject) => { const reader = new FileReader(); reader.onload = () => resolve(String(reader.result)); reader.onerror = () => reject(new Error("read failed")); reader.readAsDataURL(file); }); const resp = await fetch(`${apiBase}/v1/admin/upload/product-image`, { method: "POST", headers: adminFetchHeaders(true), body: JSON.stringify({ dataUrl }) }); const data = (await resp.json()) as { url?: string; message?: string }; if (!resp.ok || !data.url) { setMessage(data.message ?? "Image upload failed"); return; } if (onUrl) onUrl(data.url); else setImageUrl(data.url); setMessage("Image uploaded."); } catch { setMessage("Could not upload image."); } setImageUploading(false); }
async function saveProductImage(productId: string, url: string) { const resp = await fetch(`${apiBase}/v1/admin/products/${productId}/image`, { method: "PATCH", headers: adminFetchHeaders(true), body: JSON.stringify({ imageUrl: url }) }); if (resp.ok) { setMessage("Product image updated."); await loadProducts(); } else { const data = await resp.json().catch(() => ({})); setMessage((data as { message?: string }).message ?? "Could not save image."); } }
async function addProduct() { const errors = validateProductForm(); setFormErrors(errors); if (Object.keys(errors).length > 0) { setMessage("Fix the highlighted fields before saving."); return; }
setLoading(true); setMessage(""); const resp = await fetch(`${apiBase}/v1/admin/products`, { method: "POST", headers: adminFetchHeaders(true), body: JSON.stringify({ barcode: barcode.trim(), name: name.trim(), category: category.trim(), unitPrice: Number(sellingPrice), costPrice: Number(costPrice), taxPercent: Number(taxPercent), inStock: Number(inStock), demandScore: Number(demandScore), imageUrl: imageUrl.trim() || undefined }) }); if (resp.status === 401) { clearAdminToken(); router.replace("/admin"); setLoading(false); return; } if (resp.ok) { setMessage("Product added to catalogue."); resetProductForm(); await loadProducts(); await loadMetrics(); } else { const data = await resp.json().catch(() => ({})); const errMsg = (data as { message?: string }).message ?? "Unable to add product"; setMessage(errMsg); if (resp.status === 409 || errMsg.toLowerCase().includes("barcode")) { setFormErrors((prev) => ({ ...prev, barcode: errMsg })); } } setLoading(false); }
async function saveStock(productId: string, next: number) { setStockModalBusy(true); const resp = await fetch(`${apiBase}/v1/admin/products/${productId}/inventory`, { method: "PATCH", headers: adminFetchHeaders(true), body: JSON.stringify({ inStock: next }) }); if (resp.status === 401) { clearAdminToken(); router.replace("/admin"); setStockModalBusy(false); return; } if (resp.ok) { setMessage("Stock updated."); setStockModalProduct(null); await loadProducts(); await loadMetrics(); } else { const data = await resp.json().catch(() => ({})); setMessage((data as { message?: string }).message ?? "Could not update stock."); } setStockModalBusy(false); }
function openStockModal(product: AdminProduct) { setStockModalProduct({ id: product.id, name: product.name, barcode: product.barcode, inStock: product.inStock }); }
async function applyDiscount() { if (!discountProductId) { setMessage("Select a product for the discount."); return; } setMessage(""); const resp = await fetch(`${apiBase}/v1/admin/discounts`, { method: "POST", headers: adminFetchHeaders(true), body: JSON.stringify({ productId: discountProductId, discountPercent: Number(discountPct) }) }); if (resp.status === 401) { clearAdminToken(); router.replace("/admin"); return; } if (resp.ok) { setMessage("Discount applied."); await loadProducts(); await loadDiscounts(); await loadMetrics(); } else { const data = await resp.json().catch(() => ({})); setMessage((data as { message?: string }).message ?? "Could not apply discount"); } }
async function removeDiscount(productId: string) { const resp = await fetch(`${apiBase}/v1/admin/discounts/${encodeURIComponent(productId)}`, { method: "DELETE", headers: adminFetchHeaders() }); if (resp.ok) { setMessage("Discount removed."); await loadProducts(); await loadDiscounts(); await loadMetrics(); } }
if (!authChecked || !authed) { return ( <div className="adminShell"> <main className="adminMain"> <p className="muted" style={{ padding: "28px 0" }}> {authChecked ? "Redirecting to sign in…" : "Loading dashboard…"} </p> </main> </div> ); }
return ( <div className="adminShell"> <main className="adminMain"> <header className="adminHeader"> <div> <p className="adminHeader__eyebrow">ZippMart HQ</p> <h1 className="adminHeader__title">Operations dashboard</h1> <p className="adminHeader__sub">Catalogue economics, promotions, and store KPIs.</p> </div> <div className="adminHeader__actions"> <select className="adminSelect adminSelect--store" value={storeFilter} onChange={(e) => setStoreFilter(e.target.value)} aria-label="Filter metrics and orders by store" > <option value="">All stores</option> <option value="BLR001">BLR001</option> <option value="DEL001">DEL001</option> <option value="MUM001">MUM001</option> </select> <button type="button" className="adminBtn adminBtn--ghost" onClick={() => void downloadProductsCsv()}> Products CSV </button> {isManager ? ( <> <button type="button" className="adminBtn adminBtn--ghost" onClick={() => void downloadOrdersCsv()}> Orders CSV </button> <button type="button" className="adminBtn adminBtn--ghost" onClick={() => void loadAudit()}> Audit </button> </> ) : null} <button type="button" className="adminBtn adminBtn--ghost" onClick={() => { void loadMetrics(); void loadProducts(); void loadDiscounts(); void loadOrders(); }} > Refresh </button> <button type="button" className="adminBtn adminBtn--ghost adminBtn--logout" onClick={logout}> Log out </button> </div> </header>
{metrics ? ( <section className="metricsGrid" aria-label="Store KPIs"> <div className="metricCard"> <p className="metricCard__label">Paid orders</p> <p className="metricCard__value">{metrics.paidOrderCount}</p> <p className="metricCard__hint">All time (this server)</p> </div> <div className="metricCard metricCard--accent"> <p className="metricCard__label">Net revenue</p> <p className="metricCard__value">{money(metrics.totalRevenue)}</p> <p className="metricCard__hint">Completed payments</p> </div> <div className="metricCard"> <p className="metricCard__label">Open orders</p> <p className="metricCard__value">{metrics.openOrderCount}</p> <p className="metricCard__hint">{money(metrics.pendingOrderValue)} at counter / pending</p> </div> <div className="metricCard"> <p className="metricCard__label">Avg paid ticket</p> <p className="metricCard__value">{money(metrics.averagePaidOrderValue)}</p> <p className="metricCard__hint">Per settled order</p> </div> <div className="metricCard"> <p className="metricCard__label">SKU count</p> <p className="metricCard__value">{metrics.productCount}</p> <p className="metricCard__hint">{metrics.lowStockSkuCount} low stock (< 15 units)</p> </div> <div className="metricCard"> <p className="metricCard__label">Inventory @ cost</p> <p className="metricCard__value">{money(metrics.inventoryValueAtCost)}</p> <p className="metricCard__hint">Stock × unit cost</p> </div> <div className="metricCard"> <p className="metricCard__label">Inventory @ list</p> <p className="metricCard__value">{money(metrics.inventoryValueAtList)}</p> <p className="metricCard__hint">Stock × list sell</p> </div> <div className="metricCard"> <p className="metricCard__label">Active promos</p> <p className="metricCard__value">{metrics.activeDiscountCount}</p> <p className="metricCard__hint">Discount rules live on shop</p> </div> </section> ) : ( <p className="muted">Loading metrics…</p> )}
{metrics && metrics.lowStockSkuCount > 0 ? ( <div className="alertBanner" role="status"> <strong>{metrics.lowStockSkuCount}</strong> SKU{metrics.lowStockSkuCount === 1 ? "" : "s"} below 15 units — use <strong>Low stock only</strong> under inventory to focus the table. </div> ) : null}
{orders.length > 0 ? ( <section className="panel adminPanel adminPanel--orders" aria-label="Recent orders"> <h2 className="adminPanel__title">Recent orders</h2> <p className="adminPanel__lede"> Latest checkouts on this server — filter by store above. Managers can void open orders, refund paid orders (restores stock), and trigger receipt webhooks. </p> <div className="tableWrap"> <table className="adminTable adminTable--compact"> <thead> <tr> <th>When</th> <th>Store</th> <th>Order</th> <th>Token</th> <th>Mode</th> <th>Lines</th> <th>Total</th> <th>Status</th> {isManager ? <th>Actions</th> : null} </tr> </thead> <tbody> {orders.map((o) => ( <tr key={o.orderId}> <td className="muted">{new Date(o.createdAt).toLocaleString()}</td> <td className="mono">{o.storeCode ?? "—"}</td> <td className="mono" title={o.orderId}> {o.orderId.slice(0, 8)}… </td> <td>{o.tokenNumber != null ? `#${o.tokenNumber}` : "—"}</td> <td>{o.paymentMode}</td> <td>{o.lineCount}</td> <td>{money(o.grandTotal)}</td> <td> {o.voided ? <span className="pillWarn">Void</span> : null} {o.refunded ? <span className="pillWarn">Refunded</span> : null} {!o.voided && !o.refunded ? ( o.paid ? ( <span className="pillOk">Paid</span> ) : ( <span className="pillWarn">Open</span> ) ) : null} </td> {isManager ? ( <td> <div className="orderActions"> {!o.paid && !o.voided && !o.refunded ? ( <button type="button" className="adminBtn adminBtn--small" onClick={() => void voidOrder(o.orderId)} > Void </button> ) : null} {o.paid && !o.refunded && !o.voided ? ( <button type="button" className="adminBtn adminBtn--small" onClick={() => void refundOrder(o.orderId)} > Refund </button> ) : null} {o.paid && !o.refunded ? ( <button type="button" className="adminBtn adminBtn--small" onClick={() => void sendReceipt(o.orderId)} > Receipt </button> ) : null} </div> </td> ) : null} </tr> ))} </tbody> </table> </div> </section> ) : null}
{isManager && auditEntries.length > 0 ? ( <section className="panel adminPanel" aria-label="Audit log"> <h2 className="adminPanel__title">Audit log</h2> <p className="adminPanel__lede">Last security and inventory events (newest first).</p> <div className="tableWrap"> <table className="adminTable adminTable--compact"> <thead> <tr> <th>When</th> <th>Actor</th> <th>Role</th> <th>Action</th> <th>Detail</th> </tr> </thead> <tbody> {auditEntries.map((a) => ( <tr key={a.id}> <td className="muted">{new Date(a.at).toLocaleString()}</td> <td>{a.actor}</td> <td>{a.role}</td> <td className="mono">{a.action}</td> <td className="muted">{a.detail}</td> </tr> ))} </tbody> </table> </div> </section> ) : null}
{products.length === 0 && !loading ? ( <div className="alertBanner" role="status"> Your catalogue is empty. Use <strong>Add product</strong> on the left to create your first SKU — customers will see it on the shop once saved. </div> ) : null}
<div className="adminWorkspace"> <div className="adminWorkspace__left"> <section className="panel adminPanel adminPanel--add"> <h2 className="adminPanel__title">Add product</h2> <p className="adminPanel__lede"> Landed cost vs list shelf price. Scan barcodes with the camera or a USB scanner. </p>
{barcodeConflict ? ( <p className="formAlert formAlert--warn" role="status"> Barcode <strong className="mono">{barcodeConflict.barcode}</strong> already belongs to{" "} <strong>{barcodeConflict.name}</strong> — use a different code or adjust stock in the inventory table. </p> ) : null}
<div className="formGrid formGrid--paired"> <label className={`field field--full${formErrors.barcode ? " field--invalid" : ""}`}> <span>Barcode</span> <div className="barcodeRow"> <input value={barcode} onChange={(e) => handleBarcodeInput(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); nameInputRef.current?.focus(); } }} placeholder="EAN / UPC / internal SKU" autoComplete="off" inputMode="numeric" /> <button type="button" className="adminBtn adminBtn--ghost adminBtn--small" onClick={() => setCameraOn((v) => !v)} aria-pressed={cameraOn} > {cameraOn ? "Hide camera" : "Scan"} </button> </div> {formErrors.barcode ? <p className="fieldError">{formErrors.barcode}</p> : null} </label>
<div className="field--full"> <BarcodeCameraScanner active={cameraOn} onClose={() => setCameraOn(false)} onDecoded={handleBarcodeDecoded} /> </div>
<label className={`field${formErrors.name ? " field--invalid" : ""}`}> <span>Product name</span> <input ref={nameInputRef} value={name} onChange={(e) => { setName(e.target.value); setFormErrors((p) => ({ ...p, name: undefined })); }} placeholder="e.g. Basmati Rice 5kg" /> {formErrors.name ? <p className="fieldError">{formErrors.name}</p> : null} </label>
<label className={`field${formErrors.category ? " field--invalid" : ""}`}> <span>Category</span> <select value={category} onChange={(e) => { setCategory(e.target.value); setFormErrors((p) => ({ ...p, category: undefined })); }}> {CATEGORY_OPTIONS.map((c) => ( <option key={c} value={c}>{c}</option> ))} </select> {formErrors.category ? <p className="fieldError">{formErrors.category}</p> : null} </label>
<div className="field field--full imageField"> <span>Product image</span> <div className="imageField__row"> <div className="imageField__preview" aria-hidden={!imageUrl}> {imageUrl ? ( <img src={imageUrl} alt="" className="imageField__img" /> ) : ( <span className="imageField__placeholder">No image</span> )} </div> <div className="imageField__controls"> <input className="adminInput" value={imageUrl} onChange={(e) => setImageUrl(e.target.value)} placeholder="Image URL or upload a file" /> <input ref={imageInputRef} type="file" accept="image/jpeg,image/png,image/webp,image/gif" className="srOnly" onChange={(e) => { const file = e.target.files?.[0]; e.target.value = ""; if (file) void uploadProductImage(file); }} /> <button type="button" className="adminBtn adminBtn--ghost adminBtn--small" disabled={imageUploading || loading} onClick={() => imageInputRef.current?.click()} > {imageUploading ? "Uploading…" : "Upload file"} </button> </div> </div> <p className="formNote">Shown on the customer shop. Upload saves to the API server, or paste any HTTPS image link.</p> </div>
<label className={`field${formErrors.costPrice ? " field--invalid" : ""}`}> <span>Unit cost (₹)</span> <input inputMode="decimal" value={costPrice} onChange={(e) => { setCostPrice(e.target.value); setFormErrors((p) => ({ ...p, costPrice: undefined, sellingPrice: undefined })); }} placeholder="e.g. 120" /> {formErrors.costPrice ? <p className="fieldError">{formErrors.costPrice}</p> : null} </label>
<label className={`field${formErrors.sellingPrice ? " field--invalid" : ""}`}> <span>List selling price (₹)</span> <input inputMode="decimal" value={sellingPrice} onChange={(e) => { setSellingPrice(e.target.value); setFormErrors((p) => ({ ...p, sellingPrice: undefined })); }} placeholder="e.g. 189" /> {formErrors.sellingPrice ? <p className="fieldError">{formErrors.sellingPrice}</p> : null} </label>
<div className="field--pair"> <label className={`field${formErrors.taxPercent ? " field--invalid" : ""}`}> <span>Tax %</span> <input inputMode="decimal" value={taxPercent} onChange={(e) => { setTaxPercent(e.target.value); setFormErrors((p) => ({ ...p, taxPercent: undefined })); }} /> {formErrors.taxPercent ? <p className="fieldError">{formErrors.taxPercent}</p> : null} </label> <label className={`field${formErrors.inStock ? " field--invalid" : ""}`}> <span>Quantity on hand</span> <input inputMode="numeric" value={inStock} onChange={(e) => { setInStock(e.target.value); setFormErrors((p) => ({ ...p, inStock: undefined })); }} placeholder="0" /> {formErrors.inStock ? <p className="fieldError">{formErrors.inStock}</p> : null} </label> </div>
<label className={`field${formErrors.demandScore ? " field--invalid" : ""}`}> <span>Demand score (0–100)</span> <input inputMode="numeric" value={demandScore} onChange={(e) => { setDemandScore(e.target.value); setFormErrors((p) => ({ ...p, demandScore: undefined })); }} placeholder="Higher = featured in shop" /> {formErrors.demandScore ? <p className="fieldError">{formErrors.demandScore}</p> : null} </label> </div>
{formProfit != null ? ( <p className="profitHint"> Est. profit / unit at list: <strong>{money(formProfit)}</strong> {Number(taxPercent) > 0 ? ( <> · shelf price incl. {taxPercent}% tax: <strong>{money(Math.round(Number(sellingPrice) * (1 + Number(taxPercent) / 100) * 100) / 100)}</strong></> ) : null} </p> ) : null}
<div className="formActions"> <button type="button" className="adminBtn" disabled={loading || !!barcodeConflict} onClick={() => void addProduct()} > {loading ? "Saving…" : "Save product"} </button> <button type="button" className="adminBtn adminBtn--ghost" disabled={loading} onClick={resetProductForm}> Clear form </button> <p className="formNote">Required: barcode, name, category, unit cost, and selling price. Stock can be zero for catalogue-only SKUs.</p> </div> </section> </div>
<div className="adminWorkspace__right"> <section className="panel adminPanel adminWorkspace__inventory"> <h2 className="adminPanel__title">Inventory & economics</h2> <div className="invToolbar"> <label className="invSearch"> <span className="srOnly">Filter products</span> <input type="search" placeholder="Filter by name, barcode, category…" value={invFilter} onChange={(e) => setInvFilter(e.target.value)} /> </label> <button type="button" className="adminBtn adminBtn--small" onClick={() => setInvFilter("")}> Clear search </button> <button type="button" className={`adminBtn adminBtn--small${lowStockOnlyView ? " adminBtn--on" : ""}`} onClick={() => setLowStockOnlyView((v) => !v)} > Low stock only ({lowStockCount}) </button> </div> <div className="tableWrap"> <table className="adminTable"> <thead> <tr> <th>Product</th> <th>Barcode</th> <th>Cost</th> <th>List</th> <th>Promo</th> <th>Shelf</th> <th>Profit / unit</th> <th>Stock</th> <th /> </tr> </thead> <tbody> {filteredProducts.length === 0 ? ( <tr> <td colSpan={9} className="muted" style={{ padding: "20px 14px" }}> No products match this filter. Clear search or turn off low-stock-only. </td> </tr> ) : ( filteredProducts.map((p) => ( <tr key={p.id} className={p.discountPercent > 0 ? "adminTable__row--hot" : undefined}> <td> <div className="invProductCell"> {p.imageUrl ? ( <img src={p.imageUrl} alt="" className="invProductCell__thumb" /> ) : ( <span className="invProductCell__thumb invProductCell__thumb--empty" aria-hidden /> )} <div> <strong>{p.name}</strong> <div className="muted">{p.category}</div> </div> </div> </td> <td className="mono">{p.barcode}</td> <td>{money(p.costPrice)}</td> <td>{money(p.unitPrice)}</td> <td>{p.discountPercent > 0 ? <span className="pillHot">{p.discountPercent}%</span> : "—"}</td> <td>{money(p.effectiveUnitPrice)}</td> <td>{money(p.profitPerUnitAtSale)}</td> <td> <span className={ p.inStock === 0 ? "stockCell stockCell--out" : p.inStock < 15 ? "stockCell stockCell--low" : "stockCell" } > {p.inStock} </span> </td> <td> <div className="invRowActions"> <button type="button" className="adminBtn adminBtn--small" onClick={() => openStockModal(p)}> Set stock </button> <button type="button" className="adminBtn adminBtn--small adminBtn--ghost" onClick={() => { setImageTargetId(p.id); inventoryImageInputRef.current?.click(); }} > Image </button> </div> </td> </tr> )) )} </tbody> </table> </div> </section>
<section className="panel adminPanel adminPanel--promo"> <h2 className="adminPanel__title">Discounts</h2> <p className="adminPanel__lede">Percentage off list price for the customer shop. Max 90%. Removes instantly when deleted.</p> <div className="promoRow"> <select className="adminSelect" value={discountProductId} onChange={(e) => setDiscountProductId(e.target.value)}> <option value="">Select product…</option> {products.map((p) => ( <option key={p.id} value={p.id}> {p.name} ({p.barcode}) </option> ))} </select> <input className="adminPct" inputMode="numeric" value={discountPct} onChange={(e) => setDiscountPct(e.target.value)} aria-label="Discount percent" /> <span className="pctSuffix">%</span> <button type="button" className="adminBtn" onClick={() => void applyDiscount()}> Apply </button> </div> <div className="discountList"> {discounts.length === 0 ? <p className="emptyHint">No active discounts.</p> : null} {discounts.map((d) => ( <div key={d.productId} className="discountRow"> <div> <strong>{d.name}</strong> <div className="muted"> {d.discountPercent}% off · list {money(d.listPrice)} → sale {money(d.effectiveUnitPrice)} </div> <div className="muted"> Profit / unit: list {money(d.profitPerUnitAtList)} · after discount {money(d.profitPerUnitAtSale)} </div> </div> <button type="button" className="adminBtn adminBtn--danger" onClick={() => void removeDiscount(d.productId)}> Remove </button> </div> ))} </div> </section> </div> </div>
{message ? <div className="adminToast">{message}</div> : null}
<StockAdjustModal product={stockModalProduct} busy={stockModalBusy} onClose={() => { if (!stockModalBusy) setStockModalProduct(null); }} onSave={(next) => { if (stockModalProduct) void saveStock(stockModalProduct.id, next); }} />
<input ref={inventoryImageInputRef} type="file" accept="image/jpeg,image/png,image/webp,image/gif" className="srOnly" onChange={(e) => { const file = e.target.files?.[0]; const targetId = imageTargetId; e.target.value = ""; setImageTargetId(null); if (!file || !targetId) return; void uploadProductImage(file, (url) => void saveProductImage(targetId, url)); }} /> </main> </div> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990"use client";
import { useRouter } from "next/navigation";import { useEffect, useRef, useState } from "react";import { getAdminToken, setAdminSession } from "../../lib/adminAuth";
import { apiBase } from "../../lib/api";
export default function AdminLoginPage() { const router = useRouter(); const [username, setUsername] = useState(""); const [password, setPassword] = useState(""); const [error, setError] = useState(""); const [busy, setBusy] = useState(false); const passwordRef = useRef<HTMLInputElement>(null);
useEffect(() => { if (getAdminToken()) { router.replace("/admin/dashboard"); } }, [router]);
async function onSubmit(e: React.FormEvent) { e.preventDefault(); setError(""); setBusy(true); try { const resp = await fetch(`${apiBase}/v1/admin/auth/login`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ username, password }) }); const data = await resp.json(); if (!resp.ok) { setError(data.message ?? "Sign-in failed"); setBusy(false); return; } const token = data.token as string; const role = String((data as { role?: string }).role ?? "staff"); setAdminSession(token, role); router.push("/admin/dashboard"); } catch { setError(`Cannot reach API at ${apiBase}. Run npm run dev from the project root.`); } setBusy(false); }
return ( <main className="loginPage"> <div className="loginCard"> <h1 className="loginTitle">ZippMart HQ</h1> <p className="loginHint">Sign in to the operations console</p>
<form onSubmit={(e) => void onSubmit(e)} className="loginForm"> <label className="loginLabel"> Username <input className="loginInput" autoComplete="username" value={username} onChange={(e) => setUsername(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); passwordRef.current?.focus(); } }} /> </label> <label className="loginLabel"> Password <input ref={passwordRef} className="loginInput" type="password" autoComplete="current-password" value={password} onChange={(e) => setPassword(e.target.value)} /> </label> {error ? <p className="loginError">{error}</p> : null} <button type="submit" className="loginSubmit" disabled={busy}> {busy ? "Signing in…" : "Sign in"} </button> </form> </div> </main> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155"use client";
import { useCallback, useEffect, useId, useRef, useState } from "react";
type Props = { active: boolean; onClose: () => void; onDecoded: (text: string) => void;};
export function BarcodeCameraScanner({ active, onClose, onDecoded }: Props) { const readerId = useId().replace(/:/g, ""); const readerElementId = `barcode-camera-${readerId}`; const scannerRef = useRef<import("html5-qrcode").Html5Qrcode | null>(null); const onDecodedRef = useRef(onDecoded); const lastRef = useRef<{ text: string; at: number }>({ text: "", at: 0 }); const [error, setError] = useState<string | null>(null); const [starting, setStarting] = useState(false);
onDecodedRef.current = onDecoded;
const stopScanner = useCallback(async () => { const s = scannerRef.current; scannerRef.current = null; if (!s) return; try { if (s.isScanning) await s.stop(); } catch { /* ignore */ } try { s.clear(); } catch { /* ignore */ } }, []);
useEffect(() => { if (!active) { void stopScanner(); setError(null); setStarting(false); return; }
let cancelled = false; setStarting(true); setError(null);
void (async () => { try { const { Html5Qrcode, Html5QrcodeSupportedFormats } = await import("html5-qrcode"); if (cancelled) return;
await stopScanner(); if (cancelled) return;
await new Promise<void>((r) => requestAnimationFrame(() => r())); if (cancelled) return;
if (!document.getElementById(readerElementId)) { if (!cancelled) setError("Scanner view not ready"); return; }
const formats = [ Html5QrcodeSupportedFormats.EAN_13, Html5QrcodeSupportedFormats.EAN_8, Html5QrcodeSupportedFormats.CODE_128, Html5QrcodeSupportedFormats.UPC_A, Html5QrcodeSupportedFormats.UPC_E, Html5QrcodeSupportedFormats.CODE_39, Html5QrcodeSupportedFormats.CODE_93, Html5QrcodeSupportedFormats.ITF, Html5QrcodeSupportedFormats.CODABAR, Html5QrcodeSupportedFormats.QR_CODE ];
const html5 = new Html5Qrcode(readerElementId, { formatsToSupport: formats, useBarCodeDetectorIfSupported: true, verbose: false }); if (cancelled) { try { html5.clear(); } catch { /* ignore */ } return; }
scannerRef.current = html5;
await html5.start( { facingMode: "environment" }, { fps: 8, qrbox: (viewfinderWidth: number, viewfinderHeight: number) => { const w = Math.min(320, Math.floor(viewfinderWidth * 0.92)); const h = Math.min(220, Math.floor(viewfinderHeight * 0.42)); return { width: w, height: h }; }, aspectRatio: 1.777777778, videoConstraints: { facingMode: { ideal: "environment" } } }, (decodedText) => { const now = Date.now(); if (decodedText === lastRef.current.text && now - lastRef.current.at < 2200) return; lastRef.current = { text: decodedText, at: now }; onDecodedRef.current(decodedText); }, () => undefined ); } catch (e) { if (!cancelled) { setError( e instanceof Error ? e.message : "Could not open camera. Allow camera permission and use HTTPS or localhost." ); } } finally { if (!cancelled) setStarting(false); } })();
return () => { cancelled = true; void stopScanner(); }; }, [active, stopScanner, readerElementId]);
if (!active) return null;
return ( <div className="scanCamera"> <div className="scanCamera__toolbar"> <span className="scanCamera__label">Point at barcode</span> <button type="button" className="scanCamera__close" onClick={() => { void stopScanner().then(onClose); }} > Close camera </button> </div> <div id={readerElementId} className="scanCamera__viewport" /> {starting ? <p className="scanCamera__hint">Starting camera…</p> : null} {error ? <p className="scanCamera__err">{error}</p> : null} </div> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136"use client";
import { useEffect, useRef, useState } from "react";
type Product = { id: string; name: string; barcode: string; inStock: number;};
type Props = { product: Product | null; busy: boolean; onClose: () => void; onSave: (next: number) => void;};
export function StockAdjustModal({ product, busy, onClose, onSave }: Props) { const [value, setValue] = useState(""); const inputRef = useRef<HTMLInputElement>(null);
useEffect(() => { if (!product) return; setValue(String(product.inStock)); const t = window.setTimeout(() => { inputRef.current?.focus(); inputRef.current?.select(); }, 0); return () => window.clearTimeout(t); }, [product]);
useEffect(() => { if (!product) return; function onKey(e: KeyboardEvent) { if (e.key === "Escape") onClose(); } window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey); }, [product, onClose]);
if (!product) return null;
const parsed = Math.max(0, Math.floor(Number(value))); const valid = value.trim() !== "" && Number.isFinite(Number(value)); const delta = valid ? parsed - product.inStock : 0;
function bump(amount: number) { const base = valid ? parsed : product!.inStock; setValue(String(Math.max(0, base + amount))); }
function submit() { if (!valid || busy) return; onSave(parsed); }
return ( <div className="adminModalBackdrop" onClick={onClose} role="presentation"> <div className="adminModal" role="dialog" aria-modal="true" aria-labelledby="stock-modal-title" onClick={(e) => e.stopPropagation()} > <div className="adminModal__header"> <div> <p className="adminModal__eyebrow">Update inventory</p> <h2 id="stock-modal-title" className="adminModal__title"> {product.name} </h2> <p className="adminModal__meta mono">{product.barcode}</p> </div> <button type="button" className="adminModal__close" onClick={onClose} aria-label="Close"> × </button> </div>
<div className="adminModal__body"> <p className="adminModal__current"> Current on hand: <strong>{product.inStock}</strong> </p>
<label className="adminModal__field"> <span>New quantity on hand</span> <input ref={inputRef} className="adminModal__input" inputMode="numeric" value={value} disabled={busy} onChange={(e) => setValue(e.target.value.replace(/[^\d]/g, ""))} onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); submit(); } }} /> </label>
<div className="adminModal__quick"> <button type="button" className="adminBtn adminBtn--ghost adminBtn--small" disabled={busy} onClick={() => bump(-10)}> −10 </button> <button type="button" className="adminBtn adminBtn--ghost adminBtn--small" disabled={busy} onClick={() => bump(-1)}> −1 </button> <button type="button" className="adminBtn adminBtn--ghost adminBtn--small" disabled={busy} onClick={() => bump(1)}> +1 </button> <button type="button" className="adminBtn adminBtn--ghost adminBtn--small" disabled={busy} onClick={() => bump(10)}> +10 </button> </div>
{valid && delta !== 0 ? ( <p className={`adminModal__delta${delta > 0 ? " adminModal__delta--up" : " adminModal__delta--down"}`}> {delta > 0 ? `+${delta}` : delta} units from current shelf count </p> ) : null} </div>
<div className="adminModal__footer"> <button type="button" className="adminBtn adminBtn--ghost" disabled={busy} onClick={onClose}> Cancel </button> <button type="button" className="adminBtn" disabled={!valid || busy} onClick={submit}> {busy ? "Saving…" : "Save stock"} </button> </div> </div> </div> );}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259@import url("https://fonts.googleapis.com/css2?family=Fraunces:ital,opsz,wght@9..144,500;9..144,600;9..144,700&family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap");
:root { color-scheme: light; --bg: #f4efe6; --bg-deep: #e8e0d4; --surface: #fdfcfa; --surface-2: #f0ebe3; --olive: #5c6648; --olive-dark: #454e38; --olive-soft: rgba(92, 102, 72, 0.12); --orange: #d97736; --orange-soft: rgba(217, 119, 54, 0.12); --text: #2c2a26; --muted: #6b6560; --line: rgba(44, 42, 38, 0.12); --shadow: 0 12px 36px rgba(44, 42, 38, 0.08); --radius: 16px; --font: "Plus Jakarta Sans", system-ui, sans-serif; --font-display: "Fraunces", Georgia, serif; --danger: #b91c1c; --danger-bg: #fef2f2;}
* { box-sizing: border-box;}
body { margin: 0; font-family: var(--font); background: var(--bg); color: var(--text); min-height: 100dvh;}
a { color: var(--olive-dark); font-weight: 600;}
.container { max-width: 1120px; margin: 0 auto; padding: 24px 20px 48px;}
.topbar { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: flex-start; gap: 16px; margin-bottom: 28px; padding-bottom: 20px; border-bottom: 1px solid var(--line);}
.title { margin: 0; font-family: var(--font-display); font-size: clamp(1.5rem, 4vw, 2rem); font-weight: 600; color: var(--olive-dark); letter-spacing: -0.02em;}
.subtitle { margin: 8px 0 0; color: var(--muted); font-size: 15px; line-height: 1.5; max-width: 52ch;}
.badge { border-radius: 999px; padding: 7px 14px; font-size: 12px; font-weight: 700; background: var(--olive-soft); color: var(--olive-dark); border: 1px solid var(--line);}
.grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 18px;}
.panel { background: var(--surface); border: 1px solid var(--line); border-radius: var(--radius); padding: 20px; box-shadow: var(--shadow);}
.panel h3 { margin: 0 0 14px; font-size: 1.05rem; font-weight: 700; color: var(--olive-dark);}
.row { display: flex; flex-wrap: wrap; gap: 10px; align-items: center;}
.row input { flex: 1 1 140px; min-width: 0;}
input { width: 100%; height: 44px; border: 1px solid var(--line); border-radius: 12px; padding: 0 14px; font-family: inherit; font-size: 14px; background: var(--surface-2); color: var(--text); outline: none; transition: border-color 0.15s ease, box-shadow 0.15s ease;}
input:focus { border-color: rgba(92, 102, 72, 0.45); box-shadow: 0 0 0 3px var(--olive-soft);}
button { border: none; border-radius: 12px; padding: 0 18px; height: 44px; background: var(--olive); color: #fff; font-weight: 700; font-family: inherit; font-size: 14px; cursor: pointer; box-shadow: 0 8px 20px rgba(69, 78, 56, 0.2); transition: transform 0.1s ease, opacity 0.15s ease;}
button:active { transform: scale(0.98);}
button:disabled { opacity: 0.5; cursor: not-allowed;}
button.secondary { background: var(--surface-2); color: var(--olive-dark); border: 1px solid var(--line); box-shadow: none;}
.list { display: grid; gap: 10px;}
.item { border: 1px solid var(--line); border-radius: 12px; padding: 14px 16px; display: flex; flex-wrap: wrap; justify-content: space-between; align-items: center; gap: 12px; background: linear-gradient(180deg, var(--surface) 0%, var(--surface-2) 100%);}
.item strong { font-size: 15px; color: var(--text);}
.muted { color: var(--muted); font-size: 13px;}
.status { margin-top: 18px; padding: 14px 16px; border-radius: 12px; background: var(--surface); border: 1px solid var(--line); font-size: 14px; color: var(--text); box-shadow: var(--shadow);}
@media (max-width: 920px) { .grid { grid-template-columns: 1fr; }}
/* ——— Marketing home /admin root ——— */.adminHome { min-height: 100dvh; display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 32px 20px; text-align: center; background: linear-gradient(180deg, var(--surface) 0%, var(--bg) 50%);}
.adminHome__title { margin: 0; font-family: var(--font-display); font-size: 2rem; font-weight: 600; color: var(--olive-dark);}
.adminHome__text { margin: 12px 0 24px; color: var(--muted); max-width: 360px; line-height: 1.55;}
.adminHome__link { display: inline-flex; align-items: center; justify-content: center; min-height: 48px; padding: 0 28px; border-radius: 14px; background: var(--olive); color: #fff !important; text-decoration: none; font-weight: 700; box-shadow: 0 10px 28px rgba(69, 78, 56, 0.25);}
/* ——— Login ——— */.loginPage { min-height: 100dvh; display: grid; place-items: center; padding: 24px; background: linear-gradient(165deg, var(--olive-dark) 0%, #3d442f 45%, var(--bg-deep) 100%);}
.loginCard { width: 100%; max-width: 420px; background: var(--surface); border-radius: var(--radius); padding: 32px 28px; box-shadow: 0 28px 60px rgba(44, 42, 38, 0.2); border: 1px solid var(--line);}
.loginTitle { margin: 0; font-family: var(--font-display); font-size: 1.75rem; font-weight: 600; color: var(--olive-dark);}
.loginHint { margin: 8px 0 22px; color: var(--muted); font-size: 14px; line-height: 1.45;}
.loginForm { display: flex; flex-direction: column; gap: 16px;}
.loginLabel { display: flex; flex-direction: column; gap: 8px; font-size: 13px; font-weight: 600; color: var(--olive-dark);}
.loginInput { width: 100%; height: 46px;}
.loginError { margin: 0; color: var(--danger); font-size: 13px;}
.loginSubmit { height: 48px; font-size: 15px; margin-top: 4px;}
.loginDevHint { margin: 20px 0 0; font-size: 12px; color: var(--muted); line-height: 1.45;}
.topbarActions { display: flex; flex-wrap: wrap; align-items: center; gap: 10px;}
.itemActions { display: flex; flex-wrap: wrap; align-items: center; gap: 8px;}
.itemActions button { height: 38px; padding: 0 14px; font-size: 13px;}
.panel--wide { grid-column: 1 / -1;}
.emptyHint { margin: 0; color: var(--muted); font-size: 14px;}
/* ——— Desktop dashboard ——— */.mono { font-family: ui-monospace, monospace; font-size: 12px;}
.adminShell { min-height: 100dvh; background: var(--bg);}
.adminMain { max-width: 1280px; margin: 0 auto; padding: 28px 28px 56px;}
.adminHeader { display: flex; flex-wrap: wrap; justify-content: space-between; gap: 20px; margin-bottom: 28px; padding-bottom: 22px; border-bottom: 1px solid var(--line);}
.adminHeader__eyebrow { margin: 0; font-size: 11px; font-weight: 800; letter-spacing: 0.12em; text-transform: uppercase; color: var(--orange);}
.adminHeader__title { margin: 8px 0 0; font-family: var(--font-display); font-size: 2rem; font-weight: 600; color: var(--olive-dark);}
.adminHeader__sub { margin: 8px 0 0; max-width: 56ch; color: var(--muted); line-height: 1.5;}
.adminHeader__actions { display: flex; flex-wrap: wrap; align-items: center; justify-content: flex-end; gap: 8px; width: 100%;}
@media (min-width: 1025px) { .adminHeader { align-items: flex-end; }
.adminHeader__actions { width: auto; flex: 0 0 auto; flex-wrap: nowrap; }}
@media (max-width: 767px) { .adminHeader__actions { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px; }
.adminSelect--store { grid-column: 1 / -1; width: 100%; }
.adminHeader__actions .adminBtn { width: 100%; min-width: 0; padding: 0 10px; font-size: 13px; }}
.adminBtn { height: 42px; padding: 0 18px; border-radius: 12px; border: none; font-family: inherit; font-weight: 700; font-size: 14px; cursor: pointer; background: var(--olive); color: #fff; box-shadow: 0 8px 20px rgba(69, 78, 56, 0.2);}
.adminBtn--ghost { background: var(--surface); color: var(--olive-dark); border: 1px solid var(--line); box-shadow: none;}
.adminBtn--danger { background: var(--danger-bg); color: var(--danger); border: 1px solid rgba(185, 28, 28, 0.25); box-shadow: none;}
.adminBtn--small { height: 34px; padding: 0 12px; font-size: 12px;}
.metricsGrid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 16px; margin-bottom: 28px;}
@media (max-width: 1100px) { .metricsGrid { grid-template-columns: repeat(2, minmax(0, 1fr)); }}
.metricCard { background: var(--surface); border: 1px solid var(--line); border-radius: var(--radius); padding: 18px; box-shadow: var(--shadow);}
.metricCard--accent { border-color: rgba(217, 119, 54, 0.35); background: linear-gradient(160deg, #fffdfb, var(--surface));}
.metricCard__label { margin: 0; font-size: 12px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.06em; color: var(--muted);}
.metricCard__value { margin: 10px 0 0; font-size: 1.45rem; font-weight: 800; color: var(--olive-dark);}
.metricCard__hint { margin: 8px 0 0; font-size: 12px; color: var(--muted); line-height: 1.4;}
.adminWorkspace { display: grid; grid-template-columns: 1fr; gap: 22px; align-items: start;}
.adminWorkspace__right { display: flex; flex-direction: column; gap: 22px; min-width: 0;}
@media (min-width: 1025px) { .adminWorkspace { grid-template-columns: minmax(0, 420px) minmax(0, 1fr); }
.adminWorkspace__left .formGrid { grid-template-columns: 1fr; }}
.adminWorkspace__inventory { min-width: 0;}
.adminPanel { margin-bottom: 0;}
.adminPanel__title { margin: 0 0 8px; font-size: 1.15rem; font-weight: 800; color: var(--olive-dark);}
.adminPanel__lede { margin: 0 0 16px; font-size: 13px; color: var(--muted); line-height: 1.5;}
.formGrid { display: grid; grid-template-columns: 1fr 1fr; gap: 14px 16px; margin-bottom: 4px;}
.formGrid--paired .field--pair { display: grid; grid-template-columns: 1fr 1fr; gap: 14px 16px; grid-column: 1 / -1;}
@media (max-width: 520px) { .formGrid { grid-template-columns: 1fr; }
.formGrid--paired .field--pair { grid-template-columns: 1fr; }}
.field--full { grid-column: 1 / -1;}
.field input,.field select { height: 42px;}
.field select { width: 100%; border: 1px solid var(--line); border-radius: 12px; padding: 0 14px; font-family: inherit; font-size: 14px; background: var(--surface-2); color: var(--text); outline: none;}
.field select:focus { border-color: rgba(92, 102, 72, 0.45); box-shadow: 0 0 0 3px var(--olive-soft);}
.field--invalid input,.field--invalid select { border-color: rgba(185, 28, 28, 0.55); box-shadow: 0 0 0 3px rgba(185, 28, 28, 0.08);}
.fieldError { margin: 0; font-size: 12px; font-weight: 600; color: var(--danger);}
.barcodeRow { display: flex; gap: 8px; align-items: stretch;}
.barcodeRow input { flex: 1 1 auto; min-width: 0;}
.barcodeRow .adminBtn { flex: 0 0 auto; white-space: nowrap;}
.formActions { display: flex; flex-direction: column; gap: 10px; margin-top: 18px; padding-top: 18px; border-top: 1px solid var(--line);}
.formActions .adminBtn { width: 100%; height: 46px;}
.formNote { margin: 0; font-size: 12px; color: var(--muted); line-height: 1.45;}
.formAlert { margin: 0 0 14px; padding: 10px 12px; border-radius: 10px; font-size: 13px; line-height: 1.45;}
.formAlert--warn { background: var(--orange-soft); border: 1px solid rgba(217, 119, 54, 0.35); color: #9a3412;}
.formAlert--err { background: var(--danger-bg); border: 1px solid rgba(185, 28, 28, 0.25); color: var(--danger);}
@media (max-width: 520px) { .formGrid { grid-template-columns: 1fr; }}
.field { display: flex; flex-direction: column; gap: 6px; font-size: 12px; font-weight: 700; color: var(--olive-dark);}
.field input { height: 42px;}
.profitHint { margin: 12px 0 0; font-size: 14px; color: var(--muted);}
.promoRow { display: grid; grid-template-columns: 1fr auto auto auto; gap: 10px; align-items: center; margin-bottom: 16px;}
@media (max-width: 600px) { .promoRow { grid-template-columns: 1fr 1fr; }
.promoRow .adminBtn { grid-column: 1 / -1; width: 100%; }}
.adminSelect { flex: 1 1 220px; min-width: 200px; height: 44px; border-radius: 12px; border: 1px solid var(--line); padding: 0 12px; font-family: inherit; background: var(--surface-2);}
.adminPct { width: 72px; height: 44px; border-radius: 12px; border: 1px solid var(--line); text-align: center; font-weight: 700;}
.pctSuffix { font-weight: 700; color: var(--muted);}
.discountList { display: flex; flex-direction: column; gap: 10px;}
.discountRow { display: flex; justify-content: space-between; gap: 12px; align-items: flex-start; padding: 12px 14px; border-radius: 12px; border: 1px solid var(--line); background: linear-gradient(180deg, #fffefb, var(--surface-2));}
.discountRow .adminBtn { flex-shrink: 0;}
.scanCamera { margin-top: 12px; padding: 14px; border-radius: var(--radius); background: var(--surface); border: 1px solid var(--line); box-shadow: var(--shadow);}
.scanCamera__toolbar { display: flex; justify-content: space-between; align-items: center; gap: 10px; margin-bottom: 10px;}
.scanCamera__label { font-size: 13px; font-weight: 700; color: var(--olive-dark);}
.scanCamera__close { font-size: 13px; font-weight: 700; padding: 8px 12px; border-radius: 10px; border: 1px solid var(--line); background: var(--surface-2); color: var(--text); cursor: pointer; font-family: inherit;}
.scanCamera__viewport { border-radius: 14px; overflow: hidden; min-height: 200px; background: #1a1a18;}
.scanCamera__viewport video { width: 100% !important; display: block; border-radius: 14px;}
.scanCamera__hint,.scanCamera__err { margin: 10px 0 0; font-size: 13px; color: var(--muted);}
.scanCamera__err { color: var(--danger);}
.tableWrap { overflow-x: auto; border-radius: 12px; border: 1px solid var(--line);}
.adminTable { width: 100%; border-collapse: collapse; font-size: 13px; background: var(--surface);}
.adminTable th,.adminTable td { padding: 12px 14px; text-align: left; border-bottom: 1px solid var(--line); vertical-align: top;}
.adminTable th { font-size: 11px; text-transform: uppercase; letter-spacing: 0.06em; color: var(--muted); background: var(--surface-2);}
.adminTable tr:last-child td { border-bottom: none;}
.adminTable__row--hot { background: rgba(217, 119, 54, 0.08);}
.pillHot { display: inline-block; padding: 2px 8px; border-radius: 999px; font-size: 11px; font-weight: 800; background: var(--orange); color: #fff;}
.adminToast { position: fixed; bottom: 28px; right: 28px; max-width: 360px; padding: 14px 16px; border-radius: 12px; background: var(--surface); border: 1px solid var(--line); box-shadow: var(--shadow); font-size: 14px;}
.srOnly { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0;}
.alertBanner { margin: 0 0 20px; padding: 14px 18px; border-radius: 14px; background: var(--orange-soft); border: 1px solid var(--line); font-size: 14px; line-height: 1.5; color: var(--text);}
.adminPanel--orders { margin-bottom: 24px;}
.adminTable--compact th,.adminTable--compact td { padding: 10px 12px; font-size: 12px;}
.pillOk { display: inline-block; padding: 2px 8px; border-radius: 999px; font-size: 11px; font-weight: 800; background: var(--olive-soft); color: var(--olive-dark);}
.pillWarn { display: inline-block; padding: 2px 8px; border-radius: 999px; font-size: 11px; font-weight: 800; background: var(--orange-soft); color: #9a3412;}
.invToolbar { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; margin-bottom: 14px;}
.invSearch { flex: 1 1 220px; min-width: 0;}
.invSearch input { width: 100%; height: 42px; padding: 0 14px; border-radius: 12px; border: 1px solid var(--line); font: inherit; font-size: 14px; background: var(--surface);}
.adminBtn--on { background: var(--olive); color: #fff; border-color: var(--olive);}
.adminRolePill { display: inline-flex; align-items: center; padding: 6px 12px; border-radius: 999px; font-size: 12px; font-weight: 800; background: var(--surface-2); border: 1px solid var(--line); color: var(--olive-dark);}
.adminStorePick { display: flex; align-items: center;}
.adminSelect--store,.adminSelect--compact { min-width: 140px; height: 42px; border-radius: 12px; border: 1px solid var(--line); font: inherit; font-size: 14px; padding: 0 12px; background: var(--surface);}
.orderActions { display: flex; flex-wrap: wrap; gap: 6px;}
.adminModalBackdrop { position: fixed; inset: 0; z-index: 1000; display: flex; align-items: center; justify-content: center; padding: 20px; background: rgba(34, 38, 28, 0.45); backdrop-filter: blur(4px);}
.adminModal { width: min(100%, 420px); background: var(--surface); border: 1px solid var(--line); border-radius: var(--radius); box-shadow: 0 24px 60px rgba(34, 38, 28, 0.22); overflow: hidden;}
.adminModal__header { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; padding: 20px 20px 0;}
.adminModal__eyebrow { margin: 0; font-size: 11px; font-weight: 800; letter-spacing: 0.08em; text-transform: uppercase; color: var(--orange);}
.adminModal__title { margin: 6px 0 0; font-size: 1.2rem; font-weight: 800; color: var(--olive-dark); line-height: 1.3;}
.adminModal__meta { margin: 6px 0 0; font-size: 12px; color: var(--muted);}
.adminModal__close { flex: 0 0 auto; width: 36px; height: 36px; border: 1px solid var(--line); border-radius: 10px; background: var(--surface-2); color: var(--muted); font-size: 22px; line-height: 1; cursor: pointer;}
.adminModal__close:hover { color: var(--olive-dark); border-color: rgba(92, 102, 72, 0.35);}
.adminModal__body { padding: 18px 20px 8px;}
.adminModal__current { margin: 0 0 14px; font-size: 14px; color: var(--muted);}
.adminModal__field { display: flex; flex-direction: column; gap: 8px; margin-bottom: 14px;}
.adminModal__field span { font-size: 13px; font-weight: 700; color: var(--olive-dark);}
.adminModal__input { height: 48px; border: 1px solid var(--line); border-radius: 12px; padding: 0 14px; font: inherit; font-size: 1.25rem; font-weight: 700; text-align: center; background: var(--surface-2); color: var(--olive-dark); outline: none;}
.adminModal__input:focus { border-color: rgba(92, 102, 72, 0.45); box-shadow: 0 0 0 3px var(--olive-soft);}
.adminModal__quick { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 8px;}
.adminModal__delta { margin: 14px 0 0; font-size: 13px; font-weight: 600; color: var(--muted);}
.adminModal__delta--up { color: #166534;}
.adminModal__delta--down { color: var(--danger);}
.adminModal__footer { display: flex; justify-content: flex-end; gap: 10px; padding: 16px 20px 20px; border-top: 1px solid var(--line); background: var(--surface-2);}
.stockCell { font-weight: 700;}
.stockCell--low { color: var(--danger);}
.stockCell--out { color: var(--danger); font-weight: 800;}
.adminInput { width: 100%; height: 42px; border: 1px solid var(--line); border-radius: 12px; padding: 0 12px; font: inherit; font-size: 14px; background: var(--surface-2);}
.imageField__row { display: flex; gap: 12px; align-items: flex-start;}
.imageField__preview { flex: 0 0 72px; width: 72px; height: 72px; border-radius: 12px; border: 1px solid var(--line); background: var(--surface-2); overflow: hidden; display: flex; align-items: center; justify-content: center;}
.imageField__img { width: 100%; height: 100%; object-fit: cover;}
.imageField__placeholder { font-size: 11px; font-weight: 700; color: var(--muted); text-align: center; padding: 6px;}
.imageField__controls { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 8px;}
.invProductCell { display: flex; align-items: center; gap: 10px; min-width: 0;}
.invProductCell__thumb { flex: 0 0 40px; width: 40px; height: 40px; border-radius: 8px; object-fit: cover; border: 1px solid var(--line); background: var(--surface-2);}
.invProductCell__thumb--empty { display: block; background: linear-gradient(135deg, var(--surface-2), var(--surface));}
.invRowActions { display: flex; flex-direction: column; gap: 6px; align-items: stretch;}12345678910111213141516import type { Metadata } from "next";import type { ReactNode } from "react";import "./globals.css";
export const metadata: Metadata = { title: "ZippMart HQ", description: "ZippMart operations console"};
export default function RootLayout({ children }: { children: ReactNode }) { return ( <html lang="en"> <body>{children}</body> </html> );}12345678910111213import Link from "next/link";
export default function Home() { return ( <main className="adminHome"> <h1 className="adminHome__title">ZippMart HQ</h1> <p className="adminHome__text">Operations console for catalogue, counter tokens, receipts, and store KPIs.</p> <Link href="/admin" className="adminHome__link"> Open admin sign-in </Link> </main> );}1234567891011121314151617181920212223242526272829303132333435const STORAGE_KEY = "checkout_admin_token";const ROLE_KEY = "checkout_admin_role";
export function getAdminToken(): string | null { if (typeof window === "undefined") return null; return localStorage.getItem(STORAGE_KEY);}
export function getAdminRole(): string | null { if (typeof window === "undefined") return null; return localStorage.getItem(ROLE_KEY);}
export function setAdminSession(token: string, role: string): void { localStorage.setItem(STORAGE_KEY, token); localStorage.setItem(ROLE_KEY, role);}
/** @deprecated Prefer setAdminSession — defaults role to staff */export function setAdminToken(token: string): void { setAdminSession(token, "staff");}
export function clearAdminToken(): void { localStorage.removeItem(STORAGE_KEY); localStorage.removeItem(ROLE_KEY);}
export function adminFetchHeaders(json = false): HeadersInit { const headers: Record<string, string> = {}; if (json) headers["Content-Type"] = "application/json"; const t = getAdminToken(); if (t) headers.Authorization = `Bearer ${t}`; return headers;}1export const apiBase = (process.env.NEXT_PUBLIC_API_BASE_URL ?? "http://localhost:4000").replace(/\/$/, "");123456/// <reference types="next" />/// <reference types="next/image-types/global" />import "./.next/types/routes.d.ts";
// NOTE: This file should not be edited// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.12345678910111213import type { NextConfig } from "next";
const apiProxy = process.env.API_PROXY_TARGET?.replace(/\/$/, "");
const nextConfig: NextConfig = { output: "standalone", async rewrites() { if (!apiProxy) return []; return [{ source: "/checkout-api/:path*", destination: `${apiProxy}/:path*` }]; }};
export default nextConfig;12345678910111213141516171819202122232425{ "name": "admin-web", "version": "1.0.0", "private": true, "description": "Admin operations dashboard", "scripts": { "dev": "next dev -p 3002", "build": "next build", "start": "next start -p 3002", "lint": "next lint", "test": "node -e \"console.log('no tests yet')\"" }, "dependencies": { "html5-qrcode": "^2.3.8", "next": "^16.2.6", "react": "^19.2.6", "react-dom": "^19.2.6" }, "devDependencies": { "@types/node": "^25.7.0", "@types/react": "^19.2.14", "@types/react-dom": "^19.2.3", "typescript": "^6.0.3" }}123456789101112131415{ "extends": "../../tsconfig.base.json", "compilerOptions": { "module": "ESNext", "moduleResolution": "Bundler", "jsx": "preserve", "noEmit": true, "allowJs": true, "incremental": true, "isolatedModules": true, "plugins": [{ "name": "next" }] }, "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"], "exclude": ["node_modules"]}123456{ "$schema": "https://openapi.vercel.sh/vercel.json", "framework": "nextjs", "installCommand": "cd ../.. && npm ci", "buildCommand": "npm run build -w admin-web"}123456789101112131415161718192021222324252627282930FROM node:22-alpine AS buildWORKDIR /app
COPY package.json package-lock.json ./COPY tsconfig.base.json ./COPY apps/admin-web/package.json ./apps/admin-web/
RUN npm ci
COPY apps/admin-web ./apps/admin-web
ENV NEXT_PUBLIC_API_BASE_URL=https://adi576-zippmart.hf.space/checkout-apiRUN npm run build -w admin-web \ && test -f apps/admin-web/.next/BUILD_ID \ && test -d apps/admin-web/.next/standalone
FROM node:22-alpineWORKDIR /app
ENV NODE_ENV=productionENV PORT=7860ENV HOSTNAME=0.0.0.0
COPY --from=build /app/apps/admin-web/.next/standalone ./COPY --from=build /app/apps/admin-web/.next/static ./apps/admin-web/.next/staticCOPY deploy/huggingface-admin/start.sh /start.shRUN chmod +x /start.sh
EXPOSE 7860CMD ["/start.sh"]123456789101112131415161718192021222324---title: Zippmart Adminemoji: 📊colorFrom: purplecolorTo: redsdk: dockerapp_port: 7860pinned: false---
# ZippMart Admin HQ
Staff and manager dashboard for catalogue, stock, orders, and store KPIs.
Open **/admin** to sign in.
Uses the API on the main ZippMart Space: `https://adi576-zippmart.hf.space/checkout-api`
## Default logins
Set via secrets on the **main** API Space (`ADMIN_*` / `MANAGER_*`). Dev defaults if unchanged:
- Staff: `admin` / `admin123`- Manager: `manager` / `manager123`12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152# Push admin app to Hugging Face Space ADI576/zippmart_admin
$ErrorActionPreference = "Stop"$Root = Resolve-Path (Join-Path $PSScriptRoot "..\..")$SpaceDir = Join-Path $env:TEMP "zippmart-hf-admin"$SpaceUrl = "https://huggingface.co/spaces/ADI576/zippmart_admin"
$SkipNames = @(".git", "node_modules", ".next", "dist")
$Token = $env:HF_TOKENif (-not $Token) { $Token = $env:HUGGING_FACE_HUB_TOKEN }if ($Token) { $SpaceUrl = "https://user:$Token@huggingface.co/spaces/ADI576/zippmart_admin"}
if (Test-Path $SpaceDir) { Remove-Item -Recurse -Force $SpaceDir }git clone $SpaceUrl $SpaceDir
function Copy-Tree($Source, $Dest) { New-Item -ItemType Directory -Force -Path $Dest | Out-Null Get-ChildItem $Source -Force | ForEach-Object { if ($SkipNames -contains $_.Name) { return } $target = Join-Path $Dest $_.Name if ($_.PSIsContainer) { Copy-Tree $_.FullName $target } else { Copy-Item $_.FullName $target -Force } }}
New-Item -ItemType Directory -Force -Path (Join-Path $SpaceDir "apps") | Out-NullCopy-Tree (Join-Path $Root "apps\admin-web") (Join-Path $SpaceDir "apps\admin-web")New-Item -ItemType Directory -Force -Path (Join-Path $SpaceDir "deploy") | Out-NullCopy-Tree (Join-Path $Root "deploy\huggingface-admin") (Join-Path $SpaceDir "deploy\huggingface-admin")
foreach ($file in @("package.json", "package-lock.json", "tsconfig.base.json")) { Copy-Item (Join-Path $Root $file) (Join-Path $SpaceDir $file) -Force}
Copy-Item "$Root\deploy\huggingface-admin\README.md" (Join-Path $SpaceDir "README.md") -ForceCopy-Item "$Root\deploy\huggingface-admin\Dockerfile" (Join-Path $SpaceDir "Dockerfile") -Force
Push-Location $SpaceDirgit add -Aif (-not (git diff --cached --quiet)) { git commit -m "Deploy ZippMart admin dashboard (Docker Space)"}git pushPop-Location
Write-Host "Pushed. Open https://huggingface.co/spaces/ADI576/zippmart_admin"123#!/bin/shset -eexec node /app/apps/admin-web/server.js123456789101112131415161718192021222324252627282930313233{ "name": "checkout-system", "version": "1.0.0", "private": true, "description": "ZippMart checkout platform monorepo", "workspaces": [ "apps/*", "services/*", "packages/*" ], "scripts": { "dev": "concurrently -n api,worker,customer,admin,cashier -c blue,magenta,green,yellow,cyan \"npm run dev -w services/api\" \"npm run dev -w services/worker\" \"npm run dev -w apps/customer-web\" \"npm run dev -w apps/admin-web\" \"npm run dev -w apps/cashier-web\"", "setup:api": "node -e \"const fs=require('fs');const p='services/api/.env';if(!fs.existsSync(p)){fs.copyFileSync('services/api/.env.example',p);console.log('Created',p,'— edit DATABASE_URL with your Supabase password');}else{console.log(p,'already exists');}\"", "dev:customer": "npm run dev -w apps/customer-web", "dev:admin": "npm run dev -w apps/admin-web", "dev:cashier": "npm run dev -w apps/cashier-web", "dev:api": "npm run dev -w services/api", "dev:worker": "npm run dev -w services/worker", "build": "npm run build -w @checkout/shared && npm run build --workspaces --if-present", "test": "npm run test --workspaces", "lint": "npm run lint --workspaces" }, "engines": { "node": ">=20.0.0" }, "devDependencies": { "@types/node": "^25.7.0", "concurrently": "^9.2.1", "eslint": "^10.3.0", "tsx": "^4.21.0", "typescript": "^6.0.3" }}12345678910111213{ "compilerOptions": { "target": "ES2022", "module": "NodeNext", "moduleResolution": "NodeNext", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "resolveJsonModule": true, "outDir": "dist" }}DockerfileAdded+30
README.md+19-8
apps/admin-web/.env.exampleAdded+4
apps/admin-web/app/admin/dashboard/page.tsxAdded+1141
apps/admin-web/app/admin/page.tsxAdded+90
apps/admin-web/app/components/BarcodeCameraScanner.tsxAdded+155
apps/admin-web/app/components/StockAdjustModal.tsxAdded+136
apps/admin-web/app/globals.cssAdded+1259
apps/admin-web/app/layout.tsxAdded+16
apps/admin-web/app/page.tsxAdded+13
apps/admin-web/lib/adminAuth.tsAdded+35
apps/admin-web/lib/api.tsAdded+1
apps/admin-web/next-env.d.tsAdded+6
apps/admin-web/next.config.tsAdded+13
apps/admin-web/package.jsonAdded+25
apps/admin-web/tsconfig.jsonAdded+15
apps/admin-web/vercel.jsonAdded+6
deploy/huggingface-admin/DockerfileAdded+30
deploy/huggingface-admin/README.mdAdded+24
deploy/huggingface-admin/push.ps1Added+52
deploy/huggingface-admin/start.shAdded+3
package-lock.jsonAdded
package.jsonAdded+33
tsconfig.base.jsonAdded+13