roles leaderboard changes

This commit is contained in:
Abhijit 2026-11-27 14:43:24 +05:30
parent 4f0c1a2e5e
commit e4ddd2de13
5 changed files with 208 additions and 64 deletions

View File

@ -201,6 +201,19 @@
color: #4a4a4a; color: #4a4a4a;
box-shadow: 0 12px 18px rgba(0, 0, 0, 0.08); box-shadow: 0 12px 18px rgba(0, 0, 0, 0.08);
} }
.mlb-rank-list { margin-top: 14px; }
.mlb-rank-row {
display: flex;
align-items: center;
gap: 10px;
padding: 8px 10px;
border-radius: 12px;
background: #fff;
margin-bottom: 8px;
}
.mlb-rank-no { width: 22px; font-weight: 700; color: #6b6b6b; }
.mlb-rank-name { flex: 1; font-weight: 600; color: #1f1f1f; }
.mlb-rank-score { font-weight: 700; }
.mlb-bar.rank-1 { height: 128px; background: #f3d34a; } .mlb-bar.rank-1 { height: 128px; background: #f3d34a; }
.mlb-bar.rank-2 { height: 92px; background: #d5d8e0; } .mlb-bar.rank-2 { height: 92px; background: #d5d8e0; }
.mlb-bar.rank-3 { height: 68px; background: #ff8b3d; } .mlb-bar.rank-3 { height: 68px; background: #ff8b3d; }

View File

@ -1,4 +1,4 @@
import { Controller } from 'react-hook-form'; import { Controller, useWatch } from 'react-hook-form';
import { Button, Form, Table } from 'react-bootstrap'; import { Button, Form, Table } from 'react-bootstrap';
function patchRow(rows, index, patch) { function patchRow(rows, index, patch) {
@ -8,11 +8,12 @@ function patchRow(rows, index, patch) {
} }
function emptyRow() { function emptyRow() {
return { title: '', role: '', limit: 10, sort_order: 0, view_mode: 'versus', scope: 'domain' }; return { title: '', role: '', limit: 10, sort_order: 0, view_mode: 'versus', scope: 'domain', show_as: 'user', highlight_count: 0, highlight_color: '' };
} }
export default function RankRolesField({ field, control }) { export default function RankRolesField({ field, control }) {
const roles = field.roles || {}; const roles = field.roles || {};
const isTeam = useWatch({ control, name: 'leaderboard_roles_type' }) === 'team';
return ( return (
<Controller <Controller
name={field.key} name={field.key}
@ -33,8 +34,11 @@ export default function RankRolesField({ field, control }) {
<th>Title</th> <th>Title</th>
<th>Role</th> <th>Role</th>
<th>View Mode</th> <th>View Mode</th>
<th>Show</th> {isTeam ? <th>What to show</th> : null}
{isTeam ? <th>Show</th> : null}
<th>Limit</th> <th>Limit</th>
<th>Highlight</th>
<th>Color</th>
<th>Sort Order</th> <th>Sort Order</th>
<th /> <th />
</tr> </tr>
@ -50,6 +54,7 @@ export default function RankRolesField({ field, control }) {
</td> </td>
<td> <td>
<Form.Select <Form.Select
disabled={isTeam && row.show_as === 'team'}
value={row.role || ''} value={row.role || ''}
onChange={(e) => rhf.onChange(patchRow(rows, index, { role: e.target.value }))} onChange={(e) => rhf.onChange(patchRow(rows, index, { role: e.target.value }))}
> >
@ -71,15 +76,32 @@ export default function RankRolesField({ field, control }) {
<option value="list">List</option> <option value="list">List</option>
</Form.Select> </Form.Select>
</td> </td>
<td> {isTeam ? (
<Form.Select <td>
value={row.scope === 'state_head' ? 'state_head' : 'domain'} <Form.Select
onChange={(e) => rhf.onChange(patchRow(rows, index, { scope: e.target.value }))} value={row.show_as === 'team' ? 'team' : 'user'}
> onChange={(e) => rhf.onChange(patchRow(rows, index, {
<option value="domain">Domain wise</option> show_as: e.target.value,
<option value="state_head">State head wise</option> ...(e.target.value === 'team' ? { role: '', scope: 'domain' } : {}),
</Form.Select> }))}
</td> >
<option value="user">Users</option>
<option value="team">Teams</option>
</Form.Select>
</td>
) : null}
{isTeam ? (
<td>
<Form.Select
disabled={row.show_as === 'team'}
value={row.scope === 'own_team' ? 'own_team' : 'domain'}
onChange={(e) => rhf.onChange(patchRow(rows, index, { scope: e.target.value }))}
>
<option value="domain">Domain wise</option>
<option value="own_team">Own team</option>
</Form.Select>
</td>
) : null}
<td> <td>
<Form.Control <Form.Control
type="number" type="number"
@ -88,6 +110,21 @@ export default function RankRolesField({ field, control }) {
onChange={(e) => rhf.onChange(patchRow(rows, index, { limit: e.target.value }))} onChange={(e) => rhf.onChange(patchRow(rows, index, { limit: e.target.value }))}
/> />
</td> </td>
<td>
<Form.Control
type="number"
min={0}
value={row.highlight_count ?? 0}
onChange={(e) => rhf.onChange(patchRow(rows, index, { highlight_count: e.target.value }))}
/>
</td>
<td>
<Form.Control
type="color"
value={/^#[0-9A-Fa-f]{6}$/.test(row.highlight_color || '') ? row.highlight_color : '#ffffff'}
onChange={(e) => rhf.onChange(patchRow(rows, index, { highlight_color: e.target.value }))}
/>
</td>
<td> <td>
<Form.Control <Form.Control
type="number" type="number"

View File

@ -215,7 +215,11 @@ const leaderboards = {
.map((row) => ({ .map((row) => ({
...row, ...row,
view_mode: ['versus', 'podium', 'list'].includes(row.view_mode) ? row.view_mode : 'versus', view_mode: ['versus', 'podium', 'list'].includes(row.view_mode) ? row.view_mode : 'versus',
scope: row.scope === 'state_head' ? 'state_head' : 'domain', show_as: next.leaderboard_roles_type === 'team' && row.show_as === 'team' ? 'team' : 'user',
role: row.show_as === 'team' ? '' : (row.role || ''),
scope: next.leaderboard_roles_type === 'team' && row.show_as !== 'team' && row.scope === 'own_team' ? 'own_team' : 'domain',
highlight_count: Number(row.highlight_count) > 0 ? Number(row.highlight_count) : 0,
highlight_color: /^#[0-9A-Fa-f]{6}$/.test(row.highlight_color || '') ? row.highlight_color : '',
})) }))
.sort(bySortOrder); .sort(bySortOrder);
next.metrics = (Array.isArray(next.metrics) ? next.metrics : []) next.metrics = (Array.isArray(next.metrics) ? next.metrics : [])
@ -252,15 +256,21 @@ const leaderboards = {
payload.bg_color = Array.isArray(payload.bg_color) ? '' : payload.bg_color || ''; payload.bg_color = Array.isArray(payload.bg_color) ? '' : payload.bg_color || '';
payload.default_interval = payload.default_interval ?? ''; payload.default_interval = payload.default_interval ?? '';
payload.rank_roles = (Array.isArray(payload.rank_roles) ? payload.rank_roles : []) payload.rank_roles = (Array.isArray(payload.rank_roles) ? payload.rank_roles : [])
.filter((row) => row.title || row.role) .filter((row) => row.title || row.role || row.show_as === 'team')
.map((row) => ({ .map((row) => {
title: row.title || '', const showAs = leaderboardType === 'team' && row.show_as === 'team' ? 'team' : 'user';
role: row.role || '', return {
limit: row.limit === '' || row.limit == null ? 10 : Number(row.limit), title: row.title || '',
sort_order: row.sort_order === '' || row.sort_order == null ? 0 : Number(row.sort_order), role: showAs === 'team' ? 'team' : (row.role || ''),
view_mode: ['versus', 'podium', 'list'].includes(row.view_mode) ? row.view_mode : 'versus', limit: row.limit === '' || row.limit == null ? 10 : Number(row.limit),
scope: row.scope === 'state_head' ? 'state_head' : 'domain', 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',
show_as: showAs,
scope: showAs === 'user' && leaderboardType === 'team' && row.scope === 'own_team' ? 'own_team' : 'domain',
highlight_count: Number(row.highlight_count) > 0 ? Number(row.highlight_count) : 0,
highlight_color: /^#[0-9A-Fa-f]{6}$/.test(row.highlight_color || '') ? row.highlight_color : '',
};
});
payload.metrics = (Array.isArray(payload.metrics) ? payload.metrics : []) payload.metrics = (Array.isArray(payload.metrics) ? payload.metrics : [])
.filter((row) => row.metric) .filter((row) => row.metric)
.map((row) => ({ .map((row) => ({

View File

@ -5,19 +5,31 @@ import { signedGet, isSuccess } from '@/api/client';
import { asArray, rankRoleId, rankRoleName, rankRolePillLabel, userInitials } from '@/views/dashboard/helpers'; import { asArray, rankRoleId, rankRoleName, rankRolePillLabel, userInitials } from '@/views/dashboard/helpers';
import EmptyChart from '@/views/dashboard/EmptyChart'; import EmptyChart from '@/views/dashboard/EmptyChart';
function podiumUsersFromRankRole(rankRole) { function sectionsFor(board) {
return asArray(rankRole?.users) const roleRanks = asArray(board?.role_ranks);
.slice(0, 3) if (roleRanks.length) return roleRanks;
.map((row) => { return asArray(board?.rank_roles);
const info = row.user || {}; }
const name = String(info.name || '').trim();
return { function rankedRowsFromSection(section) {
name, const people = asArray(section?.users);
initials: userInitials(name), const teams = asArray(section?.teams);
avatar: info.avatar || '', const source = people.length ? people : teams.length ? teams : (section?.team ? [section] : []);
score: Number.isFinite(Number(row.score)) ? Number(row.score) : 0, const highlightCount = Number(section?.highlight_count) > 0 ? Number(section.highlight_count) : 0;
}; const color = /^#[0-9A-Fa-f]{6}$/.test(section?.highlight_color || '') ? section.highlight_color : '';
}); return source.map((row, index) => {
const info = row.user || row.team || {};
const name = String(info.name || '').trim();
return {
rank: row.rank ?? index + 1,
name,
initials: userInitials(name),
avatar: info.avatar || info.icon || '',
score: Number.isFinite(Number(row.score)) ? Number(row.score) : 0,
highlight: Boolean(color) && index < highlightCount,
color,
};
});
} }
function Podium({ users }) { function Podium({ users }) {
@ -52,7 +64,7 @@ function Podium({ users }) {
<div className="mlb-name" title={user.name}> <div className="mlb-name" title={user.name}>
{user.name} {user.name}
</div> </div>
<div className={`mlb-bar rank-${rank}`}>{user.score}</div> <div className={`mlb-bar rank-${rank}`} style={user.highlight ? { background: user.color } : undefined}>{user.score}</div>
</> </>
) : ( ) : (
<> <>
@ -67,11 +79,31 @@ function Podium({ users }) {
); );
} }
function RankList({ rows }) {
if (!rows.length) return <p className="text-muted mb-0 mt-2">No data</p>;
return (
<div className="mlb-rank-list">
{rows.map((row) => (
<div
key={`${row.rank}-${row.name}`}
className="mlb-rank-row"
style={row.highlight ? { background: row.color } : undefined}
>
<span className="mlb-rank-no">{row.rank}</span>
<span className="mlb-rank-name">{row.name || '-'}</span>
<span className="mlb-rank-score">{row.score}</span>
</div>
))}
</div>
);
}
function LeaderboardCard({ item }) { function LeaderboardCard({ item }) {
const [activeIndex, setActiveIndex] = useState(0); const [activeIndex, setActiveIndex] = useState(0);
const pills = item.pills || []; const pills = item.pills || [];
const active = pills[activeIndex] || pills[0]; const active = pills[activeIndex] || pills[0];
const users = active?.podium_users || item.podium_users || []; const rows = active?.rows || [];
const isList = active?.view_mode === 'list';
const detailsUrl = active?.url || item.details_url || '#'; const detailsUrl = active?.url || item.details_url || '#';
return ( return (
@ -88,14 +120,11 @@ function LeaderboardCard({ item }) {
</Link> </Link>
</div> </div>
</div> </div>
<div className="mlb-podium">
<Podium users={users} />
</div>
{pills.length ? ( {pills.length ? (
<div className="mlb-pills"> <div className="mlb-pills">
{pills.map((pill, index) => ( {pills.map((pill, index) => (
<button <button
key={pill.label} key={`${pill.label}-${index}`}
type="button" type="button"
className={`mlb-pill ${index === activeIndex ? 'is-active' : ''}`} className={`mlb-pill ${index === activeIndex ? 'is-active' : ''}`}
onClick={() => setActiveIndex(index)} onClick={() => setActiveIndex(index)}
@ -105,6 +134,13 @@ function LeaderboardCard({ item }) {
))} ))}
</div> </div>
) : null} ) : null}
{isList ? (
<RankList rows={rows} />
) : (
<div className="mlb-podium">
<Podium users={rows.slice(0, 3)} />
</div>
)}
</article> </article>
</div> </div>
); );
@ -115,23 +151,28 @@ export default function MilestoneTeamLeaderboard({ widget }) {
useEffect(() => { useEffect(() => {
const load = async () => { const load = async () => {
const response = await signedGet('reports', 'roles_leaderboard/list', {}, { timeout: 120000 }); let leaderboards = [];
if (!isSuccess(response)) { try {
setItems([]); const response = await signedGet('reports', 'roles_leaderboard/list', {}, { timeout: 120000 });
return; leaderboards = isSuccess(response) ? asArray(response.data) : [];
} catch {
leaderboards = [];
} }
let leaderboards = response.data;
if (leaderboards?.items) leaderboards = leaderboards.items;
leaderboards = asArray(leaderboards);
const mapped = leaderboards.map((board) => { const mapped = leaderboards.map((board) => {
const rankRoles = asArray(board.rank_roles); const sections = sectionsFor(board);
const pills = rankRoles.map((rankRole, index) => { const pills = sections.map((section, index) => {
const limit = Number(rankRole.limit) > 0 ? Number(rankRole.limit) : 10; const limit = Number(section.limit) > 0 ? Number(section.limit) : 10;
const roleId = rankRoleId(rankRole); const roleId = section.show_as === 'team' ? '' : rankRoleId(section);
const params = new URLSearchParams({ id: board.id || '' });
if (roleId) params.set('role', roleId);
const label = section.show_as === 'team'
? (String(section.title || '').trim() || 'Teams')
: rankRolePillLabel(section.title, limit, rankRoleName(section));
return { return {
label: rankRolePillLabel(rankRole.title, limit, rankRoleName(rankRole)), label,
url: `/leaderboard/dashboard?id=${encodeURIComponent(board.id || '')}&role=${encodeURIComponent(roleId)}`, url: `/leaderboard/dashboard?${params.toString()}`,
podium_users: podiumUsersFromRankRole(rankRole), view_mode: section.view_mode || '',
rows: rankedRowsFromSection(section),
active: index === 0, active: index === 0,
}; };
}); });
@ -142,7 +183,6 @@ export default function MilestoneTeamLeaderboard({ widget }) {
title: board.name || widget.title || 'Leaderboard', title: board.name || widget.title || 'Leaderboard',
interval_label: `${start}${start && end ? ' – ' : ''}${end}`.trim(), interval_label: `${start}${start && end ? ' – ' : ''}${end}`.trim(),
details_url: pills[0]?.url || `/leaderboard/dashboard?id=${encodeURIComponent(board.id || '')}`, details_url: pills[0]?.url || `/leaderboard/dashboard?id=${encodeURIComponent(board.id || '')}`,
podium_users: pills[0]?.podium_users || [],
pills, pills,
}; };
}); });

View File

@ -56,7 +56,9 @@ function rowsWithMetrics(rows, readInfo) {
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) {
roles = asArray(groups).map((group) => group?.role || group); roles = asArray(groups)
.map((group) => group?.role)
.filter((role) => role && typeof role === 'object');
} }
roles = [...roles].sort((a, b) => Number(a?.sort_order || 0) - Number(b?.sort_order || 0)); roles = [...roles].sort((a, b) => Number(a?.sort_order || 0) - Number(b?.sort_order || 0));
return roles.map((rankRole, index) => { return roles.map((rankRole, index) => {
@ -83,6 +85,15 @@ function withTeamPill(pills, leaderboardId, period, roleId, hasTeams) {
]; ];
} }
function highlightFrom(group) {
const count = Number(group?.highlight_count ?? group?.role?.highlight_count);
const color = String(group?.highlight_color ?? group?.role?.highlight_color ?? '').trim();
return {
highlightCount: Number.isFinite(count) && count > 0 ? Math.floor(count) : 0,
highlightColor: /^#[0-9A-Fa-f]{6}$/.test(color) ? color : '',
};
}
function periodLabelFrom(view) { function periodLabelFrom(view) {
const firstDay = view.firstDay || ''; const firstDay = view.firstDay || '';
const lastDay = view.lastDay || ''; const lastDay = view.lastDay || '';
@ -98,9 +109,11 @@ function shapeView({ id, roleId, period, dashboard, item }) {
const title = view.name || item?.name || 'Leaderboard'; const title = view.name || item?.name || 'Leaderboard';
const periodLabel = periodLabelFrom(view); const periodLabel = periodLabelFrom(view);
const hasTeams = isTeamView(view.team_view) || teamRows.length; const hasTeams = isTeamView(view.team_view) || teamRows.length;
const pills = withTeamPill(buildPills(id, roleId, item?.rank_roles, groups, period), id, period, roleId, hasTeams); const rolePills = buildPills(id, roleId, item?.rank_roles, groups, period);
const configured = rolePills.length > 0;
const pills = configured ? rolePills : withTeamPill(rolePills, id, period, roleId, hasTeams);
if (hasTeams && !roleId) { if (hasTeams && !roleId && !configured) {
const shaped = rowsWithMetrics(teamRows, (row) => { const shaped = rowsWithMetrics(teamRows, (row) => {
const team = row?.team || {}; const team = row?.team || {};
const name = String(team.name || '').trim(); const name = String(team.name || '').trim();
@ -117,15 +130,18 @@ function shapeView({ id, roleId, period, dashboard, item }) {
metrics: shaped.metrics, metrics: shaped.metrics,
pills, pills,
selectedRole: '', selectedRole: '',
...highlightFrom(groups.find((group) => asArray(group?.teams).length) || null),
}; };
} }
const selected = const selected =
groups.find((group) => { groups.find((group) => {
const currentRoleId = rankRoleId(group?.role || group); const role = group?.role;
if (!role || typeof role !== 'object') return false;
const currentRoleId = rankRoleId(role);
return !roleId || currentRoleId === roleId; return !roleId || currentRoleId === roleId;
}) || null; }) || null;
const selectedRole = selected ? rankRoleId(selected.role || selected) : roleId; const selectedRole = selected ? rankRoleId(selected.role) : roleId;
if (!selected) { if (!selected) {
return { return {
@ -139,6 +155,30 @@ function shapeView({ id, roleId, period, dashboard, item }) {
metrics: [], metrics: [],
pills, pills,
selectedRole, selectedRole,
highlightCount: 0,
highlightColor: '',
};
}
const selectedTeamRows = asArray(selected?.teams);
if (selectedTeamRows.length || selected?.role?.show_as === 'team') {
const shaped = rowsWithMetrics(selectedTeamRows, (row) => {
const team = row?.team || {};
const name = String(team.name || '').trim();
return { name: name || 'Team', avatar: team.icon || '' };
});
return {
error: selectedTeamRows.length ? '' : 'No data found for this role.',
isTeam: true,
title,
periodLabel,
periods,
selectedPeriod,
users: shaped.users,
metrics: shaped.metrics,
pills,
selectedRole,
...highlightFrom(selected),
}; };
} }
@ -159,6 +199,7 @@ function shapeView({ id, roleId, period, dashboard, item }) {
metrics: shaped.metrics, metrics: shaped.metrics,
pills, pills,
selectedRole, selectedRole,
...highlightFrom(selected),
}; };
} }
@ -325,8 +366,10 @@ export default function LeaderboardDashboard() {
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{users.map((user) => ( {users.map((user, index) => {
<tr key={`${user.name}-${user.rank}`}> const highlighted = view?.highlightColor && index < Number(view?.highlightCount || 0);
return (
<tr key={`${user.name}-${user.rank}`} style={highlighted ? { backgroundColor: view.highlightColor } : undefined}>
<td>{user.rank}</td> <td>{user.rank}</td>
<td> <td>
<div className="d-flex align-items-center"> <div className="d-flex align-items-center">
@ -355,7 +398,8 @@ export default function LeaderboardDashboard() {
<td key={metric.id}>{user.metric_values?.[metric.id] ?? '—'}</td> <td key={metric.id}>{user.metric_values?.[metric.id] ?? '—'}</td>
))} ))}
</tr> </tr>
))} );
})}
</tbody> </tbody>
</Table> </Table>
</div> </div>