Merge remote main and keep both insights glossary and horizon report routes.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Ravi Gulhane 2026-11-25 15:42:10 +05:30
commit 5eb233ae90
9 changed files with 1110 additions and 60 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

@ -8,7 +8,7 @@ function patchRow(rows, index, patch) {
} }
function emptyRow() { function emptyRow() {
return { title: '', role: '', limit: 10, sort_order: 0 }; return { title: '', role: '', limit: 10, sort_order: 0, view_mode: 'versus', scope: 'domain' };
} }
export default function RankRolesField({ field, control }) { export default function RankRolesField({ field, control }) {
@ -32,6 +32,8 @@ export default function RankRolesField({ field, control }) {
<tr> <tr>
<th>Title</th> <th>Title</th>
<th>Role</th> <th>Role</th>
<th>View Mode</th>
<th>Show</th>
<th>Limit</th> <th>Limit</th>
<th>Sort Order</th> <th>Sort Order</th>
<th /> <th />
@ -59,6 +61,25 @@ export default function RankRolesField({ field, control }) {
))} ))}
</Form.Select> </Form.Select>
</td> </td>
<td>
<Form.Select
value={['versus', 'podium', 'list'].includes(row.view_mode) ? row.view_mode : 'versus'}
onChange={(e) => rhf.onChange(patchRow(rows, index, { view_mode: e.target.value }))}
>
<option value="versus">Versus</option>
<option value="podium">Podium</option>
<option value="list">List</option>
</Form.Select>
</td>
<td>
<Form.Select
value={row.scope === 'state_head' ? 'state_head' : 'domain'}
onChange={(e) => rhf.onChange(patchRow(rows, index, { scope: e.target.value }))}
>
<option value="domain">Domain wise</option>
<option value="state_head">State head wise</option>
</Form.Select>
</td>
<td> <td>
<Form.Control <Form.Control
type="number" type="number"

View File

@ -145,6 +145,22 @@ export function getMenuItems({ permissions = [], roles = [], domain = '', email
}); });
} }
if (domain === 'horizon') {
const designationName = String(designation).trim().toUpperCase();
const fullAccess = permissions.includes('all_data_access') || designationName === 'HO';
const isZbm = designationName === 'ZBM';
if ((fullAccess || isZbm) && designationName !== 'RBM') {
items.push({
key: 'horizon-custom-reports',
label: 'Custom Reports',
icon: LuFileText,
children: [
child('horizon-field-work', 'Monthly Field Work Report', '/horizonreport/fieldwork'),
],
});
}
}
if (domain === 'pulmocare' && roles.includes('1650360330-5bf35594-674a-4f31-HO_Audit-47738d2151ab')) { if (domain === 'pulmocare' && roles.includes('1650360330-5bf35594-674a-4f31-HO_Audit-47738d2151ab')) {
items.push({ items.push({
key: 'healthy-lung', key: 'healthy-lung',
@ -314,6 +330,8 @@ export function getMenuItems({ permissions = [], roles = [], domain = '', email
child('formexports', 'Form Data Export', '/formexports', 'formexports_get_all'), child('formexports', 'Form Data Export', '/formexports', 'formexports_get_all'),
child('reminders', 'Reminders', '/reminders', 'reminder_get_all'), child('reminders', 'Reminders', '/reminders', 'reminder_get_all'),
child('leaderboards', 'Leaderboard', '/leaderboards', 'roles_leaderboard_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)); ].filter((item) => !item.permission || permissions.includes(item.permission));
if (hasAny(permissions, ['workflow_definition_get_all', 'workflow_instance_get_all'])) { if (hasAny(permissions, ['workflow_definition_get_all', 'workflow_instance_get_all'])) {

View File

@ -141,7 +141,6 @@ const leaderboards = {
roles, roles,
required: true, required: true,
fullwidth: true, fullwidth: true,
showIf: { leaderboard_roles_type: 'roles' },
}, },
{ {
key: 'metrics', key: 'metrics',
@ -212,7 +211,13 @@ const leaderboards = {
next.leaderboard_team_ids = asArray(next.leaderboard_team_ids); next.leaderboard_team_ids = asArray(next.leaderboard_team_ids);
next.manager_details = asArray(next.manager_details); next.manager_details = asArray(next.manager_details);
if (!next.manager_details.length) next.manager_details = ['l1manager']; if (!next.manager_details.length) next.manager_details = ['l1manager'];
next.rank_roles = (Array.isArray(next.rank_roles) ? next.rank_roles : []).slice().sort(bySortOrder); next.rank_roles = (Array.isArray(next.rank_roles) ? next.rank_roles : [])
.map((row) => ({
...row,
view_mode: ['versus', 'podium', 'list'].includes(row.view_mode) ? row.view_mode : 'versus',
scope: row.scope === 'state_head' ? 'state_head' : 'domain',
}))
.sort(bySortOrder);
next.metrics = (Array.isArray(next.metrics) ? next.metrics : []) next.metrics = (Array.isArray(next.metrics) ? next.metrics : [])
.map((row) => ({ .map((row) => ({
metric: row.metric || '', metric: row.metric || '',
@ -253,6 +258,8 @@ const leaderboards = {
role: row.role || '', role: row.role || '',
limit: row.limit === '' || row.limit == null ? 10 : Number(row.limit), limit: row.limit === '' || row.limit == null ? 10 : Number(row.limit),
sort_order: row.sort_order === '' || row.sort_order == null ? 0 : Number(row.sort_order), sort_order: row.sort_order === '' || row.sort_order == null ? 0 : Number(row.sort_order),
view_mode: ['versus', 'podium', 'list'].includes(row.view_mode) ? row.view_mode : 'versus',
scope: row.scope === 'state_head' ? 'state_head' : 'domain',
})); }));
payload.metrics = (Array.isArray(payload.metrics) ? payload.metrics : []) payload.metrics = (Array.isArray(payload.metrics) ? payload.metrics : [])
.filter((row) => row.metric) .filter((row) => row.metric)

View File

@ -86,6 +86,8 @@ const MagMediaViewers = lazy(() => import('@/views/content/MagMediaViewers'));
const WorkflowEditor = lazy(() => import('@/views/workflow/Editor')); const WorkflowEditor = lazy(() => import('@/views/workflow/Editor'));
const WorkflowMonitor = lazy(() => import('@/views/workflow/Monitor')); const WorkflowMonitor = lazy(() => import('@/views/workflow/Monitor'));
const LeaderboardDashboard = lazy(() => import('@/views/leaderboard/Dashboard')); 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 NebReportList = lazy(() => import('@/views/neblogistic/ReportList'));
const NebReportDetail = lazy(() => import('@/views/neblogistic/ReportDetail')); const NebReportDetail = lazy(() => import('@/views/neblogistic/ReportDetail'));
const NebDepotPage = lazy(() => import('@/views/neblogistic/DepotPage')); const NebDepotPage = lazy(() => import('@/views/neblogistic/DepotPage'));
@ -101,6 +103,7 @@ const GoalProficiencyReport = lazy(() => import('@/views/coachingtooldashboard/G
const AdherencePobDriveReport = lazy(() => import('@/views/adherencepobdrivereport/Report')); const AdherencePobDriveReport = lazy(() => import('@/views/adherencepobdrivereport/Report'));
const IvaReportPage = lazy(() => import('@/views/ivareport/ReportPage')); const IvaReportPage = lazy(() => import('@/views/ivareport/ReportPage'));
const InsightsGlossaryForm = lazy(() => import('@/views/insights/GlossaryForm')); const InsightsGlossaryForm = lazy(() => import('@/views/insights/GlossaryForm'));
const HorizonFieldWorkReport = lazy(() => import('@/views/horizonreport/Report'));
function moduleRoutes(config) { function moduleRoutes(config) {
const routes = [ const routes = [
@ -200,6 +203,8 @@ export const routes = [
{ path: '/workflow/editor', element: <WorkflowEditor /> }, { path: '/workflow/editor', element: <WorkflowEditor /> },
{ path: '/workflow/monitor', element: <WorkflowMonitor /> }, { path: '/workflow/monitor', element: <WorkflowMonitor /> },
{ path: '/leaderboard/dashboard', element: <LeaderboardDashboard /> }, { path: '/leaderboard/dashboard', element: <LeaderboardDashboard /> },
{ path: '/commentary', element: <Commentary /> },
// { path: '/commentary-test', element: <CommentaryTest /> },
...moduleRoutes(detailingcontests), ...moduleRoutes(detailingcontests),
...moduleRoutes(contestparameters), ...moduleRoutes(contestparameters),
...moduleRoutes(detailingcontestresponses), ...moduleRoutes(detailingcontestresponses),
@ -246,6 +251,7 @@ export const routes = [
{ path: '/ivareport/kamwise', element: <IvaReportPage key="kamwise" tab="kamwise" /> }, { path: '/ivareport/kamwise', element: <IvaReportPage key="kamwise" tab="kamwise" /> },
{ path: '/ivareport/drbrandwise', element: <IvaReportPage key="drbrandwise" tab="drbrandwise" /> }, { path: '/ivareport/drbrandwise', element: <IvaReportPage key="drbrandwise" tab="drbrandwise" /> },
{ path: '/ivareport/skuwise', element: <IvaReportPage key="skuwise" tab="skuwise" /> }, { path: '/ivareport/skuwise', element: <IvaReportPage key="skuwise" tab="skuwise" /> },
{ path: '/horizonreport/fieldwork', element: <HorizonFieldWorkReport /> },
{ path: '/coming-soon', element: <ComingSoon /> }, { path: '/coming-soon', element: <ComingSoon /> },
{ path: '*', element: <ComingSoon /> }, { path: '*', element: <ComingSoon /> },
], ],

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>
);
}

View File

@ -0,0 +1,235 @@
import { Fragment, useEffect, useMemo, useState } from 'react';
import { Button, Container, Form } from 'react-bootstrap';
import { isSuccess, signedGet } from '@/api/client';
import { useAuth } from '@/auth/AuthProvider';
import PageMetaData from '@/components/PageMetaData';
import { exportFieldWorkReport } from './exportXlsx';
const TITLE = 'Monthly Field Work Report';
const REPORT_TIMEOUT = 120000;
const FIRST_MONTH = new Date(2026, 10, 1);
const IDENTITY = [
'RBM/ZBM Name',
'Emp Code',
'Role Name',
'Position Name',
'Manager 1 Code',
'Manager 1 Name',
'Manager 2 Code',
'Manager 2 Name',
];
function monthName(date) {
return date.toLocaleString('en-US', { month: 'long', year: 'numeric' });
}
function reportMonths() {
const months = [];
const end = new Date();
end.setDate(1);
const cursor = new Date(FIRST_MONTH);
while (cursor <= end) {
months.push(monthName(cursor));
cursor.setMonth(cursor.getMonth() + 1);
}
return months.reverse();
}
function dayLabel(iso) {
const [year, month, day] = String(iso).split('-');
return `${day}-${month}-${year}`;
}
function reportPayload(payload) {
if (!payload) return null;
if (payload.body !== undefined) {
let body = payload.body;
if (typeof body === 'string') {
try {
body = JSON.parse(body);
} catch {
return null;
}
}
return body?.data || null;
}
return payload.data || null;
}
export default function HorizonFieldWorkReport() {
const { domain } = useAuth();
const allowed = domain === 'horizon';
const months = useMemo(() => reportMonths(), []);
const [selected, setSelected] = useState(() => {
const current = monthName(new Date());
return months.includes(current) ? current : months[0];
});
const [month, setMonth] = useState(selected);
const [loading, setLoading] = useState(allowed);
const [error, setError] = useState('');
const [report, setReport] = useState(null);
const [exporting, setExporting] = useState(false);
useEffect(() => {
if (!allowed) return undefined;
let cancelled = false;
setLoading(true);
setError('');
signedGet('reports', 'horizon_reports/field_work_report', { month }, { timeout: REPORT_TIMEOUT }).then((response) => {
if (cancelled) return;
const data = reportPayload(response);
if (!isSuccess(response) || !data || typeof data !== 'object') {
setReport(null);
setError(response?.message || 'Unable to load the field work report.');
return;
}
setReport(data);
}).finally(() => {
if (!cancelled) setLoading(false);
});
return () => {
cancelled = true;
};
}, [allowed, month]);
const days = Array.isArray(report?.days) ? report.days : [];
const rows = Array.isArray(report?.rows) ? report.rows : [];
const columnCount = IDENTITY.length + days.length * 2 + 1;
const handleSubmit = (event) => {
event.preventDefault();
setMonth(selected);
};
const handleExport = async () => {
setExporting(true);
setError('');
try {
const slug = String(month || 'report').toLowerCase().replace(/\s+/g, '-');
await exportFieldWorkReport(report, `horizon-field-work-${slug}.xlsx`);
} catch (err) {
setError(err.message || 'Unable to export the field work report.');
} finally {
setExporting(false);
}
};
if (!allowed || report?.access === false) {
return (
<Container fluid>
<PageMetaData title={TITLE} />
<div className="card mt-3">
<div className="card-body">
<h4 className="page-title">{TITLE}</h4>
<div className="alert alert-danger mb-0" role="alert">You do not have access to this report.</div>
</div>
</div>
</Container>
);
}
return (
<Container fluid>
<PageMetaData title={TITLE} />
<div className="card mt-3">
<div className="card-body">
<h4 className="page-title mb-0">{TITLE}</h4>
{error ? <div className="alert alert-danger mt-3" role="alert">{error}</div> : null}
<Form onSubmit={handleSubmit} className="row g-2 align-items-end mt-2">
<div className="col-md-4">
<Form.Label htmlFor="horizon-field-month">Month</Form.Label>
<Form.Select id="horizon-field-month" value={selected} onChange={(event) => setSelected(event.target.value)}>
{months.map((option) => (
<option key={option} value={option}>{option}</option>
))}
</Form.Select>
</div>
<div className="col-auto">
<Button type="submit" variant="primary" disabled={loading}>Show report</Button>
</div>
{!loading && rows.length ? (
<div className="col-auto">
<Button variant="outline-primary" onClick={handleExport} disabled={exporting}>
{exporting ? 'Exporting...' : 'Download Excel'}
</Button>
</div>
) : null}
</Form>
{loading ? <p className="text-muted fw-bold mt-2 mb-0">Loading the report wait.....</p> : null}
</div>
</div>
{!loading && report ? (
<div className="card">
<div className="card-body">
<div className="table-responsive" style={{ maxHeight: '70vh' }}>
<table className="table table-bordered table-sm mb-0 text-nowrap">
<thead>
<tr>
{IDENTITY.map((label) => (
<th key={label} rowSpan={2} className="align-middle text-center">{label}</th>
))}
{days.map((day) => (
<th key={day} colSpan={2} className="text-center">{dayLabel(day)}</th>
))}
<th rowSpan={2} className="align-middle text-center">RBM/ZBM wise Total</th>
</tr>
<tr>
{days.map((day) => (
<Fragment key={day}>
<th className="text-center">Link</th>
<th className="text-center">Time</th>
</Fragment>
))}
</tr>
</thead>
<tbody>
{rows.length ? rows.map((row) => (
<tr key={`${row.employee_code}-${row.position_name}-${row.name}`}>
<td>{row.name}</td>
<td>{row.employee_code}</td>
<td>{row.role_name}</td>
<td>{row.position_name}</td>
<td>{row.manager_1_code}</td>
<td>{row.manager_1_name}</td>
<td>{row.manager_2_code}</td>
<td>{row.manager_2_name}</td>
{days.map((day) => {
const cell = row.days?.[day] || { status: 'blank' };
if (cell.status === 'link' && cell.link) {
return (
<Fragment key={day}>
<td className="text-center">
<a href={cell.link} target="_blank" rel="noreferrer">Link</a>
</td>
<td className="text-center">{cell.time}</td>
</Fragment>
);
}
if (cell.status === 'no') {
return <td key={day} colSpan={2} className="text-center">No</td>;
}
return <td key={day} colSpan={2} />;
})}
<td className="text-center">{row.total ?? 0}</td>
</tr>
)) : null}
{rows.length ? (
<tr className="fw-semibold">
<td colSpan={IDENTITY.length + days.length * 2}>Total</td>
<td className="text-center">{rows.reduce((sum, row) => sum + Number(row.total || 0), 0)}</td>
</tr>
) : (
<tr>
<td colSpan={columnCount}>No rows for this month.</td>
</tr>
)}
</tbody>
</table>
</div>
</div>
</div>
) : null}
</Container>
);
}

View File

@ -0,0 +1,118 @@
const IDENTITY = [
'RBM/ZBM Name',
'Emp Code',
'Role Name',
'Position Name',
'Manager 1 Code',
'Manager 1 Name',
'Manager 2 Code',
'Manager 2 Name',
];
function dayLabel(iso) {
const [year, month, day] = String(iso).split('-');
return `${day}-${month}-${year}`;
}
function textCell(sheet, row, column, value) {
const cell = sheet.getCell(row, column);
cell.value = value === null || value === undefined ? '' : String(value);
cell.alignment = { vertical: 'middle', horizontal: 'center', wrapText: true };
return cell;
}
export async function exportFieldWorkReport(report, filename) {
const { default: ExcelJS } = await import('exceljs');
const workbook = new ExcelJS.Workbook();
const sheet = workbook.addWorksheet('Field Work');
const days = Array.isArray(report?.days) ? report.days : [];
const rows = Array.isArray(report?.rows) ? report.rows : [];
const identityCount = IDENTITY.length;
const lastColumn = identityCount + days.length * 2 + 1;
textCell(sheet, 1, 1, 'Monthly Field Work Report');
sheet.getCell(1, 1).font = { bold: true };
sheet.getCell(1, 1).alignment = { vertical: 'middle', horizontal: 'left' };
IDENTITY.forEach((label, index) => {
const column = index + 1;
textCell(sheet, 2, column, label);
sheet.mergeCells(2, column, 3, column);
sheet.getCell(2, column).font = { bold: true };
});
days.forEach((day, index) => {
const column = identityCount + index * 2 + 1;
textCell(sheet, 2, column, dayLabel(day));
sheet.mergeCells(2, column, 2, column + 1);
sheet.getCell(2, column).font = { bold: true };
textCell(sheet, 3, column, 'Link');
textCell(sheet, 3, column + 1, 'Time');
sheet.getCell(3, column).font = { bold: true };
sheet.getCell(3, column + 1).font = { bold: true };
});
textCell(sheet, 2, lastColumn, 'RBM/ZBM wise Total');
sheet.mergeCells(2, lastColumn, 3, lastColumn);
sheet.getCell(2, lastColumn).font = { bold: true };
rows.forEach((row, rowIndex) => {
const excelRow = rowIndex + 4;
const values = [
row.name,
row.employee_code,
row.role_name,
row.position_name,
row.manager_1_code,
row.manager_1_name,
row.manager_2_code,
row.manager_2_name,
];
values.forEach((value, index) => {
const cell = textCell(sheet, excelRow, index + 1, value);
if (index === 0 || index === 2 || index === 3 || index === 5 || index === 7) {
cell.alignment = { vertical: 'middle', horizontal: 'left' };
}
});
days.forEach((day, index) => {
const column = identityCount + index * 2 + 1;
const cell = row.days?.[day] || { status: 'blank', link: '', time: '' };
if (cell.status === 'link' && cell.link) {
const linkCell = sheet.getCell(excelRow, column);
linkCell.value = { text: 'Link', hyperlink: cell.link };
linkCell.font = { color: { argb: 'FF0563C1' }, underline: true };
linkCell.alignment = { vertical: 'middle', horizontal: 'center' };
textCell(sheet, excelRow, column + 1, cell.time || '');
} else if (cell.status === 'no') {
sheet.mergeCells(excelRow, column, excelRow, column + 1);
textCell(sheet, excelRow, column, 'No');
} else {
sheet.mergeCells(excelRow, column, excelRow, column + 1);
textCell(sheet, excelRow, column, '');
}
});
textCell(sheet, excelRow, lastColumn, row.total ?? 0);
});
if (rows.length) {
const totalRow = rows.length + 4;
const columnTotal = rows.reduce((sum, row) => sum + Number(row.total || 0), 0);
textCell(sheet, totalRow, 1, 'Total');
sheet.getCell(totalRow, 1).font = { bold: true };
sheet.getCell(totalRow, 1).alignment = { vertical: 'middle', horizontal: 'left' };
textCell(sheet, totalRow, lastColumn, columnTotal);
sheet.getCell(totalRow, lastColumn).font = { bold: true };
}
for (let column = 1; column <= lastColumn; column += 1) {
sheet.getColumn(column).width = column <= identityCount ? 22 : 14;
}
const buffer = await workbook.xlsx.writeBuffer();
const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
const anchor = document.createElement('a');
anchor.href = URL.createObjectURL(blob);
anchor.download = filename;
document.body.appendChild(anchor);
anchor.click();
document.body.removeChild(anchor);
URL.revokeObjectURL(anchor.href);
}

View File

@ -16,6 +16,43 @@ function uniquePeriods(periods) {
}); });
} }
function isTeamView(flag) {
return flag === true || flag === 1 || flag === '1' || flag === 'true' || flag === 'yes';
}
function teamRowsFromGroups(groups) {
for (const group of asArray(groups)) {
const rows = asArray(group?.teams);
if (rows.length) return rows;
}
return [];
}
function rowsWithMetrics(rows, readInfo) {
const metrics = [];
const users = rows.map((row, index) => {
const info = readInfo(row);
const metricValues = {};
asArray(row?.metrics).forEach((metric, metricIndex) => {
const metricId = metric?.metric || metric?.title || `m${metricIndex}`;
const metricName = metric?.name || metric?.display || metric?.title || metricId;
if (index === 0) metrics.push({ id: metricId, name: metricName });
metricValues[metricId] = metric?.value ?? 0;
});
return {
rank: row?.rank ?? index + 1,
name: info.name || '',
avatar: info.avatar || '',
employee_code: info.employee_code || '',
designation: info.designation || '',
position_name: info.position_name || '',
score: row?.score ?? 0,
metric_values: metricValues,
};
});
return { metrics, users };
}
function buildPills(leaderboardId, selectedRoleId, rankRoles, groups, period) { function buildPills(leaderboardId, selectedRoleId, rankRoles, groups, period) {
let roles = asArray(rankRoles); let roles = asArray(rankRoles);
if (!roles.length) { if (!roles.length) {
@ -36,12 +73,52 @@ function buildPills(leaderboardId, selectedRoleId, rankRoles, groups, period) {
}); });
} }
function withTeamPill(pills, leaderboardId, period, roleId, hasTeams) {
if (!hasTeams) return pills;
const params = new URLSearchParams({ id: leaderboardId });
if (period) params.set('period', period);
return [
{ label: 'Teams', to: `/leaderboard/dashboard?${params.toString()}`, active: !roleId, roleId: 'teams' },
...pills.map((pill) => ({ ...pill, active: Boolean(roleId) && pill.active })),
];
}
function periodLabelFrom(view) {
const firstDay = view.firstDay || '';
const lastDay = view.lastDay || '';
return `${firstDay}${firstDay && lastDay ? ' – ' : ''}${lastDay}`.trim();
}
function shapeView({ id, roleId, period, dashboard, item }) { function shapeView({ id, roleId, period, dashboard, item }) {
const view = dashboard?.view || {}; const view = dashboard?.view || {};
const groups = asArray(dashboard?.leaderboard); const groups = asArray(dashboard?.leaderboard);
const periods = uniquePeriods(view.periods); const periods = uniquePeriods(view.periods);
const selectedPeriod = String(period || view.interval || 'all') || 'all'; const selectedPeriod = String(period || view.interval || 'all') || 'all';
const pills = buildPills(id, roleId, item?.rank_roles, groups, period); const teamRows = teamRowsFromGroups(groups);
const title = view.name || item?.name || 'Leaderboard';
const periodLabel = periodLabelFrom(view);
const hasTeams = isTeamView(view.team_view) || teamRows.length;
const pills = withTeamPill(buildPills(id, roleId, item?.rank_roles, groups, period), id, period, roleId, hasTeams);
if (hasTeams && !roleId) {
const shaped = rowsWithMetrics(teamRows, (row) => {
const team = row?.team || {};
const name = String(team.name || '').trim();
return { name: name || 'Team', avatar: team.icon || '' };
});
return {
error: '',
isTeam: true,
title,
periodLabel,
periods,
selectedPeriod,
users: shaped.users,
metrics: shaped.metrics,
pills,
selectedRole: '',
};
}
const selected = const selected =
groups.find((group) => { groups.find((group) => {
@ -53,7 +130,8 @@ function shapeView({ id, roleId, period, dashboard, item }) {
if (!selected) { if (!selected) {
return { return {
error: 'No data found for this role.', error: 'No data found for this role.',
title: view.name || item?.name || 'Leaderboard', isTeam: false,
title,
periodLabel: '', periodLabel: '',
periods, periods,
selectedPeriod, selectedPeriod,
@ -66,44 +144,19 @@ function shapeView({ id, roleId, period, dashboard, item }) {
const roleConfig = selected.role || {}; const roleConfig = selected.role || {};
const limit = Number(roleConfig.limit) > 0 ? Number(roleConfig.limit) : 0; const limit = Number(roleConfig.limit) > 0 ? Number(roleConfig.limit) : 0;
const roleTitle = String(roleConfig.title || '').trim() || 'Role';
const rows = asArray(selected.users); const rows = asArray(selected.users);
const limited = limit > 0 ? rows.slice(0, limit) : rows; const limited = limit > 0 ? rows.slice(0, limit) : rows;
const shaped = rowsWithMetrics(limited, (row) => row?.user || {});
const metrics = [];
const users = limited.map((row, index) => {
const info = row?.user || {};
const metricValues = {};
asArray(row?.metrics).forEach((metric, metricIndex) => {
const metricId = metric?.metric || metric?.title || `m${metricIndex}`;
const metricName = metric?.name || metric?.display || metric?.title || metricId;
if (index === 0) metrics.push({ id: metricId, name: metricName });
metricValues[metricId] = metric?.value ?? 0;
});
return {
rank: row?.rank ?? index + 1,
name: info.name || '',
avatar: info.avatar || '',
employee_code: info.employee_code || '',
designation: info.designation || '',
position_name: info.position_name || '',
score: row?.score ?? 0,
metric_values: metricValues,
};
});
const firstDay = view.firstDay || '';
const lastDay = view.lastDay || '';
const periodLabel = `${firstDay}${firstDay && lastDay ? ' – ' : ''}${lastDay}`.trim();
return { return {
error: '', error: '',
title: view.name || item?.name || 'Leaderboard', isTeam: false,
title,
periodLabel, periodLabel,
periods, periods,
selectedPeriod, selectedPeriod,
users, users: shaped.users,
metrics, metrics: shaped.metrics,
pills, pills,
selectedRole, selectedRole,
}; };
@ -172,20 +225,19 @@ export default function LeaderboardDashboard() {
const pills = view?.pills || []; const pills = view?.pills || [];
const users = view?.users || []; const users = view?.users || [];
const metrics = view?.metrics || []; const metrics = view?.metrics || [];
const isTeam = Boolean(view?.isTeam);
const exportRows = useMemo(() => { const exportRows = useMemo(() => {
const header = ['Rank', 'User', 'Employee Code', 'Designation', 'Position', 'Score', ...metrics.map((metric) => metric.name)]; const metricHeaders = metrics.map((metric) => metric.name);
const body = users.map((user) => [ const metricCells = (user) => metrics.map((metric) => user.metric_values?.[metric.id] ?? '');
user.rank, const header = isTeam ? ['Rank', 'Team', 'Score', ...metricHeaders] : ['Rank', 'User', 'Employee Code', 'Designation', 'Position', 'Score', ...metricHeaders];
user.name, const body = users.map((user) =>
user.employee_code, isTeam
user.designation, ? [user.rank, user.name, user.score, ...metricCells(user)]
user.position_name, : [user.rank, user.name, user.employee_code, user.designation, user.position_name, user.score, ...metricCells(user)],
user.score, );
...metrics.map((metric) => user.metric_values?.[metric.id] ?? ''),
]);
return [header, ...body]; return [header, ...body];
}, [users, metrics]); }, [users, metrics, isTeam]);
const onPeriodChange = (value) => { const onPeriodChange = (value) => {
const next = new URLSearchParams(searchParams); const next = new URLSearchParams(searchParams);
@ -259,9 +311,13 @@ export default function LeaderboardDashboard() {
<thead className="table-light"> <thead className="table-light">
<tr> <tr>
<th>Rank</th> <th>Rank</th>
<th>User</th> <th>{isTeam ? 'Team' : 'User'}</th>
<th>Employee Code</th> {isTeam ? null : (
<th>Designation / Position</th> <>
<th>Employee Code</th>
<th>Designation / Position</th>
</>
)}
<th>Score</th> <th>Score</th>
{metrics.map((metric) => ( {metrics.map((metric) => (
<th key={metric.id}>{metric.name}</th> <th key={metric.id}>{metric.name}</th>
@ -270,7 +326,7 @@ export default function LeaderboardDashboard() {
</thead> </thead>
<tbody> <tbody>
{users.map((user) => ( {users.map((user) => (
<tr key={`${user.employee_code}-${user.rank}`}> <tr key={`${user.name}-${user.rank}`}>
<td>{user.rank}</td> <td>{user.rank}</td>
<td> <td>
<div className="d-flex align-items-center"> <div className="d-flex align-items-center">
@ -280,16 +336,20 @@ export default function LeaderboardDashboard() {
<span>{user.name || '-'}</span> <span>{user.name || '-'}</span>
</div> </div>
</td> </td>
<td>{user.employee_code || '-'}</td> {isTeam ? null : (
<td> <>
{user.designation || '-'} <td>{user.employee_code || '-'}</td>
{user.position_name ? ( <td>
<> {user.designation || '-'}
<br /> {user.position_name ? (
<small className="text-muted">{user.position_name}</small> <>
</> <br />
) : null} <small className="text-muted">{user.position_name}</small>
</td> </>
) : null}
</td>
</>
)}
<td>{user.score}</td> <td>{user.score}</td>
{metrics.map((metric) => ( {metrics.map((metric) => (
<td key={metric.id}>{user.metric_values?.[metric.id] ?? '—'}</td> <td key={metric.id}>{user.metric_values?.[metric.id] ?? '—'}</td>