-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathmodernizationPage.tsx
More file actions
1297 lines (1184 loc) · 43.1 KB
/
Copy pathmodernizationPage.tsx
File metadata and controls
1297 lines (1184 loc) · 43.1 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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as React from "react"
import Content from "../components/Content/Content";
import Header from "../components/Header/Header";
import HeaderTools from "../components/Header/HeaderTools";
import PanelLeft from "../components/Panels/PanelLeft";
import {
Button,
Text,
Card,
makeStyles,
tokens,
Tooltip,
Spinner,
} from "@fluentui/react-components"
import {
DismissCircle24Regular,
Warning24Regular,
CheckmarkCircle24Regular,
DocumentRegular,
ChevronDown16Filled,
ChevronRight16Regular,
HistoryFilled,
bundleIcon,
HistoryRegular,
ArrowSyncRegular,
ArrowDownload24Regular,
} from "@fluentui/react-icons"
import { Light as SyntaxHighlighter } from "react-syntax-highlighter"
import { vs } from "react-syntax-highlighter/dist/esm/styles/hljs"
import sql from "react-syntax-highlighter/dist/cjs/languages/hljs/sql"
import { useNavigate, useParams } from "react-router-dom"
import { useState, useEffect } from "react"
import { getApiUrl, headerBuilder } from '../api/config';
import BatchHistoryPanel from "../components/batchHistoryPanel"
import PanelRight from "../components/Panels/PanelRight";
import PanelRightToolbar from "../components/Panels/PanelRightToolbar";
import PanelRightToggles from "../components/Header/PanelRightToggles";
import { filesLogsBuilder, BatchSummary, completedFiles, filesErrorCounter, hasFiles, renderFileError, fileErrorCounter, renderErrorContent, filesFinalErrorCounter, fileWarningCounter } from "../api/utils";
import { format } from "sql-formatter";
export const History = bundleIcon(HistoryFilled, HistoryRegular);
SyntaxHighlighter.registerLanguage("sql", sql)
const useStyles = makeStyles({
root: {
display: "flex",
flexDirection: "column",
height: "100vh",
// backgroundColor: tokens.colorNeutralBackground2,
},
content: {
display: "flex",
flex: 1,
overflow: "hidden",
},
fileIcon: {
color: tokens.colorNeutralForeground1,
marginRight: "12px",
flexShrink: 0,
fontSize: "20px",
height: "20px",
width: "20px",
},
statusContainer: {
display: "flex",
alignItems: "center",
gap: "8px",
marginLeft: "auto",
},
fileName: {
flex: 1,
overflow: "hidden",
textOverflow: "ellipsis",
whiteSpace: "nowrap",
fontWeight: "600",
},
fileList: {
display: "flex",
flexDirection: "column",
gap: "4px",
padding: "16px",
flex: 1,
overflow: "auto",
},
panelHeader: {
padding: "16px 20px",
display: "flex",
justifyContent: "space-between",
alignItems: "center",
},
fileCard: {
backgroundColor: tokens.colorNeutralBackground1,
border: `1px solid ${tokens.colorNeutralStroke1}`,
borderRadius: "4px",
padding: "12px",
display: "flex",
alignItems: "center",
cursor: "pointer",
"&:hover": {
backgroundColor: tokens.colorNeutralBackground3,
border: tokens.colorBrandBackground,
},
},
selectedCard: {
border: "var(--NeutralStroke2.Rest)",
backgroundColor: "rgb(221, 217, 217)",
},
progressFill: {
height: "100%",
backgroundColor: "#2563EB",
transition: "width 0.3s ease",
},
imageContainer: {
display: "flex",
justifyContent: "center",
marginTop: "24px",
marginBottom: "24px",
},
stepList: {
marginTop: "48px",
},
step: {
fontSize: "16px", // Increase font size
fontWeight: "400", // Make text bold (optional)
marginBottom: "48px", // Add spacing between steps
},
codeCard: {
backgroundColor: tokens.colorNeutralBackground1,
boxShadow: tokens.shadow4,
overflow: "hidden",
maxHeight: "87vh",
overflowY: "auto",
},
codeHeader: {
padding: "12px 16px",
},
summaryContent: {
padding: "24px",
},
summaryCard: {
backgroundColor: "#F2FBF2",
marginBottom: "16px",
boxShadow: "none"
},
errorContent: {
backgroundColor: "#F8DADB",
marginBottom: "16px",
boxShadow: "none"
},
errorSection: {
backgroundColor: "#F8DADB",
marginBottom: "8px",
boxShadow: "none"
},
warningSection: {
backgroundColor: tokens.colorStatusWarningBackground1,
marginBottom: "16px",
boxShadow: "none"
},
warningContent: {
backgroundColor: tokens.colorStatusWarningBackground1,
marginBottom: "16px",
paddingBottom: "22px",
paddingTop: "8px",
boxShadow: "none"
},
sectionHeader: {
display: "flex",
alignItems: "center",
justifyContent: "space-between",
cursor: "pointer",
},
errorItem: {
marginTop: "16px",
paddingLeft: "20px",
},
errorTitle: {
display: "flex",
alignItems: "center",
gap: "8px",
marginBottom: "8px",
},
errorDetails: {
marginTop: "4px",
color: tokens.colorNeutralForeground2,
paddingLeft: "20px",
},
errorSource: {
color: tokens.colorNeutralForeground2,
fontSize: "12px",
},
// Styles for the loading overlay
loadingOverlay: {
position: "absolute",
top: 0,
left: 0,
right: 0,
bottom: 0,
backgroundColor: tokens.colorNeutralBackground1,
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
zIndex: 1000,
},
loadingCard: {
width: "100%",
maxWidth: "500px",
padding: "32px",
textAlign: "center",
boxShadow: tokens.shadow16,
borderRadius: "8px",
},
loadingProgressBar: {
width: "100%",
height: "8px",
backgroundColor: tokens.colorNeutralBackground3,
borderRadius: "4px",
marginTop: "24px",
marginBottom: "8px",
overflow: "hidden",
},
loadingProgressFill: {
height: "100%",
backgroundColor: tokens.colorBrandBackground,
transition: "width 0.5s ease-out",
},
mainContent: {
flex: 1,
top: "60",
backgroundColor: "white", // Change from tokens.colorNeutralBackground1 to white
overflow: "auto",
},
progressSection: {
maxWidth: "800px",
margin: "20px auto 0", // Add top margin to move it lower in the page
display: "flex",
flexDirection: "column",
paddingTop: "20px", // Add padding at the top
},
progressBar: {
width: "100%",
height: "4px",
backgroundColor: "#E5E7EB",
borderRadius: "2px",
marginTop: "32px",
marginBottom: "16px",
overflow: "hidden",
},
buttonContainer: {
padding: "16px",
display: "flex",
justifyContent: "flex-end",
gap: "8px",
},
summaryHeader: {
display: "flex",
justifyContent: "space-between",
alignItems: "center",
padding: "12px 24px", // Replacing theme.spacing(2) with a fixed value
},
summaryTitle: {
fontSize: "12px",
},
aiGeneratedTag: {
color: "#6b7280", // Replacing theme.palette.text.secondary with a neutral gray
fontSize: "0.875rem",
backgroundColor: "#f3f4f6", // Replacing theme.palette.background.default with a light gray
padding: "4px 8px", // Replacing theme.spacing(0.5, 1)
borderRadius: "4px", // Replacing theme.shape.borderRadius with a standard value
},
queuedFile: {
borderRadius: "4px",
backgroundColor: "var(--NeutralBackgroundInvertedDisabled-Rest)", // Correct background color
opacity: 0.5, // Disabled effect
pointerEvents: "none", // Prevents clicks
},
summaryDisabled: {
borderRadius: "4px",
backgroundColor: "var(--NeutralBackgroundInvertedDisabled-Rest)", // Correct background color
opacity: 0.5, // Disabled effect
pointerEvents: "none", // Prevents clicks
},
inProgressFile: {
borderRadius: "4px",
backgroundColor: "var(--NeutralBackground1.Rest)", // Correct background color
opacity: 0.5, // Disabled effect
},
completedFile: {
borderRadius: "4px",
backgroundColor: "var(--NeutralBackground1-Rest)", // Correct background color
},
downloadButton: {
marginLeft: "auto",
display: "flex",
alignItems: "center",
gap: "4px",
},
errorBanner: {
backgroundColor: "#F8DADB",
marginBottom: "16px",
boxShadow: "none"
},
fixedButtonContainer: {
position: "absolute",
bottom: 0,
left: 0,
right: 0, /* Match your panel background color */
backgroundColor: tokens.colorNeutralBackground2,
borderTop: "1px solid #e5e7eb", /* Optional: adds a separator line */
padding: "0px 16px",
zIndex: "10",
},
panelContainer: {
display: "flex",
flexDirection: "column",
height: "100%",
position: "relative",
},
fileListContainer: {
flex: 1,
overflowY: "auto",
paddingBottom: "60px", /* Add padding to prevent content from being hidden behind the fixed buttons */
},
});
type FileType = "summary" | "code"
type FileResult = "info" | "warning" | "error" | null
interface TrackLogMessage {
batch_id: string;
file_id: string;
agent_type: string;
agent_message: string;
process_status: string;
file_result: FileResult;
}
interface FileItem {
id: string
name: string
type: FileType
status: string
code?: string
translatedCode?: string
errorCount?: number
warningCount?: number
file_logs?: any[];
file_result?: string
file_track_log?: TrackLogMessage[]
file_track_percentage: number
fileId?: string
batchId?: string
order?: number
}
// Updated function to fetch file content with translated content
const fetchFileFromAPI = async (fileId: string): Promise<any> => {
const apiUrl = getApiUrl();
try {
const response = await fetch(`${apiUrl}/file/${fileId}`, { headers: headerBuilder({}) });
if (!response.ok) {
throw new Error(`Failed to fetch file: ${response.statusText}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error("Error fetching file from API:", error);
return { content: "", translatedContent: "" };
}
};
const fetchBatchSummary = async (batchId: string): Promise<any> => {
try {
const apiUrl = getApiUrl();
const response = await fetch(`${apiUrl}/status/${batchId}/render`, { headers: headerBuilder({}) });
if (!response.ok) {
throw new Error(`Failed to fetch batch data: ${response.statusText}`);
}
const responseData = await response.json();
if (!responseData || !responseData.files) {
throw new Error("Invalid data format received from server");
}
const data: BatchSummary = {
batch_id: responseData.batch.batch_id,
upload_id: responseData.batch.id, // Use id as upload_id
date_created: responseData.batch.created_at,
total_files: responseData.batch.file_count,
completed_files: completedFiles(responseData.files),
error_count: responseData.batch.status === "completed" ? filesFinalErrorCounter(responseData.files) : filesErrorCounter(responseData.files),
status: responseData.batch.status,
warning_count: responseData.files.reduce((count, file) => count + (file.syntax_count || 0), 0),
hasFiles: hasFiles(responseData),
files: responseData.files.map(file => ({
file_id: file.file_id,
name: file.original_name, // Use original_name here
status: file.status,
file_result: file.file_result,
warning_count: fileWarningCounter(file),
error_count: fileErrorCounter(file),
translated_content: file.translated_content,
file_logs: filesLogsBuilder(file),
}))
};
return data;
} catch (error) {
console.error("Error fetchBatchSummary:", error);
return { content: "", translatedContent: "" };
}
};
const getPrintFileStatus = (status: string): string => {
switch (status) {
case "completed":
return "Completed";
case "in_process":
return "Processing";
case "Processing":
return "Pending";
case "Pending":
return "Pending";
default:
return "Queued";
}
};
const ModernizationPage = () => {
const { batchId } = useParams<{ batchId: string }>();
const navigate = useNavigate();
const [batchSummary, setBatchSummary] = useState<BatchSummary | null>(null);
const styles = useStyles();
const [text, setText] = useState("");
const [isPanelOpen, setIsPanelOpen] = React.useState(false); // Add state management
// Get batchId and fileList from Redux
const [reduxFileList, setReduxFileList] = useState<FileItem[]>([]);
// State for the loading component
const [showLoading, setShowLoading] = useState(true);
const [selectedFilebg, setSelectedFile] = useState<string | null>(null);
const [selectedFileId, setSelectedFileId] = React.useState<string>("");
const fileId = selectedFileId;
const [expandedSections, setExpandedSections] = React.useState<string[]>([]);
const [progressPercentage] = useState(0);
const [allFilesCompleted, setAllFilesCompleted] = useState(false);
const [isZipButtonDisabled, setIsZipButtonDisabled] = useState(true);
const [fileLoading, setFileLoading] = useState(false);
const [processingStarted, setProcessingStarted] = useState(false);
// Fetch file content when a file is selected
useEffect(() => {
if (selectedFileId === "summary" || !selectedFileId || fileLoading) {
return;
}
const fetchFileContent = async () => {
try {
const selectedFile = files.find((f) => f.id === selectedFileId);
if (!selectedFile || !selectedFile.translatedCode) {
setFileLoading(true);
const _newFileUpdate = await fetchFileFromAPI(selectedFile?.fileId || "");
setFileLoading(false);
}
} catch (err) {
console.error("Error fetching file content:", err);
setFileLoading(false);
}
};
fetchFileContent();
}, [selectedFileId]);
const fetchBatchData = async (batchId, isInitialLoad = true) => {
try {
if (isInitialLoad) {
setShowLoading(true);
}
const data = await fetchBatchSummary(batchId);
setBatchSummary(data);
if (data) {
const batchCompleted = data.status?.toLowerCase() === "completed" || data.status === "failed";
if (batchCompleted) {
setAllFilesCompleted(true);
if (data.hasFiles > 0) {
setIsZipButtonDisabled(false);
}
}
// Transform the server response to an array of your FileItem objects
const fileItems: FileItem[] = data.files.map((file: any, index: number) => ({
id: `file${index}`,
name: file.name,
type: "code",
status: file.status?.toLowerCase(),
file_result: file.file_result,
errorCount: file.status.toLowerCase() === "completed" ? file.error_count : 0,
warningCount: file.warning_count || 0,
code: "",
translatedCode: file.translated_content || "",
file_logs: file.file_logs,
fileId: file.file_id,
batchId: file.batch_id
}));
const updatedFiles: FileItem[] = [
{
id: "summary",
name: "Summary",
type: "summary",
status: data.status?.toLowerCase() === "in_process" ? "Pending" : data.status,
errorCount: batchCompleted ? data.error_count : 0,
file_track_percentage: 0,
warningCount: 0
},
...fileItems
];
// Store it in local state, not Redux
setReduxFileList(updatedFiles);
} else {
console.log("No data received from server");
}
if (isInitialLoad) {
setShowLoading(false);
}
} catch (err) {
console.error("Error fetching batch data:", err);
if (isInitialLoad) {
setShowLoading(false);
}
}
};
useEffect(() => {
if (!batchId || batchId.length !== 36) {
console.log("No valid batch ID provided");
setShowLoading(false);
return;
}
fetchBatchData(batchId);
// If we're navigating from upload page, processing has already started
// Set processingStarted to true immediately to begin polling
setProcessingStarted(true);
}, [batchId]);
// Add polling effect for batch summary updates - runs every 5 seconds when processing starts
useEffect(() => {
if (!batchId || allFilesCompleted) {
return;
}
console.log('Setting up batch summary polling every 5 seconds...');
// Poll immediately on mount
fetchBatchData(batchId, false);
// Then set up interval for every 5 seconds
const pollInterval = setInterval(() => {
console.log('Polling batch summary...');
fetchBatchData(batchId, false); // false = not initial load, don't show loading spinner
}, 10000); // Poll every 10 seconds
return () => {
console.log('Cleaning up batch summary polling');
clearInterval(pollInterval);
};
}, [batchId, allFilesCompleted]);
const handleDownloadZip = async () => {
if (batchId) {
try {
const apiUrl = getApiUrl();
const response = await fetch(`${apiUrl}/download/${batchId}?batch_id=${batchId}`, { headers: headerBuilder({}) });
if (!response.ok) {
throw new Error("Failed to download file");
}
// Create a blob from the response
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
// Create a temporary <a> element and trigger download
const link = document.createElement("a");
link.href = url;
link.setAttribute("download", "download.zip"); // Specify a filename
document.body.appendChild(link);
link.click();
// Cleanup
document.body.removeChild(link);
window.URL.revokeObjectURL(url);
} catch (error) {
console.error("Download failed:", error);
}
}
};
// Initialize files state with a summary file
const [files, setFiles] = useState<FileItem[]>([
{ id: "summary", name: "Summary", type: "summary", status: "Pending", errorCount: 0, warningCount: 0, file_track_percentage: 0 },
]);
useEffect(() => {
// This handles the browser's refresh button and keyboard shortcuts
const handleBeforeUnload = (e) => {
e.preventDefault();
e.returnValue = '';
// You could store a flag in sessionStorage here
sessionStorage.setItem('refreshAttempt', 'true');
};
// This will execute when the page loads
const checkForRefresh = () => {
if (sessionStorage.getItem('refreshAttempt') === 'true') {
// Clear the flag
sessionStorage.removeItem('refreshAttempt');
// Handle the "after refresh" behavior here
console.log('Page was refreshed, restore state...');
// You could restore form data or UI state here
}
};
window.addEventListener('beforeunload', handleBeforeUnload);
checkForRefresh(); // Check on component mount
return () => {
window.removeEventListener('beforeunload', handleBeforeUnload);
};
}, []);
useEffect(() => {
const handleBeforeUnload = (event) => {
// Completely prevent browser's default dialog
event.preventDefault();
event.stopPropagation();
// Show your custom dialog
//setShowLeaveDialog(true);
// Modern browsers require this to suppress their own dialog
event.returnValue = 'You have unsaved changes. Are you sure you want to leave?';
return '';
};
// Add event listeners for maximum coverage
window.addEventListener('beforeunload', handleBeforeUnload);
// Cleanup event listener on component unmount
return () => {
window.removeEventListener('beforeunload', handleBeforeUnload);
};
}, []); // Empty dependency array means this runs once on component mount
useEffect(() => {
// Prevent default refresh behavior
const handleKeyDown = (event) => {
// Prevent Ctrl+R, Cmd+R, and F5 refresh
if (
(event.ctrlKey || event.metaKey) && event.key === 'r' ||
event.key === 'F5'
) {
event.preventDefault();
// Optional: Show a dialog or toast to inform user
event.returnValue = 'You have unsaved changes. Are you sure you want to leave?';
return '';
}
};
// Prevent accidental page unload
const handleBeforeUnload = (event) => {
event.preventDefault();
event.returnValue = ''; // Required for Chrome
};
// Add event listeners
window.addEventListener('keydown', handleKeyDown);
window.addEventListener('beforeunload', handleBeforeUnload);
// Cleanup event listeners on component unmount
return () => {
window.removeEventListener('keydown', handleKeyDown);
window.removeEventListener('beforeunload', handleBeforeUnload);
};
}, []);
// Update files state when Redux fileList changes
useEffect(() => {
if (reduxFileList && reduxFileList.length > 0) {
setAllFilesCompleted(false);
// Map the Redux fileList to our FileItem format
const fileItems: FileItem[] = reduxFileList.filter(file => file.type !== 'summary').map((file: any, index: number) => ({
id: file.id,
name: file.name,
type: "code",
status: file.status, // Initial status
file_result: file.file_result,
fileId: file.fileId,
batchId: file.batchId,
file_logs: file.file_logs,
file_track_percentage: file.status === "completed" ? 100 : 0,
code: "",
translatedCode: file.translatedCode || "",
errorCount: file.errorCount || 0,
warningCount: file.warningCount || 0,
}));
// Add summary file at the beginning
const summaryFile = reduxFileList.find(file => file.type === 'summary');
setFiles([
summaryFile || { id: "summary", name: "Summary", type: "summary", status: "Pending", errorCount: 0, warningCount: 0, file_track_percentage: 0 },
...fileItems
]);
// If no file is selected, select the first file
if (!selectedFileId && fileItems.length > 0) {
if (summaryFile && summaryFile.status === "completed") {
setSelectedFileId(summaryFile.id);
} else {
setSelectedFileId(fileItems[0].id);
}
}
// Update text with file count
setText(`${new Date().toLocaleDateString()} (${fileItems.length} files)`);
}
}, [reduxFileList, batchId]);
// Check if batchId is valid
useEffect(() => {
if (batchId?.length !== 36) {
console.log("The page you are looking for does not exist. Redirected to Home")
navigate("/")
}
}, [batchId]);
//new PT FR ends
const updateSummaryStatus = async () => {
try {
const latestBatch = await fetchBatchSummary(batchId!);
setBatchSummary(latestBatch);
const allFilesDone = latestBatch.files.every(file =>
["completed", "failed", "error"].includes(file.status?.toLowerCase() || "")
);
if (allFilesDone) {
setAllFilesCompleted(true);
const hasUsableFile = latestBatch.files.some(file =>
file.status?.toLowerCase() === "completed" &&
file.file_result !== "error" &&
!!file.translated_content?.trim()
);
setIsZipButtonDisabled(!hasUsableFile);
setFiles(prevFiles => {
const updated = [...prevFiles];
const summaryIndex = updated.findIndex(f => f.id === "summary");
if (summaryIndex !== -1) {
updated[summaryIndex] = {
...updated[summaryIndex],
status: "completed",
errorCount: latestBatch.error_count,
warningCount: latestBatch.warning_count,
};
}
return updated;
});
}
} catch (err) {
console.error("Failed to update summary status:", err);
}
};
useEffect(() => {
const areAllFilesTerminal = files.every(file =>
file.id === "summary" || // skip summary
["completed", "failed", "error"].includes(file.status?.toLowerCase() || "")
);
if (files.length > 1 && areAllFilesTerminal && !allFilesCompleted) {
updateSummaryStatus();
}
}, [files, allFilesCompleted]);
useEffect(() => {
const nonSummaryFiles = files.filter(f => f.id !== "summary");
const completedCount = nonSummaryFiles.filter(f => f.status === "completed").length;
if (
nonSummaryFiles.length > 0 &&
completedCount === nonSummaryFiles.length &&
!allFilesCompleted
) {
updateSummaryStatus(); //single source of truth
}
}, [files, allFilesCompleted, batchId]);
//new end
// Set a timeout for initial loading - if no progress after 30 seconds, show error
useEffect(() => {
const loadingTimeout = setTimeout(() => {
if (progressPercentage < 5 && showLoading) {
console.log('Processing is taking longer than expected. You can continue waiting or try again later.');
}
}, 30000);
return () => clearTimeout(loadingTimeout);
}, [progressPercentage, showLoading]);
useEffect(() => {
console.log('Current files state:', files);
console.log('Selected file ID:', selectedFileId);
console.log('All files completed:', allFilesCompleted);
}, [files, selectedFileId, allFilesCompleted]);
// Monitor when processing starts
useEffect(() => {
const hasProcessingStarted = files.some(file =>
file.id !== "summary" && (file.status === "in_process" || file.status === "completed")
);
if (hasProcessingStarted && !processingStarted) {
console.log('Processing has started, enabling polling...');
setProcessingStarted(true);
}
}, [files, processingStarted]);
// Auto-select next processing file
useEffect(() => {
// If no file is selected, try to select one
if (!selectedFileId && files.length > 1) {
const processingFile = files.find((f) => f.status === "in_process");
if (processingFile) {
setSelectedFileId(processingFile.id);
} else {
// Select first non-summary file
const firstFile = files.find(f => f.id !== "summary");
if (firstFile) {
setSelectedFileId(firstFile.id);
}
}
}
}, [files, selectedFileId, allFilesCompleted]);
const renderBottomButtons = () => {
return (
<div className={styles.buttonContainer}>
<Button appearance="secondary" onClick={() => navigate("/")}>
Return home
</Button>
<Button
appearance="primary"
onClick={handleDownloadZip}
className={styles.downloadButton}
icon={<ArrowDownload24Regular />}
disabled={isZipButtonDisabled}
>
Download all as .zip
</Button>
</div>
);
};
const selectedFile = files.find((f) => f.id === selectedFileId);
// Fix for the Progress tracker title, positioning and background color
const renderContent = () => {
const renderHeader = () => {
const selectedFile = files.find((f) => f.id === selectedFileId);
if (!selectedFile) return null;
const title = selectedFile.id === "summary" ? "Summary" : "T-SQL";
return (
<div className={styles.summaryHeader}>
<Text size={500} weight="semibold">{title}</Text>
<Text size={200} style={{ color: tokens.colorNeutralForeground3 }}>
AI-generated content may be incorrect
</Text>
</div>
);
};
const processingStarted = files.some(file =>
file.id !== "summary" && (file.status === "in_process" || file.status === "completed")
);
// Show spinner if processing hasn't started yet
if (!processingStarted) {
return (
<div className="loading-container" style={{
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
height: '50vh'
}}>
<Spinner size="large" />
<Text style={{ marginTop: '16px', fontSize: "24px", fontWeight: "600" }}>Getting things ready</Text>
</div>
);
}
// Always show the progress bar until all files are completed
if (!allFilesCompleted || selectedFile?.id !== "summary") {
// If a specific file is selected (not summary) and it's completed, show the file content
if (selectedFile && selectedFile.id !== "summary" && selectedFile.status === "completed") {
return (
<>
{renderHeader()}
<Card className={styles.codeCard}>
<div className={styles.codeHeader}>
<Text weight="semibold">
{selectedFile.name} {selectedFile.translatedCode ? "(Translated)" : ""}
</Text>
</div>
{!selectedFile.errorCount && selectedFile.warningCount ? (
<>
<Card className={styles.warningContent}>
<Text weight="semibold">File processed with warnings</Text>
</Card>
<Text style={{ padding: "20px" }}>
{renderFileError(selectedFile)}
</Text>
</>
) : null}
{selectedFile.translatedCode ? (
<SyntaxHighlighter
language="sql"
style={vs}
showLineNumbers
customStyle={{
margin: 0,
padding: "16px",
backgroundColor: tokens.colorNeutralBackground1,
}}
>
{format(selectedFile.translatedCode, { language: "tsql" })}
</SyntaxHighlighter>
) : selectedFile.status === "completed" && !selectedFile.translatedCode && !selectedFile.errorCount ? (
<div style={{ padding: "20px", textAlign: "center" }}>
<Spinner />
<Text>Loading file content...</Text>
</div>
) : null}
{selectedFile.errorCount ? (
<>
<Card className={styles.errorContent}>
<Text weight="semibold">Unable to process the file</Text>
</Card>
<Text style={{ padding: "20px" }}>
{renderFileError(selectedFile)}
</Text>
</>
) : null}
</Card>
</>
);
}
// Otherwise, show the progress view with summary information
// selectedFileId/fileId is the internal UI id (e.g. "summary"/"file0"),
// so match against file.id rather than the server-side file.fileId.
const fileIndex = files.findIndex(file => file.id === fileId);
const currentFile = files[fileIndex];
return (
<>
{currentFile?.file_track_percentage ? (
<div className={styles.progressSection}>
<Text size={600} weight="semibold" style={{ marginBottom: "20px", marginTop: "40px" }}>
Progress tracker
</Text>
<div className={styles.progressBar}>
<div className={styles.progressFill} style={{ width: `${currentFile?.file_track_percentage ?? 0}%`, transition: "width 0.5s ease-out" }} />
</div>
<div style={{ display: "flex", justifyContent: "flex-end" }}>
<Text style={{ fontWeight: "bold", color: "#333" }}>
{Math.floor(currentFile?.file_track_percentage ?? 0)}/100%