'use strict'; const buildChapterTree = (chapters = [], blocks = []) => { const nodeMap = new Map(); chapters.forEach(chapter => { nodeMap.set(chapter.id, { ...chapter, blocks: [], children: [], }); }); blocks.forEach(block => { const node = nodeMap.get(block.chapterId); if (node) { node.blocks.push(block); } }); const roots = []; chapters.forEach(chapter => { const node = nodeMap.get(chapter.id); if (chapter.parentId && nodeMap.has(chapter.parentId)) { nodeMap.get(chapter.parentId).children.push(node); } else { roots.push(node); } }); const sortNodes = (nodes = []) => { nodes.sort((a, b) => a.position - b.position || a.id - b.id); nodes.forEach(node => { node.blocks.sort((a, b) => a.position - b.position || a.id - b.id); sortNodes(node.children); }); }; sortNodes(roots); return roots; }; const buildDocxImportChapterPayload = (nodes = [], sourceFileUrl, sourceFileName) => { return nodes.map((node, index) => ({ title: String(node.title || `Chapter ${index + 1}`), position: index + 1, blocks: [ { blockType: 'text', position: 1, config: { format: 'html', source: 'docxImport', sourceFileUrl, sourceFileName, }, contentSnapshot: { content: String(node.contentHtml || ''), }, } ], children: buildDocxImportChapterPayload(node.children || [], sourceFileUrl, sourceFileName), })); }; module.exports = { buildChapterTree, buildDocxImportChapterPayload, };