-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
1671 lines (1454 loc) · 79.4 KB
/
Copy pathapp.js
File metadata and controls
1671 lines (1454 loc) · 79.4 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
(function enforcePortalSecurityGate() {
const isSessionValid = sessionStorage.getItem('isAdminAuthenticated') === 'true';
const isPermanentValid = localStorage.getItem('isAdminAuthenticated') === 'true';
if (!isSessionValid && !isPermanentValid) {
window.location.replace("login.html");
}
})();
const API_BASE = 'http://localhost:3000/api';
let activeTable = 'member';
let workingRecordId = null;
// Global State Tracking Variables for Multi-Step Transaction Flow Mechanisms
let isWizardMode = false;
const wizardSteps = ['member', 'contact', 'employment', 'prevemployment', 'heir', 'governmentid'];
let wizardCurrentStepIndex = 0;
let wizardPrimaryTrackingKey = null;
let interruptedWizardState = null;
// Dynamic Multiplier Matrix: Tracks how many input sets to clone on array steps
let wizardStepRowMultipliers = {
employment: 1,
prevemployment: 1,
heir: 1
};
// Caches EVERY single step locally until the final submission commit
let wizardMultiEntryStore = {
member: null,
contact: null,
employment: [],
prevemployment: [],
heir: []
};
// Programmatic mappings linking dynamic user inputs directly to file column keys
const tableStructures = {
member: ['Pagibig_ID', 'Regis_num', 'Occ_Stats', 'First_time', 'Mem_Type', 'Mem_Subtype', 'Type_Work', 'Type_Country', 'Mem_Name', 'Fat_Name', 'Mot_Name', 'Spouse_Name', 'MemCert_Name', 'Birth_Date', 'Place_Birth', 'Sex', 'Height', 'Weight', 'Marital_Status', 'Citizenship', 'Facial_Features', 'Frequency_Payment'],
contact: ['Pagibig_ID', 'Cell_Num', 'Home_Num', 'Business_Direct', 'Business_Trunk', 'Email_Address', 'Perm_Address', 'Present_Address', 'Pref_Mail_Address'],
employment: ['Pagibig_ID', 'Employer_ID', 'Employment_Status', 'Occupation', 'Office_Assignment', 'Date_Employed', 'Monthly_Income'],
prevemployment: ['Pagibig_ID', 'Employer_ID', 'Date_From', 'Date_To', 'PrevOffice_Assignment'],
heir: ['Pagibig_ID', 'Heir_Code', 'Heir_Name', 'Relationship', 'Heir_DateBirth'],
governmentid: ['Pagibig_ID', 'TIN_Num', 'SSS_Num', 'CRN', 'EM_Num', 'AFP_PNP_Num', 'Deped_Code'],
employer: ['Employer_ID', 'Employer_Name', 'Employer_Address']
};
// Required fields configuration framework for wizard and standalone evaluations
const requiredFieldsConfig = {
member: ['Pagibig_ID', 'Regis_num', 'Occ_Stats', 'First_time', 'Mem_Type', 'Mem_Subtype', 'Mem_Name', 'Mot_Name', 'Birth_Date', 'Place_Birth', 'Sex', 'Marital_Status', 'Citizenship'],
contact: ['Pagibig_ID', 'Cell_Num', 'Perm_Address', 'Present_Address', 'Pref_Mail_Address'],
employment: ['Pagibig_ID', 'Employer_ID', 'Employment_Status', 'Occupation', 'Office_Assignment', 'Date_Employed', 'Monthly_Income'],
prevemployment: ['Pagibig_ID', 'Employer_ID', 'Date_From', 'Date_To', 'PrevOffice_Assignment'],
heir: ['Pagibig_ID', 'Heir_Code', 'Heir_Name', 'Relationship', 'Heir_DateBirth'],
governmentid: [],
employer: ['Employer_ID', 'Employer_Name', 'Employer_Address']
};
const primaryKeyTracker = {
member: ['Pagibig_ID'], contact: ['Pagibig_ID'], employment: ['Pagibig_ID'],
governmentid: ['Pagibig_ID'], employer: ['Employer_ID'],
prevemployment: ['Pagibig_ID', 'Employer_ID'],
heir: ['Pagibig_ID', 'Heir_Code']
};
// ── FILTER FIELD DEFINITIONS ──────────────────────────────────────────────────
// Mirrors the exact input types / options used in the add-member form.
// type: 'select' | 'radio' | 'date-range' | 'text' (default)
const FILTER_FIELD_DEFINITIONS = {
// member
Occ_Stats: { type: 'select', options: ['UNEMPLOYED/NOT YET EMPLOYED', 'EMPLOYED'] },
First_time: { type: 'radio', options: ['YES', 'NO'] },
Mem_Type: { type: 'select', options: ['MANDATORY', 'VOLUNTARY'] },
Mem_Subtype: { type: 'select', options: ['EMPLOYED', 'OVERSEAS FILIPINO WORKER (OFW)', 'SELF-EMPLOYED', 'INDIVIDUAL PAYOR', 'OTHERS'] },
Type_Work: { type: 'select', options: ['Land-based', 'Sea-based'] },
Sex: { type: 'radio', options: ['M', 'F'] },
Marital_Status: { type: 'select', options: [
{ value: 'S', label: 'Single / Unmarried' },
{ value: 'W', label: 'Widow / er' },
{ value: 'A', label: 'Annulled' },
{ value: 'M', label: 'Married' },
{ value: 'LS', label: 'Legally Separated' }
]},
Frequency_Payment: { type: 'select', options: ['Monthly', 'Quarterly'] },
Birth_Date: { type: 'date-range' },
// contact
Pref_Mail_Address: { type: 'select', options: ['Present Home Address', 'Permanent Home Address', 'Employer/Business Address'] },
// employment
Employment_Status: { type: 'select', options: ['Permanent/Regular', 'Casual', 'Contractual', 'Project-based', 'Part-time/Temporary'] },
Office_Assignment: { type: 'select', options: ['Head Office', 'Branch Office'] },
Date_Employed: { type: 'date-range' },
// prevemployment
PrevOffice_Assignment: { type: 'select', options: ['Head Office', 'Branch Office'] },
Date_From: { type: 'date-range' },
Date_To: { type: 'date-range' },
// heir
Heir_DateBirth: { type: 'date-range' },
};
let activeFilters = {}; // { col: { type, value, valueTo? } }
window.addEventListener('DOMContentLoaded', () => {
buildFormWorkspace();
fetchLedgerRecords();
});
function changeWorkspaceTable(tableKey, menuRef) {
activeTable = tableKey;
document.querySelectorAll('#table-tabs li').forEach(el => el.classList.remove('selected'));
menuRef.classList.add('selected');
// ── 🏷️ METADATA MAPPING MATCHING YOUR EXACT ACCESSIBLE KEYS ──
const tableNamingMap = {
member: { main: "Member Information", sql: "member" },
contact: { main: "Contact Details", sql: "contact" },
employment: { main: "Current Employment", sql: "employment" },
prevemployment: { main: "Previous Employment", sql: "prevemployment" },
heir: { main: "Beneficiary Registry", sql: "heir" },
governmentid: { main: "Government IDs", sql: "governmentid" },
employer: { main: "Employer Registry", sql: "employer" }
};
const currentNaming = tableNamingMap[tableKey] || { main: tableKey, sql: tableKey };
// Update main text title header element
document.getElementById('active-title').innerText = currentNaming.main;
// Smoothly apply the gray folder path style with your exact blue SQL name popout
const breadcrumbContainer = document.querySelector('.breadcrumbs');
if (breadcrumbContainer) {
breadcrumbContainer.innerHTML = `
<span style="color: var(--slate-text-light);">Database / Tables / <span id="breadcrumb-sub" style="color: var(--pagibig-blue); font-weight: 600;">${currentNaming.sql}</span></span>
`;
}
clearFormCache();
buildFormWorkspace();
fetchLedgerRecords();
activeFilters = {};
const panel = document.getElementById('filter-panel');
if (panel) panel.classList.add('hidden');
buildFilterPanel();
const searchInput = document.getElementById('ledger-search-input');
if (searchInput) searchInput.value = '';
}
function initiateNewMemberWizard() {
isWizardMode = true;
wizardCurrentStepIndex = 0;
wizardPrimaryTrackingKey = null;
interruptedWizardState = null;
wizardStepRowMultipliers = { employment: 1, prevemployment: 1, heir: 1 };
wizardMultiEntryStore.member = null;
wizardMultiEntryStore.contact = null;
wizardMultiEntryStore.employment = [];
wizardMultiEntryStore.prevemployment = [];
wizardMultiEntryStore.heir = [];
wizardMultiEntryStore.governmentid = null;
activeTable = wizardSteps[wizardCurrentStepIndex];
workingRecordId = null;
document.getElementById('modal-title-intent').innerText = "Step 1: Account Identification Registration (Member Profile)";
openCrudModal();
buildFormWorkspace();
}
function clearFormCache() {
workingRecordId = null;
if (!isWizardMode) {
isWizardMode = false;
wizardPrimaryTrackingKey = null;
interruptedWizardState = null;
wizardStepRowMultipliers = { employment: 1, prevemployment: 1, heir: 1 };
wizardMultiEntryStore.member = null;
wizardMultiEntryStore.contact = null;
wizardMultiEntryStore.employment = [];
wizardMultiEntryStore.prevemployment = [];
wizardMultiEntryStore.heir = [];
wizardMultiEntryStore.governmentid = null;
}
}
function terminateWizardSession() {
isWizardMode = false;
wizardPrimaryTrackingKey = null;
interruptedWizardState = null;
closeCrudModal();
}
function injectWizardProgressIndicator() {
const box = document.getElementById('form-grid-target');
let progressHtml = `<div class="wizard-progress-bar">`;
wizardSteps.forEach((step, idx) => {
let statusClass = 'wizard-step-indicator';
let icon = 'circle';
if (idx === wizardCurrentStepIndex) {
statusClass += ' active-step';
icon = 'radio_button_unchecked';
} else if (idx < wizardCurrentStepIndex) {
statusClass += ' completed-step';
icon = 'check';
}
let stepLabel = step;
if (step === 'prevemployment') stepLabel = 'Prev Job';
if (step === 'governmentid') stepLabel = 'Gov IDs';
progressHtml += `
<div class="${statusClass}">
<div class="step-icon-wrapper">
<span class="material-symbols-outlined">${icon}</span>
</div>
<span class="step-label-text">${stepLabel}</span>
</div>`;
});
progressHtml += `</div>`;
box.innerHTML = progressHtml + box.innerHTML;
}
function suspendWizardForEmployerFiling() {
interruptedWizardState = {
wizardCurrentStepIndex: wizardCurrentStepIndex,
wizardPrimaryTrackingKey: wizardPrimaryTrackingKey,
cachedFormData: {}
};
const totalMultipliers = wizardStepRowMultipliers[activeTable] || 1;
for (let index = 0; index < totalMultipliers; index++) {
tableStructures[activeTable].forEach(attr => {
const domId = totalMultipliers === 1 ? `attr-${attr}` : `attr-${attr}-${index}`;
const field = document.getElementById(domId);
if (field) {
interruptedWizardState.cachedFormData[domId] = field.value;
} else if (['First_time', 'Sex'].includes(attr)) {
const checkedRadio = document.querySelector(`input[name="name-${domId}"]:checked`);
if (checkedRadio) interruptedWizardState.cachedFormData[domId] = checkedRadio.value;
}
});
}
isWizardMode = false;
activeTable = 'employer';
workingRecordId = null;
document.querySelectorAll('#table-tabs li').forEach(el => {
if(el.innerText.includes('Employer')) el.classList.add('selected');
else el.classList.remove('selected');
});
document.getElementById('modal-title-intent').innerText = "Interrupted Step Path: Provision New Employer Reference Key";
buildFormWorkspace();
}
function updateLedgerRowCounter() {
const counterDisplay = document.getElementById('ledger-row-counter-display');
if (!counterDisplay) return;
const rows = document.getElementById('ledger-body-target').getElementsByTagName('tr');
let totalCount = rows.length;
let visibleCount = 0;
// Check if the current table is completely empty first
if (totalCount === 1 && rows[0].cells.length === 1 && rows[0].cells[0].colSpan > 1) {
counterDisplay.innerText = "Showing 0 rows total";
return;
}
for (let i = 0; i < totalCount; i++) {
if (rows[i].style.display !== 'none') {
visibleCount++;
}
}
// Adjust text based on active filter applications
if (visibleCount === totalCount) {
counterDisplay.innerText = `Showing ${totalCount} row${totalCount !== 1 ? 's' : ''} total`;
} else {
counterDisplay.innerText = `Showing ${visibleCount} of ${totalCount} filtered row${totalCount !== 1 ? 's' : ''}`;
}
}
async function buildFormWorkspace() {
const box = document.getElementById('form-grid-target');
box.innerHTML = '';
const isNewRecord = workingRecordId === null;
if (!isWizardMode) {
const titleElement = document.getElementById('modal-title-intent');
if (titleElement) {
// Mapping table keys to clean display text labels
const displayNames = {
member: "Member Information Record",
contact: "Contact Details Record",
employment: "Current Employment Record",
prevemployment: "Previous Employment Record",
heir: "Beneficiary Registry Record",
governmentid: "Government IDs Record",
employer: "Employer Registry Record"
};
const currentLabel = displayNames[activeTable] || activeTable;
// Set title based on whether you are adding fresh or editing existing rows
titleElement.innerText = isNewRecord
? `Add Direct Entry (${currentLabel})`
: `Modify Record Entry (${currentLabel})`;
}
}
let nextEmployerId = '';
if (activeTable === 'employer' && isNewRecord) {
try {
const response = await fetch(`${API_BASE}/table/employer`);
const rows = await response.json();
let highestNum = 0;
rows.forEach(r => {
const match = (r.Employer_ID || '').match(/^E(\d+)$/i);
if (match) highestNum = Math.max(highestNum, parseInt(match[1], 10));
});
nextEmployerId = `E${String(highestNum + 1).padStart(3, '0')}`;
} catch(e) { nextEmployerId = 'E001'; }
}
let employerOptionsHtml = '<option value="" selected disabled>-- Select Registered Employer --</option>';
if (['employment', 'prevemployment'].includes(activeTable)) {
try {
const response = await fetch(`${API_BASE}/table/employer`);
const employers = await response.json();
employers.forEach(emp => {
employerOptionsHtml += `<option value="${emp.Employer_ID}">${emp.Employer_Name} (${emp.Employer_ID})</option>`;
});
} catch (err) { console.error(err); }
}
const renderLimitCount = isWizardMode ? (wizardStepRowMultipliers[activeTable] || 1) : 1;
for (let entryIndex = 0; entryIndex < renderLimitCount; entryIndex++) {
if (renderLimitCount > 1) {
let sectionLabel = activeTable === 'heir' ? `Beneficiary Profile #${entryIndex + 1}` : `Employment Entry Record #${entryIndex + 1}`;
let deleteSectionButtonHtml = entryIndex > 0
? `<button type="button" class="btn-divider-delete" onclick="evictWizardRowSetFields('${activeTable}', ${entryIndex})" title="Remove this entire row block">
<span class="material-symbols-outlined">delete</span> Delete Section
</button>`
: '';
box.innerHTML += `
<div class="multiplier-row-divider alignment-split-header">
<div class="notice-left-content" style="gap: 8px;">
<span class="material-symbols-outlined">layers</span>
<h4>${sectionLabel}</h4>
</div>
${deleteSectionButtonHtml}
</div>`;
}
let nextHeirCode = `H${String(1 + entryIndex).padStart(3, '0')}`;
if (activeTable === 'heir' && isNewRecord) {
try {
const response = await fetch(`${API_BASE}/table/heir`);
const rows = await response.json();
let highestHeirNum = 0;
rows.forEach(r => {
const match = (r.Heir_Code || '').match(/^H(\d+)$/i);
if (match) highestHeirNum = Math.max(highestHeirNum, parseInt(match[1], 10));
});
nextHeirCode = `H${String(highestHeirNum + 1 + entryIndex).padStart(3, '0')}`;
} catch(e) {}
}
tableStructures[activeTable].forEach(attr => {
if (attr === 'id') return;
let labelName = attr.replace(/_/g, ' ');
let inputHtml = '';
const isRequired = requiredFieldsConfig[activeTable].includes(attr);
const requiredAsterisk = isRequired ? ' <span class="required-asterisk">*</span>' : '';
const targetDOMId = renderLimitCount === 1 ? `attr-${attr}` : `attr-${attr}-${entryIndex}`;
switch (attr) {
case 'Occ_Stats':
inputHtml = `<select id="${targetDOMId}"><option value="" selected disabled>-- Select Status --</option><option value="UNEMPLOYED/NOT YET EMPLOYED">UNEMPLOYED / NOT YET EMPLOYED</option><option value="EMPLOYED">EMPLOYED</option></select>`;
break;
case 'First_time':
inputHtml = `
<div class="radio-group-container">
<label class="radio-inline-label"><input type="radio" name="name-${targetDOMId}" id="${targetDOMId}-YES" value="YES"> YES</label>
<label class="radio-inline-label"><input type="radio" name="name-${targetDOMId}" id="${targetDOMId}-NO" value="NO"> NO</label>
</div>`;
break;
case 'Mem_Type':
inputHtml = `<select id="${targetDOMId}" onchange="evaluateSubtypeConditionalDropdowns(this.value)"><option value="" selected disabled>-- Select Membership Type --</option><option value="MANDATORY">MANDATORY</option><option value="VOLUNTARY">VOLUNTARY</option></select>`;
break;
case 'Mem_Subtype':
inputHtml = `
<div id="subtype-conditional-wrapper">
<select id="${targetDOMId}" onchange="evaluateSubtypeConditionalDropdowns(document.getElementById('attr-Mem_Type').value); evaluateOfwFieldsVisibility(this.value);">
<option value="" selected disabled>-- Select Membership Type First --</option>
</select>
</div>`;
break;
case 'Type_Work':
inputHtml = `
<select id="${targetDOMId}">
<option value="" selected disabled>-- Select Type of Work --</option>
<option value="Land-based">Land-based</option>
<option value="Sea-based">Sea-based</option>
</select>`;
break;
case 'Type_Country':
inputHtml = `<input type="text" id="${targetDOMId}" maxlength="30" placeholder="e.g. SINGAPORE" autocomplete="off">`;
break;
case 'Sex':
inputHtml = `
<div class="radio-group-container">
<label class="radio-inline-label"><input type="radio" name="name-${targetDOMId}" id="${targetDOMId}-M" value="M"> M</label>
<label class="radio-inline-label"><input type="radio" name="name-${targetDOMId}" id="${targetDOMId}-F" value="F"> F</label>
</div>`;
break;
case 'Marital_Status':
inputHtml = `<select id="${targetDOMId}"><option value="" selected disabled>-- Select Marital Status --</option><option value="S">Single / Unmarried</option><option value="W">Widow / er</option><option value="A">Annulled</option><option value="M">Married</option><option value="LS">Legally Separated</option></select>`;
break;
case 'Frequency_Payment':
inputHtml = `<select id="${targetDOMId}"><option value="" selected disabled>-- Select Frequency --</option><option value="Monthly">Monthly</option><option value="Quarterly">Quarterly</option></select>`;
break;
case 'Pref_Mail_Address':
inputHtml = `<select id="${targetDOMId}"><option value="" selected disabled>-- Select Preferred Address --</option><option value="Present Home Address">Present Home Address</option><option value="Permanent Home Address">Permanent Home Address</option><option value="Employer/Business Address">Employer / Business Address</option></select>`;
break;
case 'Employer_ID':
if (['employment', 'prevemployment'].includes(activeTable)) {
inputHtml = `<select id="${targetDOMId}">${employerOptionsHtml}</select>`;
} else if (activeTable === 'employer') {
inputHtml = `<input type="text" id="${targetDOMId}" value="${isNewRecord ? nextEmployerId : ''}" disabled>`;
}
break;
case 'Employment_Status':
inputHtml = `<select id="${targetDOMId}"><option value="" selected disabled>-- Select Employment Status --</option><option value="Permanent/Regular">Permanent / Regular</option><option value="Casual">Casual</option><option value="Contractual">Contractual</option><option value="Project-based">Project-based</option><option value="Part-time/Temporary">Part-time / Temporary</option></select>`;
break;
case 'Office_Assignment':
case 'PrevOffice_Assignment':
inputHtml = `<select id="${targetDOMId}"><option value="" selected disabled>-- Select Office Assignment --</option><option value="Head Office">Head Office</option><option value="Branch Office">Branch Office</option></select>`;
break;
case 'Heir_Code':
inputHtml = `<input type="text" id="${targetDOMId}" value="${isNewRecord ? nextHeirCode : ''}" disabled>`;
break;
default:
let inputType = 'text';
let extraAttributes = '';
let placeholderText = '';
const numericColumns = ['Pagibig_ID', 'Regis_num', 'Height', 'Weight', 'Monthly_Income', 'TIN_Num', 'SSS_Num', 'CRN', 'EM_Num', 'AFP_PNP_Num', 'Deped_Code'];
const dateColumns = ['Birth_Date', 'Date_Employed', 'Date_From', 'Date_To', 'Heir_DateBirth'];
if (numericColumns.includes(attr)) inputType = 'number';
if (dateColumns.includes(attr)) {
inputType = 'date';
// Dynamically calculate today's ISO date string (YYYY-MM-DD)
const todayISO = new Date().toISOString().split('T')[0];
extraAttributes += ` max="${todayISO}"`;
}
if (['Mem_Name', 'Fat_Name', 'Mot_Name', 'Spouse_Name', 'MemCert_Name', 'Heir_Name'].includes(attr)) {
placeholderText = 'LAST NAME, FIRST NAME MIDDLE NAME';
} else if (['Cell_Num'].includes(attr)) {
placeholderText = '+63 XXX XXXX XXX';
}
if (inputType === 'text') {
if (attr !== 'Pagibig_ID') {
extraAttributes = `placeholder="${placeholderText}"`;
}
if (['Mem_Name', 'MemCert_Name', 'Fat_Name', 'Mot_Name', 'Spouse_Name', 'Heir_Name', 'Employer_Name'].includes(attr)) {
extraAttributes += ' maxlength="50"';
} else if (['Place_Birth', 'Perm_Address', 'Present_Address', 'Employer_Address'].includes(attr)) {
extraAttributes += ' maxlength="80"';
} else if (attr === 'Facial_Features') {
extraAttributes += ' maxlength="50"';
} else if (attr === 'Type_Country') {
extraAttributes += ' maxlength="30"';
} else if (attr === 'Cell_Num') {
extraAttributes += ' maxlength="16"';
} else if (['Home_Num', 'Business_Direct', 'Business_Trunk', 'Relationship'].includes(attr)) {
extraAttributes += ' maxlength="15"';
}
} else if (inputType === 'number') {
if (['Pagibig_ID', 'Regis_num', 'CRN', 'EM_Num'].includes(attr)) extraAttributes = 'oninput="if(this.value.length > 12) this.value = this.value.slice(0, 12);"';
else if (attr === 'TIN_Num') extraAttributes = 'oninput="if(this.value.length > 9) this.value = this.value.slice(0, 9);"';
else if (attr === 'SSS_Num') extraAttributes = 'oninput="if(this.value.length > 11) this.value = this.value.slice(0, 11);"';
else if (['Height', 'Weight'].includes(attr)) extraAttributes = 'oninput="if(this.value.length > 3) this.value = this.value.slice(0, 3);"';
else if (['AFP_PNP_Num', 'Deped_Code'].includes(attr)) extraAttributes = 'oninput="if(this.value.length > 6) this.value = this.value.slice(0, 6);"';
}
inputHtml = `<input type="${inputType}" id="${targetDOMId}" ${extraAttributes} autocomplete="off">`;
break;
}
let wrapperIdHtml = '';
if (attr === 'Type_Work' || attr === 'Type_Country') {
wrapperIdHtml = ` id="grid-row-wrapper-${attr}" style="display: none;"`;
}
box.innerHTML += `
<div${wrapperIdHtml}>
<label for="${targetDOMId}">${labelName}${requiredAsterisk}</label>
${inputHtml}
</div>`;
});
}
if (activeTable === 'contact') {
const addressMirrorCheckboxHtml = `
<div style="grid-column: span 2; flex-direction: row !important; align-items: center; gap: 8px; margin: -4px 0 6px 0;">
<input type="checkbox" id="sync-present-address-checkbox" style="width: auto; cursor: pointer;" onchange="toggleAddressMirrorSynchronization(this)">
<label for="sync-present-address-checkbox" style="margin: 0; text-transform: none; font-size: 13px; font-weight: 500; cursor: pointer; color: var(--slate-text-light);">
Present Address is the same as Permanent Home Address
</label>
</div>`;
const presentAddrField = document.getElementById('attr-Present_Address').parentElement;
presentAddrField.insertAdjacentHTML('beforebegin', addressMirrorCheckboxHtml);
const permAddrInput = document.getElementById('attr-Perm_Address');
if (permAddrInput) {
permAddrInput.addEventListener('input', () => {
const cb = document.getElementById('sync-present-address-checkbox');
if (cb && cb.checked) {
document.getElementById('attr-Present_Address').value = permAddrInput.value;
}
});
}
}
// ==========================================================================
// 🔒 TIMELINE STEPPER FOOTER MANAGEMENT LAYERS
// ==========================================================================
if (isWizardMode) {
injectWizardProgressIndicator();
if (['employment', 'prevemployment'].includes(activeTable)) {
const topNoticeHtml = `
<div class="wizard-top-notice-banner">
<div class="notice-left-content">
<span class="material-symbols-outlined">corporate_fare</span>
<span>Can't find the registered business listed in the drop-down selector?</span>
</div>
<button type="button" class="btn-primary flex-center" onclick="suspendWizardForEmployerFiling()">
<span class="material-symbols-outlined">add</span> Input New Employer
</button>
</div>`;
const progressBarElement = box.querySelector('.wizard-progress-bar');
if (progressBarElement) {
progressBarElement.insertAdjacentHTML('afterend', topNoticeHtml);
}
}
let wizardFooterActionsHtml = '';
if (['employment', 'prevemployment'].includes(activeTable)) {
wizardFooterActionsHtml += `
<div class="wizard-array-actions-block">
<button type="button" class="btn-secondary" onclick="incrementWizardFormRowFields('${activeTable}')">+ Cache & Add Another Job</button>
</div>`;
} else if (activeTable === 'heir') {
wizardFooterActionsHtml += `
<div class="wizard-array-actions-block">
<button type="button" class="btn-secondary" onclick="incrementWizardFormRowFields('heir')">+ Cache & Add Another Beneficiary</button>
</div>`;
}
if (wizardFooterActionsHtml) {
box.insertAdjacentHTML('beforeend', `<div style="grid-column: span 2; margin-top: 10px;">${wizardFooterActionsHtml}</div>`);
}
const modalFooter = document.querySelector('.modal-footer');
if (modalFooter) {
const optionalTables = ['employment', 'prevemployment'];
const isCurrentStepOptional = optionalTables.includes(activeTable);
let skipButtonHtml = isCurrentStepOptional
? `<button class="btn-danger" style="background-color: #fef2f2; color: #dc2626; border: 1px solid #fca5a5;" onclick="bypassOptionalWizardSegment('${activeTable}')">Skip Step</button>`
: '';
if (wizardCurrentStepIndex > 0) {
modalFooter.innerHTML = `
<button class="btn-secondary" onclick="closeCrudModal()">Cancel</button>
<button class="btn-secondary" style="margin-right: auto;" onclick="advanceWizardStepEngine('prev')">← Back</button>
${skipButtonHtml}
<button class="btn-primary" onclick="commitSaveTransaction()">Next Step →</button>
`;
} else {
modalFooter.innerHTML = `
<button class="btn-secondary" onclick="closeCrudModal()">Cancel</button>
${skipButtonHtml}
<button class="btn-primary" onclick="commitSaveTransaction()">Next Step →</button>
`;
}
}
const nextButton = document.querySelector('.modal-footer .btn-primary');
if (nextButton) {
nextButton.innerText = (wizardCurrentStepIndex === wizardSteps.length - 1) ? "Finish & Save" : "Next Step →";
}
} else if (activeTable === 'employer' && interruptedWizardState !== null) {
const modalFooter = document.querySelector('.modal-footer');
if (modalFooter) {
modalFooter.innerHTML = `
<button class="btn-secondary" onclick="cancelEmployerFilingAndReturn()">Cancel</button>
<button class="btn-primary" onclick="commitSaveTransaction()">Commit Employer & Return</button>
`;
}
} else {
const modalFooter = document.querySelector('.modal-footer');
if (modalFooter) {
modalFooter.innerHTML = `
<button class="btn-secondary" onclick="closeCrudModal()">Cancel</button>
<button class="btn-primary" onclick="commitSaveTransaction()">Save Changes</button>
`;
}
}
// SAFE DATA RESTORATION FOR SINGLE-OR-MULTIPLIED NODES
if (isWizardMode) {
try {
const stepCacheData = wizardMultiEntryStore[activeTable];
if (stepCacheData) {
const isArrayData = Array.isArray(stepCacheData);
const itemsToLoad = isArrayData ? stepCacheData : [stepCacheData];
itemsToLoad.forEach((rowPayload, indexId) => {
if (indexId >= renderLimitCount) return;
tableStructures[activeTable].forEach(attr => {
const elementId = renderLimitCount === 1 ? `attr-${attr}` : `attr-${attr}-${indexId}`;
if (['First_time', 'Sex'].includes(attr)) {
const radioVal = rowPayload[attr];
if (radioVal) {
// 💡 Fixed: Target option inputs matching specific generated IDs
const radioEl = document.getElementById(`${elementId}-${radioVal}`);
if (radioEl) radioEl.checked = true;
}
} else {
const field = document.getElementById(elementId);
if (field && rowPayload[attr] !== undefined && rowPayload[attr] !== null) {
if (attr === 'Mem_Type') {
field.value = rowPayload[attr];
evaluateSubtypeConditionalDropdowns(rowPayload[attr]);
} else if (attr === 'Mem_Subtype') {
field.value = rowPayload[attr];
evaluateOfwFieldsVisibility(rowPayload[attr]);
} else {
field.value = rowPayload[attr];
}
}
}
});
});
}
} catch (restorationError) {
console.warn("Restoration loop safely caught exceptions:", restorationError);
}
}
// LOCK DOWN AND MONITOR PAG-IBIG ID FIELD WITH NO PLACEHOLDER
const primaryIdField = document.getElementById('attr-Pagibig_ID') || document.getElementById('attr-Pagibig_ID-0');
if (primaryIdField) {
if (isWizardMode) {
if (activeTable === 'member') {
primaryIdField.readOnly = false;
primaryIdField.disabled = false;
if (wizardPrimaryTrackingKey) {
primaryIdField.value = wizardPrimaryTrackingKey;
}
} else {
for(let i=0; i<renderLimitCount; i++) {
const dynamicIdField = document.getElementById(`attr-Pagibig_ID-${i}`) || document.getElementById('attr-Pagibig_ID');
if(dynamicIdField) {
dynamicIdField.value = wizardPrimaryTrackingKey || '';
dynamicIdField.readOnly = true;
}
}
}
} else {
primaryIdField.readOnly = false;
primaryIdField.disabled = false;
primaryIdField.value = '';
}
}
}
// 💡 FIXED: Reads and preserves typed data from existing blocks before adding a new section pass
function incrementWizardFormRowFields(tableKey) {
const loopCount = wizardStepRowMultipliers[tableKey] || 1;
const compiledPayloadCache = [];
// 1. Gather all inputs currently typed on the screen so we don't lose them
for (let rowId = 0; rowId < loopCount; rowId++) {
const singleRowPayload = {};
tableStructures[tableKey].forEach(attr => {
const domId = loopCount === 1 ? `attr-${attr}` : `attr-${attr}-${rowId}`;
if (['First_time', 'Sex'].includes(attr)) {
const checkedRadio = document.querySelector(`input[name="name-${domId}"]:checked`);
singleRowPayload[attr] = checkedRadio ? checkedRadio.value : '';
} else {
const inputField = document.getElementById(domId);
if (inputField) {
let val = inputField.value;
if (typeof val === 'string' && inputField.tagName.toLowerCase() === 'input' && inputField.type === 'text') {
val = val.trim().toUpperCase();
}
singleRowPayload[attr] = val;
} else {
singleRowPayload[attr] = '';
}
}
});
if (wizardPrimaryTrackingKey !== null && tableStructures[tableKey].includes('Pagibig_ID')) {
singleRowPayload['Pagibig_ID'] = wizardPrimaryTrackingKey;
}
compiledPayloadCache.push(singleRowPayload);
}
// 2. Commit the active rows directly into your temporary memory store array
wizardMultiEntryStore[tableKey] = compiledPayloadCache;
// 3. Safe increment the field section multiplier pointer
wizardStepRowMultipliers[tableKey] = loopCount + 1;
triggerNotificationBanner('success', "Successfully appended new input fields.");
// 4. Re-render the form. The restoration engine below will fill in what we just saved!
buildFormWorkspace();
}
function toggleAddressMirrorSynchronization(checkboxRef) {
const presentAddrInput = document.getElementById('attr-Present_Address');
const permAddrValue = document.getElementById('attr-Perm_Address').value;
if (checkboxRef.checked) {
presentAddrInput.value = permAddrValue;
presentAddrInput.disabled = true;
} else {
presentAddrInput.disabled = false;
presentAddrInput.value = '';
}
}
function openChoiceModal() {
document.getElementById('choice-modal-overlay').classList.remove('hidden');
}
function closeChoiceModal() {
document.getElementById('choice-modal-overlay').classList.add('hidden');
}
function handleChoiceSelection(selectionType) {
closeChoiceModal();
if (selectionType === 'wizard') {
initiateNewMemberWizard();
} else if (selectionType === 'single') {
clearFormCache();
buildFormWorkspace();
openCrudModal();
}
}
function bypassOptionalWizardSegment(tableKey) {
wizardMultiEntryStore[tableKey] = [];
triggerNotificationBanner('success', `Skipped records for ${tableKey}.`);
if (wizardCurrentStepIndex < wizardSteps.length - 1) {
wizardCurrentStepIndex++;
activeTable = wizardSteps[wizardCurrentStepIndex];
workingRecordId = null;
buildFormWorkspace();
document.getElementById('modal-title-intent').innerText = `Step ${wizardCurrentStepIndex + 1}: Unified Registration (${activeTable})`;
}
}
async function advanceWizardStepEngine(direction = 'next') {
if (direction === 'next' || direction === 'prev') {
const loopCount = wizardStepRowMultipliers[activeTable] || 1;
const compiledPayloadCache = [];
for (let rowId = 0; rowId < loopCount; rowId++) {
const singleRowPayload = {};
tableStructures[activeTable].forEach(attr => {
const domId = loopCount === 1 ? `attr-${attr}` : `attr-${attr}-${rowId}`;
if (['First_time', 'Sex'].includes(attr)) {
// 💡 Fixed: Extract radio choices utilizing unique indexed row configurations
const checkedRadio = document.querySelector(`input[name="name-${domId}"]:checked`);
singleRowPayload[attr] = checkedRadio ? checkedRadio.value : '';
} else {
const inputField = document.getElementById(domId);
if (inputField) {
let val = inputField.value;
if (typeof val === 'string' && inputField.tagName.toLowerCase() === 'input' && inputField.type === 'text') {
val = val.trim().toUpperCase();
}
singleRowPayload[attr] = val;
} else {
singleRowPayload[attr] = '';
}
}
});
if (wizardPrimaryTrackingKey !== null && tableStructures[activeTable].includes('Pagibig_ID')) {
singleRowPayload['Pagibig_ID'] = wizardPrimaryTrackingKey;
}
compiledPayloadCache.push(singleRowPayload);
}
if (!['employment', 'prevemployment', 'heir'].includes(activeTable)) {
wizardMultiEntryStore[activeTable] = compiledPayloadCache[0];
} else {
wizardMultiEntryStore[activeTable] = compiledPayloadCache.filter(rowItem => {
return Object.keys(rowItem).some(k => k !== 'Pagibig_ID' && k !== 'Heir_Code' && rowItem[k] !== '');
});
}
}
if (direction === 'prev') {
if (wizardCurrentStepIndex > 0) {
wizardCurrentStepIndex--;
activeTable = wizardSteps[wizardCurrentStepIndex];
workingRecordId = null;
await buildFormWorkspace();
document.getElementById('modal-title-intent').innerText = `Step ${wizardCurrentStepIndex + 1}: Unified Registration (${activeTable})`;
}
return;
}
if (wizardCurrentStepIndex < wizardSteps.length - 1) {
wizardCurrentStepIndex++;
activeTable = wizardSteps[wizardCurrentStepIndex];
workingRecordId = null;
await buildFormWorkspace();
document.getElementById('modal-title-intent').innerText = `Step ${wizardCurrentStepIndex + 1}: Unified Registration (${activeTable})`;
} else {
if (wizardMultiEntryStore.heir.length === 0) {
triggerNotificationBanner('error', "Validation Violation: Member must have at least one beneficiary.");
return;
}
await pushMultiEntryWizardPipeline();
}
}
async function pushMultiEntryWizardPipeline() {
try {
triggerNotificationBanner('success', "Uploading batch registration records...");
if (wizardMultiEntryStore.member) {
await fetch(`${API_BASE}/create/member`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(wizardMultiEntryStore.member)
});
}
if (wizardMultiEntryStore.contact) {
await fetch(`${API_BASE}/create/contact`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(wizardMultiEntryStore.contact)
});
}
const arrayTables = ['employment', 'prevemployment', 'heir'];
for (let tableKey of arrayTables) {
const recordsList = wizardMultiEntryStore[tableKey];
if (recordsList && recordsList.length > 0) {
for (let dataRow of recordsList) {
await fetch(`${API_BASE}/create/${tableKey}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(dataRow)
});
}
}
}
if (wizardMultiEntryStore.governmentid) {
const explicitUserInputs = Object.keys(wizardMultiEntryStore.governmentid).filter(key => key !== 'Pagibig_ID');
const hasValidIdentificationData = explicitUserInputs.some(
key => wizardMultiEntryStore.governmentid[key] !== null && wizardMultiEntryStore.governmentid[key].trim() !== ""
);
if (hasValidIdentificationData) {
await fetch(`${API_BASE}/create/governmentid`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(wizardMultiEntryStore.governmentid)
});
}
}
isWizardMode = false;
activeTable = 'member';
fetchLedgerRecords();
terminateWizardSession();
triggerNotificationBanner('success', "Full member data has been successfully added to all relations!");
} catch (err) {
console.error("Batch commit crash transaction failure:", err);
triggerNotificationBanner('error', "Fatal transaction failure encountered during sequential data persistence.");
}
}
async function commitSaveTransaction() {
// === 📅 DATE & AGE VALIDATION POLISHES ===
const today = new Date();
today.setHours(0, 0, 0, 0);
const isWizard = isWizardMode;
const currentTable = activeTable;
const bounds = isWizard ? (wizardStepRowMultipliers[currentTable] || 1) : 1;
for (let rId = 0; rId < bounds; rId++) {
const dateFields = ['Birth_Date', 'Date_Employed', 'Date_From', 'Date_To', 'Heir_DateBirth'].filter(d => tableStructures[currentTable].includes(d));
for (let attr of dateFields) {
const domId = bounds === 1 ? `attr-${attr}` : `attr-${attr}-${rId}`;
const dateFieldInput = document.getElementById(domId);
if (dateFieldInput && dateFieldInput.value) {
const selectedDate = new Date(dateFieldInput.value);
selectedDate.setHours(0, 0, 0, 0);
if (selectedDate > today) {
triggerNotificationBanner('error', `Validation Blocked: ${attr.replace(/_/g, ' ')} cannot be a future date.`);
return;
}
if (attr === 'Birth_Date' && currentTable === 'member') {
let age = today.getFullYear() - selectedDate.getFullYear();
const monthDifference = today.getMonth() - selectedDate.getMonth();
if (monthDifference < 0 || (monthDifference === 0 && today.getDate() < selectedDate.getDate())) {
age--;
}
if (age < 18) {
triggerNotificationBanner('error', "Registration Refused: Member account registration requires applicant to be at least 18 years old.");
return;
}
}
}
}
}
const isEditMode = workingRecordId !== null;
if (!isWizardMode || (activeTable === 'employer' && interruptedWizardState !== null)) {
const dataPayload = {};
let requiredFieldsMissing = false;
tableStructures[activeTable].forEach(attr => {
if (['First_time', 'Sex'].includes(attr)) {
const checkedRadio = document.querySelector(`input[name="name-attr-${attr}"]:checked`);
dataPayload[attr] = checkedRadio ? checkedRadio.value : '';
} else {
const inputField = document.getElementById(`attr-${attr}`);
if (inputField) {
let val = inputField.value;
if (typeof val === 'string' && inputField.tagName.toLowerCase() === 'input' && inputField.type === 'text') {
val = val.trim().toUpperCase();
}
dataPayload[attr] = val;
}
}
if (requiredFieldsConfig[activeTable].includes(attr) && !dataPayload[attr]) requiredFieldsMissing = true;
});
if (requiredFieldsMissing) {
triggerNotificationBanner('error', "Validation Blocked: Missing mandatory fields.");
return;
}
// ── PAG-IBIG ID EXISTENCE CHECK FOR STANDALONE ENTRIES ──
if (activeTable !== 'member' && activeTable !== 'employer' && dataPayload['Pagibig_ID']) {
try {
const checkResponse = await fetch(`${API_BASE}/table/member`);
const existingMembers = await checkResponse.json();
const idExists = existingMembers.some(m => String(m.Pagibig_ID).trim() === String(dataPayload['Pagibig_ID']).trim());
if (!idExists) {
triggerNotificationBanner('error', `Save Refused: Pag-IBIG ID '${dataPayload['Pagibig_ID']}' does not exist in the Member Registry.`);
return; // Halt transaction execution flow completely