-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
1419 lines (1200 loc) · 49.8 KB
/
Copy pathcontent.js
File metadata and controls
1419 lines (1200 loc) · 49.8 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
// Xero Cash Coding Filter Extension
// Wait for the page to be fully loaded
(function() {
'use strict';
console.log('Xero Cash Coding Filter: Extension loaded');
// Store filter values globally so they persist when row is re-added
const filterState = {
payee: '',
reference: '',
description: '',
accountHasValue: false
};
let mutationObserver = null;
// Wait for the DOM to be ready
function init() {
// Check if the required elements exist
const showMoreButton = document.querySelector('span.text[data-automationid="Show more-button"]');
const tableHeader = document.getElementById('ext-gen26');
const tableBody = document.getElementById('ext-gen27');
if (!showMoreButton || !tableHeader || !tableBody) {
console.log('Xero Cash Coding Filter: Required elements not found, retrying...');
setTimeout(init, 1000);
return;
}
console.log('Xero Cash Coding Filter: Elements found, initializing...');
addLoadAllButton();
addFilterRow();
setupMutationObserver();
}
// Setup MutationObserver to watch for table changes
function setupMutationObserver() {
const tableHeader = document.getElementById('ext-gen26');
const tableBody = document.getElementById('ext-gen27');
if (!tableHeader) {
console.log('Xero Cash Coding Filter: Cannot setup observer - table header not found');
return;
}
// Disconnect existing observer if any
if (mutationObserver) {
mutationObserver.disconnect();
}
let filterReapplyTimeout = null;
// Create new observer
mutationObserver = new MutationObserver((mutations) => {
// Check if filter row still exists
const filterRow = document.getElementById('xero-filter-row');
if (!filterRow) {
XCCFLog('Filter row was removed, re-adding...');
// Small delay to ensure Xero has finished its updates
setTimeout(() => {
addFilterRow();
}, 100);
}
// Check if table body rows were modified
let rowsModified = false;
for (const mutation of mutations) {
if (mutation.target.id === 'ext-gen27' ||
(mutation.target.closest && mutation.target.closest('#ext-gen27'))) {
rowsModified = true;
break;
}
}
// Re-apply filters if rows were modified and we have active filters
if (rowsModified && (filterState.payee || filterState.reference || filterState.description || filterState.accountHasValue)) {
XCCFLog('Table body modified, re-applying filters...');
// Debounce filter reapplication to avoid excessive calls
if (filterReapplyTimeout) {
clearTimeout(filterReapplyTimeout);
}
filterReapplyTimeout = setTimeout(() => {
applyFilters();
XCCFLog('Filters re-applied after table modification');
}, 200);
}
});
// Start observing the table header for changes
mutationObserver.observe(tableHeader, {
childList: true,
subtree: true,
attributes: false
});
// Also observe table body if it exists
if (tableBody) {
mutationObserver.observe(tableBody, {
childList: true,
subtree: true,
attributes: false
});
XCCFLog('MutationObserver watching both header and body');
} else {
XCCFLog('MutationObserver watching header only');
}
XCCFLog('MutationObserver setup complete');
}
// Add "Load all" button next to "Show more" button
function addLoadAllButton() {
XCCFLog('addLoadAllButton');
const showMoreButton = document.querySelector('span.text[data-automationid="Show more-button"]');
if (!showMoreButton) {
XCCFLog('addLoadAllButton: Show more button not found');
return;
}
// Check if button already exists
if (document.getElementById('xero-filter-load-all-btn')) {
XCCFLog('addLoadAllButton: Load all button already exists');
return;
}
// Find the parent container
const showMoreContainer = showMoreButton.closest('.button');
if (!showMoreContainer) {
XCCFLog('addLoadAllButton: Show more container not found');
return;
}
// Create the "Load all" button by cloning the "Show more" button structure
const loadAllContainer = showMoreContainer.cloneNode(true);
loadAllContainer.id = 'xero-filter-load-all-btn';
// Update the link and text
const link = loadAllContainer.querySelector('a');
const span = loadAllContainer.querySelector('span.text');
if (link && span) {
// Remove href to prevent any default navigation
link.removeAttribute('href');
link.setAttribute('href', 'javascript:void(0);');
// Use addEventListener instead of onclick for better event handling
link.addEventListener('click', function(e) {
XCCFLog('Load all button clicked!');
e.preventDefault();
e.stopPropagation();
loadAllRows();
return false;
}, true); // Use capture phase to ensure our handler runs first
// Also add a click listener to the span for redundancy
span.addEventListener('click', function(e) {
XCCFLog('Load all button span clicked!');
e.preventDefault();
e.stopPropagation();
loadAllRows();
return false;
}, true);
span.textContent = 'Load all';
span.setAttribute('data-automationid', 'Load all-button');
XCCFLog('Load all button event listeners attached');
} else {
XCCFLog('addLoadAllButton: Link or span not found in cloned button');
}
// Insert after the "Show more" button
showMoreContainer.parentNode.insertBefore(loadAllContainer, showMoreContainer.nextSibling);
XCCFLog('Load all button added to DOM');
}
// Parse the "Displaying X of Y" text
function getDisplayCounts() {
const totalSpan = document.querySelector('span.total');
if (!totalSpan) {
console.log('Xero Cash Coding Filter: Total span not found');
return null;
}
const text = totalSpan.textContent;
const match = text.match(/Displaying (\d+) of (\d+)/);
if (match) {
return {
current: parseInt(match[1]),
total: parseInt(match[2])
};
}
XCCFLog('Could not parse display text: ' + text);
return null;
}
// Create and show custom modal
function showLoadingModal(totalRecords, onConfirm) {
// Create modal overlay
const overlay = document.createElement('div');
overlay.id = 'xero-filter-modal-overlay';
overlay.style.cssText = `
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
z-index: 10000;
`;
// Create modal content
const modal = document.createElement('div');
modal.style.cssText = `
background: white;
padding: 30px;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
max-width: 400px;
text-align: center;
`;
// Add message
const message = document.createElement('p');
message.style.cssText = `
font-size: 16px;
margin-bottom: 20px;
color: #333;
line-height: 1.5;
`;
message.innerHTML = `<strong>Loading ${totalRecords} records</strong><br><br>This might take a while - go make some tea and leave it to me! ☕`;
// Add button
const button = document.createElement('button');
button.textContent = "Let's go";
button.style.cssText = `
background-color: #13B5EA;
color: white;
border: none;
padding: 10px 30px;
font-size: 16px;
border-radius: 4px;
cursor: pointer;
font-weight: bold;
`;
button.onmouseover = function() {
this.style.backgroundColor = '#0E8AB8';
};
button.onmouseout = function() {
this.style.backgroundColor = '#13B5EA';
};
button.onclick = function() {
document.body.removeChild(overlay);
onConfirm();
};
modal.appendChild(message);
modal.appendChild(button);
overlay.appendChild(modal);
document.body.appendChild(overlay);
}
// Update the Load all button text
function updateLoadAllButtonText(text) {
const loadAllButton = document.querySelector('#xero-filter-load-all-btn span.text');
if (loadAllButton) {
loadAllButton.textContent = text;
}
}
// Wait for row count to increase
function waitForRowsToLoad(previousCount, timeout = 10000) {
XCCFLog('waitForRowsToLoad start');
return new Promise((resolve, reject) => {
const startTime = Date.now();
const pollInterval = 500; // Check every 500ms
function checkCount() {
const counts = getDisplayCounts();
if (!counts) {
if (Date.now() - startTime > timeout) {
reject(new Error('Timeout: Could not read display counts'));
return;
}
setTimeout(checkCount, pollInterval);
return;
}
// Check if count has increased
if (counts.current > previousCount) {
console.log(`Xero Cash Coding Filter: Rows loaded, now at ${counts.current} of ${counts.total}`);
resolve(counts);
} else if (counts.current === counts.total) {
// All rows are loaded
console.log('Xero Cash Coding Filter: All rows loaded');
resolve(counts);
} else if (Date.now() - startTime > timeout) {
reject(new Error(`Timeout: Row count did not increase from ${previousCount}`));
} else {
// Keep checking
setTimeout(checkCount, pollInterval);
}
}
checkCount();
});
}
// Function to load all rows by repeatedly clicking "Show more"
function loadAllRows() {
XCCFLog('Starting to load all rows...');
// First, check the filter-matches-toggle checkbox
const filterCheckbox = document.getElementById('filter-matches-toggle');
if (filterCheckbox && !filterCheckbox.checked) {
filterCheckbox.click();
console.log('Xero Cash Coding Filter: Checked filter-matches-toggle');
}
// Get initial counts
const initialCounts = getDisplayCounts();
if (!initialCounts) {
console.error('Xero Cash Coding Filter: Could not get initial counts');
alert('Error: Could not read the number of records. Please try again.');
return;
}
console.log(`Xero Cash Coding Filter: Initial counts - ${initialCounts.current} of ${initialCounts.total}`);
// Check if all rows are already loaded
if (initialCounts.current >= initialCounts.total) {
console.log('Xero Cash Coding Filter: All rows already loaded');
alert('All rows are already loaded!');
return;
}
// Function to actually start loading
function startLoading() {
updateLoadAllButtonText('Loading...');
async function clickShowMoreWithWait() {
try {
while (true) {
const counts = getDisplayCounts();
if (!counts) {
console.error('Xero Cash Coding Filter: Could not get counts');
updateLoadAllButtonText('Load all');
alert('Error: Lost track of row counts. Please try again.');
return;
}
// Update progress
updateLoadAllButtonText(`Loading... ${counts.current}/${counts.total}`);
// Check if we're done
if (counts.current >= counts.total) {
console.log('Xero Cash Coding Filter: All rows loaded!');
updateLoadAllButtonText('Load all');
alert(`Success! All ${counts.total} rows have been loaded.`);
return;
}
// Find and click the "Show more" button
XCCFLog('=== SHOW MORE CLICK START ===');
const showMoreButton = document.querySelector('span.text[data-automationid="Show more-button"]');
if (!showMoreButton) {
XCCFLog('ERROR: Show more button span not found');
updateLoadAllButtonText('Load all');
alert('Error: Show more button not found. Please try again.');
return;
}
XCCFLog('Show more button span found: ' + showMoreButton.textContent);
const link = showMoreButton.closest('a');
if (!link) {
XCCFLog('ERROR: Show more link not found');
updateLoadAllButtonText('Load all');
alert('Error: Show more link not found. Please try again.');
return;
}
XCCFLog('Show more link found');
// Check if button is disabled
const buttonContainer = link.closest('.button');
if (!buttonContainer) {
XCCFLog('WARNING: Button container not found');
} else {
XCCFLog('Button container found, classes: ' + buttonContainer.className);
if (buttonContainer.classList.contains('disabled')) {
XCCFLog('Show more button is DISABLED, waiting...');
await new Promise(resolve => setTimeout(resolve, 1000));
continue;
}
}
// Record current count before clicking
const currentCount = counts.current;
XCCFLog(`Attempting to click Show more (currently at ${currentCount} of ${counts.total})`);
// Try multiple click methods
let clickSuccess = false;
// Method 1: Direct click on link
try {
XCCFLog('Method 1: Trying link.click()');
link.click();
clickSuccess = true;
XCCFLog('Method 1: link.click() executed');
} catch (error) {
XCCFLog('Method 1 ERROR: ' + error.message);
}
// Method 2: Direct click on span
try {
XCCFLog('Method 2: Trying showMoreButton.click()');
showMoreButton.click();
clickSuccess = true;
XCCFLog('Method 2: showMoreButton.click() executed');
} catch (error) {
XCCFLog('Method 2 ERROR: ' + error.message);
}
// Method 3: Dispatch MouseEvent on link
try {
XCCFLog('Method 3: Dispatching MouseEvent on link');
const mouseDownEvent = new MouseEvent('mousedown', {
view: window,
bubbles: true,
cancelable: true
});
const mouseUpEvent = new MouseEvent('mouseup', {
view: window,
bubbles: true,
cancelable: true
});
const clickEvent = new MouseEvent('click', {
view: window,
bubbles: true,
cancelable: true
});
link.dispatchEvent(mouseDownEvent);
link.dispatchEvent(mouseUpEvent);
link.dispatchEvent(clickEvent);
clickSuccess = true;
XCCFLog('Method 3: MouseEvents dispatched on link');
} catch (error) {
XCCFLog('Method 3 ERROR: ' + error.message);
}
// Method 4: Dispatch MouseEvent on span
try {
XCCFLog('Method 4: Dispatching MouseEvent on span');
const mouseDownEvent = new MouseEvent('mousedown', {
view: window,
bubbles: true,
cancelable: true
});
const mouseUpEvent = new MouseEvent('mouseup', {
view: window,
bubbles: true,
cancelable: true
});
const clickEvent = new MouseEvent('click', {
view: window,
bubbles: true,
cancelable: true
});
showMoreButton.dispatchEvent(mouseDownEvent);
showMoreButton.dispatchEvent(mouseUpEvent);
showMoreButton.dispatchEvent(clickEvent);
clickSuccess = true;
XCCFLog('Method 4: MouseEvents dispatched on span');
} catch (error) {
XCCFLog('Method 4 ERROR: ' + error.message);
}
// Method 5: Click on button container
if (buttonContainer) {
try {
XCCFLog('Method 5: Trying buttonContainer.click()');
buttonContainer.click();
clickSuccess = true;
XCCFLog('Method 5: buttonContainer.click() executed');
} catch (error) {
XCCFLog('Method 5 ERROR: ' + error.message);
}
}
if (!clickSuccess) {
XCCFLog('ERROR: All click methods failed!');
updateLoadAllButtonText('Load all');
alert('Error: Could not click Show more button. Please try again.');
return;
}
XCCFLog('=== SHOW MORE CLICK END ===');
// Wait for rows to load
try {
await waitForRowsToLoad(currentCount);
// Add a small delay between successful loads (1-2 seconds)
const delay = 1000 + Math.random() * 1000; // Random delay between 1-2 seconds
await new Promise(resolve => setTimeout(resolve, delay));
} catch (error) {
console.error('Xero Cash Coding Filter: Error waiting for rows:', error);
updateLoadAllButtonText('Load all');
alert(`Error: ${error.message}. Loaded ${counts.current} of ${counts.total} rows.`);
return;
}
}
} catch (error) {
XCCFLog('Unexpected error: ' + error);
updateLoadAllButtonText('Load all');
alert('An unexpected error occurred. Please try again.');
}
}
clickShowMoreWithWait();
}
// Show modal if more than 300 records, otherwise start immediately
if (initialCounts.total > 300) {
showLoadingModal(initialCounts.total, startLoading);
} else {
startLoading();
}
}
// Add filter row to the table header
function addFilterRow() {
const tableHeader = document.getElementById('ext-gen26');
if (!tableHeader) {
XCCFLog('addFilterRow: table header not found');
return;
}
const headerTable = tableHeader.querySelector('table');
if (!headerTable) {
XCCFLog('addFilterRow: header table not found');
return;
}
const thead = headerTable.querySelector('thead');
if (!thead) {
XCCFLog('addFilterRow: thead not found');
return;
}
// Check if filter row already exists
if (document.getElementById('xero-filter-row')) {
XCCFLog('addFilterRow: filter row already exists');
return;
}
const headerRow = thead.querySelector('tr.x-grid3-hd-row');
if (!headerRow) {
XCCFLog('addFilterRow: header row not found');
return;
}
// Create filter row
const filterRow = document.createElement('tr');
filterRow.id = 'xero-filter-row';
filterRow.className = 'x-grid3-hd-row xero-filter-row';
// Get all header cells
const headers = headerRow.querySelectorAll('td');
headers.forEach((header, index) => {
const filterCell = document.createElement('td');
filterCell.className = header.className;
filterCell.style.cssText = header.style.cssText;
const cellDiv = document.createElement('div');
cellDiv.className = 'x-grid3-hd-inner';
cellDiv.style.cssText = header.querySelector('.x-grid3-hd-inner')?.style.cssText || '';
// Determine which column this is
const columnClass = Array.from(header.classList).find(c => c.startsWith('x-grid3-td-'));
if (columnClass === 'x-grid3-td-checker') {
// Checkbox column - add "Select all filtered" checkbox
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.id = 'xero-filter-select-all';
checkbox.className = 'xero-filter-checkbox';
checkbox.title = 'Select all filtered items';
checkbox.addEventListener('change', function(e) {
e.stopPropagation();
selectAllFiltered(this.checked);
}, false);
cellDiv.appendChild(checkbox);
} else if (columnClass === 'x-grid3-td-colDate') {
// Date column - add "Filter:" text and "Clear" button
cellDiv.style.display = 'flex';
cellDiv.style.alignItems = 'center';
cellDiv.style.justifyContent = 'flex-end';
cellDiv.style.gap = '8px';
cellDiv.style.paddingRight = '10px';
const filterLabel = document.createElement('span');
filterLabel.textContent = 'Filter:';
filterLabel.style.fontWeight = 'bold';
const clearButton = document.createElement('button');
clearButton.textContent = 'Clear';
clearButton.id = 'xero-filter-clear-btn';
clearButton.className = 'xero-filter-clear-button';
clearButton.style.cssText = `
padding: 2px 8px;
font-size: 11px;
cursor: pointer;
background-color: #f0f0f0;
border: 1px solid #ccc;
border-radius: 3px;
font-weight: normal;
`;
// Hover effects
clearButton.addEventListener('mouseenter', function() {
this.style.backgroundColor = '#e0e0e0';
}, false);
clearButton.addEventListener('mouseleave', function() {
this.style.backgroundColor = '#f0f0f0';
}, false);
// Click handler to clear all filters
clearButton.addEventListener('click', function(e) {
e.stopPropagation();
e.preventDefault();
XCCFLog('=== CLEAR BUTTON CLICKED ===');
// Clear all text input filters
const payeeInput = document.querySelector('.xero-filter-input[data-column="payee"]');
const referenceInput = document.querySelector('.xero-filter-input[data-column="reference"]');
const descriptionInput = document.querySelector('.xero-filter-input[data-column="description"]');
const accountHasValueCheckbox = document.getElementById('xero-filter-account-has-value');
const selectAllCheckbox = document.getElementById('xero-filter-select-all');
if (payeeInput) {
XCCFLog('Clearing Payee filter (was: "' + payeeInput.value + '")');
payeeInput.value = '';
}
if (referenceInput) {
XCCFLog('Clearing Reference filter (was: "' + referenceInput.value + '")');
referenceInput.value = '';
}
if (descriptionInput) {
XCCFLog('Clearing Description filter (was: "' + descriptionInput.value + '")');
descriptionInput.value = '';
}
if (accountHasValueCheckbox) {
XCCFLog('Clearing Account "Has value" filter (was: ' + accountHasValueCheckbox.checked + ')');
accountHasValueCheckbox.checked = false;
}
if (selectAllCheckbox) {
XCCFLog('Unchecking "Select all filtered" checkbox');
selectAllCheckbox.checked = false;
}
// Reset filter state
XCCFLog('Resetting filter state object');
filterState.payee = '';
filterState.reference = '';
filterState.description = '';
filterState.accountHasValue = false;
// Apply filters (which will show all rows since filters are empty)
XCCFLog('Applying filters (all rows should now be visible)');
applyFilters();
XCCFLog('=== CLEAR BUTTON COMPLETE ===');
}, false);
cellDiv.appendChild(filterLabel);
cellDiv.appendChild(clearButton);
} else if (columnClass === 'x-grid3-td-colPayee') {
// Add filter input for Payee
const input = document.createElement('input');
input.type = 'text';
input.className = 'xero-filter-input';
input.placeholder = 'Filter...';
input.dataset.column = 'payee';
input.value = filterState.payee;
// Use event listeners instead of inline handlers to prevent event bubbling
input.addEventListener('input', function(e) {
e.stopPropagation();
filterState.payee = this.value;
applyFilters();
}, false);
input.addEventListener('click', function(e) {
e.stopPropagation();
}, false);
cellDiv.appendChild(input);
} else if (columnClass === 'x-grid3-td-colReference') {
// Add filter input for Reference
const input = document.createElement('input');
input.type = 'text';
input.className = 'xero-filter-input';
input.placeholder = 'Filter...';
input.dataset.column = 'reference';
input.value = filterState.reference;
input.addEventListener('input', function(e) {
e.stopPropagation();
filterState.reference = this.value;
applyFilters();
}, false);
input.addEventListener('click', function(e) {
e.stopPropagation();
}, false);
cellDiv.appendChild(input);
} else if (columnClass === 'x-grid3-td-colDescription') {
// Add filter input for Description
const input = document.createElement('input');
input.type = 'text';
input.className = 'xero-filter-input';
input.placeholder = 'Filter...';
input.dataset.column = 'description';
input.value = filterState.description;
input.addEventListener('input', function(e) {
e.stopPropagation();
filterState.description = this.value;
applyFilters();
}, false);
input.addEventListener('click', function(e) {
e.stopPropagation();
}, false);
cellDiv.appendChild(input);
} else if (columnClass === 'x-grid3-td-colAccount') {
// Add "Has value" checkbox for Account
const checkboxContainer = document.createElement('div');
checkboxContainer.style.cssText = 'display: flex; align-items: center; gap: 5px;';
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.id = 'xero-filter-account-has-value';
checkbox.className = 'xero-filter-checkbox';
checkbox.checked = filterState.accountHasValue;
checkbox.addEventListener('change', function(e) {
e.stopPropagation();
filterState.accountHasValue = this.checked;
XCCFLog('Account "Has value" filter: ' + (this.checked ? 'ENABLED' : 'DISABLED'));
applyFilters();
}, false);
checkbox.addEventListener('click', function(e) {
e.stopPropagation();
}, false);
const label = document.createElement('label');
label.htmlFor = 'xero-filter-account-has-value';
label.textContent = 'Has value';
label.style.cssText = 'cursor: pointer; font-size: 11px; white-space: nowrap;';
label.addEventListener('click', function(e) {
e.stopPropagation();
}, false);
checkboxContainer.appendChild(checkbox);
checkboxContainer.appendChild(label);
cellDiv.appendChild(checkboxContainer);
}
// For all other columns, leave empty
filterCell.appendChild(cellDiv);
filterRow.appendChild(filterCell);
});
// Insert filter row as the first row in thead
thead.insertBefore(filterRow, headerRow);
XCCFLog('Filter row added successfully');
// Apply filters if any exist
if (filterState.payee || filterState.reference || filterState.description || filterState.accountHasValue) {
applyFilters();
}
}
// Apply filters to the table
function applyFilters() {
const tableBody = document.getElementById('ext-gen27');
if (!tableBody) return;
// Get filter values from state
const filters = {};
if (filterState.payee) filters.payee = filterState.payee.toLowerCase().trim();
if (filterState.reference) filters.reference = filterState.reference.toLowerCase().trim();
if (filterState.description) filters.description = filterState.description.toLowerCase().trim();
// Get all rows
const rows = tableBody.querySelectorAll('.x-grid3-row');
let accountHasValueFilteredCount = 0;
let totalVisibleBeforeAccountFilter = 0;
rows.forEach(row => {
let visible = true;
// Check each filter
for (const [column, filterValue] of Object.entries(filters)) {
let cellValue = '';
if (column === 'payee') {
const cell = row.querySelector('.x-grid3-td-colPayee .x-grid3-cell-inner');
cellValue = cell ? cell.textContent.toLowerCase().trim() : '';
} else if (column === 'reference') {
const cell = row.querySelector('.x-grid3-td-colReference .x-grid3-cell-inner');
cellValue = cell ? cell.textContent.toLowerCase().trim() : '';
} else if (column === 'description') {
const cell = row.querySelector('.x-grid3-td-colDescription .x-grid3-cell-inner');
cellValue = cell ? cell.textContent.toLowerCase().trim() : '';
}
// AND logic - all filters must match
if (!cellValue.includes(filterValue)) {
visible = false;
break;
}
}
// If still visible after text filters, check Account "Has value" filter
if (visible && filterState.accountHasValue) {
totalVisibleBeforeAccountFilter++;
const accountCell = row.querySelector('.x-grid3-td-colAccount .x-grid3-cell-inner');
const accountValue = accountCell ? accountCell.textContent.trim() : '';
// Only show rows that have a value in the Account column
if (!accountValue || accountValue === '') {
visible = false;
accountHasValueFilteredCount++;
}
}
// Show or hide the row
if (visible) {
row.style.display = '';
} else {
row.style.display = 'none';
}
});
// Uncheck the "select all" checkbox when filters change
const selectAllCheckbox = document.getElementById('xero-filter-select-all');
if (selectAllCheckbox) {
selectAllCheckbox.checked = false;
}
// Log filter results
let logMessage = 'Filters applied';
if (filterState.accountHasValue) {
logMessage += ` - Account "Has value" filter: ${accountHasValueFilteredCount} rows filtered out of ${totalVisibleBeforeAccountFilter} visible rows`;
}
XCCFLog(logMessage);
}
// Select all filtered items
function selectAllFiltered(checked) {
XCCFLog('=== SELECT ALL FILTERED START ===');
XCCFLog('Checkbox state: ' + (checked ? 'CHECKED' : 'UNCHECKED'));
const tableBody = document.getElementById('ext-gen27');
if (!tableBody) {
XCCFLog('ERROR: Table body not found!');
return;
}
XCCFLog('Table body found: ' + tableBody.id);
const rows = tableBody.querySelectorAll('.x-grid3-row');
XCCFLog('Total rows found: ' + rows.length);
let visibleCount = 0;
let hiddenCount = 0;
let clickedCount = 0;
let alreadyInCorrectState = 0;
rows.forEach((row, index) => {
// Only check/uncheck visible rows
const isVisible = row.style.display !== 'none';
if (!isVisible) {
hiddenCount++;
return; // Skip hidden rows
}
visibleCount++;
XCCFLog(`Row ${index}: VISIBLE`);
// Try multiple methods to find the checkbox
let checkbox = row.querySelector('.x-grid3-row-checker');
if (!checkbox) {
// Try alternative selectors
checkbox = row.querySelector('div[class*="checker"]');
}
if (!checkbox) {
checkbox = row.querySelector('td.x-grid3-td-checker div');
}
if (!checkbox) {
XCCFLog(`Row ${index}: ERROR - Checkbox not found!`);
XCCFLog(`Row ${index}: Row HTML: ` + row.innerHTML.substring(0, 200));
return;
}
XCCFLog(`Row ${index}: Checkbox found - ${checkbox.className}`);
// Check current state
const isChecked = row.classList.contains('x-grid3-row-selected');
XCCFLog(`Row ${index}: Current state: ${isChecked ? 'SELECTED' : 'NOT SELECTED'}`);
XCCFLog(`Row ${index}: Desired state: ${checked ? 'SELECTED' : 'NOT SELECTED'}`);
// Only click if state needs to change
if (checked && !isChecked) {
XCCFLog(`Row ${index}: CLICKING to SELECT`);
// Try multiple click methods
try {
// Method 1: Direct click
checkbox.click();
XCCFLog(`Row ${index}: Direct click executed`);
// Method 2: Dispatch MouseEvent (as backup)
const clickEvent = new MouseEvent('click', {
view: window,
bubbles: true,
cancelable: true
});
checkbox.dispatchEvent(clickEvent);
XCCFLog(`Row ${index}: MouseEvent dispatched`);
clickedCount++;
} catch (error) {
XCCFLog(`Row ${index}: ERROR clicking - ${error.message}`);
}
} else if (!checked && isChecked) {
XCCFLog(`Row ${index}: CLICKING to DESELECT`);
try {
// Method 1: Direct click
checkbox.click();
XCCFLog(`Row ${index}: Direct click executed`);
// Method 2: Dispatch MouseEvent (as backup)
const clickEvent = new MouseEvent('click', {
view: window,
bubbles: true,
cancelable: true
});
checkbox.dispatchEvent(clickEvent);
XCCFLog(`Row ${index}: MouseEvent dispatched`);
clickedCount++;
} catch (error) {
XCCFLog(`Row ${index}: ERROR clicking - ${error.message}`);
}
} else {
XCCFLog(`Row ${index}: Already in correct state, skipping`);
alreadyInCorrectState++;
}
});
XCCFLog('=== SELECT ALL FILTERED SUMMARY ===');
XCCFLog(`Total rows: ${rows.length}`);
XCCFLog(`Visible rows: ${visibleCount}`);
XCCFLog(`Hidden rows: ${hiddenCount}`);
XCCFLog(`Clicked: ${clickedCount}`);
XCCFLog(`Already in correct state: ${alreadyInCorrectState}`);
XCCFLog('=== SELECT ALL FILTERED END ===');
}
// Add SaveAndReconcile button listener
function setupSaveAndReconcileListener() {
XCCFLog('Setting up SaveAndReconcile button listener...');
// Try to find the button
const saveAndReconcileButton = document.getElementById('SaveAndReconcile');