SPB Git

Repository Public

Statistics.tsx 12.4 KB 164 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/Statistics.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 { useMemo, useState } from 'react';43import { get, post } from '../../../shared/api.ts';44import { usePrefs } from '../prefs.tsx';45import { useSession } from '../session.tsx';46import { Link } from '../router.tsx';47import { DEFAULT_TZ, resolveLocal } from '../time.ts';48import type { BrandReport, ContentRow, Page, Snapshot } from '../types.ts';49import { ActionStatus, Await, Bars, Check, Empty, ErrorNote, Field, Notice, PageHead, Panel, TableWrap, Tag, useAction, useLoad } from '../ui/core.tsx';5051const METRICS = ['reach', 'impressions', 'interactions', 'reactions', 'comments', 'shares', 'link_clicks', 'followers'] as const;52type Metric = (typeof METRICS)[number];53/** A PostgreSQL numeric arrives as text; null stays null (unavailable is never zero). */54const numOrNull = (v: string | number | null | undefined): number | null => { if (v === null || v === undefined || v === '') return null; const n = Number(v); return Number.isFinite(n) ? n : null; };5556export function Statistics() {57  const { t, tl, dt, num } = usePrefs();58  const s = useSession();59  const [own, setOwn] = useState(s.brands.length === 1 ? s.brands[0].id : '');60  const brandId = s.brandId || own;61  const brand = s.brandById(brandId);62  const tz = brand?.timezone || DEFAULT_TZ;63  const metrics = useLoad(async () => (brandId ? (await get<{ snapshots: Snapshot[] }>(`/v1/metrics?brandId=${brandId}`)).snapshots : null), [brandId]);64  const report = useLoad(async () => (brandId ? get<BrandReport>(`/v1/reports/brand/${brandId}`) : null), [brandId]);65  const [metric, setMetric] = useState<Metric>('reach');66  const reload = () => { metrics.reload(); report.reload(); };67  const Value = ({ v }: { v: string | number | null }) => { const n = numOrNull(v); return n === null ? <em>{t('c.unavailable')}</em> : <>{num(n)}</>; };68  return (69    <>70      <PageHead title={t('st.title')} lead={t('st.lead')}>{brandId ? <button type="button" onClick={reload}>{t('c.reload')}</button> : null}</PageHead>71      {!s.brandId ? <div className="filters"><Field label={t('c.brand')}><select value={own} onChange={(e) => setOwn(e.target.value)}><option value="">{t('c.select')}</option>{s.brands.map((b) => <option key={b.id} value={b.id}>{b.name}</option>)}</select></Field></div> : null}72      {!brandId ? <Empty>{t('c.chooseBrand')}</Empty> : (<>73        <Await of={report}>{(r) => !r ? null : (<>74          <Panel title={t('st.caveats')}>75            <ul>{r.caveats.map((c, i) => <li key={i}>{c}</li>)}</ul>76            <p className="small">{t('st.generated', { date: dt(r.generatedAt, tz) })}</p>77          </Panel>78          <Panel title={t('st.compare')}>79            <p className="small">{t('st.compareNote')}</p>80            {r.campaigns.length === 0 ? <Empty>{t('st.noCampaign')}</Empty> : (<>81              <TableWrap caption={t('st.compare')}>82                <thead><tr><th scope="col">{t('st.campaign')}</th><th scope="col" className="num">{t('st.contents')}</th><th scope="col" className="num">{t('st.verified')}</th>{METRICS.map((m) => <th scope="col" className="num" key={m}>{tl('metric', m)}</th>)}</tr></thead>83                <tbody>{r.campaigns.map((c) => (84                  <tr key={c.id}><th scope="row"><Link to={`/campaigns/${c.id}`}>{c.name}</Link></th><td className="num">{num(c.contents)}</td><td className="num">{num(c.verified)}</td>85                    {METRICS.map((m) => { const p = r.perCampaign.find((x) => x.campaign_id === c.id && x.metric === m); const tot = p ? numOrNull(p.total) : null;86                      return <td className="num" key={m}>{!p ? <em>{t('st.noReading')}</em> : <>{tot === null ? <em>{t('c.unavailable')}</em> : num(tot)}<span className="cell-note">{t('st.readings', { n: p.n, missing: p.missing })}</span></>}</td>; })}87                  </tr>88                ))}</tbody>89              </TableWrap>90              <div className="filters"><Field label={t('st.chartMetric')}><select value={metric} onChange={(e) => setMetric(e.target.value as Metric)}>{METRICS.map((m) => <option key={m} value={m}>{tl('metric', m)}</option>)}</select></Field></div>91              <figure className="chart">92                <figcaption>{t('st.chartCaption', { metric: tl('metric', metric) })}</figcaption>93                <Bars format={(n) => num(n)} rows={r.campaigns.map((c) => { const p = r.perCampaign.find((x) => x.campaign_id === c.id && x.metric === metric); return { label: c.name, value: p ? numOrNull(p.total) : null }; })} />94              </figure>95            </>)}96          </Panel>97        </>)}</Await>98        <Panel title={t('st.readingsTitle')}>99          <Await of={metrics}>{(rows) => !rows || rows.length === 0 ? <Empty>{t('st.empty')}</Empty> : (<>100            {rows.length >= 1000 ? <Notice tone="warn"><p>{t('st.truncated')}</p></Notice> : null}101            <TableWrap caption={t('st.readingsTitle')}>102              <thead><tr><th scope="col">{t('st.metric')}</th><th scope="col" className="num">{t('st.value')}</th><th scope="col">{t('st.availability')}</th><th scope="col">{t('st.period')}</th><th scope="col">{t('c.page')}</th><th scope="col">{t('st.contentCol')}</th><th scope="col">{t('c.source')}</th><th scope="col">{t('st.captured')}</th></tr></thead>103              <tbody>{rows.map((m, i) => (104                <tr key={m.id ?? i}><th scope="row">{tl('metric', m.metric)}</th><td className="num"><Value v={m.value} /></td><td><Tag prefix="st.avail" value={m.availability} tone={m.availability === 'available' ? 'ok' : 'idle'} /></td><td>{dt(m.period_start, tz)} → {dt(m.period_end, tz)}</td><td>{m.page_name ?? '—'}</td><td>{m.content_id ? <Link to={`/content/${m.content_id}`}>{t('c.open')}</Link> : t('st.pageLevel')}</td><td>{m.source}</td><td>{dt(m.captured_at, tz)}</td></tr>105              ))}</tbody>106            </TableWrap>107          </>)}</Await>108        </Panel>109        <Entry brandId={brandId} tz={tz} onDone={reload} />110      </>)}111    </>112  );113}114115function Entry({ brandId, tz, onDone }: { brandId: string; tz: string; onDone: () => void }) {116  const { t, tl } = usePrefs();117  const pages = useLoad(async () => (await get<{ pages: Page[] }>(`/v1/pages?brandId=${brandId}`)).pages, [brandId]);118  const content = useLoad(async () => (await get<{ items: ContentRow[] }>(`/v1/content?brandId=${brandId}`)).items, [brandId]);119  const [f, setF] = useState({ pageId: '', contentId: '', d1: '', t1: '00:00', d2: '', t2: '23:59', source: '' });120  const [vals, setVals] = useState<Record<Metric, { on: boolean; v: string }>>(() => Object.fromEntries(METRICS.map((m) => [m, { on: false, v: '' }])) as any);121  const a = useAction();122  const start = useMemo(() => resolveLocal(f.d1, f.t1, tz), [f.d1, f.t1, tz]);123  const end = useMemo(() => resolveLocal(f.d2, f.t2, tz), [f.d2, f.t2, tz]);124  const chosen = METRICS.filter((m) => vals[m].on);125  const bad = chosen.filter((m) => vals[m].v.trim() !== '' && !(Number.isFinite(Number(vals[m].v.replace(',', '.'))) && Number(vals[m].v.replace(',', '.')) >= 0));126  const order = 'utc' in start && 'utc' in end && end.utc.getTime() < start.utc.getTime();127  const ready = f.pageId && 'utc' in start && 'utc' in end && !order && f.source.trim().length >= 2 && chosen.length > 0 && bad.length === 0;128  const send = async () => {129    if (!('utc' in start) || !('utc' in end)) return;130    const body = { pageId: f.pageId, contentId: f.contentId || null, periodStart: start.utc.toISOString(), periodEnd: end.utc.toISOString(), source: f.source.trim(), metrics: chosen.map((m) => ({ metric: m, value: vals[m].v.trim() === '' ? null : Number(vals[m].v.replace(',', '.')) })) };131    if (await a.run(() => post('/v1/metrics/import', body), t('c.saved'))) { setVals(Object.fromEntries(METRICS.map((m) => [m, { on: false, v: '' }])) as any); onDone(); }132  };133  return (134    <Panel title={t('st.entry')}>135      <p className="small">{t('st.entryLead')}</p>136      <ErrorNote error={pages.error} /><ErrorNote error={content.error} />137      <form className="form" onSubmit={(e) => { e.preventDefault(); if (ready) void send(); }}>138        <div className="form-grid">139          <Field label={t('c.page')}><select value={f.pageId} onChange={(e) => setF({ ...f, pageId: e.target.value })} required><option value="">{t('c.select')}</option>{(pages.data ?? []).map((p) => <option key={p.id} value={p.id}>{p.display_name}</option>)}</select></Field>140          <Field label={`${t('st.contentCol')} (${t('c.optional')})`} hint={t('st.contentHint')}><select value={f.contentId} onChange={(e) => setF({ ...f, contentId: e.target.value })}><option value="">{t('st.pageLevel')}</option>{(content.data ?? []).map((c) => <option key={c.id} value={c.id}>{c.title}</option>)}</select></Field>141          <Field label={t('st.start')} hint={t('sch.zoneHint', { tz })}><span className="row"><input type="date" value={f.d1} onChange={(e) => setF({ ...f, d1: e.target.value })} required aria-label={`${t('st.start')} — ${t('sch.date')}`} /><input type="time" value={f.t1} onChange={(e) => setF({ ...f, t1: e.target.value })} required aria-label={`${t('st.start')} — ${t('sch.time')}`} /></span></Field>142          <Field label={t('st.end')}><span className="row"><input type="date" value={f.d2} onChange={(e) => setF({ ...f, d2: e.target.value })} required aria-label={`${t('st.end')} — ${t('sch.date')}`} /><input type="time" value={f.t2} onChange={(e) => setF({ ...f, t2: e.target.value })} required aria-label={`${t('st.end')} — ${t('sch.time')}`} /></span></Field>143          <Field label={t('c.source')} hint={t('st.sourceHint')} wide><input value={f.source} onChange={(e) => setF({ ...f, source: e.target.value })} maxLength={200} required /></Field>144        </div>145        {('error' in start && start.error === 'gap') || ('error' in end && end.error === 'gap') ? <p className="note note-error" role="alert">{t('sch.gap.title')} {t('sch.gap.text', { tz })}</p> : null}146        {order ? <p className="note note-error" role="alert">{t('st.order')}</p> : null}147        <fieldset className="metrics-entry">148          <legend>{t('st.values')}</legend>149          <p className="small">{t('st.valuesHint')}</p>150          {METRICS.map((m) => (151            <div className="metric-row" key={m}>152              <Check label={tl('metric', m)} checked={vals[m].on} onChange={(on) => setVals({ ...vals, [m]: { ...vals[m], on } })} />153              <input inputMode="decimal" value={vals[m].v} disabled={!vals[m].on} onChange={(e) => setVals({ ...vals, [m]: { ...vals[m], v: e.target.value } })} aria-label={`${tl('metric', m)} — ${t('st.value')}`} aria-invalid={bad.includes(m)} placeholder={vals[m].on ? t('c.unavailable') : ''} className="short num" />154              <span className="small">{!vals[m].on ? t('st.notRecorded') : vals[m].v.trim() === '' ? t('st.willBeNull') : bad.includes(m) ? t('st.badNumber') : ''}</span>155            </div>156          ))}157        </fieldset>158        <div className="row"><button type="submit" className="primary" disabled={!ready || a.busy}>{t('st.save')}</button></div>159        <ActionStatus a={a} />160      </form>161    </Panel>162  );163}164
Files main
Menu

Theme