@kruschdev/pascal-plugin-plumbing 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,9 @@
1
+ export * from './tables'
2
+ export * from './rules'
3
+ export * from './sizing'
4
+ export * from './framing-interop'
5
+ export * from './routing'
6
+ export * from './autopopulate'
7
+ export * from './schedule'
8
+ export * from './audit'
9
+ export * from './pricing'
@@ -0,0 +1,571 @@
1
+ /**
2
+ * Pure Priced Plumbing BOM Takeoff & CSV Export (`src/ipc/pricing.ts`).
3
+ * Framework-free: zero React, Three.js, or `@pascal-app/*` imports.
4
+ */
5
+
6
+ import {
7
+ type BomCostScope,
8
+ type PascalBomFragment,
9
+ createBomLine,
10
+ slugifyBomSku,
11
+ } from '@kruschdev/pascal-mep-kernel/bom'
12
+ import type { SceneNodeLike } from './framing-interop'
13
+ import { type PlumbingSchedule, buildPlumbingSchedule } from './schedule'
14
+ import {
15
+ type CodeEdition,
16
+ type EquipmentKind,
17
+ FIXTURE_SPECS,
18
+ type FixtureKind,
19
+ type ManifoldKind,
20
+ type OccupancyType,
21
+ type PipeMaterial,
22
+ type PipeNominalSize,
23
+ csvEscape,
24
+ round2,
25
+ } from './tables'
26
+
27
+ export type PlumbingPricingOptions = {
28
+ laborRateUsd?: number
29
+ materialMarkupPct?: number
30
+ salesTaxPct?: number
31
+ codeEdition?: CodeEdition
32
+ occupancy?: OccupancyType
33
+ supplyMaterial?: 'pex-a' | 'pex-b' | 'copper-l' | 'copper-m' | 'cpvc'
34
+ /** Optional precomputed schedule to avoid redundant scene scans. */
35
+ schedule?: PlumbingSchedule
36
+ }
37
+
38
+ export type PlumbingBomLine = {
39
+ category: 'Equipment' | 'Manifolds' | 'Fixtures' | 'Pipe & Tubing' | 'Fittings & Accessories'
40
+ item: string
41
+ unit: string
42
+ quantity: number
43
+ unitMaterialUsd: number
44
+ materialUsd: number
45
+ laborHours: number
46
+ laborUsd: number
47
+ totalUsd: number
48
+ }
49
+
50
+ export type PlumbingBomResult = {
51
+ lines: PlumbingBomLine[]
52
+ subtotalMaterialUsd: number
53
+ markupUsd: number
54
+ taxUsd: number
55
+ subtotalLaborUsd: number
56
+ totalLaborHours: number
57
+ grandTotalUsd: number
58
+ }
59
+
60
+ const EQUIPMENT_PRICES: Readonly<Record<EquipmentKind, { mat: number; hrs: number; label: string }>> = {
61
+ 'water-heater-tank-gas': { mat: 980, hrs: 5.0, label: 'Gas Tank Water Heater (50/75 gal)' },
62
+ 'water-heater-tank-electric': { mat: 780, hrs: 4.0, label: 'Electric Tank Water Heater (50/75 gal)' },
63
+ 'water-heater-tankless-gas': { mat: 1650, hrs: 7.5, label: 'Tankless Condensing Gas Water Heater' },
64
+ 'water-heater-hpwh': { mat: 1890, hrs: 5.5, label: 'Hybrid Heat Pump Water Heater' },
65
+ 'expansion-tank': { mat: 68, hrs: 0.75, label: 'Thermal Expansion Tank (IPC 607.3)' },
66
+ 'main-shutoff-prv': { mat: 215, hrs: 2.0, label: 'Main Shutoff + PRV + Check Valve Assembly' },
67
+ 'water-softener': { mat: 890, hrs: 3.5, label: 'Whole-House Water Softener + Brine Tank' },
68
+ 'sump-pump': { mat: 460, hrs: 4.0, label: 'Cast-Iron Sump Pump + Basin + Check Valve' },
69
+ 'sewage-ejector': { mat: 840, hrs: 5.5, label: 'Sewage Ejector Pump + Sealed Basin' },
70
+ 'recirc-pump': { mat: 295, hrs: 2.0, label: 'Hot Water Recirculation Pump + Aquastat' },
71
+ 'gas-meter': { mat: 320, hrs: 2.5, label: 'Gas Service Meter Bar & Regulator Assembly' },
72
+ 'backwater-valve': { mat: 195, hrs: 2.0, label: 'Mainline Backwater Valve (IPC 714)' },
73
+ }
74
+
75
+ const MANIFOLD_PRICES: Readonly<Record<ManifoldKind, { mat: number; hrs: number; label: string }>> = {
76
+ 'pex-homerun': { mat: 345, hrs: 3.5, label: 'PEX Home-Run Manifold w/ Ball Valves' },
77
+ 'copper-header': { mat: 265, hrs: 3.0, label: 'Type L Copper Distribution Header' },
78
+ 'gas-csst': { mat: 185, hrs: 2.0, label: 'CSST Fuel Gas Distribution Manifold' },
79
+ }
80
+
81
+ const FIXTURE_ROUGH_PRICES: Readonly<Record<FixtureKind, { mat: number; hrs: number }>> = {
82
+ 'water-closet': { mat: 290, hrs: 2.5 },
83
+ lavatory: { mat: 240, hrs: 2.0 },
84
+ 'kitchen-sink': { mat: 380, hrs: 2.5 },
85
+ bathtub: { mat: 520, hrs: 4.0 },
86
+ shower: { mat: 640, hrs: 4.5 },
87
+ 'tub-shower-combo': { mat: 680, hrs: 5.0 },
88
+ dishwasher: { mat: 65, hrs: 1.0 },
89
+ 'clothes-washer': { mat: 95, hrs: 1.5 },
90
+ 'laundry-sink': { mat: 210, hrs: 2.0 },
91
+ 'bar-sink': { mat: 190, hrs: 1.8 },
92
+ 'floor-drain': { mat: 85, hrs: 1.5 },
93
+ 'hose-bibb': { mat: 58, hrs: 1.0 },
94
+ bidet: { mat: 310, hrs: 2.0 },
95
+ 'garbage-disposal': { mat: 185, hrs: 1.2 },
96
+ urinal: { mat: 420, hrs: 3.0 },
97
+ 'mop-sink': { mat: 360, hrs: 2.8 },
98
+ 'drinking-fountain': { mat: 680, hrs: 3.0 },
99
+ 'grease-interceptor': { mat: 1150, hrs: 6.0 },
100
+ }
101
+
102
+ const PEX_ROLL_PRICE_BY_SIZE: Readonly<Record<PipeNominalSize, number>> = {
103
+ '3/8"': 52,
104
+ '1/2"': 62,
105
+ '3/4"': 95,
106
+ '1"': 145,
107
+ '1-1/4"': 215,
108
+ '1-1/2"': 295,
109
+ '2"': 440,
110
+ '2-1/2"': 620,
111
+ '3"': 840,
112
+ '4"': 1250,
113
+ '6"': 2100,
114
+ }
115
+
116
+ const COPPER_STICK_PRICE_BY_SIZE: Readonly<Record<PipeNominalSize, number>> = {
117
+ '3/8"': 42,
118
+ '1/2"': 54,
119
+ '3/4"': 86,
120
+ '1"': 128,
121
+ '1-1/4"': 176,
122
+ '1-1/2"': 235,
123
+ '2"': 345,
124
+ '2-1/2"': 490,
125
+ '3"': 660,
126
+ '4"': 1020,
127
+ '6"': 1850,
128
+ }
129
+
130
+ const DWV_PLASTIC_STICK_PRICE_BY_SIZE: Readonly<Record<PipeNominalSize, number>> = {
131
+ '3/8"': 8,
132
+ '1/2"': 9,
133
+ '3/4"': 10,
134
+ '1"': 11,
135
+ '1-1/4"': 11.5,
136
+ '1-1/2"': 12,
137
+ '2"': 16,
138
+ '2-1/2"': 22,
139
+ '3"': 28,
140
+ '4"': 42,
141
+ '6"': 86,
142
+ }
143
+
144
+ const CAST_IRON_STICK_PRICE_BY_SIZE: Readonly<Record<PipeNominalSize, number>> = {
145
+ '3/8"': 48,
146
+ '1/2"': 52,
147
+ '3/4"': 56,
148
+ '1"': 60,
149
+ '1-1/4"': 64,
150
+ '1-1/2"': 68,
151
+ '2"': 74,
152
+ '2-1/2"': 84,
153
+ '3"': 92,
154
+ '4"': 125,
155
+ '6"': 215,
156
+ }
157
+
158
+ const BLACK_IRON_STICK_PRICE_BY_SIZE: Readonly<Record<PipeNominalSize, number>> = {
159
+ '3/8"': 28,
160
+ '1/2"': 36,
161
+ '3/4"': 48,
162
+ '1"': 68,
163
+ '1-1/4"': 94,
164
+ '1-1/2"': 118,
165
+ '2"': 162,
166
+ '2-1/2"': 225,
167
+ '3"': 295,
168
+ '4"': 420,
169
+ '6"': 720,
170
+ }
171
+
172
+ const CSST_ROLL_PRICE_BY_SIZE: Readonly<Record<PipeNominalSize, number>> = {
173
+ '3/8"': 135,
174
+ '1/2"': 165,
175
+ '3/4"': 225,
176
+ '1"': 310,
177
+ '1-1/4"': 420,
178
+ '1-1/2"': 540,
179
+ '2"': 720,
180
+ '2-1/2"': 920,
181
+ '3"': 1150,
182
+ '4"': 1550,
183
+ '6"': 2400,
184
+ }
185
+
186
+ const CPVC_STICK_PRICE_BY_SIZE: Readonly<Record<PipeNominalSize, number>> = {
187
+ '3/8"': 12,
188
+ '1/2"': 14,
189
+ '3/4"': 20,
190
+ '1"': 30,
191
+ '1-1/4"': 42,
192
+ '1-1/2"': 56,
193
+ '2"': 78,
194
+ '2-1/2"': 115,
195
+ '3"': 155,
196
+ '4"': 225,
197
+ '6"': 390,
198
+ }
199
+
200
+ function pipeUnitPricing(material: PipeMaterial, size: PipeNominalSize): {
201
+ unit: string
202
+ unitFt: number
203
+ matPerUnit: number
204
+ hrsPer100Ft: number
205
+ } {
206
+ if (material === 'pex-a' || material === 'pex-b') {
207
+ const mat = PEX_ROLL_PRICE_BY_SIZE[size] ?? 95
208
+ return { unit: '100 ft roll', unitFt: 100, matPerUnit: mat, hrsPer100Ft: 3.2 }
209
+ }
210
+ if (material === 'copper-l' || material === 'copper-m') {
211
+ const mat = COPPER_STICK_PRICE_BY_SIZE[size] ?? 86
212
+ return { unit: '20 ft stick', unitFt: 20, matPerUnit: mat, hrsPer100Ft: 7.5 }
213
+ }
214
+ if (material === 'pvc-dwv' || material === 'abs-dwv') {
215
+ const mat = DWV_PLASTIC_STICK_PRICE_BY_SIZE[size] ?? 28
216
+ return { unit: '10 ft stick', unitFt: 10, matPerUnit: mat, hrsPer100Ft: 5.5 }
217
+ }
218
+ if (material === 'cast-iron') {
219
+ const mat = CAST_IRON_STICK_PRICE_BY_SIZE[size] ?? 92
220
+ return { unit: '10 ft stick', unitFt: 10, matPerUnit: mat, hrsPer100Ft: 9.0 }
221
+ }
222
+ if (material === 'black-iron' || material === 'csst') {
223
+ const mat =
224
+ material === 'csst'
225
+ ? (CSST_ROLL_PRICE_BY_SIZE[size] ?? 225)
226
+ : (BLACK_IRON_STICK_PRICE_BY_SIZE[size] ?? 48)
227
+ const unitFt = material === 'csst' ? 50 : 10
228
+ return { unit: `${unitFt} ft`, unitFt, matPerUnit: mat, hrsPer100Ft: material === 'csst' ? 4.0 : 8.5 }
229
+ }
230
+ if (material === 'cpvc') {
231
+ const mat = CPVC_STICK_PRICE_BY_SIZE[size] ?? 24
232
+ return { unit: '10 ft stick', unitFt: 10, matPerUnit: mat, hrsPer100Ft: 4.5 }
233
+ }
234
+ const rigidMat = size === '6"' ? 42 : size === '4"' ? 28 : 22
235
+ return { unit: '10 ft stick', unitFt: 10, matPerUnit: rigidMat, hrsPer100Ft: 4.5 }
236
+ }
237
+
238
+ /**
239
+ * Generate a complete priced plumbing BOM takeoff for the scene.
240
+ */
241
+ export function buildPlumbingBom(
242
+ nodes: Readonly<Record<string, SceneNodeLike>>,
243
+ options: PlumbingPricingOptions = {},
244
+ ): PlumbingBomResult {
245
+ const {
246
+ laborRateUsd: rawLaborRateUsd = 115,
247
+ materialMarkupPct: rawMaterialMarkupPct = 0,
248
+ salesTaxPct: rawSalesTaxPct = 0,
249
+ codeEdition = 'IPC-2021',
250
+ occupancy = 'residential',
251
+ supplyMaterial,
252
+ } = options
253
+ const laborRateUsd = Number.isFinite(rawLaborRateUsd) ? Math.max(0, rawLaborRateUsd) : 115
254
+ const materialMarkupPct = Number.isFinite(rawMaterialMarkupPct) ? Math.max(0, rawMaterialMarkupPct) : 0
255
+ const salesTaxPct = Number.isFinite(rawSalesTaxPct) ? Math.max(0, rawSalesTaxPct) : 0
256
+ const schedule =
257
+ options.schedule ??
258
+ buildPlumbingSchedule(nodes, {
259
+ codeEdition,
260
+ occupancy,
261
+ ...(supplyMaterial ? { supplyMaterial } : {}),
262
+ })
263
+ const all = Object.values(nodes)
264
+ const lines: PlumbingBomLine[] = []
265
+
266
+ const addLine = (
267
+ category: PlumbingBomLine['category'],
268
+ item: string,
269
+ unit: string,
270
+ quantity: number,
271
+ unitMaterialUsd: number,
272
+ laborHours: number,
273
+ ) => {
274
+ if (quantity <= 0) return
275
+ const mat = round2(quantity * unitMaterialUsd)
276
+ const hrs = round2(laborHours)
277
+ const lab = round2(hrs * laborRateUsd)
278
+ lines.push({
279
+ category,
280
+ item,
281
+ unit,
282
+ quantity,
283
+ unitMaterialUsd: round2(unitMaterialUsd),
284
+ materialUsd: mat,
285
+ laborHours: hrs,
286
+ laborUsd: lab,
287
+ totalUsd: round2(mat + lab),
288
+ })
289
+ }
290
+
291
+ // 1. Equipment (separate roughInOnly SKU-linked units so real-world water heater SKUs aren't double-billed)
292
+ const eqFullCounts = new Map<EquipmentKind, number>()
293
+ const eqRoughOnlyCounts = new Map<EquipmentKind, number>()
294
+ for (const n of all) {
295
+ if (n.type !== 'plumbing:equipment') continue
296
+ const k = (n.equipmentKind as EquipmentKind) || 'water-heater-tank-electric'
297
+ if (n.roughInOnly === true) {
298
+ eqRoughOnlyCounts.set(k, (eqRoughOnlyCounts.get(k) ?? 0) + 1)
299
+ } else {
300
+ eqFullCounts.set(k, (eqFullCounts.get(k) ?? 0) + 1)
301
+ }
302
+ }
303
+ for (const [k, qty] of eqFullCounts) {
304
+ const p = EQUIPMENT_PRICES[k] ?? { mat: 350, hrs: 2.5, label: k }
305
+ addLine('Equipment', p.label, 'ea', qty, p.mat, qty * p.hrs)
306
+ }
307
+ for (const [k, qty] of eqRoughOnlyCounts) {
308
+ const p = EQUIPMENT_PRICES[k] ?? { mat: 350, hrs: 2.5, label: k }
309
+ addLine('Equipment', `${p.label} (rough-in connection, SKU linked)`, 'ea', qty, round2(p.mat * 0.25), round2(qty * p.hrs * 0.55))
310
+ }
311
+
312
+ // 2. Manifolds (separate roughInOnly SKU-linked manifolds so catalog SKUs aren't double-billed)
313
+ const manFullCounts = new Map<ManifoldKind, number>()
314
+ const manRoughOnlyCounts = new Map<ManifoldKind, number>()
315
+ for (const n of all) {
316
+ if (n.type !== 'plumbing:manifold') continue
317
+ const k = (n.manifoldKind as ManifoldKind) || 'pex-homerun'
318
+ if (n.roughInOnly === true) {
319
+ manRoughOnlyCounts.set(k, (manRoughOnlyCounts.get(k) ?? 0) + 1)
320
+ } else {
321
+ manFullCounts.set(k, (manFullCounts.get(k) ?? 0) + 1)
322
+ }
323
+ }
324
+ for (const [k, qty] of manFullCounts) {
325
+ const p = MANIFOLD_PRICES[k] ?? { mat: 295, hrs: 3.0, label: k }
326
+ addLine('Manifolds', p.label, 'ea', qty, p.mat, qty * p.hrs)
327
+ }
328
+ for (const [k, qty] of manRoughOnlyCounts) {
329
+ const p = MANIFOLD_PRICES[k] ?? { mat: 295, hrs: 3.0, label: k }
330
+ addLine('Manifolds', `${p.label} (rough-in connection, SKU linked)`, 'ea', qty, round2(p.mat * 0.35), round2(qty * p.hrs * 0.55))
331
+ }
332
+
333
+ // 3. Fixtures (separate linked real-world SKU/furnishing rough-in-only assemblies so porcelain/trim isn't double-billed)
334
+ const fixFullCounts = new Map<FixtureKind, number>()
335
+ const fixRoughOnlyCounts = new Map<FixtureKind, number>()
336
+ for (const f of schedule.fixtures) {
337
+ if (f.roughInOnly) {
338
+ fixRoughOnlyCounts.set(f.fixtureKind, (fixRoughOnlyCounts.get(f.fixtureKind) ?? 0) + 1)
339
+ } else {
340
+ fixFullCounts.set(f.fixtureKind, (fixFullCounts.get(f.fixtureKind) ?? 0) + 1)
341
+ }
342
+ }
343
+ for (const [k, qty] of fixFullCounts) {
344
+ const p = FIXTURE_ROUGH_PRICES[k] ?? { mat: 200, hrs: 2.0 }
345
+ addLine('Fixtures', `${k} (rough-in + trim)`, 'ea', qty, p.mat, qty * p.hrs)
346
+ }
347
+ for (const [k, qty] of fixRoughOnlyCounts) {
348
+ const p = FIXTURE_ROUGH_PRICES[k] ?? { mat: 200, hrs: 2.0 }
349
+ addLine('Fixtures', `${k} (rough-in stub-out, SKU linked)`, 'ea', qty, round2(p.mat * 0.35), round2(qty * p.hrs * 0.55))
350
+ }
351
+
352
+ // 4. Pipe & Tubing (with 10% waste factor)
353
+ let totalPipeFt = 0
354
+ let totalDwvFt = 0
355
+ let totalSupplyFt = 0
356
+ for (const row of schedule.pipeSummary) {
357
+ const billedFt = row.totalLengthFt * 1.1
358
+ if (billedFt <= 0) continue
359
+ totalPipeFt += billedFt
360
+ if (row.system === 'dwv-drain' || row.system === 'dwv-vent') totalDwvFt += billedFt
361
+ if (row.system === 'cold-water' || row.system === 'hot-water' || row.system === 'hot-recirc') {
362
+ totalSupplyFt += billedFt
363
+ }
364
+ const p = pipeUnitPricing(row.material, row.nominalSize)
365
+ const qty = Math.max(1, Math.ceil(billedFt / p.unitFt))
366
+ addLine(
367
+ 'Pipe & Tubing',
368
+ `${row.nominalSize} ${row.material.toUpperCase()} (${row.system})`,
369
+ p.unit,
370
+ qty,
371
+ p.matPerUnit,
372
+ (billedFt / 100) * p.hrsPer100Ft,
373
+ )
374
+ }
375
+
376
+ // 5. Fittings, Hangers, P-Traps, Cleanouts, Angle Stops & Consumables
377
+ const externalSupplyKeys = new Set<string>()
378
+ for (const n of all) {
379
+ if (
380
+ n.type === 'plumbing:pipe-run' &&
381
+ (n.system === 'cold-water' || n.system === 'hot-water') &&
382
+ typeof n.targetNodeId === 'string' &&
383
+ n.targetNodeId
384
+ ) {
385
+ const target = nodes[n.targetNodeId]
386
+ if (target && !target.type.startsWith('plumbing:')) {
387
+ externalSupplyKeys.add(`${n.system}:${n.targetNodeId}`)
388
+ }
389
+ }
390
+ }
391
+ const externalSupplyStops = externalSupplyKeys.size
392
+ const fixTotal = schedule.fixtures.length
393
+ const dwvFixtureCount = schedule.fixtures.filter((f) => f.drainSize !== null || f.dfu > 0).length
394
+ const supplyFixtureCount =
395
+ schedule.fixtures.filter((f) => f.supplySize !== null || f.wsfuTotal > 0).length + externalSupplyStops
396
+ const hasDwvScope = totalDwvFt > 0 || dwvFixtureCount > 0
397
+ const hasSupplyScope = totalSupplyFt > 0 || supplyFixtureCount > 0
398
+ if (fixTotal > 0 || totalPipeFt > 0) {
399
+ const pTraps = schedule.fixtures.filter(
400
+ (f) => FIXTURE_SPECS[f.fixtureKind]?.needsPTrap && nodes[f.nodeId]?.hasPTrap !== false,
401
+ ).length
402
+ const cleanouts = hasDwvScope
403
+ ? Math.max(2, all.filter((n) => n.type === 'plumbing:pipe-run' && n.hasCleanout).length)
404
+ : 0
405
+ const dwvFittings = hasDwvScope ? Math.ceil(dwvFixtureCount * 3 + totalDwvFt / 10) : 0
406
+ const supplyFittings = hasSupplyScope ? Math.ceil(supplyFixtureCount * 4 + totalSupplyFt / 15) : 0
407
+ const hangers = Math.ceil(totalPipeFt / 4)
408
+ const NO_ANGLE_STOP_FIXTURES = new Set<FixtureKind>([
409
+ 'bathtub',
410
+ 'shower',
411
+ 'tub-shower-combo',
412
+ 'floor-drain',
413
+ 'hose-bibb',
414
+ 'garbage-disposal',
415
+ 'grease-interceptor',
416
+ 'urinal',
417
+ 'mop-sink',
418
+ 'drinking-fountain',
419
+ ])
420
+ const angleStops =
421
+ schedule.fixtures.reduce((sum, f) => {
422
+ if (NO_ANGLE_STOP_FIXTURES.has(f.fixtureKind)) return sum
423
+ return sum + (f.wsfuCold > 0 ? 1 : 0) + (f.wsfuHot > 0 ? 1 : 0)
424
+ }, 0) + externalSupplyStops
425
+
426
+ addLine('Fittings & Accessories', 'DWV Fittings (Wyes, Combos, Sweeps, San-Tees)', 'ea', dwvFittings, 7.5, dwvFittings * 0.08)
427
+ addLine('Fittings & Accessories', 'Supply Fittings & Crimp/Expansion Rings', 'ea', supplyFittings, 4.2, supplyFittings * 0.05)
428
+ addLine('Fittings & Accessories', 'P-Trap Assemblies (1-1/2" / 2")', 'ea', pTraps, 16, pTraps * 0.25)
429
+ addLine('Fittings & Accessories', 'Cleanout Tees & Brass/PVC Plugs', 'ea', cleanouts, 24, cleanouts * 0.4)
430
+ addLine('Fittings & Accessories', 'Quarter-Turn Angle Stops & Braided Supply Lines', 'ea', angleStops, 18, angleStops * 0.15)
431
+ addLine('Fittings & Accessories', 'Pipe Hangers, J-Hooks, Nail Plates & Solvent Cement', 'ea', hangers, 2.5, hangers * 0.04)
432
+ }
433
+
434
+ const subtotalMaterialUsd = round2(lines.reduce((s, l) => s + l.materialUsd, 0))
435
+ const subtotalLaborUsd = round2(lines.reduce((s, l) => s + l.laborUsd, 0))
436
+ const totalLaborHours = round2(lines.reduce((s, l) => s + l.laborHours, 0))
437
+ const markupUsd = round2(subtotalMaterialUsd * (materialMarkupPct / 100))
438
+ const taxUsd = round2((subtotalMaterialUsd + markupUsd) * (salesTaxPct / 100))
439
+ const grandTotalUsd = round2(subtotalMaterialUsd + markupUsd + taxUsd + subtotalLaborUsd)
440
+
441
+ return {
442
+ lines,
443
+ subtotalMaterialUsd,
444
+ markupUsd,
445
+ taxUsd,
446
+ subtotalLaborUsd,
447
+ totalLaborHours,
448
+ grandTotalUsd,
449
+ }
450
+ }
451
+
452
+ export function formatPlumbingBomCsv(bom: PlumbingBomResult): string {
453
+ const header = ['Category', 'Item', 'Unit', 'Qty', 'Unit Material ($)', 'Material ($)', 'Labor (hrs)', 'Labor ($)', 'Total ($)']
454
+ const rows = bom.lines.map((l) =>
455
+ [
456
+ l.category,
457
+ l.item,
458
+ l.unit,
459
+ l.quantity,
460
+ l.unitMaterialUsd.toFixed(2),
461
+ l.materialUsd.toFixed(2),
462
+ l.laborHours.toFixed(2),
463
+ l.laborUsd.toFixed(2),
464
+ l.totalUsd.toFixed(2),
465
+ ]
466
+ .map(csvEscape)
467
+ .join(','),
468
+ )
469
+ rows.push(['Summary', 'Material Subtotal', '', '', '', bom.subtotalMaterialUsd.toFixed(2), '', '', bom.subtotalMaterialUsd.toFixed(2)].join(','))
470
+ if (bom.markupUsd > 0) {
471
+ rows.push(['Summary', 'Material Markup', '', '', '', bom.markupUsd.toFixed(2), '', '', bom.markupUsd.toFixed(2)].join(','))
472
+ }
473
+ if (bom.taxUsd > 0) {
474
+ rows.push(['Summary', 'Sales Tax', '', '', '', bom.taxUsd.toFixed(2), '', '', bom.taxUsd.toFixed(2)].join(','))
475
+ }
476
+ rows.push(['Summary', 'Labor Subtotal', '', '', '', '', bom.totalLaborHours.toFixed(2), bom.subtotalLaborUsd.toFixed(2), bom.subtotalLaborUsd.toFixed(2)].join(','))
477
+ rows.push(['Summary', 'Grand Total', '', '', '', round2(bom.subtotalMaterialUsd + bom.markupUsd + bom.taxUsd).toFixed(2), bom.totalLaborHours.toFixed(2), bom.subtotalLaborUsd.toFixed(2), bom.grandTotalUsd.toFixed(2)].join(','))
478
+ return [header.join(','), ...rows].join('\n')
479
+ }
480
+
481
+ function classifyPlumbingBomLine(line: PlumbingBomLine): {
482
+ readonly costScope: BomCostScope
483
+ readonly csiMasterFormat?: string
484
+ readonly dedupeKey?: string
485
+ } {
486
+ const lower = line.item.toLowerCase()
487
+ if (line.category === 'Fixtures') {
488
+ if (/\b(?:rough-?in|carrier|flange|stub-?out)\b/.test(lower)) {
489
+ return { costScope: 'rough-in', csiMasterFormat: '22 41 00' }
490
+ }
491
+ if (lower.includes('water closet') || lower.includes('toilet')) {
492
+ return { costScope: 'allowance', csiMasterFormat: '22 41 13', dedupeKey: 'fixture:water-closet' }
493
+ }
494
+ if (lower.includes('lavatory')) {
495
+ return { costScope: 'allowance', csiMasterFormat: '22 41 16', dedupeKey: 'fixture:lavatory' }
496
+ }
497
+ if (lower.includes('kitchen sink')) {
498
+ return { costScope: 'allowance', csiMasterFormat: '22 41 16', dedupeKey: 'fixture:kitchen-sink' }
499
+ }
500
+ if (lower.includes('bathtub') || lower.includes('tub-shower') || lower.includes('tub / shower')) {
501
+ return { costScope: 'allowance', csiMasterFormat: '22 41 19', dedupeKey: 'fixture:bathtub' }
502
+ }
503
+ if (lower.includes('shower')) {
504
+ return { costScope: 'allowance', csiMasterFormat: '22 41 19', dedupeKey: 'fixture:shower' }
505
+ }
506
+ return { costScope: 'allowance', csiMasterFormat: '22 41 00' }
507
+ }
508
+ if (line.category === 'Equipment' || line.category === 'Manifolds') {
509
+ return { costScope: 'assembly' }
510
+ }
511
+ if (line.category === 'Fittings & Accessories') {
512
+ return { costScope: 'consumable' }
513
+ }
514
+ if (/\b(?:dwv|abs|pvc|drain|vent|waste|sanitary|cast\s*iron|no-hub)\b/.test(lower)) {
515
+ return { costScope: 'rough-in', csiMasterFormat: '22 13 16' }
516
+ }
517
+ return { costScope: 'rough-in', csiMasterFormat: '22 11 16' }
518
+ }
519
+
520
+ /**
521
+ * Convert a `PlumbingBomResult` into a canonical `@kruschdev/pascal-mep-kernel/bom` fragment (`pascal-bom/1.x`).
522
+ */
523
+ export function toPlumbingPascalBom(
524
+ bom: PlumbingBomResult,
525
+ options: { readonly laborRateUsd?: number } = {},
526
+ ): PascalBomFragment {
527
+ const effectiveLaborRate =
528
+ typeof options.laborRateUsd === 'number' && Number.isFinite(options.laborRateUsd)
529
+ ? Math.max(0, options.laborRateUsd)
530
+ : 125
531
+ const lines = bom.lines.map((line) => {
532
+ const meta = classifyPlumbingBomLine(line)
533
+ return createBomLine({
534
+ sourcePlugin: 'pascal-plugin-plumbing',
535
+ trade: 'plumbing',
536
+ category: line.category,
537
+ costScope: meta.costScope,
538
+ ...(meta.csiMasterFormat ? { csiMasterFormat: meta.csiMasterFormat } : {}),
539
+ ...(meta.dedupeKey ? { dedupeKey: meta.dedupeKey } : {}),
540
+ sku: slugifyBomSku('PLB', line.item),
541
+ name: line.item,
542
+ quantity: line.quantity,
543
+ unit: line.unit,
544
+ unitMaterialUsd: line.unitMaterialUsd,
545
+ extendedMaterialUsd: line.materialUsd,
546
+ extendedLaborHours: line.laborHours,
547
+ laborRateUsd: effectiveLaborRate,
548
+ extendedLaborUsd: line.laborUsd,
549
+ })
550
+ })
551
+
552
+ return {
553
+ plugin: 'pascal-plugin-plumbing',
554
+ pluginVersion: '0.2.1',
555
+ laborIncluded: true,
556
+ lines,
557
+ }
558
+ }
559
+
560
+ export function buildPlumbingPascalBom(
561
+ nodes: Readonly<Record<string, SceneNodeLike>>,
562
+ options: PlumbingPricingOptions = {},
563
+ ): PascalBomFragment {
564
+ const effectiveLaborRate =
565
+ typeof options.laborRateUsd === 'number' && Number.isFinite(options.laborRateUsd)
566
+ ? Math.max(0, options.laborRateUsd)
567
+ : 125
568
+ return toPlumbingPascalBom(buildPlumbingBom(nodes, { ...options, laborRateUsd: effectiveLaborRate }), {
569
+ laborRateUsd: effectiveLaborRate,
570
+ })
571
+ }