fix: SVA chapters

This commit is contained in:
gosangam
2026-05-02 17:45:32 +05:30
parent ae6a752787
commit 47a2dc375e
6 changed files with 869 additions and 505 deletions
+251 -167
View File
@@ -1,9 +1,10 @@
/**
* Data access layer for Songs of the Vaiṣṇava Ācāryas (SVA).
*
* Reads from MongoDB via Prisma, same as the rest of the app.
* SVA is a prose/song book with 4 parts (chapters) plus intro segments.
* We use volume=0 as the sentinel for "no volumes".
* Reads from MongoDB via Prisma.
* SVA is a song book with 4 parent parts, each containing multiple songs
* (sub-chapters). Each song is stored as its own prose_chapters document
* with slugs like "1-1", "1-2", "2-1", etc.
*
* When the DB isn't seeded yet, falls back to reading local JSON files
* from lib/jsons/books/sva/.
@@ -22,11 +23,11 @@ import path from "path";
// Constants
// ---------------------------------------------------------------------------
const BOOK = "sva";
/** Volume sentinel for books without volumes. */
const NO_VOLUME = 0;
const BOOK = "sva";
const SVA_JSON_DIR = path.join(process.cwd(), "lib", "jsons", "books", "sva");
// ---------------------------------------------------------------------------
@@ -37,15 +38,21 @@ export type SvaMeta = {
book: string;
title: string;
author: string;
year?: number;
year: number;
description: string;
totalChapters: number;
chapters: SvaChapterEntry[];
chapters: SvaParentChapter[];
};
export type SvaChapterEntry = {
export type SvaParentChapter = {
number: number;
title: string;
subChapters: SvaSubChapterEntry[];
};
export type SvaSubChapterEntry = {
slug: string; // "1-1", "1-2", etc.
title: string;
};
export type SvaIntroSegment = {
@@ -59,27 +66,29 @@ export type SvaIntroSegment = {
export type SvaChapter = {
book: string;
chapter: number | null;
chapter: string; // "1-1", "2-1", etc.
parentChapter: number;
subChapter: number;
title: string;
parentTitle: string;
type: string;
slug?: string;
paragraphs: string[];
};
/** Union type used in sidebar / table-of-contents navigation. */
export type SvaSidebarItem = {
/** URL-safe slug: "intro-front-pages", "intro-foreword", "1", "4" */
/** URL-safe slug: "intro-front-pages", "1-1", "parent-1", etc. */
slug: string;
/** Human-readable label for the sidebar */
label: string;
/** "intro-segment" | "chapter" */
/** "intro-segment" | "parent" | "sub-chapter" */
type: string;
/** Chapter number, or null for non-chapter items */
chapter: number | null;
/** Parent chapter number, or null for intro segments */
parentChapter: number | null;
};
// ---------------------------------------------------------------------------
// HTML sanitisation (mirrors lib/api.ts)
// HTML sanitisation
// ---------------------------------------------------------------------------
function sanitizeHtml(html: string): string {
@@ -148,13 +157,29 @@ function getLocalIntroSegment(rawSlug: string): SvaIntroSegment | null {
return readLocalJson<SvaIntroSegment>(filePath);
}
function getLocalChapter(chapterNum: number): SvaChapter | null {
const filePath = path.join(
SVA_JSON_DIR,
"chapters",
String(chapterNum).padStart(2, "0") + ".json",
);
return readLocalJson<SvaChapter>(filePath);
function getLocalSubChapter(slug: string): SvaChapter | null {
const filePath = path.join(SVA_JSON_DIR, "chapters", `${slug}.json`);
const raw = readLocalJson<{
book: string;
slug: string;
parentChapter: number;
subChapter: number;
title: string;
parentTitle: string;
type: string;
paragraphs: string[];
}>(filePath);
if (!raw) return null;
return {
book: raw.book,
chapter: raw.slug,
parentChapter: raw.parentChapter,
subChapter: raw.subChapter,
title: raw.title,
parentTitle: raw.parentTitle,
type: raw.type,
paragraphs: raw.paragraphs,
};
}
// ---------------------------------------------------------------------------
@@ -162,11 +187,15 @@ function getLocalChapter(chapterNum: number): SvaChapter | null {
// ---------------------------------------------------------------------------
/**
* Book-level metadata (title, author, chapter list, etc.)
* Book-level metadata (title, author, chapter list with sub-chapters, etc.)
*/
export async function getSvaMeta(): Promise<SvaMeta | null> {
const meta = await prisma.bookMeta.findUnique({ where: { book: BOOK } });
if (meta) return meta.data as unknown as SvaMeta;
try {
const meta = await prisma.bookMeta.findUnique({ where: { book: BOOK } });
if (meta) return meta.data as unknown as SvaMeta;
} catch {
// Prisma BSON decode error — fall through to local JSON
}
// Fallback to local JSON
const introPath = path.join(SVA_JSON_DIR, "intro.json");
@@ -181,20 +210,24 @@ export async function getSvaMeta(): Promise<SvaMeta | null> {
* All intro segments, ordered by their `order` field.
*/
export async function getSvaIntroSegments(): Promise<SvaIntroSegment[]> {
const results = await prisma.proseChapter.findMany({
where: { book: BOOK, volume: NO_VOLUME, type: "intro-segment" },
orderBy: { order: "asc" },
});
try {
const results = await prisma.proseChapter.findMany({
where: { book: BOOK, volume: NO_VOLUME, type: "intro-segment" },
orderBy: { order: "asc" },
});
if (results.length > 0) {
return results.map((doc) => ({
slug: doc.slug,
title: doc.title,
type: doc.type,
book: doc.book,
order: doc.order,
paragraphs: normalizeParagraphs(doc.paragraphs),
}));
if (results.length > 0) {
return results.map((doc) => ({
slug: doc.slug,
title: doc.title,
type: doc.type,
book: doc.book,
order: doc.order,
paragraphs: normalizeParagraphs(doc.paragraphs),
}));
}
} catch {
// Prisma BSON decode error — fall through to local JSON
}
// Fallback to local JSON
@@ -203,14 +236,16 @@ export async function getSvaIntroSegments(): Promise<SvaIntroSegment[]> {
/**
* A single intro segment by slug.
* Accepts both "intro-foreword" (URL slug) and "foreword" (raw slug).
* Accepts both "intro-front-pages" (URL slug) and "front-pages" (raw slug).
*/
export async function getSvaIntroSegment(
slug: string,
): Promise<SvaIntroSegment | null> {
// DB stores with "intro-" prefix; accept either form
const dbSlug = slug.startsWith("intro-") ? slug : `intro-${slug}`;
const rawSlug = slug.startsWith("intro-") ? slug.replace(/^intro-/, "") : slug;
const rawSlug = slug.startsWith("intro-")
? slug.replace(/^intro-/, "")
: slug;
const doc = await prisma.proseChapter.findUnique({
where: {
@@ -240,42 +275,54 @@ export async function getSvaIntroSegment(
}
// ---------------------------------------------------------------------------
// Chapters
// Chapters (sub-chapters like "1-1", "2-3", etc.)
// ---------------------------------------------------------------------------
/**
* A numbered chapter (1–4).
* A sub-chapter (song) by its slug (e.g. "1-1", "2-3").
*/
export async function getSvaChapter(
chapterNum: number,
): Promise<SvaChapter | null> {
if (chapterNum < 1 || chapterNum > 4 || !Number.isInteger(chapterNum)) {
return null;
}
const doc = await prisma.proseChapter.findUnique({
where: {
book_volume_slug: {
book: BOOK,
volume: NO_VOLUME,
slug: String(chapterNum),
export async function getSvaChapter(slug: string): Promise<SvaChapter | null> {
try {
const doc = await prisma.proseChapter.findUnique({
where: {
book_volume_slug: {
book: BOOK,
volume: NO_VOLUME,
slug,
},
},
},
});
});
if (doc) {
return {
book: doc.book,
chapter: doc.chapter,
title: doc.title,
type: doc.type,
slug: doc.slug,
paragraphs: normalizeParagraphs(doc.paragraphs),
};
if (doc) {
// Parse parentChapter and subChapter from slug "X-Y"
const parts = slug.split("-");
const parentChapter = parseInt(parts[0], 10);
const subChapter = parseInt(parts[1], 10);
// Derive parentTitle from meta if available
const meta = await getSvaMeta();
const parentEntry = meta?.chapters.find(
(ch) => ch.number === parentChapter,
);
const parentTitle = parentEntry?.title ?? "";
return {
book: doc.book,
chapter: slug,
parentChapter,
subChapter,
title: doc.title,
parentTitle,
type: doc.type,
paragraphs: normalizeParagraphs(doc.paragraphs),
};
}
} catch {
// Prisma BSON decode error — fall through to local JSON
}
// Fallback to local JSON
const local = getLocalChapter(chapterNum);
const local = getLocalSubChapter(slug);
if (!local) return null;
return {
...local,
@@ -290,10 +337,10 @@ export async function getSvaChapter(
/**
* Get content by URL slug.
*
* "intro-front-pages" → intro segment
* "intro-foreword" → intro segment
* "intro-introduction" → intro segment
* "1" … "4" → chapter (part)
* "intro-front-pages" → intro segment
* "intro-foreword" → intro segment
* "intro-introduction" → intro segment
* "1-1", "2-3", etc. → sub-chapter (song)
*/
export async function getSvaContent(
slug: string,
@@ -302,12 +349,8 @@ export async function getSvaContent(
return getSvaIntroSegment(slug);
}
const num = Number(slug);
if (!Number.isNaN(num) && Number.isInteger(num) && num >= 1 && num <= 4) {
return getSvaChapter(num);
}
return null;
// Sub-chapter slug like "1-1", "2-3"
return getSvaChapter(slug);
}
// ---------------------------------------------------------------------------
@@ -315,131 +358,172 @@ export async function getSvaContent(
// ---------------------------------------------------------------------------
/**
* Build the full sidebar navigation list.
* Build the full sidebar navigation list with hierarchical structure.
*
* Order: front-pages → foreword → introduction → parts 1–4
* Order: front-pages → foreword → introduction
* → parent-1 (label) → 1-1, 1-2, ... → parent-2 (label) → 2-1, 2-2, ...
*
* "parent" type items are non-clickable headings. Only "intro-segment" and
* "sub-chapter" items are navigable pages.
*/
export async function getSvaSidebarItems(): Promise<SvaSidebarItem[]> {
const [meta, allDocs] = await Promise.all([
getSvaMeta(),
prisma.proseChapter.findMany({
let allDocs: {
slug: string;
title: string;
type: string;
chapter: number | null;
order: number;
}[] = [];
const meta = await getSvaMeta();
try {
allDocs = await prisma.proseChapter.findMany({
where: { book: BOOK, volume: NO_VOLUME },
orderBy: { order: "asc" },
select: { slug: true, title: true, type: true, chapter: true, order: true },
}),
]);
// If we got DB results, build from those
if (meta && allDocs.length > 0) {
return buildSidebarFromDocs(meta, allDocs);
select: {
slug: true,
title: true,
type: true,
chapter: true,
order: true,
},
});
} catch {
// Prisma BSON decode error — build sidebar from meta alone
}
// Fallback: build from local JSON
return buildSidebarFromLocal(meta);
}
if (!meta) {
// Try building from local JSON
return buildSidebarFromLocal();
}
function buildSidebarFromDocs(
meta: SvaMeta,
allDocs: { slug: string; title: string; type: string; chapter: number | null; order: number | null }[],
): SvaSidebarItem[] {
const items: SvaSidebarItem[] = [];
// Intro segments that come BEFORE chapters (order < 99)
for (const doc of allDocs) {
if (doc.type === "intro-segment" && (doc.order ?? 0) < 99) {
if (allDocs.length > 0) {
for (const doc of allDocs) {
if (doc.type === "intro-segment" && (doc.order ?? 0) < 99) {
items.push({
slug: doc.slug,
label: doc.title,
type: "intro-segment",
parentChapter: null,
});
}
}
} else {
// Fallback: local intro segments
const localIntros = getLocalIntroSegments();
for (const seg of localIntros) {
if ((seg.order ?? 0) < 99) {
items.push({
slug: `intro-${seg.slug}`,
label: seg.title,
type: "intro-segment",
parentChapter: null,
});
}
}
}
// Chapters — grouped by parent chapter with sub-chapters
for (const ch of meta.chapters) {
// Parent heading (non-clickable label)
items.push({
slug: `parent-${ch.number}`,
label: `Part ${ch.number}: ${ch.title}`,
type: "parent",
parentChapter: ch.number,
});
// Sub-chapters (songs) under this parent
for (const sub of ch.subChapters) {
items.push({
slug: doc.slug,
label: doc.title,
type: "intro-segment",
chapter: null,
slug: sub.slug,
label: sub.title,
type: "sub-chapter",
parentChapter: ch.number,
});
}
}
// Chapters 1–4 (use meta.chapters for consistent title/ordering)
for (const ch of meta.chapters) {
items.push({
slug: String(ch.number),
label: `Part ${ch.number}: ${ch.title}`,
type: "chapter",
chapter: ch.number,
});
}
// Intro segments that come AFTER chapters (order >= 99)
for (const doc of allDocs) {
if (doc.type === "intro-segment" && (doc.order ?? 0) >= 99) {
items.push({
slug: doc.slug,
label: doc.title,
type: "intro-segment",
chapter: null,
});
if (allDocs.length > 0) {
for (const doc of allDocs) {
if (doc.type === "intro-segment" && (doc.order ?? 0) >= 99) {
items.push({
slug: doc.slug,
label: doc.title,
type: "intro-segment",
parentChapter: null,
});
}
}
}
return items;
}
function buildSidebarFromLocal(meta: SvaMeta | null): SvaSidebarItem[] {
function buildSidebarFromLocal(): SvaSidebarItem[] {
const items: SvaSidebarItem[] = [];
// Local intro segments (front matter)
// Intro segments
const introSegs = getLocalIntroSegments();
const frontMatter = introSegs.filter((s) => (s.order ?? 0) < 99);
const backMatter = introSegs.filter((s) => (s.order ?? 0) >= 99);
for (const seg of frontMatter) {
items.push({
slug: `intro-${seg.slug}`,
label: seg.title,
type: "intro-segment",
chapter: null,
});
}
// Chapters from meta or generate default 1-4
if (meta && meta.chapters) {
for (const ch of meta.chapters) {
for (const seg of introSegs) {
if ((seg.order ?? 0) < 99) {
items.push({
slug: String(ch.number),
label: `Part ${ch.number}: ${ch.title}`,
type: "chapter",
chapter: ch.number,
slug: `intro-${seg.slug}`,
label: seg.title,
type: "intro-segment",
parentChapter: null,
});
}
} else {
// Fallback: scan local chapter JSONs
const chaptersDir = path.join(SVA_JSON_DIR, "chapters");
if (fs.existsSync(chaptersDir)) {
const files = fs
.readdirSync(chaptersDir)
.filter((f) => f.endsWith(".json"))
.sort();
for (const file of files) {
const ch = readLocalJson<SvaChapter>(path.join(chaptersDir, file));
if (ch) {
const num = ch.chapter ?? parseInt(file.replace(".json", ""), 10);
items.push({
slug: String(num),
label: `Part ${num}: ${ch.title}`,
type: "chapter",
chapter: num,
});
}
}
// Load meta for chapter structure
const introPath = path.join(SVA_JSON_DIR, "intro.json");
const meta = readLocalJson<SvaMeta>(introPath);
if (meta?.chapters) {
for (const ch of meta.chapters) {
items.push({
slug: `parent-${ch.number}`,
label: `Part ${ch.number}: ${ch.title}`,
type: "parent",
parentChapter: ch.number,
});
for (const sub of ch.subChapters) {
items.push({
slug: sub.slug,
label: sub.title,
type: "sub-chapter",
parentChapter: ch.number,
});
}
}
}
// Back matter
for (const seg of backMatter) {
items.push({
slug: `intro-${seg.slug}`,
label: seg.title,
type: "intro-segment",
chapter: null,
});
for (const seg of introSegs) {
if ((seg.order ?? 0) >= 99) {
items.push({
slug: `intro-${seg.slug}`,
label: seg.title,
type: "intro-segment",
parentChapter: null,
});
}
}
return items;
}
/**
* Get the flat list of navigable sidebar items (excludes "parent" headings).
* Used for prev/next navigation.
*/
export function getNavigableItems(items: SvaSidebarItem[]): SvaSidebarItem[] {
return items.filter((item) => item.type !== "parent");
}