Hinweis-Zähler im Admin-Menü: offene Bestellungen, neue Kunden und Anmeldungen, wenig Bestand
This commit is contained in:
parent
390b5f3f4f
commit
c1ac5ca8fa
8 changed files with 172 additions and 29 deletions
|
|
@ -1,6 +1,6 @@
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
|
import { cookies } from "next/headers";
|
||||||
import "@/styles/admin.css";
|
import "@/styles/admin.css";
|
||||||
import { db } from "@/lib/db";
|
|
||||||
import { can, requireAdmin } from "@/lib/auth";
|
import { can, requireAdmin } from "@/lib/auth";
|
||||||
import { logout } from "@/lib/auth-actions";
|
import { logout } from "@/lib/auth-actions";
|
||||||
import { getSettings } from "@/lib/settings";
|
import { getSettings } from "@/lib/settings";
|
||||||
|
|
@ -8,6 +8,8 @@ import { Icon } from "@/components/Icon";
|
||||||
import { AdminNav } from "@/components/admin/AdminNav";
|
import { AdminNav } from "@/components/admin/AdminNav";
|
||||||
import { MobileAdminNav } from "@/components/admin/MobileAdminNav";
|
import { MobileAdminNav } from "@/components/admin/MobileAdminNav";
|
||||||
import { ADMIN_NAV } from "@/components/admin/nav";
|
import { ADMIN_NAV } from "@/components/admin/nav";
|
||||||
|
import { AdminBadgesProvider } from "@/components/admin/AdminBadges";
|
||||||
|
import { SEEN_COOKIE, SEEN_SECTIONS, getBadges } from "@/lib/admin-badges";
|
||||||
|
|
||||||
export const dynamic = "force-dynamic";
|
export const dynamic = "force-dynamic";
|
||||||
export const metadata = { title: "Admin", robots: { index: false } };
|
export const metadata = { title: "Admin", robots: { index: false } };
|
||||||
|
|
@ -16,9 +18,8 @@ export default async function AdminLayout({ children }: { children: React.ReactN
|
||||||
const user = await requireAdmin();
|
const user = await requireAdmin();
|
||||||
const settings = await getSettings();
|
const settings = await getSettings();
|
||||||
const groups = ADMIN_NAV.map((g) => ({ ...g, items: g.items.filter((i) => can(user, i.permission)) })).filter((g) => g.items.length);
|
const groups = ADMIN_NAV.map((g) => ({ ...g, items: g.items.filter((i) => can(user, i.permission)) })).filter((g) => g.items.length);
|
||||||
const openOrders = can(user, "orders.view") ? await db.order.count({ where: { status: { in: ["PAID", "PROCESSING"] } } }) : 0;
|
const badges = await getBadges(user, (await cookies()).get(SEEN_COOKIE)?.value);
|
||||||
const badges = { openOrders };
|
const nav = <AdminNav groups={groups} />;
|
||||||
const nav = <AdminNav groups={groups} badges={badges} />;
|
|
||||||
const foot = (
|
const foot = (
|
||||||
<div className="ad-side__foot">
|
<div className="ad-side__foot">
|
||||||
<p>{[user.firstName, user.lastName].filter(Boolean).join(" ") || user.email}</p>
|
<p>{[user.firstName, user.lastName].filter(Boolean).join(" ") || user.email}</p>
|
||||||
|
|
@ -46,24 +47,26 @@ export default async function AdminLayout({ children }: { children: React.ReactN
|
||||||
</Link>
|
</Link>
|
||||||
);
|
);
|
||||||
return (
|
return (
|
||||||
<div className="ad">
|
<AdminBadgesProvider initial={badges} seenSections={SEEN_SECTIONS}>
|
||||||
<aside className="ad-side">
|
<div className="ad">
|
||||||
{brand}
|
<aside className="ad-side">
|
||||||
{nav}
|
{brand}
|
||||||
{foot}
|
{nav}
|
||||||
</aside>
|
{foot}
|
||||||
<div style={{ minWidth: 0 }}>
|
</aside>
|
||||||
<div className="ad-top">
|
<div style={{ minWidth: 0 }}>
|
||||||
<MobileAdminNav>
|
<div className="ad-top">
|
||||||
{brand}
|
<MobileAdminNav>
|
||||||
{nav}
|
{brand}
|
||||||
{foot}
|
{nav}
|
||||||
</MobileAdminNav>
|
{foot}
|
||||||
<strong style={{ letterSpacing: "0.24em", fontWeight: 400, textTransform: "uppercase" }}>{settings.general.shopName}.</strong>
|
</MobileAdminNav>
|
||||||
<Link className="sm-header__btn" href="/" aria-label="Shop ansehen"><Icon name="external" /></Link>
|
<strong style={{ letterSpacing: "0.24em", fontWeight: 400, textTransform: "uppercase" }}>{settings.general.shopName}.</strong>
|
||||||
|
<Link className="sm-header__btn" href="/" aria-label="Shop ansehen"><Icon name="external" /></Link>
|
||||||
|
</div>
|
||||||
|
<main className="ad-main">{children}</main>
|
||||||
</div>
|
</div>
|
||||||
<main className="ad-main">{children}</main>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</AdminBadgesProvider>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
12
src/app/admin/badges/route.ts
Normal file
12
src/app/admin/badges/route.ts
Normal file
|
|
@ -0,0 +1,12 @@
|
||||||
|
import { cookies } from "next/headers";
|
||||||
|
import { getCurrentUser } from "@/lib/auth";
|
||||||
|
import { SEEN_COOKIE, getBadges } from "@/lib/admin-badges";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
export async function GET() {
|
||||||
|
const user = await getCurrentUser();
|
||||||
|
if (!user?.role) return Response.json({}, { status: 401 });
|
||||||
|
const badges = await getBadges(user, (await cookies()).get(SEEN_COOKIE)?.value);
|
||||||
|
return Response.json(badges, { headers: { "Cache-Control": "no-store" } });
|
||||||
|
}
|
||||||
48
src/components/admin/AdminBadges.tsx
Normal file
48
src/components/admin/AdminBadges.tsx
Normal file
|
|
@ -0,0 +1,48 @@
|
||||||
|
"use client";
|
||||||
|
import { usePathname } from "next/navigation";
|
||||||
|
import { createContext, useCallback, useContext, useEffect, useState } from "react";
|
||||||
|
|
||||||
|
type Badges = Record<string, number>;
|
||||||
|
const Ctx = createContext<Badges>({});
|
||||||
|
export const useBadges = () => useContext(Ctx);
|
||||||
|
|
||||||
|
const SEEN_COOKIE = "ad_seen";
|
||||||
|
const REFRESH_MS = 60_000;
|
||||||
|
|
||||||
|
function markSeen(key: string) {
|
||||||
|
const m = document.cookie.match(new RegExp(`(?:^|; )${SEEN_COOKIE}=([^;]*)`));
|
||||||
|
let seen: Record<string, number> = {};
|
||||||
|
try {
|
||||||
|
seen = m ? JSON.parse(decodeURIComponent(m[1])) : {};
|
||||||
|
} catch {}
|
||||||
|
seen[key] = Date.now();
|
||||||
|
document.cookie = `${SEEN_COOKIE}=${encodeURIComponent(JSON.stringify(seen))}; path=/admin; max-age=31536000; samesite=lax`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hält die Zähler in der Navigation aktuell: beim Seitenwechsel und jede Minute
|
||||||
|
export function AdminBadgesProvider({ initial, seenSections, children }: { initial: Badges; seenSections: Record<string, string>; children: React.ReactNode }) {
|
||||||
|
const [badges, setBadges] = useState(initial);
|
||||||
|
const pathname = usePathname();
|
||||||
|
const refresh = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
const res = await fetch("/admin/badges", { cache: "no-store" });
|
||||||
|
if (res.ok) setBadges(await res.json());
|
||||||
|
} catch {}
|
||||||
|
}, []);
|
||||||
|
useEffect(() => {
|
||||||
|
for (const [key, href] of Object.entries(seenSections)) {
|
||||||
|
if (pathname === href || pathname.startsWith(href + "/")) markSeen(key);
|
||||||
|
}
|
||||||
|
void refresh();
|
||||||
|
}, [pathname, refresh, seenSections]);
|
||||||
|
useEffect(() => {
|
||||||
|
const id = setInterval(() => document.visibilityState === "visible" && refresh(), REFRESH_MS);
|
||||||
|
const onVis = () => document.visibilityState === "visible" && refresh();
|
||||||
|
document.addEventListener("visibilitychange", onVis);
|
||||||
|
return () => {
|
||||||
|
clearInterval(id);
|
||||||
|
document.removeEventListener("visibilitychange", onVis);
|
||||||
|
};
|
||||||
|
}, [refresh]);
|
||||||
|
return <Ctx.Provider value={badges}>{children}</Ctx.Provider>;
|
||||||
|
}
|
||||||
|
|
@ -2,10 +2,19 @@
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { usePathname } from "next/navigation";
|
import { usePathname } from "next/navigation";
|
||||||
import { Icon } from "../Icon";
|
import { Icon } from "../Icon";
|
||||||
import type { NavItem } from "./nav";
|
import type { BadgeKey, NavItem } from "./nav";
|
||||||
|
import { useBadges } from "./AdminBadges";
|
||||||
|
|
||||||
export function AdminNav({ groups, badges }: { groups: { group: string; items: NavItem[] }[]; badges: Record<string, number> }) {
|
const BADGE: Record<BadgeKey, { cls: string; title: (n: number) => string }> = {
|
||||||
|
openOrders: { cls: " ad-nav__badge--strong", title: (n) => `${n} offene ${n === 1 ? "Bestellung" : "Bestellungen"}` },
|
||||||
|
newCustomers: { cls: "", title: (n) => `${n} ${n === 1 ? "neuer Kunde" : "neue Kunden"} seit deinem letzten Besuch` },
|
||||||
|
newSubscribers: { cls: "", title: (n) => `${n} ${n === 1 ? "neue Anmeldung" : "neue Anmeldungen"} seit deinem letzten Besuch` },
|
||||||
|
lowStock: { cls: " ad-nav__badge--warn", title: (n) => `${n} Artikel mit wenig oder keinem Bestand` },
|
||||||
|
};
|
||||||
|
|
||||||
|
export function AdminNav({ groups }: { groups: { group: string; items: NavItem[] }[] }) {
|
||||||
const pathname = usePathname();
|
const pathname = usePathname();
|
||||||
|
const badges = useBadges();
|
||||||
const active = (href: string) => (href === "/admin" ? pathname === "/admin" : pathname === href || pathname.startsWith(href + "/"));
|
const active = (href: string) => (href === "/admin" ? pathname === "/admin" : pathname === href || pathname.startsWith(href + "/"));
|
||||||
return (
|
return (
|
||||||
<nav className="ad-nav" aria-label="Admin-Navigation">
|
<nav className="ad-nav" aria-label="Admin-Navigation">
|
||||||
|
|
@ -16,7 +25,12 @@ export function AdminNav({ groups, badges }: { groups: { group: string; items: N
|
||||||
<Link key={i.href} href={i.href} aria-current={active(i.href) ? "page" : undefined}>
|
<Link key={i.href} href={i.href} aria-current={active(i.href) ? "page" : undefined}>
|
||||||
<Icon name={i.icon} />
|
<Icon name={i.icon} />
|
||||||
{i.label}
|
{i.label}
|
||||||
{i.badge && badges[i.badge] > 0 && <span className="ad-nav__badge">{badges[i.badge]}</span>}
|
{i.badge && badges[i.badge] > 0 && (
|
||||||
|
<span className={`ad-nav__badge${BADGE[i.badge].cls}`} title={BADGE[i.badge].title(badges[i.badge])}>
|
||||||
|
{badges[i.badge] > 99 ? "99+" : badges[i.badge]}
|
||||||
|
<span className="sr-only">: {BADGE[i.badge].title(badges[i.badge])}</span>
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
</Link>
|
</Link>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,7 @@
|
||||||
import { usePathname } from "next/navigation";
|
import { usePathname } from "next/navigation";
|
||||||
import { useEffect, useRef } from "react";
|
import { useEffect, useRef } from "react";
|
||||||
import { Icon } from "../Icon";
|
import { Icon } from "../Icon";
|
||||||
|
import { useBadges } from "./AdminBadges";
|
||||||
|
|
||||||
export function MobileAdminNav({ children }: { children: React.ReactNode }) {
|
export function MobileAdminNav({ children }: { children: React.ReactNode }) {
|
||||||
const ref = useRef<HTMLDetailsElement>(null);
|
const ref = useRef<HTMLDetailsElement>(null);
|
||||||
|
|
@ -9,10 +10,15 @@ export function MobileAdminNav({ children }: { children: React.ReactNode }) {
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (ref.current) ref.current.open = false;
|
if (ref.current) ref.current.open = false;
|
||||||
}, [pathname]);
|
}, [pathname]);
|
||||||
|
const badges = useBadges();
|
||||||
|
const attention = (badges.openOrders ?? 0) + (badges.lowStock ?? 0) + (badges.newCustomers ?? 0) + (badges.newSubscribers ?? 0) > 0;
|
||||||
const close = () => ref.current && (ref.current.open = false);
|
const close = () => ref.current && (ref.current.open = false);
|
||||||
return (
|
return (
|
||||||
<details className="sm-mnav" ref={ref}>
|
<details className="sm-mnav" ref={ref}>
|
||||||
<summary className="sm-header__btn" aria-label="Menü öffnen" style={{ display: "grid" }}><Icon name="menu" /></summary>
|
<summary className="sm-header__btn" aria-label={attention ? "Menü öffnen, es gibt Neuigkeiten" : "Menü öffnen"} style={{ display: "grid", position: "relative" }}>
|
||||||
|
<Icon name="menu" />
|
||||||
|
{attention && <span className="ad-menu-dot" aria-hidden="true" />}
|
||||||
|
</summary>
|
||||||
<div className="sm-mnav__overlay" onClick={close} />
|
<div className="sm-mnav__overlay" onClick={close} />
|
||||||
<div className="sm-mnav__panel">
|
<div className="sm-mnav__panel">
|
||||||
<button type="button" className="sm-header__btn sm-mnav__close" aria-label="Menü schließen" onClick={close}><Icon name="close" /></button>
|
<button type="button" className="sm-header__btn sm-mnav__close" aria-label="Menü schließen" onClick={close}><Icon name="close" /></button>
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,9 @@
|
||||||
import type { IconName } from "../Icon";
|
import type { IconName } from "../Icon";
|
||||||
import type { Permission } from "@/lib/permissions";
|
import type { Permission } from "@/lib/permissions";
|
||||||
|
|
||||||
export type NavItem = { href: string; label: string; icon: IconName; permission: Permission; badge?: "openOrders" };
|
export type BadgeKey = "openOrders" | "newCustomers" | "newSubscribers" | "lowStock";
|
||||||
|
|
||||||
|
export type NavItem = { href: string; label: string; icon: IconName; permission: Permission; badge?: BadgeKey };
|
||||||
|
|
||||||
export const ADMIN_NAV: { group: string; items: NavItem[] }[] = [
|
export const ADMIN_NAV: { group: string; items: NavItem[] }[] = [
|
||||||
{
|
{
|
||||||
|
|
@ -12,15 +14,15 @@ export const ADMIN_NAV: { group: string; items: NavItem[] }[] = [
|
||||||
group: "Verkauf",
|
group: "Verkauf",
|
||||||
items: [
|
items: [
|
||||||
{ href: "/admin/bestellungen", label: "Bestellungen", icon: "receipt", permission: "orders.view", badge: "openOrders" },
|
{ href: "/admin/bestellungen", label: "Bestellungen", icon: "receipt", permission: "orders.view", badge: "openOrders" },
|
||||||
{ href: "/admin/kunden", label: "Kunden", icon: "users", permission: "customers.view" },
|
{ href: "/admin/kunden", label: "Kunden", icon: "users", permission: "customers.view", badge: "newCustomers" },
|
||||||
{ href: "/admin/gutscheine", label: "Gutscheine", icon: "ticket", permission: "coupons.edit" },
|
{ href: "/admin/gutscheine", label: "Gutscheine", icon: "ticket", permission: "coupons.edit" },
|
||||||
{ href: "/admin/newsletter", label: "Newsletter", icon: "mail", permission: "newsletter.view" },
|
{ href: "/admin/newsletter", label: "Newsletter", icon: "mail", permission: "newsletter.view", badge: "newSubscribers" },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
group: "Katalog",
|
group: "Katalog",
|
||||||
items: [
|
items: [
|
||||||
{ href: "/admin/produkte", label: "Produkte", icon: "box", permission: "products.view" },
|
{ href: "/admin/produkte", label: "Produkte", icon: "box", permission: "products.view", badge: "lowStock" },
|
||||||
{ href: "/admin/kategorien", label: "Kategorien", icon: "folder", permission: "categories.edit" },
|
{ href: "/admin/kategorien", label: "Kategorien", icon: "folder", permission: "categories.edit" },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
|
|
||||||
53
src/lib/admin-badges.ts
Normal file
53
src/lib/admin-badges.ts
Normal file
|
|
@ -0,0 +1,53 @@
|
||||||
|
import "server-only";
|
||||||
|
import { db } from "./db";
|
||||||
|
import { can, type CurrentUser } from "./auth";
|
||||||
|
import { PAYMENT_DEFINITIONS } from "./payments/catalog";
|
||||||
|
|
||||||
|
import type { BadgeKey } from "@/components/admin/nav";
|
||||||
|
|
||||||
|
export type { BadgeKey };
|
||||||
|
export type Badges = Partial<Record<BadgeKey, number>>;
|
||||||
|
|
||||||
|
export const SEEN_COOKIE = "ad_seen";
|
||||||
|
// Bereiche, deren Zähler nach dem Besuch zurückgesetzt wird
|
||||||
|
export const SEEN_SECTIONS = { newCustomers: "/admin/kunden", newSubscribers: "/admin/newsletter" } as const;
|
||||||
|
|
||||||
|
const MANUAL = PAYMENT_DEFINITIONS.filter((d) => d.provider === "manual").map((d) => d.code);
|
||||||
|
const LOW_STOCK = 3;
|
||||||
|
|
||||||
|
export function parseSeen(raw: string | undefined): Partial<Record<keyof typeof SEEN_SECTIONS, number>> {
|
||||||
|
try {
|
||||||
|
const v = JSON.parse(decodeURIComponent(raw ?? "")) as Record<string, unknown>;
|
||||||
|
return Object.fromEntries(Object.entries(v).filter(([, t]) => typeof t === "number"));
|
||||||
|
} catch {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getBadges(user: CurrentUser, seenRaw: string | undefined): Promise<Badges> {
|
||||||
|
const seen = parseSeen(seenRaw);
|
||||||
|
// Ohne Besuch zählen die letzten 7 Tage als neu
|
||||||
|
const since = (k: keyof typeof SEEN_SECTIONS) => new Date(seen[k] ?? Date.now() - 7 * 86400000);
|
||||||
|
const [openOrders, newCustomers, newSubscribers, lowStock] = await Promise.all([
|
||||||
|
can(user, "orders.view")
|
||||||
|
? db.order.count({
|
||||||
|
where: {
|
||||||
|
OR: [
|
||||||
|
{ status: { in: ["PAID", "PROCESSING"] } },
|
||||||
|
// Vorkasse, Rechnung und Nachnahme warten ebenfalls auf uns; offene Online-Zahlungen sind meist abgebrochene Kassenvorgänge
|
||||||
|
{ status: "PENDING", paymentMethod: { in: MANUAL } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
})
|
||||||
|
: 0,
|
||||||
|
can(user, "customers.view") ? db.user.count({ where: { roleId: null, createdAt: { gt: since("newCustomers") } } }) : 0,
|
||||||
|
can(user, "newsletter.view") ? db.newsletterSubscriber.count({ where: { createdAt: { gt: since("newSubscribers") } } }) : 0,
|
||||||
|
can(user, "products.view")
|
||||||
|
? Promise.all([
|
||||||
|
db.product.count({ where: { trackStock: true, active: true, stock: { lte: LOW_STOCK }, variants: { none: {} } } }),
|
||||||
|
db.productVariant.count({ where: { stock: { lte: LOW_STOCK }, product: { trackStock: true, active: true } } }),
|
||||||
|
]).then(([a, b]) => a + b)
|
||||||
|
: 0,
|
||||||
|
]);
|
||||||
|
return { openOrders, newCustomers, newSubscribers, lowStock };
|
||||||
|
}
|
||||||
|
|
@ -171,3 +171,8 @@ a.ad-kpi:hover { border-color: var(--line-strong); }
|
||||||
.ad-form .sm-form-row .sm-field + .sm-field { margin-top: 0; }
|
.ad-form .sm-form-row .sm-field + .sm-field { margin-top: 0; }
|
||||||
.ad-upload__bar { display: block; width: 80px; height: 4px; margin: var(--space-1) auto 0; border-radius: 2px; background: var(--line); overflow: hidden; }
|
.ad-upload__bar { display: block; width: 80px; height: 4px; margin: var(--space-1) auto 0; border-radius: 2px; background: var(--line); overflow: hidden; }
|
||||||
.ad-upload__bar > span { display: block; height: 100%; background: var(--gold); transition: width 150ms linear; }
|
.ad-upload__bar > span { display: block; height: 100%; background: var(--gold); transition: width 150ms linear; }
|
||||||
|
.ad-nav__badge--strong { background: var(--gold); color: var(--on-gold); }
|
||||||
|
.ad-nav__badge--warn { background: var(--danger-soft); color: var(--danger); }
|
||||||
|
.ad-nav a[aria-current="page"] .ad-nav__badge { background: var(--gold); color: var(--on-gold); }
|
||||||
|
.ad-menu-dot { position: absolute; top: 9px; right: 9px; width: 9px; height: 9px; border-radius: 50%; background: var(--gold); box-shadow: 0 0 0 2px var(--surface); }
|
||||||
|
.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0; }
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue