SPB Git

Repository Public

Campaigns.tsx 8.4 KB 142 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/Campaigns.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 { Link } from '../router.tsx';47import { DEFAULT_TZ, zonedToUtc } from '../time.ts';48import type { Campaign, ContentRow } from '../types.ts';49import { ActionStatus, Await, Empty, ErrorNote, Field, KV, Modal, Notice, PageHead, Panel, TableWrap, Tag, useAction, useLoad } from '../ui/core.tsx';5051export function Campaigns({ id }: { id: string | null }) {52  const { t, d } = usePrefs();53  const s = useSession();54  const list = useLoad(() => get<{ campaigns: Campaign[] }>(`/v1/campaigns${brandQuery(s.brandId)}`), [s.brandId]);55  const [creating, setCreating] = useState(false);56  if (id) return <CampaignDetail key={id} id={id} list={list.data?.campaigns} error={list.error} />;57  return (58    <>59      <PageHead title={t('cp.title')} lead={t('cp.lead')}><button type="button" className="primary" onClick={() => setCreating(true)}>{t('cp.new')}</button></PageHead>60      <Await of={list}>{(data) => data.campaigns.length === 0 ? <Empty>{t('cp.empty')}</Empty> : (61        <TableWrap caption={t('cp.title')}>62          <thead><tr><th scope="col">{t('c.name')}</th><th scope="col">{t('c.brand')}</th><th scope="col">{t('cp.starts')}</th><th scope="col">{t('cp.ends')}</th><th scope="col">{t('c.status')}</th></tr></thead>63          <tbody>{data.campaigns.map((c) => { const tz = s.brandById(c.brand_id)?.timezone; return (64            <tr key={c.id}><th scope="row"><Link to={`/campaigns/${c.id}`}>{c.name}</Link></th><td>{s.brandById(c.brand_id)?.name ?? '—'}</td><td>{d(c.starts_at, tz)}</td><td>{d(c.ends_at, tz)}</td><td><Tag prefix="cp.status" value={c.status} tone={c.status === 'active' ? 'ok' : 'idle'} /></td></tr>65          ); })}</tbody>66        </TableWrap>67      )}</Await>68      {creating ? <Modal title={t('cp.new')} onClose={() => setCreating(false)}><CampaignForm onDone={() => { setCreating(false); list.reload(); }} /></Modal> : null}69    </>70  );71}7273function CampaignForm({ onDone }: { onDone: () => void }) {74  const { t } = usePrefs();75  const s = useSession();76  const [f, setF] = useState({ brandId: s.brandId || (s.brands.length === 1 ? s.brands[0].id : ''), name: '', objective: '', starts: '', ends: '' });77  const [dateError, setDateError] = useState('');78  const a = useAction();79  const tz = s.brandById(f.brandId)?.timezone || DEFAULT_TZ;80  /** A campaign date is the start of that civil day in the brand's zone. */81  const dayStart = (v: string): string | null | undefined => {82    if (!v) return null;83    const [y, m, d] = v.split('-').map(Number);84    const r = zonedToUtc({ y, m, d, h: 0, mi: 0 }, tz);85    return r.kind === 'ok' ? r.utc.toISOString() : r.kind === 'overlap' ? r.first.toISOString() : r.after.toISOString();86  };87  const send = async () => {88    const startsAt = dayStart(f.starts); const endsAt = dayStart(f.ends);89    if (startsAt && endsAt && endsAt < startsAt) { setDateError(t('cp.dateOrder')); return; }90    setDateError('');91    if (await a.run(() => post('/v1/campaigns', { brandId: f.brandId, name: f.name.trim(), objective: f.objective, startsAt, endsAt }))) onDone();92  };93  return (94    <form className="form" onSubmit={(e) => { e.preventDefault(); void send(); }}>95      <Field label={t('c.brand')}><select value={f.brandId} onChange={(e) => setF({ ...f, brandId: e.target.value })} required><option value="">{t('c.select')}</option>{s.brands.map((b) => <option key={b.id} value={b.id}>{b.name}</option>)}</select></Field>96      <Field label={t('c.name')} wide><input value={f.name} onChange={(e) => setF({ ...f, name: e.target.value })} maxLength={160} required /></Field>97      <Field label={`${t('cp.objective')} (${t('c.optional')})`} wide><textarea value={f.objective} onChange={(e) => setF({ ...f, objective: e.target.value })} rows={3} maxLength={2000} /></Field>98      <div className="form-grid">99        <Field label={`${t('cp.starts')} (${t('c.optional')})`} hint={t('sch.zoneHint', { tz })}><input type="date" value={f.starts} onChange={(e) => setF({ ...f, starts: e.target.value })} /></Field>100        <Field label={`${t('cp.ends')} (${t('c.optional')})`}><input type="date" value={f.ends} onChange={(e) => setF({ ...f, ends: e.target.value })} /></Field>101      </div>102      {dateError ? <p className="note note-error" role="alert">{dateError}</p> : null}103      <div className="row"><button type="submit" className="primary" disabled={a.busy || !f.brandId || !f.name.trim()}>{t('c.create')}</button></div>104      <ActionStatus a={a} />105    </form>106  );107}108109function CampaignDetail({ id, list, error }: { id: string; list: Campaign[] | undefined; error: unknown }) {110  const { t, tl, d, dt } = usePrefs();111  const s = useSession();112  const c = list?.find((x) => x.id === id);113  // The content list has no campaign filter on the server: the brand's contents are read (300 most recent) and filtered here.114  const content = useLoad(async () => (c ? (await get<{ items: ContentRow[] }>(`/v1/content?brandId=${c.brand_id}`)).items : null), [c?.brand_id]);115  if (!c) return <><p className="crumb"><Link to="/campaigns">{t('cp.title')}</Link></p>{error ? <ErrorNote error={error} /> : list ? <Empty>{t('cp.notFound')}</Empty> : <p role="status">{t('c.loading')}</p>}</>;116  const tz = s.brandById(c.brand_id)?.timezone;117  return (118    <>119      <p className="crumb"><Link to="/campaigns">{t('cp.title')}</Link></p>120      <PageHead title={c.name} lead={s.brandById(c.brand_id)?.name} />121      <Panel>122        <KV rows={[[t('cp.objective'), c.objective ? <span className="pre">{c.objective}</span> : '—'], [t('cp.starts'), d(c.starts_at, tz)], [t('cp.ends'), d(c.ends_at, tz)], [t('c.status'), <Tag prefix="cp.status" value={c.status} tone={c.status === 'active' ? 'ok' : 'idle'} />]]} />123      </Panel>124      <Panel title={t('cp.content')} actions={<Link to="/content/new" className="btn">{t('ct.new')}</Link>}>125        <p className="small">{t('cp.contentNote')}</p>126        <Await of={content}>{(items) => {127          const mine = (items ?? []).filter((x) => x.campaign_id === id);128          return (<>129            {(items?.length ?? 0) >= 300 ? <Notice tone="warn"><p>{t('cp.truncated')}</p></Notice> : null}130            {mine.length === 0 ? <Empty>{t('cp.noContent')}</Empty> : (131              <TableWrap caption={t('cp.content')}>132                <thead><tr><th scope="col">{t('c.title')}</th><th scope="col">{t('c.state')}</th><th scope="col">{t('c.language')}</th><th scope="col">{t('c.updated')}</th></tr></thead>133                <tbody>{mine.map((x) => <tr key={x.id}><th scope="row"><Link to={`/content/${x.id}`}>{x.title}</Link></th><td><Tag prefix="contentState" value={x.state} /></td><td>{tl('c.lang', x.lang)}</td><td>{dt(x.updated_at, tz)}</td></tr>)}</tbody>134              </TableWrap>135            )}136          </>);137        }}</Await>138      </Panel>139    </>140  );141}142
Files main
Menu

Theme