mirror of
https://framagit.org/enfance-libre/statistiques
synced 2025-12-07 13:53:45 +00:00
81 lines
2.4 KiB
TypeScript
81 lines
2.4 KiB
TypeScript
import { Client, isFullBlock } from "@notionhq/client";
|
|
import { BlockObjectRequest } from "@notionhq/client/build/src/api-endpoints";
|
|
import { ELStats } from "../../statistiques/ELStats";
|
|
import { listAllChildrenBlocks } from "../utils/listAllChildrenBlocks";
|
|
import { removeBlocks } from "../utils/removeBlocks";
|
|
import { richTextToPlainText } from "../utils/text/richTextToPlainText";
|
|
import { currentStatsHeading, statsPageId } from "./publishStatisticsToNotion";
|
|
|
|
export async function publishCurrentStats(
|
|
notionClient: Client,
|
|
stats: ELStats
|
|
) {
|
|
const childrenBlocks = (
|
|
await listAllChildrenBlocks(notionClient, {
|
|
block_id: statsPageId,
|
|
})
|
|
).filter(isFullBlock);
|
|
|
|
const currentStatsHeadingBlockIndex = childrenBlocks.findIndex(
|
|
(block) =>
|
|
block.type === "heading_1" &&
|
|
richTextToPlainText(block.heading_1.rich_text) === currentStatsHeading
|
|
);
|
|
const endOfCurrentStats = childrenBlocks.findIndex(
|
|
(block, index) =>
|
|
index > currentStatsHeadingBlockIndex && block.type === "heading_1"
|
|
);
|
|
if (currentStatsHeadingBlockIndex === -1 || endOfCurrentStats === -1) {
|
|
throw new Error("Cannot find expected headings in statistics page");
|
|
}
|
|
|
|
const currentStatsHeadingBlock =
|
|
childrenBlocks[currentStatsHeadingBlockIndex];
|
|
|
|
const blocksIdsToRemove = childrenBlocks
|
|
.slice(currentStatsHeadingBlockIndex + 1, endOfCurrentStats)
|
|
.map((b) => b.id);
|
|
await removeBlocks(notionClient, blocksIdsToRemove);
|
|
|
|
notionClient.blocks.children.append({
|
|
block_id: statsPageId,
|
|
after: currentStatsHeadingBlock.id,
|
|
children: [
|
|
currentStatBlock("Nb Famille Résistante", stats.nbFamilleResistantes),
|
|
currentStatBlock(
|
|
"Nb Famille Résistante ou Ex-Résistante",
|
|
stats.nbFamilleResistantesOrEx
|
|
),
|
|
currentStatBlock(
|
|
"Durée Moyenne Résistance (jours)",
|
|
stats.dureeMoyenneResistance
|
|
),
|
|
currentStatBlock(
|
|
"Durée Médiane Résistance (jours)",
|
|
stats.dureeMedianeResistance
|
|
),
|
|
],
|
|
});
|
|
}
|
|
|
|
function currentStatBlock(
|
|
stateName: string,
|
|
value: number
|
|
): BlockObjectRequest {
|
|
return {
|
|
paragraph: {
|
|
rich_text: [
|
|
{
|
|
text: {
|
|
content:
|
|
stateName +
|
|
": " +
|
|
value.toLocaleString("us-FR", {
|
|
maximumFractionDigits: 0,
|
|
}),
|
|
},
|
|
},
|
|
],
|
|
},
|
|
};
|
|
}
|