@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,653 @@
1
+ /**
2
+ * Pure Plumbing Schedule, Load Summary, and Electrical Power Coordination Table (`src/ipc/schedule.ts`).
3
+ * Framework-free: zero React, Three.js, or `@pascal-app/*` imports.
4
+ */
5
+
6
+ import {
7
+ type ElectricalPowerDemand,
8
+ type SceneNodeLike,
9
+ getEquipmentElectricalDemand,
10
+ getFixtureElectricalDemand,
11
+ resolveNodeLevelId,
12
+ } from './framing-interop'
13
+ import { polylineLengthM } from './routing'
14
+ import {
15
+ type FuelGasGraphSegment,
16
+ computeFuelGasDevelopedLengths,
17
+ sizeBuildingDrain,
18
+ sizeFuelGasPipe,
19
+ sizeSupplyPipe,
20
+ sizeVentStack,
21
+ sizeWaterHeater,
22
+ wsfuToGpm,
23
+ } from './sizing'
24
+ import {
25
+ type CodeEdition,
26
+ type EquipmentKind,
27
+ FIXTURE_SPECS,
28
+ type FixtureKind,
29
+ METERS_TO_FEET,
30
+ METERS_TO_INCHES,
31
+ type OccupancyType,
32
+ type PipeMaterial,
33
+ type PipeNominalSize,
34
+ type PlumbingSystem,
35
+ csvEscape,
36
+ getFixtureDfu,
37
+ getFixtureWsfu,
38
+ round2,
39
+ } from './tables'
40
+
41
+ export type FixtureScheduleRow = {
42
+ nodeId: string
43
+ name: string
44
+ roomName: string
45
+ fixtureKind: FixtureKind
46
+ dfu: number
47
+ wsfuCold: number
48
+ wsfuHot: number
49
+ wsfuTotal: number
50
+ trapSize: PipeNominalSize | null
51
+ drainSize: PipeNominalSize | null
52
+ ventSize: PipeNominalSize | null
53
+ supplySize: PipeNominalSize | null
54
+ roughInHeightIn: number
55
+ catalogSku?: string
56
+ furnishingSourceId?: string
57
+ roughInOnly?: boolean
58
+ }
59
+
60
+ export type PipeSystemSummaryRow = {
61
+ system: PlumbingSystem
62
+ material: PipeMaterial
63
+ nominalSize: PipeNominalSize
64
+ runCount: number
65
+ totalLengthFt: number
66
+ }
67
+
68
+ export type ElectricalCoordinationRow = {
69
+ sourceNodeId: string
70
+ sourceType: 'plumbing:equipment' | 'plumbing:fixture'
71
+ label: string
72
+ voltage: number
73
+ poles: 1 | 2 | 3
74
+ breakerAmps: number
75
+ loadVa: number
76
+ dedicatedCircuit: boolean
77
+ gfciRequired: boolean
78
+ wired: boolean
79
+ matchedElectricalDeviceId?: string
80
+ matchedCircuitNumber?: number
81
+ }
82
+
83
+ export type PlumbingLoadSummary = {
84
+ codeEdition: CodeEdition
85
+ occupancy: OccupancyType
86
+ fixtureCount: number
87
+ waterClosetCount: number
88
+ totalDfu: number
89
+ totalWsfuCold: number
90
+ totalWsfuHot: number
91
+ totalWsfu: number
92
+ peakDemandGpm: number
93
+ recommendedBuildingDrain: PipeNominalSize
94
+ recommendedVentStack: PipeNominalSize
95
+ recommendedColdMain: PipeNominalSize
96
+ recommendedHotMain: PipeNominalSize
97
+ coldVelocityFps: number
98
+ hotVelocityFps: number
99
+ totalGasBtuh: number
100
+ recommendedGasMain: PipeNominalSize | null
101
+ waterHeaterRecommendation: ReturnType<typeof sizeWaterHeater>
102
+ }
103
+
104
+ export type PlumbingSchedule = {
105
+ fixtures: FixtureScheduleRow[]
106
+ pipeSummary: PipeSystemSummaryRow[]
107
+ electricalCoordination: ElectricalCoordinationRow[]
108
+ loads: PlumbingLoadSummary
109
+ }
110
+
111
+ /**
112
+ * Resolve the authoritative electrical power demand for a plumbing equipment or fixture node.
113
+ * Recomputes from the current `equipmentKind` / `fixtureKind` whenever the unit is passive
114
+ * or persisted `electricalDemand` metadata is stale from a previous kind switch.
115
+ */
116
+ export function resolveNodeElectricalDemand(n: SceneNodeLike): ElectricalPowerDemand | null {
117
+ const raw = n.electricalDemand as Partial<ElectricalPowerDemand> | undefined
118
+
119
+ if (n.type === 'plumbing:equipment' && typeof n.equipmentKind === 'string') {
120
+ const kind = n.equipmentKind as EquipmentKind
121
+ const base = getEquipmentElectricalDemand(kind)
122
+ if (!base) return null
123
+ const rawWatts = typeof n.watts === 'number' && n.watts > 0 ? n.watts : undefined
124
+ const withRawWatts = rawWatts ? getEquipmentElectricalDemand(kind, rawWatts) : base
125
+ const labelMatchesKind =
126
+ typeof raw?.label === 'string' &&
127
+ (raw.label === base.label || raw.label === withRawWatts?.label)
128
+ const isStaleWatts =
129
+ rawWatts !== undefined &&
130
+ !labelMatchesKind &&
131
+ (rawWatts === raw?.loadVa || rawWatts === 4500)
132
+ const expected = isStaleWatts ? base : (withRawWatts ?? base)
133
+ if (
134
+ raw &&
135
+ typeof raw === 'object' &&
136
+ raw.required === true &&
137
+ raw.voltage === expected.voltage &&
138
+ raw.poles === expected.poles &&
139
+ raw.loadVa === expected.loadVa &&
140
+ raw.breakerAmps === expected.breakerAmps &&
141
+ raw.label === expected.label
142
+ ) {
143
+ return {
144
+ ...expected,
145
+ gfciRequired: typeof raw.gfciRequired === 'boolean' ? raw.gfciRequired : expected.gfciRequired,
146
+ afciRequired: typeof raw.afciRequired === 'boolean' ? raw.afciRequired : expected.afciRequired,
147
+ }
148
+ }
149
+ return expected
150
+ }
151
+
152
+ if (n.type === 'plumbing:fixture' && typeof n.fixtureKind === 'string') {
153
+ const expected = getFixtureElectricalDemand(n.fixtureKind as FixtureKind)
154
+ if (!expected) return null
155
+ if (
156
+ raw &&
157
+ typeof raw === 'object' &&
158
+ raw.required === true &&
159
+ raw.voltage === expected.voltage &&
160
+ raw.poles === expected.poles &&
161
+ raw.loadVa === expected.loadVa &&
162
+ raw.breakerAmps === expected.breakerAmps &&
163
+ raw.label === expected.label
164
+ ) {
165
+ return {
166
+ ...expected,
167
+ gfciRequired: typeof raw.gfciRequired === 'boolean' ? raw.gfciRequired : expected.gfciRequired,
168
+ afciRequired: typeof raw.afciRequired === 'boolean' ? raw.afciRequired : expected.afciRequired,
169
+ }
170
+ }
171
+ return expected
172
+ }
173
+
174
+ return null
175
+ }
176
+
177
+ /**
178
+ * Match powered plumbing equipment/fixtures against same-level `electrical:device` nodes in the scene
179
+ * so users see live `WIRED` vs `UNWIRED` coordination with `@kruschdev/pascal-plugin-electrical`.
180
+ */
181
+ export function buildElectricalCoordination(
182
+ nodes: Readonly<Record<string, SceneNodeLike>>,
183
+ ): ElectricalCoordinationRow[] {
184
+ const all = Object.values(nodes)
185
+ const elecDevices = all.filter((n) => n.type === 'electrical:device')
186
+
187
+ // Count how many devices share each (panelId, circuitNumber) so dedicated plumbing loads do not match shared countertop circuits
188
+ const circuitDeviceCounts = new Map<string, number>()
189
+ for (const d of elecDevices) {
190
+ if (typeof d.circuitNumber === 'number' && d.circuitNumber > 0) {
191
+ const key = `${String(d.panelId ?? '')}:${d.circuitNumber}`
192
+ circuitDeviceCounts.set(key, (circuitDeviceCounts.get(key) ?? 0) + 1)
193
+ }
194
+ }
195
+
196
+ const poweredUnits: Array<{
197
+ node: SceneNodeLike
198
+ demand: ElectricalPowerDemand
199
+ nodeLevelId: string | null
200
+ pos: readonly [number, number, number] | null
201
+ }> = []
202
+
203
+ for (const n of all) {
204
+ if (n.type !== 'plumbing:equipment' && n.type !== 'plumbing:fixture') continue
205
+ const demand = resolveNodeElectricalDemand(n)
206
+ if (!demand || !demand.required) continue
207
+ const pos =
208
+ Array.isArray(n.position) && n.position.length >= 3
209
+ ? ([Number(n.position[0]), Number(n.position[1]), Number(n.position[2])] as const)
210
+ : null
211
+ poweredUnits.push({
212
+ node: n,
213
+ demand,
214
+ nodeLevelId: resolveNodeLevelId(nodes, n),
215
+ pos,
216
+ })
217
+ }
218
+
219
+ // 2-pass matching with exclusive device claiming:
220
+ // Pass 1: Explicit `mepSourceNodeId` link (direct or inside metadata) wins first when electrically & level compatible
221
+ // Pass 2: Priority-ordered (highest poles/amps/dedicated first) closest unclaimed same-level proximity match
222
+ const claimedDeviceIds = new Set<string>()
223
+ const matchedBySourceId = new Map<string, SceneNodeLike>()
224
+
225
+ const isCompatibleDevice = (
226
+ unit: (typeof poweredUnits)[number],
227
+ d: SceneNodeLike,
228
+ ): boolean => {
229
+ // Never match devices across different building levels!
230
+ if (resolveNodeLevelId(nodes, d) !== unit.nodeLevelId) return false
231
+ const dPoles = typeof d.poles === 'number' ? d.poles : 1
232
+ const dAmps = typeof d.breakerAmps === 'number' ? d.breakerAmps : 15
233
+ if (dPoles < unit.demand.poles || dAmps < unit.demand.breakerAmps) return false
234
+ if (typeof d.voltage === 'number' && d.voltage > 0 && d.voltage !== unit.demand.voltage) {
235
+ return false
236
+ }
237
+ // When the plumbing load requires a dedicated circuit, require a dedicated/single-load circuit match
238
+ if (unit.demand.dedicatedCircuit) {
239
+ const isDedicatedKind = d.deviceKind === 'dedicated-240v' || dPoles >= 2
240
+ const cktKey =
241
+ typeof d.circuitNumber === 'number' && d.circuitNumber > 0
242
+ ? `${String(d.panelId ?? '')}:${d.circuitNumber}`
243
+ : null
244
+ const isSingleLoadCircuit = cktKey !== null && (circuitDeviceCounts.get(cktKey) ?? 0) === 1
245
+ if (!isDedicatedKind && !isSingleLoadCircuit) return false
246
+ }
247
+ return true
248
+ }
249
+
250
+ for (const unit of poweredUnits) {
251
+ for (const d of elecDevices) {
252
+ if (claimedDeviceIds.has(d.id)) continue
253
+ const meta = d.metadata as { mepSourceNodeId?: string } | undefined
254
+ if (
255
+ (d.mepSourceNodeId === unit.node.id || meta?.mepSourceNodeId === unit.node.id) &&
256
+ isCompatibleDevice(unit, d)
257
+ ) {
258
+ matchedBySourceId.set(unit.node.id, d)
259
+ claimedDeviceIds.add(d.id)
260
+ break
261
+ }
262
+ }
263
+ }
264
+
265
+ const prioritizedUnits = [...poweredUnits].sort(
266
+ (a, b) =>
267
+ b.demand.poles - a.demand.poles ||
268
+ b.demand.breakerAmps - a.demand.breakerAmps ||
269
+ Number(b.demand.dedicatedCircuit) - Number(a.demand.dedicatedCircuit),
270
+ )
271
+
272
+ for (const unit of prioritizedUnits) {
273
+ if (matchedBySourceId.has(unit.node.id) || !unit.pos) continue
274
+ let bestDevice: SceneNodeLike | undefined
275
+ let bestDist = Infinity
276
+ for (const d of elecDevices) {
277
+ if (claimedDeviceIds.has(d.id)) continue
278
+ if (!isCompatibleDevice(unit, d)) continue
279
+
280
+ const dPos = Array.isArray(d.position) && d.position.length >= 3 ? d.position : null
281
+ if (!dPos) continue
282
+ const dist = Math.hypot(unit.pos[0] - dPos[0], unit.pos[2] - dPos[2])
283
+ if (dist > 1.5) continue
284
+ if (dist < bestDist) {
285
+ bestDist = dist
286
+ bestDevice = d
287
+ }
288
+ }
289
+ if (bestDevice) {
290
+ matchedBySourceId.set(unit.node.id, bestDevice)
291
+ claimedDeviceIds.add(bestDevice.id)
292
+ }
293
+ }
294
+
295
+ const rows: ElectricalCoordinationRow[] = poweredUnits.map(({ node: n, demand }) => {
296
+ const matchedDevice = matchedBySourceId.get(n.id)
297
+ return {
298
+ sourceNodeId: n.id,
299
+ sourceType: n.type as 'plumbing:equipment' | 'plumbing:fixture',
300
+ label: demand.label,
301
+ voltage: demand.voltage,
302
+ poles: demand.poles,
303
+ breakerAmps: demand.breakerAmps,
304
+ loadVa: demand.loadVa,
305
+ dedicatedCircuit: demand.dedicatedCircuit,
306
+ gfciRequired: demand.gfciRequired,
307
+ wired: Boolean(matchedDevice),
308
+ matchedElectricalDeviceId: matchedDevice?.id,
309
+ matchedCircuitNumber:
310
+ typeof matchedDevice?.circuitNumber === 'number' ? matchedDevice.circuitNumber : undefined,
311
+ }
312
+ })
313
+ return rows
314
+ }
315
+
316
+ const scheduleCache = new WeakMap<
317
+ Readonly<Record<string, SceneNodeLike>>,
318
+ Map<string, PlumbingSchedule>
319
+ >()
320
+
321
+ /**
322
+ * Compile the full Fixture Schedule, Pipe System Summary, Load Summary, and Electrical Coordination Table.
323
+ * WeakMap-memoized per scene nodes object reference.
324
+ */
325
+ export function buildPlumbingSchedule(
326
+ nodes: Readonly<Record<string, SceneNodeLike>>,
327
+ options: {
328
+ codeEdition?: CodeEdition
329
+ occupancy?: OccupancyType
330
+ supplyMaterial?: 'pex-a' | 'pex-b' | 'copper-l' | 'copper-m' | 'cpvc'
331
+ } = {},
332
+ ): PlumbingSchedule {
333
+ const { codeEdition = 'IPC-2021', occupancy = 'residential' } = options
334
+ const cacheKey = `${codeEdition}|${occupancy}|${options.supplyMaterial ?? '__auto__'}`
335
+ let byKey = scheduleCache.get(nodes)
336
+ if (!byKey) {
337
+ byKey = new Map()
338
+ scheduleCache.set(nodes, byKey)
339
+ }
340
+ const cached = byKey.get(cacheKey)
341
+ if (cached) return cached
342
+
343
+ const all = Object.values(nodes)
344
+
345
+ const fixtures: FixtureScheduleRow[] = []
346
+ let totalDfu = 0
347
+ let totalWsfuCold = 0
348
+ let totalWsfuHot = 0
349
+ let totalWsfu = 0
350
+ let wcCount = 0
351
+
352
+ for (const n of all) {
353
+ if (n.type !== 'plumbing:fixture') continue
354
+ const kind = (typeof n.fixtureKind === 'string' && n.fixtureKind in FIXTURE_SPECS
355
+ ? n.fixtureKind
356
+ : 'lavatory') as FixtureKind
357
+ const spec = FIXTURE_SPECS[kind]
358
+ const ratedWsfu = getFixtureWsfu(kind, occupancy)
359
+ const dfu =
360
+ typeof n.dfu === 'number' && n.dfu !== spec.dfuIpc && n.dfu !== spec.dfuUpc
361
+ ? n.dfu
362
+ : getFixtureDfu(kind, codeEdition)
363
+ const wsfuCold =
364
+ occupancy === 'commercial'
365
+ ? Math.max(ratedWsfu.cold, typeof n.wsfuCold === 'number' ? n.wsfuCold : 0)
366
+ : typeof n.wsfuCold === 'number'
367
+ ? n.wsfuCold
368
+ : ratedWsfu.cold
369
+ const wsfuHot =
370
+ occupancy === 'commercial'
371
+ ? Math.max(ratedWsfu.hot, typeof n.wsfuHot === 'number' ? n.wsfuHot : 0)
372
+ : typeof n.wsfuHot === 'number'
373
+ ? n.wsfuHot
374
+ : ratedWsfu.hot
375
+ const hasCustomBranchWsfu = wsfuCold !== ratedWsfu.cold || wsfuHot !== ratedWsfu.hot
376
+ const hasDefaultTotalWsfu = n.wsfuTotal === spec.wsfuTotal || n.wsfuTotal === ratedWsfu.total
377
+ const wsfuTotal =
378
+ hasCustomBranchWsfu && hasDefaultTotalWsfu
379
+ ? round2(wsfuCold + wsfuHot)
380
+ : occupancy === 'commercial'
381
+ ? Math.max(ratedWsfu.total, typeof n.wsfuTotal === 'number' ? n.wsfuTotal : 0)
382
+ : typeof n.wsfuTotal === 'number'
383
+ ? n.wsfuTotal
384
+ : ratedWsfu.total
385
+
386
+ totalDfu += dfu
387
+ totalWsfuCold += wsfuCold
388
+ totalWsfuHot += wsfuHot
389
+ totalWsfu += wsfuTotal
390
+ if (kind === 'water-closet') wcCount += 1
391
+
392
+ fixtures.push({
393
+ nodeId: n.id,
394
+ name: typeof n.name === 'string' && n.name ? n.name : spec.label,
395
+ roomName: typeof n.roomName === 'string' && n.roomName ? n.roomName : 'General',
396
+ fixtureKind: kind,
397
+ dfu,
398
+ wsfuCold,
399
+ wsfuHot,
400
+ wsfuTotal,
401
+ trapSize: (n.trapSize as PipeNominalSize | null | undefined) ?? spec.minTrapIn,
402
+ drainSize: (n.drainSize as PipeNominalSize | null | undefined) ?? spec.minDrainIn,
403
+ ventSize: (n.ventSize as PipeNominalSize | null | undefined) ?? spec.minVentIn,
404
+ supplySize: (n.supplySize as PipeNominalSize | null | undefined) ?? spec.supplySizeIn,
405
+ roughInHeightIn: Math.round(spec.roughInHeightM * METERS_TO_INCHES),
406
+ ...(typeof n.catalogSku === 'string' && n.catalogSku ? { catalogSku: n.catalogSku } : {}),
407
+ ...(typeof n.furnishingSourceId === 'string' && n.furnishingSourceId
408
+ ? { furnishingSourceId: n.furnishingSourceId }
409
+ : {}),
410
+ ...(n.roughInOnly === true ? { roughInOnly: true } : {}),
411
+ })
412
+ }
413
+
414
+ // Group pipe runs by (system, material, nominalSize)
415
+ const pipeMap = new Map<string, PipeSystemSummaryRow>()
416
+ const supplyMatCounts = new Map<'pex-a' | 'pex-b' | 'copper-l' | 'copper-m' | 'cpvc', number>()
417
+ const gasGraphSegments: FuelGasGraphSegment[] = []
418
+ let applianceGasBtuh = 0
419
+ let maxPipeGasBtuh = 0
420
+ const countedGasTargetIds = new Set<string>()
421
+ const countedExternalColdTargetIds = new Set<string>()
422
+ let hasCsstGas = false
423
+ let detectedWhFuel: 'gas' | 'electric' | 'hpwh' | 'tankless-gas' | undefined
424
+
425
+ const countedExternalHotTargetIds = new Set<string>()
426
+ // First collect equipment/HVAC gas loads (and seed manifolds / gas-meters so trunk gas runs targeting them never double-count)
427
+ for (const n of all) {
428
+ if (n.type === 'plumbing:manifold' || (n.type === 'plumbing:equipment' && n.equipmentKind === 'gas-meter')) {
429
+ countedGasTargetIds.add(n.id)
430
+ }
431
+ if (
432
+ ((n.type === 'plumbing:equipment' && n.equipmentKind !== 'gas-meter') ||
433
+ n.type === 'hvac:equipment') &&
434
+ typeof n.gasBtuh === 'number' &&
435
+ n.gasBtuh > 0
436
+ ) {
437
+ applianceGasBtuh += n.gasBtuh
438
+ countedGasTargetIds.add(n.id)
439
+ }
440
+ }
441
+
442
+ for (const n of all) {
443
+ if (n.type === 'plumbing:manifold' && n.manifoldKind === 'gas-csst') {
444
+ hasCsstGas = true
445
+ }
446
+ if (n.type === 'plumbing:equipment' && typeof n.equipmentKind === 'string' && !detectedWhFuel) {
447
+ if (n.equipmentKind === 'water-heater-tank-electric') detectedWhFuel = 'electric'
448
+ else if (n.equipmentKind === 'water-heater-hpwh') detectedWhFuel = 'hpwh'
449
+ else if (n.equipmentKind === 'water-heater-tankless-gas') detectedWhFuel = 'tankless-gas'
450
+ else if (n.equipmentKind === 'water-heater-tank-gas') detectedWhFuel = 'gas'
451
+ }
452
+ if (n.type !== 'plumbing:pipe-run') continue
453
+ const system = (n.system as PlumbingSystem) || 'cold-water'
454
+ const material = (n.material as PipeMaterial) || 'pex-a'
455
+ const nominalSize = (n.nominalSize as PipeNominalSize) || '1/2"'
456
+ const path = Array.isArray(n.path) ? (n.path as ReadonlyArray<readonly [number, number, number]>) : []
457
+ const lengthFt = polylineLengthM(path) * METERS_TO_FEET
458
+
459
+ // Include auxiliary cold/hot branch loads targeting external catalog/furnishing appliances (e.g. fridge ice makers)
460
+ if (
461
+ (system === 'cold-water' || system === 'hot-water') &&
462
+ typeof n.targetNodeId === 'string' &&
463
+ n.targetNodeId &&
464
+ typeof n.wsfuLoad === 'number' &&
465
+ n.wsfuLoad > 0
466
+ ) {
467
+ const targetNode = nodes[n.targetNodeId]
468
+ if (targetNode && !targetNode.type.startsWith('plumbing:')) {
469
+ if (system === 'cold-water' && !countedExternalColdTargetIds.has(n.targetNodeId)) {
470
+ countedExternalColdTargetIds.add(n.targetNodeId)
471
+ totalWsfuCold += n.wsfuLoad
472
+ totalWsfu += n.wsfuLoad
473
+ } else if (system === 'hot-water' && !countedExternalHotTargetIds.has(n.targetNodeId)) {
474
+ countedExternalHotTargetIds.add(n.targetNodeId)
475
+ totalWsfuHot += n.wsfuLoad
476
+ totalWsfu += n.wsfuLoad
477
+ }
478
+ }
479
+ }
480
+
481
+ if (
482
+ (system === 'cold-water' || system === 'hot-water') &&
483
+ (material === 'pex-a' ||
484
+ material === 'pex-b' ||
485
+ material === 'copper-l' ||
486
+ material === 'copper-m' ||
487
+ material === 'cpvc')
488
+ ) {
489
+ supplyMatCounts.set(material, (supplyMatCounts.get(material) ?? 0) + 1)
490
+ }
491
+
492
+ if (system === 'fuel-gas') {
493
+ gasGraphSegments.push({
494
+ id: n.id,
495
+ lengthFt,
496
+ ...(typeof n.sourceNodeId === 'string' && n.sourceNodeId ? { sourceNodeId: n.sourceNodeId } : {}),
497
+ ...(typeof n.targetNodeId === 'string' && n.targetNodeId ? { targetNodeId: n.targetNodeId } : {}),
498
+ })
499
+ if (material === 'csst') hasCsstGas = true
500
+ if (typeof n.gasBtuh === 'number' && n.gasBtuh > 0) {
501
+ if (n.gasBtuh > maxPipeGasBtuh) maxPipeGasBtuh = n.gasBtuh
502
+ if (typeof n.targetNodeId === 'string' && n.targetNodeId && !countedGasTargetIds.has(n.targetNodeId)) {
503
+ countedGasTargetIds.add(n.targetNodeId)
504
+ applianceGasBtuh += n.gasBtuh
505
+ }
506
+ }
507
+ }
508
+
509
+ const key = `${system}|${material}|${nominalSize}`
510
+ const existing = pipeMap.get(key)
511
+ if (existing) {
512
+ existing.runCount += 1
513
+ existing.totalLengthFt += lengthFt
514
+ } else {
515
+ pipeMap.set(key, {
516
+ system,
517
+ material,
518
+ nominalSize,
519
+ runCount: 1,
520
+ totalLengthFt: lengthFt,
521
+ })
522
+ }
523
+ }
524
+ for (const row of pipeMap.values()) {
525
+ row.totalLengthFt = round2(row.totalLengthFt)
526
+ }
527
+
528
+ let effectiveSupplyMaterial: 'pex-a' | 'pex-b' | 'copper-l' | 'copper-m' | 'cpvc' =
529
+ options.supplyMaterial ?? 'pex-a'
530
+ if (!options.supplyMaterial && supplyMatCounts.size > 0) {
531
+ let bestMat: 'pex-a' | 'pex-b' | 'copper-l' | 'copper-m' | 'cpvc' = 'pex-a'
532
+ let bestCount = -1
533
+ for (const [mat, cnt] of supplyMatCounts.entries()) {
534
+ if (cnt > bestCount) {
535
+ bestCount = cnt
536
+ bestMat = mat
537
+ }
538
+ }
539
+ effectiveSupplyMaterial = bestMat
540
+ }
541
+ const totalGasBtuh = Math.max(applianceGasBtuh, maxPipeGasBtuh)
542
+
543
+ const flushType = occupancy === 'commercial' ? 'flushometer' : 'flush-tank'
544
+ const drainSizing = sizeBuildingDrain({
545
+ totalDfu,
546
+ slopeInPerFt: 0.25,
547
+ hasWaterCloset: wcCount > 0,
548
+ waterClosetCount: wcCount,
549
+ codeEdition,
550
+ })
551
+ const ventSizing = sizeVentStack({ totalDfu, isMainStack: true })
552
+ const coldMain = sizeSupplyPipe({
553
+ wsfu: totalWsfu,
554
+ material: effectiveSupplyMaterial,
555
+ isHot: false,
556
+ minSize: '3/4"',
557
+ flushType,
558
+ })
559
+ const hotMain = sizeSupplyPipe({
560
+ wsfu: totalWsfuHot,
561
+ material: effectiveSupplyMaterial,
562
+ isHot: true,
563
+ minSize: '3/4"',
564
+ flushType: 'flush-tank',
565
+ })
566
+
567
+ const peakDemandGpm = wsfuToGpm(totalWsfu, flushType)
568
+ const hotPeakDemandGpm = wsfuToGpm(totalWsfuHot, 'flush-tank')
569
+ const bathroomCount = Math.max(1, wcCount)
570
+ const whRec = sizeWaterHeater({
571
+ bathrooms: bathroomCount,
572
+ bedrooms: Math.max(2, bathroomCount + 1),
573
+ occupancy,
574
+ fuelType: detectedWhFuel ?? 'gas',
575
+ peakGpm: totalWsfuHot > 0 ? hotPeakDemandGpm : totalWsfu > 0 ? 0 : undefined,
576
+ })
577
+
578
+ // Conservative IFGC 402.4.1 sizing: traverse connected gas networks for root-to-most-remote-outlet developed length
579
+ const longestGasFt = computeFuelGasDevelopedLengths(gasGraphSegments).maxDevelopedLengthFt
580
+ const detectedGasMaterial: 'black-iron' | 'csst' = hasCsstGas ? 'csst' : 'black-iron'
581
+ const gasSizing =
582
+ totalGasBtuh > 0
583
+ ? sizeFuelGasPipe({
584
+ totalBtuh: totalGasBtuh,
585
+ longestRunFt: Math.max(25, longestGasFt),
586
+ material: detectedGasMaterial,
587
+ })
588
+ : null
589
+
590
+ const result: PlumbingSchedule = {
591
+ fixtures,
592
+ pipeSummary: [...pipeMap.values()].sort((a, b) => a.system.localeCompare(b.system)),
593
+ electricalCoordination: buildElectricalCoordination(nodes),
594
+ loads: {
595
+ codeEdition,
596
+ occupancy,
597
+ fixtureCount: fixtures.length,
598
+ waterClosetCount: wcCount,
599
+ totalDfu: round2(totalDfu),
600
+ totalWsfuCold: round2(totalWsfuCold),
601
+ totalWsfuHot: round2(totalWsfuHot),
602
+ totalWsfu: round2(totalWsfu),
603
+ peakDemandGpm,
604
+ recommendedBuildingDrain: drainSizing.recommendedSize,
605
+ recommendedVentStack: ventSizing.recommendedSize,
606
+ recommendedColdMain: coldMain.size,
607
+ recommendedHotMain: hotMain.size,
608
+ coldVelocityFps: coldMain.velocityFps,
609
+ hotVelocityFps: hotMain.velocityFps,
610
+ totalGasBtuh,
611
+ recommendedGasMain: gasSizing ? gasSizing.recommendedSize : null,
612
+ waterHeaterRecommendation: whRec,
613
+ },
614
+ }
615
+ byKey.set(cacheKey, result)
616
+ return result
617
+ }
618
+
619
+ export function formatPlumbingScheduleCsv(schedule: PlumbingSchedule): string {
620
+ const header = [
621
+ 'Fixture',
622
+ 'Room',
623
+ 'Kind',
624
+ 'DFU',
625
+ 'Cold WSFU',
626
+ 'Hot WSFU',
627
+ 'Total WSFU',
628
+ 'Trap',
629
+ 'Drain',
630
+ 'Vent',
631
+ 'Supply',
632
+ 'Rough-In (in AFF)',
633
+ ]
634
+ const rows = schedule.fixtures.map((f) =>
635
+ [
636
+ f.name,
637
+ f.roomName,
638
+ f.fixtureKind,
639
+ f.dfu,
640
+ f.wsfuCold,
641
+ f.wsfuHot,
642
+ f.wsfuTotal,
643
+ f.trapSize ?? '-',
644
+ f.drainSize ?? '-',
645
+ f.ventSize ?? '-',
646
+ f.supplySize ?? '-',
647
+ f.roughInHeightIn,
648
+ ]
649
+ .map(csvEscape)
650
+ .join(','),
651
+ )
652
+ return [header.join(','), ...rows].join('\n')
653
+ }