Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr Social Engine & Remote Navigator8 * File : services/control-api/src/core/content.ts9 * Module : core10 * Repository : https://git.spboucher.ai/maclustr-social11 * Project Website : https://social.spboucher.ai12 * Created : 2026-12-0113 * Last Modified : 2026-12-0114 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142import { createHash } from 'node:crypto';43import { canonicalContent, type ContentPayload } from '@mls/contracts';44import { canApprove, type ActorRef } from '@mls/policy-engine';45import type { Tx } from '../db.ts';46import { audit, type Actor } from '../audit.ts';47import { bad, conflict, forbidden, notFound } from './errors.ts';4849export const contentHash = (p: ContentPayload) => createHash('sha256').update(canonicalContent(p)).digest('hex');50export const rowToPayload = (v: any): ContentPayload => ({ lang: v.lang, body: v.body, linkUrl: v.link_url, mediaSha256: v.media_sha256, altText: v.alt_text });5152async function checkMedia(tx: Tx, brandId: string, shas: string[]) {53 if (!shas.length) return;54 const n = (await tx.query("SELECT count(*)::int AS n FROM media_assets WHERE brand_id=$1 AND sha256 = ANY($2) AND status IN ('pending','approved')", [brandId, shas])).rows[0].n;55 if (n !== new Set(shas).size) throw bad('media_unknown', 'Un média référencé est introuvable dans cette marque.');56}57async function addVersion(tx: Tx, contentId: string, p: ContentPayload, author: Actor) {58 const version = ((await tx.query('SELECT coalesce(max(version),0) AS v FROM content_versions WHERE content_id=$1', [contentId])).rows[0].v as number) + 1;59 const v = (await tx.query('INSERT INTO content_versions(content_id, version, lang, body, link_url, media_sha256, alt_text, content_hash, author_kind, author_id) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10) RETURNING *',60 [contentId, version, p.lang, p.body, p.linkUrl, p.mediaSha256, p.altText, contentHash(p), author.kind === 'agent' ? 'agent' : 'user', author.id])).rows[0];61 await tx.query('UPDATE content_items SET current_version_id=$2, updated_at=now() WHERE id=$1', [contentId, v.id]);62 return v;63}64export async function createContent(tx: Tx, a: { brandId: string; pageId: string | null; campaignId: string | null; title: string; payload: ContentPayload; sourceEventId: string | null }, author: Actor, creatorUserId: string | null, correlationId?: string) {65 await checkMedia(tx, a.brandId, a.payload.mediaSha256);66 const item = (await tx.query('INSERT INTO content_items(brand_id, page_id, campaign_id, title, source_event_id, created_by) VALUES ($1,$2,$3,$4,$5,$6) RETURNING *', [a.brandId, a.pageId, a.campaignId, a.title, a.sourceEventId, creatorUserId])).rows[0];67 const v = await addVersion(tx, item.id, a.payload, author);68 await audit(tx, { correlationId, actor: author, action: 'content.create', targetKind: 'content', targetId: item.id, brandId: a.brandId, result: 'ok', detail: { version: 1, hash: v.content_hash } });69 return { ...item, current_version_id: v.id, version: v };70}71/** Any change to the text, media, link or page voids approvals and cancels jobs that have not touched the platform yet. */72export async function updateContent(tx: Tx, id: string, patch: { title?: string; pageId?: string | null; payload?: ContentPayload }, author: Actor, correlationId?: string) {73 const item = (await tx.query('SELECT * FROM content_items WHERE id=$1 FOR UPDATE', [id])).rows[0];74 if (!item) throw notFound('contenu');75 let changed = false; let v: any = null;76 if (patch.payload) {77 const cur = (await tx.query('SELECT * FROM content_versions WHERE id=$1', [item.current_version_id])).rows[0];78 if (contentHash(patch.payload) !== cur.content_hash) { await checkMedia(tx, item.brand_id, patch.payload.mediaSha256); v = await addVersion(tx, id, patch.payload, author); changed = true; }79 }80 if (patch.pageId !== undefined && patch.pageId !== item.page_id) { await tx.query('UPDATE content_items SET page_id=$2 WHERE id=$1', [id, patch.pageId]); changed = true; }81 if (patch.title) await tx.query('UPDATE content_items SET title=$2, updated_at=now() WHERE id=$1', [id, patch.title]);82 if (changed) await invalidate(tx, id, item.brand_id, 'contenu ou page modifié', author, correlationId);83 return { changed, version: v };84}85export async function invalidate(tx: Tx, contentId: string, brandId: string, reason: string, actor: Actor, correlationId?: string) {86 const inv = await tx.query('UPDATE approvals SET invalidated_at=now(), invalidated_reason=$2 WHERE content_id=$1 AND invalidated_at IS NULL', [contentId, reason]);87 await tx.query("UPDATE content_items SET state='DRAFT', updated_at=now() WHERE id=$1", [contentId]);88 const jobs = await tx.query("UPDATE publication_jobs SET state='CANCELLED', state_reason=$2, updated_at=now() WHERE content_id=$1 AND state IN ('QUEUED','PREPARING') AND NOT EXISTS (SELECT 1 FROM job_attempts a WHERE a.job_id=publication_jobs.id AND a.phase='submitting') RETURNING id", [contentId, `approbation invalidée : ${reason}`]);89 // A job already waiting on a human keeps its state but loses its approval: preflight will refuse it.90 await audit(tx, { correlationId, actor, action: 'approval.invalidate', targetKind: 'content', targetId: contentId, brandId, result: 'ok', detail: { reason, approvals: inv.rowCount, cancelledJobs: jobs.rows.map((r) => r.id) } });91}92export async function submitForReview(tx: Tx, id: string, actor: Actor, correlationId?: string) {93 const item = (await tx.query('SELECT * FROM content_items WHERE id=$1 FOR UPDATE', [id])).rows[0];94 if (!item) throw notFound('contenu');95 if (item.state !== 'DRAFT') throw conflict('not_draft', 'Seul un brouillon peut être soumis.');96 if (!item.page_id) throw bad('page_required', 'Associez une page avant la révision.');97 await tx.query("UPDATE content_items SET state='REVIEW', updated_at=now() WHERE id=$1", [id]);98 await audit(tx, { correlationId, actor, action: 'content.submit_review', targetKind: 'content', targetId: id, brandId: item.brand_id, result: 'ok' });99}100/** Approval is bound to (version, content hash, page). The caller proves what they looked at by sending all three. */101export async function decide(tx: Tx, id: string, input: { versionId: string; contentHash: string; pageId: string; decision: 'approve' | 'reject'; comment: string }, actor: ActorRef, brandRole: any, correlationId?: string) {102 const item = (await tx.query('SELECT c.*, b.validation FROM content_items c JOIN brands b ON b.id=c.brand_id WHERE c.id=$1 FOR UPDATE OF c', [id])).rows[0];103 if (!item) throw notFound('contenu');104 const a: Actor = { kind: actor.kind, id: actor.id };105 const deny = async (code: string, msg: string) => { await audit(tx, { correlationId, actor: a, action: 'content.approve', targetKind: 'content', targetId: id, brandId: item.brand_id, result: 'denied', detail: { code } }); return code === 'stale_approval' ? conflict(code, msg) : forbidden(code, msg); };106 const cur = (await tx.query('SELECT * FROM content_versions WHERE id=$1', [item.current_version_id])).rows[0];107 if (item.state !== 'REVIEW') throw conflict('not_in_review', 'Le contenu doit être en révision.');108 if (cur.id !== input.versionId || cur.content_hash !== input.contentHash || item.page_id !== input.pageId) { const e = await deny('stale_approval', 'Le contenu ou la page a changé depuis votre aperçu.'); return { error: e }; }109 const firstAuthor = (await tx.query("SELECT author_id FROM content_versions WHERE content_id=$1 AND author_kind='user' ORDER BY version DESC LIMIT 1", [id])).rows[0]?.author_id ?? item.created_by ?? '';110 const can = canApprove(actor, { authorId: firstAuthor, allowSelfApproval: !!item.validation.allowSelfApproval, brandRole });111 if (!can.allow) { const e = await deny(can.reason, 'Approbation refusée par la politique.'); return { error: e }; }112 const page = (await tx.query('SELECT status FROM pages WHERE id=$1', [input.pageId])).rows[0];113 if (page?.status !== 'confirmed') { const e = await deny('page_not_confirmed', "La page n'est pas confirmée."); return { error: e }; }114 if (input.decision === 'approve') {115 const unapproved = (await tx.query("SELECT count(*)::int AS n FROM media_assets WHERE brand_id=$1 AND sha256 = ANY($2) AND status <> 'approved'", [item.brand_id, cur.media_sha256])).rows[0].n;116 if (unapproved) { const e = await deny('media_not_approved', 'Un média joint n’a pas ses droits validés.'); return { error: e }; }117 const blocked = (await tx.query("SELECT agent FROM agent_runs WHERE target_kind='content_version' AND target_id=$1 AND status='blocked' AND agent IN ('fact_checker','compliance') AND NOT EXISTS (SELECT 1 FROM agent_runs r2 WHERE r2.target_id=agent_runs.target_id AND r2.agent=agent_runs.agent AND r2.started_at > agent_runs.started_at AND r2.status='ok')", [cur.id])).rows;118 if (blocked.length) { const e = await deny('blocked_by_agent', `Bloqué par : ${blocked.map((b) => b.agent).join(', ')}`); return { error: e }; }119 }120 if ((await tx.query('SELECT 1 FROM approvals WHERE content_id=$1 AND version_id=$2 AND approver_id=$3 AND invalidated_at IS NULL', [id, cur.id, actor.id])).rowCount) throw conflict('already_decided', 'Vous avez déjà statué sur cette version.');121 const ap = (await tx.query('INSERT INTO approvals(content_id, version_id, content_hash, page_id, approver_id, decision, comment) VALUES ($1,$2,$3,$4,$5,$6,$7) RETURNING *', [id, cur.id, cur.content_hash, input.pageId, actor.id, input.decision, input.comment])).rows[0];122 let state = 'REVIEW';123 if (input.decision === 'reject') state = 'DRAFT';124 else {125 const n = (await tx.query("SELECT count(DISTINCT approver_id)::int AS n FROM approvals WHERE content_id=$1 AND version_id=$2 AND decision='approve' AND invalidated_at IS NULL", [id, cur.id])).rows[0].n;126 if (n >= (item.validation.approvalsRequired ?? 1)) state = 'APPROVED';127 }128 await tx.query('UPDATE content_items SET state=$2, updated_at=now() WHERE id=$1', [id, state]);129 await audit(tx, { correlationId, actor: a, action: `content.${input.decision}`, targetKind: 'content', targetId: id, brandId: item.brand_id, result: 'ok', detail: { versionId: cur.id, hash: cur.content_hash, pageId: input.pageId, state } });130 return { approval: ap, state };131}132