@@ -393,6 +393,36 @@ const generateSectionContent = (section: any, config: any) => {
393393 return sectionContent ;
394394} ;
395395
396+ // Function to build a hierarchical structure from a flat list of sections
397+ const buildSectionsHierarchy = ( sections : any [ ] ) => {
398+ const sectionMap = new Map ( ) ;
399+
400+ // Create a map of sections by ID
401+ sections . forEach ( ( section ) => {
402+ sectionMap . set ( section . sectionId , { ...section , subSections : [ ] } ) ;
403+ } ) ;
404+
405+ const rootSections : any [ ] = [ ] ;
406+
407+ // Organize sections into a hierarchy
408+ sections . forEach ( ( section ) => {
409+ if ( section . parentSectionId ) {
410+ // If the section has a parent, add it as a subSection
411+ const parent = sectionMap . get ( section . parentSectionId ) ;
412+ if ( parent ) {
413+ parent . subSections . push ( sectionMap . get ( section . sectionId ) ) ;
414+ } else {
415+ console . warn ( `Parent section with ID ${ section . parentSectionId } not found.` ) ;
416+ }
417+ } else {
418+ // If no parent, it's a root section
419+ rootSections . push ( sectionMap . get ( section . sectionId ) ) ;
420+ }
421+ } ) ;
422+
423+ return rootSections ;
424+ } ;
425+
396426async function execGenWordFuncs (
397427 data : {
398428 title : string ;
@@ -491,6 +521,9 @@ async function execGenWordFuncs(
491521 ) ;
492522 }
493523
524+ // Build sections hierarchy
525+ const sectionsHierarchy = buildSectionsHierarchy ( data . sections ) ;
526+
494527 // Create the document based on JSON data
495528 const doc = new Document ( {
496529 styles : {
@@ -533,7 +566,7 @@ async function execGenWordFuncs(
533566 } ) ,
534567 ...tableOfContentConfigs ,
535568 // Generate all sections and sub-sections
536- ...data . sections . flatMap ( ( section ) =>
569+ ...sectionsHierarchy . flatMap ( ( section ) =>
537570 generateSectionContent ( section , { ...config , numberingReference : selectedNumberingOption ?. reference } )
538571 ) ,
539572 ] ,
0 commit comments