Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr Social Engine & Remote Navigator8 * File : apps/social-web/src/screens/Comments.tsx9 * Module : screens10 * 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 { useState } from 'react';43import { get, post } from '../../../shared/api.ts';44import { usePrefs } from '../prefs.tsx';45import { brandQuery, useSession } from '../session.tsx';46import type { AgentRunResult, CommentRow, Lang2, Page, ReplyDraft } from '../types.ts';47import { ActionStatus, Await, Empty, ErrorNote, Field, Notice, PageHead, Panel, Tag, useAction, useLoad } from '../ui/core.tsx';4849async function refOf(body: string): Promise<string> {50 const h = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(body.normalize('NFC')));51 return 'paste:' + [...new Uint8Array(h)].slice(0, 12).map((b) => b.toString(16).padStart(2, '0')).join('');52}5354export function Comments() {55 const { t } = usePrefs();56 const s = useSession();57 const list = useLoad(() => get<{ comments: CommentRow[] }>(`/v1/comments${brandQuery(s.brandId)}`), [s.brandId]);58 const pages = useLoad(() => get<{ pages: Page[] }>(`/v1/pages${brandQuery(s.brandId)}`), [s.brandId]);59 const [status, setStatus] = useState('');60 const pageName = (id: string) => pages.data?.pages.find((p) => p.id === id)?.display_name ?? '—';61 return (62 <>63 <PageHead title={t('cm.title')} lead={t('cm.lead')}><button type="button" onClick={list.reload} disabled={list.loading}>{t('c.reload')}</button></PageHead>64 <Notice><p><strong>{t('cm.neverPosted')}</strong> {t('cm.neverPosted2')}</p></Notice>65 <Import pages={pages.data?.pages ?? []} error={pages.error} onDone={list.reload} />66 <div className="filters"><Field label={t('c.status')}><select value={status} onChange={(e) => setStatus(e.target.value)}><option value="">{t('c.all')}</option>{['open', 'human_required', 'drafted', 'closed'].map((x) => <option key={x} value={x}>{t(`commentStatus.${x}` as 'commentStatus.open')}</option>)}</select></Field></div>67 <Await of={list}>{(d) => {68 const rows = d.comments.filter((c) => !status || c.status === status);69 return rows.length === 0 ? <Empty>{d.comments.length === 0 ? t('cm.empty') : t('cm.emptyFilter')}</Empty> : <ul className="plain stack">{rows.map((c) => <CommentCard key={c.id} c={c} pageName={pageName(c.page_id)} tz={s.brandById(c.brand_id)?.timezone} reload={list.reload} />)}</ul>;70 }}</Await>71 </>72 );73}7475function Import({ pages, error, onDone }: { pages: Page[]; error: unknown; onDone: () => void }) {76 const { t } = usePrefs();77 const [pageId, setPageId] = useState('');78 const [text, setText] = useState('');79 const [res, setRes] = useState<{ imported: number; sent: number } | null>(null);80 const a = useAction();81 const blocks = text.split(/\r?\n\s*\r?\n/).map((b) => b.trim()).filter(Boolean);82 const tooLong = blocks.some((b) => b.length > 5000);83 const send = async () => {84 setRes(null);85 const r = await a.run(async () => post<{ imported: number }>('/v1/comments/import', { pageId, items: await Promise.all(blocks.map(async (body) => ({ externalRef: await refOf(body), body }))) }));86 if (r) { setRes({ imported: r.imported, sent: blocks.length }); setText(''); onDone(); }87 };88 return (89 <Panel title={t('cm.import')}>90 <p className="small">{t('cm.importLead')}</p>91 <ErrorNote error={error} />92 <form className="form" onSubmit={(e) => { e.preventDefault(); void send(); }}>93 <Field label={t('c.page')}><select value={pageId} onChange={(e) => setPageId(e.target.value)} required><option value="">{t('c.select')}</option>{pages.map((p) => <option key={p.id} value={p.id}>{p.display_name}</option>)}</select></Field>94 <Field label={t('cm.paste')} hint={`${t('cm.pasteHint')} ${t('cm.blocks', { n: blocks.length })}${tooLong ? ` ${t('cm.tooLong')}` : ''}`} wide><textarea value={text} onChange={(e) => setText(e.target.value)} rows={6} required /></Field>95 <div className="row"><button type="submit" disabled={!pageId || blocks.length === 0 || blocks.length > 200 || tooLong || a.busy}>{t('cm.importGo')}</button></div>96 <ActionStatus a={a} />97 {res ? <p role="status">{t('cm.imported', { n: res.imported, sent: res.sent })}</p> : null}98 </form>99 </Panel>100 );101}102103function CommentCard({ c, pageName, tz, reload }: { c: CommentRow; pageName: string; tz?: string; reload: () => void }) {104 const { t, tl, dt, lang } = usePrefs();105 const a = useAction();106 const [run, setRun] = useState<AgentRunResult | null>(null);107 const [body, setBody] = useState('');108 const [dl, setDl] = useState<Lang2>(lang);109 const human = c.status === 'human_required' || c.sensitivity === 'sensitive';110 const closed = c.status === 'closed';111 const agent = async () => { setRun(null); const r = await a.run(() => post<AgentRunResult>('/v1/agents/run', { agent: 'community', commentId: c.id })); if (r) { setRun(r); reload(); } };112 const saveDraft = async () => { if (await a.run(() => post(`/v1/comments/${c.id}/drafts`, { body: body.trim(), lang: dl }), t('c.saved'))) { setBody(''); reload(); } };113 const decide = async (d: ReplyDraft, state: 'approved' | 'discarded' | 'posted_manually') => { if (await a.run(() => post(`/v1/reply-drafts/${d.id}/decide`, { state }), t('c.saved'))) reload(); };114 const close = async () => { if (await a.run(() => post(`/v1/comments/${c.id}/close`), t('c.saved'))) reload(); };115 const drafts = c.drafts ?? [];116 return (117 <li className="card">118 <div className="card-head">119 <p className="small">{pageName} · {dt(c.captured_at, tz)} · <code>{c.source}</code></p>120 <span className="row"><Tag prefix="sens" value={c.sensitivity} /><Tag prefix="commentStatus" value={c.status} /></span>121 </div>122 <blockquote className="quote pre">{c.body}</blockquote>123 {c.sensitivity_reasons.length ? <p className="small">{t('cm.reasons')} {c.sensitivity_reasons.join(' · ')}</p> : null}124 {human ? <Notice tone="warn"><p><strong>{t('cm.humanRequired')}</strong> {t('cm.humanRequired2')}</p></Notice> : null}125 {drafts.length ? (126 <ul className="plain drafts">{drafts.map((d) => (127 <li key={d.id}>128 <p className="small">{d.author_kind === 'agent' ? t('cm.draftAgent') : t('cm.draftHuman')} · {tl('c.lang', d.lang)} · {dt(d.created_at, tz)} <Tag prefix="draftState" value={d.state} /></p>129 <p className="pre">{d.body}</p>130 <div className="row">131 {d.state === 'draft' ? <button type="button" className="small-btn" disabled={a.busy} onClick={() => decide(d, 'approved')}>{t('cm.approve')}</button> : null}132 {d.state === 'draft' || d.state === 'approved' ? <button type="button" className="small-btn" disabled={a.busy} onClick={() => decide(d, 'discarded')}>{t('cm.discard')}</button> : null}133 {d.state === 'approved' ? <button type="button" className="small-btn" disabled={a.busy} onClick={() => decide(d, 'posted_manually')}>{t('cm.posted')}</button> : null}134 {d.state !== 'posted_manually' && !closed ? <button type="button" className="small-btn" onClick={() => { setBody(d.body); setDl(d.lang === 'en' ? 'en' : 'fr'); }}>{t('cm.reuse')}</button> : null}135 </div>136 </li>137 ))}</ul>138 ) : null}139 {!closed ? (140 <details className="more">141 <summary>{t('cm.write')}</summary>142 <form className="form" onSubmit={(e) => { e.preventDefault(); void saveDraft(); }}>143 <p className="small">{t('cm.editNote')}</p>144 <Field label={t('cm.replyBody')} wide><textarea value={body} onChange={(e) => setBody(e.target.value)} rows={3} maxLength={1200} required /></Field>145 <Field label={t('c.language')}><select value={dl} onChange={(e) => setDl(e.target.value as Lang2)}><option value="fr">{t('c.lang.fr')}</option><option value="en">{t('c.lang.en')}</option></select></Field>146 <div className="row"><button type="submit" disabled={!body.trim() || a.busy}>{t('cm.saveDraft')}</button></div>147 </form>148 </details>149 ) : null}150 <div className="row">151 {!closed ? <button type="button" onClick={agent} disabled={a.busy || human} aria-describedby={human ? `why-${c.id}` : undefined}>{t('cm.runAgent')}</button> : null}152 {!closed ? <button type="button" onClick={close} disabled={a.busy}>{t('cm.close')}</button> : null}153 </div>154 {human && !closed ? <p className="small" id={`why-${c.id}`}>{t('cm.agentBlocked')}</p> : null}155 <ActionStatus a={a} />156 {run ? (157 <div className="note note-info" role="status">158 <p><strong>{tl('agent', run.agent)}</strong> <Tag prefix="runStatus" value={run.status} /></p>159 {run.status === 'blocked' ? <p>{t('cm.agentRefused')} {Array.isArray(run.output?.reasons) ? run.output.reasons.join(' · ') : ''}</p> : null}160 {run.status === 'ok' ? <p>{t('cm.agentDrafted')}</p> : null}161 {run.output?.summary ? <p className="small">{String(run.output.summary)}</p> : null}162 {run.error ? <p><code>{run.error}</code></p> : null}163 {run.llm ? <p className="small"><code>{run.llm.model || '—'}</code> · <code>{run.llm.status}</code></p> : null}164 </div>165 ) : null}166 </li>167 );168}169