#!/usr/bin/env node // Baut aus den Daten in daten/ die Tabellen in den Markdown-Dateien und auf // Wunsch einen Export des Redaktionsplans für Noah (PDF, HTML oder Markdown). // // node werkzeuge/bauen.mjs Markdown-Dateien aktualisieren // node werkzeuge/bauen.mjs --pruefen nur prüfen, nichts schreiben // node werkzeuge/bauen.mjs --von=JJJJ-MM-TT --bis=JJJJ-MM-TT --format=pdf|html|md --ziel=DATEI [--ideen] // // --ideen hängt an den Export den Ideen-Pool zum Thema an. // // Die Daten sind die einzige Quelle. In den Markdown-Dateien stehen die // erzeugten Teile zwischen Markierungen wie und // . Alles dazwischen wird bei jedem Lauf ersetzt, alles // außerhalb bleibt, wie es ist. import { readFileSync, writeFileSync, mkdirSync, mkdtempSync, rmSync, statSync } from "node:fs"; import { spawn } from "node:child_process"; import { createRequire } from "node:module"; import { dirname, join, basename } from "node:path"; import { tmpdir } from "node:os"; import { fileURLToPath, pathToFileURL } from "node:url"; const HUB = join(dirname(fileURLToPath(import.meta.url)), ".."); const CHROME = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"; const args = new Set(process.argv.slice(2)); const PRUEFEN = args.has("--pruefen"); const IDEEN = args.has("--ideen"); // Export für einen Zeitraum: // node werkzeuge/bauen.mjs --von=2026-10-19 --bis=2026-11-01 --format=pdf --ziel=/pfad/datei.pdf const OPT = Object.fromEntries(process.argv.slice(2).filter((a) => /^--\w+=/.test(a)) .map((a) => { const [k, ...v] = a.slice(2).split("="); return [k, v.join("=")]; })); const EXPORT = Boolean(OPT.von && OPT.bis && OPT.format && OPT.ziel); const pfad = (...teile) => join(HUB, ...teile); const lies = (p) => readFileSync(pfad(p), "utf8"); const json = (p) => JSON.parse(lies(p)); const PLAN = json("daten/redaktionsplan.json"); const ROADMAP = json("daten/roadmap.json"); const KANAELE = json("daten/kanaele.json"); const MD_PLAN = "Brainstorming Kickoff/Strategie/Redaktionsplan.md"; const MD_ROADMAP = "Brainstorming Kickoff/Strategie/Roadmap.md"; const MD_BIB = "Ressourcen/Formatbibliothek.md"; // ---------------------------------------------------------------- Datum const WT = ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"]; const tag = (iso) => new Date(iso + "T00:00:00Z"); const iso = (d) => d.toISOString().slice(0, 10); const plus = (isoDatum, n) => { const d = tag(isoDatum); d.setUTCDate(d.getUTCDate() + n); return iso(d); }; const ttmm = (isoDatum) => `${isoDatum.slice(8, 10)}.${isoDatum.slice(5, 7)}.`; const wochentag = (isoDatum) => WT[tag(isoDatum).getUTCDay()]; function kw(isoDatum) { const d = tag(isoDatum); const wt = (d.getUTCDay() + 6) % 7; d.setUTCDate(d.getUTCDate() - wt + 3); const erster = new Date(Date.UTC(d.getUTCFullYear(), 0, 4)); return 1 + Math.round(((d - erster) / 86400000 - 3 + ((erster.getUTCDay() + 6) % 7)) / 7); } const montag = (isoDatum) => plus(isoDatum, -((tag(isoDatum).getUTCDay() + 6) % 7)); // "12. bis 18.10." im selben Monat, sonst "26.10. bis 01.11." function spanne(von, bis) { if (von.slice(0, 7) === bis.slice(0, 7)) return `${von.slice(8, 10)}. bis ${ttmm(bis)}`; return `${ttmm(von)} bis ${ttmm(bis)}`; } function slotDatum(s) { let text = `${wochentag(s.datum)} ${ttmm(s.datum)}`; if (s.bis) { text = s.datum.slice(0, 7) === s.bis.slice(0, 7) ? `${wochentag(s.datum)} ${s.datum.slice(8, 10)}. bis ${wochentag(s.bis)} ${ttmm(s.bis)}` : `${wochentag(s.datum)} ${ttmm(s.datum)} bis ${wochentag(s.bis)} ${ttmm(s.bis)}`; } return s.wichtig ? `**${text}**` : text; } // ---------------------------------------------------------------- Funnel const FUNNEL_NAME = { top: "Top", middle: "Middle", bottom: "Bottom" }; const formatVon = (code) => PLAN.formate.find((f) => f.kuerzel === code) || PLAN.linkedin.find((l) => l.kuerzel === code); // Die Stufe eines Slots: steht sie am Slot, gilt die, sonst die des ersten Formats. function funnel(s) { if (s.funnel) return s.funnel; if (s.kanaele.includes("intern")) return null; const code = (s.format.match(FORMAT_CODE) || [])[0]; return code ? formatVon(code)?.funnel || null : null; } // Anteil je Stufe, auf ganze Prozent gerundet. function mix(slots) { const z = { top: 0, middle: 0, bottom: 0 }; for (const s of slots) { const f = funnel(s); if (f) z[f] += 1; } const n = z.top + z.middle + z.bottom; const pz = (k) => (n ? Math.round((z[k] / n) * 100) : 0); return { n, top: pz("top"), middle: pz("middle"), bottom: pz("bottom"), zahl: z }; } // Geschütztes Leerzeichen vor %, damit Zahl und Zeichen nicht getrennt umbrechen. const mixText = (m) => `Top ${m.top}\u00a0%, Middle ${m.middle}\u00a0%, Bottom ${m.bottom}\u00a0%`; // Noahs Vorgabe gilt für die Reels: rund 70 % davon sind Top. const nurReels = (slots) => slots.filter((s) => art(s) === "reel"); // ---------------------------------------------------------------- Prüfen const KANAL_NAMEN = new Set(["Instagram", "Facebook", "TikTok", "YouTube Shorts", "LinkedIn", "Instagram Stories", "intern"]); const SLOT_STATUS = new Set(["geplant", "fertig", "erschienen", "ausgefallen"]); const SCHRITT_STATUS = new Set(["offen", "läuft", "erledigt", "später", "entfällt"]); const ISO_DATUM = /^\d{4}-\d{2}-\d{2}$/; const FORMAT_CODE = /\b(F\d{1,2}b?|CH|L[1-4])\b/g; const BEKANNTE_CODES = new Set([ ...PLAN.formate.map((f) => f.kuerzel), ...PLAN.linkedin.map((l) => l.kuerzel), "F1", "F8", "F9", "F11", "F12", "F13", ]); const fehler = []; const hinweise = []; function pruefeTexte(wurzel, wo) { // Hausregel: keine Geviertstriche und keine Halbgeviertstriche als Gedankenstrich. const gehe = (wert, pfadTeil) => { if (typeof wert === "string") { if (/[—–]/.test(wert)) fehler.push(`${wo}${pfadTeil}: Gedankenstrich im Text: ${wert.slice(0, 60)}`); } else if (Array.isArray(wert)) wert.forEach((w, i) => gehe(w, `${pfadTeil}[${i}]`)); else if (wert && typeof wert === "object") Object.entries(wert).forEach(([k, w]) => gehe(w, `${pfadTeil}.${k}`)); }; gehe(wurzel, ""); } function pruefen() { const ids = new Set(); for (const s of PLAN.slots) { const wo = `Slot ${s.id}`; if (!s.id || ids.has(s.id)) fehler.push(`${wo}: Kennung fehlt oder doppelt`); ids.add(s.id); if (!ISO_DATUM.test(s.datum) || isNaN(tag(s.datum))) fehler.push(`${wo}: Datum ${s.datum} ungültig`); if (s.bis && (!ISO_DATUM.test(s.bis) || s.bis < s.datum)) fehler.push(`${wo}: bis ${s.bis} ungültig`); for (const k of s.kanaele || []) if (!KANAL_NAMEN.has(k)) fehler.push(`${wo}: Kanal „${k}“ unbekannt`); if (!s.kanaele?.length) fehler.push(`${wo}: kein Kanal`); if (!SLOT_STATUS.has(s.status)) fehler.push(`${wo}: Status „${s.status}“ unbekannt`); for (const c of (s.format.match(FORMAT_CODE) || [])) if (!BEKANNTE_CODES.has(c)) hinweise.push(`${wo}: Format ${c} steht nicht in den Abkürzungen`); const tagNr = tag(s.datum).getUTCDay(); if ((tagNr === 0 || tagNr === 6) && !s.bis) hinweise.push(`${wo}: liegt auf einem Wochenende (${slotDatum(s)})`); } for (const t of PLAN.tests) { for (const d of t.termine) { if (!ISO_DATUM.test(d)) fehler.push(`Test ${t.id}: Termin ${d} ungültig`); const intern = PLAN.slots.find((s) => s.datum === d && s.kanaele.includes("intern")); if (!intern) hinweise.push(`Test ${t.id}: am ${ttmm(d)} steht kein interner Slot im Plan`); else if (t.id !== "M" && !intern.format.includes(t.id)) hinweise.push(`Test ${t.id}: der interne Slot am ${ttmm(d)} nennt ${t.id} nicht`); } } const schrittIds = new Set(); for (const p of ROADMAP.pakete) { for (const s of p.schritte) { const wo = `Schritt ${s.id}`; if (schrittIds.has(s.id)) fehler.push(`${wo}: Kennung doppelt`); schrittIds.add(s.id); if (!SCHRITT_STATUS.has(s.status)) fehler.push(`${wo}: Status „${s.status}“ unbekannt`); if (s.faellig !== null && s.faellig !== undefined && !ISO_DATUM.test(s.faellig)) fehler.push(`${wo}: fällig ${s.faellig} ungültig`); } } // Jeder Beitrag braucht eine Funnel-Stufe, und der Mix der Reels soll Noahs Vorgabe treffen. for (const s of PLAN.slots) { if (!s.kanaele.includes("intern") && !funnel(s)) fehler.push(`Slot ${s.id}: keine Funnel-Stufe (Format ohne "funnel" und kein "funnel" am Slot)`); } const [unten, oben] = PLAN.funnel?.ziel_top || [60, 70]; for (const p of PLAN.phasen) { const m = mix(nurReels(PLAN.slots.filter((s) => s.datum >= p.von && s.datum <= p.bis))); if (m.n && (m.top < unten || m.top > oben)) hinweise.push(`Phase ${p.nr}: Top ${m.top} % der Reels, Ziel ${unten} bis ${oben} %`); } for (const i of PLAN.ideen || []) { if (!i.name || !FUNNEL_NAME[i.funnel]) fehler.push(`Idee „${i.name || "?"}“: Name oder Funnel-Stufe fehlt`); } pruefeTexte(PLAN, "redaktionsplan"); pruefeTexte(ROADMAP, "roadmap"); pruefeTexte(KANAELE, "kanaele"); } // ---------------------------------------------------------------- Markdown-Bausteine const zelle = (t) => String(t ?? "").replace(/\|/g, "\\|").replace(/\n/g, " "); function tabelle(kopf, zeilen) { return [ `| ${kopf.join(" | ")} |`, `|${kopf.map(() => "---").join("|")}|`, ...zeilen.map((z) => `|${z.map((w) => (zelle(w) ? ` ${zelle(w)} ` : " ")).join("|")}|`), ].join("\n"); } function blockAbkuerzungen() { return [ `**Thema:** ${PLAN.thema.name}. ${PLAN.thema.text}`, "", "**Blickwinkel:**", ...PLAN.saeulen.map((s) => `- **${s.kuerzel} ${s.name}:** ${s.text}`), "", `**Funnel:** ${PLAN.funnel.ziel_text}`, ...PLAN.funnel.stufen.map((f) => `- **${f.name}:** ${f.text}`), "", "**Formate:**", "", tabelle(["Kürzel", "Format", "Funnel", "So kommt das Thema vor", "Aufwand"], PLAN.formate.map((f) => [f.kuerzel, f.name, FUNNEL_NAME[f.funnel], f.thema, f.aufwand])), "", "**LinkedIn-Postarten** (Text und Bild):", "", tabelle(["Kürzel", "Postart", "Funnel", "Was dahinter steckt"], PLAN.linkedin.map((l) => [l.kuerzel, l.name, FUNNEL_NAME[l.funnel], l.text])), ].join("\n"); } function slotZeile(s) { const blick = PLAN.saeulen.find((x) => x.kuerzel === s.saeule)?.name || s.saeule; return [slotDatum(s), s.kanaele.join(", "), s.format, blick, FUNNEL_NAME[funnel(s)] || "", s.notiz]; } function wochenBloecke(slots) { const nachWoche = new Map(); for (const s of slots) { const m = montag(s.datum); if (!nachWoche.has(m)) nachWoche.set(m, []); nachWoche.get(m).push(s); } const teile = []; for (const [m, liste] of [...nachWoche.entries()].sort(([a], [b]) => a.localeCompare(b))) { const nr = kw(m); const info = PLAN.wochen.find((w) => w.kw === nr) || {}; teile.push(`#### KW ${nr} (${spanne(m, plus(m, 6))})${info.titel ? ": " + info.titel : ""}`, ""); if (info.text) teile.push(info.text, ""); teile.push(tabelle(["Datum", "Kanal", "Format", "Blickwinkel", "Funnel", "Notiz"], liste.map(slotZeile)), ""); } return teile; } function sortierteSlots() { // Stabil nach Datum. Am selben Tag gilt die Reihenfolge in der Datei. return PLAN.slots.map((s, i) => [s, i]) .sort(([a, i], [b, j]) => a.datum.localeCompare(b.datum) || i - j) .map(([s]) => s); } function blockPlan() { const alle = sortierteSlots(); const teile = []; const vergeben = new Set(); PLAN.phasen.forEach((p) => { const drinnen = alle.filter((s) => s.datum >= p.von && s.datum <= p.bis); const r = mix(nurReels(drinnen)); teile.push(`### Phase ${p.nr}: ${p.name} (${spanne(p.von, p.bis)})`, "", `${p.text} Funnel der Reels: ${mixText(r)}. Alle Beiträge: ${mixText(mix(drinnen))}.`, ""); drinnen.forEach((s) => vergeben.add(s.id)); teile.push(...wochenBloecke(drinnen)); }); for (const pause of PLAN.pausen) { const wochen = []; for (let m = montag(pause.von); m <= pause.bis; m = plus(m, 7)) wochen.push(kw(m)); const kws = wochen.length > 1 ? `KW ${wochen.slice(0, -1).join(", ")} und ${wochen.at(-1)}` : `KW ${wochen[0]}`; teile.push(`#### ${kws} (${ttmm(pause.von)} bis ${ttmm(pause.bis)}): ${pause.titel}`, "", pause.text, ""); } const rest = alle.filter((s) => !vergeben.has(s.id)); if (rest.length) { teile.push("### Weitere Slots", ""); teile.push(...wochenBloecke(rest)); } if (PLAN.ausblick) { const a = PLAN.ausblick; teile.push(`### ${a.titel}`, "", ...(a.punkte.length === 1 ? a.punkte : a.punkte.map((p) => `- ${p}`)), ""); } return teile.join("\n").trimEnd(); } function blockFlex() { return tabelle(["Flex-Slot", "Von wem", "Was passiert, wenn er kommt"], PLAN.flex.map((f) => [`**${f.name}**`, f.von, f.dann])); } function testDatum(t) { if (!t.termine.length) return t.wann || "offen"; return t.termine.map((d, i) => (i === 0 ? `${wochentag(d)} ${ttmm(d)}` : ttmm(d))).join(", "); } function blockTests() { const mitErgebnis = PLAN.tests.some((t) => t.ergebnis); const kopf = ["Datum", "Test", "Frage", "Grundlage", ...(mitErgebnis ? ["Ergebnis"] : [])]; return tabelle(kopf, PLAN.tests.map((t) => [ testDatum(t), t.id.startsWith("T") ? `**${t.id} ${t.titel}**` : t.titel, t.frage, t.grundlage, ...(mitErgebnis ? [t.ergebnis] : []), ])); } function blockZeitstrahl() { return tabelle(["Wann", "Schwerpunkt"], ROADMAP.zeitstrahl.map((z) => [z.wann, z.text])); } function blockPaket(id) { const p = ROADMAP.pakete.find((x) => x.id === id); if (!p) throw new Error(`Paket ${id} fehlt in daten/roadmap.json`); return tabelle(p.spalten.map(([, titel]) => titel), p.schritte.map((s) => p.spalten.map(([feld]) => (feld === "kurz" ? `**${s.kurz}**` : s[feld] ?? "")))); } // Der Ideen-Pool: Formate aus der Inspo-Bibliothek, auf Meister & Nerds gemünzt. function blockIdeen() { return tabelle(["Idee", "Was passiert", "Funnel", "Aufwand", "Konto", "Baut auf"], PLAN.ideen.map((i) => [`**${i.name}**`, i.text, FUNNEL_NAME[i.funnel], i.aufwand, i.konto, [i.aus === "neu" ? "neu" : i.aus, i.vorbild].filter(Boolean).join(", ")])); } const BLOECKE = { [MD_PLAN]: { abkuerzungen: blockAbkuerzungen, plan: blockPlan, flex: blockFlex, tests: blockTests, }, [MD_ROADMAP]: { zeitstrahl: blockZeitstrahl, "paket:A": () => blockPaket("A"), "paket:B1": () => blockPaket("B1"), "paket:C": () => blockPaket("C"), "paket:D": () => blockPaket("D"), "paket:F": () => blockPaket("F"), }, [MD_BIB]: { ideen: blockIdeen, }, }; function stempel(datei, daten) { // Die Kopfzeile "Status: ..., Stand ..." folgt den Daten. const [j, m, t] = [daten.stand.slice(0, 4), daten.stand.slice(5, 7), daten.stand.slice(8, 10)]; return datei.replace(/^\*\*Status:\*\* .*$/m, `**Status:** ${daten.status}, Stand ${t}.${m}.${j}`); } function markdownAktualisieren() { const geaendert = []; for (const [datei, bloecke] of Object.entries(BLOECKE)) { let text = lies(datei); const vorher = text; for (const [name, bau] of Object.entries(bloecke)) { const auf = ``; const zu = ``; const a = text.indexOf(auf); const z = text.indexOf(zu); if (a < 0 || z < a) { fehler.push(`${basename(datei)}: Markierung ${auf} fehlt`); continue; } text = text.slice(0, a + auf.length) + "\n" + bau() + "\n" + text.slice(z); } if (datei === MD_PLAN || datei === MD_ROADMAP) text = stempel(text, datei === MD_PLAN ? PLAN : ROADMAP); if (text !== vorher) { geaendert.push(basename(datei)); if (!PRUEFEN) writeFileSync(pfad(datei), text); } } return geaendert; } // ---------------------------------------------------------------- Export für Noah // Noah interessiert immer wieder dasselbe: welcher Content in einem Zeitraum // kommt, wann und auf welchen Kanälen. Gebaut direkt aus den Daten, mit den // einfachen Texten aus daten/redaktionsplan.json (Felder "noah" und "noah_*"). // Interne Termine, Codes, Säulen, Recht und Roadmap bleiben im Hub. const datumLang = (isoDatum) => `${isoDatum.slice(8, 10)}.${isoDatum.slice(5, 7)}.${isoDatum.slice(0, 4)}`; const zeitraumText = (von, bis) => `${spanne(von, bis)}${bis.slice(0, 4)}`; function formatInfo(code) { return PLAN.formate.find((f) => f.kuerzel === code) || PLAN.linkedin.find((l) => l.kuerzel === code); } const formatCodes = (s) => [...new Set(s.format.match(FORMAT_CODE) || [])]; // Was an einem Termin erscheint, in Noahs Worten. feld: noah_name oder noah_chip. function wasErscheint(s, feld = "noah_name") { if (s.kanaele.includes("Instagram Stories")) return "Stories"; // Ein Slot kann den Namen für Noah selbst setzen, etwa bei einer Variante. if (s[feld]) return s[feld]; const namen = formatCodes(s).map((c) => formatInfo(c)?.[feld] || c); if (namen.length > 1 && namen.every((n) => n.startsWith("Reel: "))) { return "Reel: " + namen.map((n) => n.slice(6)).join(" oder "); } // Im Kalender ist wenig Platz, dort reicht ein Schrägstrich. return namen.join(feld === "noah_chip" ? " / " : " oder "); } const amTag = (s, d) => s.datum === d || (s.bis && s.datum <= d && s.bis >= d); const imZeitraum = (s, von, bis) => (s.bis || s.datum) >= von && s.datum <= bis; const noahPosts = (von, bis) => sortierteSlots().filter((s) => !s.kanaele.includes("intern") && s.status !== "ausgefallen" && imZeitraum(s, von, bis)); function exportMarkdown(von, bis, ideen = false) { const posts = noahPosts(von, bis); const V = PLAN.noah.vorbereitung; const planEnde = PLAN.phasen.at(-1).bis; const teile = []; // Woche für Woche const wochen = new Map(); for (const s of posts) { const m = montag(s.datum < von ? von : s.datum); if (!wochen.has(m)) wochen.set(m, []); wochen.get(m).push(s); } teile.push("## Woche für Woche", ""); if (V.von <= bis && V.bis >= von) { teile.push(`### KW ${kw(V.von)} (${spanne(V.von, V.bis)}): ${V.titel}`, "", tabelle(["Was", "Von wem"], V.punkte.map((x) => [x.was, x.wer])), ""); } for (const [m, liste] of wochen) { const info = PLAN.wochen.find((w) => w.kw === kw(m)) || {}; const titel = info.noah ?? info.titel; teile.push(`### KW ${kw(m)} (${spanne(m, plus(m, 6))})${titel ? ": " + titel : ""}`, ""); teile.push(tabelle(["Datum", "Was", "Kanäle", "Funnel", "Hinweis"], liste.map((s) => [ slotDatum(s), wasErscheint(s), s.kanaele.join(", "), FUNNEL_NAME[funnel(s)] || "", s.noah || "", ])), ""); } if (!posts.length) teile.push("In diesem Zeitraum ist kein Beitrag geplant.", ""); if (bis > planEnde) teile.push(`Nach dem ${ttmm(planEnde)} ist noch nichts geplant. Das planen wir frühestens Ende November.`, ""); // Formate in diesem Zeitraum. Fest im Plan und als eine von zwei // Möglichkeiten ("F7 oder F3") getrennt zählen. const fest = new Map(); const vielleicht = new Map(); for (const s of posts) { const cs = formatCodes(s); for (const c of cs) { const ziel = cs.length > 1 ? vielleicht : fest; ziel.set(c, (ziel.get(c) || 0) + 1); } } const alleCodes = [...new Set([...fest.keys(), ...vielleicht.keys()])]; const wieOft = (c) => { const a = fest.get(c) || 0; const b = vielleicht.get(c) || 0; return b ? `${a} bis ${a + b} Mal` : `${a} Mal`; }; const zeile = (c) => { const f = formatInfo(c); return [`**${f.noah_name}**`, f.noah_text, FUNNEL_NAME[f.funnel], wieOft(c)]; }; const stories = posts.filter((s) => s.kanaele.includes("Instagram Stories")); const zeilen = [ ...alleCodes.filter((c) => !c.startsWith("L")).map(zeile), ...(stories.length ? [["**Stories**", "Kurze Einblicke von der Messe, so viel vor Ort passt.", FUNNEL_NAME[funnel(stories[0])] || "", "GET Nord"]] : []), ...alleCodes.filter((c) => c.startsWith("L")).map((c) => { const z = zeile(c); z[0] = `**LinkedIn: ${formatInfo(c).noah_name}**`; return z; }), ]; if (zeilen.length) { teile.push("## Die Formate in diesem Zeitraum", "", "Ein Format ist eine feste Bauform, kein Thema. Die konkreten Themen legt Dejan bei der Produktion fest.", "", tabelle(["Format", "Was es ist", "Funnel", "Wie oft"], zeilen), ""); } if (ideen && PLAN.ideen?.length) { teile.push("## Weitere Ideen zum Thema", "", "Diese Ideen passen auch zu Meister & Nerds. Wir greifen sie auf, wenn ein Format nicht zündet oder ein Slot frei wird.", "", tabelle(["Idee", "Was passiert", "Funnel"], PLAN.ideen.map((i) => [`**${i.name}**`, i.text, FUNNEL_NAME[i.funnel]])), ""); } return { md: teile.join("\n").trimEnd(), anzahl: posts.length, mix: mix(posts), reels: mix(nurReels(posts)) }; } async function exportBauen({ von, bis, format, ziel, ideen = false }) { const stand = datumLang(PLAN.stand); const titel = `Content-Plan ${zeitraumText(von, bis)}`; const { md: rumpfMd, anzahl, mix: m, reels: r } = exportMarkdown(von, bis, ideen); const funnelText = r.n ? `, bei den Reels Funnel ${mixText(r)}` : m.n ? `, Funnel: ${mixText(m)}` : ""; const text = `Welcher Beitrag wann auf welchem Kanal erscheint. ${anzahl} ${anzahl === 1 ? "Beitrag" : "Beiträge"}${funnelText}. Thema: ${PLAN.thema.name}.`; if (format === "md") { writeFileSync(ziel, [`# HiveGrid: ${titel}`, "", `**Stand:** ${stand}, von Dejan Cosic`, "", text, "", rumpfMd, ""].join("\n")); return anzahl; } const require = createRequire(import.meta.url); const { marked } = require(pfad("Dashboard/vendor/marked.min.js")); const b64 = (p) => readFileSync(pfad(p)).toString("base64"); let rumpf = kalenderHtml(von, bis) + marked.parse(rumpfMd, { gfm: true, breaks: true }); rumpf = rumpf.replace(//g, '
').replace(/<\/table>/g, "
"); const html = seite({ titel, stand, teile: [{ id: "plan", titel: "Content-Plan", text, rumpf }], schrift: b64("Dashboard/assets/fonts/manrope-latin.woff2"), schriftExt: b64("Dashboard/assets/fonts/manrope-latin-ext.woff2"), logo: b64("Dashboard/assets/logo-weiss.svg"), }); if (format === "html") { writeFileSync(ziel, html); return anzahl; } const arbeit = mkdtempSync(join(tmpdir(), "hivegrid-export-")); try { const datei = join(arbeit, "plan.html"); writeFileSync(datei, html); await pdfDrucken(datei, ziel); } finally { rmSync(arbeit, { recursive: true, force: true }); } return anzahl; } // ---------------------------------------------------------------- PDF // Chrome über das DevTools-Protokoll statt über --print-to-pdf. Mit dem // Kommandozeilen-Druck schrieb Chrome das PDF, beendete sich danach aber // nicht und blieb hängen. So gibt es genau eine Instanz, die nach dem Druck // samt aller Hilfsprozesse beendet wird, spätestens nach 60 Sekunden. async function pdfDrucken(htmlDatei, pdfDatei) { const profil = mkdtempSync(join(tmpdir(), "hivegrid-pdf-")); const chrome = spawn(CHROME, [ "--headless", "--disable-gpu", "--no-first-run", "--no-default-browser-check", "--remote-debugging-pipe", `--user-data-dir=${profil}`, "about:blank", ], { stdio: ["ignore", "ignore", "ignore", "pipe", "pipe"], detached: true }); let beendet = false; const beenden = () => { if (beendet) return; beendet = true; try { process.kill(-chrome.pid, "SIGKILL"); } catch { /* schon weg */ } rmSync(profil, { recursive: true, force: true }); }; const offen = new Map(); const warter = []; const abbrechen = (grund) => { for (const f of offen.values()) f({ error: { message: grund } }); offen.clear(); for (const w of warter.splice(0)) w.nein(new Error(grund)); }; const notbremse = setTimeout(() => { abbrechen("Zeitgrenze von 60 Sekunden erreicht"); beenden(); }, 60000); chrome.on("exit", () => abbrechen("Chrome wurde beendet")); try { const raus = chrome.stdio[3]; let puffer = ""; let n = 0; chrome.stdio[4].on("data", (stueck) => { puffer += stueck.toString(); let i; while ((i = puffer.indexOf("\0")) >= 0) { const m = JSON.parse(puffer.slice(0, i)); puffer = puffer.slice(i + 1); if (m.id && offen.has(m.id)) { offen.get(m.id)(m); offen.delete(m.id); continue; } const w = warter.findIndex((x) => x.passt(m)); if (w >= 0) warter.splice(w, 1)[0].ok(m); } }); const senden = (method, params = {}, sessionId) => new Promise((ok, nein) => { const id = ++n; offen.set(id, (m) => (m.error ? nein(new Error(`${method}: ${m.error.message}`)) : ok(m.result))); raus.write(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) }) + "\0"); }); const warten = (passt) => new Promise((ok, nein) => warter.push({ passt, ok, nein })); const { targetId } = await senden("Target.createTarget", { url: "about:blank" }); const { sessionId } = await senden("Target.attachToTarget", { targetId, flatten: true }); await senden("Page.enable", {}, sessionId); const geladen = warten((m) => m.method === "Page.loadEventFired" && m.sessionId === sessionId); await senden("Page.navigate", { url: pathToFileURL(htmlDatei).href }, sessionId); await geladen; await senden("Runtime.evaluate", { expression: "document.fonts.ready.then(() => true)", awaitPromise: true }, sessionId); const { data } = await senden("Page.printToPDF", { printBackground: true, preferCSSPageSize: true }, sessionId); writeFileSync(pdfDatei, Buffer.from(data, "base64")); } finally { clearTimeout(notbremse); beenden(); } } // Welche Art Beitrag ein Slot ist. Gleiche Regel wie im Dashboard (hilfen.js). function art(s) { const k = s.kanaele; if (k.includes("intern")) return "intern"; if (k.includes("Instagram Stories")) return "story"; if (k.includes("LinkedIn")) return "linkedin"; if (k.includes("TikTok") || k.includes("YouTube Shorts")) return "reel"; return "carousel"; } // Der Kalender für den Zeitraum, mit den einfachen Namen statt Codes. // Tage außerhalb des Zeitraums bleiben leer und grau. function kalenderHtml(von, bis) { const posts = noahPosts(von, bis); const esc = (s) => String(s).replace(/&/g, "&").replace(/= von) { zeilen += `KW ${kw(V.von)}${esc(V.titel)}${spanne(V.von, V.bis)}${V.punkte.map((x) => `${esc(x.chip)}`).join("")}`; } // Die Vorbereitungswoche hat ihre eigene Zeile, die Wochen danach folgen. const start = V.von <= bis && V.bis >= von ? plus(V.bis, 1) : von; for (let m = montag(start); m <= bis; m = plus(m, 7)) { const info = PLAN.wochen.find((w) => w.kw === kw(m)) || {}; const titel = info.noah ?? info.titel; let zellen = ""; for (let i = 0; i < 7; i++) { const d = plus(m, i); const drin = d >= von && d <= bis; const amTagListe = drin ? posts.filter((s) => amTag(s, d)) : []; zellen += `${ttmm(d)}${amTagListe.map((s) => `${esc(wasErscheint(s, "noah_chip"))}`).join("")}`; } zeilen += `KW ${kw(m)}${titel ? `${esc(titel)}` : ""}${zellen}`; } return `

Auf einen Blick

Carousel: Instagram, Facebook Reel: Instagram, TikTok, Facebook${bis >= "2026-11-09" ? ", ab 09.11. auch YouTube Shorts" : ""} LinkedIn${posts.some((s) => art(s) === "story") ? ` Stories` : ""}${zeilen.includes("vorb-zelle") ? ` Vorbereitung` : ""}

${zeilen}
MoDiMiDoFrSaSo
`; } function seite({ titel, stand, teile, schrift, schriftExt, logo }) { const esc = (s) => String(s).replace(/&/g, "&").replace(/ ` .kal{break-inside:avoid;margin:6px 0 20px} .kal .tab{border:0;border-radius:0} .kal table{table-layout:fixed;font-size:${gross ? "12px" : "7.6pt"}} .kal th{background:#30313D;color:#fff;padding:${gross ? "6px 8px" : "4px 5px"};white-space:normal} .kal thead th:first-child,.kal tbody th{width:${gross ? "96px" : "62px"}} .kal thead th:nth-child(7),.kal thead th:nth-child(8){width:${gross ? "64px" : "56px"}} .kal tbody th{background:#F4F4F6;color:#1A1A1A;vertical-align:top;text-align:left;font-weight:800} .kal tbody th span{display:block;font-weight:600;color:#8a6200;font-size:${gross ? "11px" : "6.8pt"};line-height:1.25;margin-top:2px} .kal td{padding:3px 3px 5px;height:${gross ? "62px" : "46px"};border:1px solid #E6E6E6;background:#fff !important;vertical-align:top} .kal td.we{background:#FAFAFA !important} .kal td.aus{background:#F1F1EE !important}.kal td.aus .dt{color:#C8C8C2} .kal .dt{display:block;color:#999;font-size:${gross ? "10.5px" : "6.6pt"};margin-bottom:2px} .kal .k{display:block;border-radius:4px;padding:1px 5px;margin-top:3px;font-weight:700;font-size:${gross ? "11.5px" : "7pt"};line-height:1.4;white-space:nowrap;overflow:hidden;text-overflow:ellipsis} .kal .carousel{background:#F1B729;color:#1A1A1A}.kal .reel{background:#30313D;color:#fff}.kal .linkedin{background:#0A66C2;color:#fff} .kal .story{background:#fff;color:#C13584;box-shadow:inset 0 0 0 1px #C13584} .kal .wichtig{box-shadow:0 0 0 2px #1A1A1A} .kal td.vorb-zelle{height:auto;background:#FFFCF2 !important} .kal .vorb{display:inline-block;margin-right:6px;background:#FFF5D6;color:#7a5600;box-shadow:inset 0 0 0 1px #E9C46A} .kal-legende{font-size:${gross ? "12.5px" : "8pt"};color:#555;margin:0 0 8px} .kal-legende i{display:inline-block;width:10px;height:10px;border-radius:2px;margin:0 4px 0 12px;vertical-align:-1px} .kal-legende span{white-space:nowrap;margin-right:12px}.kal-legende i{margin-left:0 !important} .kal-legende i.carousel{background:#F1B729}.kal-legende i.reel{background:#30313D}.kal-legende i.linkedin{background:#0A66C2}.kal-legende i.story{box-shadow:inset 0 0 0 1px #C13584}.kal-legende i.vorb{background:#FFF5D6;box-shadow:inset 0 0 0 1px #E9C46A}`; return ` HiveGrid, ${esc(titel)}
HiveGrid
${esc(titel)}Stand ${stand}, von Dejan
${teile.length > 1 ? `` : ""}
${teile.map((t, i) => `
${teile.length > 1 ? `

${esc(t.titel)}

` : ""}

${esc(t.text)}

${t.rumpf}
${i > 0 ? `← ${esc(teile[i - 1].titel)}` : ""}${i < teile.length - 1 ? `Weiter: ${esc(teile[i + 1].titel)} →` : ""}
`).join("\n")}
`; } // ---------------------------------------------------------------- Ablauf pruefen(); for (const h of hinweise) console.error(`Hinweis: ${h}`); if (fehler.length) { for (const f of fehler) console.error(`Fehler: ${f}`); process.exit(1); } if (EXPORT) { const iso = /^\d{4}-\d{2}-\d{2}$/; if (!iso.test(OPT.von) || !iso.test(OPT.bis) || OPT.von > OPT.bis || !["pdf", "html", "md"].includes(OPT.format)) { console.error("Fehler: Zeitraum oder Format ungültig"); process.exit(2); } const anzahl = await exportBauen({ von: OPT.von, bis: OPT.bis, format: OPT.format, ziel: OPT.ziel, ideen: IDEEN }); console.log(`${anzahl} Beiträge, ${(statSync(OPT.ziel).size / 1024).toFixed(0)} KB`); } else { const geaendert = markdownAktualisieren(); const was = PRUEFEN ? "Markdown nicht aktuell (nur geprüft)" : "Markdown aktualisiert"; console.log(geaendert.length ? `${was}: ${geaendert.join(", ")}` : "Markdown war aktuell"); }