Merge insights-glossary: Insights glossary admin screens

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ravi Gulhane 2026-11-22 12:55:21 +05:30
commit bffcb2f848
4 changed files with 442 additions and 0 deletions

View File

@ -354,5 +354,14 @@ export function getMenuItems({ permissions = [], roles = [], domain = '', email
});
}
if (permissions.includes('insights_glossary_admin')) {
items.push({
key: 'insights',
label: 'Insights',
icon: LuChartNoAxesCombined,
children: [child('insights-glossary', 'Glossary', '/insights/glossarys', 'insights_glossary_admin')],
});
}
return items.filter((item) => !item.children || item.children.length > 0);
}

View File

@ -0,0 +1,24 @@
// Rapport Insights glossary terms (rapport/insights/functions/glossary.js).
// Listed with the generic EntityList; adding and editing use the custom
// formula builder page (src/views/insights/GlossaryForm.jsx).
const insightsglossary = {
service: 'insights',
module: 'glossary',
title: 'Glossary',
subtitle: 'Insights',
baseUrl: '/insights/glossary',
listPath: '/insights/glossarys',
deleteMethod: 'post',
listFields: [
{ key: 'actions', title: 'Actions', buttons: ['edit', 'delete'] },
{ key: 'name', title: 'Term', type: 'text' },
{ key: 'synonyms_text', title: 'Also called', type: 'text' },
{ key: 'description', title: 'Description', type: 'text' },
{ key: 'status', title: 'Status', type: 'text' },
{ key: 'updated_by_name', title: 'Updated by', type: 'text' },
{ key: 'updated_at', title: 'Updated', type: 'datetime' },
],
formFields: () => [],
};
export default insightsglossary;

View File

@ -65,6 +65,7 @@ import articlebanks from '@/modules/articlebanks';
import lmsquizs from '@/modules/lmsquizs';
import sessions from '@/modules/sessions';
import tracks from '@/modules/tracks';
import insightsglossary from '@/modules/insightsglossary';
const Login = lazy(() => import('@/views/auth/Login'));
const LoginOtp = lazy(() => import('@/views/auth/LoginOtp'));
@ -99,6 +100,7 @@ const ActionPlanReport = lazy(() => import('@/views/coachingtooldashboard/Action
const GoalProficiencyReport = lazy(() => import('@/views/coachingtooldashboard/GoalProficiencyReport'));
const AdherencePobDriveReport = lazy(() => import('@/views/adherencepobdrivereport/Report'));
const IvaReportPage = lazy(() => import('@/views/ivareport/ReportPage'));
const InsightsGlossaryForm = lazy(() => import('@/views/insights/GlossaryForm'));
function moduleRoutes(config) {
const routes = [
@ -219,6 +221,10 @@ export const routes = [
...moduleRoutes(lmsquizs),
...moduleRoutes(sessions),
...moduleRoutes(tracks),
// Rapport Insights glossary: generic list, custom add/edit page (formula builder + test).
{ path: '/insights/glossarys', element: <EntityListPage module={insightsglossary} /> },
{ path: '/insights/glossary/addnew', element: <InsightsGlossaryForm /> },
{ path: '/insights/glossary/edit', element: <InsightsGlossaryForm /> },
{ path: '/metricreports', element: <MetricReportList /> },
{ path: '/metricreport/report', element: <MetricReport /> },
{ path: '/neblogisticreports', element: <NebReportList /> },

View File

@ -0,0 +1,403 @@
// Rapport Insights glossary: add / edit a term with a guided formula builder
// and a Test panel that runs the formula on live data for the admin's own
// scope. API: rapport/insights/functions/glossary.js (insights_glossary_admin
// is required for everything on this page).
import { useEffect, useMemo, useState } from 'react';
import { Link, useNavigate, useSearchParams } from 'react-router';
import { Alert, Badge, Button, Card, Col, Container, Form, Row, Spinner, Table } from 'react-bootstrap';
import Select from 'react-select';
import { signedGet, signedPost, isSuccess } from '@/api/client';
import { useAuth } from '@/auth/AuthProvider';
import PageBreadcrumb from '@/components/PageBreadcrumb';
const LIST = '/insights/glossarys';
const AGGS = [
{ value: 'sum', label: 'Total units' },
{ value: 'count', label: 'Number of records' },
{ value: 'avg', label: 'Average units per record' },
{ value: 'distinct_contacts', label: 'Contacts reached (distinct)' },
{ value: 'distinct_users', label: 'People active (distinct)' },
];
const SOURCES = [
{ value: 'metric', label: 'A metric' },
{ value: 'contacts', label: 'Number of contacts' },
{ value: 'users', label: 'Number of people' },
];
const FILTER_OPS = [
{ value: 'eq', label: 'is' },
{ value: 'neq', label: 'is not' },
{ value: 'in', label: 'is one of' },
];
const PERIODS = [
['last_month', 'Last month'],
['this_month', 'This month'],
['last_quarter', 'Last quarter'],
['this_quarter', 'This quarter'],
['last_30_days', 'Last 30 days'],
['ytd', 'This year so far'],
['last_fy', 'Last financial year'],
];
const GROUPS = [
['', 'No grouping (one number)'],
['position', 'By position'],
['user', 'By person'],
['month', 'By month (metrics only)'],
['week', 'By week (metrics only)'],
];
const emptyOperand = (source = 'metric') => (source === 'metric' ? { source, metric_ids: [], agg: 'sum' } : { source, filters: [] });
const emptyTerm = { name: '', synonyms: '', description: '', status: 'active', formula: { kind: 'value', numerator: emptyOperand(), as_percent: false } };
/** The formula as the API wants it (drops empty filters, splits "is one of" values). */
function toApiFormula(f) {
const operand = (o) => {
if (o.source === 'metric') return { source: 'metric', metric_ids: o.metric_ids, agg: o.agg };
const filters = (o.filters || [])
.filter((x) => x.field.trim())
.map((x) => ({
field: x.field.trim(),
op: x.op,
value: x.op === 'in' ? String(x.value).split(',').map((v) => v.trim()).filter(Boolean) : String(x.value).trim(),
}));
return filters.length ? { source: o.source, filters } : { source: o.source };
};
const out = { kind: f.kind, numerator: operand(f.numerator) };
if (f.kind === 'ratio') {
out.denominator = operand(f.denominator || emptyOperand('contacts'));
out.as_percent = Boolean(f.as_percent);
}
return out;
}
/** API formula → editable state. */
function fromApiFormula(f) {
const operand = (o) =>
!o ? emptyOperand('contacts') : o.source === 'metric' ? { ...o } : { source: o.source, filters: (o.filters || []).map((x) => ({ ...x, value: Array.isArray(x.value) ? x.value.join(', ') : x.value ?? '' })) };
return { kind: f?.kind || 'value', numerator: operand(f?.numerator), denominator: f?.kind === 'ratio' ? operand(f.denominator) : undefined, as_percent: Boolean(f?.as_percent) };
}
function OperandEditor({ label, value, onChange, metrics, metricsLoading }) {
const metricOptions = useMemo(() => metrics.map((m) => ({ value: m.id, label: m.name })), [metrics]);
const selected = metricOptions.filter((o) => (value.metric_ids || []).includes(o.value));
const unknown = (value.metric_ids || []).filter((id) => !metricOptions.some((o) => o.value === id));
const setSource = (source) => onChange(emptyOperand(source));
const setFilter = (i, patch) => onChange({ ...value, filters: value.filters.map((f, j) => (j === i ? { ...f, ...patch } : f)) });
return (
<Card className="mb-3 border">
<Card.Body>
<h6 className="mb-3">{label}</h6>
<Form.Group className="mb-3">
<Form.Label>Count what</Form.Label>
<Form.Select value={value.source} onChange={(e) => setSource(e.target.value)} aria-label={`${label}: source`}>
{SOURCES.map((s) => (
<option key={s.value} value={s.value}>{s.label}</option>
))}
</Form.Select>
</Form.Group>
{value.source === 'metric' ? (
<Row>
<Col md={7}>
<Form.Group className="mb-2">
<Form.Label>Metric(s)</Form.Label>
<Select
isMulti
isLoading={metricsLoading}
options={metricOptions}
value={selected}
onChange={(opts) => onChange({ ...value, metric_ids: (opts || []).map((o) => o.value) })}
placeholder="Choose one or more metrics"
aria-label={`${label}: metrics`}
/>
{unknown.length > 0 && <Form.Text className="text-danger">{unknown.length} metric(s) in this formula are no longer active.</Form.Text>}
<Form.Text muted>Several metrics are added together.</Form.Text>
</Form.Group>
</Col>
<Col md={5}>
<Form.Group className="mb-2">
<Form.Label>Measure</Form.Label>
<Form.Select value={value.agg} onChange={(e) => onChange({ ...value, agg: e.target.value })} aria-label={`${label}: measure`}>
{AGGS.map((a) => (
<option key={a.value} value={a.value}>{a.label}</option>
))}
</Form.Select>
</Form.Group>
</Col>
</Row>
) : (
<>
<Form.Label>Only count {value.source === 'contacts' ? 'contacts' : 'people'} where (optional)</Form.Label>
{(value.filters || []).map((f, i) => (
<Row key={i} className="g-2 mb-2">
<Col md={4}>
<Form.Control value={f.field} placeholder={value.source === 'contacts' ? 'Field, e.g. type' : 'Field, e.g. designation'} onChange={(e) => setFilter(i, { field: e.target.value })} aria-label="Filter field" />
</Col>
<Col md={3}>
<Form.Select value={f.op} onChange={(e) => setFilter(i, { op: e.target.value })} aria-label="Filter operator">
{FILTER_OPS.map((o) => (
<option key={o.value} value={o.value}>{o.label}</option>
))}
</Form.Select>
</Col>
<Col md={4}>
<Form.Control value={f.value} placeholder={f.op === 'in' ? 'Values, comma separated' : 'Value'} onChange={(e) => setFilter(i, { value: e.target.value })} aria-label="Filter value" />
</Col>
<Col md={1}>
<Button variant="link" className="text-danger p-1" onClick={() => onChange({ ...value, filters: value.filters.filter((_, j) => j !== i) })} aria-label="Remove filter">✕</Button>
</Col>
</Row>
))}
{(value.filters || []).length < 10 && (
<Button size="sm" variant="outline-secondary" onClick={() => onChange({ ...value, filters: [...(value.filters || []), { field: '', op: 'eq', value: '' }] })}>
Add a condition
</Button>
)}
</>
)}
</Card.Body>
</Card>
);
}
function TestPanel({ formula, name }) {
const [period, setPeriod] = useState('last_month');
const [group, setGroup] = useState('');
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const [result, setResult] = useState(null);
const run = async () => {
setBusy(true);
setError('');
setResult(null);
const response = await signedPost('insights', 'glossary/test', { name: name || 'Value', formula: toApiFormula(formula), date_range: { relative: period }, ...(group ? { group_by: group } : {}) });
setBusy(false);
if (!isSuccess(response)) {
setError(response?.message || 'The test failed');
return;
}
setResult(response.data);
};
const show = (v, col) => {
if (v === null || v === undefined) return '-';
if (typeof v === 'number') return col?.type === 'percent' ? `${v.toLocaleString('en-IN', { maximumFractionDigits: 2 })}%` : v.toLocaleString('en-IN', { maximumFractionDigits: 2 });
return String(v);
};
const cols = result ? result.columns.filter((c) => c.key !== 'key') : [];
return (
<Card>
<Card.Body>
<h5 className="mb-1">Test on live data</h5>
<p className="text-muted small">Runs the formula for the data you can see. Nothing is saved.</p>
<Row className="g-2 align-items-end">
<Col md={5}>
<Form.Label>Period</Form.Label>
<Form.Select value={period} onChange={(e) => setPeriod(e.target.value)} aria-label="Test period">
{PERIODS.map(([v, l]) => (
<option key={v} value={v}>{l}</option>
))}
</Form.Select>
</Col>
<Col md={4}>
<Form.Label>Grouping</Form.Label>
<Form.Select value={group} onChange={(e) => setGroup(e.target.value)} aria-label="Test grouping">
{GROUPS.map(([v, l]) => (
<option key={v} value={v}>{l}</option>
))}
</Form.Select>
</Col>
<Col md={3}>
<Button className="w-100" onClick={run} disabled={busy}>
{busy ? <Spinner size="sm" /> : 'Run test'}
</Button>
</Col>
</Row>
{error && <Alert variant="danger" className="mt-3 mb-0">{error}</Alert>}
{result && (
<div className="mt-3">
<p className="small text-muted mb-2">
{[result.date_range ? `${result.date_range.from} to ${result.date_range.to}` : null, result.scope, `${result.row_count} row${result.row_count === 1 ? '' : 's'}`].filter(Boolean).join(' · ')}
</p>
<div className="table-responsive" style={{ maxHeight: 320 }}>
<Table size="sm" bordered hover className="mb-2">
<thead>
<tr>
{cols.map((c) => (
<th key={c.key} className={c.key === result.column ? 'table-primary' : undefined}>{c.key}</th>
))}
</tr>
</thead>
<tbody>
{result.rows.slice(0, 50).map((r, i) => (
<tr key={i}>
{cols.map((c) => (
<td key={c.key} className={c.key === result.column ? 'fw-semibold' : undefined}>{show(r[c.key], c)}</td>
))}
</tr>
))}
</tbody>
</Table>
</div>
{result.row_count > 50 && <p className="small text-muted">Showing 50 of {result.row_count} rows.</p>}
<details className="small text-muted">
<summary>How it was calculated</summary>
<ol className="mb-0 mt-1">
{result.steps.map((s, i) => (
<li key={i}>{s}</li>
))}
</ol>
</details>
</div>
)}
</Card.Body>
</Card>
);
}
export default function GlossaryForm() {
const [searchParams] = useSearchParams();
const id = searchParams.get('id');
const navigate = useNavigate();
const { hasPermission } = useAuth();
const allowed = hasPermission('insights_glossary_admin');
const [term, setTerm] = useState(emptyTerm);
const [metrics, setMetrics] = useState([]);
const [metricsLoading, setMetricsLoading] = useState(true);
const [loading, setLoading] = useState(Boolean(id));
const [saving, setSaving] = useState(false);
const [error, setError] = useState('');
useEffect(() => {
if (!allowed) return;
signedGet('insights', 'glossary/metrics').then((response) => {
setMetricsLoading(false);
if (isSuccess(response)) setMetrics(response.data?.items || []);
else setError(response?.message || 'Unable to load metrics');
});
}, [allowed]);
useEffect(() => {
if (!id || !allowed) return;
signedGet('insights', 'glossary/get_one', { id }).then((response) => {
setLoading(false);
if (!isSuccess(response)) {
setError(response?.message || 'Unable to load this term');
return;
}
const item = response.data.item;
setTerm({ name: item.name, synonyms: (item.synonyms || []).join(', '), description: item.description || '', status: item.status || 'active', formula: fromApiFormula(item.formula) });
});
}, [id, allowed]);
const setFormula = (patch) => setTerm((t) => ({ ...t, formula: { ...t.formula, ...patch } }));
const setKind = (kind) => setFormula(kind === 'ratio' ? { kind, denominator: term.formula.denominator || emptyOperand('contacts') } : { kind, denominator: undefined, as_percent: false });
const submit = async (event) => {
event.preventDefault();
setSaving(true);
setError('');
const body = {
...(id ? { id } : {}),
name: term.name,
synonyms: term.synonyms.split(',').map((s) => s.trim()).filter(Boolean),
description: term.description,
status: term.status,
formula: toApiFormula(term.formula),
};
const response = await signedPost('insights', id ? 'glossary/update' : 'glossary/create', body);
setSaving(false);
if (!isSuccess(response)) {
setError(response?.message || 'Save failed');
return;
}
navigate(LIST);
};
const title = id ? 'Edit glossary term' : 'New glossary term';
if (!allowed) {
return (
<Container fluid>
<PageBreadcrumb title={title} />
<Alert variant="warning" className="mt-3">You need the <code>insights_glossary_admin</code> permission to manage the Insights glossary.</Alert>
</Container>
);
}
return (
<Container fluid>
<PageBreadcrumb title={title} />
<p className="text-muted mt-2">
A term defines a business word (for example "Coverage") once, so Insights calculates it the same way for everyone. People asking about it see only their own data.
</p>
{error && <Alert variant="danger">{error}</Alert>}
{loading ? (
<Spinner />
) : (
<Row>
<Col xl={7}>
<Form onSubmit={submit}>
<Card className="mb-3">
<Card.Body>
<Row>
<Col md={6}>
<Form.Group className="mb-3" controlId="gls-name">
<Form.Label>Term</Form.Label>
<Form.Control value={term.name} maxLength={60} required onChange={(e) => setTerm({ ...term, name: e.target.value })} placeholder="e.g. Coverage" />
</Form.Group>
</Col>
<Col md={6}>
<Form.Group className="mb-3" controlId="gls-status">
<Form.Label>Status</Form.Label>
<Form.Select value={term.status} onChange={(e) => setTerm({ ...term, status: e.target.value })}>
<option value="active">Active (Insights uses it)</option>
<option value="inactive">Inactive</option>
</Form.Select>
</Form.Group>
</Col>
</Row>
<Form.Group className="mb-3" controlId="gls-synonyms">
<Form.Label>Also called</Form.Label>
<Form.Control value={term.synonyms} onChange={(e) => setTerm({ ...term, synonyms: e.target.value })} placeholder="Other words people use, comma separated (e.g. reach, doctor coverage)" />
</Form.Group>
<Form.Group controlId="gls-description">
<Form.Label>Description</Form.Label>
<Form.Control as="textarea" rows={2} maxLength={500} value={term.description} onChange={(e) => setTerm({ ...term, description: e.target.value })} placeholder="What it means, in one sentence. Insights shows this to the assistant." />
</Form.Group>
</Card.Body>
</Card>
<Card className="mb-3">
<Card.Body>
<h5 className="mb-3">Formula</h5>
<div className="mb-3">
<Form.Check inline type="radio" id="gls-kind-value" name="kind" label="A single value" checked={term.formula.kind === 'value'} onChange={() => setKind('value')} />
<Form.Check inline type="radio" id="gls-kind-ratio" name="kind" label="A ratio (one value divided by another)" checked={term.formula.kind === 'ratio'} onChange={() => setKind('ratio')} />
</div>
<OperandEditor label={term.formula.kind === 'ratio' ? 'Top (numerator)' : 'Value'} value={term.formula.numerator} onChange={(numerator) => setFormula({ numerator })} metrics={metrics} metricsLoading={metricsLoading} />
{term.formula.kind === 'ratio' && (
<>
<OperandEditor label="Bottom (denominator)" value={term.formula.denominator} onChange={(denominator) => setFormula({ denominator })} metrics={metrics} metricsLoading={metricsLoading} />
<Form.Check type="switch" id="gls-percent" label="Show as a percentage" checked={term.formula.as_percent} onChange={(e) => setFormula({ as_percent: e.target.checked })} />
</>
)}
</Card.Body>
</Card>
<div className="d-flex gap-2 mb-4">
<Button type="submit" disabled={saving}>{saving ? 'Saving…' : id ? 'Save changes' : 'Create term'}</Button>
<Link to={LIST} className="btn btn-outline-secondary">Cancel</Link>
{term.status === 'inactive' && <Badge bg="secondary" className="align-self-center">Inactive terms are not used by Insights</Badge>}
</div>
</Form>
</Col>
<Col xl={5}>
<TestPanel formula={term.formula} name={term.name} />
</Col>
</Row>
)}
</Container>
);
}