-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
697 lines (576 loc) · 21 KB
/
index.js
File metadata and controls
697 lines (576 loc) · 21 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
/*************************************************************
* BOQ CSV (AUTO-LOAD) + HIERARCHY + COLLAPSE + ROLLUP ENGINE
*
* THIS REVISION (MINIMAL CHANGE):
* - Fix rollups: parents sum ALL descendant RATE rows recursively
* + include non-rate rows with uploaded SUBTOTAL/TOTAL (Trench Mesh case)
* - Fix Rails Turbo: init runs on DOMContentLoaded + turbo:load
*
* Everything else unchanged.
*************************************************************/
/* ================= COLUMN MAP ================= */
const COL = {
CODE: 0,
DESC: 1,
QTY: 2,
UNIT: 3,
RATE: 4,
SUBTOTAL: 5,
MARKUP: 6, // UI label = FACTOR
TOTAL: 7
};
/* ================= CONFIG ================= */
const INDENT_PX = 20; // ~3–5mm
const AUTO_CSV_PATH = "./boq.csv";
/* ================= STAGE 1: LOCAL STORAGE KEY ================= */
const STORAGE_KEY = "boqRateOverrides";
/* ================= CODE UTILITIES ================= */
function isRate(code) {
return /\.R\d+$/.test(code || "");
}
function stripRate(code) {
return (code || "").replace(/\.R\d+$/, "");
}
function tradePrefix(code) {
const parts = stripRate(code).split(".");
return parts.length >= 2 ? `${parts[0]}.${parts[1]}` : "";
}
function numericSlots(code) {
return stripRate(code).split(".").slice(2).map(n => parseInt(n, 10));
}
function nonZeroCount(code) {
return numericSlots(code).reduce((a, n) => a + (n !== 0 ? 1 : 0), 0);
}
/**
* Covers relationship:
* parent covers child if all parent non-zero slots match child's slots.
*/
function covers(parentCode, childCode) {
if (!parentCode || !childCode) return false;
if (tradePrefix(parentCode) !== tradePrefix(childCode)) return false;
const p = numericSlots(parentCode);
const c = numericSlots(childCode);
for (let i = 0; i < p.length; i++) {
if (p[i] !== 0 && p[i] !== c[i]) return false;
}
return true;
}
function isDescendant(parentCode, childCode) {
if (!parentCode || !childCode) return false;
if (stripRate(parentCode) === stripRate(childCode)) return false;
if (isRate(childCode)) return false; // rates handled via base
return covers(parentCode, childCode);
}
/* ================= DOM HELPERS ================= */
function rows() {
return Array.from(document.querySelectorAll(".boq-row[data-code]"));
}
/* ================= NUMBER HELPERS ================= */
function parseNumber(v) {
const n = parseFloat(String(v ?? "").replace(/,/g, "").trim());
return Number.isFinite(n) ? n : 0;
}
function parseMoney(v) {
const n = parseFloat(String(v ?? "").replace(/[$,\s]/g, "").trim());
return Number.isFinite(n) ? n : 0;
}
function parsePercent(v) {
const n = parseFloat(String(v ?? "").replace(/[%\s]/g, "").trim());
return Number.isFinite(n) ? n : null;
}
function formatMoney(n) {
return "$" + n.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
/**
* Uploaded values are those that came from CSV at render time.
* Computed values are allowed to change after user edits.
*/
function cellHasUploadedValue(cellEl) {
return !!cellEl && cellEl.dataset && cellEl.dataset.uploaded === "1";
}
/* ================= LOCAL STORAGE HELPERS ================= */
function loadOverrides() {
try {
return JSON.parse(localStorage.getItem(STORAGE_KEY)) || {};
} catch {
return {};
}
}
function saveOverrides(obj) {
localStorage.setItem(STORAGE_KEY, JSON.stringify(obj));
}
function normaliseEditableNumberText(s) {
const cleaned = String(s ?? "")
.replace(/[$,%\s]/g, "")
.replace(/,/g, "")
.trim();
if (cleaned === "") return "";
const n = parseFloat(cleaned);
return Number.isFinite(n) ? String(n) : "";
}
/* ================= MINIMAL UI: INPUT CREATOR ================= */
function makeNumericInput(initialValue = "") {
const input = document.createElement("input");
input.type = "text";
input.value = initialValue;
// Sleek, modern, rounded – Tailwind only
input.className =
"w-full bg-white text-slate-900 text-right px-2 py-1 rounded-md " +
"focus:outline-none focus:ring-2 focus:ring-slate-300";
return input;
}
function getCellNumericText(cellEl) {
if (!cellEl) return "";
const inp = cellEl.querySelector("input");
return inp ? inp.value : cellEl.textContent;
}
/* ============================================================
* CALCULATIONS (DOES NOT OVERRIDE UPLOADED VALUES)
* REQUIRED CHANGE: FACTOR reads from input.value if present
* ============================================================ */
function applyRowCalculations(allRows) {
for (const r of allRows) {
if (!r || !r.children) continue;
const qtyCell = r.children[COL.QTY];
const rateCell = r.children[COL.RATE];
const subtotalCell = r.children[COL.SUBTOTAL];
const markupCell = r.children[COL.MARKUP]; // FACTOR
const totalCell = r.children[COL.TOTAL];
if (!qtyCell || !rateCell || !subtotalCell || !markupCell || !totalCell) continue;
const qty = parseNumber(getCellNumericText(qtyCell));
const rate = parseMoney(getCellNumericText(rateCell));
// SUBTOTAL
let subtotal = null;
if (cellHasUploadedValue(subtotalCell)) {
subtotal = parseMoney(subtotalCell.textContent);
} else {
if (qty !== 0 && rate !== 0) {
subtotal = qty * rate;
subtotalCell.textContent = formatMoney(subtotal);
} else {
subtotalCell.textContent = "";
}
}
// TOTAL
if (cellHasUploadedValue(totalCell)) continue;
if (subtotal !== null) {
let total = subtotal;
// FACTOR (still % logic, unchanged)
const factorText = String(getCellNumericText(markupCell) ?? "").trim();
if (cellHasUploadedValue(markupCell) || factorText.length > 0) {
const pct = parsePercent(factorText);
if (pct !== null) total = subtotal * (1 + pct / 100);
}
totalCell.textContent = formatMoney(total);
} else {
if (!cellHasUploadedValue(totalCell)) totalCell.textContent = "";
}
}
}
/* ============================================================
* HIERARCHY INDEX (unchanged)
* Parent = most specific PRIOR row that covers the child
* Rates attach to their base code.
* ============================================================ */
function buildHierarchyIndex(allRows) {
const nodes = allRows
.map((r, idx) => ({ el: r, code: r.dataset.code, idx }))
.filter(x => x.code && !isRate(x.code));
const parentOf = new Map(); // code -> parentCode|null
const childrenOf = new Map(); // code -> [child codes]
const rateChildrenOf = new Map(); // baseCode -> [rate codes]
const depthOf = new Map(); // code -> UI depth
for (const n of nodes) {
childrenOf.set(n.code, []);
rateChildrenOf.set(n.code, []);
}
for (const n of nodes) {
let bestParent = null;
let bestSpec = -1;
let bestIdx = -1;
for (const p of nodes) {
if (p.idx >= n.idx) break; // prior rows only
if (!covers(p.code, n.code)) continue;
const spec = nonZeroCount(p.code);
if (spec > bestSpec || (spec === bestSpec && p.idx > bestIdx)) {
bestParent = p.code;
bestSpec = spec;
bestIdx = p.idx;
}
}
if (bestParent === n.code) bestParent = null;
parentOf.set(n.code, bestParent);
if (bestParent && childrenOf.has(bestParent)) {
childrenOf.get(bestParent).push(n.code);
}
}
// Attach rate rows
for (const r of allRows) {
const c = r.dataset.code;
if (!c || !isRate(c)) continue;
const base = stripRate(c);
if (!rateChildrenOf.has(base)) rateChildrenOf.set(base, []);
rateChildrenOf.get(base).push(c);
}
// Compute depth
function computeDepth(code) {
if (depthOf.has(code)) return depthOf.get(code);
const p = parentOf.get(code);
const d = p ? computeDepth(p) + 1 : 0;
depthOf.set(code, d);
return d;
}
for (const n of nodes) computeDepth(n.code);
return { parentOf, childrenOf, rateChildrenOf, depthOf };
}
function hasChildren(code, hierarchy) {
if (!code || isRate(code)) return false;
const { childrenOf, rateChildrenOf } = hierarchy;
return (childrenOf.get(code)?.length || 0) > 0 || (rateChildrenOf.get(code)?.length || 0) > 0;
}
/* ============================================================
* PRESENTATION (unchanged)
* ============================================================ */
function applyLevelPresentation(rowEl, code, codeCell, descCell, hierarchy) {
rowEl.style.removeProperty("background-color");
if (isRate(code)) return;
const depth = hierarchy.depthOf.get(code) || 0;
if (depth === 0) {
rowEl.style.setProperty("background-color", "#f1f5f9", "important"); // slate-100
if (codeCell) {
codeCell.style.setProperty("color", "#64748b", "important"); // slate-500
codeCell.style.setProperty("font-weight", "700", "important");
codeCell.style.setProperty("text-decoration", "underline", "important");
const labelSpan = codeCell.querySelector("span:last-child");
if (labelSpan) {
labelSpan.style.setProperty("color", "#64748b", "important");
labelSpan.style.setProperty("font-weight", "700", "important");
labelSpan.style.setProperty("text-decoration", "underline", "important");
}
}
if (descCell) {
descCell.style.setProperty("color", "#64748b", "important");
descCell.style.setProperty("font-weight", "700", "important");
descCell.style.setProperty("text-decoration", "underline", "important");
}
} else {
if (descCell) {
descCell.style.setProperty("font-weight", "700", "important");
}
}
}
/* ============================================================
* ROLLUPS (FIXED: recursive descendant rates + uploaded non-rate values)
*
* Rule:
* - Parent sums ALL descendant RATE rows recursively (base covered by parent)
* - PLUS non-rate rows that have uploaded SUBTOTAL/TOTAL (even if they have children)
* - Avoid double-counting rollup nodes by only counting uploaded values for non-rates
* ============================================================ */
function rowHasUploadedMoney(rowEl) {
const subCell = rowEl.children[COL.SUBTOTAL];
const totCell = rowEl.children[COL.TOTAL];
return (subCell && cellHasUploadedValue(subCell)) || (totCell && cellHasUploadedValue(totCell));
}
function recomputeAllRollups(allRows, hierarchy) {
const nodes = allRows.filter(r => r.dataset.code && !isRate(r.dataset.code));
for (const node of nodes) {
const nCode = node.dataset.code;
let subtotal = 0;
let total = 0;
for (const r of allRows) {
const rCode = r.dataset.code;
if (!rCode) continue;
// Descendancy test is done on base codes
const base = stripRate(rCode);
const within =
base === nCode || isDescendant(nCode, base);
if (!within) continue;
if (isRate(rCode)) {
// ✅ Recursive: include ALL descendant rate rows
subtotal += parseMoney(r.children[COL.SUBTOTAL]?.textContent);
total += parseMoney(r.children[COL.TOTAL]?.textContent);
continue;
}
// ✅ Non-rate rows: ONLY include if they have uploaded money values
// (prevents rollup rows from counting themselves / double counting)
if (rowHasUploadedMoney(r)) {
subtotal += parseMoney(r.children[COL.SUBTOTAL]?.textContent);
total += parseMoney(r.children[COL.TOTAL]?.textContent);
}
}
// Parent rows never show quantity
node.children[COL.QTY].textContent = "";
node.children[COL.SUBTOTAL].textContent = formatMoney(subtotal);
node.children[COL.TOTAL].textContent = formatMoney(total);
}
}
/* ================= VISIBILITY (unchanged) ================= */
function hideSubtree(code, allRows, hierarchy) {
const { childrenOf, rateChildrenOf } = hierarchy;
(rateChildrenOf.get(code) || []).forEach(rc => {
const el = allRows.find(r => r.dataset.code === rc);
if (el) el.style.display = "none";
});
(childrenOf.get(code) || []).forEach(child => {
const el = allRows.find(r => r.dataset.code === child);
if (el) {
el.style.display = "none";
el.classList.add("collapsed");
el.classList.remove("expanded");
}
hideSubtree(child, allRows, hierarchy);
});
}
function showImmediateChildren(code, allRows, hierarchy) {
const { childrenOf, rateChildrenOf } = hierarchy;
(childrenOf.get(code) || []).forEach(child => {
const el = allRows.find(r => r.dataset.code === child);
if (el) el.style.display = "grid";
});
(rateChildrenOf.get(code) || []).forEach(rc => {
const el = allRows.find(r => r.dataset.code === rc);
if (el) {
el.style.display = "grid";
// REQUIRED: ensure newly shown rate rows get inputs + listeners
enableEditingForRateRow(el, hierarchy);
}
});
}
/* ================= UI INIT (unchanged) ================= */
function initBoqUI(allRows, hierarchy) {
const { depthOf } = hierarchy;
for (const r of allRows) {
const code = r.dataset.code;
if (!code) continue;
const codeCell = r.children[COL.CODE];
const descCell = r.children[COL.DESC];
if (!codeCell || !descCell) continue;
// Indentation
if (!isRate(code)) {
const d = depthOf.get(code) || 0;
descCell.style.setProperty("padding-left", `${d * INDENT_PX}px`, "important");
} else {
const base = stripRate(code);
const pd = depthOf.get(base) || 0;
descCell.style.setProperty("padding-left", `${(pd + 1) * INDENT_PX}px`, "important");
}
// Rebuild CODE cell
const codeLabel = code;
codeCell.innerHTML = "";
const wrap = document.createElement("div");
wrap.className = "flex items-center gap-2 select-none";
if (!isRate(code) && hasChildren(code, hierarchy)) {
const icon = document.createElement("span");
icon.textContent = r.classList.contains("expanded") ? "▾" : "▸";
icon.className = "text-slate-500";
wrap.appendChild(icon);
codeCell.classList.add("cursor-pointer", "text-blue-700");
codeCell.addEventListener("click", () => {
const isExpanded = r.classList.contains("expanded");
if (isExpanded) {
r.classList.remove("expanded");
r.classList.add("collapsed");
icon.textContent = "▸";
hideSubtree(code, allRows, hierarchy);
} else {
r.classList.add("expanded");
r.classList.remove("collapsed");
icon.textContent = "▾";
showImmediateChildren(code, allRows, hierarchy);
}
});
}
const label = document.createElement("span");
label.textContent = codeLabel;
wrap.appendChild(label);
codeCell.appendChild(wrap);
// Apply presentation AFTER rebuild
applyLevelPresentation(r, code, codeCell, descCell, hierarchy);
}
}
/* ================= CSV LOAD (unchanged, with uploaded flags) ================= */
function parseCSV(text) {
const lines = text.trim().split(/\r?\n/);
lines.shift();
return lines
.filter(l => l.trim().length > 0)
.map(l => {
const v = l.split(",");
return {
CODE: (v[0] ?? "").trim(),
DESCRIPTION: (v[1] ?? "").trim(),
QTY: (v[2] ?? "").trim(),
UNIT: (v[3] ?? "").trim(),
RATE: (v[4] ?? "").trim(),
SUBTOTAL: (v[5] ?? "").trim(),
MARKUP: (v[6] ?? "").trim(), // FACTOR
TOTAL: (v[7] ?? "").trim()
};
});
}
function clearBoq() {
document.querySelectorAll(".boq-row").forEach(r => r.remove());
}
function renderFromCSV(data) {
const container = document.getElementById("boqContainer");
data.forEach(row => {
const el = document.createElement("div");
el.className = "boq-row boq-grid px-3 py-2";
el.dataset.code = row.CODE;
// Rate rows stay light blue
if (isRate(row.CODE)) {
el.classList.add("bg-sky-100", "mx-2", "my-1", "rounded-md");
}
el.innerHTML = `
<div></div>
<div>${row.DESCRIPTION || ""}</div>
<div class="text-right">${row.QTY || ""}</div>
<div class="text-right">${row.UNIT || ""}</div>
<div class="text-right">${row.RATE || ""}</div>
<div class="text-right">${row.SUBTOTAL || ""}</div>
<div class="text-right">${row.MARKUP || ""}</div>
<div class="text-right">${row.TOTAL || ""}</div>
`;
const subtotalCell = el.children[COL.SUBTOTAL];
const markupCell = el.children[COL.MARKUP];
const totalCell = el.children[COL.TOTAL];
if (row.SUBTOTAL && subtotalCell) subtotalCell.dataset.uploaded = "1";
if (row.MARKUP && markupCell) markupCell.dataset.uploaded = "1";
if (row.TOTAL && totalCell) totalCell.dataset.uploaded = "1";
container.appendChild(el);
});
}
/* ================= RATE EDITING (INPUT FIELDS) ================= */
function enableEditingForRateRow(r, hierarchy) {
const code = r.dataset.code;
if (!code || !isRate(code)) return;
const qtyCell = r.children[COL.QTY];
const rateCell = r.children[COL.RATE];
const factorCell = r.children[COL.MARKUP];
if (!qtyCell || !rateCell || !factorCell) return;
// Prevent double-binding / double-injection
if (qtyCell.dataset.editEnabled === "1") return;
qtyCell.dataset.editEnabled = "1";
rateCell.dataset.editEnabled = "1";
factorCell.dataset.editEnabled = "1";
const overrides = loadOverrides();
// Determine initial values (CSV first, then override)
const initialQty =
overrides[code] && overrides[code].qty !== undefined
? String(overrides[code].qty)
: String(qtyCell.textContent || "");
const initialRate =
overrides[code] && overrides[code].rate !== undefined
? String(overrides[code].rate)
: String(rateCell.textContent || "");
const initialFactor =
overrides[code] && overrides[code].factor !== undefined
? String(overrides[code].factor)
: String(factorCell.textContent || "");
// Inject inputs (sleek)
const qtyInput = makeNumericInput(initialQty);
const rateInput = makeNumericInput(initialRate);
const factorInput = makeNumericInput(initialFactor);
qtyCell.textContent = "";
rateCell.textContent = "";
factorCell.textContent = "";
qtyCell.appendChild(qtyInput);
rateCell.appendChild(rateInput);
factorCell.appendChild(factorInput);
function persistAndRefresh() {
const qTxt = normaliseEditableNumberText(qtyInput.value);
const rTxt = normaliseEditableNumberText(rateInput.value);
const fTxt = normaliseEditableNumberText(factorInput.value);
qtyInput.value = qTxt;
rateInput.value = rTxt;
factorInput.value = fTxt;
overrides[code] = {
qty: qTxt === "" ? "" : parseNumber(qTxt),
rate: rTxt === "" ? "" : parseNumber(rTxt),
factor: fTxt === "" ? "" : parseNumber(fTxt)
};
saveOverrides(overrides);
const allNow = rows();
applyRowCalculations(allNow);
recomputeAllRollups(allNow, hierarchy);
}
qtyInput.addEventListener("blur", persistAndRefresh);
rateInput.addEventListener("blur", persistAndRefresh);
factorInput.addEventListener("blur", persistAndRefresh);
// Enter commits (optional, matches your prior behaviour)
qtyInput.addEventListener("keydown", (e) => {
if (e.key === "Enter") {
e.preventDefault();
qtyInput.blur();
}
});
rateInput.addEventListener("keydown", (e) => {
if (e.key === "Enter") {
e.preventDefault();
rateInput.blur();
}
});
factorInput.addEventListener("keydown", (e) => {
if (e.key === "Enter") {
e.preventDefault();
factorInput.blur();
}
});
}
/* ================= STAGE 1: enable for all rates currently present ================= */
function enableRateEditing(allRows, hierarchy) {
for (const r of allRows) {
enableEditingForRateRow(r, hierarchy);
}
}
/* ================= STARTUP (Rails Turbo-safe) ================= */
async function bootBoq() {
const container = document.getElementById("boqContainer");
if (!container) return;
// Prevent double init on the same DOM (Turbo can fire multiple events)
if (container.dataset.boqInit === "1") return;
container.dataset.boqInit = "1";
const res = await fetch(AUTO_CSV_PATH, { cache: "no-store" });
const text = await res.text();
const data = parseCSV(text);
clearBoq();
renderFromCSV(data);
const all = rows();
const hierarchy = buildHierarchyIndex(all);
// Initial visibility: show only root headings; hide all others
for (const r of all) {
const code = r.dataset.code;
if (!code) continue;
if (isRate(code)) {
r.style.display = "none";
continue;
}
const parent = hierarchy.parentOf.get(code);
if (parent === null) {
r.style.display = "grid";
r.classList.add("collapsed");
r.classList.remove("expanded");
} else {
r.style.display = "none";
r.classList.add("collapsed");
r.classList.remove("expanded");
}
}
initBoqUI(all, hierarchy);
// Enable editing (inputs) for all rate rows (even while hidden)
enableRateEditing(all, hierarchy);
// Calculate after overrides
applyRowCalculations(all);
// Rollups after calculations
recomputeAllRollups(all, hierarchy);
}
// Plain static + first load
document.addEventListener("DOMContentLoaded", bootBoq);
// Rails Turbo navigation
document.addEventListener("turbo:load", () => {
// New DOM, allow init again
const container = document.getElementById("boqContainer");
if (container) delete container.dataset.boqInit;
bootBoq();
});