diff --git a/src/commentary/defaultRules.js b/src/commentary/defaultRules.js new file mode 100644 index 0000000..fdb9f21 --- /dev/null +++ b/src/commentary/defaultRules.js @@ -0,0 +1,144 @@ +// Starting rules for a new config. The test page can run only some of them. +export function defaultRules() { + return [ + { + id: 'DAY_SUMMARY', + tag: 'END OF DAY', + enabled: true, + headline: 'End of day: {day} submissions', + body: 'Month total {mtd}.', + params: {}, + }, + { + id: 'YET_TO_BAT', + tag: 'YET TO BAT', + enabled: true, + headline: '{count} reps still on zero for the month', + body: '{under_vacant_abm} of them report to a vacant ABM post.', + params: { min_working_day: 6 }, + }, + { + id: 'MILESTONE', + tag: 'MILESTONE', + enabled: true, + headline: 'Pass {milestone}', + body: 'Month total {mtd}.', + params: { step: 500 }, + }, + { + id: 'ASKING_RATE', + tag: 'ASKING RATE', + enabled: true, + headline: 'Asking rate is {ratio}x the current rate', + body: 'Need {rrr} a day against {crr} so far.', + params: { min_ratio: 1.5 }, + }, + { + id: 'TARGET_MET', + tag: 'CENTURY', + enabled: true, + headline: '{name} reaches the monthly target', + body: '{mtd} against {target}, with {wd_left} working days to spare.', + params: {}, + }, + { + id: 'RECORD_DAY', + tag: 'CHARGE', + enabled: true, + headline: '{unit} post {day}, the best day of the month', + body: 'They had averaged {month_avg} a working day before this.', + params: { lift: 1.8, floor: 20 }, + }, + { + id: 'BIG_HITTING', + tag: 'BIG HITTING', + enabled: true, + headline: '{name} hits {day} in a day', + body: 'Takes the month to {mtd}.', + params: { abs_min: 5 }, + }, + { + id: 'TEAM_BIG_DAY', + tag: 'TEAM EFFORT', + enabled: true, + headline: "{abm}'s team makes {day} in a day", + body: "That's {share}% of its month total of {mtd}.", + params: { min_day: 10, min_share_of_mtd: 0.4 }, + }, + { + id: 'OFF_THE_MARK', + tag: 'OFF THE MARK', + enabled: true, + headline: '{name} opens the account with {day}', + body: 'First submission of the month.', + params: { min_working_day: 6 }, + }, + { + id: 'HAT_TRICK', + tag: 'HAT-TRICK', + enabled: true, + headline: '{name} scores {streak} days running', + body: 'Month total now {mtd}.', + params: { lengths: '3,5,10' }, + }, + { + id: 'TOP_OF_TABLE', + tag: 'TOP OF THE TABLE', + enabled: true, + headline: '{unit} stays top at {pct}%', + body: 'Par today is {par}%.', + params: { min_working_day: 5 }, + }, + { + id: 'ORANGE_CAP', + tag: 'ORANGE CAP', + enabled: true, + headline: '{name} leads the month with {mtd}', + body: 'Highest submission count this month.', + params: {}, + }, + { + id: 'SURGE', + tag: 'SURGE', + enabled: true, + headline: "{unit}'s region on pace to beat last month", + body: 'Projected {projected} against {prev_month}.', + params: { min_ratio: 1.3 }, + }, + { + id: 'NO_SIGNAL', + tag: 'NO SIGNAL', + enabled: true, + headline: "{name}'s region: nothing logged for 2 working days", + body: 'Worth a data check before the next report.', + params: { window_working_days: 2, min_active: 10 }, + }, + { + id: 'COLLAPSE', + tag: 'COLLAPSE', + enabled: true, + headline: "{unit}'s region on {mtd} after {prev_month} last month", + body: 'On pace for about {projected}.', + params: { max_ratio: 0.5 }, + }, + { + id: 'OUT_OF_FORM', + tag: 'OUT OF FORM', + enabled: true, + headline: '{names}: on zero after a strong last month', + body: 'Worth a call from the ABM.', + params: { min_prev: 15 }, + }, + ]; +} + +export function blankConfig() { + return { + id: `cfg-${Date.now()}`, + name: 'New config', + formIds: [], + form_ids: [], + target: '', + rules: defaultRules(), + }; +} diff --git a/src/layouts/menu.js b/src/layouts/menu.js index 3f3836c..71d0feb 100644 --- a/src/layouts/menu.js +++ b/src/layouts/menu.js @@ -314,6 +314,8 @@ export function getMenuItems({ permissions = [], roles = [], domain = '', email child('formexports', 'Form Data Export', '/formexports', 'formexports_get_all'), child('reminders', 'Reminders', '/reminders', 'reminder_get_all'), child('leaderboards', 'Leaderboard', '/leaderboards', 'roles_leaderboard_get_all'), + child('commentary', 'Commentary', '/commentary', 'formentity_get_all'), + // child('commentary-test', 'Commentary Test', '/commentary-test', 'formentity_get_all'), ].filter((item) => !item.permission || permissions.includes(item.permission)); if (hasAny(permissions, ['workflow_definition_get_all', 'workflow_instance_get_all'])) { diff --git a/src/routes/index.jsx b/src/routes/index.jsx index 21272a8..f50b715 100644 --- a/src/routes/index.jsx +++ b/src/routes/index.jsx @@ -85,6 +85,8 @@ const MagMediaViewers = lazy(() => import('@/views/content/MagMediaViewers')); const WorkflowEditor = lazy(() => import('@/views/workflow/Editor')); const WorkflowMonitor = lazy(() => import('@/views/workflow/Monitor')); const LeaderboardDashboard = lazy(() => import('@/views/leaderboard/Dashboard')); +const Commentary = lazy(() => import('@/views/commentary/Commentary')); +// const CommentaryTest = lazy(() => import('@/views/commentary/CommentaryTest')); const NebReportList = lazy(() => import('@/views/neblogistic/ReportList')); const NebReportDetail = lazy(() => import('@/views/neblogistic/ReportDetail')); const NebDepotPage = lazy(() => import('@/views/neblogistic/DepotPage')); @@ -198,6 +200,8 @@ export const routes = [ { path: '/workflow/editor', element: }, { path: '/workflow/monitor', element: }, { path: '/leaderboard/dashboard', element: }, + { path: '/commentary', element: }, + // { path: '/commentary-test', element: }, ...moduleRoutes(detailingcontests), ...moduleRoutes(contestparameters), ...moduleRoutes(detailingcontestresponses), diff --git a/src/views/commentary/Commentary.jsx b/src/views/commentary/Commentary.jsx new file mode 100644 index 0000000..79e67a4 --- /dev/null +++ b/src/views/commentary/Commentary.jsx @@ -0,0 +1,441 @@ +import { useEffect, useState } from 'react'; +import { Button, Card, Col, Container, Form, Row, Spinner, Table } from 'react-bootstrap'; +import { isSuccess, signedGet, signedPost } from '@/api/client'; +import { useAuth } from '@/auth/AuthProvider'; +import PageBreadcrumb from '@/components/PageBreadcrumb'; +import { blankConfig } from '@/commentary/defaultRules'; + +function emptyConfig() { + return { ...blankConfig(), name: '', form_ids: [], formIds: [] }; +} + +function rulesOf(value) { + if (Array.isArray(value)) return value; + if (typeof value === 'string' && value) { + try { + const parsed = JSON.parse(value); + return Array.isArray(parsed) ? parsed : []; + } catch (e) { + return []; + } + } + return []; +} + +function asConfig(item) { + if (!item) return null; + const form_ids = Array.isArray(item.form_ids) ? item.form_ids : []; + return { + id: item.id || '', + name: item.name || '', + form_ids, + target: item.target ?? '', + status: item.status || 'active', + rules: rulesOf(item.rules), + }; +} + +function todayStr() { + const today = new Date(); + return ( + today.getFullYear() + + '-' + + String(today.getMonth() + 1).padStart(2, '0') + + '-' + + String(today.getDate()).padStart(2, '0') + ); +} + +export default function Commentary() { + const { user } = useAuth(); + const [tab, setTab] = useState('config'); + const [config, setConfig] = useState(() => emptyConfig()); + const [forms, setForms] = useState([]); + const [formsError, setFormsError] = useState(''); + const [loadError, setLoadError] = useState(''); + const [loading, setLoading] = useState(true); + const [saving, setSaving] = useState(false); + const [saveMessage, setSaveMessage] = useState(''); + const [reportDate, setReportDate] = useState(() => todayStr()); + const [loadingResponse, setLoadingResponse] = useState(false); + const [exporting, setExporting] = useState(false); + const [responseError, setResponseError] = useState(''); + const [exportMessage, setExportMessage] = useState(''); + const [response, setResponse] = useState(null); + + useEffect(() => { + let cancelled = false; + setLoading(true); + setLoadError(''); + signedGet('reports', 'commentary/get_all') + .then((result) => { + if (cancelled) return; + if (!isSuccess(result)) { + setLoadError(result?.message || 'Unable to load commentary'); + setConfig(emptyConfig()); + return; + } + const items = Array.isArray(result.data?.items) ? result.data.items : []; + const first = items.find((item) => item && !item.is_deleted) || items[0]; + setConfig(first ? asConfig(first) : emptyConfig()); + }) + .catch((err) => { + if (!cancelled) { + setLoadError(err.message || 'Unable to load commentary'); + setConfig(emptyConfig()); + } + }) + .finally(() => { + if (!cancelled) setLoading(false); + }); + return () => { + cancelled = true; + }; + }, [user?.partition]); + + useEffect(() => { + let cancelled = false; + setForms([]); + setFormsError(''); + signedGet('form', 'formentity/dropdown') + .then((result) => { + if (cancelled) return; + if (!isSuccess(result)) { + setFormsError(result?.message || 'Unable to load forms'); + return; + } + const items = Array.isArray(result.data?.items) ? result.data.items : []; + setForms(items.filter((item) => item?.id)); + }) + .catch(() => { + if (!cancelled) setFormsError('Unable to load forms'); + }); + return () => { + cancelled = true; + }; + }, [user?.partition]); + + const updateConfig = (patch) => setConfig((current) => ({ ...current, ...patch })); + + const updateRule = (index, patch) => { + const rules = config.rules.map((rule, ruleIndex) => (ruleIndex === index ? { ...rule, ...patch } : rule)); + updateConfig({ rules }); + }; + + const updateParam = (index, key, value) => { + const rule = config.rules[index]; + if (!rule) return; + const current = rule.params && typeof rule.params === 'object' ? rule.params : {}; + const nextValue = value === '' || Number.isNaN(Number(value)) ? value : Number(value); + updateRule(index, { params: { ...current, [key]: nextValue } }); + }; + + const addParam = (index) => { + const rule = config.rules[index]; + if (!rule) return; + const current = rule.params && typeof rule.params === 'object' ? { ...rule.params } : {}; + let key = 'threshold'; + let n = 2; + while (Object.prototype.hasOwnProperty.call(current, key)) { + key = `threshold_${n}`; + n += 1; + } + current[key] = 0; + updateRule(index, { params: current }); + }; + + const addRule = () => { + updateConfig({ + rules: [ + ...config.rules, + { + id: `CUSTOM_${Date.now()}`, + tag: 'CUSTOM', + enabled: true, + headline: '', + body: '', + params: {}, + }, + ], + }); + }; + + const save = async () => { + setSaving(true); + setSaveMessage(''); + try { + const known = new Set(forms.map((form) => form.id)); + const form_ids = (config.form_ids || []).filter((id) => known.has(id)); + if (!form_ids.length) throw new Error('Select at least one form.'); + const payload = { + form_ids, + target: config.target, + rules: config.rules, + status: config.status || 'active', + }; + const result = config.id + ? await signedPost('reports', 'commentary/update', { id: config.id, ...payload }) + : await signedPost('reports', 'commentary/create', payload); + if (!isSuccess(result)) throw new Error(result?.message || 'Unable to save commentary'); + const saved = asConfig(result.data?.item) || { ...config, ...payload, id: result.data?.item?.id || config.id }; + setConfig(saved); + setSaveMessage('Commentary saved'); + } catch (err) { + setSaveMessage(err.message || 'Unable to save commentary'); + } finally { + setSaving(false); + } + }; + + const build = async () => { + setLoadingResponse(true); + setResponseError(''); + setResponse(null); + try { + if (!reportDate) throw new Error('Pick a report date before building.'); + if (!(config.form_ids || []).length) throw new Error('Select at least one form and save before building.'); + const result = await signedPost( + 'reports', + 'commentary/response', + { date: reportDate }, + { timeout: 120000 }, + ); + if (!isSuccess(result)) throw new Error(result?.message || 'Unable to build the response'); + const built = result.data || {}; + setResponse({ + date: built.date || reportDate, + cards: Array.isArray(built.cards) ? built.cards : [], + skipped: Array.isArray(built.skipped) ? built.skipped : [], + audience: built.audience, + scope: built.scope, + }); + } catch (err) { + setResponseError(err.message || 'Unable to build the response'); + } finally { + setLoadingResponse(false); + } + }; + + const exportCsv = async () => { + setExporting(true); + setExportMessage(''); + setResponseError(''); + try { + if (!reportDate) throw new Error('Pick a report date before exporting.'); + if (!(config.form_ids || []).length) throw new Error('Select at least one form and save before exporting.'); + const result = await signedPost( + 'reports', + 'commentary/export', + { date: reportDate }, + { timeout: 120000 }, + ); + if (!isSuccess(result)) throw new Error(result?.message || 'Unable to export commentary'); + const csvFile = result.data?.csvFile; + const count = result.data?.count ?? 0; + if (!csvFile) throw new Error('Export did not return a file URL'); + setExportMessage(`Exported ${count} events.`); + window.open(csvFile, '_blank', 'noopener,noreferrer'); + } catch (err) { + setResponseError(err.message || 'Unable to export commentary'); + } finally { + setExporting(false); + } + }; + + return ( + + +

One commentary config per domain. Open, edit, save, build, and export.

+
+ + +
+ + {loading ? : null} + {loadError ?
{loadError}
: null} + + {!loading && tab === 'config' ? ( + + + + + Monthly target + updateConfig({ target: event.target.value })} + /> + + + Status + updateConfig({ status: event.target.value })} + > + + + + + + + + + {saveMessage ?
{saveMessage}
: null} + {formsError ?
{formsError}
: null} + + + Forms * + +
+ {forms.map((form) => { + const checked = (config.form_ids || []).includes(form.id); + return ( + { + const current = config.form_ids || []; + const form_ids = event.target.checked + ? [...current, form.id] + : current.filter((id) => id !== form.id); + updateConfig({ form_ids }); + }} + /> + ); + })} +
+ +
+
Rules
+ +
+ + + + + + + + + + + + + {(config.rules || []).map((rule, index) => ( + + + + + + + + + ))} + +
OnIdTagHeadlineBodyThresholds
+ updateRule(index, { enabled: event.target.checked })} + /> + + updateRule(index, { id: event.target.value })} /> + + updateRule(index, { tag: event.target.value })} /> + + updateRule(index, { headline: event.target.value })} + /> + + updateRule(index, { body: event.target.value })} /> + + {Object.entries(rule.params || {}).map(([key, value]) => ( + + {key} + updateParam(index, key, event.target.value)} /> + + ))} + +
+
+
+ ) : null} + + {!loading && tab === 'response' ? ( + + + + + Report date + setReportDate(event.target.value)} /> + + + + + + + + +
+ Build shows the selected feed (up to 8 cards). Export lists every scored event with subject, managers, and in_feed yes/no for the selected 8. +
+ {loadingResponse || exporting ? : null} + {responseError ?
{responseError}
: null} + {exportMessage ?
{exportMessage}
: null} + {response ? ( + <> +

+ Date used: {response.date || 'none'} + {response.scope ? <> · Scope: {response.scope} : null} + {response.audience ? <> · Audience: {response.audience} : null}. Cards: {response.cards.length}. +

+ {response.cards.map((card) => ( + + +
+ {card.tag} + {card.scope} +
+
{card.headline}
+
{card.body}
+
+
+ ))} + {response.skipped.length ? ( + <> +
Skipped
+
    + {response.skipped.map((row) => ( +
  • + {row.tag}: {row.reason} +
  • + ))} +
+ + ) : null} + + ) : null} +
+
+ ) : null} +
+ ); +}