-
-
Notifications
You must be signed in to change notification settings - Fork 77
Expand file tree
/
Copy pathWeeklyProjectSummary.jsx
More file actions
618 lines (576 loc) · 19.7 KB
/
WeeklyProjectSummary.jsx
File metadata and controls
618 lines (576 loc) · 19.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
// export default WeeklyProjectSummary;
/* eslint-disable import/no-unresolved */
import { useState, useEffect, useMemo, useRef } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { v4 as uuidv4 } from 'uuid';
import html2canvas from 'html2canvas';
import { jsPDF } from 'jspdf';
import { toast } from 'react-toastify';
import WeeklyProjectSummaryHeader from './WeeklyProjectSummaryHeader';
import CostPredictionChart from './CostPredictionChart';
import ToolStatusDonutChart from './ToolStatusDonutChart/ToolStatusDonutChart';
import PaidLaborCost from './PaidLaborCost/PaidLaborCost';
import { fetchAllMaterials } from '../../../actions/bmdashboard/materialsActions';
import QuantityOfMaterialsUsed from './QuantityOfMaterialsUsed/QuantityOfMaterialsUsed';
import ProjectRiskProfileOverview from './ProjectRiskProfileOverview';
import IssuesBreakdownChart from './IssuesBreakdownChart';
import InjuryCategoryBarChart from './GroupedBarGraphInjurySeverity/InjuryCategoryBarChart';
import ToolsHorizontalBarChart from './Tools/ToolsHorizontalBarChart';
import ExpenseBarChart from './Financials/ExpenseBarChart';
import ActualVsPlannedCost from './ActualVsPlannedCost/ActualVsPlannedCost';
import TotalMaterialCostPerProject from './TotalMaterialCostPerProject/TotalMaterialCostPerProject';
import EmbedInteractiveMap from '../InteractiveMap/EmbedInteractiveMap';
import InteractiveMap from '../InteractiveMap/InteractiveMap';
import styles from './WeeklyProjectSummary.module.css';
import IssueCharts from '../Issues/openIssueCharts';
import SupplierPerformanceGraph from './SupplierPerformanceGraph.jsx';
import MostFrequentKeywords from './MostFrequentKeywords/MostFrequentKeywords';
import DistributionLaborHours from './DistributionLaborHours/DistributionLaborHours';
const projectStatusButtons = [
{
title: 'Total Projects',
value: 426,
change: '+16% week over week',
bgColor: '#F0FFEE',
buttonColor: '#BAF0B6',
textColor: '#328D1B',
},
{
title: 'Completed Projects',
value: 127,
change: '+14% week over week',
bgColor: '#F3FCFF',
buttonColor: '#C1EFFB',
textColor: '#328D1B',
},
{
title: 'Delayed Projects',
value: 34,
change: '-18% week over week',
bgColor: '#FFE9FA',
buttonColor: '#FECFF3',
textColor: '#C82F2F',
},
{
title: 'Active Projects',
value: 265,
change: '+3% week over week',
bgColor: '#E8E8FF',
buttonColor: '#CBCBFE',
textColor: '#328D1B',
},
{
title: 'Avg Project Duration',
value: '17 hrs',
change: '+13% week over week',
bgColor: '#FFF6EE',
buttonColor: '#FFD8A5',
textColor: '#FFD8A5',
},
{
title: 'Total Material Cost',
value: '$27.6K',
change: '+9% week over week',
bgColor: '#FFF3F3',
buttonColor: '#FBC1C2',
textColor: '#328D1B',
},
{
title: 'Total Material Used',
value: '2714',
change: '+11% week over week',
bgColor: '#DAC8FF',
buttonColor: '#B28ECC',
textColor: '#328D1B',
},
{
title: 'Active Projects',
value: '265',
change: '+3% week over week',
bgColor: '#E8E8FF',
buttonColor: '#CBCBFE',
textColor: '#328D1B',
},
{
title: 'Total Labor Hours Invested',
value: '12.8K',
change: '+17% week over week',
bgColor: '#E5C1FC',
buttonColor: '#F6E1FB',
textColor: '#328D1B',
},
{
title: 'Total Labor Cost',
value: '$18.4K',
change: '+14% week over week',
bgColor: '#FFFDF3',
buttonColor: '#FBF9C1',
textColor: '#328D1B',
},
{
title: 'Material Available',
value: 693,
change: '-8% week over week',
bgColor: '#B4D9C5',
buttonColor: '#31BD41',
textColor: '#C82F2F',
},
{
title: 'Material Wasted',
value: 879,
change: '+14% week over week',
bgColor: '#EFBABB',
buttonColor: '#F79395',
textColor: '#328D1B',
},
];
export function WeeklyProjectSummaryContent() {
const dispatch = useDispatch();
const materials = useSelector(state => state.materials?.materialslist || []);
const [openSections, setOpenSections] = useState({});
const [isGeneratingPDF, setIsGeneratingPDF] = useState(false);
const darkMode = useSelector(state => state.theme.darkMode);
const projectFilter = useSelector(state => state.weeklyProjectSummary?.projectFilter || '');
const dateRangeFilter = useSelector(state => state.weeklyProjectSummary?.dateRangeFilter || '');
const getColorScheme = percentage => {
if (percentage === '-') return 'neutral';
if (percentage > 0) return 'positive';
if (percentage < 0) return 'negative';
return 'neutral';
};
const colorScheme = getColorScheme(monthOverMonth);
const titleClass = title.replace(/\s+/g, '-').toLowerCase();
return (
<div
className={`financial-card ${colorScheme} custom-box-shadow financial-card-background-${titleClass}`}
onMouseEnter={() => setShowTooltip(true)}
onMouseLeave={() => setShowTooltip(false)}
>
<div className="financial-card-title">{title}</div>
<div className={`financial-card-ellipse financial-card-ellipse-${titleClass}`} />
<div className="financial-card-value">{value === '-' ? '-' : value.toLocaleString()}</div>
<div className={`financial-card-month-over-month ${colorScheme}`}>
{monthOverMonth === '-'
? '-'
: `${monthOverMonth > 0 ? '+' : ''}${monthOverMonth}% month over month`}
</div>
{showTooltip && Object.keys(additionalInfo).length > 0 && (
<div className="financial-card-tooltip">
{Object.entries(additionalInfo).map(([key]) => (
<div key={key} className="financial-card-tooltip-item">
<span className="tooltip-key">{key}:</span>
<span className="tooltip-value">{value}</span>
</div>
))}
</div>
)}
</div>
);
}
function WeeklyProjectSummary() {
const dispatch = useDispatch();
const materials = useSelector(state => state.materials?.materialslist || []);
const [openSections, setOpenSections] = useState({});
const [isGeneratingPDF, setIsGeneratingPDF] = useState(false);
const darkMode = useSelector(state => state.theme.darkMode);
const projectFilter = useSelector(state => state.weeklyProjectSummary?.projectFilter || '');
const dateRangeFilter = useSelector(state => state.weeklyProjectSummary?.dateRangeFilter || '');
const containerRef = useRef(null);
useEffect(() => {
if (materials.length === 0) {
dispatch(fetchAllMaterials());
}
}, [dispatch, materials.length]);
const quantityOfMaterialsUsedData = useMemo(() => {
if (!materials.length) return [];
const uniqueMaterials = Array.from(new Map(materials.map(m => [m._id, m])).values());
return uniqueMaterials;
}, [materials]);
const toggleSection = category => {
setOpenSections(prev => ({
...prev,
[category]: !prev[category],
}));
};
const sections = useMemo(
() => [
{
title: 'Risk profile for projects',
key: 'Risk profile for projects',
className: 'full',
content: <ProjectRiskProfileOverview />,
},
{
title: 'Project Status',
key: 'Project Status',
className: 'full',
content: (
<div className={`${styles.projectStatusGrid}`}>
{projectStatusButtons.map(button => {
const uniqueId = uuidv4();
return (
<div
key={uniqueId}
className={`${styles.weeklyProjectSummaryCard} ${styles.statusCard}`}
style={{ backgroundColor: button.bgColor }}
>
<div className={`${styles.weeklyCardTitle}`}>{button.title}</div>
<div
className={`${styles.weeklyStatusButton}`}
style={{ backgroundColor: button.buttonColor }}
>
<span className={`${styles.weeklyStatusValue}`}>{button.value}</span>
</div>
<div className="weekly-status-change" style={{ color: button.textColor }}>
{button.change}
</div>
</div>
);
})}
</div>
),
},
{
title: 'Issues Breakdown',
key: 'Issues Breakdown',
className: 'full',
content: (
<div className={`${styles.weeklyProjectSummaryCard} ${styles.fullCard}`}>
<IssuesBreakdownChart />
</div>
),
},
{
title: 'Material Consumption',
key: 'Material Consumption',
className: 'full',
content: [1, 2, 3].map((_, index) => {
let content;
if (index === 1) {
content = <QuantityOfMaterialsUsed data={quantityOfMaterialsUsedData} />;
} else if (index === 2) {
content = <TotalMaterialCostPerProject />;
} else {
content = <p>📊 Card</p>;
}
const uniqueId = uuidv4();
return (
<div
key={uniqueId}
className={`${styles.weeklyProjectSummaryCard} ${styles.normalCard}`}
>
{content}
</div>
);
}),
},
{
title: 'Issue Tracking',
key: 'Issue Tracking',
className: 'full',
content: (
<div className={`${styles.weeklyProjectSummaryCard} ${styles.normalCard}`}>
<IssueCharts />
</div>
),
},
{
title: 'Tools and Equipment Tracking',
key: 'Tools and Equipment Tracking',
className: 'full',
content: (
<div className="weekly-project-summary-card normal-card tools-tracking-layout">
<div className="tools-donut-wrap">
<ToolStatusDonutChart />
</div>
<div className="weekly-project-summary-card normal-card" style={{ minHeight: '300px' }}>
<ToolsHorizontalBarChart darkMode={darkMode} />
</div>
<div
className="weekly-project-summary-card normal-card"
style={{ minHeight: '300px', gridColumn: 'span 2' }}
>
<SupplierPerformanceGraph />
</div>
</div>
),
},
{
title: 'Lessons Learned',
key: 'Lessons Learned',
className: 'half',
content: [
<div
key="frequent-tags-card"
className={`${styles.weeklyProjectSummaryCard} ${styles.normalCard}`}
style={{ minHeight: '520px', height: 'auto', overflow: 'visible' }}
>
<MostFrequentKeywords darkMode={darkMode} />
</div>,
<div
key="injury-chart"
className={`${styles.weeklyProjectSummaryCard} ${styles.normalCard}`}
>
<InjuryCategoryBarChart />
</div>,
],
},
{
title: 'Financials',
key: 'Financials',
className: 'large',
content: (
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '10px' }}>
<div className="weekly-project-summary-card financial-small">📊 Card</div>
<div className="weekly-project-summary-card financial-small financial-chart">
<ExpenseBarChart />
</div>
<div className="weekly-project-summary-card financial-small">📊 Card</div>
<div className="weekly-project-summary-card financial-small">📊 Card</div>
<div className="weekly-project-summary-card financial-big">📊 Big Card</div>
</div>
),
},
{
title: 'Loss Tracking',
key: 'Loss Tracking',
className: 'small',
content: (
<div className={`${styles.weeklyProjectSummaryCard} ${styles.normalCard}`}>📊 Card</div>
),
},
{
title: 'Global Distribution and Project Status Overview',
key: 'Global Distribution and Project Status',
className: 'full',
content: (
<div
className={`${styles.weeklyProjectSummaryCard} ${styles.mapCard}`}
style={{ height: '500px', padding: '0' }}
>
<InteractiveMap />
</div>
),
},
{
title: 'Labor and Time Tracking',
key: 'Labor and Time Tracking',
className: 'half',
content: [1, 2].map((_, index) => {
const uniqueId = uuidv4();
return (
<div
key={uniqueId}
className={`${styles.weeklyProjectSummaryCard} ${styles.normalCard}`}
>
{index === 1 ? <PaidLaborCost /> : <DistributionLaborHours />}
</div>
);
}),
},
{
title: 'Financials Tracking',
key: 'Financials Tracking',
className: 'full',
content: [1, 2, 3, 4].map((_, index) => {
const uniqueId = uuidv4();
return (
<div
key={uniqueId}
className={`${styles.weeklyProjectSummaryCard} ${styles.normalCard}`}
>
{(() => {
if (index === 2) return <CostPredictionChart projectId={1} />;
if (index === 3) return <ActualVsPlannedCost />;
return '📊 Card';
})()}
</div>
);
}),
},
],
[quantityOfMaterialsUsedData, darkMode],
);
const handleSaveAsPDF = async () => {
// Prevent multiple simultaneous PDF generations
if (isGeneratingPDF) {
return;
}
const currentOpenSections = { ...openSections };
setIsGeneratingPDF(true);
// Show loading toast
const loadingToastId = toast.info('Generating PDF...', {
position: 'top-right',
autoClose: false,
closeOnClick: false,
pauseOnHover: false,
});
try {
// Open all sections for PDF export
const allSectionsOpen = {};
sections.forEach(section => {
allSectionsOpen[section.key] = true;
});
setOpenSections(allSectionsOpen);
// Wait for sections to render
// eslint-disable-next-line no-promise-executor-return
await new Promise(resolve => setTimeout(resolve, 500));
// Try to find the container using ref first, then fallback to querySelector
const contentElement =
containerRef.current || document.querySelector(`.${styles.weeklyProjectSummaryContainer}`);
if (!contentElement) {
throw new Error(
'Weekly project summary container not found. Please refresh the page and try again.',
);
}
// Create PDF container
const pdfContainer = document.createElement('div');
pdfContainer.id = 'pdf-export-container';
Object.assign(pdfContainer.style, {
width: '420mm',
padding: '10mm',
backgroundColor: '#fff',
position: 'absolute',
left: '-9999px',
top: '0',
boxSizing: 'border-box',
zIndex: '-1',
});
// Clone the content
const clonedContent = contentElement.cloneNode(true);
clonedContent
.querySelectorAll(
'button, .weekly-project-summary-dropdown-icon, .no-print, .weekly-summary-header-controls',
)
.forEach(el => {
if (el.parentNode) {
el.parentNode.removeChild(el);
}
});
// Add styles for PDF
const styleElem = document.createElement('style');
styleElem.textContent = `
img, svg {
height: auto !important;
page-break-inside: avoid !important;
}
* {
-webkit-print-color-adjust: exact !important;
print-color-adjust: exact !important;
}
`;
clonedContent.prepend(styleElem);
pdfContainer.appendChild(clonedContent);
document.body.appendChild(pdfContainer);
// Wait a bit for styles to apply
// eslint-disable-next-line no-promise-executor-return
await new Promise(resolve => setTimeout(resolve, 300));
// Generate canvas from HTML
const canvas = await html2canvas(pdfContainer, {
scale: 2,
useCORS: true,
backgroundColor: '#fff',
windowWidth: pdfContainer.scrollWidth,
windowHeight: pdfContainer.scrollHeight,
logging: false,
allowTaint: false,
});
if (!canvas) {
throw new Error('Failed to capture content as image. Please try again.');
}
const imgData = canvas.toDataURL('image/jpeg', 0.95);
if (!imgData || imgData === 'data:,') {
throw new Error('Failed to generate image data. Please try again.');
}
const pdfWidth = 210; // A4 width in mm
const imgHeight = (canvas.height * pdfWidth) / canvas.width;
// Create PDF
// eslint-disable-next-line new-cap
const pdf = new jsPDF({
orientation: imgHeight > pdfWidth ? 'portrait' : 'landscape',
unit: 'mm',
format: [pdfWidth, imgHeight],
});
pdf.addImage(imgData, 'JPEG', 0, 0, pdfWidth, imgHeight);
// Generate filename with project and date range
const now = new Date();
const dateStr = now.toISOString().slice(0, 10);
const projectName = projectFilter || 'All-Projects';
const dateRange = dateRangeFilter
? dateRangeFilter.replace(/\s+/g, '-').replace(/,/g, '')
: dateStr;
const fileName = `weekly-project-summary-${projectName}-${dateRange}.pdf`;
pdf.save(fileName);
// Clean up
if (document.body.contains(pdfContainer)) {
document.body.removeChild(pdfContainer);
}
// Dismiss loading toast and show success
toast.dismiss(loadingToastId);
toast.success('PDF generated and downloaded successfully!', {
position: 'top-right',
autoClose: 3000,
});
} catch (err) {
// Dismiss loading toast
toast.dismiss(loadingToastId);
// Show error message
const errorMessage =
err?.message ||
'Failed to generate PDF. Please try again or contact support if the issue persists.';
toast.error(errorMessage, {
position: 'top-right',
autoClose: 5000,
});
// Log error for debugging
// eslint-disable-next-line no-console
console.error('PDF generation failed:', err);
// Clean up PDF container if it exists
const pdfContainer = document.getElementById('pdf-export-container');
if (pdfContainer && document.body.contains(pdfContainer)) {
document.body.removeChild(pdfContainer);
}
} finally {
setOpenSections(currentOpenSections);
setIsGeneratingPDF(false);
}
};
return (
<div
ref={containerRef}
className={`weekly-project-summary-container ${styles.weeklyProjectSummaryContainer} ${
darkMode ? styles.darkMode : ''
}`}
data-testid="weekly-project-summary-container"
>
<WeeklyProjectSummaryHeader
handleSaveAsPDF={handleSaveAsPDF}
isGeneratingPDF={isGeneratingPDF}
/>
<div className={`${styles.weeklyProjectSummaryDashboardContainer}`}>
<div className={`${styles.weeklyProjectSummaryDashboardGrid}`}>
{sections.map(({ title, key, className, content }) => (
<div
key={key}
className={`${styles.weeklyProjectSummaryDashboardSection} ${styles[className]}`}
>
<button
type="button"
className={styles.weeklyProjectSummaryDashboardCategoryTitle}
onClick={() => toggleSection(key)}
>
{title} <span>{openSections[key] ? '∧' : '∨'}</span>
</button>
{openSections[key] && (
<div className={`${styles.weeklyProjectSummaryDashboardCategoryContent}`}>
{content}
</div>
)}
</div>
))}
</div>
</div>
</div>
);
}
export default WeeklyProjectSummary;