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

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