From 3b1c6e2527e012a5cba466f73eafe80260b1fda0 Mon Sep 17 00:00:00 2001 From: "Sameer .I. Siddiqui" Date: Sun, 22 Nov 2026 23:40:32 +0530 Subject: [PATCH 01/15] feat(encyclopedia): define immutable editorial workflow and quality contracts --- docs/food-encyclopedia/P2-EDITORIAL.md | 21 ++++++ .../editorial-contracts.test.ts | 30 ++++++++ .../food-encyclopedia/editorial-contracts.ts | 73 +++++++++++++++++++ 3 files changed, 124 insertions(+) create mode 100644 docs/food-encyclopedia/P2-EDITORIAL.md create mode 100644 src/modules/food-encyclopedia/editorial-contracts.test.ts create mode 100644 src/modules/food-encyclopedia/editorial-contracts.ts diff --git a/docs/food-encyclopedia/P2-EDITORIAL.md b/docs/food-encyclopedia/P2-EDITORIAL.md new file mode 100644 index 00000000..eaed9e5c --- /dev/null +++ b/docs/food-encyclopedia/P2-EDITORIAL.md @@ -0,0 +1,21 @@ +# 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 **0117_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. diff --git a/src/modules/food-encyclopedia/editorial-contracts.test.ts b/src/modules/food-encyclopedia/editorial-contracts.test.ts new file mode 100644 index 00000000..798f4f85 --- /dev/null +++ b/src/modules/food-encyclopedia/editorial-contracts.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, it } from "vitest"; +import { FoodDraftSchema, editorialQualityIssues, transitionAllowed } from "./editorial-contracts"; +import { getFoodEntry } from "./pilot"; + +describe("Food Encyclopedia editorial gates", () => { + const fixture = getFoodEntry("dishes", "paneer-tikka")!; + const draft = { + kind: fixture.kind, slug: fixture.slug, title: fixture.title, + eyebrow: fixture.eyebrow, description: fixture.description, tint: fixture.tint, + imagePath: fixture.imagePath, imageAlt: fixture.imageAlt, aliases: fixture.aliases, + facts: fixture.facts, sections: fixture.sections, sourceUrls: fixture.sourceUrls, + relatedSlugs: fixture.relatedSlugs, caution: fixture.caution, + }; + it("accepts a bounded draft, not a published record or executable markup", () => { + expect(FoodDraftSchema.parse(draft).slug).toBe("paneer-tikka"); + expect(FoodDraftSchema.safeParse({ ...draft, status: "published" }).success).toBe(false); + expect(FoodDraftSchema.safeParse({ ...draft, slug: "../admin" }).success).toBe(false); + expect(FoodDraftSchema.safeParse({ ...draft, sourceUrls: ["http://example.com"] }).success).toBe(false); + }); + it("never qualifies a content fixture as human-reviewed by default", () => { + expect(editorialQualityIssues(FoodDraftSchema.parse(draft)).length).toBeGreaterThan(0); + }); + it("rejects bypasses of submit/approve/publish transition order", () => { + expect(transitionAllowed("draft", "approve")).toBe(false); + expect(transitionAllowed("draft", "publish")).toBe(false); + expect(transitionAllowed("in_review", "publish")).toBe(false); + expect(transitionAllowed("approved", "publish")).toBe(true); + expect(transitionAllowed("published", "save")).toBe(true); // published revision remains immutable + }); +}); diff --git a/src/modules/food-encyclopedia/editorial-contracts.ts b/src/modules/food-encyclopedia/editorial-contracts.ts new file mode 100644 index 00000000..9d98de6f --- /dev/null +++ b/src/modules/food-encyclopedia/editorial-contracts.ts @@ -0,0 +1,73 @@ +import { z } from "zod"; +import { foodKinds } from "./contracts"; + +/** Editorial identity is platform-wide, never a merchant-owned dish or tenancy scope. */ +const slug = z.string().trim().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/).max(90); +const httpsUrl = z.string().url().max(1000).refine((value) => { + try { const url = new URL(value); return url.protocol === "https:" && !url.username && !url.password; } + catch { return false; } +}, "A public HTTPS source is required"); + +export const FoodDraftSchema = z.object({ + kind: z.enum(foodKinds), + slug, + title: z.string().trim().min(3).max(100), + eyebrow: z.string().trim().min(3).max(120), + description: z.string().trim().min(35).max(320), + tint: z.enum(["cream", "sage", "blue", "peach", "lavender"]), + imagePath: z.string().regex(/^\/assets\/food\/dishes\/[a-zA-Z0-9/_-]+\.(?:png|webp|avif)$/).max(240).optional(), + imageAlt: z.string().trim().max(200).optional(), + aliases: z.array(z.string().trim().min(2).max(90)).max(20).default([]), + facts: z.array(z.object({ label: z.string().trim().min(2).max(40), value: z.string().trim().min(2).max(140) }).strict()).min(2).max(8), + sections: z.array(z.object({ + id: slug, + eyebrow: z.string().trim().min(3).max(80), + title: z.string().trim().min(3).max(150), + body: z.array(z.string().trim().min(25).max(1800)).min(1).max(6), + }).strict()).min(2).max(12), + sourceUrls: z.array(httpsUrl).max(20).default([]), + relatedSlugs: z.array(slug).max(20).default([]), + caution: z.string().trim().min(20).max(650).optional(), +}).strict(); +export type FoodDraft = z.infer; +export const FoodEditorialActionSchema = z.enum(["create", "save", "submit", "approve", "publish", "unpublish", "restore"]); +export type FoodEditorialAction = z.infer; +export type FoodWorkflowStatus = "draft" | "in_review" | "approved" | "published" | "archived"; +export type FoodEditorialRow = { + id: string; kind: FoodDraft["kind"]; slug: string; title: string; + status: FoodWorkflowStatus; version: number; createdAt: string; updatedAt: string; + hasPublishedVersion: boolean; publishedAt: string | null; +}; +export type FoodEditorialDetail = FoodEditorialRow & { + draft: FoodDraft | null; + versions: Array<{ id: string; version: number; authorId: string; reviewedBy: string | null; reviewedAt: string | null; createdAt: string; approved: boolean }>; + publishedRevisionId: string | null; draftRevisionId: string | null; + reviewRevisionId: string | null; approvedRevisionId: string | null; + events: Array<{ action: string; actorId: string; createdAt: string; revisionId: string | null }>; +}; + +export type QualityIssue = { field: string; detail: string }; +/** Human editorial review is still mandatory even when this local checker is satisfied. */ +export function editorialQualityIssues(draft: FoodDraft): QualityIssue[] { + const issues: QualityIssue[] = []; + if (draft.sourceUrls.length < 2) issues.push({ field: "sourceUrls", detail: "At least two credible independent sources are required" }); + if (new Set(draft.sourceUrls).size !== draft.sourceUrls.length) issues.push({ field: "sourceUrls", detail: "Duplicate source URLs" }); + if (new Set(draft.sections.map((s) => s.id)).size !== draft.sections.length) issues.push({ field: "sections", detail: "Section IDs must be unique" }); + if (new Set(draft.aliases.map((a) => a.toLocaleLowerCase())).size !== draft.aliases.length) issues.push({ field: "aliases", detail: "Aliases must be unique" }); + const copy = draft.sections.flatMap((s) => s.body).join(" "); + if (copy.trim().split(/\s+/u).length < 110) issues.push({ field: "sections", detail: "Article needs more useful, original explanatory content (110 words minimum for this pilot)" }); + if (draft.imagePath && (!draft.imageAlt || draft.imageAlt.length < 15)) + issues.push({ field: "imageAlt", detail: "Meaningful alternative text is required for illustrations" }); + return issues; +} + +export function transitionAllowed(status: FoodWorkflowStatus, action: FoodEditorialAction): boolean { + if (action === "create") return status === "draft"; + if (action === "save") return true; // creates a NEW revision; never edits an approved one + if (action === "submit") return status === "draft"; + if (action === "approve") return status === "in_review"; + if (action === "publish") return status === "approved"; + if (action === "unpublish") return status === "published"; + if (action === "restore") return true; // requires a previously approved revision in SQL + return false; +} From 03a33aef79177c454dbfcc82658515980d12bec2 Mon Sep 17 00:00:00 2001 From: "Sameer .I. Siddiqui" Date: Sun, 22 Nov 2026 23:41:34 +0530 Subject: [PATCH 02/15] feat(encyclopedia): add isolated additive PostgreSQL editorial schema with owner-only RLS --- .../0117_food_encyclopedia_editorial.sql | 130 ++++++++++++++++++ src/db/migrations/meta/_journal.json | 7 + src/db/schema/food-encyclopedia.ts | 66 +++++++++ src/db/schema/index.ts | 2 + 4 files changed, 205 insertions(+) create mode 100644 src/db/migrations/0117_food_encyclopedia_editorial.sql create mode 100644 src/db/schema/food-encyclopedia.ts diff --git a/src/db/migrations/0117_food_encyclopedia_editorial.sql b/src/db/migrations/0117_food_encyclopedia_editorial.sql new file mode 100644 index 00000000..2dc481d3 --- /dev/null +++ b/src/db/migrations/0117_food_encyclopedia_editorial.sql @@ -0,0 +1,130 @@ +-- 0117 Food Encyclopedia editorial foundation. Additive / app+worker direct access denied. +-- IMPORTANT: #366 reserves 0115/0116; reconcile migration journal after that PR BEFORE merge. +-- Public data remains empty until a separately approved human editorial review. +CREATE TABLE food_entries ( + id text PRIMARY KEY DEFAULT gen_random_uuid()::text, + kind text NOT NULL CHECK (kind IN ('dishes','ingredients','cuisines','terms','compare')), + slug text NOT NULL CHECK (slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' AND length(slug)<=90), + status text NOT NULL DEFAULT 'draft' + CHECK (status IN ('draft','in_review','approved','published','archived')), + version integer NOT NULL DEFAULT 0 CHECK (version >= 0), + draft_revision_id text, + review_revision_id text, + approved_revision_id text, + published_revision_id text, + published_at timestamptz, + search_text text NOT NULL DEFAULT '', + created_by text NOT NULL REFERENCES users(id) ON DELETE RESTRICT, + updated_by text NOT NULL REFERENCES users(id) ON DELETE RESTRICT, + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + updated_at timestamptz NOT NULL DEFAULT clock_timestamp(), + CONSTRAINT food_entries_kind_slug_key UNIQUE(kind,slug), + CONSTRAINT food_entries_published_pointer_check + CHECK ((published_revision_id IS NULL) = (published_at IS NULL)) +); +CREATE INDEX food_entries_published_at_idx ON food_entries(published_at DESC,id) + WHERE published_revision_id IS NOT NULL; +CREATE INDEX food_entries_search_idx ON food_entries + USING gin(to_tsvector('simple',search_text)); + +CREATE TABLE food_revisions ( + id text PRIMARY KEY DEFAULT gen_random_uuid()::text, + entry_id text NOT NULL REFERENCES food_entries(id) ON DELETE RESTRICT, + version integer NOT NULL CHECK (version > 0), + content jsonb NOT NULL CHECK (jsonb_typeof(content)='object'), + digest text NOT NULL CHECK (digest ~ '^[0-9a-f]{64}$'), + author_id text NOT NULL REFERENCES users(id) ON DELETE RESTRICT, + approved boolean NOT NULL DEFAULT false, + reviewed_by text REFERENCES users(id) ON DELETE RESTRICT, + reviewed_at timestamptz, + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + CONSTRAINT food_revisions_entry_version_key UNIQUE(entry_id,version), + CONSTRAINT food_revisions_entry_id_key UNIQUE(entry_id,id), + CONSTRAINT food_revisions_approval_check CHECK + ((approved=false AND reviewed_by IS NULL AND reviewed_at IS NULL) OR + (approved=true AND reviewed_by IS NOT NULL AND reviewed_at IS NOT NULL AND reviewed_by<>author_id)) +); +ALTER TABLE food_entries + ADD CONSTRAINT food_entries_draft_revision_fk + FOREIGN KEY(id,draft_revision_id) REFERENCES food_revisions(entry_id,id), + ADD CONSTRAINT food_entries_review_revision_fk + FOREIGN KEY(id,review_revision_id) REFERENCES food_revisions(entry_id,id), + ADD CONSTRAINT food_entries_approved_revision_fk + FOREIGN KEY(id,approved_revision_id) REFERENCES food_revisions(entry_id,id), + ADD CONSTRAINT food_entries_published_revision_fk + FOREIGN KEY(id,published_revision_id) REFERENCES food_revisions(entry_id,id); + +CREATE TABLE food_sources ( + id text PRIMARY KEY DEFAULT gen_random_uuid()::text, + url text NOT NULL UNIQUE CHECK (length(url) BETWEEN 10 AND 1000 AND url ~ '^https://'), + title text NOT NULL DEFAULT '' CHECK (length(title)<=240), + publisher text NOT NULL DEFAULT '' CHECK (length(publisher)<=140), + retrieved_at timestamptz, + created_at timestamptz NOT NULL DEFAULT clock_timestamp() +); +CREATE TABLE food_entry_sources ( + revision_id text NOT NULL REFERENCES food_revisions(id) ON DELETE RESTRICT, + source_id text NOT NULL REFERENCES food_sources(id) ON DELETE RESTRICT, + section_id text NOT NULL DEFAULT '' CHECK (length(section_id)<=90), + PRIMARY KEY(revision_id,source_id,section_id) +); +CREATE TABLE food_aliases ( + entry_id text NOT NULL REFERENCES food_entries(id) ON DELETE CASCADE, + alias text NOT NULL CHECK(length(alias) BETWEEN 2 AND 90), + normalized text NOT NULL CHECK(length(normalized) BETWEEN 2 AND 90), + PRIMARY KEY(entry_id,normalized) +); +CREATE INDEX food_aliases_normalized_idx ON food_aliases(normalized); +CREATE TABLE food_relations ( + entry_id text NOT NULL REFERENCES food_entries(id) ON DELETE CASCADE, + related_entry_id text NOT NULL REFERENCES food_entries(id) ON DELETE CASCADE, + relation text NOT NULL DEFAULT 'related' CHECK (relation IN ('related','ingredient','cuisine','comparison')), + PRIMARY KEY(entry_id,related_entry_id,relation), + CONSTRAINT food_relations_not_self CHECK(entry_id<>related_entry_id) +); +CREATE TABLE food_media ( + id text PRIMARY KEY DEFAULT gen_random_uuid()::text, + entry_id text NOT NULL REFERENCES food_entries(id) ON DELETE CASCADE, + path text NOT NULL CHECK (path ~ '^/assets/food/dishes/[a-zA-Z0-9/_-]+[.](png|webp|avif)$'), + alt_text text NOT NULL CHECK (length(alt_text) BETWEEN 15 AND 200), + license text NOT NULL DEFAULT 'pending' CHECK (length(license)<=100), + attribution text NOT NULL DEFAULT '' CHECK (length(attribution)<=240), + rights_approved boolean NOT NULL DEFAULT false, + verified_by text REFERENCES users(id) ON DELETE RESTRICT, + verified_at timestamptz, + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + CONSTRAINT food_media_rights_check CHECK( + (rights_approved=false AND verified_by IS NULL AND verified_at IS NULL) OR + (rights_approved=true AND verified_by IS NOT NULL AND verified_at IS NOT NULL) + ) +); +CREATE TABLE food_editorial_events ( + id text PRIMARY KEY DEFAULT gen_random_uuid()::text, + entry_id text NOT NULL REFERENCES food_entries(id) ON DELETE RESTRICT, + revision_id text REFERENCES food_revisions(id) ON DELETE RESTRICT, + action text NOT NULL CHECK (action IN ('create','save','submit','approve','publish','unpublish','restore','import')), + actor_id text NOT NULL REFERENCES users(id) ON DELETE RESTRICT, + details jsonb NOT NULL DEFAULT '{}'::jsonb, + created_at timestamptz NOT NULL DEFAULT clock_timestamp() +); +CREATE INDEX food_editorial_events_entry_idx ON food_editorial_events(entry_id,created_at DESC); +CREATE TABLE food_redirects ( + kind text NOT NULL CHECK (kind IN ('dishes','ingredients','cuisines','terms','compare')), + old_slug text NOT NULL CHECK (old_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$'), + entry_id text NOT NULL REFERENCES food_entries(id) ON DELETE RESTRICT, + PRIMARY KEY(kind,old_slug) +); + +-- Migration role is the only direct-reader/writer. Definer gateway functions (appended in +-- the next commit) whitelist public projection and demand live operator+step-up for edits. +DO $block$ DECLARE t text; BEGIN + FOREACH t IN ARRAY ARRAY[ + 'food_entries','food_revisions','food_sources','food_entry_sources', + 'food_aliases','food_relations','food_media','food_editorial_events','food_redirects' + ] LOOP + EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY',t); + EXECUTE format('ALTER TABLE %I FORCE ROW LEVEL SECURITY',t); + EXECUTE format('REVOKE ALL ON %I FROM PUBLIC,menuminute_app,menuminute_worker',t); + EXECUTE format('CREATE POLICY food_owner_only ON %I FOR ALL TO menuminute_owner USING (true) WITH CHECK (true)',t); + END LOOP; +END $block$; diff --git a/src/db/migrations/meta/_journal.json b/src/db/migrations/meta/_journal.json index f73ddf7b..cc3b7530 100644 --- a/src/db/migrations/meta/_journal.json +++ b/src/db/migrations/meta/_journal.json @@ -799,6 +799,13 @@ "when": 1797080400046, "tag": "0114_tiffin_foundation", "breakpoints": true + }, + { + "idx": 114, + "version": "7", + "when": 1797080400049, + "tag": "0117_food_encyclopedia_editorial", + "breakpoints": true } ] } diff --git a/src/db/schema/food-encyclopedia.ts b/src/db/schema/food-encyclopedia.ts new file mode 100644 index 00000000..56b58169 --- /dev/null +++ b/src/db/schema/food-encyclopedia.ts @@ -0,0 +1,66 @@ +// Platform-owned editorial storage; no merchant tenancy scope or runtime table grants. +// Migration 0117 is authoritative; access only through narrow SECURITY DEFINER functions. +import { sql } from "drizzle-orm"; +import { + boolean, check, index, integer, jsonb, pgTable, text, timestamp, unique, +} from "drizzle-orm/pg-core"; +const clock = () => timestamp("created_at",{withTimezone:true}).notNull().default(sql`clock_timestamp()`); +export const foodEntries = pgTable("food_entries",{ + id:text("id").primaryKey().default(sql`gen_random_uuid()::text`), + kind:text("kind").notNull(), slug:text("slug").notNull(), + status:text("status").notNull().default("draft"), + version:integer("version").notNull().default(0), + draftRevisionId:text("draft_revision_id"), reviewRevisionId:text("review_revision_id"), + approvedRevisionId:text("approved_revision_id"), publishedRevisionId:text("published_revision_id"), + publishedAt:timestamp("published_at",{withTimezone:true}), + searchText:text("search_text").notNull().default(""), + createdBy:text("created_by").notNull(), updatedBy:text("updated_by").notNull(), + createdAt:clock(), updatedAt:timestamp("updated_at",{withTimezone:true}).notNull().default(sql`clock_timestamp()`), +},(t)=>[unique("food_entries_kind_slug_key").on(t.kind,t.slug), + check("food_entries_published_pointer_check",sql`(${t.publishedRevisionId} IS NULL) = (${t.publishedAt} IS NULL)`) +]); +export const foodRevisions=pgTable("food_revisions",{ + id:text("id").primaryKey().default(sql`gen_random_uuid()::text`), + entryId:text("entry_id").notNull(),version:integer("version").notNull(), + content:jsonb("content").$type>().notNull(), + digest:text("digest").notNull(),authorId:text("author_id").notNull(), + approved:boolean("approved").notNull().default(false), + reviewedBy:text("reviewed_by"),reviewedAt:timestamp("reviewed_at",{withTimezone:true}), + createdAt:clock(), +},(t)=>[unique("food_revisions_entry_version_key").on(t.entryId,t.version), + unique("food_revisions_entry_id_key").on(t.entryId,t.id)]); +export const foodSources=pgTable("food_sources",{ + id:text("id").primaryKey().default(sql`gen_random_uuid()::text`), + url:text("url").notNull().unique(), title:text("title").notNull().default(""), + publisher:text("publisher").notNull().default(""), + retrievedAt:timestamp("retrieved_at",{withTimezone:true}),createdAt:clock(), +}); +export const foodEntrySources=pgTable("food_entry_sources",{ + revisionId:text("revision_id").notNull(),sourceId:text("source_id").notNull(), + sectionId:text("section_id").notNull().default(""), +}); +export const foodAliases=pgTable("food_aliases",{ + entryId:text("entry_id").notNull(),alias:text("alias").notNull(), + normalized:text("normalized").notNull(), +}); +export const foodRelations=pgTable("food_relations",{ + entryId:text("entry_id").notNull(),relatedEntryId:text("related_entry_id").notNull(), + relation:text("relation").notNull().default("related"), +}); +export const foodMedia=pgTable("food_media",{ + id:text("id").primaryKey().default(sql`gen_random_uuid()::text`), + entryId:text("entry_id").notNull(),path:text("path").notNull(),altText:text("alt_text").notNull(), + license:text("license").notNull().default("pending"), + attribution:text("attribution").notNull().default(""), + rightsApproved:boolean("rights_approved").notNull().default(false), + verifiedBy:text("verified_by"),verifiedAt:timestamp("verified_at",{withTimezone:true}),createdAt:clock(), +}); +export const foodEditorialEvents=pgTable("food_editorial_events",{ + id:text("id").primaryKey().default(sql`gen_random_uuid()::text`), + entryId:text("entry_id").notNull(),revisionId:text("revision_id"), + action:text("action").notNull(),actorId:text("actor_id").notNull(), + details:jsonb("details").$type>().notNull().default({}),createdAt:clock(), +},(t)=>[index("food_editorial_events_entry_idx").on(t.entryId,t.createdAt)]); +export const foodRedirects=pgTable("food_redirects",{ + kind:text("kind").notNull(),oldSlug:text("old_slug").notNull(),entryId:text("entry_id").notNull(), +}); diff --git a/src/db/schema/index.ts b/src/db/schema/index.ts index f05e512f..4a1d86ba 100644 --- a/src/db/schema/index.ts +++ b/src/db/schema/index.ts @@ -33,3 +33,5 @@ export * from "./hospitality"; export * from "./crm"; export * from "./tiffin"; + +export * from "./food-encyclopedia"; From 209f503b64960373ced06f1aa1829081cbc402cf Mon Sep 17 00:00:00 2001 From: "Sameer .I. Siddiqui" Date: Sun, 22 Nov 2026 23:42:59 +0530 Subject: [PATCH 03/15] feat(encyclopedia): secure reviewed publishing gateway and public-only SQL projection --- .../0117_food_encyclopedia_editorial.sql | 341 ++++++++++++++++++ .../food-encyclopedia/editorial-service.ts | 72 ++++ 2 files changed, 413 insertions(+) create mode 100644 src/modules/food-encyclopedia/editorial-service.ts diff --git a/src/db/migrations/0117_food_encyclopedia_editorial.sql b/src/db/migrations/0117_food_encyclopedia_editorial.sql index 2dc481d3..063685e3 100644 --- a/src/db/migrations/0117_food_encyclopedia_editorial.sql +++ b/src/db/migrations/0117_food_encyclopedia_editorial.sql @@ -128,3 +128,344 @@ DO $block$ DECLARE t text; BEGIN EXECUTE format('CREATE POLICY food_owner_only ON %I FOR ALL TO menuminute_owner USING (true) WITH CHECK (true)',t); END LOOP; END $block$; + +-- Approved media identity is entry+path, never a generic merchant upload. +CREATE UNIQUE INDEX food_media_entry_path_key ON food_media(entry_id,path); + +-- The whitelisted public projection never includes draft notes, editor history, +-- candidate imports, privileged event metadata or unreviewed revisions. +CREATE FUNCTION app_private.food_public_payload(p_entry food_entries,p_revision food_revisions) +RETURNS jsonb LANGUAGE sql STABLE SECURITY DEFINER +SET search_path=pg_catalog,public,pg_temp AS $payload$ + SELECT jsonb_build_object( + 'id',p_entry.id,'kind',p_entry.kind,'slug',p_entry.slug, + 'title',p_revision.content->>'title', + 'eyebrow',p_revision.content->>'eyebrow', + 'description',p_revision.content->>'description', + 'tint',p_revision.content->>'tint', + 'imagePath',p_revision.content->>'imagePath', + 'imageAlt',p_revision.content->>'imageAlt', + 'aliases',coalesce(p_revision.content->'aliases','[]'::jsonb), + 'facts',coalesce(p_revision.content->'facts','[]'::jsonb), + 'sections',coalesce(p_revision.content->'sections','[]'::jsonb), + 'relatedSlugs',coalesce(p_revision.content->'relatedSlugs','[]'::jsonb), + 'caution',p_revision.content->>'caution', + 'sourceUrls',coalesce(p_revision.content->'sourceUrls','[]'::jsonb), + 'status','published', + 'reviewedBy',(SELECT u.name FROM users u WHERE u.id=p_revision.reviewed_by), + 'reviewedAt',p_revision.reviewed_at, + 'publishedAt',p_entry.published_at + ); +$payload$; +REVOKE ALL ON FUNCTION app_private.food_public_payload(food_entries,food_revisions) + FROM PUBLIC,menuminute_app,menuminute_worker; + +CREATE FUNCTION app_private.food_public_entry(p_kind text,p_slug text) +RETURNS jsonb LANGUAGE sql STABLE SECURITY DEFINER +SET search_path=pg_catalog,public,pg_temp AS $entry$ + SELECT app_private.food_public_payload(e,r) + FROM food_entries e JOIN food_revisions r + ON r.entry_id=e.id AND r.id=e.published_revision_id + WHERE e.kind=p_kind AND e.slug=p_slug + AND e.published_at IS NOT NULL AND r.approved + AND r.reviewed_at IS NOT NULL AND r.reviewed_by IS NOT NULL + LIMIT 1; +$entry$; +REVOKE ALL ON FUNCTION app_private.food_public_entry(text,text) FROM PUBLIC; +GRANT EXECUTE ON FUNCTION app_private.food_public_entry(text,text) TO menuminute_app; + +-- Bounded search across reviewed publication only; drafts and archived revisions never leak. +CREATE FUNCTION app_private.food_public_list(p_kind text,p_query text,p_limit integer) +RETURNS TABLE(entry jsonb) LANGUAGE sql STABLE SECURITY DEFINER +SET search_path=pg_catalog,public,pg_temp AS $list$ + SELECT app_private.food_public_payload(e,r) AS entry + FROM food_entries e JOIN food_revisions r + ON r.entry_id=e.id AND r.id=e.published_revision_id + WHERE e.published_at IS NOT NULL AND r.approved + AND r.reviewed_by IS NOT NULL AND r.reviewed_at IS NOT NULL + AND (p_kind IS NULL OR p_kind='' OR e.kind=p_kind) + AND (p_query IS NULL OR btrim(p_query)='' OR + to_tsvector('simple',e.search_text) @@ plainto_tsquery('simple',left(p_query,100)) + OR e.search_text ILIKE ('%' || replace(replace(left(p_query,100),'%','\\%'),'_','\\_') || '%') ESCAPE '\\' + ) + ORDER BY e.published_at DESC,e.id + LIMIT GREATEST(0,LEAST(coalesce(p_limit,30),100)); +$list$; +REVOKE ALL ON FUNCTION app_private.food_public_list(text,text,integer) FROM PUBLIC; +GRANT EXECUTE ON FUNCTION app_private.food_public_list(text,text,integer) TO menuminute_app; + +CREATE FUNCTION app_private.food_public_redirect(p_kind text,p_slug text) +RETURNS text LANGUAGE sql STABLE SECURITY DEFINER +SET search_path=pg_catalog,public,pg_temp AS $redirect$ + SELECT e.slug FROM food_redirects d JOIN food_entries e ON e.id=d.entry_id + WHERE d.kind=p_kind AND d.old_slug=p_slug AND e.published_revision_id IS NOT NULL + LIMIT 1; +$redirect$; +REVOKE ALL ON FUNCTION app_private.food_public_redirect(text,text) FROM PUBLIC; +GRANT EXECUTE ON FUNCTION app_private.food_public_redirect(text,text) TO menuminute_app; + +CREATE FUNCTION app_private.food_editorial_list(p_query text,p_status text,p_limit integer) +RETURNS TABLE(item jsonb) LANGUAGE plpgsql STABLE SECURITY DEFINER +SET search_path=pg_catalog,public,pg_temp AS $list$ +BEGIN + IF NOT app_private.is_super_admin(NULLIF(current_setting('app.actor_id',true),'')) + THEN RAISE EXCEPTION 'Unauthorized editorial access' USING ERRCODE='42501'; END IF; + RETURN QUERY + SELECT jsonb_build_object( + 'id',e.id,'kind',e.kind,'slug',e.slug, + 'title',coalesce(r.content->>'title',e.slug),'status',e.status, + 'version',e.version,'createdAt',e.created_at,'updatedAt',e.updated_at, + 'hasPublishedVersion',e.published_revision_id IS NOT NULL,'publishedAt',e.published_at + ) + FROM food_entries e + LEFT JOIN food_revisions r ON r.id=coalesce(e.draft_revision_id,e.published_revision_id) + WHERE (p_status IS NULL OR p_status='' OR e.status=p_status) + AND (p_query IS NULL OR btrim(p_query)='' OR e.slug ILIKE '%'||left(p_query,100)||'%' + OR r.content->>'title' ILIKE '%'||left(p_query,100)||'%') + ORDER BY e.updated_at DESC,e.id + LIMIT GREATEST(1,LEAST(coalesce(p_limit,80),100)); +END; +$list$; +REVOKE ALL ON FUNCTION app_private.food_editorial_list(text,text,integer) FROM PUBLIC; +GRANT EXECUTE ON FUNCTION app_private.food_editorial_list(text,text,integer) TO menuminute_app; + +CREATE FUNCTION app_private.food_editorial_detail(p_id text) +RETURNS jsonb LANGUAGE plpgsql STABLE SECURITY DEFINER +SET search_path=pg_catalog,public,pg_temp AS $detail$ +DECLARE e food_entries%ROWTYPE; +BEGIN + IF NOT app_private.is_super_admin(NULLIF(current_setting('app.actor_id',true),'')) + THEN RAISE EXCEPTION 'Unauthorized editorial access' USING ERRCODE='42501'; END IF; + SELECT * INTO e FROM food_entries WHERE id=p_id; + IF NOT FOUND THEN RETURN NULL; END IF; + RETURN jsonb_build_object( + 'id',e.id,'kind',e.kind,'slug',e.slug, + 'title',coalesce((SELECT content->>'title' FROM food_revisions WHERE id=e.draft_revision_id),e.slug), + 'status',e.status,'version',e.version, + 'createdAt',e.created_at,'updatedAt',e.updated_at, + 'hasPublishedVersion',e.published_revision_id IS NOT NULL,'publishedAt',e.published_at, + 'draftRevisionId',e.draft_revision_id,'reviewRevisionId',e.review_revision_id, + 'approvedRevisionId',e.approved_revision_id,'publishedRevisionId',e.published_revision_id, + 'draft',(SELECT r.content FROM food_revisions r WHERE r.id=e.draft_revision_id), + 'versions',coalesce((SELECT jsonb_agg(jsonb_build_object( + 'id',r.id,'version',r.version,'authorId',r.author_id,'reviewedBy',r.reviewed_by, + 'reviewedAt',r.reviewed_at,'createdAt',r.created_at,'approved',r.approved + ) ORDER BY r.version DESC) + FROM food_revisions r WHERE r.entry_id=e.id),'[]'::jsonb), + 'events',coalesce((SELECT jsonb_agg(jsonb_build_object( + 'action',v.action,'actorId',v.actor_id,'createdAt',v.created_at, + 'revisionId',v.revision_id + ) ORDER BY v.created_at DESC) + FROM (SELECT * FROM food_editorial_events WHERE entry_id=e.id + ORDER BY created_at DESC LIMIT 30) v),'[]'::jsonb) + ); +END; +$detail$; +REVOKE ALL ON FUNCTION app_private.food_editorial_detail(text) FROM PUBLIC; +GRANT EXECUTE ON FUNCTION app_private.food_editorial_detail(text) TO menuminute_app; + +-- One entrypoint for editorial mutations. Each request is recorded once; +-- the same idempotency key returns the same receipt without consuming a second TOTP. +CREATE FUNCTION app_private.food_editorial_command( + p_action text,p_target text,p_data jsonb,p_key text +) RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER +SET search_path=pg_catalog,public,pg_temp AS $command$ +DECLARE + actor text := nullif(current_setting('app.actor_id',true),''); + session_id text := nullif(current_setting('app.session_id',true),''); + existing admin_command_receipts%ROWTYPE; + e food_entries%ROWTYPE; + r food_revisions%ROWTYPE; + rev_id text; + payload jsonb; + result jsonb := '{}'::jsonb; + content_digest text; + source_count integer; + s text; + target_revision text; + affected integer; + reason text; +BEGIN + IF actor IS NULL OR session_id IS NULL OR NOT app_private.is_super_admin(actor) + OR p_action NOT IN ('create','save','submit','approve','publish','unpublish','restore','media.approve','import') + OR p_key IS NULL OR p_key !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR p_target IS NULL OR length(p_target) NOT BETWEEN 1 AND 100 + OR p_data IS NULL OR jsonb_typeof(p_data)<>'object' + THEN RAISE EXCEPTION 'Invalid or unauthorized editorial command' USING ERRCODE='42501'; END IF; + + PERFORM pg_advisory_xact_lock(hashtextextended(actor||':'||p_key,0)); + SELECT * INTO existing FROM admin_command_receipts + WHERE actor_id=actor AND request_key=p_key; + IF FOUND THEN + IF existing.action<>'food.'||p_action OR existing.target_id<>p_target OR existing.payload<>p_data + THEN RAISE EXCEPTION 'Editorial idempotency conflict' USING ERRCODE='23505'; END IF; + RETURN existing.result; + END IF; + + IF NOT app_private.require_step_up() + THEN RAISE EXCEPTION 'Verify a privileged session at /account/security' USING ERRCODE='42501'; END IF; + + IF p_action IN ('create','save','import') THEN + payload := p_data->'content'; + IF jsonb_typeof(payload)<>'object' OR payload->>'kind' NOT IN ('dishes','ingredients','cuisines','terms','compare') + OR coalesce(payload->>'slug','') !~ '^[a-z0-9]+(-[a-z0-9]+)*$' + OR length(payload->>'slug')>90 + OR length(btrim(coalesce(payload->>'title',''))) NOT BETWEEN 3 AND 100 + OR length(btrim(coalesce(payload->>'description',''))) NOT BETWEEN 35 AND 320 + OR jsonb_typeof(payload->'sections')<>'array' + OR jsonb_array_length(payload->'sections') NOT BETWEEN 2 AND 12 + OR jsonb_typeof(payload->'sourceUrls')<>'array' + OR jsonb_array_length(payload->'sourceUrls')>20 + OR jsonb_typeof(payload->'facts')<>'array' + OR jsonb_array_length(payload->'facts') NOT BETWEEN 2 AND 8 + OR length(payload::text)>28000 + THEN RAISE EXCEPTION 'Invalid editorial content fields' USING ERRCODE='22023'; END IF; + IF EXISTS(SELECT 1 FROM jsonb_array_elements_text(payload->'sourceUrls') AS source(url) + WHERE url !~ '^https://' OR length(url)>1000) + THEN RAISE EXCEPTION 'Only HTTPS editorial sources are permitted' USING ERRCODE='22023'; END IF; + IF p_action IN ('create','import') THEN + IF p_target<>'new' THEN RAISE EXCEPTION 'Creation must target new' USING ERRCODE='22023'; END IF; + INSERT INTO food_entries(kind,slug,created_by,updated_by) + VALUES(payload->>'kind',payload->>'slug',actor,actor) RETURNING * INTO e; + ELSE + SELECT * INTO e FROM food_entries WHERE id=p_target FOR UPDATE; + IF NOT FOUND THEN RAISE EXCEPTION 'Unknown food entry' USING ERRCODE='22023'; END IF; + IF (p_data->>'expectedVersion')::int IS DISTINCT FROM e.version + OR e.kind<>payload->>'kind' OR e.slug<>payload->>'slug' + THEN RAISE EXCEPTION 'Concurrent editorial revision or canonical identity change' USING ERRCODE='40001'; END IF; + END IF; + content_digest := encode(sha256(convert_to(payload::text,'UTF8')),'hex'); + INSERT INTO food_revisions(entry_id,version,content,digest,author_id) + VALUES(e.id,e.version+1,payload,content_digest,actor) RETURNING id INTO rev_id; + UPDATE food_entries SET version=version+1, status='draft',draft_revision_id=rev_id, + review_revision_id=NULL,approved_revision_id=NULL,updated_by=actor,updated_at=clock_timestamp() + WHERE id=e.id; + INSERT INTO food_sources(url) + SELECT DISTINCT source.url FROM jsonb_array_elements_text(payload->'sourceUrls') source(url) + ON CONFLICT(url) DO NOTHING; + INSERT INTO food_entry_sources(revision_id,source_id) + SELECT rev_id, s.id FROM food_sources s + JOIN jsonb_array_elements_text(payload->'sourceUrls') source(url) ON source.url=s.url + ON CONFLICT DO NOTHING; + IF payload->>'imagePath' IS NOT NULL THEN + INSERT INTO food_media(entry_id,path,alt_text) + VALUES(e.id,payload->>'imagePath',payload->>'imageAlt') + ON CONFLICT(entry_id,path) DO NOTHING; + END IF; + result:=jsonb_build_object('id',e.id,'revisionId',rev_id, + 'version',e.version+1,'status','draft','digest',content_digest); + ELSIF p_action='media.approve' THEN + SELECT * INTO e FROM food_entries WHERE id=p_target FOR UPDATE; + IF NOT FOUND OR p_data->>'path' IS NULL + OR length(coalesce(p_data->>'attribution',''))>240 + OR p_data->>'license' NOT IN ('owned','commissioned','cc0','cc-by','licensed') + THEN RAISE EXCEPTION 'Invalid media verification' USING ERRCODE='22023'; END IF; + UPDATE food_media SET rights_approved=true,license=p_data->>'license', + attribution=coalesce(p_data->>'attribution',''), + verified_by=actor,verified_at=clock_timestamp() + WHERE entry_id=e.id AND path=p_data->>'path' AND rights_approved=false; + GET DIAGNOSTICS affected=ROW_COUNT; + IF affected<>1 THEN RAISE EXCEPTION 'Media not found or already verified' USING ERRCODE='22023'; END IF; + result:=jsonb_build_object('id',e.id,'mediaApproved',true); + ELSE + SELECT * INTO e FROM food_entries WHERE id=p_target FOR UPDATE; + IF NOT FOUND THEN RAISE EXCEPTION 'Unknown food entry' USING ERRCODE='22023'; END IF; + IF (p_data->>'expectedVersion')::int IS DISTINCT FROM e.version THEN + RAISE EXCEPTION 'Concurrent editorial revision' USING ERRCODE='40001'; END IF; + IF p_action='submit' THEN + IF e.status<>'draft' OR e.draft_revision_id IS NULL + THEN RAISE EXCEPTION 'Only current drafts may be submitted' USING ERRCODE='22023'; END IF; + SELECT * INTO r FROM food_revisions WHERE id=e.draft_revision_id; + SELECT count(DISTINCT source_id) INTO source_count + FROM food_entry_sources WHERE revision_id=r.id; + IF source_count<2 OR length(r.content::text)<950 + THEN RAISE EXCEPTION 'Article needs substantive researched content and two references' USING ERRCODE='22023'; END IF; + UPDATE food_entries SET status='in_review',review_revision_id=r.id, + updated_by=actor,updated_at=clock_timestamp() WHERE id=e.id; + rev_id:=r.id; + result:=jsonb_build_object('id',e.id,'status','in_review'); + ELSIF p_action='approve' THEN + IF e.status<>'in_review' OR e.review_revision_id IS NULL + THEN RAISE EXCEPTION 'A submitted revision is required' USING ERRCODE='22023'; END IF; + SELECT * INTO r FROM food_revisions WHERE id=e.review_revision_id FOR UPDATE; + IF r.author_id=actor THEN + RAISE EXCEPTION 'A separate reviewer must approve authored content' USING ERRCODE='42501'; END IF; + SELECT count(DISTINCT source_id) INTO source_count + FROM food_entry_sources WHERE revision_id=r.id; + IF source_count<2 THEN RAISE EXCEPTION 'Two sources required' USING ERRCODE='22023'; END IF; + IF r.content->>'imagePath' IS NOT NULL AND NOT EXISTS( + SELECT 1 FROM food_media m WHERE m.entry_id=e.id AND m.path=r.content->>'imagePath' + AND m.rights_approved AND m.verified_by IS NOT NULL + ) THEN RAISE EXCEPTION 'Artwork rights verification required' USING ERRCODE='22023'; END IF; + UPDATE food_revisions SET approved=true,reviewed_by=actor,reviewed_at=clock_timestamp() + WHERE id=r.id AND NOT approved; + IF NOT FOUND THEN RAISE EXCEPTION 'Revision already approved' USING ERRCODE='22023'; END IF; + UPDATE food_entries SET status='approved',approved_revision_id=r.id, + updated_by=actor,updated_at=clock_timestamp() WHERE id=e.id; + rev_id:=r.id; + result:=jsonb_build_object('id',e.id,'status','approved'); + ELSIF p_action='publish' THEN + IF e.status<>'approved' OR e.approved_revision_id IS NULL + THEN RAISE EXCEPTION 'Only an independently approved revision can publish' USING ERRCODE='22023'; END IF; + SELECT * INTO r FROM food_revisions WHERE id=e.approved_revision_id AND entry_id=e.id; + IF NOT FOUND OR NOT r.approved OR r.reviewed_by IS NULL + OR r.reviewed_at IS NULL OR r.reviewed_by=r.author_id + THEN RAISE EXCEPTION 'Invalid reviewed content' USING ERRCODE='42501'; END IF; + UPDATE food_entries SET published_revision_id=r.id,published_at=clock_timestamp(), + status='published',search_text=coalesce(r.content->>'title','')||' '|| + coalesce(r.content->>'description','')||' '||coalesce(r.content->>'slug','')||' '|| + coalesce((SELECT string_agg(value,' ') FROM jsonb_array_elements_text(r.content->'aliases')),''), + updated_by=actor,updated_at=clock_timestamp() WHERE id=e.id; + DELETE FROM food_aliases WHERE entry_id=e.id; + INSERT INTO food_aliases(entry_id,alias,normalized) + SELECT DISTINCT ON (lower(btrim(alias))) e.id,alias,lower(btrim(alias)) + FROM jsonb_array_elements_text(r.content->'aliases') x(alias) + WHERE length(btrim(alias)) BETWEEN 2 AND 90 + ORDER BY lower(btrim(alias)),alias; + DELETE FROM food_relations WHERE entry_id=e.id; + INSERT INTO food_relations(entry_id,related_entry_id,relation) + SELECT e.id,target.id,'related' + FROM food_entries target + JOIN jsonb_array_elements_text(r.content->'relatedSlugs') related(slug) + ON target.slug=related.slug AND target.id<>e.id + WHERE target.published_revision_id IS NOT NULL + ON CONFLICT DO NOTHING; + rev_id:=r.id; + result:=jsonb_build_object('id',e.id,'status','published','revisionId',rev_id); + ELSIF p_action='unpublish' THEN + IF e.published_revision_id IS NULL THEN + RAISE EXCEPTION 'Entry is not published' USING ERRCODE='22023'; END IF; + rev_id:=e.published_revision_id; + UPDATE food_entries SET published_revision_id=NULL,published_at=NULL, + status='archived',search_text='',updated_by=actor,updated_at=clock_timestamp() + WHERE id=e.id; + DELETE FROM food_aliases WHERE entry_id=e.id; + result:=jsonb_build_object('id',e.id,'status','archived'); + ELSIF p_action='restore' THEN + target_revision:=p_data->>'revisionId'; + SELECT * INTO r FROM food_revisions WHERE id=target_revision AND entry_id=e.id; + IF NOT FOUND OR NOT r.approved OR r.reviewed_by IS NULL OR r.reviewed_at IS NULL + THEN RAISE EXCEPTION 'Only a previously approved revision can be restored' USING ERRCODE='22023'; END IF; + UPDATE food_entries SET published_revision_id=r.id,published_at=clock_timestamp(), + status='published',search_text=coalesce(r.content->>'title','')||' '|| + coalesce(r.content->>'description','')||' '||coalesce(r.content->>'slug',''), + updated_by=actor,updated_at=clock_timestamp() WHERE id=e.id; + rev_id:=r.id; + result:=jsonb_build_object('id',e.id,'status','published','revisionId',rev_id); + END IF; + END IF; + + INSERT INTO food_editorial_events(entry_id,revision_id,action,actor_id,details) + VALUES(e.id,rev_id,p_action,actor,p_data - 'content'); + INSERT INTO admin_audit_logs(id,actor_id,actor_email,action,target_type,target_id,details) + VALUES(gen_random_uuid()::text,actor, + (SELECT u.email FROM users u WHERE u.id=actor), + 'food.'||p_action,'food_entry',e.id, + jsonb_build_object('revisionId',rev_id,'requestKey',p_key)); + INSERT INTO admin_command_receipts(actor_id,request_key,action,target_id,payload,result) + VALUES(actor,p_key,'food.'||p_action,p_target,p_data,result); + RETURN result; +END; +$command$; +REVOKE ALL ON FUNCTION app_private.food_editorial_command(text,text,jsonb,text) FROM PUBLIC; +GRANT EXECUTE ON FUNCTION app_private.food_editorial_command(text,text,jsonb,text) TO menuminute_app; diff --git a/src/modules/food-encyclopedia/editorial-service.ts b/src/modules/food-encyclopedia/editorial-service.ts new file mode 100644 index 00000000..871a7b1f --- /dev/null +++ b/src/modules/food-encyclopedia/editorial-service.ts @@ -0,0 +1,72 @@ +import { getPool } from "@/db"; +import { withActor } from "@/modules/tenancy/service"; +import { sql } from "drizzle-orm"; +import type { AdminActor } from "@/lib/admin-guard"; +import { FoodDraftSchema, type FoodDraft, type FoodEditorialDetail, type FoodEditorialRow, type FoodEditorialAction } from "./editorial-contracts"; +import { type FoodEntry, FoodEntrySchema, type FoodKind } from "./contracts"; + +function parseFoodRow(value: unknown): FoodEntry | null { + const result = FoodEntrySchema.safeParse(value); + return result.success && result.data.status === "published" ? result.data : null; +} +/** Queries read only a vetted projection of approved and published revisions. */ +export async function getPublishedFoodEntry(kind: FoodKind, slug: string): Promise { + try { + const r = await getPool().query<{ entry: unknown }>( + "SELECT app_private.food_public_entry($1,$2) AS entry", [kind, slug] + ); + return parseFoodRow(r.rows[0]?.entry); + } catch { + // During additive deployments, a missing migration must fail closed rather + // than exposing drafts, throwing a site-wide 500, or claiming published content. + return null; + } +} +export async function listPublishedFood(kind?: FoodKind, query?: string, limit = 40): Promise { + try { + const r = await getPool().query<{ entry: unknown }>( + "SELECT entry FROM app_private.food_public_list($1,$2,$3)", + [kind ?? null, (query ?? "").trim().slice(0, 100), Math.min(100,Math.max(1,limit))] + ); + return r.rows.flatMap(({ entry }) => { const parsed = parseFoodRow(entry); return parsed ? [parsed] : []; }); + } catch { return []; } +} +export async function getPublicFoodRedirect(kind: FoodKind, slug: string): Promise { + try { + const r = await getPool().query<{ slug: string | null }>( + "SELECT app_private.food_public_redirect($1,$2) AS slug", [kind,slug]); + return r.rows[0]?.slug ?? null; + } catch { return null; } +} +export async function listEditorialEntries(actor: AdminActor, query = "", status = ""): Promise { + return withActor({ userId: actor.id, sessionId: actor.sessionId }, async tx => { + const result = await tx.execute<{ item: FoodEditorialRow }>( + sql`SELECT item FROM app_private.food_editorial_list(${query.slice(0,100)},${status},80)` + ); + return result.rows.map(row => row.item); + }); +} +export async function getEditorialDetail(actor: AdminActor, id: string): Promise { + return withActor({ userId: actor.id, sessionId: actor.sessionId }, async tx => { + const result = await tx.execute<{ detail: FoodEditorialDetail | null }>( + sql`SELECT app_private.food_editorial_detail(${id}) AS detail` + ); + return result.rows[0]?.detail ?? null; + }); +} +export type EditorialCommandReceipt = { id: string; status?: string; revisionId?: string; version?: number; digest?: string }; +export async function runEditorialCommand(actor: AdminActor, action: FoodEditorialAction | "media.approve" | "import", targetId: string, + data: { content?: FoodDraft; expectedVersion?: number; revisionId?: string; license?: string; attribution?: string; path?: string }, + requestKey: string = crypto.randomUUID()): Promise { + if (!actor.sessionId) throw new Error("A live authenticated administrative session is required"); + const payload = { ...data, ...(data.content ? { content: FoodDraftSchema.parse(data.content) } : {}) }; + return withActor({ userId: actor.id, sessionId: actor.sessionId }, async tx => { + const result = await tx.execute<{ result: EditorialCommandReceipt }>( + sql`SELECT app_private.food_editorial_command( + ${action},${targetId},${JSON.stringify(payload)}::jsonb,${requestKey} + ) AS result` + ); + if (!result.rows[0]) throw new Error("No editorial command receipt"); + return result.rows[0].result; + }); +} From dc5cedc50fc0de3f578e4e864da5f75ca0d14109 Mon Sep 17 00:00:00 2001 From: "Sameer .I. Siddiqui" Date: Sun, 22 Nov 2026 23:43:56 +0530 Subject: [PATCH 04/15] feat(encyclopedia): add restricted Atlas editorial dashboard and server actions --- src/app/admin/admin-nav.tsx | 2 + src/app/admin/encyclopedia/[id]/page.tsx | 16 +++++ src/app/admin/encyclopedia/actions.ts | 54 ++++++++++++++++ src/app/admin/encyclopedia/new/page.tsx | 9 +++ src/app/admin/encyclopedia/page.tsx | 62 +++++++++++++++++++ .../food-encyclopedia/editorial-template.ts | 17 +++++ 6 files changed, 160 insertions(+) create mode 100644 src/app/admin/encyclopedia/[id]/page.tsx create mode 100644 src/app/admin/encyclopedia/actions.ts create mode 100644 src/app/admin/encyclopedia/new/page.tsx create mode 100644 src/app/admin/encyclopedia/page.tsx create mode 100644 src/modules/food-encyclopedia/editorial-template.ts 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..523e738c --- /dev/null +++ b/src/app/admin/encyclopedia/[id]/page.tsx @@ -0,0 +1,16 @@ +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..84fdac4d --- /dev/null +++ b/src/app/admin/encyclopedia/actions.ts @@ -0,0 +1,54 @@ +"use server"; + +import { revalidatePath } from "next/cache"; +import { z } from "zod"; +import { verifySuperAdmin } from "@/lib/admin-guard"; +import { + FoodDraftSchema, FoodEditorialActionSchema, type FoodDraft, +} 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/new/page.tsx b/src/app/admin/encyclopedia/new/page.tsx new file mode 100644 index 00000000..f120bb66 --- /dev/null +++ b/src/app/admin/encyclopedia/new/page.tsx @@ -0,0 +1,9 @@ +import type { Metadata } from "next"; +import { verifySuperAdmin } from "@/lib/admin-guard"; +import { EditorialEditor } from "../editor"; +import { newEditorialDraft } from "@/modules/food-encyclopedia/editorial-template"; +export const metadata:Metadata={title:"New food guide | Editorial Studio",robots:{index:false}}; +export default async function NewFoodGuidePage(){ + await verifySuperAdmin(); + return ; +} diff --git a/src/app/admin/encyclopedia/page.tsx b/src/app/admin/encyclopedia/page.tsx new file mode 100644 index 00000000..fecfa0cc --- /dev/null +++ b/src/app/admin/encyclopedia/page.tsx @@ -0,0 +1,62 @@ +import type { Metadata } from "next"; +import Link from "next/link"; +import { BookOpenText, Plus, ArrowRight, Search, LockKeyhole } from "lucide-react"; +import { verifySuperAdmin } from "@/lib/admin-guard"; +import { listEditorialEntries } from "@/modules/food-encyclopedia/editorial-service"; + +export const dynamic="force-dynamic"; +export const metadata:Metadata={title:"Food Encyclopedia | Editorial Studio",robots:{index:false,follow:false}}; +export default async function EditorialDashboard({searchParams}:{searchParams:Promise<{q?:string;status?:string}>}){ + const actor=await verifySuperAdmin(); + const p=await searchParams; + let entries:Awaited>=[]; + let available=true; + try{entries=await listEditorialEntries(actor,p.q??"",p.status??"");}catch{available=false} + return
+
+
+

The Atlas / Editorial control

+

Food Encyclopedia Studio

+

+ Research, review and publish immutable food guides. No recipe or AI suggestion is automatically indexable. +

+
+ New guide +
+
+ {[["Drafts",entries.filter(x=>x.status==="draft").length],["Awaiting review",entries.filter(x=>x.status==="in_review").length],["Published",entries.filter(x=>x.hasPublishedVersion).length]].map(([label,count])=> +
+

{label}

{count}

+
)} +
+
+
Protected publishing
+

Changes require a verified administrative step-up. Authors cannot approve their own revisions. Review at least two credible sources and any artwork licenses before publishing.

+
+
+ + + +
+ {!available?

Editorial database is not installed or currently unavailable. Public menu operations are unaffected; an operator must review migration 0117 after migration 0115/0116.

+ :entries.length===0?
+

The library starts here.

Create the first researched draft or import a catalogue candidate for review.

+ Create a draft +
:
+ + {["Guide","Type","Stage","Version","Published","Action"].map(h=>)} + {entries.map(e=> + + + + + )}
{h}
{e.title}
/{e.slug}
{e.kind}{e.status.replace("_"," ")}{e.version}{e.hasPublishedVersion?"Yes":"No"}Open
+
} +
; +} diff --git a/src/modules/food-encyclopedia/editorial-template.ts b/src/modules/food-encyclopedia/editorial-template.ts new file mode 100644 index 00000000..0dfa734d --- /dev/null +++ b/src/modules/food-encyclopedia/editorial-template.ts @@ -0,0 +1,17 @@ +import type { FoodDraft } from "./editorial-contracts"; +export function newEditorialDraft(kind:FoodDraft["kind"]="dishes",slug="new-guide"):FoodDraft { + return { + kind,slug,title:"New food guide",eyebrow:"FOOD ATLAS / EDITORIAL", + description:"A concise explanation of this food, including the context that readers should know before they order or prepare it.", + tint:"cream",aliases:[],facts:[ + {label:"Category",value:"To be researched"}, + {label:"Tradition",value:"To be researched"}, + ], + sections:[ + {id:"introduction",eyebrow:"01 / DEFINITION",title:"What is this food?",body:["Introduce the dish or ingredient with independently researched facts and enough detail to help a reader understand its significance."]}, + {id:"background",eyebrow:"02 / BACKGROUND",title:"Ingredients, tastes and variations",body:["Explain the typical ingredients, preparation differences and cultural context. Note important exceptions and avoid implying safety for individual restaurant servings."]}, + ], + sourceUrls:[],relatedSlugs:[], + caution:"Preparations and food handling vary. Ask the restaurant for details about any allergy or dietary restriction.", + }; +} From 4c5c2714558a7bcc6985b1c03e079d56091e8266 Mon Sep 17 00:00:00 2001 From: "Sameer .I. Siddiqui" Date: Sun, 22 Nov 2026 23:45:13 +0530 Subject: [PATCH 05/15] feat(encyclopedia): polish Atlas Editorial Studio with source review, artwork rights and revision UX --- src/app/admin/encyclopedia/editor.tsx | 189 ++++++++++++++++++ .../food-encyclopedia/provenance.test.ts | 23 +++ src/modules/food-encyclopedia/provenance.ts | 20 ++ 3 files changed, 232 insertions(+) create mode 100644 src/app/admin/encyclopedia/editor.tsx create mode 100644 src/modules/food-encyclopedia/provenance.test.ts create mode 100644 src/modules/food-encyclopedia/provenance.ts diff --git a/src/app/admin/encyclopedia/editor.tsx b/src/app/admin/encyclopedia/editor.tsx new file mode 100644 index 00000000..be629858 --- /dev/null +++ b/src/app/admin/encyclopedia/editor.tsx @@ -0,0 +1,189 @@ +"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

+
+ + + + +