added commentary code

This commit is contained in:
Abhijit 2026-11-20 21:57:05 +05:30
parent d027721a73
commit 945f593fb1
4 changed files with 591 additions and 0 deletions

View File

@ -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(),
};
}

View File

@ -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'])) {

View File

@ -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: <WorkflowEditor /> },
{ path: '/workflow/monitor', element: <WorkflowMonitor /> },
{ path: '/leaderboard/dashboard', element: <LeaderboardDashboard /> },
{ path: '/commentary', element: <Commentary /> },
// { path: '/commentary-test', element: <CommentaryTest /> },
...moduleRoutes(detailingcontests),
...moduleRoutes(contestparameters),
...moduleRoutes(detailingcontestresponses),

View File

@ -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 (
<Container fluid>
<PageBreadcrumb title="Commentary" />
<p className="text-muted">One commentary config per domain. Open, edit, save, build, and export.</p>
<div className="btn-group mb-3">
<Button variant={tab === 'config' ? 'primary' : 'outline-primary'} onClick={() => setTab('config')}>
Configuration
</Button>
<Button variant={tab === 'response' ? 'primary' : 'outline-primary'} onClick={() => setTab('response')}>
Response
</Button>
</div>
{loading ? <Spinner animation="border" /> : null}
{loadError ? <div className="alert alert-warning">{loadError}</div> : null}
{!loading && tab === 'config' ? (
<Card>
<Card.Body>
<Row className="g-3 mb-3">
<Col md={3}>
<Form.Label>Monthly target</Form.Label>
<Form.Control
type="number"
value={config.target ?? ''}
onChange={(event) => updateConfig({ target: event.target.value })}
/>
</Col>
<Col md={3}>
<Form.Label>Status</Form.Label>
<Form.Select
value={config.status || 'active'}
onChange={(event) => updateConfig({ status: event.target.value })}
>
<option value="active">Active</option>
<option value="disabled">Disabled</option>
</Form.Select>
</Col>
<Col md={4} className="d-flex align-items-end">
<Button variant="primary" onClick={save} disabled={saving}>
{saving ? 'Saving...' : 'Save'}
</Button>
</Col>
</Row>
{saveMessage ? <div className="alert alert-info">{saveMessage}</div> : null}
{formsError ? <div className="alert alert-danger">{formsError}</div> : null}
<Form.Label>
Forms <span className="text-danger">*</span>
</Form.Label>
<div className="border rounded p-2 mb-3" style={{ maxHeight: 280, overflowY: 'auto' }}>
{forms.map((form) => {
const checked = (config.form_ids || []).includes(form.id);
return (
<Form.Check
key={form.id}
type="checkbox"
id={`commentary-form-${form.id}`}
className="mb-1"
label={form.title || form.id}
checked={checked}
onChange={(event) => {
const current = config.form_ids || [];
const form_ids = event.target.checked
? [...current, form.id]
: current.filter((id) => id !== form.id);
updateConfig({ form_ids });
}}
/>
);
})}
</div>
<div className="d-flex justify-content-between align-items-center mb-2">
<h5 className="mb-0">Rules</h5>
<Button size="sm" variant="outline-primary" onClick={addRule}>
Add rule
</Button>
</div>
<Table bordered responsive>
<thead>
<tr>
<th>On</th>
<th>Id</th>
<th>Tag</th>
<th>Headline</th>
<th>Body</th>
<th>Thresholds</th>
</tr>
</thead>
<tbody>
{(config.rules || []).map((rule, index) => (
<tr key={`${rule.id}-${index}`}>
<td>
<Form.Check
checked={rule.enabled !== false}
onChange={(event) => updateRule(index, { enabled: event.target.checked })}
/>
</td>
<td>
<Form.Control value={rule.id || ''} onChange={(event) => updateRule(index, { id: event.target.value })} />
</td>
<td>
<Form.Control value={rule.tag || ''} onChange={(event) => updateRule(index, { tag: event.target.value })} />
</td>
<td>
<Form.Control
value={rule.headline || ''}
onChange={(event) => updateRule(index, { headline: event.target.value })}
/>
</td>
<td>
<Form.Control value={rule.body || ''} onChange={(event) => updateRule(index, { body: event.target.value })} />
</td>
<td>
{Object.entries(rule.params || {}).map(([key, value]) => (
<Form.Group key={key} className="mb-1">
<Form.Label className="mb-0 small">{key}</Form.Label>
<Form.Control value={value} onChange={(event) => updateParam(index, key, event.target.value)} />
</Form.Group>
))}
<Button size="sm" variant="link" className="p-0" onClick={() => addParam(index)}>
Add threshold
</Button>
</td>
</tr>
))}
</tbody>
</Table>
</Card.Body>
</Card>
) : null}
{!loading && tab === 'response' ? (
<Card>
<Card.Body>
<Row className="g-3 mb-3 align-items-end">
<Col md={3}>
<Form.Label>Report date</Form.Label>
<Form.Control type="date" value={reportDate} onChange={(event) => setReportDate(event.target.value)} />
</Col>
<Col md="auto">
<Button variant="primary" onClick={build} disabled={loadingResponse || exporting || saving}>
{loadingResponse ? 'Building...' : 'Build response'}
</Button>
</Col>
<Col md="auto">
<Button variant="outline-primary" onClick={exportCsv} disabled={exporting || loadingResponse || saving}>
{exporting ? 'Exporting...' : 'Export CSV'}
</Button>
</Col>
</Row>
<div className="form-text mb-3">
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.
</div>
{loadingResponse || exporting ? <Spinner animation="border" className="mb-3" /> : null}
{responseError ? <div className="alert alert-danger">{responseError}</div> : null}
{exportMessage ? <div className="alert alert-success">{exportMessage}</div> : null}
{response ? (
<>
<p>
Date used: <strong>{response.date || 'none'}</strong>
{response.scope ? <> · Scope: {response.scope}</> : null}
{response.audience ? <> · Audience: {response.audience}</> : null}. Cards: {response.cards.length}.
</p>
{response.cards.map((card) => (
<Card key={`${card.rank}-${card.type}-${card.subject_id || card.scope}`} className="mb-2">
<Card.Body>
<div className="d-flex justify-content-between">
<strong>{card.tag}</strong>
<span className="text-muted">{card.scope}</span>
</div>
<div>{card.headline}</div>
<div className="text-muted">{card.body}</div>
</Card.Body>
</Card>
))}
{response.skipped.length ? (
<>
<h6>Skipped</h6>
<ul>
{response.skipped.map((row) => (
<li key={row.id}>
{row.tag}: {row.reason}
</li>
))}
</ul>
</>
) : null}
</>
) : null}
</Card.Body>
</Card>
) : null}
</Container>
);
}