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/components/form/RankRolesField.jsx b/src/components/form/RankRolesField.jsx index 2a74568..2db422f 100644 --- a/src/components/form/RankRolesField.jsx +++ b/src/components/form/RankRolesField.jsx @@ -8,7 +8,7 @@ function patchRow(rows, index, patch) { } 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 }) { @@ -32,6 +32,8 @@ export default function RankRolesField({ field, control }) { Title Role + View Mode + Show Limit Sort Order @@ -59,6 +61,25 @@ export default function RankRolesField({ field, control }) { ))} + + rhf.onChange(patchRow(rows, index, { view_mode: e.target.value }))} + > + + + + + + + rhf.onChange(patchRow(rows, index, { scope: e.target.value }))} + > + + + + !item.permission || permissions.includes(item.permission)); if (hasAny(permissions, ['workflow_definition_get_all', 'workflow_instance_get_all'])) { diff --git a/src/modules/leaderboards.js b/src/modules/leaderboards.js index 376c103..f61999e 100644 --- a/src/modules/leaderboards.js +++ b/src/modules/leaderboards.js @@ -141,7 +141,6 @@ const leaderboards = { roles, required: true, fullwidth: true, - showIf: { leaderboard_roles_type: 'roles' }, }, { key: 'metrics', @@ -212,7 +211,13 @@ const leaderboards = { next.leaderboard_team_ids = asArray(next.leaderboard_team_ids); next.manager_details = asArray(next.manager_details); 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 : []) .map((row) => ({ metric: row.metric || '', @@ -253,6 +258,8 @@ const leaderboards = { role: row.role || '', limit: row.limit === '' || row.limit == null ? 10 : Number(row.limit), 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 : []) .filter((row) => row.metric) diff --git a/src/routes/index.jsx b/src/routes/index.jsx index 8c1fda0..ff84e47 100644 --- a/src/routes/index.jsx +++ b/src/routes/index.jsx @@ -86,6 +86,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')); @@ -101,6 +103,7 @@ const GoalProficiencyReport = lazy(() => import('@/views/coachingtooldashboard/G const AdherencePobDriveReport = lazy(() => import('@/views/adherencepobdrivereport/Report')); const IvaReportPage = lazy(() => import('@/views/ivareport/ReportPage')); const InsightsGlossaryForm = lazy(() => import('@/views/insights/GlossaryForm')); +const HorizonFieldWorkReport = lazy(() => import('@/views/horizonreport/Report')); function moduleRoutes(config) { const routes = [ @@ -200,6 +203,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), @@ -246,6 +251,7 @@ export const routes = [ { path: '/ivareport/kamwise', element: }, { path: '/ivareport/drbrandwise', element: }, { path: '/ivareport/skuwise', element: }, + { path: '/horizonreport/fieldwork', element: }, { path: '/coming-soon', element: }, { path: '*', element: }, ], 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} +
+ ); +} diff --git a/src/views/horizonreport/Report.jsx b/src/views/horizonreport/Report.jsx new file mode 100644 index 0000000..b39edc9 --- /dev/null +++ b/src/views/horizonreport/Report.jsx @@ -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 ( + + +
+
+

{TITLE}

+
You do not have access to this report.
+
+
+
+ ); + } + + return ( + + +
+
+

{TITLE}

+ {error ?
{error}
: null} +
+
+ Month + setSelected(event.target.value)}> + {months.map((option) => ( + + ))} + +
+
+ +
+ {!loading && rows.length ? ( +
+ +
+ ) : null} +
+ {loading ?

Loading the report wait.....

: null} +
+
+ + {!loading && report ? ( +
+
+
+ + + + {IDENTITY.map((label) => ( + + ))} + {days.map((day) => ( + + ))} + + + + {days.map((day) => ( + + + + + ))} + + + + {rows.length ? rows.map((row) => ( + + + + + + + + + + {days.map((day) => { + const cell = row.days?.[day] || { status: 'blank' }; + if (cell.status === 'link' && cell.link) { + return ( + + + + + ); + } + if (cell.status === 'no') { + return ; + } + return + + )) : null} + {rows.length ? ( + + + + + ) : ( + + + + )} + +
{label}{dayLabel(day)}RBM/ZBM wise Total
LinkTime
{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} + Link + {cell.time}No; + })} + {row.total ?? 0}
Total{rows.reduce((sum, row) => sum + Number(row.total || 0), 0)}
No rows for this month.
+
+
+
+ ) : null} +
+ ); +} diff --git a/src/views/horizonreport/exportXlsx.js b/src/views/horizonreport/exportXlsx.js new file mode 100644 index 0000000..e7f49d7 --- /dev/null +++ b/src/views/horizonreport/exportXlsx.js @@ -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); +} diff --git a/src/views/leaderboard/Dashboard.jsx b/src/views/leaderboard/Dashboard.jsx index 0066ca1..a2cd894 100644 --- a/src/views/leaderboard/Dashboard.jsx +++ b/src/views/leaderboard/Dashboard.jsx @@ -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) { let roles = asArray(rankRoles); 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 }) { const view = dashboard?.view || {}; const groups = asArray(dashboard?.leaderboard); const periods = uniquePeriods(view.periods); 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 = groups.find((group) => { @@ -53,7 +130,8 @@ function shapeView({ id, roleId, period, dashboard, item }) { if (!selected) { return { error: 'No data found for this role.', - title: view.name || item?.name || 'Leaderboard', + isTeam: false, + title, periodLabel: '', periods, selectedPeriod, @@ -66,44 +144,19 @@ function shapeView({ id, roleId, period, dashboard, item }) { const roleConfig = selected.role || {}; const limit = Number(roleConfig.limit) > 0 ? Number(roleConfig.limit) : 0; - const roleTitle = String(roleConfig.title || '').trim() || 'Role'; const rows = asArray(selected.users); const limited = limit > 0 ? rows.slice(0, limit) : rows; - - 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(); + const shaped = rowsWithMetrics(limited, (row) => row?.user || {}); return { error: '', - title: view.name || item?.name || 'Leaderboard', + isTeam: false, + title, periodLabel, periods, selectedPeriod, - users, - metrics, + users: shaped.users, + metrics: shaped.metrics, pills, selectedRole, }; @@ -172,20 +225,19 @@ export default function LeaderboardDashboard() { const pills = view?.pills || []; const users = view?.users || []; const metrics = view?.metrics || []; + const isTeam = Boolean(view?.isTeam); const exportRows = useMemo(() => { - const header = ['Rank', 'User', 'Employee Code', 'Designation', 'Position', 'Score', ...metrics.map((metric) => metric.name)]; - const body = users.map((user) => [ - user.rank, - user.name, - user.employee_code, - user.designation, - user.position_name, - user.score, - ...metrics.map((metric) => user.metric_values?.[metric.id] ?? ''), - ]); + const metricHeaders = metrics.map((metric) => metric.name); + const metricCells = (user) => metrics.map((metric) => user.metric_values?.[metric.id] ?? ''); + const header = isTeam ? ['Rank', 'Team', 'Score', ...metricHeaders] : ['Rank', 'User', 'Employee Code', 'Designation', 'Position', 'Score', ...metricHeaders]; + const body = users.map((user) => + isTeam + ? [user.rank, user.name, user.score, ...metricCells(user)] + : [user.rank, user.name, user.employee_code, user.designation, user.position_name, user.score, ...metricCells(user)], + ); return [header, ...body]; - }, [users, metrics]); + }, [users, metrics, isTeam]); const onPeriodChange = (value) => { const next = new URLSearchParams(searchParams); @@ -259,9 +311,13 @@ export default function LeaderboardDashboard() { Rank - User - Employee Code - Designation / Position + {isTeam ? 'Team' : 'User'} + {isTeam ? null : ( + <> + Employee Code + Designation / Position + + )} Score {metrics.map((metric) => ( {metric.name} @@ -270,7 +326,7 @@ export default function LeaderboardDashboard() { {users.map((user) => ( - + {user.rank}
@@ -280,16 +336,20 @@ export default function LeaderboardDashboard() { {user.name || '-'}
- {user.employee_code || '-'} - - {user.designation || '-'} - {user.position_name ? ( - <> -
- {user.position_name} - - ) : null} - + {isTeam ? null : ( + <> + {user.employee_code || '-'} + + {user.designation || '-'} + {user.position_name ? ( + <> +
+ {user.position_name} + + ) : null} + + + )} {user.score} {metrics.map((metric) => ( {user.metric_values?.[metric.id] ?? '—'}