The idea is that we group all items so we get combinations of chapter with resp. paragraphs. However, some paragraphs don't have a parent (chapter). In this case those paragraphs should be handled first.
Well, here is kind of a generic solution (read solution pattern). You need 1 function that extracts the groupingkey from an item. The getGroupingKeys function just takes the distinct values of all grouping keys. So when you have the groupingkeys, you can determine the items belonging to each group using this predicate [local:getGroupingKey(.) = $grouping_key]. Next you handle the items for each group the way you want.