SPB Git

Repository Public

Job.tsx 12.1 KB 192 lines tsx

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/Job.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, type ReactNode } from 'react';43import { get, goToOtherApp, post } from '../../../shared/api.ts';44import { usePrefs } from '../prefs.tsx';45import { useSession } from '../session.tsx';46import { Link } from '../router.tsx';47import type { JobDetail, Receipt } from '../types.ts';48import { ActionStatus, Await, Empty, ExtLink, Field, Hash, JsonView, KV, Notice, PageHead, Panel, TableWrap, Tag, useAction, useLoad } from '../ui/core.tsx';49import { Preview, useMediaIndex } from '../ui/Preview.tsx';5051export function JobDetailScreen({ id }: { id: string }) {52  const { t } = usePrefs();53  const d = useLoad(() => get<JobDetail>(`/v1/jobs/${id}`), [id]);54  return (55    <>56      <p className="crumb"><Link to="/calendar">{t('nav.calendar')}</Link></p>57      <Await of={d}>{(data) => <Body d={data} reload={d.reload} />}</Await>58    </>59  );60}6162function Body({ d, reload }: { d: JobDetail; reload: () => void }) {63  const { t, tl, dt } = usePrefs();64  const s = useSession();65  const { job } = d;66  const tz = s.brandById(job.brand_id)?.timezone;67  const media = useMediaIndex(job.brand_id);68  const nav = useAction();69  return (70    <>71      <PageHead title={job.title ?? t('jb.title')} lead={<><Tag prefix="jobState" value={job.state} /> {job.state_reason}</>}><button type="button" onClick={reload}>{t('c.reload')}</button></PageHead>72      {d.notice ? <Notice tone="warn"><p><strong>{d.notice}</strong></p></Notice> : null}73      <div className="split">74        <div>75          <Panel title={t('jb.summary')}>76            <KV rows={[77              [t('c.state'), <Tag prefix="jobState" value={job.state} />],78              [t('jb.reason'), job.state_reason || '—'],79              [t('dash.col.when'), <>{dt(job.scheduled_at, tz)} <span className="small">· {t('c.utc')} <code>{job.scheduled_at}</code></span></>],80              [t('dash.col.mode'), <><strong>{tl('mode', job.mode)}</strong> <span className="small">{tl('modeHelp', job.mode)}</span></>],81              [t('c.page'), <>{job.page_name} {job.page_url ? <ExtLink href={job.page_url} /> : null} <span className="small">({job.platform})</span></>],82              [t('jb.content'), <Link to={`/content/${job.content_id}`}>{job.title}</Link>],83              [t('sch.approvedHash'), <Hash value={job.content_hash} full />],84              [t('jb.prepareAttempts'), String(job.prepare_attempts)],85              ...(job.dead_letter ? [[t('jb.deadLetter'), t('jb.deadLetterYes')] as [string, string]] : []),86              ...(job.cancel_requested_at ? [[t('jb.cancelRequested'), dt(job.cancel_requested_at, tz)] as [string, string]] : []),87              [t('c.id'), <Hash value={job.id} full />],88            ]} />89          </Panel>90          <Actions d={d} reload={reload} />91          {s.isAdmin ? <p><button type="button" onClick={() => nav.run(() => goToOtherApp('navigator'))} disabled={nav.busy}>{t('ss.openNavigator')}</button></p> : null}92          <ActionStatus a={nav} />93        </div>94        <Preview content={d.content} media={media} pageName={job.page_name} hash={job.content_hash} />95      </div>96      <Panel title={t('jb.receipts')}>97        {d.receipts.length === 0 ? <Empty>{t('jb.noReceipts')}</Empty> : <ul className="plain stack">{d.receipts.map((r) => <ReceiptRow key={r.id} r={r} tz={tz} />)}</ul>}98      </Panel>99      <Panel title={t('jb.attempts')}>100        {d.attempts.length === 0 ? <Empty>{t('jb.noAttempts')}</Empty> : (101          <TableWrap caption={t('jb.attempts')}>102            <thead><tr><th scope="col">#</th><th scope="col">{t('jb.phase')}</th><th scope="col">{t('jb.started')}</th><th scope="col">{t('jb.ended')}</th><th scope="col">{t('jb.outcome')}</th><th scope="col">{t('jb.error')}</th><th scope="col">{t('jb.steps')}</th></tr></thead>103            <tbody>{d.attempts.map((a) => (104              <tr key={a.id}><th scope="row">{a.n}</th><td><code>{a.phase}</code></td><td>{dt(a.started_at, tz)}</td><td>{a.ended_at ? dt(a.ended_at, tz) : '—'}</td><td>{a.outcome ?? '—'}</td><td>{a.error ? <code>{a.error}</code> : '—'}</td>105                <td>{Array.isArray(a.steps) && a.steps.length ? <details><summary>{t('jb.stepsCount', { n: a.steps.length })}</summary><JsonView value={a.steps} /></details> : '—'}</td></tr>106            ))}</tbody>107          </TableWrap>108        )}109      </Panel>110    </>111  );112}113114function ReceiptRow({ r, tz }: { r: Receipt; tz?: string }) {115  const { t, dt } = usePrefs();116  return (117    <li className="card">118      <div className="card-head"><h3>{t(`jb.receipt.${r.kind}` as 'jb.receipt.observed')}</h3><span className="small">{dt(r.created_at, tz)}</span></div>119      {r.kind === 'human_attested' ? <p><Tag prefix="jb.attested" value="human" tone="hold" /></p> : null}120      <KV rows={[121        ...(r.label ? [[t('jb.label'), r.label] as [string, string]] : []),122        [t('jb.externalUrl'), r.external_url ? <ExtLink href={r.external_url} /> : '—'],123        ...(r.external_id ? [[t('pg.externalId'), <code>{r.external_id}</code>] as [string, ReactNode]] : []),124        ...(r.evidence_sha256 ? [['sha256', <Hash value={r.evidence_sha256} full />] as [string, ReactNode]] : []),125      ]} />126      {r.evidence_url ? <figure className="evidence"><a href={r.evidence_url} target="_blank" rel="noopener noreferrer"><img src={r.evidence_url} alt={t('jb.evidenceAlt', { label: r.label || r.kind })} loading="lazy" /></a><figcaption>{t('jb.evidenceCaption')}</figcaption></figure> : null}127    </li>128  );129}130131function Actions({ d, reload }: { d: JobDetail; reload: () => void }) {132  const { t } = usePrefs();133  const s = useSession();134  const { job } = d;135  const a = useAction();136  const [url, setUrl] = useState('');137  const [armed, setArmed] = useState<'' | 'cancel' | 'authorize'>('');138  const [outcome, setOutcome] = useState<'published' | 'not_published'>('published');139  const [note, setNote] = useState('');140  const [cancelRes, setCancelRes] = useState<{ cancelled: boolean; afterSubmission: boolean; state: string } | null>(null);141  const urlOk = !url.trim() || /^https?:\/\/\S+$/i.test(url.trim());142  const terminal = ['VERIFIED', 'FAILED', 'CANCELLED'].includes(job.state);143  const confirm = async (action: 'human_published' | 'authorize_submit') => { setArmed(''); if (await a.run(() => post(`/v1/jobs/${job.id}/confirm`, { action, externalUrl: action === 'human_published' ? url.trim() || null : null }), t('c.saved'))) reload(); };144  const cancel = async () => { setArmed(''); const r = await a.run(() => post<NonNullable<typeof cancelRes>>(`/v1/jobs/${job.id}/cancel`)); if (r) { setCancelRes(r); reload(); } };145  const reconcile = async () => { if (await a.run(() => post(`/v1/jobs/${job.id}/reconcile`, { outcome, externalUrl: outcome === 'published' ? url.trim() || null : null, note: note.trim() }), t('c.saved'))) reload(); };146  return (147    <Panel title={t('jb.actions')}>148      {!s.isAdmin ? <p className="small">{t('c.brandRoleHint')}</p> : null}149      {job.state === 'AWAITING_CONFIRMATION' ? (150        <form className="form" onSubmit={(e) => { e.preventDefault(); if (urlOk) void confirm('human_published'); }}>151          <h3>{t('jb.human.title')}</h3>152          <p>{t('jb.human.lead')}</p>153          <Field label={`${t('jb.externalUrl')} (${t('c.optional')})`} hint={urlOk ? undefined : t('ed.linkInvalid')} wide><input type="url" value={url} onChange={(e) => setUrl(e.target.value)} maxLength={1000} aria-invalid={!urlOk} /></Field>154          <div className="row"><button type="submit" className="primary" disabled={a.busy || !urlOk}>{t('jb.human.go')}</button></div>155          {job.mode === 'auto_submit' ? (<>156            <h3>{t('jb.auth.title')}</h3>157            <p>{t('jb.auth.lead')}</p>158            {armed === 'authorize' ? <div className="row"><button type="button" className="danger" onClick={() => confirm('authorize_submit')} disabled={a.busy}>{t('jb.auth.confirm')}</button><button type="button" onClick={() => setArmed('')}>{t('c.cancel')}</button></div>159              : <div className="row"><button type="button" onClick={() => setArmed('authorize')} disabled={a.busy}>{t('jb.auth.go')}</button></div>}160          </>) : <p className="small">{t('jb.auth.unavailable')}</p>}161        </form>162      ) : null}163      {job.state === 'UNKNOWN_OUTCOME' ? (164        <form className="form" onSubmit={(e) => { e.preventDefault(); if (urlOk) void reconcile(); }}>165          <h3>{t('jb.rec.title')}</h3>166          <Notice tone="warn"><p><strong>{t('jb.rec.never')}</strong> {t('jb.rec.lead')}</p></Notice>167          <fieldset><legend>{t('jb.rec.outcome')}</legend>168            <label className="check"><input type="radio" name="outcome" checked={outcome === 'published'} onChange={() => setOutcome('published')} /><span>{t('jb.rec.published')}</span></label>169            <label className="check"><input type="radio" name="outcome" checked={outcome === 'not_published'} onChange={() => setOutcome('not_published')} /><span>{t('jb.rec.notPublished')}</span></label>170          </fieldset>171          {outcome === 'published' ? <Field label={`${t('jb.externalUrl')} (${t('c.optional')})`} hint={urlOk ? undefined : t('ed.linkInvalid')} wide><input type="url" value={url} onChange={(e) => setUrl(e.target.value)} maxLength={1000} aria-invalid={!urlOk} /></Field> : null}172          <Field label={`${t('c.note')} (${t('c.optional')})`} wide><textarea value={note} onChange={(e) => setNote(e.target.value)} rows={2} maxLength={1000} /></Field>173          <div className="row"><button type="submit" className="primary" disabled={a.busy || !urlOk}>{t('jb.rec.go')}</button></div>174        </form>175      ) : null}176      {!terminal ? (<>177        <h3>{t('jb.cancel.title')}</h3>178        <p>{['SUBMITTED', 'UNKNOWN_OUTCOME'].includes(job.state) ? t('jb.cancel.after') : t('jb.cancel.before')}</p>179        {armed === 'cancel' ? <div className="row"><button type="button" className="danger" onClick={cancel} disabled={a.busy}>{t('jb.cancel.confirm')}</button><button type="button" onClick={() => setArmed('')}>{t('c.back')}</button></div>180          : <div className="row"><button type="button" onClick={() => setArmed('cancel')} disabled={a.busy}>{t('jb.cancel.go')}</button></div>}181      </>) : job.state !== 'AWAITING_CONFIRMATION' && job.state !== 'UNKNOWN_OUTCOME' ? <Empty>{t('jb.noAction')}</Empty> : null}182      {cancelRes ? (183        <div className={cancelRes.afterSubmission ? 'note note-warn' : 'note note-info'} role="status">184          <p><strong>{cancelRes.afterSubmission ? t('jb.cancel.resAfter') : cancelRes.cancelled ? t('jb.cancel.resOk') : t('jb.cancel.resNo')}</strong></p>185          {cancelRes.afterSubmission ? <p>{t('jb.cancel.resAfter2')}</p> : null}186        </div>187      ) : null}188      <ActionStatus a={a} />189    </Panel>190  );191}192
Files main
Menu

Theme