-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOperations.js
More file actions
1747 lines (1503 loc) · 68.1 KB
/
Copy pathOperations.js
File metadata and controls
1747 lines (1503 loc) · 68.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Operations.gs
* Core data management and administrative operations
*/
/**
* Fetch App Configuration from Settings sheet
*/
function getAppConfig() {
const config = { CFG_COL_CONTACT: "Contact Name", CFG_COL_REP: "Sales Rep" };
try {
const sheet = getSheet(SHEET_NAMES.SETTINGS);
const lastRow = sheet.getLastRow();
if (lastRow < 2) return config;
const data = sheet.getRange(2, 1, lastRow - 1, 2).getValues();
data.forEach(row => {
const key = String(row[0]).trim();
const val = String(row[1]).trim();
if (key) config[key] = val;
});
// Directive v1.8.49: Fetch Admin Key from Named Range
try {
const adminRange = SpreadsheetApp.getActiveSpreadsheet().getRangeByName("ADMIN_LOGIN");
if (adminRange) {
config.ADMIN_KEY = String(adminRange.getValue()).trim();
} else {
// Fail closed: no key means admin access is denied
config.ADMIN_KEY = config.ADMIN_KEY || "";
}
} catch (e) { }
} catch (e) {
console.error("Error reading config:", e);
}
return config;
}
/**
* Update Configuration Setting
*/
function updateConfigSetting(key, value) {
const ss = SpreadsheetApp.getActiveSpreadsheet();
let sheet = ss.getSheetByName(SHEET_NAMES.SETTINGS);
if (!sheet) {
setupSettingsSheet();
sheet = ss.getSheetByName(SHEET_NAMES.SETTINGS);
}
const data = sheet.getRange(2, 1, sheet.getLastRow() - 1, 2).getValues();
let rowToUpdate = -1;
for (let i = 0; i < data.length; i++) {
if (String(data[i][0]).trim() === key) {
rowToUpdate = i + 2;
break;
}
}
if (rowToUpdate !== -1) {
sheet.getRange(rowToUpdate, 2).setValue(value);
} else {
sheet.appendRow([key, value]);
}
SpreadsheetApp.flush();
return { success: true, key: key, value: value };
}
/**
* Dashboard Action Router
*/
function onSelectionChange(e) {
const range = e.range;
const sheet = range.getSheet();
if (sheet.getName() !== SHEET_NAMES.DASHBOARD) return;
if (range.getNumRows() === 1 && range.getColumn() === 2) {
const row = range.getRow();
if (row < 6 || row > 15) return;
const actions = {
6: "showOrderFormDialog",
8: "showAddProductSidebar",
11: "generateSelectedOrderPdf",
12: "cleanupProductSheet",
13: "styleProductHeaders",
14: "refreshDailyOperationsDashboard"
};
const functionName = actions[row];
if (functionName && typeof this[functionName] === 'function') {
SpreadsheetApp.getActiveSpreadsheet().toast("Processing action: " + actionNameFromRow(row) + "...", "Order System", 3);
sheet.getRange("A1").activate(); // Reset selection
this[functionName]();
}
}
}
/**
* Helper to get clean name for Toast
*/
function actionNameFromRow(row) {
const names = {
6: "Launch Web App",
8: "Add Product",
11: "Generate PDF",
12: "Cleanup",
13: "Refresh Visuals",
14: "Update Daily Ops"
};
return names[row] || "Action";
}
/**
* Save Client Information Update Request
* Writes to CLIENT_INFO_UPDATES sheet for admin review
*/
function saveClientInfoUpdate(updateData) {
const ss = SpreadsheetApp.getActiveSpreadsheet();
let sheet = ss.getSheetByName(SHEET_NAMES.CLIENT_INFO_UPDATES);
// Create sheet if it doesn't exist
if (!sheet) {
sheet = ss.insertSheet(SHEET_NAMES.CLIENT_INFO_UPDATES);
sheet.appendRow([
'Timestamp',
'Original Client ID',
'New Client ID',
'New Client Name',
'New Address',
'Status'
]);
sheet.getRange(1, 1, 1, 6).setFontWeight('bold');
}
// Append the update request
sheet.appendRow([
new Date(),
updateData.originalClientId || '',
updateData.newClientId || '',
updateData.newClientName || '',
updateData.newAddress || '',
'Pending Review'
]);
return { success: true, message: 'Update request submitted for review.' };
}
/**
* Client Data Operations
*/
function getClientById(clientId) {
const clients = getClientData();
if (clients.length === 0) return null;
const targetId = String(clientId).trim().toLowerCase();
const idKey = Object.keys(clients[0]).find(k => superNormalize(k) === 'clientid');
if (!idKey) return null;
const client = clients.find(c => String(c[idKey]).trim().toLowerCase() === targetId);
if (client) {
client.Name = client['Company Name'] || client['Company Name '] || client['Name'] || "";
client.Address = client['Address'] || client['Address '] || "";
// DEBUG: Log all client keys
const clientKeys = Object.keys(client);
console.log('[getClientById] Client keys:', JSON.stringify(clientKeys));
// Read section permissions - try to find section columns dynamically
client.allowedSections = [];
clientKeys.forEach(key => {
const upperKey = String(key).toUpperCase();
if (upperKey.includes('SECTION')) {
const val = client[key];
console.log(`[getClientById] Section key "${key}" = ${val} (type: ${typeof val})`);
if (val === true || String(val).toUpperCase() === 'TRUE') {
// Extract A, B, C, D from key name
if (upperKey.includes('_A') || upperKey.endsWith('A')) client.allowedSections.push('A');
else if (upperKey.includes('_B') || upperKey.endsWith('B')) client.allowedSections.push('B');
else if (upperKey.includes('_C') || upperKey.endsWith('C')) client.allowedSections.push('C');
else if (upperKey.includes('_D') || upperKey.endsWith('D')) client.allowedSections.push('D');
}
}
});
console.log('[getClientById] Allowed sections after check:', JSON.stringify(client.allowedSections));
// If no sections specified, allow all (backward compatibility)
if (client.allowedSections.length === 0) {
console.log('[getClientById] No sections found, defaulting to all');
client.allowedSections = ['A', 'B', 'C', 'D'];
}
}
return client;
}
function getClientData() {
const sheet = getSheet(SHEET_NAMES.CLIENT_DATA);
const lastRow = sheet.getLastRow();
const lastCol = sheet.getLastColumn();
if (lastRow < 3 || lastCol < 1) return [];
// Read BOTH header rows - row 1 has SECTION columns, row 2 has other columns
const headerRow1 = sheet.getRange(1, 1, 1, lastCol).getValues()[0];
const headerRow2 = sheet.getRange(2, 1, 1, lastCol).getValues()[0];
// Smart merge: Use row 1 ONLY for SECTION columns, row 2 for everything else
const validIndices = [];
const headers = [];
for (let i = 0; i < lastCol; i++) {
const h1 = String(headerRow1[i] || '').trim();
const h2 = String(headerRow2[i] || '').trim();
// Use row 1 header only if it contains "SECTION", otherwise use row 2
let header;
if (h1.toUpperCase().includes('SECTION')) {
header = h1; // Use SECTION_A, SECTION_B, etc. from row 1
} else {
header = h2 || h1; // Use row 2 (CLIENT_ID, Company Name, etc.), fallback to row 1
}
if (header) {
validIndices.push(i);
headers.push(header);
}
}
console.log('[getClientData] Merged headers:', JSON.stringify(headers.slice(0, 10)) + '...');
if (headers.length === 0) return [];
const dataValues = sheet.getRange(3, 1, lastRow - 2, lastCol).getValues();
return dataValues.map(row => {
let client = {};
validIndices.forEach((colIndex, i) => { client[headers[i]] = row[colIndex]; });
return client;
});
}
/**
* Fetch Client Types from the CLIENT_TYPES named range
* Returns an array of type strings for the dropdown
*/
function getClientTypes() {
try {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const range = ss.getRangeByName("CLIENT_TYPES");
if (!range) return [];
const values = range.getValues();
const types = [];
values.forEach(row => {
const val = String(row[0] || "").trim();
if (val) types.push(val);
});
return types;
} catch (e) {
console.error("[getClientTypes] Error:", e.message);
return [];
}
}
/**
* Fetch Section Names from named ranges SECTION_A, SECTION_B, SECTION_C, SECTION_D
* Returns an array of { key: 'A', name: 'Tobacco' } objects
*/
function getSectionNames() {
const sections = [];
const ss = SpreadsheetApp.getActiveSpreadsheet();
const keys = ['A', 'B', 'C', 'D'];
keys.forEach(key => {
try {
const range = ss.getRangeByName('SECTION_' + key);
if (range) {
const name = String(range.getValue() || '').trim();
sections.push({ key: key, name: name || ('Section ' + key) });
} else {
sections.push({ key: key, name: 'Section ' + key });
}
} catch (e) {
sections.push({ key: key, name: 'Section ' + key });
}
});
return sections;
}
/**
* Add a new client to the CLIENT DATA sheet
* @param {Object} clientData - { clientId, companyName, type, phone, manager, address }
* @returns {Object} - { success, message }
*/
function addNewClient(clientData) {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName(SHEET_NAMES.CLIENT_DATA);
if (!sheet) throw new Error("CLIENT DATA sheet not found.");
const lastCol = sheet.getLastColumn();
const headerRow1 = sheet.getRange(1, 1, 1, lastCol).getValues()[0];
const headerRow2 = sheet.getRange(2, 1, 1, lastCol).getValues()[0];
// Build a column index map from the header row (row 2) for data fields
// Uses superNormalize for resilient matching regardless of column order or casing
const colMap = {};
const colMapRaw = {};
headerRow2.forEach((h, i) => {
const key = String(h || "").trim();
const norm = superNormalize(key);
if (norm) {
colMap[norm] = i;
colMapRaw[key.toLowerCase()] = i;
}
});
// Build section column map from row 1 (SECTION_A, SECTION_B, etc.)
const sectionColMap = {};
headerRow1.forEach((h, i) => {
const key = String(h || "").trim().toUpperCase();
if (key.includes('SECTION')) {
sectionColMap[key] = i;
}
});
console.log("[addNewClient] Data column map:", JSON.stringify(Object.keys(colMap)));
console.log("[addNewClient] Section column map:", JSON.stringify(sectionColMap));
// Validate required fields
const clientId = String(clientData.clientId || "").trim();
const companyName = String(clientData.companyName || "").trim();
if (!clientId) return { success: false, message: "Client ID is required." };
if (!companyName) return { success: false, message: "Company Name is required." };
// Check for duplicate Client ID
const existingClients = getClientData();
const idKey = Object.keys(existingClients[0] || {}).find(k => superNormalize(k) === 'clientid');
if (idKey) {
const duplicate = existingClients.find(c => String(c[idKey]).trim().toLowerCase() === clientId.toLowerCase());
if (duplicate) return { success: false, message: "Client ID '" + clientId + "' already exists." };
}
// Build the new row (all empty, then fill mapped columns)
const newRow = new Array(lastCol).fill("");
// Map data fields to columns using normalized + raw matching for resilience
const setCol = (names, value) => {
// Try exact raw lowercase match first, then superNormalize match
for (const name of names) {
if (colMapRaw[name] !== undefined) {
newRow[colMapRaw[name]] = value;
return true;
}
}
for (const name of names) {
const norm = superNormalize(name);
if (colMap[norm] !== undefined) {
newRow[colMap[norm]] = value;
return true;
}
}
return false;
};
setCol(['client_id', 'clientid', 'client id', 'id'], clientId);
setCol(['company name', 'companyname', 'name', 'company'], companyName);
setCol(['type', 'client type', 'clienttype', 'account type'], clientData.type || "");
setCol(['phone', 'phone number', 'telephone', 'tel'], clientData.phone || "");
setCol(['manager', 'contact', 'contact name', 'manager name'], clientData.manager || "");
setCol(['address', 'street address', 'full address'], clientData.address || "");
// Set section values (TRUE/FALSE) from checkbox selections
const sections = clientData.sections || {};
['A', 'B', 'C', 'D'].forEach(key => {
const colKey = 'SECTION_' + key;
if (sectionColMap[colKey] !== undefined) {
newRow[sectionColMap[colKey]] = sections[key] === true;
}
});
// Append after the last row
const lastRow = sheet.getLastRow();
const newRowNum = lastRow + 1;
sheet.getRange(newRowNum, 1, 1, lastCol).setValues([newRow]);
// Apply checkbox data validation to the section columns in the new row
const checkboxRule = SpreadsheetApp.newDataValidation()
.requireCheckbox()
.setAllowInvalid(false)
.build();
['A', 'B', 'C', 'D'].forEach(key => {
const colKey = 'SECTION_' + key;
if (sectionColMap[colKey] !== undefined) {
const colNum = sectionColMap[colKey] + 1; // 1-indexed
sheet.getRange(newRowNum, colNum).setDataValidation(checkboxRule);
}
});
SpreadsheetApp.flush();
console.log("[addNewClient] Added client: " + clientId + " - " + companyName + " with sections: " + JSON.stringify(sections));
return { success: true, message: "Client '" + companyName + "' added successfully!" };
}
/**
* Load color definitions from the COLOUR_FORMAT_DEFINITIONS named range.
* Expects a table with 3 columns: Color Name | Hex Value | Text Color
* Returns an object keyed by lowercase color name.
*/
function loadColorDefinitions_() {
const defs = {};
try {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const range = ss.getRangeByName('COLOUR_FORMAT_DEFINITIONS');
if (!range) return defs;
const data = range.getValues();
for (let r = 0; r < data.length; r++) {
const name = String(data[r][0] || '').trim().toLowerCase();
const hex = String(data[r][1] || '').trim();
const textColor = String(data[r][2] || '').trim();
if (name && hex) {
defs[name] = { hex: hex, textColor: textColor || '#ffffff' };
}
}
} catch (e) {
console.warn('[loadColorDefinitions_] Could not load COLOUR_FORMAT_DEFINITIONS:', e.message);
}
return defs;
}
/**
* Resolve a color value — accepts hex (#FFA500) or a named color (Orange).
* Returns { hex, textColor } if a named color is matched, or { hex, textColor: null } for raw hex.
*/
function resolveColor_(value, colorDefs) {
if (!value) return { hex: value, textColor: null };
const v = String(value).trim();
if (v.startsWith('#')) return { hex: v, textColor: null }; // Already hex, no auto text color
const lookup = colorDefs[v.toLowerCase()];
if (lookup) return { hex: lookup.hex, textColor: lookup.textColor }; // Named color found
return { hex: v, textColor: null }; // Unknown — pass through as-is
}
/**
* Fetch App Styles (Primary/Secondary colours from named ranges)
* Reads: PRIMARY_COLOUR, PRIMARY_COLOUR_TEXT, SECONDARY_COLOUR, SECONDARY_COLOUR_TEXT
* Accepts hex values (#FFA500) or named colors (Orange, Teal, Navy, etc.)
* When a named color is used, automatically applies its defined text color unless overridden.
*/
function getAppStyles() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const colorDefs = loadColorDefinitions_();
const styles = {
primaryColor: '#FFA500', // Default orange (matches current brand)
primaryTextColor: '#ffffff',
secondaryColor: '#625b71', // MD3 default secondary
secondaryTextColor: '#ffffff'
};
// Read raw values and keep range references for font color fallback
const rawValues = {};
const rangeRefs = {};
const rangeNames = ['PRIMARY_COLOUR', 'PRIMARY_COLOUR_TEXT', 'SECONDARY_COLOUR', 'SECONDARY_COLOUR_TEXT'];
rangeNames.forEach(rangeName => {
try {
const range = ss.getRangeByName(rangeName);
if (range) {
const val = String(range.getValue() || '').trim();
if (val) {
rawValues[rangeName] = val;
rangeRefs[rangeName] = range;
}
}
} catch (e) {
console.warn('[getAppStyles] Named range ' + rangeName + ' not found, using default.');
}
});
// Resolve PRIMARY_COLOUR (may be a name like "Orange" or hex "#FFA500")
if (rawValues['PRIMARY_COLOUR']) {
const resolved = resolveColor_(rawValues['PRIMARY_COLOUR'], colorDefs);
styles.primaryColor = resolved.hex;
}
// PRIMARY_COLOUR_TEXT logic
if (rawValues['PRIMARY_COLOUR_TEXT'] && rawValues['PRIMARY_COLOUR_TEXT'] !== rawValues['PRIMARY_COLOUR']) {
styles.primaryTextColor = rawValues['PRIMARY_COLOUR_TEXT'];
} else {
// Fallback: If text color is missing OR is identical to background, read from cell font color
try {
if (rangeRefs['PRIMARY_COLOUR']) {
styles.primaryTextColor = rangeRefs['PRIMARY_COLOUR'].getFontColor();
}
} catch (e) {
console.warn('[getAppStyles] Error fetching font color for PRIMARY_COLOUR:', e.message);
}
}
// Resolve SECONDARY_COLOUR
if (rawValues['SECONDARY_COLOUR']) {
const resolved = resolveColor_(rawValues['SECONDARY_COLOUR'], colorDefs);
styles.secondaryColor = resolved.hex;
}
// SECONDARY_COLOUR_TEXT logic
if (rawValues['SECONDARY_COLOUR_TEXT'] && rawValues['SECONDARY_COLOUR_TEXT'] !== rawValues['SECONDARY_COLOUR']) {
styles.secondaryTextColor = rawValues['SECONDARY_COLOUR_TEXT'];
} else {
// Fallback: If text color is missing OR is identical to background, read from cell font color
try {
if (rangeRefs['SECONDARY_COLOUR']) {
styles.secondaryTextColor = rangeRefs['SECONDARY_COLOUR'].getFontColor();
}
} catch (e) {
console.warn('[getAppStyles] Error fetching font color for SECONDARY_COLOUR:', e.message);
}
}
console.log('[getAppStyles] Loaded:', JSON.stringify(styles));
return styles;
}
/**
* Ensure text color has adequate contrast against background.
* If contrast is insufficient, returns white or black based on background luminance.
* @param {string} bgHex - Background color hex (e.g. '#0000FF')
* @param {string} textHex - Text color hex (e.g. '#000000')
* @returns {string} - Validated text color hex
*/
function ensureContrast_(bgHex, textHex) {
if (!bgHex || !textHex) return textHex || '#ffffff';
const toLum = (hex) => {
const h = String(hex).replace('#', '');
if (h.length !== 6) return -1;
const r = parseInt(h.substr(0, 2), 16);
const g = parseInt(h.substr(2, 2), 16);
const b = parseInt(h.substr(4, 2), 16);
return ((r * 299) + (g * 587) + (b * 114)) / 1000;
};
const bgLum = toLum(bgHex);
const txtLum = toLum(textHex);
if (bgLum < 0) return textHex; // Can't parse bg, leave as-is
// Check if contrast is sufficient (difference > 100 on 0-255 scale)
if (txtLum >= 0 && Math.abs(bgLum - txtLum) > 100) {
return textHex; // Contrast is fine
}
// Insufficient contrast — pick white or black based on background
return (bgLum >= 128) ? '#000000' : '#ffffff';
}
/**
* Fetch Category Settings (Colors & Order & SaleStatus)
*/
function getCategorySettings() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName(SHEET_NAMES.SETTINGS);
const settings = {};
if (!sheet) return settings;
const data = sheet.getDataRange().getValues();
const lastRow = data.length;
if (lastRow < 1) return settings;
let headerRowIdx = -1;
let catColIdx = -1;
let bestCatScore = -1;
for (let r = 0; r < data.length; r++) {
for (let c = 0; c < data[r].length; c++) {
const s = String(data[r][c]).toLowerCase().trim();
let score = -1;
if (s === "category name" || s === "cat name") score = 10;
else if (s === "category" || s === "cat") score = 5;
if (score > bestCatScore) {
headerRowIdx = r;
catColIdx = c;
bestCatScore = score;
}
}
if (bestCatScore === 10) break;
}
if (headerRowIdx === -1) return settings;
const headers = data[headerRowIdx];
let colorIdx = -1, saleIdx = -1, orderIdx = -1, textColIdx = -1;
let orderCandidates = [];
headers.forEach((h, i) => {
const head = String(h).trim().toLowerCase();
// IMPORTANT: Check 'text colour' BEFORE generic 'colour' to prevent false match
if (head.includes('text colo') || head.includes('font colo') || head === 'text colour' || head === 'text color') textColIdx = i;
else if (head.includes('color') || head.includes('colour') || head === 'hex') colorIdx = i;
else if (head.includes('sale active') || head.includes('sale status') || head.includes('sale mode')) saleIdx = i;
else if (head.includes('order') || head.includes('sort') || head.includes('display')) orderCandidates.push(i);
});
// Find SECTION column for client access filtering
let sectionIdx = -1;
headers.forEach((h, i) => {
const head = String(h).trim().toLowerCase();
if (head === 'section' || head === 'group' || head === 'access') sectionIdx = i;
});
if (orderCandidates.length > 0) {
let maxScore = -999;
orderCandidates.forEach(idx => {
let score = 0;
for (let r = headerRowIdx + 1; r < Math.min(headerRowIdx + 11, lastRow); r++) {
const val = data[r][idx];
if (typeof val === 'number' && !isNaN(val)) score += 15;
else if (typeof val === 'boolean' || val === true || val === false) score -= 40;
else if (!isNaN(parseInt(val))) score += 5;
}
if (headers[idx].toLowerCase().includes('order') || headers[idx].toLowerCase().includes('sort')) score += 50;
if (headers[idx].toLowerCase().includes('display order')) score += 75;
if (score > maxScore) { maxScore = score; orderIdx = idx; }
});
}
const range = sheet.getRange(headerRowIdx + 1, 1, lastRow - headerRowIdx, sheet.getLastColumn());
const dataSlice = range.getValues();
const backgrounds = range.getBackgrounds();
// PERFORMANCE (Going GAS): Removed getFontColors() — text colour now read from data column
for (let r = 0; r < dataSlice.length; r++) {
const rawCatName = String(dataSlice[r][catColIdx]).trim();
// STOP if name is empty - prevents picking up stray text below the table
if (!rawCatName) break;
if (rawCatName.toLowerCase().includes("category")) continue;
const catKey = superNormalize(rawCatName);
if (!catKey) continue;
let order = 999;
if (orderIdx > -1) {
const rawVal = dataSlice[r][orderIdx];
if (typeof rawVal === 'number') order = rawVal;
else if (rawVal && !isNaN(parseInt(rawVal))) {
const parsed = parseInt(String(rawVal).replace(/[^0-9]/g, ''));
if (!isNaN(parsed)) order = parsed;
}
}
const catColor = colorIdx > -1 ? (String(dataSlice[r][colorIdx] || "").trim() || backgrounds[r][colorIdx]) : "#cccccc";
// Read text colour from dedicated column, auto-contrast fallback
let catText = "";
if (textColIdx > -1) {
catText = String(dataSlice[r][textColIdx] || "").trim();
}
if (!catText && catColor && catColor.startsWith('#')) {
catText = getContrastYIQ(catColor);
}
const catSection = sectionIdx > -1 ? String(dataSlice[r][sectionIdx]).trim().toUpperCase() : "";
settings[catKey] = {
name: rawCatName, // Store original name
color: catColor,
textColor: catText,
order: order,
section: catSection, // A, B, C, D for client filtering
saleActive: saleIdx > -1 ? (dataSlice[r][saleIdx] === true || String(dataSlice[r][saleIdx]).toUpperCase() === 'TRUE') : false
};
}
return settings;
}
/**
* Fetch Default Variations from Settings
* Looks for specific range or keywords in SETTINGS sheet
*/
function getVariationDefaults() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName(SHEET_NAMES.SETTINGS);
const defaults = { var1: "", var2: "", var3: "", var4: "", values: [] };
if (!sheet) return defaults;
const data = sheet.getDataRange().getValues();
// Look for "VARIATION DEFAULTS" section
const startRow = data.findIndex(r => String(r[0]).toUpperCase().includes("VARIATION DEFAULTS"));
if (startRow === -1) return defaults;
// Assume header is at startRow, data follows
// [VARIATION DEFAULTS]
// [Var 1 Name] | [Var 2 Name] | [Var 3 Name] | [Var 4 Name]
// [Value 1] | [Value 2] | [Value 3] | [Value 4]
const headerRow = data[startRow + 1];
if (headerRow) {
defaults.var1 = String(headerRow[0] || "");
defaults.var2 = String(headerRow[1] || "");
defaults.var3 = String(headerRow[2] || "");
defaults.var4 = String(headerRow[3] || "");
}
return defaults;
}
/**
* Fetch Variation Groups from the "Variation Groups and Values" table in SETTINGS.
* Table structure: Group Name | Variation Number | Group Data (Comma Separated List)
* Returns: [{ groupName, variationNumber, values: [...] }, ...]
*/
/**
* Fetch Variation Groups from the "VARIATION_GROUPS_AND_VALUES" named range.
* Range contains: [Title, Header Row, Data Rows...]
* Returns: [{ groupName, variationNumber, values: [...] }, ...]
*/
function getVariationGroups() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const range = ss.getRangeByName('VARIATION_GROUPS_AND_VALUES');
const groups = [];
if (!range) {
console.warn('[getVariationGroups] Named range VARIATION_GROUPS_AND_VALUES not found.');
return groups;
}
const data = range.getValues();
const startRow = range.getRow();
const startCol = range.getColumn();
// Skip the title (index 0) and header (index 1)
for (let i = 2; i < data.length; i++) {
const groupName = String(data[i][0] || '').trim();
if (!groupName) continue; // Skip empty rows within the range
const varNum = parseInt(String(data[i][1] || '1')) || 1;
const rawValues = String(data[i][2] || '').trim();
const values = rawValues
.split(',')
.map(v => v.trim())
.filter(v => v.length > 0);
groups.push({
groupName: groupName,
variationNumber: varNum,
values: values,
_absoluteRow: startRow + i, // 1-indexed sheet row
_absoluteCol: startCol // 1-indexed sheet column
});
}
console.log('[getVariationGroups] Found ' + groups.length + ' groups in named range.');
return groups;
}
/**
* Add a new value to an existing Variation Group in SETTINGS.
*/
function addValueToVariationGroup(groupName, newValue) {
const groups = getVariationGroups();
const group = groups.find(g => g.groupName.toLowerCase() === groupName.toLowerCase());
if (!group) throw new Error('Group "' + groupName + '" not found in VARIATION_GROUPS_AND_VALUES.');
const ss = SpreadsheetApp.getActiveSpreadsheet();
const range = ss.getRangeByName('VARIATION_GROUPS_AND_VALUES');
if (!range) throw new Error('Range not found during update.');
const sheet = range.getSheet();
const existingValues = group.values;
if (existingValues.includes(newValue)) return { success: true };
const updated = existingValues.length > 0 ? existingValues.join(', ') + ', ' + newValue : newValue;
sheet.getRange(group._absoluteRow, group._absoluteCol + 2).setValue(updated);
return { success: true };
}
/**
* Create a new Variation Group in the persistent table.
*/
function createNewVariationGroup(varNum, groupName, valuesString) {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const range = ss.getRangeByName('VARIATION_GROUPS_AND_VALUES');
if (!range) throw new Error('VARIATION_GROUPS_AND_VALUES named range not found.');
const sheet = range.getSheet();
const data = range.getValues();
const startRow = range.getRow();
const startCol = range.getColumn();
// Find the first empty row within or after the range
let insertRow = -1;
for (let i = 2; i < data.length; i++) {
if (!String(data[i][0] || '').trim()) {
insertRow = startRow + i;
break;
}
}
if (insertRow === -1) {
// Append at the bottom of the named range's row sequence
insertRow = startRow + data.length;
}
sheet.getRange(insertRow, startCol, 1, 3).setValues([[groupName, varNum, valuesString]]);
return { success: true, groupName: groupName };
}
/**
* ==========================================
* Header Protection & Recovery System
* ==========================================
*/
/** Sheets to protect - each entry defines how many header rows to back up */
const PROTECTED_SHEETS = {
'CLIENT DATA': { headerRows: 2 }, // Row 1: SECTION_*, Row 2: field headers
'PRODUCTS': { headerRows: 1 },
'ORDERS': { headerRows: 1 },
'SETTINGS': { headerRows: 1 }
};
/**
* Backup all critical sheet headers to Script Properties.
* Call once to set the "golden" snapshot, or re-run to update after intentional changes.
*/
function backupSheetHeaders() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const props = PropertiesService.getScriptProperties();
const backup = {};
const timestamp = new Date().toISOString();
Object.keys(PROTECTED_SHEETS).forEach(sheetName => {
const sheet = ss.getSheetByName(sheetName);
if (!sheet) {
console.warn(`[backupSheetHeaders] Sheet "${sheetName}" not found, skipping.`);
return;
}
const config = PROTECTED_SHEETS[sheetName];
const lastCol = sheet.getLastColumn();
if (lastCol < 1) return;
const headerData = [];
for (let r = 1; r <= config.headerRows; r++) {
const row = sheet.getRange(r, 1, 1, lastCol).getValues()[0];
headerData.push(row.map(v => String(v || "").trim()));
}
backup[sheetName] = {
headers: headerData,
colCount: lastCol,
headerRows: config.headerRows,
timestamp: timestamp
};
});
props.setProperty('HEADER_BACKUP', JSON.stringify(backup));
props.setProperty('HEADER_BACKUP_TIMESTAMP', timestamp);
const count = Object.keys(backup).length;
SpreadsheetApp.getActiveSpreadsheet().toast(
`Backed up headers for ${count} sheets at ${timestamp}`,
'Header Backup', 5
);
console.log('[backupSheetHeaders] Saved backup for:', Object.keys(backup).join(', '));
return { success: true, message: `Backed up ${count} sheets.`, timestamp: timestamp };
}
/**
* Compare current sheet headers against the backup.
* Shows a detailed report as a dialog.
*/
function compareSheetHeaders() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const props = PropertiesService.getScriptProperties();
const backupJson = props.getProperty('HEADER_BACKUP');
if (!backupJson) {
SpreadsheetApp.getUi().alert(
'No Backup Found',
'No header backup exists yet. Run "Backup Sheet Headers" first to create a golden snapshot.',
SpreadsheetApp.getUi().ButtonSet.OK
);
return { success: false, message: 'No backup found.' };
}
const backup = JSON.parse(backupJson);
const backupTimestamp = props.getProperty('HEADER_BACKUP_TIMESTAMP') || 'Unknown';
let report = `HEADER COMPARISON REPORT\nBackup from: ${backupTimestamp}\n${'='.repeat(50)}\n\n`;
let hasChanges = false;
Object.keys(PROTECTED_SHEETS).forEach(sheetName => {
const sheet = ss.getSheetByName(sheetName);
const savedData = backup[sheetName];
if (!sheet && savedData) {
report += `⚠️ SHEET "${sheetName}": MISSING (was backed up)\n\n`;
hasChanges = true;
return;
}
if (!savedData) {
report += `ℹ️ SHEET "${sheetName}": No backup exists for this sheet\n\n`;
return;
}
const config = PROTECTED_SHEETS[sheetName];
const lastCol = sheet.getLastColumn();
const maxCol = Math.max(lastCol, savedData.colCount);
let sheetReport = '';
let sheetHasChanges = false;
for (let r = 0; r < config.headerRows; r++) {
const currentRow = lastCol > 0
? sheet.getRange(r + 1, 1, 1, maxCol).getValues()[0].map(v => String(v || "").trim())
: [];
const savedRow = savedData.headers[r] || [];
// Pad shorter arrays
while (currentRow.length < maxCol) currentRow.push('');
while (savedRow.length < maxCol) savedRow.push('');
for (let c = 0; c < maxCol; c++) {
const saved = savedRow[c] || '';
const current = currentRow[c] || '';
if (saved !== current) {
sheetHasChanges = true;
const colLetter = columnToLetter(c + 1);
if (saved && !current) {
sheetReport += ` 🔴 Row ${r + 1}, Col ${colLetter}: REMOVED "${saved}"\n`;
} else if (!saved && current) {
sheetReport += ` 🟢 Row ${r + 1}, Col ${colLetter}: ADDED "${current}"\n`;
} else {
sheetReport += ` 🟡 Row ${r + 1}, Col ${colLetter}: CHANGED "${saved}" → "${current}"\n`;
}
}
}
// Check if column was moved (exists in both but different position)
savedRow.forEach((savedHeader, savedIdx) => {
if (!savedHeader) return;
const currentIdx = currentRow.indexOf(savedHeader);
if (currentIdx !== -1 && currentIdx !== savedIdx && savedHeader === currentRow[currentIdx]) {
sheetReport += ` ↔️ Row ${r + 1}: "${savedHeader}" moved from Col ${columnToLetter(savedIdx + 1)} → Col ${columnToLetter(currentIdx + 1)}\n`;
sheetHasChanges = true;
}
});
}
if (sheetHasChanges) {
report += `⚠️ SHEET "${sheetName}": Changes detected\n${sheetReport}\n`;
hasChanges = true;
} else {
report += `✅ SHEET "${sheetName}": No changes\n\n`;
}
});
if (!hasChanges) {
report += '\n🎉 All headers match the backup. No changes detected.';
} else {
report += '\n⚠️ Some headers have changed. Use "Reset Sheet Headers" to restore from backup.';
}
// Show report as a scrollable dialog
const htmlReport = HtmlService.createHtmlOutput(
`<pre style="font-family: Consolas, 'Courier New', monospace; font-size: 13px; white-space: pre-wrap; padding: 16px;">${report}</pre>`
).setWidth(600).setHeight(500);
SpreadsheetApp.getUi().showModalDialog(htmlReport, 'Header Comparison Report');
console.log('[compareSheetHeaders] Report generated. Has changes:', hasChanges);
return { success: true, hasChanges: hasChanges, report: report };
}
/**
* Reset sheet headers back to the backed-up golden snapshot.
* Prompts for confirmation before making changes.
*/
function resetSheetHeaders() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const ui = SpreadsheetApp.getUi();
const props = PropertiesService.getScriptProperties();
const backupJson = props.getProperty('HEADER_BACKUP');
if (!backupJson) {
ui.alert(
'No Backup Found',
'No header backup exists yet. Run "Backup Sheet Headers" first.',
ui.ButtonSet.OK
);
return { success: false, message: 'No backup found.' };
}
// Confirm with the user
const confirm = ui.alert(
'Reset Sheet Headers',
'This will restore all header rows to their backed-up state.\n\n' +