Skip to content

Commit 907e602

Browse files
Merge pull request #3688 from OneCommunityGlobal/Taariq_fix_Weekly_Summary_Reports_Team_Code_Changes_on_refresh
Taariq fix weekly summary reports team code changes on refresh
2 parents 7fb718d + 21da9ee commit 907e602

3 files changed

Lines changed: 92 additions & 119 deletions

File tree

src/components/Badge/__tests__/NewBadges.test.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@ describe('NewBadges component', () => {
151151
expect(badgeImages).toHaveLength(3);
152152

153153
fireEvent.mouseEnter(badgeImages[0]);
154-
screen.findByText(/Early Bird/);
154+
await screen.findByText(/Early Bird/);
155155
});
156156

157157
it('should filter out badges earned older than a week', async () => {

src/components/Projects/WBS/wbs.test.jsx

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
// eslint-disable-next-line no-unused-vars
12
import React from 'react';
23
import { render, screen, waitFor } from '@testing-library/react';
34
import '@testing-library/jest-dom/extend-expect';
@@ -8,8 +9,6 @@ import configureStore from 'redux-mock-store';
89
import WBS from './wbs';
910
import { setWBSStart, setWBS } from '../../../actions/wbs';
1011

11-
12-
1312
jest.mock('../../../actions/wbs', () => ({
1413
addNewWBS: jest.fn(),
1514
fetchAllWBS: jest.fn(),
@@ -45,7 +44,7 @@ describe('WBS Component', () => {
4544
frontPermissions: ['deleteWbs', 'addWbs', 'fetchAllWBS'],
4645
backPermissions: [],
4746
},
48-
role: "Manager",
47+
role: 'Manager',
4948
},
5049
},
5150
role: { roles: [] },
@@ -74,6 +73,7 @@ describe('WBS Component', () => {
7473
});
7574

7675
it('dispatches setWBSStart and setWBS when fetchAllWBS is called on mount', async () => {
76+
jest.setTimeout(10000);
7777
const mockWBSData = [{ _id: 'wbs1', wbsName: 'WBS 1' }];
7878
axios.get.mockResolvedValueOnce({ data: mockWBSData });
7979

@@ -82,11 +82,11 @@ describe('WBS Component', () => {
8282
expect(store.dispatch).toHaveBeenCalledWith(setWBSStart());
8383

8484
await waitFor(() => {
85+
expect(store.dispatch).toHaveBeenCalledWith(setWBSStart());
8586
expect(store.dispatch).toHaveBeenCalledWith(setWBS(mockWBSData));
8687
});
8788
});
8889

89-
9090
it('renders AddWBS component', () => {
9191
renderComponent();
9292
expect(screen.getByTestId('add-wbs')).toBeInTheDocument();
@@ -114,5 +114,4 @@ describe('WBS Component', () => {
114114
expect(screen.getByText('#')).toBeInTheDocument();
115115
expect(screen.getByText('Name')).toBeInTheDocument();
116116
});
117-
118-
});
117+
});

src/components/WeeklySummariesReport/WeeklySummariesReport.jsx

Lines changed: 86 additions & 112 deletions
Original file line numberDiff line numberDiff line change
@@ -207,92 +207,27 @@ const WeeklySummariesReport = props => {
207207
}
208208
};
209209

210-
// Initial data loading
211210
const createIntialSummaries = async () => {
212211
try {
213-
const {
214-
allBadgeData,
215-
getWeeklySummariesReport,
216-
fetchAllBadges,
217-
hasPermission,
218-
auth,
219-
setTeamCodes,
220-
} = props;
221-
222-
// Get the active tab from session storage or use default
223-
const activeTab =
224-
sessionStorage.getItem('tabSelection') === null
225-
? navItems[1]
226-
: sessionStorage.getItem('tabSelection');
227-
228-
// Get the week index for the active tab
229-
const weekIndex = navItems.indexOf(activeTab);
230-
231-
// console.log(`Initial load: Fetching data for tab ${activeTab} with weekIndex ${weekIndex}`);
212+
const initialTabIndex = 0;
213+
const activeTab = navItems[initialTabIndex];
232214

233-
// Set initial loading and active tab state
234-
setState(prevState => ({
235-
...prevState,
236-
loading: true,
237-
activeTab,
238-
tabsLoading: {
239-
...prevState.tabsLoading,
240-
[activeTab]: true,
241-
},
242-
}));
243-
244-
// Get permissions
245-
const badgeStatusCode = await fetchAllBadges();
246-
setPermissionState(prev => ({
247-
...prev,
248-
bioEditPermission: hasPermission('putUserProfileImportantInfo'),
249-
canEditSummaryCount: hasPermission('putUserProfileImportantInfo'),
250-
codeEditPermission:
251-
hasPermission('editTeamCode') ||
252-
auth.user.role === 'Owner' ||
253-
auth.user.role === 'Administrator',
254-
canSeeBioHighlight: hasPermission('highlightEligibleBios'),
255-
}));
256-
257-
// Fetch data for the active tab only
258-
const res = await getWeeklySummariesReport(weekIndex);
259-
// console.log('API response:', res);
260-
// console.log('Response data:', res?.data);
261-
// console.log('Data is array:', Array.isArray(res?.data));
262-
// console.log('Data length:', res?.data?.length);
215+
const res = await props.getWeeklySummariesReport(initialTabIndex);
263216
const summaries = res?.data ?? [];
264217

265-
if (!Array.isArray(summaries) || summaries.length === 0) {
266-
setState(prevState => ({
267-
...prevState,
268-
loading: false,
269-
tabsLoading: {
270-
...prevState.tabsLoading,
271-
[activeTab]: false,
272-
},
273-
}));
274-
return null;
275-
}
276-
277-
// Process the data
278-
const teamCodeGroup = {};
279-
const teamCodes = [];
280-
281-
// Shallow copy and sort
282218
let summariesCopy = [...summaries];
283219
summariesCopy = alphabetize(summariesCopy);
284220

285-
// Add new key of promised hours by week
286221
summariesCopy = summariesCopy.map(summary => {
287222
const promisedHoursByWeek = weekDates.map(weekDate =>
288223
getPromisedHours(weekDate.toDate, summary.weeklycommittedHoursHistory),
289224
);
290-
291225
const filterColor = summary.filterColor || null;
292-
293226
return { ...summary, promisedHoursByWeek, filterColor };
294227
});
295228

229+
const teamCodeGroup = {};
230+
const teamCodes = [];
296231
const colorOptionGroup = new Set();
297232
const colorOptions = [];
298233
const COLORS = [
@@ -318,7 +253,6 @@ const WeeklySummariesReport = props => {
318253
'#C8A2C8',
319254
];
320255

321-
// Process team codes and colors
322256
summariesCopy.forEach(summary => {
323257
const code = summary.teamCode || 'noCodeLabel';
324258
if (teamCodeGroup[code]) {
@@ -327,70 +261,61 @@ const WeeklySummariesReport = props => {
327261
teamCodeGroup[code] = [summary];
328262
}
329263

330-
if (summary.weeklySummaryOption) colorOptionGroup.add(summary.weeklySummaryOption);
264+
if (summary.weeklySummaryOption) {
265+
colorOptionGroup.add(summary.weeklySummaryOption);
266+
}
331267
});
332268

333269
Object.keys(teamCodeGroup).forEach(code => {
334270
if (code !== 'noCodeLabel') {
335271
teamCodes.push({
336272
value: code,
337273
label: `${code} (${teamCodeGroup[code].length})`,
338-
_ids: teamCodeGroup[code]?.map(item => item._id),
274+
_ids: teamCodeGroup[code].map(item => item._id),
339275
});
340276
}
341277
});
342278

343-
setTeamCodes(teamCodes);
279+
if (teamCodeGroup.noCodeLabel?.length > 0) {
280+
teamCodes.push({
281+
value: '',
282+
label: `Select All With NO Code (${teamCodeGroup.noCodeLabel.length})`,
283+
_ids: teamCodeGroup.noCodeLabel.map(item => item._id),
284+
});
285+
}
344286

345287
colorOptionGroup.forEach(option => {
346-
colorOptions.push({
347-
value: option,
348-
label: option,
349-
});
288+
colorOptions.push({ value: option, label: option });
350289
});
351290

352-
colorOptions.sort((a, b) => `${a.label}`.localeCompare(`${b.label}`));
353-
teamCodes
354-
.sort((a, b) => `${a.label}`.localeCompare(`${b.label}`))
355-
.push({
356-
value: '',
357-
label: `Select All With NO Code (${teamCodeGroup.noCodeLabel?.length || 0})`,
358-
_ids: teamCodeGroup?.noCodeLabel?.map(item => item._id),
359-
});
291+
colorOptions.sort((a, b) => a.label.localeCompare(b.label));
292+
teamCodes.sort((a, b) => a.label.localeCompare(b.label));
360293

361294
const chartData = [];
362295

363-
// Store the data in the tab-specific state
364296
setState(prevState => ({
365297
...prevState,
366298
loading: false,
367-
allRoleInfo: [],
299+
activeTab,
368300
summaries: summariesCopy,
369-
loadedTabs: [activeTab],
370-
summariesByTab: {
371-
[activeTab]: summariesCopy,
372-
},
373-
badges: allBadgeData,
374-
hasSeeBadgePermission: badgeStatusCode === 200,
375301
filteredSummaries: summariesCopy,
302+
loadedTabs: [activeTab],
303+
summariesByTab: { [activeTab]: summariesCopy },
376304
tableData: teamCodeGroup,
377305
chartData,
378306
COLORS,
379307
colorOptions,
380308
teamCodes,
381309
teamCodeWarningUsers: summariesCopy.filter(s => s.teamCodeWarning),
382-
auth,
383-
tabsLoading: {
384-
[activeTab]: false,
385-
},
310+
tabsLoading: { ...prevState.tabsLoading, [activeTab]: false },
311+
selectedCodes: [],
386312
}));
387313

388-
// Now load info collections
314+
// 🔐 Now load info collections
389315
await intialInfoCollections(summariesCopy);
390-
391-
return summariesCopy;
392316
} catch (error) {
393-
// console.error('Error in createInitialSummaries:', error);
317+
// eslint-disable-next-line no-console
318+
console.error('Error in createInitialSummaries:', error);
394319
setState(prevState => ({
395320
...prevState,
396321
loading: false,
@@ -399,7 +324,6 @@ const WeeklySummariesReport = props => {
399324
[prevState.activeTab]: false,
400325
},
401326
}));
402-
return null;
403327
}
404328
};
405329

@@ -763,10 +687,20 @@ const WeeklySummariesReport = props => {
763687
};
764688

765689
const handleSelectCodeChange = event => {
766-
setState(prev => ({
767-
...prev,
768-
selectedCodes: event,
769-
}));
690+
setState(prev => {
691+
const selectedValues = event.map(e => e.value);
692+
// Move selected codes to the front of the dropdown list // newly added
693+
const reorderedTeamCodes = [
694+
...prev.teamCodes.filter(code => selectedValues.includes(code.value)), // selected first
695+
...prev.teamCodes.filter(code => !selectedValues.includes(code.value)), // then the rest
696+
];
697+
698+
return {
699+
...prev,
700+
selectedCodes: event,
701+
teamCodes: reorderedTeamCodes,
702+
};
703+
});
770704
};
771705

772706
const handleOverHoursToggleChange = () => {
@@ -939,6 +873,11 @@ const WeeklySummariesReport = props => {
939873
_ids: updatedSummaries.filter(s => s.teamCode === replaceCode).map(s => s._id),
940874
});
941875

876+
const reorderedTeamCodes = [
877+
updatedSelectedCodes[0], // the newly replaced code on top
878+
...updatedTeamCodes.filter(tc => tc.value !== updatedSelectedCodes[0].value),
879+
];
880+
942881
const updatedWarningUsers = [...teamCodeWarningUsers];
943882
updatedUsers.forEach(({ userId, teamCodeWarning }) => {
944883
const existingIndex = updatedWarningUsers.findIndex(user => user._id === userId);
@@ -961,7 +900,9 @@ const WeeklySummariesReport = props => {
961900
setState(prev => ({
962901
...prev,
963902
summaries: updatedSummaries,
964-
teamCodes: updatedTeamCodes,
903+
// teamCodes: updatedTeamCodes,
904+
teamCodes: reorderedTeamCodes,
905+
// selectedCodes: [],
965906
selectedCodes: updatedSelectedCodes,
966907
replaceCode: '',
967908
replaceCodeError: null,
@@ -1068,10 +1009,12 @@ const WeeklySummariesReport = props => {
10681009
let isMounted = true;
10691010
window._isMounted = isMounted;
10701011

1071-
// console.log('Initial useEffect running');
1072-
1073-
// Only load the initial tab, nothing else
1074-
createIntialSummaries();
1012+
// Wrap createIntialSummaries in an async fn so we can await it
1013+
const loadInitialData = async () => {
1014+
await createIntialSummaries();
1015+
};
1016+
// Kick off the async load on mount
1017+
loadInitialData();
10751018

10761019
return () => {
10771020
isMounted = false;
@@ -1103,6 +1046,37 @@ const WeeklySummariesReport = props => {
11031046
state.summaries,
11041047
state.activeTab,
11051048
]);
1049+
1050+
useEffect(() => {
1051+
// On mount: fetch all badges before deriving permissions
1052+
const fetchInitialPermissions = async () => {
1053+
try {
1054+
// Fetch all badges first so we can derive up‑to‑date permissions
1055+
await props.fetchAllBadges();
1056+
setPermissionState(prev => ({
1057+
...prev,
1058+
bioEditPermission: props.hasPermission('putUserProfileImportantInfo'),
1059+
// codeEditPermission: props.hasPermission('replaceTeamCodes'),
1060+
// allow team‑code edits for specific roles or permissions
1061+
codeEditPermission:
1062+
props.hasPermission('editTeamCode') ||
1063+
props.auth?.user?.role === 'Owner' ||
1064+
props.auth?.user?.role === 'Administrator',
1065+
// Permit editing of summary hour counts if the user has that badge
1066+
canEditSummaryCount: props.hasPermission('editSummaryHoursCount'),
1067+
// Show bio highlights only to users with that permission
1068+
canSeeBioHighlight: props.hasPermission('highlightEligibleBios'),
1069+
}));
1070+
} catch (error) {
1071+
// log failure fetching badges or permissions
1072+
// eslint-disable-next-line no-console
1073+
console.error('Failed to fetch badges or permissions', error);
1074+
}
1075+
};
1076+
1077+
fetchInitialPermissions();
1078+
}, []);
1079+
11061080
const { role, darkMode } = props;
11071081
const { error } = props;
11081082
const hasPermissionToFilter = role === 'Owner' || role === 'Administrator';

0 commit comments

Comments
 (0)