Untitled
Anonymous
Plain Text
10/06/2025 3:01 AM
11.3 KB
17
Indexable
Never
/* eslint-disable react/prop-types */ import React, { useEffect, useMemo, useState } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { actions } from '../redux'; import { isString } from 'lodash'; import useDateTimeFormat from './useDateTimeFormat'; import Issue from '../pages/NewReports/components/HierarchyView/components/IssueFields/components/Issue'; import UserCell from '../pages/NewReports/components/HierarchyView/components/UserCell'; import { DATE_VIEW, formatDuration, TIMESHEET_DISPLAY_COLUMNS_OPTIONS } from '../utils'; import dayjs from 'dayjs'; import { sortingTime } from '../pages/NewReports/components/HierarchyView/helper'; import moment from 'moment'; import { Box } from '@mui/material'; // ✅ needed for highlighting import Project from '../pages/NewReports/components/HierarchyView/components/ProjectFields/components/Project'; // --- helpers --- const renderTime = ({ value, durationFormat, includeScheduled }) => { if (!value || value === '0/0') return ''; if (isString(value) && includeScheduled) { const [logged, scheduled] = value.split('/'); return ${formatDuration(Number(logged), durationFormat)}/${formatDuration(Number(scheduled), durationFormat)}; } return formatDuration(value, durationFormat); }; const renderCellValue = ({ value, durationFormat, includeScheduled, isProcessing, isPercentage = false, status, showZero = false, statFilter = [], }) => { if (isProcessing) return ''; if (isPercentage) return ${(value || 0).toFixed(2)}%; if (showZero && value === 0) return '0h'; const statusMap = { 1: { label: 'pending', color: '#FFF3CD' }, 2: { label: 'approved', color: '#D4EDDA' }, 3: { label: 'rejected', color: '#F8D7DA' }, }; let bgColor = 'transparent'; if (value > 0 && statusMap[status]) { const { label, color } = statusMap[status]; if (statFilter.includes(label)) { bgColor = color; } } return ( <Box sx={{ bgcolor: bgColor, display: 'flex', justifyContent: 'center', alignItems: 'center', px: 2, width: '100%', height: '100%', }} > {renderTime({ value, durationFormat, includeScheduled })} </Box> ); }; const getDateCell = (t, date, view) => { if (view === DATE_VIEW.weeks) return ${t('Week')} ${date}; else if (view === DATE_VIEW.months) return date; return ${dayjs(date).format('D ddd')}; }; export const genWeekKeyFromDate = (weekDate) => { if (!weekDate) return { key: null, dateArr: [] }; const m = moment(weekDate, ['YYYY-MM-DD', moment.ISO_8601], true); if (!m.isValid()) return { key: null, dateArr: [] }; const start = m.clone(); const end = m.clone().add(6, 'day'); const dateArr = []; const cur = start.clone(); while (cur.isSameOrBefore(end, 'day')) { dateArr.push(cur.format('YYYY-MM-DD')); cur.add(1, 'day'); } return { key: week_${start.format('YYYYMMDD')}_${end.format('YYYYMMDD')}, dateArr, }; }; const useTimesheetColumns = ({ t, data = [], weeks, dateView = 'weeks', isTeamMode, groupState, displayColumns = [], statFilter, }) => { const dispatch = useDispatch(); const { durationFormat } = useDateTimeFormat(); const { issueMap, projectMap } = useSelector((state) => state.timesheet); const { dateArr: ranges } = useMemo(() => genWeekKeyFromDate(weeks), [weeks]); const [columnData, setColumnData] = useState([]); const [totalData, setTotalData] = useState({}); const [loading, setLoading] = useState(true); useEffect(() => { if (!Array.isArray(data)) return; setLoading(true); try { // build statusMap from timesheets (date -> status) const statusMap = data.reduce((acc, entry) => { const sheets = entry.timesheets || {}; Object.values(sheets).forEach((sheet) => { Object.values(sheet.days || {}).forEach((day) => { if (day.date) acc[day.date] = day.status; }); }); return acc; }, {}); // group by project_task_author so each row represents a task (for that author/project) const grouped = {}; data.forEach((entry) => { Object.values(entry.timelogs || {}).forEach((logs) => { logs.forEach((log) => { const key = ${log.projectKey}_${log.issueId}_${log.assignee}; const hours = Number(log.hour ?? log.duration ?? 0); if (!grouped[key]) { grouped[key] = { project: log.projectKey, projectId: log.projectId, task: log.issueId, author: log.assignee, totalHours: 0, hoursByDate: {}, // { '2025-09-08': 3, ... } statusByDate: {}, // { '2025-09-08': 2, ... } (status for that date) approvedHours: 0, rejectedHours: 0, pendingHours: 0, }; } const row = grouped[key]; row.totalHours += hours; row.hoursByDate[log.date] = (row.hoursByDate[log.date] || 0) + hours; // store status for that date (statusMap is global per date) const s = statusMap[log.date] ?? null; row.statusByDate[log.date] = s; if (s === 1) row.pendingHours += hours; else if (s === 2) row.approvedHours += hours; else if (s === 3) row.rejectedHours += hours; }); }); }); const flattened = Object.values(grouped); // totals per date in the current ranges const totals = ranges.reduce((acc, d) => { acc[d] = flattened.reduce((sum, r) => sum + (r.hoursByDate?.[d] || 0), 0); return acc; }, {}); setColumnData(flattened); setTotalData(totals); } catch (err) { console.error('Timesheet flatten error:', err); setColumnData([]); setTotalData({}); } finally { setLoading(false); dispatch(actions.setIsProcessing(false)); } }, [data, weeks, ranges, dispatch]); // columns const columns = useMemo(() => { const baseCols = [ { header: t('TimesheetOverview.table.project'), accessorKey: 'project', size: 120, enableSorting: false, enableHiding: true, enableColumnFilter: false, Cell: ({ row, column }) => { const { task, projectId, project } = row.original; const projectData = projectMap?.[projectId] || {}; return <Project data={projectData} projectKey={project} issueId={task} size={column.getSize()} />; }, }, { header: t('TimesheetOverview.table.task'), accessorKey: 'task', size: 330, enableSorting: false, Cell: ({ row, column }) => { const taskId = row.original.task; const issue = issueMap?.[taskId] || {}; return <Issue data={issue} valueDisplay={issue.key} parentStyle={{ width: column.getSize() }} />; }, Footer: () => ( <span style={{ color: '#44546F', fontWeight: 550, fontSize: 15, width: '100%' }}>{t('Report.total')}</span> ), }, { header: t('TimesheetOverview.table.member'), accessorKey: 'author', size: 120, enableSorting: false, Cell: ({ row }) => <UserCell value={row.original.author} />, }, { header: t('TimesheetOverview.table.logTime'), accessorKey: 'logged', size: 120, enableResizing: false, muiTableHeadCellProps: { align: 'center' }, muiTableBodyCellProps: { align: 'center' }, muiTableFooterCellProps: { align: 'center', sx: { justifyContent: 'center' } }, aggregationFn: (key, rows) => rows.reduce((acc, r) => acc + (r.original?.totalHours || 0), 0), AggregatedCell: ({ cell }) => renderCellValue({ value: cell.getValue(), durationFormat, isProcessing: loading, status: 0, }), Cell: ({ row }) => renderCellValue({ value: row.original.totalHours, durationFormat, isProcessing: loading, status: 0, }), Footer: () => renderCellValue({ // footer = sum of totals for visible date range value: Object.values(totalData).reduce((a, v) => a + (v || 0), 0), durationFormat, isProcessing: loading, showZero: true, }), sortingFn: sortingTime, }, ].filter(Boolean); // --- Status columns (stable order: approved → rejected → pending) --- const statusCols = []; if (displayColumns.includes(TIMESHEET_DISPLAY_COLUMNS_OPTIONS[1].value)) { statusCols.push({ header: t('TimesheetOverview.table.approved'), accessorKey: 'approved', size: 130, enableResizing: false, muiTableHeadCellProps: { align: 'center' }, muiTableBodyCellProps: { align: 'center' }, muiTableFooterCellProps: { align: 'center', sx: { justifyContent: 'center' } }, aggregationFn: (key, rows) => rows.reduce((acc, r) => acc + (r.original?.approvedHours || 0), 0), AggregatedCell: ({ cell }) => renderCellValue({ value: cell.getValue(), durationFormat, isProcessing: loading, status: 0, }), Cell: ({ row }) => renderCellValue({ value: row.original.approvedHours || null, durationFormat, isProcessing: loading, status: 2, }), Footer: () => renderCellValue({ value: columnData.reduce((acc, r) => acc + (r.approvedHours || 0), 0), durationFormat, isProcessing: loading, showZero: true, }), sortingFn: sortingTime, }); } if (displayColumns.includes(TIMESHEET_DISPLAY_COLUMNS_OPTIONS[2].value)) { statusCols.push({ header: t('TimesheetOverview.table.rejected'), accessorKey: 'rejected', size: 120, enableResizing: false, muiTableHeadCellProps: { align: 'center' }, muiTableBodyCellProps: { align: 'center' }, muiTableFooterCellProps: { align: 'center', sx: { justifyContent: 'center' } }, aggregationFn: (key, rows) => rows.reduce((acc, r) => acc + (r.original?.rejectedHours || 0), 0), AggregatedCell: ({ cell }) => renderCellValue({ value: cell.getValue(), durationFormat, isProcessing: loading, status: 0, }), Cell: ({ row }) => renderCellValue({ value: row.original.rejectedHours || null, durationFormat, isProcessing: loading, status: 3, }), Footer: () => renderCellValue({ value: columnData.reduce((acc, r) => acc + (r.rejectedHours || 0), 0), durationFormat, isProcessing: loading, showZero: true, }), sortingFn: sortingTime, }); } if (displayColumns.includes(TIMESHEET_DISPLAY_COLUMNS_OPTIONS[3].value)) { statusCols.push({ header: t('TimesheetOverview.table.pending'), accessorKey: 'pending', size: 120, enableResizing: false, muiTableHeadCellProps: { align: 'center' }, muiTableBodyCellProps: { align: 'center' }, muiTableFooterCellProps: { align: 'center', sx: { justifyContent: 'center' } }, aggregationFn: (key, rows) => rows.reduce((acc, r) => acc + (r.original?.pendingHours || 0), 0), AggregatedCell: ({ cell }) => renderCellValue({ value: cell.getValue(), durationFormat, isProcessing: loading, status: 0, }), Cell: ({ row }) => renderCellValue({ value: row.original.pendingHours || null, durationFormat, isProcessing: loading, status: 1, }), Footer: () => renderCellValue({ value: columnData.reduce((acc, r) => acc + (r.pendingHours || 0), 0), durationFormat, isProcessing: loading, showZero: true, }), sortingFn: sortingTime, }); } const dateCols = ranges.map((date) => ({ size: 110, header: getDateCell(t, date, dateView), accessorKey: date, enableResizing: false, muiTableHeadCellProps: { align: 'center', sx: { borderLeft: '1px solid #E0E0E0', display: 'flex', justifyContent: 'center', alignItems: 'center' }, }, muiTableBodyCellProps: { align: 'center', sx: { borderLeft: '1px solid #E0E0E0', padding: 0 }, }, muiTableFooterCellProps: { align: 'center', sx: { borderLeft: '1px solid #E0E0E0', justifyContent: 'center' }, }, aggregationFn: (key, rows) => rows.reduce((acc, r) => acc + (r.original?.hoursByDate?.[key] || 0), 0), AggregatedCell: ({ cell }) => { const subStatuses = cell.row.subRows?.map((r) => r.original?.statusByDate?.[date]).filter(Boolean) || []; const uniqueStatuses = [...new Set(subStatuses)]; const aggStatus = uniqueStatuses.length === 1 ? uniqueStatuses[0] : null; return renderCellValue({ value: cell.getValue(), durationFormat, isProcessing: loading, status: aggStatus, statFilter, }); }, Cell: ({ row }) => renderCellValue({ value: row.original.hoursByDate?.[date] || 0, durationFormat, isProcessing: loading, status: row.original.statusByDate?.[date] ?? null, statFilter, }), Footer: () => renderCellValue({ value: totalData[date], durationFormat, isProcessing: loading, }), sortingFn: sortingTime, })); return [...baseCols, ...statusCols, ...dateCols]; }, [ranges, totalData, durationFormat, loading, t, dateView, isTeamMode, issueMap, groupState, columnData]); return { columns, columnData, totalData, loading }; }; export default useTimesheetColumns;Editor is loading...
Leave a Comment