-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadmin_logic.html
More file actions
762 lines (683 loc) · 33.4 KB
/
Copy pathadmin_logic.html
File metadata and controls
762 lines (683 loc) · 33.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
<script>
let existingSkus = [];
let baseProducts = [];
let allCatalog = [];
let categories = [];
let headerMap = { labels: {}, indices: {} };
let variationGroups = [];
// Initialize Admin Module
function initAdminModule() {
console.log("Initializing Admin Module...");
// Fetch Categories
google.script.run.withSuccessHandler(cats => {
categories = cats;
const select = document.getElementById('category');
select.innerHTML = '<option value="">Select Category...</option><option value="NEW_CAT">+ Add New Category</option>';
cats.forEach(c => {
const opt = document.createElement('option');
opt.value = c.name;
opt.textContent = c.name;
select.appendChild(opt);
});
}).getCategoryData();
// Fetch Variation Defaults
google.script.run.withSuccessHandler(defaults => {
if (defaults.var1) document.getElementById('var1Name').value = defaults.var1;
if (defaults.var2) document.getElementById('var2Name').value = defaults.var2;
if (defaults.var3) document.getElementById('var3Name').value = defaults.var3;
if (defaults.var4) document.getElementById('var4Name').value = defaults.var4;
}).getVariationDefaults();
// Fetch Header Map First for Dynamic Labels
google.script.run.withSuccessHandler(map => {
headerMap = map;
updateLabels();
}).getProductHeaderMap();
google.script.run.withSuccessHandler(products => {
allCatalog = products;
existingSkus = products.map(p => p.sku);
const map = new Map();
products.forEach(p => {
if (!map.has(p.name)) {
map.set(p.name, p);
}
});
baseProducts = Array.from(map.values()).sort((a, b) => a.name.localeCompare(b.name));
const select = document.getElementById('existingProduct');
select.innerHTML = '<option value="">Select a Base Product...</option>';
baseProducts.forEach(p => {
const opt = document.createElement('option');
opt.value = p.name;
opt.textContent = p.name;
select.appendChild(opt);
});
}).getProductCatalog();
// Fetch Variation Groups from SETTINGS
google.script.run.withSuccessHandler(groups => {
variationGroups = groups || [];
populateVarNameDropdowns();
}).getVariationGroups();
// Load Order Form Templates into the template selector
google.script.run.withSuccessHandler(templates => {
const sel = document.getElementById('orderFormNumber');
if (!sel || !templates || templates.length === 0) return;
sel.innerHTML = '';
templates.forEach(t => {
const opt = document.createElement('option');
opt.value = t.formNum;
opt.textContent = t.label;
sel.appendChild(opt);
});
}).getOrderFormTemplates();
// Auto-derive Reference Character from SKU (strip spaces and hyphens)
const skuInput = document.getElementById('baseSku');
if (skuInput) {
skuInput.addEventListener('input', () => {
const ref = skuInput.value.replace(/[\s\-]/g, '');
document.getElementById('baseRef').value = ref;
});
}
// Default to Single Entry Mode
addVariationRow();
}
function generateBulkRows() {
// Collect checked variation values into hidden textareas first
applySelectedVarGroups();
const list1 = document.getElementById('bulkVar1List').value.split('\n').map(s => s.trim()).filter(s => s);
const list2 = document.getElementById('bulkVar2List').value.split('\n').map(s => s.trim()).filter(s => s);
const genSingle = document.getElementById('formatAEnabled').checked;
const genCase = document.getElementById('formatBEnabled').checked;
const masterPrice = parseFloat(document.getElementById('masterPrice').value) || 0;
const masterSalePriceRaw = document.getElementById('masterSalePrice').value;
const masterSalePrice = masterSalePriceRaw !== '' ? parseFloat(masterSalePriceRaw) : null;
// Format A Settings
const fmtAName = document.getElementById('formatAName').value || "Single";
const fmtAUnits = parseFloat(document.getElementById('formatAUnits').value) || 1;
// Format B Settings
const fmtBName = document.getElementById('formatBName').value || "Carton";
const fmtBUnitsRaw = document.getElementById('formatBUnits').value;
const fmtBUnits = fmtBUnitsRaw ? parseFloat(fmtBUnitsRaw) : 0; // Default to 0 or handle validation below
const list = document.getElementById('variationList');
// list.innerHTML = ""; // Don't clear? User might want to append.
// Logic says "list.innerHTML = """ in Step 2656. Yes, clear it.
list.innerHTML = "";
if (list1.length === 0) {
alert("Please enter at least one Variation 1 (e.g. Flavor).");
return;
}
if (genCase && (isNaN(fmtBUnits) || fmtBUnits <= 1)) {
alert("Please enter a valid 'Units per Case' (greater than 1) for the Carton/Case format.");
return;
}
const baseSku = document.getElementById('baseSku').value.trim();
const baseImage = document.getElementById('imageUrl').value.trim();
const baseDesc = document.getElementById('description').value.trim(); // Get base description
let skuCounter = 1;
// Helper to add row
const addRow = (v1, v2, v3, v4, price, units, salePrice) => {
let sku = "";
if (baseSku) {
sku = baseSku + "-" + String(skuCounter).padStart(2, '0');
skuCounter++;
}
addVariationRow({
variation: v1,
variation2: v2,
variation3: v3,
variation4: v4,
price: price,
salePrice: salePrice !== null ? Number(salePrice).toFixed(2) : '',
unitsPerCase: units,
image: baseImage,
description: baseDesc,
inventory: "instock",
sku: sku
});
};
list1.forEach(v1 => {
// If List 2 exists, iterate. Else just use v1.
const loop2 = list2.length > 0 ? list2 : [null];
loop2.forEach(v2 => {
// Generate Format A (e.g. Single)
if (genSingle) {
let price = (masterPrice * fmtAUnits).toFixed(2);
let sp = masterSalePrice !== null ? masterSalePrice * fmtAUnits : null;
addRow(v1, v2, fmtAName, fmtAUnits, price, fmtAUnits, sp);
}
// Generate Format B (e.g. Case)
if (genCase) {
let price = (masterPrice * fmtBUnits).toFixed(2);
let sp = masterSalePrice !== null ? masterSalePrice * fmtBUnits : null;
addRow(v1, v2, fmtBName, fmtBUnits, price, fmtBUnits, sp);
}
});
});
alert(`Generated rows! Please review before submitting.`);
}
function toggleMode() {
const mode = document.querySelector('input[name="mode"]:checked').value;
const selectWrapper = document.getElementById('existingSelectWrapper');
const addForm = document.getElementById('addFormSection');
const deleteSection = document.getElementById('deleteSection');
const bulkSection = document.getElementById('bulkGeneratorSection');
const addCustomerSection = document.getElementById('addCustomerSection');
const list = document.getElementById('variationList');
const submitBtn = document.getElementById('submitBtn');
const baseNameInput = document.getElementById('baseName');
document.getElementById('msg').textContent = "";
// Default visibility
selectWrapper.style.display = 'none';
addForm.style.display = 'block';
deleteSection.style.display = 'none';
bulkSection.style.display = 'none';
addCustomerSection.style.display = 'none';
baseNameInput.readOnly = false;
baseNameInput.style.backgroundColor = "white";
if (mode === 'new') {
list.innerHTML = "";
addVariationRow();
bulkSection.style.display = 'block';
submitBtn.textContent = "Submit Products";
}
else if (mode === 'bulk') {
list.innerHTML = "";
bulkSection.style.display = 'block';
submitBtn.textContent = "Submit Bulk Products";
}
else if (mode === 'existing') {
selectWrapper.style.display = 'block';
baseNameInput.readOnly = true;
baseNameInput.style.backgroundColor = "#f0f0f0";
onExistingProductChange();
submitBtn.textContent = "Add Variations";
}
else if (mode === 'edit') {
selectWrapper.style.display = 'block';
onExistingProductChange();
submitBtn.textContent = "Save Changes";
}
else if (mode === 'delete') {
addForm.style.display = 'none';
selectWrapper.style.display = 'block';
deleteSection.style.display = 'block';
onExistingProductChange();
}
else if (mode === 'addcustomer') {
addForm.style.display = 'none';
addCustomerSection.style.display = 'block';
loadClientTypes();
loadSectionNames();
}
}
// ... [Include standard functions like addVariationRow, submitForm, onCategorySelectChange] ...
// To save space and duplicates, I will adapt these from the sidebar logic but minimalize dependencies.
function addVariationRow(data) {
data = data || {};
const list = document.getElementById('variationList');
const id = 'row_' + Date.now() + '_' + Math.random().toString(36).substr(2, 5);
const div = document.createElement('div');
div.className = 'variation-card fade-in';
div.id = id;
let html = `
<div class="variation-header">
<span>Variation Row</span>
<button class="icon-btn" onclick="removeRow('${id}')">
<span class="material-symbols-outlined">close</span>
</button>
</div>
<div class="variation-grid">
<div class="md3-input-wrapper compact-input">
<label>Variation 1 (${document.getElementById('var1Name').value || 'Flavor'})</label>
<input type="text" class="v1" value="${data.variation || ''}" placeholder=" ">
</div>
<div class="md3-input-wrapper compact-input">
<label>Variation 2 (${document.getElementById('var2Name').value || 'Strength'})</label>
<input type="text" class="v2" value="${data.variation2 || ''}" placeholder=" ">
</div>
<div class="md3-input-wrapper compact-input">
<label>Format</label>
<select class="v3" onchange="onFormatChange(this)">
<option value="Single" ${(data.variation3 === 'Single' || !data.variation3) ? 'selected' : ''}>Single</option>
<option value="Carton" ${data.variation3 === 'Carton' ? 'selected' : ''}>Carton</option>
<option value="Box" ${data.variation3 === 'Box' ? 'selected' : ''}>Box</option>
</select>
</div>
<div class="md3-input-wrapper compact-input units-wrapper" style="display: ${data.variation3 === 'Single' ? 'none' : 'block'};">
<label>Units</label>
<input type="number" class="v4" value="${data.unitsPerCase || data.variation4 || 1}" placeholder="1">
</div>
<div class="md3-input-wrapper compact-input price-wrapper">
<label>Price ($)</label>
<input type="number" class="price" value="${data.price || ''}" step="0.01" placeholder="0.00">
</div>
<div class="md3-input-wrapper compact-input">
<label>Sale Price ($)</label>
<input type="number" class="salePrice" value="${data.salePrice || ''}" step="0.01" placeholder="0.00">
</div>
<div class="md3-input-wrapper compact-input">
<label>Image URL</label>
<input type="text" class="variationImage" value="${data.image || ''}" placeholder="Individual URL">
</div>
<div class="md3-input-wrapper compact-input">
<label>Description</label>
<input type="text" class="variationDescription" value="${data.description || ''}" placeholder="Individual Description">
</div>
<div class="md3-input-wrapper compact-input">
<label>Inventory</label>
<input type="text" class="inventory" value="${data.inventory || 'instock'}" placeholder="e.g. instock">
</div>
<div class="md3-input-wrapper compact-input">
<label>SKU (Auto if empty)</label>
<input type="text" class="sku" value="${data.sku || ''}" placeholder="LEAVE EMPTY TO AUTO-GEN">
</div>
</div>
`;
div.innerHTML = html;
list.appendChild(div);
}
function removeRow(id) {
const el = document.getElementById(id);
if (el) el.remove();
}
function onFormatChange(select) {
const row = select.closest('.variation-card');
const unitsWrapper = row.querySelector('.units-wrapper');
const val = select.value;
if (val === 'Single') {
unitsWrapper.style.display = 'none';
// Reset units to 1 if single?
row.querySelector('.v4').value = "1";
} else {
unitsWrapper.style.display = 'block';
// Default to master units if available
// REFACTOR: Removed "masterUnits" fallback.
// If checking "Box" or "Carton", user must specify units if not already.
const current = row.querySelector('.v4').value;
if (!current || current == "1") {
// Optional: Set a flag or placeholder? Just leave as is.
}
}
}
function submitForm() {
// Collect Data
const brand = document.getElementById('brand').value;
const name = document.getElementById('baseName').value;
const category = document.getElementById('category').value;
const ref = document.getElementById('baseRef').value;
const baseSku = document.getElementById('baseSku').value;
// Basic Validation
if (!name || !category || !ref || !baseSku) {
document.getElementById('msg').textContent = "Base Name, Category, Ref, and Base SKU are required.";
return;
}
const rows = document.querySelectorAll('.variation-card');
if (rows.length === 0) {
document.getElementById('msg').textContent = "Please add at least one variation.";
return;
}
const payload = [];
const commissionRate = document.getElementById('commissionRate') ? document.getElementById('commissionRate').value : '';
rows.forEach(row => {
const v1 = row.querySelector('.v1').value;
const v2 = row.querySelector('.v2').value;
const v3 = row.querySelector('.v3').value; // Format
const v4 = row.querySelector('.v4').value; // Units
const price = row.querySelector('.price').value;
const salePrice = row.querySelector('.salePrice') ? row.querySelector('.salePrice').value : '';
const rowImage = row.querySelector('.variationImage').value;
const rowDesc = row.querySelector('.variationDescription').value;
const rowInventory = row.querySelector('.inventory').value.trim() || 'instock'; // New Field
const skuOverride = row.querySelector('.sku').value;
// Construct SKU if empty
// Format: [REF]-[BaseSKU]-[VAR]-[FORMAT]-[UNITS] ??
// Current system seems to use manual or generated SKUs.
// Let's rely on backend if empty, OR generate a temp one.
// User usually enters Base SKU part.
if (v1 && price) {
payload.push({
brand, name, category, ref, baseSku,
orderFormNumber: document.getElementById('orderFormNumber').value || '1',
// Pass Metadata for Parent Row creation
var1Name: document.getElementById('var1Name').value,
var2Name: document.getElementById('var2Name').value,
var3Name: document.getElementById('var3Name').value,
var4Name: document.getElementById('var4Name').value,
backgroundColor: document.getElementById('baseColor').value, // Color Name/Hex
textColor: document.getElementById('baseTextColor').value, // Text Colour (blank = auto)
description: rowDesc || document.getElementById('description').value, // Row description takes priority
image: rowImage || document.getElementById('imageUrl').value, // Row image takes priority, then fallback to base
variation: v1,
variation2: v2,
variation3: v3,
variation4: v4,
price: price,
salePrice: salePrice,
commissionRate: commissionRate,
unitsPerCase: (v3 === 'Single') ? 1 : v4,
inventory: rowInventory,
sku: skuOverride
});
}
});
// Send to Backend
const btn = document.getElementById('submitBtn');
btn.textContent = "Processing...";
btn.disabled = true;
google.script.run
.withSuccessHandler(res => {
btn.disabled = false;
btn.textContent = "Submit Products";
if (res.success) {
alert("Success! Added " + res.count + " products.");
// Clear form or reset
toggleMode(); // Reset
} else {
document.getElementById('msg').textContent = "Error: " + res.message;
}
})
.withFailureHandler(e => {
btn.disabled = false;
btn.textContent = "Submit Products";
document.getElementById('msg').textContent = "System Error: " + e.message;
})
.addProductBatch(payload); // Corrected function name
}
// Helper: updateLabels, onExistingProductChange (simplified)
function updateLabels() {
const labels = headerMap.labels;
if (labels.name) document.getElementById('lbl_name').textContent = labels.name;
// ... mapped labels ...
}
// Stub for onExistingProductChange - implement full logic if needed
// For now, focusing on Bulk/New mode as per request.
function onExistingProductChange() {
// ... (Similar logic to sidebar, identifying parent/child) ...
// Logic to populate form from existing product
const name = document.getElementById('existingProduct').value;
const products = allCatalog.filter(p => p.name === name);
if (products.length > 0) {
const parent = products.find(p => p.isParent) || products[0];
document.getElementById('brand').value = parent.brand || "";
document.getElementById('baseName').value = parent.name;
document.getElementById('category').value = parent.category;
document.getElementById('baseRef').value = parent.ref || "";
// ... populate rest ...
}
}
function onCategorySelectChange() {
// ... existing logic ...
}
/**
* Load Client Types from the CLIENT_TYPES named range into the dropdown.
*/
let _clientTypesLoaded = false;
function loadClientTypes() {
const select = document.getElementById('newClientType');
if (!select) return;
if (_clientTypesLoaded) return;
select.innerHTML = '<option value="">Loading...</option>';
select.disabled = true;
google.script.run
.withSuccessHandler(types => {
select.disabled = false;
if (types && types.length > 0) {
select.innerHTML = '<option value="">Select Type...</option>';
types.forEach(type => {
const opt = document.createElement('option');
opt.value = type;
opt.textContent = type;
select.appendChild(opt);
});
_clientTypesLoaded = true;
} else {
// Named Range is empty or missing — show clear warning
select.innerHTML = '<option value="">⚠ CLIENT_TYPES range is empty</option>';
_clientTypesLoaded = false; // allow retry
console.warn('[loadClientTypes] CLIENT_TYPES named range returned empty. Check the SETTINGS sheet.');
}
})
.withFailureHandler(err => {
select.disabled = false;
select.innerHTML = '<option value="">⚠ Failed to load types</option>';
_clientTypesLoaded = false;
console.error('[loadClientTypes] Error:', err);
})
.getClientTypes();
}
/**
* Load Section Names from named ranges SECTION_A-D into checkbox labels
*/
let sectionNamesLoaded = false;
function loadSectionNames() {
if (sectionNamesLoaded) return;
google.script.run
.withSuccessHandler(sections => {
sectionNamesLoaded = true;
sections.forEach(sec => {
const label = document.getElementById('section' + sec.key + 'Label');
if (label) label.textContent = sec.name;
const wrapper = label ? label.closest('.md3-checkbox-wrapper') : null;
if (wrapper) wrapper.title = sec.name;
});
})
.withFailureHandler(err => {
console.error('[loadSectionNames] Error:', err);
})
.getSectionNames();
}
/**
* Submit New Client to the CLIENT DATA sheet
*/
function submitNewClient() {
const msgEl = document.getElementById('msg');
msgEl.textContent = '';
const clientId = document.getElementById('newClientId').value.trim();
const companyName = document.getElementById('newCompanyName').value.trim();
const type = document.getElementById('newClientType').value;
const phone = document.getElementById('newClientPhone').value.trim();
const manager = document.getElementById('newClientManager').value.trim();
// Compose address from multiple fields
const street = document.getElementById('newAddrStreet').value.trim();
const city = document.getElementById('newAddrCity').value.trim();
const province = document.getElementById('newAddrProvince').value.trim();
const postal = document.getElementById('newAddrPostal').value.trim();
// Build address string: "Street, City, Province Postal"
let addressParts = [];
if (street) addressParts.push(street);
if (city) addressParts.push(city);
let provPostal = '';
if (province && postal) provPostal = province + ' ' + postal;
else if (province) provPostal = province;
else if (postal) provPostal = postal;
if (provPostal) addressParts.push(provPostal);
const address = addressParts.join(', ');
// Validate
if (!clientId) {
msgEl.textContent = 'Client ID is required.';
msgEl.style.color = '#B00020';
return;
}
if (!companyName) {
msgEl.textContent = 'Company Name is required.';
msgEl.style.color = '#B00020';
return;
}
const btn = document.getElementById('submitClientBtn');
btn.disabled = true;
btn.textContent = 'Saving...';
google.script.run
.withSuccessHandler(result => {
btn.disabled = false;
btn.innerHTML = '<span class="material-symbols-outlined" style="margin-right:8px;">person_add</span> Add Customer';
if (result.success) {
msgEl.textContent = result.message;
msgEl.style.color = '#006c4c';
// Clear form
document.getElementById('newClientId').value = '';
document.getElementById('newCompanyName').value = '';
document.getElementById('newClientType').value = '';
document.getElementById('newClientPhone').value = '';
document.getElementById('newClientManager').value = '';
document.getElementById('newAddrStreet').value = '';
document.getElementById('newAddrCity').value = '';
document.getElementById('newAddrProvince').value = '';
document.getElementById('newAddrPostal').value = '';
// Reset section checkboxes to checked (default)
document.getElementById('newSectionA').checked = true;
document.getElementById('newSectionB').checked = true;
document.getElementById('newSectionC').checked = true;
document.getElementById('newSectionD').checked = true;
} else {
msgEl.textContent = result.message;
msgEl.style.color = '#B00020';
}
})
.withFailureHandler(err => {
btn.disabled = false;
btn.innerHTML = '<span class="material-symbols-outlined" style="margin-right:8px;">person_add</span> Add Customer';
msgEl.textContent = 'Error: ' + (err.message || err);
msgEl.style.color = '#B00020';
})
.addNewClient({
clientId: clientId,
companyName: companyName,
type: type,
phone: phone,
manager: manager,
address: address,
sections: {
A: document.getElementById('newSectionA').checked,
B: document.getElementById('newSectionB').checked,
C: document.getElementById('newSectionC').checked,
D: document.getElementById('newSectionD').checked
}
});
}
/**
* Populate the Variation 1/2 Name dropdowns from loaded groups
*/
function populateVarNameDropdowns() {
[1, 2].forEach(slot => {
const select = document.getElementById('var' + slot + 'Name');
if (!select) return;
// Keep the first option, clear the rest
select.length = 1;
// Filter by variation number (or include if varNum is missing/1 for Slot 1)
const filtered = variationGroups.filter(group => {
const varNum = group.variationNumber || 1;
return varNum === slot;
});
filtered.forEach(group => {
const opt = document.createElement('option');
opt.value = group.groupName;
opt.textContent = group.groupName;
select.appendChild(opt);
});
// Add "Other" option
const otherOpt = document.createElement('option');
otherOpt.value = 'OTHER_GROUP';
otherOpt.textContent = '+ Other (New Group)';
select.appendChild(otherOpt);
});
}
/**
* When a variation group is selected from the dropdown,
* render individual value checkboxes + Select All + Other input
*/
function onVarNameSelect(slot) {
const select = document.getElementById('var' + slot + 'Name');
const container = document.getElementById('varSlot' + slot + 'Checks');
if (!container) return;
container.innerHTML = '';
const groupName = select.value;
if (!groupName) return;
if (groupName === 'OTHER_GROUP') {
// New Group UI
container.innerHTML = `
<div style="width:100%; border:1px dashed #ccc; padding:12px; border-radius:8px; background: rgba(0,0,0,0.02);">
<div class="md3-input-wrapper compact-input">
<label>New Group Name (e.g. Strength)</label>
<input type="text" id="newGroupNameSlot_${slot}" placeholder=" ">
</div>
<div class="md3-input-wrapper compact-input" style="margin-bottom:0;">
<label>Initial Values (one per line)</label>
<textarea id="newGroupValuesSlot_${slot}" rows="3" placeholder="50mg\n100mg\n200mg" style="font-size:12px;"></textarea>
</div>
<p style="font-size:10px; color:#666; margin-top:8px;">* This new group will be saved to your Variations Table.</p>
</div>
`;
return;
}
// Find the group
const group = variationGroups.find(g => g.groupName === groupName);
if (!group) return;
// Render Textarea for values instead of checkboxes
const existingValuesString = group.values.join('\n');
container.innerHTML = `
<div class="md3-input-wrapper" style="width:100%;">
<label style="font-size:11px; color: var(--md-sys-color-primary);">VARIATION VALUES (ONE PER LINE)</label>
<textarea id="slotTextarea_${slot}" rows="5" placeholder="Enter values..." style="font-size:13px;">${existingValuesString}</textarea>
<p style="font-size:10px; color: var(--md-sys-color-on-surface-variant); margin-top:4px;">
* Values entered here will be used for generation but won't bloat your spreadsheet.
</p>
</div>
`;
}
/**
* Toggle all checkboxes in a variation slot
*/
function toggleSlotAll(slot) {
const selectAll = document.getElementById('slotAll_' + slot);
const checkboxes = document.querySelectorAll('.slotVal_' + slot);
checkboxes.forEach(cb => cb.checked = selectAll.checked);
}
/**
* Collect checked variation values from slot checkboxes,
* populate hidden textareas. Handle "Other" auto-save.
* Called automatically before generateBulkRows().
*/
function applySelectedVarGroups() {
[1, 2].forEach(slot => {
const textarea = document.getElementById('bulkVar' + slot + 'List');
if (textarea) textarea.value = '';
const select = document.getElementById('var' + slot + 'Name');
let groupName = select ? select.value : '';
if (!groupName) return;
const checked = [];
// Case A: User selected "Other" as a group name (creating new group)
if (groupName === 'OTHER_GROUP') {
const newName = document.getElementById('newGroupNameSlot_' + slot).value.trim();
const newValuesRaw = document.getElementById('newGroupValuesSlot_' + slot).value.trim();
if (newName) {
// Support both command and newline separated for the new group creation
const valueList = newValuesRaw.split(/[\n,]/).map(v => v.trim()).filter(v => v);
checked.push(...valueList);
// Call backend to create this group persistently (comma separated for sheet)
google.script.run
.withSuccessHandler(res => {
console.log('Successfully created persistent group:', res.groupName);
variationGroups.push({
groupName: newName,
variationNumber: slot,
values: valueList
});
})
.withFailureHandler(err => console.error('Failed to create variation group:', err))
.createNewVariationGroup(slot, newName, valueList.join(', '));
}
}
// Case B: User selected an existing group
else {
const textareaSlot = document.getElementById('slotTextarea_' + slot);
if (textareaSlot) {
// Use newlines as primary separator as requested
const values = textareaSlot.value.split('\n').map(v => v.trim()).filter(v => v);
checked.push(...values);
}
}
// Populate hidden textarea (used by generation logic)
if (textarea && checked.length > 0) {
textarea.value = checked.join('\n');
}
});
}
</script>