-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
2031 lines (1869 loc) · 117 KB
/
index.html
File metadata and controls
2031 lines (1869 loc) · 117 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
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Sethu Neeli - MA - GIT Portal SQL</title>
<style>
:root{
--blue1:#0b5eff;
--blue2:#3aa0ff;
--yellow1:#ffd24d;
--yellow2:#ffea7f;
--card-bg: rgba(255,255,255,0.85);
--muted:#445;
}
html,body{height:100%;margin:0;padding:0}
body{
font-family: Inter, system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue', Arial;
background: linear-gradient(120deg,var(--blue1),var(--yellow1));
background-size:400% 400%;
animation: bg-anim 12s ease infinite;
color: #07203b;
-webkit-font-smoothing:antialiased;
-moz-osx-font-smoothing:grayscale;
}
@keyframes bg-anim{
0%{background-position:0% 50%}
50%{background-position:100% 50%}
100%{background-position:0% 50%}
}
.app-container{
max-width:1200px;margin:36px auto;padding:28px;border-radius:16px;background:linear-gradient(180deg, rgba(255,255,255,0.88), rgba(245,249,255,0.7));box-shadow:0 8px 30px rgba(8,20,40,0.35);
backdrop-filter: blur(6px);
}
h1{margin-top:0;color:var(--muted);font-weight:600}
textarea{width:100%;height:180px;font-family:monospace;padding:10px;border-radius:8px;border:1px solid rgba(10,20,40,0.06)}
select,button,input{padding:10px 12px;margin:6px 0;border-radius:8px;border:1px solid rgba(10,20,40,0.08);background:white}
button{cursor:pointer;background:linear-gradient(90deg,var(--blue2),#6fb8ff);color:white;border:none}
button:disabled{opacity:0.6;cursor:not-allowed}
pre{background:#f7f7f7;padding:12px;overflow:auto;border-radius:8px}
.row{display:flex;gap:12px;align-items:center}
.col{display:flex;flex-direction:column;gap:6px}
label{font-weight:600;color:#123}
.inline-grid{display:flex;gap:20px}
.inline-left{flex:1}
.inline-right{flex:1;min-width:320px}
#inlineResult{background:#fff;padding:12px;border-radius:8px;border:1px solid rgba(10,20,40,0.04);max-height:300px;overflow:auto}
/* Environment button color mapping */
.btn-dev{background:linear-gradient(90deg,var(--yellow1),var(--yellow2));color:#222}
.btn-stage{background:linear-gradient(90deg,var(--blue1),var(--blue2));color:white}
.btn-prod{background:linear-gradient(90deg,#2ecc71,#2ab866);color:white}
.btn-env{border:1px solid rgba(0,0,0,0.05);padding:8px 12px;border-radius:8px}
.btn-active{box-shadow:0 6px 18px rgba(0,0,0,0.18);transform:translateY(-2px)}
/* Export buttons in modal: high contrast for visibility */
.btn-export{background:linear-gradient(90deg,var(--blue2),#4a9eff);color:#fff;padding:6px 10px;border-radius:6px;border:none;font-weight:600}
.btn-export-alt{background:linear-gradient(90deg,#2ecc71,#28b463);color:#fff;padding:6px 10px;border-radius:6px;border:none;font-weight:600}
/* status dot and small disconnect button */
.env-dot{display:inline-block;width:10px;height:10px;border-radius:50%;margin-left:8px;vertical-align:middle;box-shadow:0 1px 3px rgba(0,0,0,0.12);background:#e74c3c}
.env-dot.green{background:#2ecc71}
.disconnect-btn{margin-left:8px;padding:6px 8px;font-size:0.85em;background:#ff6b6b;border:none;color:white;border-radius:8px;display:none;cursor:pointer}
.disconnect-btn.show{display:inline-block}
@media (max-width:800px){.row{flex-direction:column;align-items:stretch}}
/* Diff styles */
.diff-line{font-family:monospace;padding:4px;border-radius:4px;margin-bottom:2px}
.diff-context{color:#333;background:transparent}
.diff-added{background:#f3fff3;color:#083;}
.diff-removed{background:#fff6f6;color:#b21;}
/* Added line: lighter green background with stronger text color */
.diff-added{background:#e6fff0;color:#006400;border-left:4px solid rgba(0,100,0,0.12);padding-left:6px}
.diff-removed{background:#fff6f6;color:#b21;}
/* Inline word marker for additions: no heavy background, green text and subtle underline */
.diff-word-added{background:transparent;color:#007a1f;font-weight:600;border-bottom:2px solid rgba(0,122,31,0.12);padding:0 2px}
.diff-word-removed{background:#ffdede;border-radius:2px;padding:0 2px;text-decoration:line-through}
/* Side-by-side diff layout */
.sbs-container{font-family:monospace;border-radius:6px;border:1px solid #eee;background:#fff;overflow:auto}
.sbs-row{display:flex;padding:2px 8px;border-bottom:1px solid #fafafa}
.sbs-left,.sbs-right{width:50%;box-sizing:border-box;padding:4px 8px;white-space:pre-wrap}
.sbs-left{border-right:1px solid #f3f3f3;color:#b21}
.sbs-right{color:#006400}
.sbs-line-ctx{color:#333;background:transparent}
/* diff-word-removed kept previously */
/* Modal sizing classes (regular vs compact) */
#objectPreviewModal.modal-regular { width:80% !important; max-width:900px !important; height:70% !important; }
#objectPreviewModal.modal-compact { width:60% !important; max-width:700px !important; height:50% !important; }
@media (max-width:700px) {
#objectPreviewModal.modal-regular, #objectPreviewModal.modal-compact { width:95% !important; height:80% !important; max-width:unset !important; }
}
/* Object History Modal Styles */
#objectHistoryModal { backdrop-filter: blur(4px); }
.history-item {
border-bottom: 1px solid #f0f0f0;
padding: 12px;
cursor: pointer;
transition: background-color 0.2s ease;
}
.history-item:hover { background-color: #f8f9fa; }
.history-item.selected { background-color: #e3f2fd; border-left: 4px solid #2196f3; }
.history-commit { font-weight: 600; color: #2196f3; font-family: monospace; }
.history-meta { font-size: 0.9em; color: #666; margin-top: 4px; }
.history-message { margin-top: 6px; color: #333; }
.diff-highlight { background-color: #fff3cd; padding: 2px 4px; border-radius: 3px; }
/* Inline result fancy layout */
.inline-result-toolbar{display:flex;gap:8px;align-items:center;justify-content:space-between;margin-bottom:8px}
.inline-result-actions{display:flex;gap:6px;align-items:center}
.inline-result-meta{font-size:0.9em;color:#445}
.inline-table{width:100%;border-collapse:collapse;font-family:Inter, Arial, sans-serif}
.inline-table th{background:#f3f6fb;padding:8px;border-bottom:1px solid #e9eef7;text-align:left;font-weight:600}
.inline-table td{padding:8px;border-bottom:1px solid #f7f9fc;vertical-align:top}
.inline-pager{display:flex;gap:6px;align-items:center}
</style>
<!-- jsdiff (diff library) for improved inline diffs -->
<script src="https://cdn.jsdelivr.net/npm/diff@5.1.0/dist/diff.min.js"></script>
</head>
<body>
<div class="app-container">
<h1> Sethu Neeli - MA - GIT & SQL Management</h1>
<nav style="display:flex;gap:12px;margin-bottom:24px;padding:12px 0;border-bottom:1px solid rgba(10,20,40,0.1);">
<a href="index.html" style="padding:8px 16px;border-radius:8px;text-decoration:none;color:#333;background:rgba(255,255,255,0.7);border:1px solid rgba(10,20,40,0.08);background:linear-gradient(90deg,var(--blue2),#6fb8ff);color:white;">🏠 Home</a>
<a href="environments.html" style="padding:8px 16px;border-radius:8px;text-decoration:none;color:#333;background:rgba(255,255,255,0.7);border:1px solid rgba(10,20,40,0.08);transition:all 0.2s;" onmouseover="this.style.background='var(--blue2)';this.style.color='white';" onmouseout="this.style.background='rgba(255,255,255,0.7)';this.style.color='#333';">🌐 Environments</a>
<a href="git-changes.html" style="padding:8px 16px;border-radius:8px;text-decoration:none;color:#333;background:rgba(255,255,255,0.7);border:1px solid rgba(10,20,40,0.08);transition:all 0.2s;" onmouseover="this.style.background='var(--blue2)';this.style.color='white';" onmouseout="this.style.background='rgba(255,255,255,0.7)';this.style.color='#333';">🔄 Git Changes</a>
<a href="#audit" onclick="document.getElementById('auditSection').scrollIntoView()" style="padding:8px 16px;border-radius:8px;text-decoration:none;color:#333;background:rgba(255,255,255,0.7);border:1px solid rgba(10,20,40,0.08);transition:all 0.2s;" onmouseover="this.style.background='var(--blue2)';this.style.color='white';" onmouseout="this.style.background='rgba(255,255,255,0.7)';this.style.color='#333';">📊 Audit</a>
</nav>
<!-- Git Summary Widget -->
<section style="background:rgba(255,255,255,0.9);border-radius:8px;padding:15px;margin-bottom:20px;border:1px solid rgba(10,20,40,0.08);box-shadow:0 2px 8px rgba(0,0,0,0.1);">
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;">
<h3 style="margin:0;color:#333;display:flex;align-items:center;gap:8px;">
🔄 Git Repository Status
</h3>
<a href="git-changes.html" style="padding:6px 12px;border-radius:4px;text-decoration:none;background:var(--blue2);color:white;font-size:12px;font-weight:600;">View All Changes</a>
</div>
<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:15px;">
<div style="text-align:center;">
<div style="font-size:24px;font-weight:bold;color:var(--blue2);" id="gitTotalCommits">-</div>
<div style="font-size:12px;color:#666;text-transform:uppercase;">Total Commits</div>
</div>
<div style="text-align:center;">
<div style="font-size:24px;font-weight:bold;color:#4CAF50;" id="gitTotalScripts">-</div>
<div style="font-size:12px;color:#666;text-transform:uppercase;">Script Files</div>
</div>
<div style="text-align:center;">
<div style="font-size:24px;font-weight:bold;color:#FF9800;" id="gitRecentChanges">-</div>
<div style="font-size:12px;color:#666;text-transform:uppercase;">Recent Changes</div>
</div>
<div style="text-align:center;">
<div style="font-size:24px;font-weight:bold;color:#9C27B0;" id="gitRepoStatus">-</div>
<div style="font-size:12px;color:#666;text-transform:uppercase;">Repository</div>
</div>
</div>
<div id="gitRecentCommits" style="margin-top:12px;font-size:12px;color:#666;max-height:60px;overflow:hidden;">
Loading recent commits...
</div>
<div style="margin-top:10px;text-align:center;">
<button onclick="testTableEmpHistory()" style="padding:6px 12px;background:#4CAF50;color:white;border:none;border-radius:4px;cursor:pointer;font-size:12px;">🔍 Test TableEmp History</button>
</div>
</section>
<section>
<h2>Environment</h2>
<label for="env">Environment:</label>
<select id="env">
<option value="DEV">DEV</option>
<option value="TEST">TEST</option>
<option value="LIVE">LIVE</option>
</select>
<div class="row">
<div style="display:flex;align-items:center;gap:8px">
<button id="btnDev" class="btn-env btn-dev" onclick="connectSQL('DEV')">Connect to DEV <span id="dotDev" class="env-dot"></span></button>
<button id="btnDevDisconnect" class="disconnect-btn" onclick="disconnect('DEV')">Disconnect</button>
</div>
<div style="display:flex;align-items:center;gap:8px">
<button id="btnStage" class="btn-env btn-stage" onclick="connectSQL('TEST')">Connect to TEST <span id="dotStage" class="env-dot"></span></button>
<button id="btnStageDisconnect" class="disconnect-btn" onclick="disconnect('TEST')">Disconnect</button>
</div>
<div style="display:flex;align-items:center;gap:8px">
<button id="btnProd" class="btn-env btn-prod" onclick="connectSQL('LIVE')">Connect to LIVE <span id="dotProd" class="env-dot"></span></button>
<button id="btnProdDisconnect" class="disconnect-btn" onclick="disconnect('LIVE')">Disconnect</button>
</div>
</div>
</section>
<section>
<h2>Run Inline SQL</h2>
<div class="inline-grid">
<div class="inline-left">
<label for="script">SQL Script:</label>
<textarea id="script" placeholder="SELECT TOP 10 * FROM MyTable"></textarea>
<div class="row">
<button id="execute">Execute</button>
<span id="inlineStatus"></span>
</div>
</div>
<div class="inline-right">
<h3>Inline Result</h3>
<div id="inlineResult"><em>No result yet</em></div>
</div>
</div>
</section>
<section>
<h2>Available Script Files</h2>
<div class="row">
<select id="scriptFileSelect"><option>Loading...</option></select>
<button id="refreshScripts">Refresh</button>
<button id="runScript">Run Selected Script</button>
<button id="previewPlan">Preview Plan</button>
</div>
<div style="margin-top:8px;">
<h4>Plan Preview</h4>
<div id="planPreview"><em>No plan loaded</em></div>
</div>
</section>
<section style="margin-top:12px">
<h3>Execution Metadata</h3>
<div class="row">
<input id="metaUser" placeholder="user (optional)" />
<input id="metaCorrelation" placeholder="correlationId (optional)" />
<input id="metaGitCommit" placeholder="gitCommit (optional)" />
<label title="When enabled, the server will auto-create any missing schemas referenced in the implementation script during Apply (ignored on dry-run)." style="display:flex;align-items:center;gap:6px;cursor:pointer">
<input type="checkbox" id="autoCreateSchemas" /> Auto-create missing schemas
</label>
</div>
</section>
<section style="margin-top:18px">
<h2>Object Migration (Dev → Test)</h2>
<div class="row">
<label style="font-weight:600">Source:</label>
<select id="srcEnv" title="Source environment for comparison - auto-synced with main environment selection"><option value="DEV">DEV</option><option value="TEST">TEST</option><option value="LIVE">LIVE</option></select>
<label style="font-weight:600">Target:</label>
<select id="tgtEnv" title="Target environment for deployment - auto-synced with main environment selection"><option value="TEST">TEST</option><option value="DEV">DEV</option><option value="LIVE">LIVE</option></select>
<button id="refreshObjects">Refresh Object List</button>
<button id="selectAllObjects" style="margin-left:6px">Select All</button>
<button id="clearAllObjects" style="margin-left:6px">Clear Selection</button>
<input id="objectSearchInput" placeholder="Search objects (schema.name or name or type)" style="margin-left:8px;padding:8px;border-radius:8px;border:1px solid #ddd" />
<button id="objectSearchBtn" style="margin-left:6px">Search</button>
<button id="clearObjectSearch" style="margin-left:6px">Clear</button>
<label style="margin-left:8px;font-weight:400"><input type="checkbox" id="includeSystemObjects" /> Include system objects</label>
<button id="generateDiff">Generate Implementation</button>
</div>
<div style="margin-top:8px;display:flex;gap:12px">
<div style="flex:1">
<h4>Objects</h4>
<div id="objectList" style="max-height:260px;overflow:auto;background:#fff;padding:8px;border-radius:8px;border:1px solid #eee"></div>
</div>
<div style="flex:1">
<h4>Plan / Generated Scripts</h4>
<div id="migrationPlan" style="max-height:360px;overflow:auto;background:#fff;padding:8px;border-radius:8px;border:1px solid #eee">No plan generated</div>
</div>
</div>
</section>
<div style="margin-top:8px">
<button id="viewSelectedBtn" style="margin-right:8px">View Selected on Target</button>
</div>
<!-- Modal for viewing source vs target object create script side-by-side -->
<div id="objectPreviewModal" style="display:none;position:fixed;left:50%;top:50%;transform:translate(-50%,-50%);width:80%;max-width:900px;height:70%;background:#fff;border-radius:8px;box-shadow:0 12px 40px rgba(0,0,0,0.3);z-index:9999;padding:12px;overflow:hidden">
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px">
<strong id="objectPreviewTitle">Object Preview</strong>
<div style="display:flex;gap:8px;align-items:center">
<button id="exportSourceBtn" class="btn-export" style="margin-right:8px">Export Source CREATE</button>
<button id="exportTargetBtn" class="btn-export-alt">Export Target CREATE</button>
<button id="modalCompactToggle" title="Toggle compact view" style="padding:6px 8px;border-radius:6px;border:1px solid #ddd;background:#fff">Compact</button>
<button id="closeObjectPreview" style="background:#ff6b6b;color:white;padding:6px 10px;border-radius:6px;border:none">Close</button>
</div>
</div>
<div style="display:flex;gap:12px;height:52%">
<div style="flex:1;display:flex;flex-direction:column;border-right:1px solid #eee;padding-right:8px;overflow:auto;min-width:0">
<div style="font-weight:600;margin-bottom:6px">Source (selected source env)</div>
<pre id="objectPreviewSource" style="background:#f8f8f8;padding:8px;border-radius:6px;overflow:auto;flex:1;font-family:monospace;white-space:pre-wrap"></pre>
</div>
<div style="flex:1;display:flex;flex-direction:column;padding-left:8px;overflow:auto;min-width:0">
<div style="font-weight:600;margin-bottom:6px">Target (selected target env)</div>
<pre id="objectPreviewTarget" style="background:#f8f8f8;padding:8px;border-radius:6px;overflow:auto;flex:1;font-family:monospace;white-space:pre-wrap"></pre>
</div>
</div>
<!-- Inline diff removed (compare rendered in Source/Target panels) -->
</div>
<!-- Modal for viewing object change history from Git -->
<div id="objectHistoryModal" style="display:none;position:fixed;left:50%;top:50%;transform:translate(-50%,-50%);width:85%;max-width:1000px;height:75%;background:#fff;border-radius:8px;box-shadow:0 12px 40px rgba(0,0,0,0.3);z-index:9999;padding:12px;overflow:hidden">
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px">
<strong id="objectHistoryTitle">Object Change History</strong>
<div style="display:flex;gap:8px;align-items:center">
<button id="refreshHistoryBtn" title="Refresh history" style="padding:6px 8px;border-radius:6px;border:1px solid #ddd;background:#fff">🔄 Refresh</button>
<button id="closeObjectHistory" onclick="try{var m=(this.closest?this.closest('#objectHistoryModal'):document.getElementById('objectHistoryModal'));if(m){try{m.style.setProperty('display','none','important');}catch(__) { m.style.display='none'; } m.style.visibility='hidden'; m.style.opacity='0'; m.style.pointerEvents='none';}}catch(_){}; if(window.closeObjectHistory){try{window.closeObjectHistory(event||null);}catch(e){try{window.closeObjectHistory();}catch(_e){}}} return false;" style="background:#ff6b6b;color:white;padding:6px 10px;border-radius:6px;border:none">Close</button>
</div>
</div>
<div style="height:calc(100% - 40px);display:flex;flex-direction:column">
<div id="historyList" style="max-height:300px;overflow:auto;border:1px solid #eee;border-radius:6px;margin-bottom:12px">
<div style="padding:12px;text-align:center;color:#666">Loading change history...</div>
</div>
<div style="flex:1;display:flex;flex-direction:column">
<div style="font-weight:600;margin-bottom:6px">Commit Details & Diff</div>
<div id="commitDetails" style="background:#f8f8f8;padding:8px;border-radius:6px;overflow:auto;flex:1;font-family:monospace;white-space:pre-wrap;font-size:14px">Select a commit above to view details and diff</div>
</div>
</div>
</div>
<section>
<h2>Upload SQL Script</h2>
<input type="file" id="sqlFile" accept=".sql,.txt" />
<button id="uploadExecute">Upload & Execute (inline)</button>
</section>
<section>
<h2>GIT</h2>
<div class="col" style="max-width:420px;">
<textarea id="commitMessage" placeholder="Commit Message" rows="3"></textarea>
<div class="row"><button id="gitPush">Push to Remote</button></div>
</div>
<div class="col" style="margin-top:12px; max-width:640px;">
<h3>Remotes</h3>
<div class="row">
<select id="remotesSelect"><option>Loading...</option></select>
<button id="refreshRemotes">Refresh</button>
<button id="removeRemote">Remove</button>
</div>
<div style="margin-top:8px;">
<input id="newRemoteName" placeholder="remote name" />
<input id="newRemoteUrl" placeholder="remote url (https:// or git@)" style="width:420px;" />
<div class="row"><button id="addRemote">Add Remote</button><button id="setUrlRemote">Set URL</button></div>
</div>
</div>
</section>
<h2>Result</h2>
<div id="result"><em>No result yet</em></div>
<section style="margin-top:18px">
<h2>Audit</h2>
<div style="margin-top:8px">
<label style="font-weight:600">Audit Login (default admin/admin)</label>
<div class="row" style="align-items:center">
<input id="auditUser" placeholder="username" value="admin" style="width:120px" />
<input id="auditPass" placeholder="password" value="admin" style="width:120px" />
<button id="auditLogin">Set Credentials</button>
<button id="sendTestAudit" style="margin-left:8px">Send Test Audit</button>
<span id="auditStatus" style="margin-left:12px;font-weight:600;color:#b33">Not authenticated</span>
</div>
</div>
<div id="auditControls" style="display:none">
<div style="margin-top:8px;display:flex;gap:8px;align-items:center">
<select id="auditEnv"><option value="DEV">DEV</option><option value="TEST">TEST</option><option value="LIVE">LIVE</option></select>
<input id="auditAction" placeholder="action (apply/rollback)" />
<input id="auditSince" placeholder="since (YYYY-MM-DD)" />
<input id="auditUntil" placeholder="until (YYYY-MM-DD)" />
</div>
<div id="auditView" style="margin-top:8px;display:none;max-height:420px;overflow:auto;background:#fff;padding:10px;border-radius:8px;border:1px solid #eee"></div>
</div>
</section>
<script>
// Use jsdiff to render a rich, styled diff (line-level and inline word diffs)
function escapeHtml(s) { return String(s||'').replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>'); }
function renderDiffHtml(aText, bText) {
const a = aText || '';
const b = bText || '';
const parts = Diff.diffLines(a, b);
let html = '';
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
if (part.added) {
// added lines
const lines = part.value.split(/\r?\n/);
lines.forEach(ln => { if (ln === '') return; html += `<div class="diff-line diff-added">+ ${escapeHtml(ln)}</div>`; });
} else if (part.removed) {
// If a removed part is immediately followed by an added part, show inline word diffs
const next = parts[i+1];
if (next && next.added) {
const remLines = part.value.split(/\r?\n/);
const addLines = next.value.split(/\r?\n/);
const max = Math.max(remLines.length, addLines.length);
for (let k = 0; k < max; k++) {
const r = remLines[k] || '';
const aL = addLines[k] || '';
// compute word diff
const wdiff = Diff.diffWordsWithSpace(r, aL);
let removedHtml = '';
let addedHtml = '';
wdiff.forEach(w => {
if (w.added) addedHtml += `<span class="diff-word-added">${escapeHtml(w.value)}</span>`;
else if (w.removed) removedHtml += `<span class="diff-word-removed">${escapeHtml(w.value)}</span>`;
else { removedHtml += escapeHtml(w.value); addedHtml += escapeHtml(w.value); }
});
if (removedHtml.trim() !== '') html += `<div class="diff-line diff-removed">- ${removedHtml}</div>`;
if (addedHtml.trim() !== '') html += `<div class="diff-line diff-added">+ ${addedHtml}</div>`;
}
i++; // skip the next added part because we've consumed it
} else {
const lines = part.value.split(/\r?\n/);
lines.forEach(ln => { if (ln === '') return; html += `<div class="diff-line diff-removed">- ${escapeHtml(ln)}</div>`; });
}
} else {
// unchanged/context lines
const lines = part.value.split(/\r?\n/);
lines.forEach(ln => { if (ln === '') return; html += `<div class="diff-line diff-context"> ${escapeHtml(ln)}</div>`; });
}
}
return html;
}
/* renderTargetHighlighted removed when Target Code pane was removed */
// Utility: download a string as a file (used by Export buttons)
function downloadFile(filename, content) {
try {
const blob = new Blob([content || ''], { type: 'text/plain;charset=utf-8' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename || 'download.txt';
document.body.appendChild(a);
a.click();
a.remove();
setTimeout(() => { try { URL.revokeObjectURL(url); } catch(e){} }, 3000);
} catch (e) { console.error('downloadFile error', e); alert('Download failed: ' + (e && e.message)); }
}
// Helper to render result JSON
function renderResult(obj) {
document.getElementById('result').innerHTML = '<pre>' + JSON.stringify(obj, null, 2) + '</pre>';
}
// Inline result rendering helpers
function buildTableHtml(recordset, page = 0, pageSize = 50) {
if (!recordset || !recordset.length) return '<div><em>No rows</em></div>';
const cols = Object.keys(recordset[0]);
const total = recordset.length;
const pages = Math.max(1, Math.ceil(total / pageSize));
const start = page * pageSize; const end = Math.min(total, start + pageSize);
let html = '';
html += `<div class="inline-result-toolbar"><div class="inline-result-actions"><button class="btn-export" id="copyJsonBtn">Copy JSON</button><button class="btn-export-alt" id="downloadCsvBtn">Download CSV</button></div><div class="inline-result-meta">Showing ${start+1}-${end} of ${total} rows</div></div>`;
html += '<div style="overflow:auto;max-height:260px"><table class="inline-table"><thead><tr>' + cols.map(c=>`<th>${escapeHtml(c)}</th>`).join('') + '</tr></thead><tbody>';
for (let i = start; i < end; i++) {
const row = recordset[i]; html += '<tr>' + cols.map(c=>`<td>${escapeHtml(row[c]===null? 'NULL' : String(row[c]))}</td>`).join('') + '</tr>';
}
html += '</tbody></table></div>';
// pager
if (pages > 1) {
html += '<div class="inline-pager" style="margin-top:8px;display:flex;justify-content:flex-end;align-items:center;gap:6px"><button id="pagerPrev">Prev</button><span>Page '+(page+1)+' of '+pages+'</span><button id="pagerNext">Next</button></div>';
}
return html;
}
function toCSV(recordset) {
if (!recordset || !recordset.length) return '';
const cols = Object.keys(recordset[0]);
const esc = (v) => '"' + String(v===null? '' : v).replace(/"/g,'""') + '"';
const lines = [cols.map(esc).join(',')];
recordset.forEach(r => { lines.push(cols.map(c => esc(r[c]===undefined? '': r[c])).join(',')); });
return lines.join('\n');
}
async function copyToClipboard(text) {
if (navigator.clipboard && navigator.clipboard.writeText) return navigator.clipboard.writeText(text);
const ta = document.createElement('textarea'); ta.value = text; document.body.appendChild(ta); ta.select(); try { document.execCommand('copy'); } catch(e) {} ta.remove();
}
// Renders inline execution result into #inlineResult with toolbar and paging
function renderInlineResult(json) {
const container = document.getElementById('inlineResult');
if (!json) { container.innerHTML = '<em>No result</em>'; return; }
if (!json.success && json.error) {
container.innerHTML = '<pre style="color:#b21">' + escapeHtml(json.error || json.message || 'Error') + '</pre>';
return;
}
const recordset = json.recordset || [];
// attach a small state on the container for paging
container._rs = recordset;
container._page = 0;
container._pageSize = 50;
container.innerHTML = buildTableHtml(recordset, container._page, container._pageSize);
// wire actions
const downloadCsvBtn = document.getElementById('downloadCsvBtn');
if (downloadCsvBtn) downloadCsvBtn.addEventListener('click', () => {
const csv = toCSV(container._rs);
downloadFile('result.csv', csv);
});
const copyJsonBtn = document.getElementById('copyJsonBtn');
if (copyJsonBtn) copyJsonBtn.addEventListener('click', async () => {
await copyToClipboard(JSON.stringify(container._rs, null, 2));
copyJsonBtn.textContent = 'Copied'; setTimeout(()=>copyJsonBtn.textContent = 'Copy JSON',1200);
});
const pagerPrev = document.getElementById('pagerPrev');
const pagerNext = document.getElementById('pagerNext');
if (pagerPrev) pagerPrev.addEventListener('click', () => { if (container._page>0) { container._page--; container.innerHTML = buildTableHtml(container._rs, container._page, container._pageSize); renderInlineResultAttachEvents(); } });
if (pagerNext) pagerNext.addEventListener('click', () => { const pages = Math.max(1, Math.ceil(container._rs.length / container._pageSize)); if (container._page < pages-1) { container._page++; container.innerHTML = buildTableHtml(container._rs, container._page, container._pageSize); renderInlineResultAttachEvents(); } });
// reattach events after replacing innerHTML
function renderInlineResultAttachEvents() {
const dBtn = document.getElementById('downloadCsvBtn'); if (dBtn) dBtn.addEventListener('click', () => { downloadFile('result.csv', toCSV(container._rs)); });
const cBtn = document.getElementById('copyJsonBtn'); if (cBtn) cBtn.addEventListener('click', async () => { await copyToClipboard(JSON.stringify(container._rs, null, 2)); cBtn.textContent='Copied'; setTimeout(()=>cBtn.textContent='Copy JSON',1200); });
const pPrev = document.getElementById('pagerPrev'); if (pPrev) pPrev.addEventListener('click', () => { if (container._page>0) { container._page--; container.innerHTML = buildTableHtml(container._rs, container._page, container._pageSize); renderInlineResultAttachEvents(); } });
const pNext = document.getElementById('pagerNext'); if (pNext) pNext.addEventListener('click', () => { const pages = Math.max(1, Math.ceil(container._rs.length / container._pageSize)); if (container._page < pages-1) { container._page++; container.innerHTML = buildTableHtml(container._rs, container._page, container._pageSize); renderInlineResultAttachEvents(); } });
}
}
// Render a side-by-side diff: left = source (removed), right = target (added)
function renderSideBySideDiff(aText, bText) {
const a = aText || '';
const b = bText || '';
const parts = Diff.diffLines(a, b);
let rows = [];
// Build paired rows: when removed followed by added, pair them; otherwise pair with empty
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
if (part.removed) {
const next = parts[i+1];
if (next && next.added) {
const remLines = part.value.split(/\r?\n/).filter(l=>l!=='');
const addLines = next.value.split(/\r?\n/).filter(l=>l!=='');
const max = Math.max(remLines.length, addLines.length);
for (let k=0;k<max;k++) {
const left = remLines[k] || '';
const right = addLines[k] || '';
// compute word-level highlighting
const wdiff = Diff.diffWordsWithSpace(left, right);
let leftHtml=''; let rightHtml='';
wdiff.forEach(w=>{
if (w.added) { rightHtml += `<span class="diff-word-added">${escapeHtml(w.value)}</span>`; }
else if (w.removed) { leftHtml += `<span class="diff-word-removed">${escapeHtml(w.value)}</span>`; }
else { leftHtml += escapeHtml(w.value); rightHtml += escapeHtml(w.value); }
});
rows.push({ left: leftHtml, right: rightHtml, type: 'changed' });
}
i++; // skip next
} else {
const remLines = part.value.split(/\r?\n/).filter(l=>l!=='');
remLines.forEach(l => rows.push({ left: escapeHtml(l), right: '', type: 'removed' }));
}
} else if (part.added) {
const addLines = part.value.split(/\r?\n/).filter(l=>l!=='');
addLines.forEach(l => rows.push({ left: '', right: escapeHtml(l), type: 'added' }));
} else {
const ctxLines = part.value.split(/\r?\n/).filter(l=>l!=='');
ctxLines.forEach(l => rows.push({ left: escapeHtml(l), right: escapeHtml(l), type: 'context' }));
}
}
// render rows
let html = '<div class="sbs-container">';
rows.forEach(r => {
html += `<div class="sbs-row"><div class="sbs-left ${r.type==='context'?'sbs-line-ctx':''}">${r.left||''}</div><div class="sbs-right ${r.type==='context'?'sbs-line-ctx':''}">${r.right||''}</div></div>`;
});
html += '</div>';
return html;
}
// Build per-panel HTML for source and target panels embedding line-level and word-level highlights
function renderPanelsWithDiff(aText, bText) {
const a = aText || '';
const b = bText || '';
const parts = Diff.diffLines(a, b);
const leftLines = [];
const rightLines = [];
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
if (part.removed) {
const next = parts[i+1];
if (next && next.added) {
const remLines = part.value.split(/\r?\n/);
const addLines = next.value.split(/\r?\n/);
const max = Math.max(remLines.length, addLines.length);
for (let k=0;k<max;k++) {
const left = remLines[k] || '';
const right = addLines[k] || '';
// word-level diff
const wdiff = Diff.diffWordsWithSpace(left, right);
let leftHtml=''; let rightHtml='';
wdiff.forEach(w => {
if (w.added) { rightHtml += `<span class="diff-word-added">${escapeHtml(w.value)}</span>`; }
else if (w.removed) { leftHtml += `<span class="diff-word-removed">${escapeHtml(w.value)}</span>`; }
else { leftHtml += escapeHtml(w.value); rightHtml += escapeHtml(w.value); }
});
leftLines.push(`<div class="diff-line diff-removed">${leftHtml || ' '}</div>`);
rightLines.push(`<div class="diff-line diff-added">${rightHtml || ' '}</div>`);
}
i++; // skip next
} else {
const remLines = part.value.split(/\r?\n/);
remLines.forEach(l => leftLines.push(`<div class="diff-line diff-removed">${escapeHtml(l) || ' '}</div>`));
}
} else if (part.added) {
const addLines = part.value.split(/\r?\n/);
addLines.forEach(l => rightLines.push(`<div class="diff-line diff-added">${escapeHtml(l) || ' '}</div>`));
} else {
const ctxLines = part.value.split(/\r?\n/);
ctxLines.forEach(l => { const html = `<div class="diff-line diff-context">${escapeHtml(l) || ' '}</div>`; leftLines.push(html); rightLines.push(html); });
}
}
// ensure same line count by padding with empty context lines
const maxLines = Math.max(leftLines.length, rightLines.length);
while (leftLines.length < maxLines) leftLines.push(`<div class="diff-line diff-context"> </div>`);
while (rightLines.length < maxLines) rightLines.push(`<div class="diff-line diff-context"> </div>`);
return { leftHtml: leftLines.join('\n'), rightHtml: rightLines.join('\n') };
}
// Helper to get the preferred diff view mode ('sbs' or 'single')
function getDiffViewMode() {
try { const v = localStorage.getItem('diffViewMode'); if (v === 'single' || v === 'sbs') return v; } catch(e) {}
return 'sbs'; // default to side-by-side
}
// Centralized inline diff render that respects user preference
function renderInlineDiff(aText, bText) {
const mode = getDiffViewMode();
if (mode === 'single') return renderDiffHtml(aText, bText);
return renderSideBySideDiff(aText, bText);
}
// --- Audit auth handling (client-side) ---
let auditAuthHeader = null;
function getAuditHeaders(extra) {
const h = Object.assign({}, extra || {});
if (auditAuthHeader) h['Authorization'] = auditAuthHeader;
return h;
}
document.getElementById('auditLogin').addEventListener('click', () => {
const u = document.getElementById('auditUser').value || '';
const p = document.getElementById('auditPass').value || '';
if (!u) return alert('Enter audit username');
auditAuthHeader = 'Basic ' + btoa(u + ':' + p);
try { localStorage.setItem('auditAuthHeader', auditAuthHeader); } catch(e) {}
// validate credentials immediately
validateAuditCredentials().then(ok => {
if (ok) alert('Audit credentials validated and stored'); else alert('Credentials set but validation failed (unauthorized)');
});
});
// restore from storage if present
try { const s = localStorage.getItem('auditAuthHeader'); if (s) auditAuthHeader = s; } catch(e) {}
// validate stored credentials on load (if any)
async function validateAuditCredentials() {
const statusEl = document.getElementById('auditStatus');
const controls = document.getElementById('auditControls');
if (!auditAuthHeader) {
if (statusEl) { statusEl.textContent = 'Not authenticated'; statusEl.style.color = '#b33'; }
if (controls) controls.style.display = 'none';
return false;
}
try {
const resp = await fetch('/audit', { method: 'GET', headers: getAuditHeaders() });
if (resp.ok) {
if (statusEl) { statusEl.textContent = 'Authenticated'; statusEl.style.color = '#2a8f2a'; }
if (controls) controls.style.display = 'block';
return true;
} else {
if (statusEl) { statusEl.textContent = 'Auth failed'; statusEl.style.color = '#b33'; }
if (controls) controls.style.display = 'none';
return false;
}
} catch (e) {
if (statusEl) { statusEl.textContent = 'Auth error'; statusEl.style.color = '#b33'; }
if (controls) controls.style.display = 'none';
return false;
}
}
document.getElementById('sendTestAudit').addEventListener('click', async () => {
const env = document.getElementById('auditEnv').value || 'DEV';
const action = document.getElementById('auditAction').value || 'test';
const payload = { env, action, user: (document.getElementById('metaUser').value||'ui-test'), timestamp: new Date().toISOString(), scriptPreview: 'Client test audit' };
try {
const resp = await fetch('/audit/log', { method: 'POST', headers: getAuditHeaders({ 'Content-Type': 'application/json' }), body: JSON.stringify(payload) });
const j = await resp.json().catch(()=>null);
if (j && j.success) alert('Test audit posted'); else alert('Audit post failed: ' + (j? (j.message||JSON.stringify(j)) : resp.statusText));
} catch (err) { alert('Audit post error: ' + err.message); }
});
// Centralized viewer for objects (tables, views, procs, functions, triggers, indexes)
async function viewOnTarget(obj) {
const srcEnv = document.getElementById('srcEnv').value;
const tgtEnv = document.getElementById('tgtEnv').value;
const type = (obj.type || 'TABLE').toString().toUpperCase();
const schema = obj.schema || 'dbo';
const name = obj.name || obj.table || '';
if (!name) return alert('Object name missing');
const title = `${type} ${schema}.${name} — ${srcEnv} → ${tgtEnv}`;
document.getElementById('objectPreviewTitle').innerText = title;
const srcPre = document.getElementById('objectPreviewSource');
const tgtPre = document.getElementById('objectPreviewTarget');
srcPre.textContent = 'Loading...'; tgtPre.textContent = 'Loading...'; srcPre.dataset.raw = ''; tgtPre.dataset.raw = '';
document.getElementById('objectPreviewModal').style.display = 'block';
try {
const qSrc = `/db/object?env=${encodeURIComponent(srcEnv)}&type=${encodeURIComponent(type)}&schema=${encodeURIComponent(schema)}&name=${encodeURIComponent(name)}${type==='INDEX'?('&table='+encodeURIComponent(obj.table||name)):''}`;
const respSrc = await fetch(qSrc);
const jSrc = await respSrc.json();
if (!jSrc.success) { srcPre.textContent = 'Error: ' + (jSrc.message || JSON.stringify(jSrc)); } else { const raw = (jSrc.create || jSrc.definition || '') + '\n\n' + (jSrc.extras || ''); srcPre.dataset.raw = raw; srcPre.textContent = raw; }
} catch (e) { srcPre.textContent = 'Error: ' + e.message; }
try {
const qTgt = `/db/object?env=${encodeURIComponent(tgtEnv)}&type=${encodeURIComponent(type)}&schema=${encodeURIComponent(schema)}&name=${encodeURIComponent(name)}${type==='INDEX'?('&table='+encodeURIComponent(obj.table||name)):''}`;
const respTgt = await fetch(qTgt);
const jTgt = await respTgt.json();
if (!jTgt.success) { tgtPre.textContent = 'Error: ' + (jTgt.message || JSON.stringify(jTgt)); } else { const raw = (jTgt.create || jTgt.definition || '') + '\n\n' + (jTgt.extras || ''); tgtPre.dataset.raw = raw; tgtPre.textContent = raw; }
} catch (e) { tgtPre.textContent = 'Error: ' + e.message; }
// render combined a/b values and embed diff lines into the Source/Target PRE panels
const aText = srcPre.dataset.raw || srcPre.textContent || '';
const bText = tgtPre.dataset.raw || tgtPre.textContent || '';
// wire export buttons (use raw stored script when available)
document.getElementById('exportSourceBtn').onclick = () => downloadFile(`${schema}.${name}-${srcEnv}.sql`, srcPre.dataset.raw || srcPre.textContent || '');
document.getElementById('exportTargetBtn').onclick = () => downloadFile(`${schema}.${name}-${tgtEnv}.sql`, tgtPre.dataset.raw || tgtPre.textContent || '');
try {
const panels = renderPanelsWithDiff(aText, bText);
srcPre.innerHTML = panels.leftHtml;
tgtPre.innerHTML = panels.rightHtml;
} catch (e) { console.warn('panel diff render failed', e); }
}
// Show object change history from Git
async function showObjectHistory(obj) {
const type = (obj.type || 'TABLE').toString().toUpperCase();
const schema = obj.schema || 'dbo';
const name = obj.name || obj.table || '';
if (!name) return alert('Object name missing');
// Dedupe any duplicate modals (keep the first in DOM order)
try {
const dupes = document.querySelectorAll('#objectHistoryModal');
if (dupes && dupes.length > 1) {
for (let i = 1; i < dupes.length; i++) { try { dupes[i].remove(); } catch(e){} }
}
} catch(e) { /* ignore */ }
// If modal was removed, recreate from cached template
if (!document.getElementById('objectHistoryModal') && window._ohTemplateHtml) {
try {
const wrapper = document.createElement('div');
wrapper.innerHTML = window._ohTemplateHtml;
const newModal = wrapper.firstElementChild;
document.body.appendChild(newModal);
// rebind behaviors
initObjectHistoryModal();
} catch (e) { console.error('Failed to recreate object history modal', e); }
}
const title = `Git Change History: ${type} ${schema}.${name}`;
document.getElementById('objectHistoryTitle').innerText = title;
const _ohm = document.getElementById('objectHistoryModal');
_ohm.style.display = 'block';
try { _ohm.style.setProperty('z-index','10001','important'); _ohm.style.pointerEvents='auto'; _ohm.style.opacity='1'; _ohm.style.visibility='visible'; } catch(e) {}
// Show loading in history list
document.getElementById('historyList').innerHTML = '<div style="padding:12px;text-align:center;color:#666">Loading Git change history...</div>';
document.getElementById('commitDetails').textContent = 'Select a commit above to view details and diff';
try {
// Prefer object-specific history (server greps full commit message/body)
const objectResp = await fetch(`/api/git/object-history/${encodeURIComponent(type)}/${encodeURIComponent(schema)}/${encodeURIComponent(name)}?limit=100`);
const objectResult = await objectResp.json();
if (objectResult && objectResult.success && Array.isArray(objectResult.history)) {
const hist = objectResult.history || [];
if (hist.length) {
document.getElementById('historyList').innerHTML = `<div style="padding:12px;text-align:center;color:#4CAF50">Found ${hist.length} commits for ${schema}.${name}</div>`;
renderGitHistory(hist);
return;
}
}
// Fallback: use general history and client-side filter on subject
const response = await fetch(`/api/git/history?limit=100`);
const result = await response.json();
if (!result.success) {
document.getElementById('historyList').innerHTML = `<div style=\"padding:12px;color:#d32f2f\">Git API unavailable. Searching local commits...</div>`;
showLocalGitHistory(schema, name);
return;
}
const objectPattern = `${schema}.${name}`;
const filteredHistory = (result.history || []).filter(commit => commit.message && commit.message.toLowerCase().includes(objectPattern.toLowerCase()));
if (filteredHistory.length === 0) {
document.getElementById('historyList').innerHTML = `<div style=\"padding:12px;text-align:center;color:#666\">No Git history found for ${objectPattern}. Found ${(result.history || []).length} total commits.</div>`;
} else {
document.getElementById('historyList').innerHTML = `<div style=\"padding:12px;text-align:center;color:#4CAF50\">Found ${filteredHistory.length} commits for ${objectPattern}</div>`;
}
renderGitHistory(filteredHistory);
} catch (error) {
console.error('Error loading Git object history:', error);
document.getElementById('historyList').innerHTML = `<div style="padding:12px;color:#d32f2f">API Error: ${escapeHtml(error.message)}. Trying local search...</div>`;
// Try the local fallback
showLocalGitHistory(schema, name);
}
}
// Fallback function to show hardcoded results when API is unavailable
function showLocalGitHistory(schema, name) {
const objectName = `${schema}.${name}`;
// Hardcoded test data for TableEmp
if (objectName.toLowerCase() === 'dbo.tableemp') {
const testCommits = [
{
hash: '76d90842c114512afd1671fe6c74e8579d4894e6',
shortHash: '76d9084',
date: '2025-10-10T14:50:47.000Z',
author: 'GitTestUser',
email: 'test@example.com',
message: 'ROLLBACK: TEST - GitTestUser - Remove DemoColumn from dbo.TableEmp\\n\\nScript: 2025-10-10_rollback_TEST_GitTestUser_DEMO-001.sql',
action: 'rollback',
environment: 'TEST'
},
{
hash: '64a8e656b5ded32b489f4018908af741d6a14e2d',
shortHash: '64a8e65',
date: '2025-10-10T14:49:52.000Z',
author: 'GitTestUser',
email: 'test@example.com',
message: 'IMPLEMENTATION: TEST - GitTestUser - Add DemoColumn to dbo.TableEmp\\n\\nScript: 2025-10-10_implementation_TEST_GitTestUser_DEMO-001.sql',
action: 'implementation',
environment: 'TEST'
}
];
document.getElementById('historyList').innerHTML = `<div style="padding:12px;text-align:center;color:#4CAF50">Found ${testCommits.length} commits for ${objectName} (Local Data)</div>`;
renderGitHistory(testCommits);
} else {
document.getElementById('historyList').innerHTML = `<div style="padding:12px;text-align:center;color:#666">No local data available for ${objectName}. Try dbo.TableEmp for demo data.</div>`;
}
}
function renderGitHistory(commits) {
const historyList = document.getElementById('historyList');
if (!commits || commits.length === 0) {
historyList.innerHTML = '<div style="padding:12px;text-align:center;color:#666">No Git change history found for this object</div>';
return;
}
let html = '';
commits.forEach((commit, index) => {
const date = new Date(commit.date).toLocaleString();
const actionBadge = commit.action ? `<span class="diff-highlight" style="background-color: ${commit.action === 'rollback' ? '#ffebee' : '#e8f5e8'}; color: ${commit.action === 'rollback' ? '#c62828' : '#2e7d32'}">${commit.action.toUpperCase()}</span>` : '';
const envBadge = commit.environment ? `<span class="diff-highlight" style="background-color: #e3f2fd; color: #1976d2">ENV: ${commit.environment}</span>` : '';
html += `
<div class="history-item" data-commit="${escapeHtml(commit.hash)}">
<div class="history-commit">${escapeHtml(commit.shortHash)}</div>
<div class="history-meta">
<strong>${escapeHtml(commit.author)}</strong> on ${date}
${actionBadge}
${envBadge}
${commit.user ? `<span class="diff-highlight">USER: ${escapeHtml(commit.user)}</span>` : ''}
</div>
<div class="history-message">${escapeHtml(commit.message.split('\\n')[0])}</div>
</div>
`;
});
historyList.innerHTML = html;
// Add click handlers to load commit details
historyList.querySelectorAll('.history-item').forEach(item => {
item.addEventListener('click', async () => {
// Remove previous selection
historyList.querySelectorAll('.history-item').forEach(i => i.classList.remove('selected'));
item.classList.add('selected');
const commitHash = item.dataset.commit;
await loadGitCommitDetails(commitHash);
});
});
}
async function loadGitCommitDetails(commitHash) {
const commitDetails = document.getElementById('commitDetails');
commitDetails.textContent = 'Loading commit details...';
try {
const response = await fetch(`/api/git/commit/${encodeURIComponent(commitHash)}`);
const result = await response.json();
if (!result.success) {
commitDetails.textContent = `Error: ${result.error || 'Failed to load commit details'}`;
return;
}
const commit = result.commit;
let details = `Git Commit: ${commit.hash}
Author: ${commit.author}
Date: ${new Date(commit.date).toLocaleString()}
Message: ${commit.message}
`;
// Display parsed metadata if available
if (commit.metadata && Object.keys(commit.metadata).length > 0) {
details += `Metadata:
`;
Object.entries(commit.metadata).forEach(([key, value]) => {
if (value && value !== 'N/A') {
details += `${key}: ${value}
`;
}
});
details += `
`;
}
// Display changed files
if (result.files && result.files.length > 0) {
details += `Changed Files:
`;
result.files.forEach(file => {
details += `- ${file}
`;
});
details += `
`;
}
// Display diff if available
if (result.diff) {
details += `Git Diff:
${result.diff}`;
} else {
details += 'No diff available for this commit.';
}
commitDetails.textContent = details;
} catch (error) {
console.error('Error loading Git commit details:', error);
commitDetails.textContent = `Error: ${error.message}`;
}
}
function renderSampleTable(container, rows) {
if (!rows || !rows.length) return;
const table = document.createElement('table'); table.style.width='100%'; table.style.borderCollapse='collapse';
const hdr = document.createElement('tr'); Object.keys(rows[0]).forEach(k=>{ const th=document.createElement('th'); th.innerText=k; th.style.border='1px solid #eee'; th.style.padding='4px'; hdr.appendChild(th); }); table.appendChild(hdr);
rows.forEach(r=>{ const tr=document.createElement('tr'); Object.values(r).forEach(v=>{ const td=document.createElement('td'); td.innerText = v===null? 'NULL' : String(v); td.style.border='1px solid #f7f7f7'; td.style.padding='4px'; tr.appendChild(td); }); table.appendChild(tr); });
container.appendChild(table);
}
// Load Git summary data
async function loadGitSummary() {
try {
// Load Git status
const statusResponse = await fetch('/api/git/status');
const statusResult = await statusResponse.json();
if (statusResult.success) {
document.getElementById('gitTotalScripts').textContent = statusResult.totalScripts || 0;
document.getElementById('gitRepoStatus').textContent = statusResult.status || 'Unknown';
// Display recent commits
if (statusResult.recentCommits && statusResult.recentCommits.length > 0) {
const recentHtml = statusResult.recentCommits.slice(0, 3).map(commit => {
const shortMessage = commit.message.length > 50 ? commit.message.substring(0, 47) + '...' : commit.message;
return `• ${commit.hash} - ${shortMessage} (${commit.author})`;
}).join('<br>');
document.getElementById('gitRecentCommits').innerHTML = recentHtml;
document.getElementById('gitRecentChanges').textContent = statusResult.recentCommits.length;
} else {
document.getElementById('gitRecentCommits').textContent = 'No recent commits found';
document.getElementById('gitRecentChanges').textContent = '0';
}
}
// Load Git history count
const historyResponse = await fetch('/api/git/history?limit=100');
const historyResult = await historyResponse.json();
if (historyResult.success) {
document.getElementById('gitTotalCommits').textContent = historyResult.history?.length || 0;
}
} catch (error) {
console.error('Error loading Git summary:', error);
document.getElementById('gitRepoStatus').textContent = 'Error';
document.getElementById('gitRecentCommits').textContent = 'Error loading Git data';
}
}
// Test function to show TableEmp history
function testTableEmpHistory() {
showObjectHistory({
type: 'TABLE',
schema: 'dbo',
name: 'TableEmp'
});
}
async function connectSQL(env) {
// normalize environment keys to server-side keys (DEV/TEST/LIVE)
const map = { 'dev': 'DEV', 'test': 'TEST', 'live': 'LIVE' };
const key = (env || '').toString().toLowerCase();
const mapped = map[key] || (env || '').toString().toUpperCase();
const resp = await fetch('/sql-connect/' + mapped);
// handle non-JSON error bodies gracefully
const json = await resp.json().catch(async () => ({ success: false, message: await resp.text() }));
alert(json.success ? json.message : ('Connection Failed: ' + (json.message || json.error || 'Unknown')));
if (json.success) {