-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOrderFormPDFService.js
More file actions
1575 lines (1379 loc) · 70.7 KB
/
Copy pathOrderFormPDFService.js
File metadata and controls
1575 lines (1379 loc) · 70.7 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
/**
* OrderFormPDFService.gs
*
* Generates ORDER_FORM_1-style PDFs via two paths:
*
* PATH A — Sheet Export (ORDERS sheet trigger):
* Reads ORDER_FORM_1 template dynamically → writes aggregated quantities
* into the live sheet → exports the sheet as a native Google Sheets PDF
* (preserves all real formatting, merged cells, colors) → clears values.
*
* PATH B — HTML PDF (web form auto-generate on submit):
* Same aggregation logic, but renders an HTML document that mirrors the
* ORDER_FORM_1 layout, converted to PDF without touching the sheet.
*
* Both paths share readOrderFormTemplate() and aggregateOrderByRef() so any
* structural change to ORDER_FORM_1 is automatically reflected in output.
*
* Version: v0.9.19
*/
// ============================================================================
// SHARED: TEMPLATE READER
// ============================================================================
/**
* Reads the live ORDER_FORM_1 sheet structure every time it is called.
* Detects header positions (Singles, MC, Total, Ref) dynamically so the
* output automatically adapts if columns are added, moved, or renamed.
*
* @returns {Object|null} Template descriptor:
* {
* sheet, // Sheet object
* headerRow, // 0-based index of the header row
* refCol, // 0-based col index for the Ref/short-code column
* labelCol, // 0-based col index for the product name column
* formatCol, // 0-based col index for format (may be -1)
* priceCol, // 0-based col index for Price/Unit (may be -1)
* mcPriceCol, // 0-based col index for MC/case price (may be -1)
* singlesCol, // 0-based col index for Singles quantity
* mcCol, // 0-based col index for MC quantity
* totalCol, // 0-based col index for Total quantity
* lastCol, // total columns in sheet
* rows: [ // one entry per data row below the header
* {
* type, // 'category' | 'product' | 'blank'
* sheetRowNum, // 1-based sheet row number (for Range writes)
* ref, // e.g. 'FRR' (product rows only)
* label, // product name text
* format, // format text (e.g. '8-pack')
* price, // price text (e.g. '$36/pack')
* mcPrice, // MC price text (e.g. '$350/MC (10)')
* bgColor, // hex background (category rows)
* }
* ]
* }
*/
/**
* Returns the row-matching mode for a given form number.
* Reads SETTINGS key FORM_1_LOOKUP, FORM_2_LOOKUP, etc.
* Valid values: "REF" (default) or "SKU"
*/
function getFormLookupMode(formNum) {
try {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('SETTINGS');
if (!sheet) return 'REF';
const data = sheet.getDataRange().getValues();
const key = ('FORM_' + formNum + '_LOOKUP').toUpperCase();
for (let i = 0; i < data.length; i++) {
if (String(data[i][0] || '').trim().toUpperCase() === key) {
const val = String(data[i][1] || '').trim().toUpperCase();
return (val === 'SKU' || val === 'REF') ? val : 'REF';
}
}
} catch (e) {
Logger.log('getFormLookupMode error: ' + e.message);
}
return 'REF'; // safe default
}
function readOrderFormTemplate(sheetName) {
sheetName = sheetName || 'ORDER_FORM_1';
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName(sheetName);
if (!sheet) throw new Error('Sheet "' + sheetName + '" not found.');
const lastRow = sheet.getLastRow();
const lastCol = sheet.getLastColumn();
if (lastRow < 2 || lastCol < 2) return null;
const allValues = sheet.getRange(1, 1, lastRow, lastCol).getValues();
const allBg = sheet.getRange(1, 1, lastRow, lastCol).getBackgrounds();
// ── Find header row ────────────────────────────────────────────────────────
// Scan up to row 10 for the row that contains "Singles", "MC" / "Multi",
// and "Total" keywords.
let headerRow = -1;
let singlesCol = -1;
let mcCol = -1;
let totalCol = -1;
for (let r = 0; r < Math.min(10, lastRow); r++) {
const row = allValues[r];
let hits = 0;
for (let c = 0; c < row.length; c++) {
const cell = String(row[c] || '').trim().toLowerCase();
if (cell === 'singles' || cell === 'single') { singlesCol = c; hits++; }
else if (cell === 'mc' || cell.startsWith('multi') || cell === 'case') { mcCol = c; hits++; }
else if (cell === 'total') { totalCol = c; hits++; }
// Also accept pure Quantity column (ORDER_FORM_2 style: Brand | $/Case | Quantity | Total)
else if (cell === 'quantity' || cell === 'qty') { if (mcCol === -1) mcCol = c; hits++; }
}
// Need at least: (Singles OR Quantity/MC) + Total, OR all three classic columns
if (hits >= 2 && totalCol > -1) { headerRow = r; break; }
}
if (headerRow === -1) throw new Error(
`Order form header not found in sheet "${sheetName}". ` +
'Ensure it has columns labelled "Singles" (or "Quantity") and "Total".'
);
// ── Detect other column positions from header row ─────────────────────────
const headerRowData = allValues[headerRow];
let refCol = -1;
let labelCol = -1;
let formatCol = -1;
let priceCol = -1;
let mcPriceCol = -1;
for (let c = 0; c < headerRowData.length; c++) {
const cell = String(headerRowData[c] || '').trim().toLowerCase();
if (c === singlesCol || c === mcCol || c === totalCol) continue;
if (cell === 'ref' || cell === 'ref #' || cell === 'code') refCol = c;
else if (cell.includes('product') || cell.includes('name') || cell.includes('item')) labelCol = c;
else if (cell.includes('format') || cell.includes('pack') || cell.includes('size')) formatCol = c;
else if (cell.includes('price') && !cell.includes('mc')) priceCol = c;
else if (cell.includes('mc') && cell.includes('price')) mcPriceCol = c;
}
// Fallback positional guesses when header labels are absent/different
// Typical layout: A=blank/inv, B=Ref, C=Name, D=Format, E=Price, F=MCPrice, G=Singles, H=MC, I=Total
if (refCol === -1) refCol = 1; // Column B
if (labelCol === -1) labelCol = 2; // Column C
// For format and price: scan between labelCol+1 and singlesCol
if (formatCol === -1 || priceCol === -1) {
for (let c = labelCol + 1; c < singlesCol && c < headerRowData.length; c++) {
if (c === formatCol || c === priceCol || c === mcPriceCol) continue;
const cell = String(headerRowData[c] || '').trim().toLowerCase();
if (cell.includes('price') || cell.includes('unit')) {
if (priceCol === -1) priceCol = c;
else if (mcPriceCol === -1) mcPriceCol = c;
} else {
if (formatCol === -1) formatCol = c;
}
}
}
// ── Parse data rows ────────────────────────────────────────────────────────
const rows = [];
// Helper: true if a hex color is a low-saturation grey (not a real category color)
const _isGrey = (hex) => {
try {
const h = hex.replace('#', '');
const r = parseInt(h.substr(0, 2), 16);
const g = parseInt(h.substr(2, 2), 16);
const b = parseInt(h.substr(4, 2), 16);
const max = Math.max(r, g, b), min = Math.min(r, g, b);
return max === 0 ? true : (max - min) / max < 0.15; // saturation < 15%
} catch (e) { return true; }
};
for (let r = headerRow + 1; r < lastRow; r++) {
const rowData = allValues[r];
const sheetRowNum = r + 1; // 1-based
// Determine row background — scan all cells, skip greys, prefer saturated colours
let rowBg = '#ffffff';
for (let c = 0; c < Math.min(lastCol, lastCol); c++) {
const bg = String(allBg[r][c] || '').toLowerCase();
if (!bg || bg === '#ffffff' || bg === '#000000') continue;
if (_isGrey(bg)) continue; // skip near-grey cells (e.g. #f3f3f3 in ref column)
rowBg = bg;
break;
}
const refVal = String(rowData[refCol] || '').trim();
const labelVal = String(rowData[labelCol] || '').trim();
// Blank row
const rowHasContent = rowData.some(c => String(c || '').trim() !== '');
if (!rowHasContent) {
rows.push({ type: 'blank', sheetRowNum });
continue;
}
// Category header: coloured background AND no ref code
if (rowBg !== '#ffffff' && !refVal) {
// Use only the most prominent cell text (label col or first non-empty)
const categoryLabel = labelVal ||
rowData.map(c => String(c || '').trim()).filter(c => c)[0] || '';
rows.push({ type: 'category', sheetRowNum, label: categoryLabel, bgColor: rowBg });
// ── STOP after "Shipping" row — everything below is secondary table / totals
if (categoryLabel.toLowerCase().includes('shipping')) break;
continue;
}
// Product row (has a ref code)
if (refVal) {
const formatVal = formatCol > -1 ? String(rowData[formatCol] || '').trim() : '';
const priceVal = priceCol > -1 ? String(rowData[priceCol] || '').trim() : '';
const mcPriceVal = mcPriceCol > -1 ? String(rowData[mcPriceCol] || '').trim() : '';
rows.push({
type: 'product',
sheetRowNum,
ref: refVal.toUpperCase(),
colA: String(rowData[0] || '').trim().toUpperCase(), // raw col-A value for SKU fallback
label: labelVal,
format: formatVal,
price: priceVal,
mcPrice: mcPriceVal,
bgColor: rowBg,
singlesQty: 0,
mcQty: 0,
totalQty: 0,
});
continue;
}
// Catch-all: non-blank row with no ref (e.g. sub-header text, notes)
const anyText = labelVal ||
rowData.map(c => String(c || '').trim()).filter(c => c)[0] || '';
if (anyText) {
rows.push({ type: 'category', sheetRowNum, label: anyText, bgColor: rowBg });
}
}
return {
sheet,
headerRow,
headerRowNum: headerRow + 1, // 1-based, used to skip during grand-total scan
refCol, labelCol, formatCol, priceCol, mcPriceCol,
singlesCol, mcCol, totalCol,
lastCol,
rows,
};
}
// ============================================================================
// SHARED: ORDER AGGREGATION
// ============================================================================
/**
* Aggregates ordered items by ref code, splitting single-unit products
* from multi-pack/case products using the product model's `hasCase` flag.
*
* @param {Array} orderItems [{sku, quantity, price, onSale}]
* @param {Array} catalog Full product catalog from getProductCatalog()
* @returns {Object}
* {
* byForm: {
* [formNumber]: { // e.g. "1", "2"
* byRef: { [refCode]: { singlesQty, mcQty, totalPrice, items[] } },
* itemizedDetail: [{ ref, sku, name, variation, quantity, isCase }]
* }
* }
* }
*/
function aggregateOrderByRef(orderItems, catalog) {
// byForm[formNumber] = { byRef: {...}, itemizedDetail: [...] }
const byForm = {};
const _ensureForm = (num) => {
if (!byForm[num]) byForm[num] = { byRef: {}, bySku: {}, itemizedDetail: [] };
};
const _ensureRef = (form, ref) => {
if (!form.byRef[ref]) form.byRef[ref] = { singlesQty: 0, mcQty: 0, totalPrice: 0, items: [] };
};
const _ensureSku = (form, sku) => {
if (!form.bySku[sku]) form.bySku[sku] = { singlesQty: 0, mcQty: 0, totalPrice: 0 };
};
(orderItems || []).forEach(item => {
const qty = parseInt(item.quantity) || 0;
if (qty <= 0) return;
const skuUpper = String(item.sku || '').trim().toUpperCase();
const product = catalog.find(p =>
String(p.sku || '').trim().toUpperCase() === skuUpper
);
const ref = product ? String(product.ref || '').trim().toUpperCase() : '?';
const isCase = product ? !!product.hasCase : false;
const formNum = product ? String(product.orderFormNumber || '1').trim() : '1';
const unitPrice = item.price ||
(product ? (product.onSale && product.salePrice > 0 ? product.salePrice : product.price) : 0);
_ensureForm(formNum);
_ensureRef(byForm[formNum], ref);
_ensureSku(byForm[formNum], skuUpper);
const formData = byForm[formNum];
if (isCase) {
formData.byRef[ref].mcQty += qty;
formData.bySku[skuUpper].mcQty += qty;
} else {
formData.byRef[ref].singlesQty += qty;
formData.bySku[skuUpper].singlesQty += qty;
}
formData.byRef[ref].totalPrice += unitPrice * qty;
formData.bySku[skuUpper].totalPrice += unitPrice * qty;
const variation = product
? [product.variation, product.variation2, product.variation3]
.filter(v => v && String(v).trim())
.join(' / ')
: '';
formData.byRef[ref].items.push({
sku: item.sku,
name: product ? product.name : item.sku,
variation,
quantity: qty,
isCase,
price: unitPrice,
});
formData.itemizedDetail.push({
ref,
sku: item.sku,
name: product ? product.name : item.sku,
brand: product ? product.brand : '',
variation,
quantity: qty,
isCase,
});
});
return { byForm };
}
// ============================================================================
// PATH A — SHEET POPULATE → NATIVE PDF EXPORT (ORDERS sheet trigger)
// ============================================================================
/**
* Entry point called from the ORDERS sheet menu.
* Works on the currently selected row.
*
* Workflow:
* 1. Parse order from selected row
* 2. Read ORDER_FORM_1 template structure
* 3. Aggregate order quantities by ref code
* 4. Write Singles/MC/Total quantities into ORDER_FORM_1
* 5. Export ORDER_FORM_1 as a native Sheets PDF
* 6. Clear the written cells (restore blank template)
* 7. Save PDF to Orders folder → show link
*/
function generateSelectedOrderFormPdf() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getActiveSheet();
if (sheet.getName() !== SHEET_NAMES.ORDERS) {
ss.toast('Please run this from the ORDERS sheet.');
return;
}
const activeRow = sheet.getActiveCell().getRow();
if (activeRow < 2) {
ss.toast('Please select an order row first.');
return;
}
const rowData = sheet.getRange(activeRow, 1, 1, sheet.getLastColumn()).getValues()[0];
const orderId = String(rowData[ORDER_COL.INVOICE_NUMBER] || '').trim();
const clientName = String(rowData[ORDER_COL.CLIENT] || '').trim();
const orderDate = (rowData[ORDER_COL.TIME_STAMP] instanceof Date)
? rowData[ORDER_COL.TIME_STAMP]
: new Date();
if (!orderId) { ss.toast('No Invoice Number found in selected row.'); return; }
// Parse product items from the row
const items = [];
for (let i = ORDER_COL.PRODUCTS_START; i < rowData.length; i++) {
const cell = String(rowData[i] || '').trim();
if (!cell) continue;
const m = cell.match(/\[(\d+)\|@?([^\|]+)\|\$?([\d.]+)\|([TF])\]/);
if (m) items.push({
quantity: parseInt(m[1]) || 0,
sku: m[2].trim(),
price: parseFloat(m[3]) || 0,
onSale: m[4] === 'T',
});
}
if (items.length === 0) { ss.toast('No products found in this order.'); return; }
ss.toast(`Building Order Form PDF for ${clientName}…`);
try {
const catalog = getProductCatalog();
const { byForm } = aggregateOrderByRef(items, catalog);
const formNums = Object.keys(byForm);
if (formNums.length === 0) {
ss.toast('No products matched a known Order Form.');
return;
}
// Read sales rep from CFG_SALES_REP named range (same source as PDFService)
let cfgSalesRep = '';
try {
const repRange = ss.getRangeByName('CFG_SALES_REP');
if (repRange) cfgSalesRep = String(repRange.getValue() || '').trim();
} catch (e) {
Logger.log('Could not read CFG_SALES_REP: ' + e.message);
}
if (!cfgSalesRep) cfgSalesRep = getSettingValue('CFG_SALES_REP') || getSettingValue('Sales Rep') || '';
const orderData = {
id: orderId,
clientName,
clientAddress: String(rowData[ORDER_COL.ADDRESS] || '').trim(),
clientComments: String(rowData[ORDER_COL.COMMENT] || '').trim(),
salesRep: cfgSalesRep || String(rowData[ORDER_COL.SALES_REP] || '').trim(),
date: orderDate,
items,
};
const formattedDate = formatDateWithOrdinal(orderDate);
const folder = getOrdersFolder();
const pdfUrls = [];
formNums.forEach(formNum => {
const sheetName = getOrderFormSheetName(formNum); // honours SETTINGS FORM_N_SHEET overrides
try {
// Native Sheets PDF — includes itemized detail written into secondary table
const page1Url = _populateSheetAndExport({
id: orderId,
clientName,
clientAddress: orderData.clientAddress,
clientComments: orderData.clientComments,
salesRep: orderData.salesRep,
date: orderDate,
items,
_formNum: formNum,
_byForm: byForm,
_sheetName: sheetName,
});
pdfUrls.push({ formNum, url: page1Url });
Logger.log('Order Form PDF (native): ' + page1Url);
} catch (formErr) {
Logger.log(`Skipping Form ${formNum} (sheet "${sheetName}"): ${formErr.message}`);
pdfUrls.push({ formNum, url: null, error: formErr.message });
}
});
const successLinks = pdfUrls.filter(u => u.url).map(u =>
`<p><a href="${u.url}" target="_blank"
style="color:#b040b0;font-weight:700;font-size:14px;">
📋 Form ${u.formNum} — Order Form PDF
</a></p>`
).join('');
const errorLines = pdfUrls.filter(u => !u.url).map(u =>
`<p style="color:#c00;font-size:12px;">⚠️ Form ${u.formNum} skipped: ${u.error || 'Sheet not found'}</p>`
).join('');
const html = HtmlService.createHtmlOutput(`
<div style="font-family:Arial,sans-serif;padding:20px;">
<p style="color:#b040b0;font-size:16px;font-weight:700;">✓ PDF generation complete</p>
${successLinks}
${errorLines}
</div>
`).setWidth(450).setHeight(160);
SpreadsheetApp.getUi().showModalDialog(html, 'Order Form PDF Ready');
} catch (e) {
SpreadsheetApp.getUi().alert('Error generating Order Form PDF:\n' + e.message);
Logger.log('OrderFormPDF (Sheet) Error: ' + e.toString());
}
}
/**
* Build ONLY the itemized detail page HTML (page 2).
* Used by Path A so we can generate a separate companion detail PDF
* while the main order form PDF comes from the native sheet export.
*/
function _buildDetailPageHtml(itemizedDetail, orderData, formattedDate) {
const clientName = orderData.clientName || 'Unknown Client';
const salesRep = orderData.salesRep || '';
const displayRep = String(salesRep).split(/\s+/)[0] || salesRep;
const ordered = (itemizedDetail || [])
.filter(i => i.quantity > 0)
.sort((a, b) => a.ref.localeCompare(b.ref) || (a.variation || a.name).localeCompare(b.variation || b.name));
const half = Math.ceil(ordered.length / 2);
const leftCol = ordered.slice(0, half);
const rightCol = ordered.slice(half);
const maxRows = Math.max(leftCol.length, rightCol.length);
let rows = '';
for (let i = 0; i < maxRows; i++) {
const L = leftCol[i];
const R = rightCol[i];
const strip = i % 2 === 0 ? '#ffffff' : '#f5f5f5';
const formatName = (item) => {
if (!item) return '';
let text = '';
if (item.brand) text += item.brand + ' ';
if (item.name) text += item.name;
if (item.variation && item.variation !== item.name) text += ' - ' + item.variation;
return text || item.variation || item.name || '';
};
rows += `
<tr style="background:${strip};">
<td style="text-align:center;font-weight:700;font-size:9px;color:#888;width:32px;border:1px solid #ddd;padding:3px 4px;">${L ? _esc(L.ref) : ''}</td>
<td style="padding:3px 7px;border:1px solid #ddd;font-size:10px;">${L ? _esc(formatName(L)) : ''}</td>
<td style="text-align:center;font-weight:700;width:44px;border:1px solid #ddd;padding:3px 4px;">${L ? L.quantity : ''}</td>
<td style="width:10px;background:#ddd;border:none;"></td>
<td style="text-align:center;font-weight:700;font-size:9px;color:#888;width:32px;border:1px solid #ddd;padding:3px 4px;">${R ? _esc(R.ref) : ''}</td>
<td style="padding:3px 7px;border:1px solid #ddd;font-size:10px;">${R ? _esc(formatName(R)) : ''}</td>
<td style="text-align:center;font-weight:700;width:44px;border:1px solid #ddd;padding:3px 4px;">${R ? R.quantity : ''}</td>
</tr>`;
}
return `<!DOCTYPE html><html><head><meta charset="utf-8">
<style>
* { box-sizing:border-box; margin:0; padding:0; }
body { font-family:Arial,Helvetica,sans-serif; font-size:11px; color:#1a1a1a; }
.page { padding:20px 24px; max-width:780px; margin:0 auto; }
.hdr { font-size:15px; font-weight:800; color:#cc66cc;
border-bottom:2px solid #cc66cc; padding-bottom:5px; margin-bottom:6px; }
.sub { font-size:10px; color:#555; margin-bottom:12px; }
table { width:100%; border-collapse:collapse; font-size:10px; }
th { font-weight:700; font-size:9px; padding:4px 7px;
text-transform:uppercase; letter-spacing:0.3px; border:1px solid #b050b0; }
</style></head><body>
<div class="page">
<div class="hdr">Order Detail — ${_esc(clientName)}</div>
<div class="sub">Date: ${formattedDate} | Order #${_esc(String(orderData.id || 'N/A'))} | Rep: ${_esc(displayRep)}</div>
<table>
<thead>
<tr>
<th bgcolor="#cc66cc" style="text-align:center;width:32px;color:#fff;">Ref</th>
<th bgcolor="#cc66cc" style="text-align:left;color:#fff;">Flavour / Strain</th>
<th bgcolor="#cc66cc" style="text-align:center;width:46px;color:#fff;">Qty</th>
<th bgcolor="#999" style="width:10px;border:none;"></th>
<th bgcolor="#cc66cc" style="text-align:center;width:32px;color:#fff;">Ref</th>
<th bgcolor="#cc66cc" style="text-align:left;color:#fff;">Flavour / Strain</th>
<th bgcolor="#cc66cc" style="text-align:center;width:46px;color:#fff;">Qty</th>
</tr>
</thead>
<tbody>${rows}</tbody>
</table>
</div>
</body></html>`;
}
/**
* Internal: write quantities into ORDER_FORM_1, export as PDF, then clear.
*
* @param {Object} orderData Standard order object with items array,
* optionally with _formNum, _byForm, _sheetName for pre-computed aggregation.
* @returns {string} URL of the saved PDF file
*/
function _populateSheetAndExport(orderData) {
const lock = LockService.getScriptLock();
try { lock.waitLock(30000); } catch (e) { throw new Error('System busy — try again in a moment.'); }
const cellsToReset = []; // Track every cell we write so we can clear cleanly
try {
// Accept pre-computed aggregation (from generateSelectedOrderFormPdf) or compute fresh
const byRef = orderData._byForm
? (orderData._byForm[orderData._formNum] || {}).byRef || {}
: (() => {
const catalog = getProductCatalog();
const { byForm } = aggregateOrderByRef(orderData.items, catalog);
return (byForm[orderData._formNum || '1'] || {}).byRef || {};
})();
const bySku = orderData._byForm
? (orderData._byForm[orderData._formNum] || {}).bySku || {}
: {};
// ── Lookup mode: REF (default) or SKU, per-form from SETTINGS ────────
// SETTINGS key: FORM_1_LOOKUP = REF, FORM_2_LOOKUP = SKU, etc.
const lookupMode = getFormLookupMode(orderData._formNum || '1');
Logger.log(`Form ${orderData._formNum} lookup mode: ${lookupMode}`);
// Helper: look up product data by the row's ref value, respecting mode,
// with automatic fallback to: other mode, then column-A value (SKU forms).
const lookupRowData = (row) => {
const k = String(row.ref || '').toUpperCase();
const kA = String(row.colA || '').toUpperCase(); // raw col-A (SKU in Form 2)
if (lookupMode === 'SKU') {
return bySku[k] || byRef[k] || (kA && kA !== k ? (bySku[kA] || byRef[kA]) : null) || null;
}
return byRef[k] || bySku[k] || (kA && kA !== k ? (byRef[kA] || bySku[kA]) : null) || null;
};
const sheetName = orderData._sheetName || getOrderFormSheetName(orderData._formNum || '1');
const template = readOrderFormTemplate(sheetName);
if (!template) throw new Error(sheetName + ' is empty.');
const formSheet = template.sheet;
// ── Write header info (Rep / Date / Store / Shipping) ─────────────────
// Scan rows 1-5 for cells containing label keywords and write values
// into the cell immediately to the right of each label.
const headerSearchRange = formSheet.getRange(1, 1, Math.min(5, formSheet.getLastRow()), formSheet.getLastColumn());
const headerVals = headerSearchRange.getValues();
const orderDate = orderData.date instanceof Date ? orderData.date : new Date();
const dateStr = formatDateWithOrdinal(orderDate);
headerVals.forEach((row, r) => {
row.forEach((cell, c) => {
const s = String(cell || '').trim().toLowerCase();
const destCol = c + 1; // Check the cell to the right
if (destCol >= row.length) return;
if (s === 'date:' || s === 'date') {
const rangeAddr = formSheet.getRange(r + 1, destCol + 1);
rangeAddr.setValue(dateStr);
cellsToReset.push(rangeAddr);
} else if (s === 'store:' || s === 'store') {
const rangeAddr = formSheet.getRange(r + 1, destCol + 1);
rangeAddr.setValue(orderData.clientName || '');
cellsToReset.push(rangeAddr);
} else if (s === 'rep:' || s === 'rep') {
const rangeAddr = formSheet.getRange(r + 1, destCol + 1);
rangeAddr.setValue(orderData.salesRep || '');
cellsToReset.push(rangeAddr);
}
// "Shipping:" left blank unless orderData.shipping provided
});
});
// ── Write Singles / MC / Total quantities into product rows ───────────
template.rows.forEach(row => {
if (row.type !== 'product') return;
const data = lookupRowData(row);
if (!data) return; // Product not in this order — leave blank
const singlesQty = data.singlesQty || 0;
const mcQty = data.mcQty || 0;
const totalPrice = data.totalPrice || 0;
// For SKU-mode forms, write the quantity (singles OR mc, whichever is present)
// into whichever column is available.
const qtyToWrite = singlesQty + mcQty; // combined for forms with a single Qty column
if (template.singlesCol > -1 && singlesQty > 0) {
const r = formSheet.getRange(row.sheetRowNum, template.singlesCol + 1);
r.setValue(singlesQty);
cellsToReset.push(r);
}
if (template.mcCol > -1) {
// In SKU/Qty-only forms (no singles col), put combined qty in mcCol
const writeQty = (template.singlesCol === -1) ? qtyToWrite : mcQty;
if (writeQty > 0) {
const r = formSheet.getRange(row.sheetRowNum, template.mcCol + 1);
r.setValue(writeQty);
cellsToReset.push(r);
}
}
if (template.totalCol > -1 && totalPrice > 0) {
const r = formSheet.getRange(row.sheetRowNum, template.totalCol + 1);
r.setValue(totalPrice);
cellsToReset.push(r);
}
});
// ── Calculate and write Grand Total to the "Total:" cell ──────────────
// Sum from whichever lookup source has data
const refTotal = Object.values(byRef).reduce((s, d) => s + (d.totalPrice || 0), 0);
const skuTotal = Object.values(bySku).reduce((s, d) => s + (d.totalPrice || 0), 0);
const grandTotal = Math.max(refTotal, skuTotal); // both should agree; take the larger
const lastTemplateRow = template.rows.length > 0
? template.rows[template.rows.length - 1].sheetRowNum
: 1;
if (grandTotal > 0) {
// Scan from lastTemplateRow (not +1) — the Total: row may BE the last template row.
// Skip the form's own column-header row (headerRowNum) to avoid matching
// the word "Total" in the "Singles | MC | Total" header.
const scanStart = lastTemplateRow;
const scanEnd = formSheet.getLastRow();
const lastSheetCol = formSheet.getLastColumn();
const skipRow = template.headerRowNum; // never write to the column-header row
for (let scanRow = scanStart; scanRow <= scanEnd; scanRow++) {
if (scanRow === skipRow) continue; // skip the singles/mc/total header row
const scanVals = formSheet.getRange(scanRow, 1, 1, lastSheetCol).getValues()[0];
// Matches: "Total", "Total:", "Grand Total:", "Sub-Total", "Order Total"
// Does NOT match "Total Singles", "Total MC", "Total Units" (trailing words)
const totalLabelIdx = scanVals.findIndex(c => {
const s = String(c || '').trim();
return /^(grand\s+|sub[-\s]?|order\s+)?total:?\s*$/i.test(s);
});
if (totalLabelIdx > -1) {
const writeCol = (totalLabelIdx + 2 <= lastSheetCol)
? totalLabelIdx + 2
: lastSheetCol;
const totalCell = formSheet.getRange(scanRow, writeCol);
totalCell.setValue(grandTotal);
cellsToReset.push(totalCell);
Logger.log(`Grand total $${grandTotal} → row ${scanRow} col ${writeCol} (label: "${scanVals[totalLabelIdx]}")`);
break;
}
}
}
// ── Write itemized detail into the secondary table (page 2 of sheet) ──
const itemizedDetail = (orderData._byForm && orderData._formNum)
? ((orderData._byForm[orderData._formNum] || {}).itemizedDetail || [])
: [];
Logger.log(`Itemized detail count: ${itemizedDetail.length}`);
if (itemizedDetail.length > 0) {
const secScanStart = lastTemplateRow + 1;
const secScanEnd = formSheet.getLastRow(); // scan all remaining rows, not just +20
const lastSheetCol = formSheet.getLastColumn();
let secHeaderRow = -1, nameCol1 = -1, qtyCol1 = -1, nameCol2 = -1, qtyCol2 = -1;
Logger.log(`Scanning for secondary table header: rows ${secScanStart}–${secScanEnd}`);
for (let r = secScanStart; r <= secScanEnd; r++) {
const vals = formSheet.getRange(r, 1, 1, lastSheetCol).getValues()[0];
const hasNameHeader = vals.some(v => /flower|concentrate|flavour|strain/i.test(String(v || '')));
const hasQtyHeader = vals.some(v => /quantity|qty/i.test(String(v || '')));
Logger.log(` row ${r}: hasNameHeader=${hasNameHeader} hasQtyHeader=${hasQtyHeader} vals=[${vals.join('|')}]`);
if (hasNameHeader && hasQtyHeader) {
secHeaderRow = r;
vals.forEach((v, i) => {
const s = String(v || '').toLowerCase();
if (/flower|concentrate|flavour|strain/i.test(s)) {
if (nameCol1 === -1) nameCol1 = i + 1;
else if (nameCol2 === -1) nameCol2 = i + 1;
} else if (/quantity|qty/i.test(s)) {
if (qtyCol1 === -1) qtyCol1 = i + 1;
else if (qtyCol2 === -1) qtyCol2 = i + 1;
}
});
break;
}
}
Logger.log(`Secondary table: headerRow=${secHeaderRow} nameCol1=${nameCol1} qtyCol1=${qtyCol1} nameCol2=${nameCol2} qtyCol2=${qtyCol2}`);
// If name columns had unrecognised/blank headers, infer from Quantity columns:
// the name column is immediately to the LEFT of each Quantity column.
if (qtyCol1 > 1 && nameCol1 === -1) nameCol1 = qtyCol1 - 1;
if (qtyCol2 > 1 && nameCol2 === -1) nameCol2 = qtyCol2 - 1;
Logger.log(`After inference: nameCol1=${nameCol1} nameCol2=${nameCol2}`);
if (secHeaderRow > 0 && qtyCol1 > 0) {
// NOTE: we do NOT write to or clear the header cells — the user has
// set "Flavour / Strain" / "Quantity" permanently in the template.
// Only the DATA rows below the header are written and cleared.
const ordered = itemizedDetail
.filter(i => (i.quantity || 0) > 0)
.sort((a, b) => (a.ref || '').localeCompare(b.ref || '') ||
(a.variation || a.name || '').localeCompare(b.variation || b.name || ''));
const half = Math.ceil(ordered.length / 2);
const leftItems = ordered.slice(0, half); // fill left column first
const rightItems = ordered.slice(half); // overflow into right column
const refCol1 = nameCol1 > 1 ? nameCol1 - 1 : -1;
const refCol2 = nameCol2 > 1 ? nameCol2 - 1 : -1;
const maxRows = formSheet.getMaxRows();
const formatDisplayName = (item) => {
let text = '';
if (item.brand) text += item.brand + ' ';
if (item.name) text += item.name;
if (item.variation && item.variation !== item.name) text += ' - ' + item.variation;
return text || item.variation || item.name || '';
};
leftItems.forEach((item, i) => {
const rowNum = secHeaderRow + 1 + i;
if (rowNum > maxRows) return;
if (refCol1 > 0) { const rc = formSheet.getRange(rowNum, refCol1); rc.setValue(item.ref); cellsToReset.push(rc); }
if (nameCol1 > 0) { const nc = formSheet.getRange(rowNum, nameCol1); nc.setValue(formatDisplayName(item)); cellsToReset.push(nc); }
if (qtyCol1 > 0) { const qc = formSheet.getRange(rowNum, qtyCol1); qc.setValue(item.quantity); cellsToReset.push(qc); }
});
rightItems.forEach((item, i) => {
const rowNum = secHeaderRow + 1 + i;
if (rowNum > maxRows) return;
if (refCol2 > 0) { const rc = formSheet.getRange(rowNum, refCol2); rc.setValue(item.ref); cellsToReset.push(rc); }
if (nameCol2 > 0) { const nc = formSheet.getRange(rowNum, nameCol2); nc.setValue(formatDisplayName(item)); cellsToReset.push(nc); }
if (qtyCol2 > 0) { const qc = formSheet.getRange(rowNum, qtyCol2); qc.setValue(item.quantity); cellsToReset.push(qc); }
});
Logger.log(`Itemized: ${ordered.length} items — ${leftItems.length} left / ${rightItems.length} right`);
}
}
// ── Resolve tokens anywhere in the template ───────────────────────────
// Product tokens: {BBS-Q}, {BBS-T}, {BBS-QS}, {BBS-QM}
// Order tokens: {CLIENT_NAME}, {CLIENT_ADDRESS}, {CLIENT_PHONE},
// {CLIENT_EMAIL}, {COMMENTS}, {SALES_REP}, {ORDER_TOTAL}
_resolveTemplateTokens(formSheet, byRef, bySku, orderData, cellsToReset);
SpreadsheetApp.flush(); // Ensure all values are committed
// ── Export as native Sheets PDF ────────────────────────────────────────
// No r1/r2 range restriction — let the sheet's own print settings / page
// breaks control what appears on each page (avoids dark extra page).
const ss = SpreadsheetApp.getActiveSpreadsheet();
const ssId = ss.getId();
const sheetId = formSheet.getSheetId();
// Build export URL — Sheets PDF export API
// We let the sheet's own page-break settings control page separation.
// fitw=true scales content to fit the paper width.
// Use explicit print area (r1/c1/r2/c2, 0-indexed) so we don't export
// a massive blank area below the secondary table.
const lastDataRow = formSheet.getLastRow(); // actual last used row
const lastDataCol = formSheet.getLastColumn(); // actual last used col
const exportUrl = [
'https://docs.google.com/spreadsheets/d/', ssId,
'/export?',
'format=pdf',
'&size=letter',
'&portrait=true',
'&fitw=true',
'&sheetnames=false',
'&printtitle=false',
'&pagenumbers=false',
'&gridlines=false',
'&fzr=false',
'&gid=', sheetId,
// Clamp to the actual data area — prevents blank pages at the bottom
'&r1=0',
'&c1=0',
'&r2=', lastDataRow - 1, // 0-indexed last row with data
'&c2=', lastDataCol - 1, // 0-indexed last col with data
].join('');
const token = ScriptApp.getOAuthToken();
const response = UrlFetchApp.fetch(exportUrl, {
headers: { Authorization: 'Bearer ' + token },
muteHttpExceptions: true,
});
if (response.getResponseCode() !== 200) {
throw new Error('PDF export failed (HTTP ' + response.getResponseCode() + '). ' +
'Ensure the script has Spreadsheets scope.');
}
const clientName = String(orderData.clientName || 'Unknown').trim();
const salesRep = String(orderData.salesRep || '').trim();
const repSuffix = salesRep ? ` - ${salesRep}` : '';
const fileName = `${clientName} ${dateStr}${repSuffix}.pdf`;
const pdfBlob = response.getBlob().setName(fileName);
const folder = getOrdersFolder();
const pdfFile = folder.createFile(pdfBlob);
Logger.log('Order Form PDF (Sheet export) saved: ' + pdfFile.getUrl());
return pdfFile.getUrl();
} finally {
// ── Restore the blank template ─────────────────────────────────────────
// Regular data cells → clearContent()
// Token cells ({REF-Q} etc.) → setValue(original) to restore the token
cellsToReset.forEach(item => {
try {
if (item && item._token) {
item.range.setValue(item.original); // restore {REF-Q} text
} else {
item.clearContent(); // clear written data
}
} catch (e) { /* ignore individual cell errors */ }
});
SpreadsheetApp.flush();
lock.releaseLock();
}
}
// ============================================================================
// TOKEN SUBSTITUTION — ORDER_FORM template placeholders
// ============================================================================
/**
* Scans every cell in the ORDER_FORM sheet for placeholder tokens.
*
* PRODUCT TOKENS (keyed by REF, place anywhere in the template):
* {REF-Q} Total units ordered (singles + cases combined)
* {REF-QS} Singles quantity only
* {REF-QM} MC / case quantity only
* {REF-T} Total dollar amount for that product group
*
* ORDER-LEVEL TOKENS:
* {CLIENT_NAME} Client / store name
* {CLIENT_ADDRESS} Client delivery address
* {CLIENT_PHONE} Client phone number
* {CLIENT_EMAIL} Client email address
* {COMMENTS} Order comments / special instructions
* {SALES_REP} Sales rep name
* {ORDER_TOTAL} Grand total dollar amount
* {ORDER_DATE} Order date (formatted)
* {ORDER_ID} Invoice / order number
*/
function _resolveTemplateTokens(sheet, byRef, bySku, orderData, cellsToReset) {
if (!sheet || !byRef) return;
bySku = bySku || {};
const od = orderData || {};
const grandTotal = Object.values(byRef).reduce((s, d) => s + (d.totalPrice || 0), 0);
const orderTokens = {
'CLIENT_NAME': String(od.clientName || ''),
'CLIENT_ADDRESS': String(od.clientAddress || ''),
'CLIENT_PHONE': String(od.clientPhone || od.phone || ''),
'CLIENT_EMAIL': String(od.clientEmail || od.email || ''),
'COMMENTS': String(od.clientComments || od.comments || od.notes || ''),
'SALES_REP': String(od.salesRep || ''),
'ORDER_TOTAL': grandTotal.toFixed(2),
'ORDER_DATE': od.date instanceof Date
? formatDateWithOrdinal(od.date)
: String(od.date || new Date().toLocaleDateString()),
'ORDER_ID': String(od.id || od.orderId || ''),
};
// Token format: {KEY-SUFFIX} where KEY can contain hyphens (for SKU tokens like CDNCL-2)
// Strategy: match the longest possible KEY that leaves a valid SUFFIX at the end.
// We capture everything before the last hyphen+suffix as the KEY.
// Examples:
// {CDNCL-Q} → key=CDNCL, suffix=Q → REF-based (sum all SKUs under CDNCL)
// {CDNCL-2-Q} → key=CDNCL-2, suffix=Q → SKU-based (exact SKU, individual qty)
// {CLIENT_NAME}→ key=CLIENT_NAME, suffix=none → order token
const TOKEN_RE = /\{([A-Z0-9][A-Z0-9_-]*)\}/gi;
const VALID_SUFFIXES = new Set(['Q', 'QS', 'QM', 'T']);
const resolveProductToken = (fullKey, suffix) => {
const uk = fullKey.toUpperCase();
// 1. Try exact SKU match first (SKU-based = individual, no summing)
if (bySku[uk]) {
const d = bySku[uk];
switch (suffix) {
case 'Q': return String((d.singlesQty || 0) + (d.mcQty || 0));
case 'QS': return String(d.singlesQty || 0);
case 'QM': return String(d.mcQty || 0);
case 'T': return Number(d.totalPrice || 0).toFixed(2);
}
}
// 2. Fall back to REF-based match (sums all SKUs under that ref)
if (byRef[uk]) {
const d = byRef[uk];
switch (suffix) {
case 'Q': return String((d.singlesQty || 0) + (d.mcQty || 0));
case 'QS': return String(d.singlesQty || 0);
case 'QM': return String(d.mcQty || 0);
case 'T': return Number(d.totalPrice || 0).toFixed(2);
}
}
return '0'; // not found
};
const dataRange = sheet.getDataRange();
const values = dataRange.getValues();
const numRows = values.length;
const numCols = values[0] ? values[0].length : 0;
if (numRows === 0 || numCols === 0) return;
const changedCells = [];
for (let r = 0; r < numRows; r++) {
for (let c = 0; c < numCols; c++) {
const raw = String(values[r][c] || '');
if (!raw.includes('{')) continue;
const resolved = raw.replace(TOKEN_RE, (match, innerKey) => {
const uk = innerKey.toUpperCase();
// Check for order-level token (no suffix, must match exactly)
if (orderTokens.hasOwnProperty(uk)) return orderTokens[uk];