diff --git a/docs/food-encyclopedia/P2-EDITORIAL.md b/docs/food-encyclopedia/P2-EDITORIAL.md new file mode 100644 index 00000000..e00defd7 --- /dev/null +++ b/docs/food-encyclopedia/P2-EDITORIAL.md @@ -0,0 +1,34 @@ +# P2 — Food Encyclopedia Editorial Engine + +Work package [#367](https://github.com/baba-dev/menuminute/issues/367), based on approved Atlas P1 [#364](https://github.com/baba-dev/menuminute/pull/364). + +## Safety-first workflow + +Draft -> Submit for review -> Distinct human superadmin approval -> Publish immutable revision. Saving after publication creates a new draft, leaving the old published revision intact. Restoring a previously approved revision is an audited publication. No automatically published AI, OCR or dish-catalogue data. Unverified foods must never be marked allergen-safe. Each publication requires a named reviewer and a separately authenticated publishing action. + +## Migration ownership and dependency + +- P2 reserves **0118_food_encyclopedia_editorial**. Concurrent Tiffin [PR #366](https://github.com/baba-dev/menuminute/pull/366) contains 0115 and 0116. +- The migration journal and final SHA **must be reconciled after #366** before merging P2. P2 cannot be merged/deployed against a migration history that skips 0115/0116. Do not force-merge around the ledger. +- All P2 SQL is additive; app/worker have no direct table privileges. Existing merchant schemas, orders, checkout and ERP remain untouched. The migration owner installs only reviewed SQL after a verified encrypted off-host backup. +- Reviews use session + active 2FA + one-use step-up via app_private.require_step_up(), with source and actor audit in the same transaction. A reviewer cannot approve their own authored revision. + +## Public and advertising + +- Published content is a whitelisted JSON projection from a narrow SECURITY DEFINER read gateway; drafts and internal notes cannot be fetched on public endpoints. +- SSR search and sitemap consider only published revisions. Preview-only P1 fixtures remain noindex and never become published without independent review. +- AdSense is disabled. Publication is **not** consent/ads activation. +- A missing migration or read failure never leaks private data or incorrectly flags an unpublished entry as indexed. + +## Validation + +Use frozen-lockfile install, TypeScript, lint/Prettier, Vitest integration, ARM64 Next compile, Playwright and independent database privilege review. Production releases require v7 helper, schema+media backups, exact-SHA checks, ERP coexistence checks and forward-only migration safety. A green PR is not production deployment. + +## P2 implementation update + +- Eight logical commits delivered on the PR branch, plus QA corrections as required. +- Real database published pages supersede P1 sample previews. In production, no sample article is indexable or served as a substitute for reviewed content. +- Public pages fail closed on missing migration or empty editorial store. Search excludes unapproved data, ad slots remain inactive. +- The editorial form requires manual explicit Save with step-up; unattended autosave is intentionally not enabled, to avoid bypassing one-use administrator verification. +- A separate independently approved superadmin is necessary to approve an author's submission; never self-approve. +- **Migration dependency**: PR #366 has 0115/0116 but another branch added 0115 receipt UPI to current main. Coordinate migration renumbering and journal sequence before merging P2; no merge/deploy until conflict resolved. diff --git a/src/app/admin/admin-nav.tsx b/src/app/admin/admin-nav.tsx index fa43879d..162a5961 100644 --- a/src/app/admin/admin-nav.tsx +++ b/src/app/admin/admin-nav.tsx @@ -13,6 +13,7 @@ import { SlidersHorizontal, Lock, LifeBuoy, + BookOpenText, ArrowLeft, } from "lucide-react"; @@ -33,6 +34,7 @@ const navItems: NavItem[] = [ { href: "/admin/payments", label: "Payments & Grants", icon: CreditCard }, { href: "/admin/kitchen", label: "Kitchen Control Desk", icon: ChefHat }, { href: "/admin/support", label: "Support Desk", icon: LifeBuoy }, + { href: "/admin/encyclopedia", label: "Food Encyclopedia", icon: BookOpenText }, { href: "/admin/security", label: "Security & Audits", icon: Lock }, ]; diff --git a/src/app/admin/encyclopedia/[id]/page.tsx b/src/app/admin/encyclopedia/[id]/page.tsx new file mode 100644 index 00000000..79c69e44 --- /dev/null +++ b/src/app/admin/encyclopedia/[id]/page.tsx @@ -0,0 +1,27 @@ +import type { Metadata } from "next"; +import { notFound } from "next/navigation"; +import { verifySuperAdmin } from "@/lib/admin-guard"; +import { getEditorialDetail } from "@/modules/food-encyclopedia/editorial-service"; +import { newEditorialDraft } from "@/modules/food-encyclopedia/editorial-template"; +import { EditorialEditor } from "../editor"; +export const dynamic = "force-dynamic"; +export const metadata: Metadata = { + title: "Edit food guide | Editorial Studio", + robots: { index: false }, +}; +export default async function FoodEditorialPage({ params }: { params: Promise<{ id: string }> }) { + const actor = await verifySuperAdmin(); + const { id } = await params; + const entry = await getEditorialDetail(actor, id); + if (!entry) notFound(); + return ( + + ); +} diff --git a/src/app/admin/encyclopedia/actions.ts b/src/app/admin/encyclopedia/actions.ts new file mode 100644 index 00000000..d38b906b --- /dev/null +++ b/src/app/admin/encyclopedia/actions.ts @@ -0,0 +1,80 @@ +"use server"; + +import { revalidatePath } from "next/cache"; +import { z } from "zod"; +import { verifySuperAdmin } from "@/lib/admin-guard"; +import { FoodDraftSchema, FoodEditorialActionSchema } from "@/modules/food-encyclopedia/editorial-contracts"; +import { runEditorialCommand } from "@/modules/food-encyclopedia/editorial-service"; + +const requestSchema = z + .object({ + action: z.union([FoodEditorialActionSchema, z.literal("media.approve"), z.literal("import")]), + target: z.string().max(100).min(1), + expectedVersion: z.number().int().min(0).optional(), + content: FoodDraftSchema.optional(), + revisionId: z.string().uuid().optional(), + path: z.string().max(240).optional(), + license: z.enum(["owned", "commissioned", "cc0", "cc-by", "licensed"]).optional(), + attribution: z.string().max(240).optional(), + requestKey: z.string().uuid(), + }) + .strict(); +export type EditorialActionRequest = z.infer; +export type EditorialActionResponse = + { ok: true; id: string; status?: string; version?: number } | { ok: false; error: string }; + +export async function submitEditorialAction( + input: EditorialActionRequest +): Promise { + const actor = await verifySuperAdmin(); + const parsed = requestSchema.safeParse(input); + if (!parsed.success) + return { ok: false, error: "Invalid editorial fields. Review the form and retry." }; + const p = parsed.data; + try { + const receipt = await runEditorialCommand( + actor, + p.action, + p.target, + { + ...(p.content ? { content: p.content } : {}), + ...(p.expectedVersion !== undefined ? { expectedVersion: p.expectedVersion } : {}), + ...(p.revisionId ? { revisionId: p.revisionId } : {}), + ...(p.path ? { path: p.path } : {}), + ...(p.license ? { license: p.license } : {}), + ...(p.attribution !== undefined ? { attribution: p.attribution } : {}), + }, + p.requestKey + ); + revalidatePath("/admin/encyclopedia"); + revalidatePath("/explore"); + revalidatePath("/explore/browse"); + revalidatePath("/explore/search"); + revalidatePath("/sitemap.xml"); + if (p.content) revalidatePath("/explore/" + p.content.kind + "/" + p.content.slug); + return { ok: true, id: receipt.id, status: receipt.status, version: receipt.version }; + } catch (e) { + const code = (e as { code?: string })?.code; + if (code === "42501") + return { + ok: false, + error: + "Administrator verification or a fresh password/TOTP step-up is required; a different person must approve authored revisions.", + }; + if (code === "40001" || code === "23505") + return { + ok: false, + error: "The entry changed or the request key conflicts. Reload before retrying.", + }; + if (code === "22023") + return { + ok: false, + error: + "Editorial rules blocked this action. Review source, length, and workflow requirements.", + }; + return { + ok: false, + error: "The editorial request could not be completed. No changes were published.", + }; + } +} diff --git a/src/app/admin/encyclopedia/editor.tsx b/src/app/admin/encyclopedia/editor.tsx new file mode 100644 index 00000000..2f253ab2 --- /dev/null +++ b/src/app/admin/encyclopedia/editor.tsx @@ -0,0 +1,781 @@ +"use client"; + +import { useMemo, useState, useTransition } from "react"; +import Link from "next/link"; +import { useRouter } from "next/navigation"; +import { + ArrowLeft, + BookOpenText, + CheckCircle2, + FileClock, + FileText, + ImageIcon, + Link2, + LockKeyhole, + Monitor, + Plus, + ShieldCheck, + Smartphone, + Trash2, + TriangleAlert, +} from "lucide-react"; +import { + FoodDraftSchema, + editorialQualityIssues, + type FoodDraft, + type FoodWorkflowStatus, +} from "@/modules/food-encyclopedia/editorial-contracts"; +import { submitEditorialAction, type EditorialActionRequest } from "./actions"; + +type History = { + id: string; + version: number; + authorId: string; + reviewedBy: string | null; + reviewedAt: string | null; + createdAt: string; + approved: boolean; +}; +type Props = { + initial: FoodDraft; + id: string | null; + version: number; + status: FoodWorkflowStatus; + versions: History[]; + publishedRevisionId: string | null; +}; +const field = + "rounded-xl border border-stone-300 bg-white px-3 py-2.5 text-sm text-stone-900 outline-offset-2 focus-visible:outline-orange-500 dark:border-stone-700 dark:bg-stone-950 dark:text-stone-100"; +const subtle = "text-xs font-semibold tracking-wide text-stone-600 dark:text-stone-400"; +const panel = + "rounded-2xl border border-stone-200 bg-white p-5 shadow-sm dark:border-stone-800 dark:bg-stone-900"; +function removeEmpty(text: string) { + return text + .split(/\r?\n/) + .map((x) => x.trim()) + .filter(Boolean); +} +function Status({ status }: { status: FoodWorkflowStatus }) { + return ( + + {status.replace("_", " ")} + + ); +} +export function EditorialEditor({ + initial, + id, + version, + status, + versions, + publishedRevisionId, +}: Props) { + const router = useRouter(); + const [draft, setDraft] = useState(initial); + const [actualVersion, setActualVersion] = useState(version); + const [currentStatus, setStatus] = useState(status); + const [busy, startTransition] = useTransition(); + const [message, setMessage] = useState<{ ok: boolean; value: string } | null>(null); + const [view, setView] = useState<"edit" | "preview">("edit"); + const [device, setDevice] = useState<"desktop" | "mobile">("desktop"); + const [license, setLicense] = useState<"owned" | "commissioned" | "cc0" | "cc-by" | "licensed">( + "owned" + ); + const [attribution, setAttribution] = useState(""); + const issues = useMemo(() => { + const parsed = FoodDraftSchema.safeParse(draft); + if (!parsed.success) + return parsed.error.issues.map((e) => ({ field: e.path.join("."), detail: e.message })); + return editorialQualityIssues(parsed.data); + }, [draft]); + const update = (key: K, value: FoodDraft[K]) => + setDraft((d) => ({ ...d, [key]: value })); + function run( + action: EditorialActionRequest["action"], + extra: Partial = {} + ) { + if (busy) return; + setMessage(null); + const isContent = ["create", "save", "import"].includes(action); + const parsed = isContent ? FoodDraftSchema.safeParse(draft) : null; + if (parsed && !parsed.success) { + setMessage({ + ok: false, + value: + "Correct form fields before saving: " + + parsed.error.issues + .slice(0, 2) + .map((x) => x.path.join(".") + " " + x.message) + .join("; "), + }); + return; + } + if (action === "submit" && issues.length) { + setMessage({ + ok: false, + value: "Resolve the quality checklist before submitting for review.", + }); + return; + } + const payload: EditorialActionRequest = { + action, + target: id ?? "new", + expectedVersion: actualVersion, + requestKey: crypto.randomUUID(), + ...(isContent ? { content: draft } : {}), + ...extra, + }; + startTransition(async () => { + const result = await submitEditorialAction(payload); + if (!result.ok) { + setMessage({ ok: false, value: result.error }); + return; + } + setMessage({ + ok: true, + value: "Recorded. Review the updated workflow state before the next action.", + }); + if (result.version !== undefined) setActualVersion(result.version); + if (result.status) setStatus(result.status as FoodWorkflowStatus); + if (!id) { + router.push("/admin/encyclopedia/" + result.id); + return; + } + router.refresh(); + }); + } + const edited = !id; + return ( +
+
+ + + All guides + +
+ + v{actualVersion} +
+
+
+
+

+ The Atlas / Editorial Studio +

+

+ {edited ? "Create a researched food guide" : draft.title} +

+

+ A draft is never public until a separate reviewer approves the exact revision. +

+
+
+ + +
+
+
+ +

+ Before each action,{" "} + + complete the one-time admin step-up + + . Saving creates a new immutable revision; it does not edit the published version. +

+
+ {message && ( +
+ {message.value} +
+ )} +
+ {view === "edit" ? ( +
+
+

+ + Identity & summary +

+
+ + + + +