import { Client, isFullBlock } from "@notionhq/client"; import { BlockObjectRequest } from "@notionhq/client/build/src/api-endpoints"; import { formatValue } from "../../../format/formatValue"; import { isStatGroupDesc, StatDesc, StatGroupDesc, StatsType, } from "../../../statistiques/v2/desc/StatsDesc"; import { listAllChildrenBlocks } from "../../utils/listAllChildrenBlocks"; import { removeBlocks } from "../../utils/removeBlocks"; export async function publishStatsToPage( notionClient: Client, statsPageId: string, descriptor: D, stats: StatsType ) { const childrenBlocks = ( await listAllChildrenBlocks(notionClient, { block_id: statsPageId, }) ).filter(isFullBlock); const blocksIdsToRemove = childrenBlocks.map((b) => b.id); await removeBlocks(notionClient, blocksIdsToRemove); const newBlocks = createStatGroupChildrenListItemBlock(descriptor, stats); await notionClient.blocks.children.append({ block_id: statsPageId, children: [...newBlocks], }); } function createStatGroupListItemBlock( descriptor: D, stats: StatsType ): BulletedListItemBlockObjectRequest { return { bulleted_list_item: { rich_text: [ { text: { content: descriptor.label, }, }, ], children: createStatGroupChildrenListItemBlock( descriptor, stats ) as BulletedListItemChildren, }, }; } type BulletedListItemBlockObjectRequest = Extract< BlockObjectRequest, { bulleted_list_item: object } >; type BulletedListItemChildren = BulletedListItemBlockObjectRequest["bulleted_list_item"]["children"]; function createStatGroupChildrenListItemBlock( descriptor: D, stats: StatsType ): BulletedListItemBlockObjectRequest[] { return Object.keys(descriptor.stats).map((statName) => { const childStatDesc = descriptor.stats[statName]; const childStatValue = stats[statName]; return isStatGroupDesc(childStatDesc) ? createStatGroupListItemBlock( childStatDesc, childStatValue as StatsType ) : createStatListItemBlock(childStatDesc, childStatValue as number); }); } function createStatListItemBlock( descriptor: StatDesc, statValue: number ): BulletedListItemBlockObjectRequest { return { bulleted_list_item: { rich_text: [ { text: { content: descriptor.label + ": " + formatValue(statValue, descriptor), }, }, ], }, }; }