14 Commits

Author SHA1 Message Date
0b78950d14 feat: Adds equipment info database tests.
All checks were successful
CI / Linux Tests (push) Successful in 5m26s
2026-01-30 15:16:09 -05:00
754019eac4 feat: Adds component loss database tests.
All checks were successful
CI / Linux Tests (push) Successful in 5m26s
2026-01-30 14:15:50 -05:00
a51e1b34d0 feat: Adds project database tests.
All checks were successful
CI / Linux Tests (push) Successful in 5m24s
2026-01-30 14:02:58 -05:00
c32ffcff8c feat: Begins live database client tests.
All checks were successful
CI / Linux Tests (push) Successful in 5m35s
2026-01-30 12:02:11 -05:00
4f3cc2c7ea WIP: Cleans up ManualDClient and adds some more document strings.
Some checks failed
CI / Linux Tests (push) Failing after 7m3s
2026-01-29 22:56:39 -05:00
9b618d55fa WIP: Adds more tagged types for rectangular size calculations. 2026-01-29 20:50:33 -05:00
9379774fae feat: Begin using Tagged types
All checks were successful
CI / Linux Tests (push) Successful in 5m23s
2026-01-29 17:10:35 -05:00
18a5ef06d3 feat: Rename items in database client for consistency.
All checks were successful
CI / Linux Tests (push) Successful in 5m24s
2026-01-29 15:47:24 -05:00
6723f7a410 feat: Adds some documentation strings in ManualDCore module. 2026-01-29 15:16:26 -05:00
5440024038 feat: Renames EffectiveLength to EquivalentLength
All checks were successful
CI / Linux Tests (push) Successful in 9m34s
2026-01-29 11:25:20 -05:00
f005b43936 feat: Try to build image in ci instead of relying on just.
All checks were successful
CI / Linux Tests (push) Successful in 5m46s
2026-01-29 10:52:07 -05:00
f44b35ab3d feat: Try extractions/setup-just
Some checks failed
CI / Linux Tests (push) Failing after 7s
2026-01-29 10:46:00 -05:00
bbf9a8b390 feat: Setup just directly in ci workflow
Some checks failed
CI / Linux Tests (push) Failing after 10s
2026-01-29 10:43:49 -05:00
c52cee212f feat: Adds ci workflow.
Some checks failed
CI / Linux Tests (push) Failing after 5s
2026-01-29 10:36:29 -05:00
72 changed files with 1716 additions and 1120 deletions

31
.gitea/workflows/ci.yaml Normal file
View File

@@ -0,0 +1,31 @@
name: CI
on:
push:
branches:
- main
- dev
pull_request:
workflow_dispatch:
jobs:
ubuntu:
name: Linux Tests
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
- name: Setup QEMU
uses: docker/setup-qemu-action@v3
- name: Setup buildx
uses: docker/setup-buildx-action@v3
- name: Build test image
uses: docker/build-push-action@v6
with:
context: .
file: docker/Dockerfile.test
push: false
load: true
tags: michael/ductcalc:test
- name: Run Tests
run: |
docker run --rm michael/ductcalc:test swift test

1
.gitignore vendored
View File

@@ -13,3 +13,4 @@ tailwindcss
*.pdf
.env
.env*
default.profraw

View File

@@ -1,5 +1,5 @@
{
"originHash" : "c3efcfd33bc1490f59ae406e4e5292027b2d01cafee9fc625652213505df50fb",
"originHash" : "300df15f5af26da69cfcf959d16ee1b9eada6101dc105a17fc01ddd244d476b4",
"pins" : [
{
"identity" : "async-http-client",
@@ -397,6 +397,15 @@
"version" : "1.6.3"
}
},
{
"identity" : "swift-tagged",
"kind" : "remoteSourceControl",
"location" : "https://github.com/pointfreeco/swift-tagged",
"state" : {
"revision" : "3907a9438f5b57d317001dc99f3f11b46882272b",
"version" : "0.10.0"
}
},
{
"identity" : "swift-url-routing",
"kind" : "remoteSourceControl",

View File

@@ -26,6 +26,7 @@ let package = Package(
.package(url: "https://github.com/apple/swift-nio.git", from: "2.65.0"),
.package(url: "https://github.com/pointfreeco/swift-dependencies", from: "1.0.0"),
.package(url: "https://github.com/pointfreeco/swift-snapshot-testing", from: "1.12.0"),
.package(url: "https://github.com/pointfreeco/swift-tagged", from: "0.6.0"),
.package(url: "https://github.com/pointfreeco/swift-url-routing.git", from: "0.6.2"),
.package(url: "https://github.com/pointfreeco/vapor-routing.git", from: "0.1.3"),
.package(url: "https://github.com/pointfreeco/swift-case-paths.git", from: "1.6.0"),
@@ -61,6 +62,12 @@ let package = Package(
.product(name: "Vapor", package: "vapor"),
]
),
.testTarget(
name: "ApiRouteTests",
dependencies: [
.target(name: "ManualDCore")
]
),
.target(
name: "AuthClient",
dependencies: [
@@ -80,7 +87,15 @@ let package = Package(
.product(name: "Vapor", package: "vapor"),
]
),
.testTarget(
name: "DatabaseClientTests",
dependencies: [
.target(name: "App"),
.target(name: "DatabaseClient"),
.product(name: "DependenciesTestSupport", package: "swift-dependencies"),
.product(name: "FluentSQLiteDriver", package: "fluent-sqlite-driver"),
]
),
.target(
name: "EnvClient",
dependencies: [
@@ -120,11 +135,10 @@ let package = Package(
.target(name: "HTMLSnapshotTesting"),
.target(name: "PdfClient"),
.product(name: "SnapshotTesting", package: "swift-snapshot-testing"),
],
resources: [
.copy("__Snapshots__")
]
// ,
// resources: [
// .copy("__Snapshots__")
// ]
),
.target(
name: "ProjectClient",
@@ -138,24 +152,19 @@ let package = Package(
.target(
name: "ManualDCore",
dependencies: [
.product(name: "CasePaths", package: "swift-case-paths"),
.product(name: "Dependencies", package: "swift-dependencies"),
.product(name: "Fluent", package: "fluent"),
.product(name: "URLRouting", package: "swift-url-routing"),
.product(name: "CasePaths", package: "swift-case-paths"),
]
),
.testTarget(
name: "ApiRouteTests",
dependencies: [
.target(name: "ManualDCore")
]
),
.target(
name: "ManualDClient",
dependencies: [
"ManualDCore",
.target(name: "ManualDCore"),
.product(name: "Dependencies", package: "swift-dependencies"),
.product(name: "DependenciesMacros", package: "swift-dependencies"),
.product(name: "Tagged", package: "swift-tagged"),
]
),
.target(

View File

@@ -104,14 +104,14 @@ extension SiteRoute.Api.ComponentLossRoute {
switch self {
case .create(let request):
return try await database.componentLoss.create(request)
return try await database.componentLosses.create(request)
case .delete(let id):
try await database.componentLoss.delete(id)
try await database.componentLosses.delete(id)
return nil
case .fetch(let projectID):
return try await database.componentLoss.fetch(projectID)
return try await database.componentLosses.fetch(projectID)
case .get(let id):
guard let room = try await database.componentLoss.get(id) else {
guard let room = try await database.componentLosses.get(id) else {
logger.error("Component loss not found for id: \(id)")
throw ApiError("Component loss not found.")
}

View File

@@ -31,7 +31,7 @@ struct DependenciesMiddleware: AsyncMiddleware {
try await values.yield {
try await withDependencies {
$0.apiController = apiController
$0.authClient = .live(on: request)
$0.auth = .live(on: request)
$0.database = database
// $0.dateFormatter = .liveValue
$0.viewController = viewController

View File

@@ -65,9 +65,7 @@ private func setupDatabase(
let databaseClient = makeDatabaseClient(app.db)
if app.environment != .testing {
try await app.migrations.add(databaseClient.migrations())
}
try await app.migrations.add(databaseClient.migrations())
return databaseClient
}

View File

@@ -5,17 +5,23 @@ import ManualDCore
import Vapor
extension DependencyValues {
public var authClient: AuthClient {
/// Authentication dependency, for handling authentication tasks.
public var auth: AuthClient {
get { self[AuthClient.self] }
set { self[AuthClient.self] = newValue }
}
}
/// Represents authentication tasks that are used in the application.
@DependencyClient
public struct AuthClient: Sendable {
/// Create a new user and log them in.
public var createAndLogin: @Sendable (User.Create) async throws -> User
/// Get the current user.
public var currentUser: @Sendable () throws -> User
/// Login a user.
public var login: @Sendable (User.Login) async throws -> User
/// Logout a user.
public var logout: @Sendable () throws -> Void
}

View File

@@ -4,23 +4,131 @@ import FluentKit
import ManualDCore
extension DependencyValues {
/// The database dependency.
public var database: DatabaseClient {
get { self[DatabaseClient.self] }
set { self[DatabaseClient.self] = newValue }
}
}
/// Represents the database interactions used by the application.
@DependencyClient
public struct DatabaseClient: Sendable {
/// Database migrations.
public var migrations: Migrations
/// Interactions with the projects table.
public var projects: Projects
/// Interactions with the rooms table.
public var rooms: Rooms
/// Interactions with the equipment table.
public var equipment: Equipment
public var componentLoss: ComponentLoss
public var effectiveLength: EffectiveLengthClient
/// Interactions with the component losses table.
public var componentLosses: ComponentLosses
/// Interactions with the equivalent lengths table.
public var equivalentLengths: EquivalentLengths
/// Interactions with the users table.
public var users: Users
public var userProfile: UserProfile
/// Interactions with the user profiles table.
public var userProfiles: UserProfiles
/// Interactions with the trunk sizes table.
public var trunkSizes: TrunkSizes
@DependencyClient
public struct ComponentLosses: Sendable {
public var create:
@Sendable (ComponentPressureLoss.Create) async throws -> ComponentPressureLoss
public var delete: @Sendable (ComponentPressureLoss.ID) async throws -> Void
public var fetch: @Sendable (Project.ID) async throws -> [ComponentPressureLoss]
public var get: @Sendable (ComponentPressureLoss.ID) async throws -> ComponentPressureLoss?
public var update:
@Sendable (ComponentPressureLoss.ID, ComponentPressureLoss.Update) async throws ->
ComponentPressureLoss
}
@DependencyClient
public struct EquivalentLengths: Sendable {
public var create: @Sendable (EquivalentLength.Create) async throws -> EquivalentLength
public var delete: @Sendable (EquivalentLength.ID) async throws -> Void
public var fetch: @Sendable (Project.ID) async throws -> [EquivalentLength]
public var fetchMax: @Sendable (Project.ID) async throws -> EquivalentLength.MaxContainer
public var get: @Sendable (EquivalentLength.ID) async throws -> EquivalentLength?
public var update:
@Sendable (EquivalentLength.ID, EquivalentLength.Update) async throws -> EquivalentLength
}
@DependencyClient
public struct Equipment: Sendable {
public var create: @Sendable (EquipmentInfo.Create) async throws -> EquipmentInfo
public var delete: @Sendable (EquipmentInfo.ID) async throws -> Void
public var fetch: @Sendable (Project.ID) async throws -> EquipmentInfo?
public var get: @Sendable (EquipmentInfo.ID) async throws -> EquipmentInfo?
public var update:
@Sendable (EquipmentInfo.ID, EquipmentInfo.Update) async throws -> EquipmentInfo
}
@DependencyClient
public struct Migrations: Sendable {
public var all: @Sendable () async throws -> [any AsyncMigration]
public func callAsFunction() async throws -> [any AsyncMigration] {
try await self.all()
}
}
@DependencyClient
public struct Projects: Sendable {
public var create: @Sendable (User.ID, Project.Create) async throws -> Project
public var delete: @Sendable (Project.ID) async throws -> Void
public var detail: @Sendable (Project.ID) async throws -> Project.Detail?
public var get: @Sendable (Project.ID) async throws -> Project?
public var getCompletedSteps: @Sendable (Project.ID) async throws -> Project.CompletedSteps
public var getSensibleHeatRatio: @Sendable (Project.ID) async throws -> Double?
public var fetch: @Sendable (User.ID, PageRequest) async throws -> Page<Project>
public var update: @Sendable (Project.ID, Project.Update) async throws -> Project
}
@DependencyClient
public struct Rooms: Sendable {
public var create: @Sendable (Room.Create) async throws -> Room
public var delete: @Sendable (Room.ID) async throws -> Void
public var deleteRectangularSize:
@Sendable (Room.ID, Room.RectangularSize.ID) async throws -> Room
public var get: @Sendable (Room.ID) async throws -> Room?
public var fetch: @Sendable (Project.ID) async throws -> [Room]
public var update: @Sendable (Room.ID, Room.Update) async throws -> Room
public var updateRectangularSize: @Sendable (Room.ID, Room.RectangularSize) async throws -> Room
}
@DependencyClient
public struct TrunkSizes: Sendable {
public var create: @Sendable (TrunkSize.Create) async throws -> TrunkSize
public var delete: @Sendable (TrunkSize.ID) async throws -> Void
public var fetch: @Sendable (Project.ID) async throws -> [TrunkSize]
public var get: @Sendable (TrunkSize.ID) async throws -> TrunkSize?
public var update:
@Sendable (TrunkSize.ID, TrunkSize.Update) async throws ->
TrunkSize
}
@DependencyClient
public struct UserProfiles: Sendable {
public var create: @Sendable (User.Profile.Create) async throws -> User.Profile
public var delete: @Sendable (User.Profile.ID) async throws -> Void
public var fetch: @Sendable (User.ID) async throws -> User.Profile?
public var get: @Sendable (User.Profile.ID) async throws -> User.Profile?
public var update: @Sendable (User.Profile.ID, User.Profile.Update) async throws -> User.Profile
}
@DependencyClient
public struct Users: Sendable {
public var create: @Sendable (User.Create) async throws -> User
public var delete: @Sendable (User.ID) async throws -> Void
public var get: @Sendable (User.ID) async throws -> User?
public var login: @Sendable (User.Login) async throws -> User.Token
public var logout: @Sendable (User.Token.ID) async throws -> Void
// public var token: @Sendable (User.ID) async throws -> User.Token
}
}
extension DatabaseClient: TestDependencyKey {
@@ -29,10 +137,10 @@ extension DatabaseClient: TestDependencyKey {
projects: .testValue,
rooms: .testValue,
equipment: .testValue,
componentLoss: .testValue,
effectiveLength: .testValue,
componentLosses: .testValue,
equivalentLengths: .testValue,
users: .testValue,
userProfile: .testValue,
userProfiles: .testValue,
trunkSizes: .testValue
)
@@ -42,44 +150,11 @@ extension DatabaseClient: TestDependencyKey {
projects: .live(database: database),
rooms: .live(database: database),
equipment: .live(database: database),
componentLoss: .live(database: database),
effectiveLength: .live(database: database),
componentLosses: .live(database: database),
equivalentLengths: .live(database: database),
users: .live(database: database),
userProfile: .live(database: database),
userProfiles: .live(database: database),
trunkSizes: .live(database: database)
)
}
}
extension DatabaseClient {
@DependencyClient
public struct Migrations: Sendable {
public var run: @Sendable () async throws -> [any AsyncMigration]
public func callAsFunction() async throws -> [any AsyncMigration] {
try await self.run()
}
}
}
extension DatabaseClient.Migrations: TestDependencyKey {
public static let testValue = Self()
}
extension DatabaseClient.Migrations: DependencyKey {
public static let liveValue = Self(
run: {
[
Project.Migrate(),
User.Migrate(),
User.Token.Migrate(),
User.Profile.Migrate(),
ComponentPressureLoss.Migrate(),
EquipmentInfo.Migrate(),
Room.Migrate(),
EffectiveLength.Migrate(),
TrunkSize.Migrate(),
]
}
)
}

View File

@@ -3,26 +3,13 @@ import DependenciesMacros
import Fluent
import Foundation
import ManualDCore
import SQLKit
extension DatabaseClient {
@DependencyClient
public struct ComponentLoss: Sendable {
public var create:
@Sendable (ComponentPressureLoss.Create) async throws -> ComponentPressureLoss
public var delete: @Sendable (ComponentPressureLoss.ID) async throws -> Void
public var fetch: @Sendable (Project.ID) async throws -> [ComponentPressureLoss]
public var get: @Sendable (ComponentPressureLoss.ID) async throws -> ComponentPressureLoss?
public var update:
@Sendable (ComponentPressureLoss.ID, ComponentPressureLoss.Update) async throws ->
ComponentPressureLoss
}
}
extension DatabaseClient.ComponentLoss: TestDependencyKey {
extension DatabaseClient.ComponentLosses: TestDependencyKey {
public static let testValue = Self()
}
extension DatabaseClient.ComponentLoss {
extension DatabaseClient.ComponentLosses {
public static func live(database: any Database) -> Self {
.init(
create: { request in

View File

@@ -4,23 +4,9 @@ import Fluent
import Foundation
import ManualDCore
extension DatabaseClient {
@DependencyClient
public struct Equipment: Sendable {
public var create: @Sendable (EquipmentInfo.Create) async throws -> EquipmentInfo
public var delete: @Sendable (EquipmentInfo.ID) async throws -> Void
public var fetch: @Sendable (Project.ID) async throws -> EquipmentInfo?
public var get: @Sendable (EquipmentInfo.ID) async throws -> EquipmentInfo?
public var update:
@Sendable (EquipmentInfo.ID, EquipmentInfo.Update) async throws -> EquipmentInfo
}
}
extension DatabaseClient.Equipment: TestDependencyKey {
public static let testValue = Self()
}
extension DatabaseClient.Equipment {
public static func live(database: any Database) -> Self {
.init(
create: { request in

View File

@@ -4,20 +4,7 @@ import Fluent
import Foundation
import ManualDCore
extension DatabaseClient {
@DependencyClient
public struct EffectiveLengthClient: Sendable {
public var create: @Sendable (EffectiveLength.Create) async throws -> EffectiveLength
public var delete: @Sendable (EffectiveLength.ID) async throws -> Void
public var fetch: @Sendable (Project.ID) async throws -> [EffectiveLength]
public var fetchMax: @Sendable (Project.ID) async throws -> EffectiveLength.MaxContainer
public var get: @Sendable (EffectiveLength.ID) async throws -> EffectiveLength?
public var update:
@Sendable (EffectiveLength.ID, EffectiveLength.Update) async throws -> EffectiveLength
}
}
extension DatabaseClient.EffectiveLengthClient: TestDependencyKey {
extension DatabaseClient.EquivalentLengths: TestDependencyKey {
public static let testValue = Self()
public static func live(database: any Database) -> Self {
@@ -74,7 +61,7 @@ extension DatabaseClient.EffectiveLengthClient: TestDependencyKey {
}
}
extension EffectiveLength.Create {
extension EquivalentLength.Create {
func toModel() throws -> EffectiveLengthModel {
try validate()
@@ -94,7 +81,7 @@ extension EffectiveLength.Create {
}
}
extension EffectiveLength {
extension EquivalentLength {
struct Migrate: AsyncMigration {
let name = "CreateEffectiveLength"
@@ -173,20 +160,20 @@ final class EffectiveLengthModel: Model, @unchecked Sendable {
$project.id = projectID
}
func toDTO() throws -> EffectiveLength {
func toDTO() throws -> EquivalentLength {
try .init(
id: requireID(),
projectID: $project.id,
name: name,
type: .init(rawValue: type)!,
straightLengths: straightLengths,
groups: JSONDecoder().decode([EffectiveLength.Group].self, from: groups),
groups: JSONDecoder().decode([EquivalentLength.FittingGroup].self, from: groups),
createdAt: createdAt!,
updatedAt: updatedAt!
)
}
func applyUpdates(_ updates: EffectiveLength.Update) throws {
func applyUpdates(_ updates: EquivalentLength.Update) throws {
if let name = updates.name, name != self.name {
self.name = name
}

View File

@@ -0,0 +1,22 @@
import Dependencies
import ManualDCore
extension DatabaseClient.Migrations: DependencyKey {
public static let testValue = Self()
public static let liveValue = Self(
all: {
[
Project.Migrate(),
User.Migrate(),
User.Token.Migrate(),
User.Profile.Migrate(),
ComponentPressureLoss.Migrate(),
EquipmentInfo.Migrate(),
Room.Migrate(),
EquivalentLength.Migrate(),
TrunkSize.Migrate(),
]
}
)
}

View File

@@ -4,20 +4,6 @@ import Fluent
import Foundation
import ManualDCore
extension DatabaseClient {
@DependencyClient
public struct Projects: Sendable {
public var create: @Sendable (User.ID, Project.Create) async throws -> Project
public var delete: @Sendable (Project.ID) async throws -> Void
public var detail: @Sendable (Project.ID) async throws -> Project.Detail?
public var get: @Sendable (Project.ID) async throws -> Project?
public var getCompletedSteps: @Sendable (Project.ID) async throws -> Project.CompletedSteps
public var getSensibleHeatRatio: @Sendable (Project.ID) async throws -> Double?
public var fetch: @Sendable (User.ID, PageRequest) async throws -> Page<Project>
public var update: @Sendable (Project.ID, Project.Update) async throws -> Project
}
}
extension DatabaseClient.Projects: TestDependencyKey {
public static let testValue = Self()
@@ -35,28 +21,7 @@ extension DatabaseClient.Projects: TestDependencyKey {
try await model.delete(on: database)
},
detail: { id in
guard
let model = try await ProjectModel.query(on: database)
.with(\.$componentLosses)
.with(\.$equipment)
.with(\.$equivalentLengths)
.with(\.$rooms)
.with(
\.$trunks,
{ trunk in
trunk.with(
\.$rooms,
{
$0.with(\.$room)
}
)
}
)
.filter(\.$id == id)
.first()
else {
throw NotFoundError()
}
let model = try await ProjectModel.fetchDetail(for: id, on: database)
// TODO: Different error ??
guard let equipmentInfo = model.equipment else { return nil }
@@ -76,44 +41,25 @@ extension DatabaseClient.Projects: TestDependencyKey {
try await ProjectModel.find(id, on: database).map { try $0.toDTO() }
},
getCompletedSteps: { id in
let roomsCount = try await RoomModel.query(on: database)
.with(\.$project)
.filter(\.$project.$id == id)
.count()
let equivalentLengths = try await EffectiveLengthModel.query(on: database)
.with(\.$project)
.filter(\.$project.$id == id)
.all()
let model = try await ProjectModel.fetchDetail(for: id, on: database)
var equivalentLengthsCompleted = false
if equivalentLengths.filter({ $0.type == "supply" }).first != nil,
equivalentLengths.filter({ $0.type == "return" }).first != nil
if model.equivalentLengths.filter({ $0.type == "supply" }).first != nil,
model.equivalentLengths.filter({ $0.type == "return" }).first != nil
{
equivalentLengthsCompleted = true
}
let componentLosses = try await ComponentLossModel.query(on: database)
.with(\.$project)
.filter(\.$project.$id == id)
.count()
let equipmentInfo = try await EquipmentModel.query(on: database)
.with(\.$project)
.filter(\.$project.$id == id)
.first()
return .init(
equipmentInfo: equipmentInfo != nil,
rooms: roomsCount > 0,
equipmentInfo: model.equipment != nil,
rooms: model.rooms.count > 0,
equivalentLength: equivalentLengthsCompleted,
frictionRate: componentLosses > 0
frictionRate: model.componentLosses.count > 0
)
},
getSensibleHeatRatio: { id in
guard
let shr = try await ProjectModel.query(on: database)
let model = try await ProjectModel.query(on: database)
.field(\.$id)
.field(\.$sensibleHeatRatio)
.filter(\.$id == id)
@@ -121,7 +67,7 @@ extension DatabaseClient.Projects: TestDependencyKey {
else {
throw NotFoundError()
}
return shr.sensibleHeatRatio
return model.sensibleHeatRatio
},
fetch: { userID, request in
try await ProjectModel.query(on: database)
@@ -241,7 +187,7 @@ extension Project {
.field("sensibleHeatRatio", .double)
.field("createdAt", .datetime)
.field("updatedAt", .datetime)
.field("userID", .uuid, .required, .references(UserModel.schema, "id"))
.field("userID", .uuid, .required, .references(UserModel.schema, "id", onDelete: .cascade))
.unique(on: "userID", "name")
.create()
}
@@ -364,4 +310,35 @@ final class ProjectModel: Model, @unchecked Sendable {
self.sensibleHeatRatio = sensibleHeatRatio
}
}
/// Returns a ``ProjectModel`` with all the relations eagerly loaded.
static func fetchDetail(
for projectID: Project.ID,
on database: any Database
) async throws -> ProjectModel {
guard
let model =
try await ProjectModel.query(on: database)
.with(\.$componentLosses)
.with(\.$equipment)
.with(\.$equivalentLengths)
.with(\.$rooms)
.with(
\.$trunks,
{ trunk in
trunk.with(
\.$rooms,
{
$0.with(\.$room)
}
)
}
)
.filter(\.$id == projectID)
.first()
else {
throw NotFoundError()
}
return model
}
}

View File

@@ -4,20 +4,6 @@ import Fluent
import Foundation
import ManualDCore
extension DatabaseClient {
@DependencyClient
public struct Rooms: Sendable {
public var create: @Sendable (Room.Create) async throws -> Room
public var delete: @Sendable (Room.ID) async throws -> Void
public var deleteRectangularSize:
@Sendable (Room.ID, Room.RectangularSize.ID) async throws -> Room
public var get: @Sendable (Room.ID) async throws -> Room?
public var fetch: @Sendable (Project.ID) async throws -> [Room]
public var update: @Sendable (Room.ID, Room.Update) async throws -> Room
public var updateRectangularSize: @Sendable (Room.ID, Room.RectangularSize) async throws -> Room
}
}
extension DatabaseClient.Rooms: TestDependencyKey {
public static let testValue = Self()

View File

@@ -4,19 +4,6 @@ import Fluent
import Foundation
import ManualDCore
extension DatabaseClient {
@DependencyClient
public struct TrunkSizes: Sendable {
public var create: @Sendable (TrunkSize.Create) async throws -> TrunkSize
public var delete: @Sendable (TrunkSize.ID) async throws -> Void
public var fetch: @Sendable (Project.ID) async throws -> [TrunkSize]
public var get: @Sendable (TrunkSize.ID) async throws -> TrunkSize?
public var update:
@Sendable (TrunkSize.ID, TrunkSize.Update) async throws ->
TrunkSize
}
}
extension DatabaseClient.TrunkSizes: TestDependencyKey {
public static let testValue = Self()

View File

@@ -4,18 +4,7 @@ import Fluent
import ManualDCore
import Vapor
extension DatabaseClient {
@DependencyClient
public struct UserProfile: Sendable {
public var create: @Sendable (User.Profile.Create) async throws -> User.Profile
public var delete: @Sendable (User.Profile.ID) async throws -> Void
public var fetch: @Sendable (User.ID) async throws -> User.Profile?
public var get: @Sendable (User.Profile.ID) async throws -> User.Profile?
public var update: @Sendable (User.Profile.ID, User.Profile.Update) async throws -> User.Profile
}
}
extension DatabaseClient.UserProfile: TestDependencyKey {
extension DatabaseClient.UserProfiles: TestDependencyKey {
public static let testValue = Self()

View File

@@ -4,19 +4,6 @@ import Fluent
import ManualDCore
import Vapor
extension DatabaseClient {
@DependencyClient
public struct Users: Sendable {
public var create: @Sendable (User.Create) async throws -> User
public var delete: @Sendable (User.ID) async throws -> Void
public var get: @Sendable (User.ID) async throws -> User?
public var login: @Sendable (User.Login) async throws -> User.Token
public var logout: @Sendable (User.Token.ID) async throws -> Void
// public var token: @Sendable (User.ID) async throws -> User.Token
}
}
extension DatabaseClient.Users: TestDependencyKey {
public static let testValue = Self()
@@ -46,6 +33,11 @@ extension DatabaseClient.Users: TestDependencyKey {
throw NotFoundError()
}
// Verify the password matches the user's hashed password.
guard try user.verifyPassword(request.password) else {
throw Abort(.unauthorized)
}
let token: User.Token
// Check if there's a user token

View File

@@ -1,175 +0,0 @@
// import Dependencies
// import DependenciesMacros
// import Fluent
// import Foundation
// import ManualDCore
//
// extension DatabaseClient {
// @DependencyClient
// public struct RectangularDuct: Sendable {
// public var create:
// @Sendable (DuctSizing.RectangularDuct.Create) async throws -> DuctSizing.RectangularDuct
// public var delete: @Sendable (DuctSizing.RectangularDuct.ID) async throws -> Void
// public var fetch: @Sendable (Room.ID) async throws -> [DuctSizing.RectangularDuct]
// public var get:
// @Sendable (DuctSizing.RectangularDuct.ID) async throws -> DuctSizing.RectangularDuct?
// public var update:
// @Sendable (DuctSizing.RectangularDuct.ID, DuctSizing.RectangularDuct.Update) async throws ->
// DuctSizing.RectangularDuct
// }
// }
//
// extension DatabaseClient.RectangularDuct: TestDependencyKey {
// public static let testValue = Self()
//
// public static func live(database: any Database) -> Self {
// .init(
// create: { request in
// try request.validate()
// let model = request.toModel()
// try await model.save(on: database)
// return try model.toDTO()
// },
// delete: { id in
// guard let model = try await RectangularDuctModel.find(id, on: database) else {
// throw NotFoundError()
// }
// try await model.delete(on: database)
// },
// fetch: { roomID in
// try await RectangularDuctModel.query(on: database)
// .with(\.$room)
// .filter(\.$room.$id == roomID)
// .all()
// .map { try $0.toDTO() }
// },
// get: { id in
// try await RectangularDuctModel.find(id, on: database)
// .map { try $0.toDTO() }
// },
// update: { id, updates in
// guard let model = try await RectangularDuctModel.find(id, on: database) else {
// throw NotFoundError()
// }
// try updates.validate()
// model.applyUpdates(updates)
// if model.hasChanges {
// try await model.save(on: database)
// }
// return try model.toDTO()
// }
// )
// }
// }
//
// extension DuctSizing.RectangularDuct.Create {
//
// func validate() throws(ValidationError) {
// guard height > 0 else {
// throw ValidationError("Rectangular duct size height should be greater than 0.")
// }
// if let register {
// guard register > 0 else {
// throw ValidationError("Rectangular duct size register should be greater than 0.")
// }
// }
// }
//
// func toModel() -> RectangularDuctModel {
// .init(roomID: roomID, height: height)
// }
// }
//
// extension DuctSizing.RectangularDuct.Update {
//
// func validate() throws(ValidationError) {
// if let height {
// guard height > 0 else {
// throw ValidationError("Rectangular duct size height should be greater than 0.")
// }
// }
// if let register {
// guard register > 0 else {
// throw ValidationError("Rectangular duct size register should be greater than 0.")
// }
// }
// }
// }
//
// extension DuctSizing.RectangularDuct {
// struct Migrate: AsyncMigration {
// let name = "CreateRectangularDuct"
//
// func prepare(on database: any Database) async throws {
// try await database.schema(RectangularDuctModel.schema)
// .id()
// .field("register", .int8)
// .field("height", .int8, .required)
// .field("roomID", .uuid, .required, .references(RoomModel.schema, "id", onDelete: .cascade))
// .field("createdAt", .datetime)
// .field("updatedAt", .datetime)
// .create()
// }
//
// func revert(on database: any Database) async throws {
// try await database.schema(RectangularDuctModel.schema).delete()
// }
// }
// }
//
// final class RectangularDuctModel: Model, @unchecked Sendable {
//
// static let schema = "rectangularDuct"
//
// @ID(key: .id)
// var id: UUID?
//
// @Parent(key: "roomID")
// var room: RoomModel
//
// @Field(key: "height")
// var height: Int
//
// @Field(key: "register")
// var register: Int?
//
// @Timestamp(key: "createdAt", on: .create, format: .iso8601)
// var createdAt: Date?
//
// @Timestamp(key: "updatedAt", on: .update, format: .iso8601)
// var updatedAt: Date?
//
// init() {}
//
// init(
// id: UUID? = nil,
// roomID: Room.ID,
// register: Int? = nil,
// height: Int
// ) {
// self.id = id
// $room.id = roomID
// self.register = register
// self.height = height
// }
//
// func toDTO() throws -> DuctSizing.RectangularDuct {
// return try .init(
// id: requireID(),
// roomID: $room.id,
// register: register,
// height: height,
// createdAt: createdAt!,
// updatedAt: updatedAt!
// )
// }
//
// func applyUpdates(_ updates: DuctSizing.RectangularDuct.Update) {
// if let height = updates.height, height != self.height {
// self.height = height
// }
// if let register = updates.register, register != self.register {
// self.register = register
// }
// }
// }

View File

@@ -4,6 +4,7 @@ import Foundation
import Vapor
extension DependencyValues {
/// Dependency used for file operations.
public var fileClient: FileClient {
get { self[FileClient.self] }
set { self[FileClient.self] = newValue }
@@ -14,9 +15,27 @@ extension DependencyValues {
public struct FileClient: Sendable {
public typealias OnCompleteHandler = @Sendable () async throws -> Void
public var writeFile: @Sendable (String, String) async throws -> Void
public var removeFile: @Sendable (String) async throws -> Void
public var streamFile: @Sendable (String, @escaping OnCompleteHandler) async throws -> Response
/// Write contents to a file.
///
/// > Warning: This will overwrite a file if it exists.
public var writeFile: @Sendable (_ contents: String, _ path: String) async throws -> Void
/// Remove a file.
public var removeFile: @Sendable (_ path: String) async throws -> Void
/// Stream a file.
public var streamFile:
@Sendable (_ path: String, @escaping OnCompleteHandler) async throws -> Response
/// Stream a file at the given path.
///
/// - Paramters:
/// - path: The path to the file to stream.
/// - onComplete: Completion handler to run when done streaming the file.
public func streamFile(
at path: String,
onComplete: @escaping OnCompleteHandler = {}
) async throws -> Response {
try await streamFile(path, onComplete)
}
}
extension FileClient: TestDependencyKey {

View File

@@ -11,12 +11,12 @@ extension Snapshotting where Value == (any HTML), Format == String {
}
}
extension Snapshotting where Value == String, Format == String {
public static var html: Snapshotting {
var snapshotting = SimplySnapshotting.lines
.pullback { $0 }
snapshotting.pathExtension = "html"
return snapshotting
}
}
// extension Snapshotting where Value == String, Format == String {
// public static var html: Snapshotting {
// var snapshotting = SimplySnapshotting.lines
// .pullback { $0 }
//
// snapshotting.pathExtension = "html"
// return snapshotting
// }
// }

View File

@@ -46,10 +46,6 @@ extension TrunkSize {
}
}
extension ComponentPressureLosses {
var totalLosses: Double { values.reduce(0) { $0 + $1 } }
}
extension Array where Element == EffectiveLengthGroup {
var totalEffectiveLength: Int {
reduce(0) { $0 + $1.effectiveLength }
@@ -101,16 +97,16 @@ func roundSize(_ size: Double) throws -> Int {
}
}
func velocity(cfm: Int, roundSize: Int) -> Int {
let cfm = Double(cfm)
func velocity(cfm: ManualDClient.CFM, roundSize: Int) -> Int {
let cfm = Double(cfm.rawValue)
let roundSize = Double(roundSize)
let velocity = cfm / (pow(roundSize / 24, 2) * 3.14)
return Int(round(velocity))
}
func flexSize(_ request: ManualDClient.DuctSizeRequest) throws -> Int {
let cfm = pow(Double(request.designCFM), 0.4)
let fr = pow(request.frictionRate / 1.76, 0.2)
func flexSize(_ cfm: ManualDClient.CFM, _ frictionRate: Double) throws -> Int {
let cfm = pow(Double(cfm.rawValue), 0.4)
let fr = pow(frictionRate / 1.76, 0.2)
let size = 0.55 * (cfm / fr)
return try roundSize(size)
}

View File

@@ -2,8 +2,10 @@ import Dependencies
import DependenciesMacros
import Logging
import ManualDCore
import Tagged
extension DependencyValues {
/// Dependency that performs manual-d duct sizing calculations.
public var manualD: ManualDClient {
get { self[ManualDClient.self] }
set { self[ManualDClient.self] = newValue }
@@ -15,12 +17,61 @@ extension DependencyValues {
///
@DependencyClient
public struct ManualDClient: Sendable {
public var ductSize: @Sendable (DuctSizeRequest) async throws -> DuctSizeResponse
public var frictionRate: @Sendable (FrictionRateRequest) async throws -> FrictionRate
public var totalEquivalentLength: @Sendable (TotalEquivalentLengthRequest) async throws -> Int
public var rectangularSize:
@Sendable (RectangularSizeRequest) async throws -> RectangularSizeResponse
/// Calculates the duct size for the given cfm and friction rate.
public var ductSize: @Sendable (CFM, DesignFrictionRate) async throws -> DuctSize
/// Calculates the design friction rate for the given request.
public var frictionRate: @Sendable (FrictionRateRequest) async throws -> FrictionRate
/// Calculates the equivalent rectangular size for the given round duct and rectangular height.
public var rectangularSize: @Sendable (RoundSize, Height) async throws -> RectangularSize
/// Calculates the duct size for the given cfm and friction rate.
///
/// - Paramaters:
/// - designCFM: The design cfm for the duct.
/// - designFrictionRate: The design friction rate for the system.
public func ductSize(
cfm designCFM: Int,
frictionRate designFrictionRate: Double
) async throws -> DuctSize {
try await ductSize(.init(rawValue: designCFM), .init(rawValue: designFrictionRate))
}
/// Calculates the duct size for the given cfm and friction rate.
///
/// - Paramaters:
/// - designCFM: The design cfm for the duct.
/// - designFrictionRate: The design friction rate for the system.
public func ductSize(
cfm designCFM: Double,
frictionRate designFrictionRate: Double
) async throws -> DuctSize {
try await ductSize(.init(rawValue: Int(designCFM)), .init(rawValue: designFrictionRate))
}
/// Calculates the equivalent rectangular size for the given round duct and rectangular height.
///
/// - Paramaters:
/// - roundSize: The round duct size.
/// - height: The rectangular height of the duct.
public func rectangularSize(
round roundSize: RoundSize,
height: Height
) async throws -> RectangularSize {
try await rectangularSize(roundSize, height)
}
/// Calculates the equivalent rectangular size for the given round duct and rectangular height.
///
/// - Paramaters:
/// - roundSize: The round duct size.
/// - height: The rectangular height of the duct.
public func rectangularSize(
round roundSize: Int,
height: Int
) async throws -> RectangularSize {
try await rectangularSize(.init(rawValue: roundSize), .init(rawValue: height))
}
}
extension ManualDClient: TestDependencyKey {
@@ -28,21 +79,20 @@ extension ManualDClient: TestDependencyKey {
}
extension ManualDClient {
public struct DuctSizeRequest: Codable, Equatable, Sendable {
public let designCFM: Int
public let frictionRate: Double
public init(
designCFM: Int,
frictionRate: Double
) {
self.designCFM = designCFM
self.frictionRate = frictionRate
}
/// A name space for tags used by the ManualDClient.
public enum Tag {
public enum CFM {}
public enum DesignFrictionRate {}
public enum Height {}
public enum Round {}
}
public struct DuctSizeResponse: Codable, Equatable, Sendable {
public typealias CFM = Tagged<Tag.CFM, Int>
public typealias DesignFrictionRate = Tagged<Tag.DesignFrictionRate, Double>
public typealias Height = Tagged<Tag.Height, Int>
public typealias RoundSize = Tagged<Tag.Round, Int>
public struct DuctSize: Codable, Equatable, Sendable {
public let calculatedSize: Double
public let finalSize: Int
@@ -66,58 +116,20 @@ extension ManualDClient {
public let externalStaticPressure: Double
public let componentPressureLosses: [ComponentPressureLoss]
public let totalEffectiveLength: Int
public let totalEquivalentLength: Int
public init(
externalStaticPressure: Double,
componentPressureLosses: [ComponentPressureLoss],
totalEffectiveLength: Int
totalEquivalentLength: Int
) {
self.externalStaticPressure = externalStaticPressure
self.componentPressureLosses = componentPressureLosses
self.totalEffectiveLength = totalEffectiveLength
self.totalEquivalentLength = totalEquivalentLength
}
}
public struct FrictionRateResponse: Codable, Equatable, Sendable {
public let availableStaticPressure: Double
public let frictionRate: Double
public init(availableStaticPressure: Double, frictionRate: Double) {
self.availableStaticPressure = availableStaticPressure
self.frictionRate = frictionRate
}
}
public struct TotalEquivalentLengthRequest: Codable, Equatable, Sendable {
public let trunkLengths: [Int]
public let runoutLengths: [Int]
public let effectiveLengthGroups: [EffectiveLengthGroup]
public init(
trunkLengths: [Int],
runoutLengths: [Int],
effectiveLengthGroups: [EffectiveLengthGroup]
) {
self.trunkLengths = trunkLengths
self.runoutLengths = runoutLengths
self.effectiveLengthGroups = effectiveLengthGroups
}
}
public struct RectangularSizeRequest: Codable, Equatable, Sendable {
public let roundSize: Int
public let height: Int
public init(round roundSize: Int, height: Int) {
self.roundSize = roundSize
self.height = height
}
}
public struct RectangularSizeResponse: Codable, Equatable, Sendable {
public struct RectangularSize: Codable, Equatable, Sendable {
public let height: Int
public let width: Int

View File

@@ -4,41 +4,47 @@ import ManualDCore
extension ManualDClient: DependencyKey {
public static let liveValue: Self = .init(
ductSize: { request in
guard request.designCFM > 0 else {
ductSize: { cfm, frictionRate in
guard cfm > 0 else {
throw ManualDError(message: "Design CFM should be greater than 0.")
}
let fr = pow(request.frictionRate, 0.5)
let ductulatorSize = pow(Double(request.designCFM) / (3.12 * fr), 0.38)
let fr = pow(frictionRate.rawValue, 0.5)
let ductulatorSize = pow(Double(cfm.rawValue) / (3.12 * fr), 0.38)
let finalSize = try roundSize(ductulatorSize)
let flexSize = try flexSize(request)
let flexSize = try flexSize(cfm, frictionRate.rawValue)
return .init(
calculatedSize: ductulatorSize,
finalSize: finalSize,
flexSize: flexSize,
velocity: velocity(cfm: request.designCFM, roundSize: finalSize)
velocity: velocity(cfm: cfm, roundSize: finalSize)
)
},
frictionRate: { request in
// Ensure the total effective length is greater than 0.
guard request.totalEffectiveLength > 0 else {
guard request.totalEquivalentLength > 0 else {
throw ManualDError(message: "Total Effective Length should be greater than 0.")
}
let totalComponentLosses = request.componentPressureLosses.total
let availableStaticPressure = request.externalStaticPressure - totalComponentLosses
let frictionRate = availableStaticPressure * 100.0 / Double(request.totalEffectiveLength)
return .init(availableStaticPressure: availableStaticPressure, value: frictionRate)
let frictionRate = availableStaticPressure * 100.0 / Double(request.totalEquivalentLength)
return .init(
availableStaticPressure: availableStaticPressure,
value: frictionRate
)
},
totalEquivalentLength: { request in
let trunkLengths = request.trunkLengths.reduce(0) { $0 + $1 }
let runoutLengths = request.runoutLengths.reduce(0) { $0 + $1 }
let groupLengths = request.effectiveLengthGroups.totalEffectiveLength
return trunkLengths + runoutLengths + groupLengths
},
rectangularSize: { request in
let width = (Double.pi * (pow(Double(request.roundSize) / 2.0, 2.0))) / Double(request.height)
return .init(height: request.height, width: Int(width.rounded(.toNearestOrEven)))
// totalEquivalentLength: { request in
// let trunkLengths = request.trunkLengths.reduce(0) { $0 + $1 }
// let runoutLengths = request.runoutLengths.reduce(0) { $0 + $1 }
// let groupLengths = request.effectiveLengthGroups.totalEffectiveLength
// return trunkLengths + runoutLengths + groupLengths
// },
rectangularSize: { round, height in
let width = (Double.pi * (pow(Double(round.rawValue) / 2.0, 2.0))) / Double(height.rawValue)
return .init(
height: height.rawValue,
width: Int(width.rounded(.toNearestOrEven))
)
}
)
}

View File

@@ -1,6 +1,10 @@
import Dependencies
import Foundation
/// Represents component pressure losses used in the friction rate worksheet.
///
/// These are items such as filter, evaporator-coils, balance-dampers, etc. that
/// need to be overcome by the system fan.
public struct ComponentPressureLoss: Codable, Equatable, Identifiable, Sendable {
public let id: UUID
@@ -44,7 +48,7 @@ extension ComponentPressureLoss {
self.value = value
}
// Return's commonly used default component pressure losses.
/// Commonly used default component pressure losses.
public static func `default`(projectID: Project.ID) -> [Self] {
[
.init(projectID: projectID, name: "supply-outlet", value: 0.03),
@@ -75,20 +79,7 @@ extension Array where Element == ComponentPressureLoss {
}
}
public typealias ComponentPressureLosses = [String: Double]
#if DEBUG
extension ComponentPressureLosses {
public static var mock: Self {
[
"evaporator-coil": 0.2,
"filter": 0.1,
"supply-outlet": 0.03,
"return-grille": 0.03,
"balancing-damper": 0.03,
]
}
}
extension Array where Element == ComponentPressureLoss {
public static func mock(projectID: Project.ID) -> Self {

View File

@@ -1,215 +0,0 @@
import Dependencies
import Foundation
// TODO: Not sure how to model effective length groups in the database.
// thinking perhaps just have a 'data' field that encoded / decodes
// to swift types??
public struct EffectiveLength: Codable, Equatable, Identifiable, Sendable {
public let id: UUID
public let projectID: Project.ID
public let name: String
public let type: EffectiveLengthType
public let straightLengths: [Int]
public let groups: [Group]
public let createdAt: Date
public let updatedAt: Date
public init(
id: UUID,
projectID: Project.ID,
name: String,
type: EffectiveLength.EffectiveLengthType,
straightLengths: [Int],
groups: [EffectiveLength.Group],
createdAt: Date,
updatedAt: Date
) {
self.id = id
self.projectID = projectID
self.name = name
self.type = type
self.straightLengths = straightLengths
self.groups = groups
self.createdAt = createdAt
self.updatedAt = updatedAt
}
}
extension EffectiveLength {
public struct Create: Codable, Equatable, Sendable {
public let projectID: Project.ID
public let name: String
public let type: EffectiveLengthType
public let straightLengths: [Int]
public let groups: [Group]
public init(
projectID: Project.ID,
name: String,
type: EffectiveLength.EffectiveLengthType,
straightLengths: [Int],
groups: [EffectiveLength.Group]
) {
self.projectID = projectID
self.name = name
self.type = type
self.straightLengths = straightLengths
self.groups = groups
}
}
public struct Update: Codable, Equatable, Sendable {
public let name: String?
public let type: EffectiveLengthType?
public let straightLengths: [Int]?
public let groups: [Group]?
public init(
name: String? = nil,
type: EffectiveLength.EffectiveLengthType? = nil,
straightLengths: [Int]? = nil,
groups: [EffectiveLength.Group]? = nil
) {
self.name = name
self.type = type
self.straightLengths = straightLengths
self.groups = groups
}
}
public enum EffectiveLengthType: String, CaseIterable, Codable, Sendable {
case `return`
case supply
}
public struct Group: Codable, Equatable, Sendable {
public let group: Int
public let letter: String
public let value: Double
public let quantity: Int
public init(
group: Int,
letter: String,
value: Double,
quantity: Int = 1
) {
self.group = group
self.letter = letter
self.value = value
self.quantity = quantity
}
}
public struct MaxContainer: Codable, Equatable, Sendable {
public let supply: EffectiveLength?
public let `return`: EffectiveLength?
public var total: Double? {
guard let supply else { return nil }
guard let `return` else { return nil }
return supply.totalEquivalentLength + `return`.totalEquivalentLength
}
public init(supply: EffectiveLength? = nil, return: EffectiveLength? = nil) {
self.supply = supply
self.return = `return`
}
}
}
extension EffectiveLength {
public var totalEquivalentLength: Double {
straightLengths.reduce(into: 0.0) { $0 += Double($1) }
+ groups.totalEquivalentLength
}
}
extension Array where Element == EffectiveLength.Group {
public var totalEquivalentLength: Double {
reduce(into: 0.0) {
$0 += ($1.value * Double($1.quantity))
}
}
}
#if DEBUG
extension EffectiveLength {
public static func mock(projectID: Project.ID) -> [Self] {
@Dependency(\.uuid) var uuid
@Dependency(\.date.now) var now
return [
.init(
id: uuid(),
projectID: projectID,
name: "Supply - 1",
type: .supply,
straightLengths: [10, 25],
groups: [
.init(group: 1, letter: "a", value: 20),
.init(group: 2, letter: "b", value: 30, quantity: 1),
.init(group: 3, letter: "a", value: 10, quantity: 1),
.init(group: 12, letter: "a", value: 10, quantity: 1),
],
createdAt: now,
updatedAt: now
),
.init(
id: uuid(),
projectID: projectID,
name: "Return - 1",
type: .return,
straightLengths: [10, 20, 5],
groups: [
.init(group: 5, letter: "a", value: 10),
.init(group: 6, letter: "a", value: 15, quantity: 1),
.init(group: 7, letter: "a", value: 20, quantity: 1),
],
createdAt: now,
updatedAt: now
),
]
}
public static let mocks: [Self] = [
.init(
id: UUID(0),
projectID: UUID(0),
name: "Test Supply - 1",
type: .supply,
straightLengths: [10, 20, 25],
groups: [
.init(group: 1, letter: "a", value: 20),
.init(group: 2, letter: "b", value: 15, quantity: 2),
.init(group: 3, letter: "c", value: 10, quantity: 1),
],
createdAt: Date(),
updatedAt: Date()
),
.init(
id: UUID(1),
projectID: UUID(0),
name: "Test Return - 1",
type: .return,
straightLengths: [10, 20, 25],
groups: [
.init(group: 1, letter: "a", value: 20),
.init(group: 2, letter: "b", value: 15, quantity: 2),
.init(group: 3, letter: "c", value: 10, quantity: 1),
],
createdAt: Date(),
updatedAt: Date()
),
]
}
#endif

View File

@@ -1,5 +1,7 @@
import Foundation
// TODO: These are not used, should they be removed??
// TODO: Add other description / label for items that have same group & letter, but
// different effective length.
public struct EffectiveLengthGroup: Codable, Equatable, Sendable {

View File

@@ -1,6 +1,10 @@
import Dependencies
import Foundation
/// Represents the equipment information for a project.
///
/// This is used in the friction rate worksheet and sizing ducts. It holds on to items
/// such as the target static pressure, cooling CFM, and heating CFM for the project.
public struct EquipmentInfo: Codable, Equatable, Identifiable, Sendable {
public let id: UUID
public let projectID: Project.ID

View File

@@ -0,0 +1,239 @@
import Dependencies
import Foundation
/// Represents the equivalent length of a single duct path.
///
/// These consist of both straight lengths of duct / trunks, as well as the
/// equivalent length of duct fittings. They are used to determine the worst
/// case total equivalent length of duct that the system fan has to move air
/// through.
///
/// There can be many equivalent lengths saved for a project, however the only
/// ones that matter in most calculations are the longest supply path and the
/// the longest return path.
///
/// It is required that project has at least one equivalent length saved for
/// the supply and one saved for return, otherwise duct sizes can not be calculated.
public struct EquivalentLength: Codable, Equatable, Identifiable, Sendable {
/// The id of the equivalent length.
public let id: UUID
/// The project that this equivalent length is associated with.
public let projectID: Project.ID
/// A unique name / label for this equivalent length.
public let name: String
/// The type (supply or return) of the equivalent length.
public let type: EffectiveLengthType
/// The straight lengths of duct for this equivalent length.
public let straightLengths: [Int]
/// The fitting groups associated with this equivalent length.
public let groups: [FittingGroup]
/// When this equivalent length was created in the database.
public let createdAt: Date
/// When this equivalent length was updated in the database.
public let updatedAt: Date
public init(
id: UUID,
projectID: Project.ID,
name: String,
type: EquivalentLength.EffectiveLengthType,
straightLengths: [Int],
groups: [EquivalentLength.FittingGroup],
createdAt: Date,
updatedAt: Date
) {
self.id = id
self.projectID = projectID
self.name = name
self.type = type
self.straightLengths = straightLengths
self.groups = groups
self.createdAt = createdAt
self.updatedAt = updatedAt
}
}
extension EquivalentLength {
/// Represents the data needed to create a new ``EquivalentLength`` in the database.
public struct Create: Codable, Equatable, Sendable {
/// The project that this equivalent length is associated with.
public let projectID: Project.ID
/// A unique name / label for this equivalent length.
public let name: String
/// The type (supply or return) of the equivalent length.
public let type: EffectiveLengthType
/// The straight lengths of duct for this equivalent length.
public let straightLengths: [Int]
/// The fitting groups associated with this equivalent length.
public let groups: [FittingGroup]
public init(
projectID: Project.ID,
name: String,
type: EquivalentLength.EffectiveLengthType,
straightLengths: [Int],
groups: [EquivalentLength.FittingGroup]
) {
self.projectID = projectID
self.name = name
self.type = type
self.straightLengths = straightLengths
self.groups = groups
}
}
/// Represents the data needed to update an ``EquivalentLength`` in the database.
///
/// Only the supplied fields are updated.
public struct Update: Codable, Equatable, Sendable {
/// A unique name / label for this equivalent length.
public let name: String?
/// The type (supply or return) of the equivalent length.
public let type: EffectiveLengthType?
/// The straight lengths of duct for this equivalent length.
public let straightLengths: [Int]?
/// The fitting groups associated with this equivalent length.
public let groups: [FittingGroup]?
public init(
name: String? = nil,
type: EquivalentLength.EffectiveLengthType? = nil,
straightLengths: [Int]? = nil,
groups: [EquivalentLength.FittingGroup]? = nil
) {
self.name = name
self.type = type
self.straightLengths = straightLengths
self.groups = groups
}
}
/// Represents the type of equivalent length, either supply or return.
public enum EffectiveLengthType: String, CaseIterable, Codable, Sendable {
case `return`
case supply
}
/// Represents a Manual-D fitting group.
///
/// These are defined by Manual-D and convert different types of fittings into
/// an equivalent length of straight duct.
public struct FittingGroup: Codable, Equatable, Sendable {
/// The fitting group number.
public let group: Int
/// The fitting group letter.
public let letter: String
/// The equivalent length of the fitting.
public let value: Double
/// The quantity of the fittings in the path.
public let quantity: Int
public init(
group: Int,
letter: String,
value: Double,
quantity: Int = 1
) {
self.group = group
self.letter = letter
self.value = value
self.quantity = quantity
}
}
// TODO: Should these not be optional and we just throw an error or return nil from
// a database query.
/// Represents the max ``EquivalentLength``'s for a project.
///
/// Calculating the duct sizes for a project requires there to be a max supply
/// and a max return equivalent length, so this container represents those values
/// when they exist in the database.
public struct MaxContainer: Codable, Equatable, Sendable {
/// The longest supply equivalent length.
public let supply: EquivalentLength?
/// The longest return equivalent length.
public let `return`: EquivalentLength?
public init(supply: EquivalentLength? = nil, return: EquivalentLength? = nil) {
self.supply = supply
self.return = `return`
}
public var totalEquivalentLength: Double? {
guard let supply else { return nil }
guard let `return` else { return nil }
return supply.totalEquivalentLength + `return`.totalEquivalentLength
}
}
}
extension EquivalentLength {
/// The calculated total equivalent length.
///
/// This is the sum of all the straigth lengths and fitting groups (with quantities).
public var totalEquivalentLength: Double {
straightLengths.reduce(into: 0.0) { $0 += Double($1) }
+ groups.totalEquivalentLength
}
}
extension Array where Element == EquivalentLength.FittingGroup {
/// The calculated total equivalent length for the fitting groups.
public var totalEquivalentLength: Double {
reduce(into: 0.0) {
$0 += ($1.value * Double($1.quantity))
}
}
}
#if DEBUG
extension EquivalentLength {
public static func mock(projectID: Project.ID) -> [Self] {
@Dependency(\.uuid) var uuid
@Dependency(\.date.now) var now
return [
.init(
id: uuid(),
projectID: projectID,
name: "Supply - 1",
type: .supply,
straightLengths: [10, 25],
groups: [
.init(group: 1, letter: "a", value: 20),
.init(group: 2, letter: "b", value: 30, quantity: 1),
.init(group: 3, letter: "a", value: 10, quantity: 1),
.init(group: 12, letter: "a", value: 10, quantity: 1),
],
createdAt: now,
updatedAt: now
),
.init(
id: uuid(),
projectID: projectID,
name: "Return - 1",
type: .return,
straightLengths: [10, 20, 5],
groups: [
.init(group: 5, letter: "a", value: 10),
.init(group: 6, letter: "a", value: 15, quantity: 1),
.init(group: 7, letter: "a", value: 20, quantity: 1),
],
createdAt: now,
updatedAt: now
),
]
}
}
#endif

View File

@@ -1,4 +1,17 @@
import Foundation
import Tagged
extension Tagged where RawValue == Double {
public func string(digits: Int = 2) -> String {
rawValue.string(digits: digits)
}
}
extension Tagged where RawValue == Int {
public func string() -> String {
rawValue.string()
}
}
extension Double {

View File

@@ -1,8 +1,14 @@
/// Holds onto values returned when calculating the design
/// friction rate for a project.
///
/// **NOTE:** This is not stored in the database, it is calculated on the fly.
public struct FrictionRate: Codable, Equatable, Sendable {
/// The available static pressure is the equipment's design static pressure
/// minus the ``ComponentPressureLoss``es for the project.
public let availableStaticPressure: Double
/// The calculated design friction rate value.
public let value: Double
/// Whether the design friction rate is within a valid range.
public var hasErrors: Bool { error != nil }
public init(
@@ -13,6 +19,7 @@ public struct FrictionRate: Codable, Equatable, Sendable {
self.value = value
}
/// The error if the design friction rate is out of a valid range.
public var error: FrictionRateError? {
if value >= 0.18 {
return .init(
@@ -37,8 +44,13 @@ public struct FrictionRate: Codable, Equatable, Sendable {
}
}
/// Represents an error when the ``FrictionRate`` is out of a valid range.
///
/// This holds onto the reason for the error as well as possible resolutions.
public struct FrictionRateError: Error, Equatable, Sendable {
/// The reason for the error.
public let reason: String
/// The possible resolutions to the error.
public let resolutions: [String]
public init(

View File

@@ -1,16 +1,29 @@
import Dependencies
import Foundation
/// Represents a single duct design project / system.
///
/// Holds items such as project name and address.
public struct Project: Codable, Equatable, Identifiable, Sendable {
/// The unique ID of the project.
public let id: UUID
/// The name of the project.
public let name: String
/// The street address of the project.
public let streetAddress: String
/// The city of the project.
public let city: String
/// The state of the project.
public let state: String
/// The zip code of the project.
public let zipCode: String
/// The global sensible heat ratio for the project.
///
/// **NOTE:** This is used for calculating the sensible cooling load for rooms.
public let sensibleHeatRatio: Double?
/// When the project was created in the database.
public let createdAt: Date
/// When the project was updated in the database.
public let updatedAt: Date
public init(
@@ -37,14 +50,20 @@ public struct Project: Codable, Equatable, Identifiable, Sendable {
}
extension Project {
/// Represents the data needed to create a new project.
public struct Create: Codable, Equatable, Sendable {
/// The name of the project.
public let name: String
/// The street address of the project.
public let streetAddress: String
/// The city of the project.
public let city: String
/// The state of the project.
public let state: String
/// The zip code of the project.
public let zipCode: String
/// The global sensible heat ratio for the project.
public let sensibleHeatRatio: Double?
public init(
@@ -64,11 +83,19 @@ extension Project {
}
}
/// Represents steps that are completed in order to calculate the duct sizes
/// for a project.
///
/// This is primarily used on the web pages to display errors or color of the
/// different steps of a project.
public struct CompletedSteps: Codable, Equatable, Sendable {
/// Whether there is ``EquipmentInfo`` for a project.
public let equipmentInfo: Bool
/// Whether there are ``Room``'s for a project.
public let rooms: Bool
/// Whether there are ``EquivalentLength``'s for a project.
public let equivalentLength: Bool
/// Whether there is a ``FrictionRate`` for a project.
public let frictionRate: Bool
public init(
@@ -84,20 +111,30 @@ extension Project {
}
}
/// Represents project details loaded from the database.
///
/// This is generally used to perform duct sizing calculations for the
/// project, once all the steps have been completed.
public struct Detail: Codable, Equatable, Sendable {
/// The project.
public let project: Project
/// The component pressure losses for the project.
public let componentLosses: [ComponentPressureLoss]
/// The equipment info for the project.
public let equipmentInfo: EquipmentInfo
public let equivalentLengths: [EffectiveLength]
/// The equivalent lengths for the project.
public let equivalentLengths: [EquivalentLength]
/// The rooms in the project.
public let rooms: [Room]
/// The trunk sizes in the project.
public let trunks: [TrunkSize]
public init(
project: Project,
componentLosses: [ComponentPressureLoss],
equipmentInfo: EquipmentInfo,
equivalentLengths: [EffectiveLength],
equivalentLengths: [EquivalentLength],
rooms: [Room],
trunks: [TrunkSize]
) {
@@ -110,13 +147,22 @@ extension Project {
}
}
/// Represents fields that can be updated for a project that has already been created.
///
/// Only fields that are supplied get updated in the database.
public struct Update: Codable, Equatable, Sendable {
/// The name of the project.
public let name: String?
/// The street address of the project.
public let streetAddress: String?
/// The city of the project.
public let city: String?
/// The state of the project.
public let state: String?
/// The zip code of the project.
public let zipCode: String?
/// The global sensible heat ratio for the project.
public let sensibleHeatRatio: Double?
public init(

View File

@@ -1,16 +1,37 @@
import Dependencies
import Foundation
/// Represents a room in a project.
///
/// This contains data such as the heating and cooling load for the
/// room, the number of registers in the room, and any rectangular
/// duct size calculations stored for the room.
public struct Room: Codable, Equatable, Identifiable, Sendable {
/// The unique id of the room.
public let id: UUID
/// The project this room is associated with.
public let projectID: Project.ID
/// A unique name for the room in the project.
public let name: String
/// The heating load required for the room (from Manual-J).
public let heatingLoad: Double
/// The total cooling load required for the room (from Manual-J).
public let coolingTotal: Double
/// An optional sensible cooling load for the room.
///
/// **NOTE:** This is generally not set, but calculated from the project wide
/// sensible heat ratio.
public let coolingSensible: Double?
/// The number of registers for the room.
public let registerCount: Int
/// The rectangular duct size calculations for a room.
///
/// **NOTE:** These are optionally set after the round sizes have been calculate
/// for a room.
public let rectangularSizes: [RectangularSize]?
/// When the room was created in the database.
public let createdAt: Date
/// When the room was updated in the database.
public let updatedAt: Date
public init(
@@ -39,13 +60,19 @@ public struct Room: Codable, Equatable, Identifiable, Sendable {
}
extension Room {
/// Represents the data required to create a new room for a project.
public struct Create: Codable, Equatable, Sendable {
/// The project this room is associated with.
public let projectID: Project.ID
/// A unique name for the room in the project.
public let name: String
/// The heating load required for the room (from Manual-J).
public let heatingLoad: Double
/// The total cooling load required for the room (from Manual-J).
public let coolingTotal: Double
/// An optional sensible cooling load for the room.
public let coolingSensible: Double?
/// The number of registers for the room.
public let registerCount: Int
public init(
@@ -65,10 +92,17 @@ extension Room {
}
}
/// Represents a rectangular size calculation that is stored in the
/// database for a given room.
///
/// These are done after the round duct sizes have been calculated and
/// can be used to calculate the equivalent rectangular size for a given run.
public struct RectangularSize: Codable, Equatable, Identifiable, Sendable {
/// The unique id of the rectangular size.
public let id: UUID
/// The register the rectangular size is associated with.
public let register: Int?
/// The height of the rectangular size, the width gets calculated.
public let height: Int
public init(
@@ -82,12 +116,21 @@ extension Room {
}
}
/// Represents field that can be updated on a room after it's been created in the database.
///
/// Only fields that are supplied get updated.
public struct Update: Codable, Equatable, Sendable {
/// A unique name for the room in the project.
public let name: String?
/// The heating load required for the room (from Manual-J).
public let heatingLoad: Double?
/// The total cooling load required for the room (from Manual-J).
public let coolingTotal: Double?
/// An optional sensible cooling load for the room.
public let coolingSensible: Double?
/// The number of registers for the room.
public let registerCount: Int?
/// The rectangular duct size calculations for a room.
public let rectangularSizes: [RectangularSize]?
public init(
@@ -120,14 +163,20 @@ extension Room {
extension Array where Element == Room {
/// The sum of heating loads for an array of rooms.
public var totalHeatingLoad: Double {
reduce(into: 0) { $0 += $1.heatingLoad }
}
/// The sum of total cooling loads for an array of rooms.
public var totalCoolingLoad: Double {
reduce(into: 0) { $0 += $1.coolingTotal }
}
/// The sum of sensible cooling loads for an array of rooms.
///
/// - Parameters:
/// - shr: The project wide sensible heat ratio.
public func totalCoolingSensible(shr: Double) -> Double {
reduce(into: 0) {
let sensible = $1.coolingSensible ?? ($1.coolingTotal * shr)
@@ -139,38 +188,6 @@ extension Array where Element == Room {
#if DEBUG
extension Room {
public static let mocks = [
Room(
id: UUID(0),
projectID: UUID(0),
name: "Kitchen",
heatingLoad: 12345,
coolingTotal: 1234,
registerCount: 2,
createdAt: Date(),
updatedAt: Date()
),
Room(
id: UUID(1),
projectID: UUID(1),
name: "Bedroom - 1",
heatingLoad: 12345,
coolingTotal: 1456,
registerCount: 1,
createdAt: Date(),
updatedAt: Date()
),
Room(
id: UUID(2),
projectID: UUID(2),
name: "Family Room",
heatingLoad: 12345,
coolingTotal: 1673,
registerCount: 3,
createdAt: Date(),
updatedAt: Date()
),
]
public static func mock(projectID: Project.ID) -> [Self] {
@Dependency(\.uuid) var uuid

View File

@@ -226,10 +226,10 @@ extension SiteRoute.Api {
extension SiteRoute.Api {
public enum EffectiveLengthRoute: Equatable, Sendable {
case create(EffectiveLength.Create)
case delete(id: EffectiveLength.ID)
case create(EquivalentLength.Create)
case delete(id: EquivalentLength.ID)
case fetch(projectID: Project.ID)
case get(id: EffectiveLength.ID)
case get(id: EquivalentLength.ID)
static let rootPath = "effectiveLength"
@@ -240,12 +240,12 @@ extension SiteRoute.Api {
"create"
}
Method.post
Body(.json(EffectiveLength.Create.self))
Body(.json(EquivalentLength.Create.self))
}
Route(.case(Self.delete(id:))) {
Path {
rootPath
EffectiveLength.ID.parser()
EquivalentLength.ID.parser()
}
Method.delete
}
@@ -261,7 +261,7 @@ extension SiteRoute.Api {
Route(.case(Self.get(id:))) {
Path {
rootPath
EffectiveLength.ID.parser()
EquivalentLength.ID.parser()
}
Method.get
}

View File

@@ -394,11 +394,11 @@ extension SiteRoute.View.ProjectRoute {
}
public enum EquivalentLengthRoute: Equatable, Sendable {
case delete(id: EffectiveLength.ID)
case field(FieldType, style: EffectiveLength.EffectiveLengthType? = nil)
case delete(id: EquivalentLength.ID)
case field(FieldType, style: EquivalentLength.EffectiveLengthType? = nil)
case index
case submit(FormStep)
case update(EffectiveLength.ID, StepThree)
case update(EquivalentLength.ID, StepThree)
static let rootPath = "effective-lengths"
@@ -406,7 +406,7 @@ extension SiteRoute.View.ProjectRoute {
Route(.case(Self.delete(id:))) {
Path {
rootPath
EffectiveLength.ID.parser()
EquivalentLength.ID.parser()
}
Method.delete
}
@@ -424,7 +424,7 @@ extension SiteRoute.View.ProjectRoute {
Field("type") { FieldType.parser() }
Optionally {
Field("style", default: nil) {
EffectiveLength.EffectiveLengthType.parser()
EquivalentLength.EffectiveLengthType.parser()
}
}
}
@@ -437,16 +437,16 @@ extension SiteRoute.View.ProjectRoute {
Route(.case(Self.update)) {
Path {
rootPath
EffectiveLength.ID.parser()
EquivalentLength.ID.parser()
}
Method.patch
Body {
FormData {
Optionally {
Field("id", default: nil) { EffectiveLength.ID.parser() }
Field("id", default: nil) { EquivalentLength.ID.parser() }
}
Field("name", .string)
Field("type") { EffectiveLength.EffectiveLengthType.parser() }
Field("type") { EquivalentLength.EffectiveLengthType.parser() }
Many {
Field("straightLengths") {
Int.parser()
@@ -490,10 +490,10 @@ extension SiteRoute.View.ProjectRoute {
Body {
FormData {
Optionally {
Field("id", default: nil) { EffectiveLength.ID.parser() }
Field("id", default: nil) { EquivalentLength.ID.parser() }
}
Field("name", .string)
Field("type") { EffectiveLength.EffectiveLengthType.parser() }
Field("type") { EquivalentLength.EffectiveLengthType.parser() }
}
.map(.memberwise(StepOne.init))
}
@@ -505,10 +505,10 @@ extension SiteRoute.View.ProjectRoute {
Body {
FormData {
Optionally {
Field("id", default: nil) { EffectiveLength.ID.parser() }
Field("id", default: nil) { EquivalentLength.ID.parser() }
}
Field("name", .string)
Field("type") { EffectiveLength.EffectiveLengthType.parser() }
Field("type") { EquivalentLength.EffectiveLengthType.parser() }
Many {
Field("straightLengths") {
Int.parser()
@@ -525,10 +525,10 @@ extension SiteRoute.View.ProjectRoute {
Body {
FormData {
Optionally {
Field("id", default: nil) { EffectiveLength.ID.parser() }
Field("id", default: nil) { EquivalentLength.ID.parser() }
}
Field("name", .string)
Field("type") { EffectiveLength.EffectiveLengthType.parser() }
Field("type") { EquivalentLength.EffectiveLengthType.parser() }
Many {
Field("straightLengths") {
Int.parser()
@@ -567,22 +567,22 @@ extension SiteRoute.View.ProjectRoute {
}
public struct StepOne: Codable, Equatable, Sendable {
public let id: EffectiveLength.ID?
public let id: EquivalentLength.ID?
public let name: String
public let type: EffectiveLength.EffectiveLengthType
public let type: EquivalentLength.EffectiveLengthType
}
public struct StepTwo: Codable, Equatable, Sendable {
public let id: EffectiveLength.ID?
public let id: EquivalentLength.ID?
public let name: String
public let type: EffectiveLength.EffectiveLengthType
public let type: EquivalentLength.EffectiveLengthType
public let straightLengths: [Int]
public init(
id: EffectiveLength.ID? = nil,
id: EquivalentLength.ID? = nil,
name: String,
type: EffectiveLength.EffectiveLengthType,
type: EquivalentLength.EffectiveLengthType,
straightLengths: [Int]
) {
self.id = id
@@ -593,9 +593,9 @@ extension SiteRoute.View.ProjectRoute {
}
public struct StepThree: Codable, Equatable, Sendable {
public let id: EffectiveLength.ID?
public let id: EquivalentLength.ID?
public let name: String
public let type: EffectiveLength.EffectiveLengthType
public let type: EquivalentLength.EffectiveLengthType
public let straightLengths: [Int]
public let groupGroups: [Int]
public let groupLetters: [String]

View File

@@ -1,5 +1,6 @@
import Foundation
/// Represents supported color themes for the website.
public enum Theme: String, CaseIterable, Codable, Equatable, Sendable {
case aqua
case cupcake
@@ -13,6 +14,7 @@ public enum Theme: String, CaseIterable, Codable, Equatable, Sendable {
case retro
case synthwave
/// Represents dark color themes.
public static let darkThemes = [
Self.aqua,
Self.cyberpunk,
@@ -22,6 +24,7 @@ public enum Theme: String, CaseIterable, Codable, Equatable, Sendable {
Self.synthwave,
]
/// Represents light color themes.
public static let lightThemes = [
Self.cupcake,
Self.light,

View File

@@ -1,14 +1,23 @@
import Dependencies
import Foundation
// Represents the database model.
/// Represents trunk calculations for a project.
///
/// These are used to size trunk ducts / runs for multiple rooms or registers.
public struct TrunkSize: Codable, Equatable, Identifiable, Sendable {
/// The unique identifier of the trunk size.
public let id: UUID
/// The project the trunk size is for.
public let projectID: Project.ID
/// The type of the trunk size (supply or return).
public let type: TrunkType
/// The rooms / registers associated with the trunk size.
public let rooms: [RoomProxy]
/// An optional rectangular height used to calculate the equivalent
/// rectangular size of the trunk.
public let height: Int?
/// An optional name / label used for identifying the trunk.
public let name: String?
public init(
@@ -29,12 +38,19 @@ public struct TrunkSize: Codable, Equatable, Identifiable, Sendable {
}
extension TrunkSize {
/// Represents the data needed to create a new ``TrunkSize`` in the database.
public struct Create: Codable, Equatable, Sendable {
/// The project the trunk size is for.
public let projectID: Project.ID
/// The type of the trunk size (supply or return).
public let type: TrunkType
/// The rooms / registers associated with the trunk size.
public let rooms: [Room.ID: [Int]]
/// An optional rectangular height used to calculate the equivalent
/// rectangular size of the trunk.
public let height: Int?
/// An optional name / label used for identifying the trunk.
public let name: String?
public init(
@@ -52,11 +68,19 @@ extension TrunkSize {
}
}
/// Represents the fields that can be updated on a ``TrunkSize`` in the database.
///
/// Only supplied fields are updated.
public struct Update: Codable, Equatable, Sendable {
/// The type of the trunk size (supply or return).
public let type: TrunkType?
/// The rooms / registers associated with the trunk size.
public let rooms: [Room.ID: [Int]]?
/// An optional rectangular height used to calculate the equivalent
/// rectangular size of the trunk.
public let height: Int?
/// An optional name / label used for identifying the trunk.
public let name: String?
public init(
@@ -72,18 +96,29 @@ extension TrunkSize {
}
}
public struct RoomProxy: Codable, Equatable, Identifiable, Sendable {
/// A container / wrapper around a ``Room`` that is used with a ``TrunkSize``.
///
/// This is needed because a room can have multiple registers and it is possible
/// that a trunk does not serve all registers in that room.
@dynamicMemberLookup
public struct RoomProxy: Codable, Equatable, Sendable {
public var id: Room.ID { room.id }
/// The room associated with the ``TrunkSize``.
public let room: Room
/// The specific room registers associated with the ``TrunkSize``.
public let registers: [Int]
public init(room: Room, registers: [Int]) {
self.room = room
self.registers = registers
}
public subscript<T>(dynamicMember keyPath: KeyPath<Room, T>) -> T {
room[keyPath: keyPath]
}
}
/// Represents the type of a ``TrunkSize``, either supply or return.
public enum TrunkType: String, CaseIterable, Codable, Equatable, Sendable {
case `return`
case supply

View File

@@ -1,12 +1,17 @@
import Dependencies
import Foundation
// FIX: Remove username.
/// Represents a user of the site.
///
public struct User: Codable, Equatable, Identifiable, Sendable {
/// The unique id of the user.
public let id: UUID
/// The user's email address.
public let email: String
/// When the user was created in the database.
public let createdAt: Date
/// When the user was updated in the database.
public let updatedAt: Date
public init(
@@ -23,10 +28,14 @@ public struct User: Codable, Equatable, Identifiable, Sendable {
}
extension User {
/// Represents the data required to create a new user.
public struct Create: Codable, Equatable, Sendable {
/// The user's email address.
public let email: String
/// The password for the user.
public let password: String
/// The password confirmation, must match the password.
public let confirmPassword: String
public init(
@@ -40,9 +49,13 @@ extension User {
}
}
/// Represents data required to login a user.
public struct Login: Codable, Equatable, Sendable {
/// The user's email address.
public let email: String
/// The password for the user.
public let password: String
/// An optional page / route to navigate to after logging in the user.
public let next: String?
public init(email: String, password: String, next: String? = nil) {
@@ -52,10 +65,13 @@ extension User {
}
}
/// Represents a user session token, for a logged in user.
public struct Token: Codable, Equatable, Identifiable, Sendable {
/// The unique id of the token.
public let id: UUID
/// The user id the token is for.
public let userID: User.ID
/// The token value.
public let value: String
public init(id: UUID, userID: User.ID, value: String) {

View File

@@ -2,19 +2,32 @@ import Dependencies
import Foundation
extension User {
/// Represents a user's profile. Which contains extra information about a user of the site.
public struct Profile: Codable, Equatable, Identifiable, Sendable {
/// The unique id of the profile
public let id: UUID
/// The user id the profile is for.
public let userID: User.ID
/// The user's first name.
public let firstName: String
/// The user's last name.
public let lastName: String
/// The user's company name.
public let companyName: String
/// The user's street address.
public let streetAddress: String
/// The user's city.
public let city: String
/// The user's state.
public let state: String
/// The user's zip code.
public let zipCode: String
/// An optional theme that the user prefers.
public let theme: Theme?
/// When the profile was created in the database.
public let createdAt: Date
/// When the profile was updated in the database.
public let updatedAt: Date
public init(
@@ -49,15 +62,25 @@ extension User {
extension User.Profile {
/// Represents the data required to create a user profile.
public struct Create: Codable, Equatable, Sendable {
/// The user id the profile is for.
public let userID: User.ID
/// The user's first name.
public let firstName: String
/// The user's last name.
public let lastName: String
/// The user's company name.
public let companyName: String
/// The user's street address.
public let streetAddress: String
/// The user's city.
public let city: String
/// The user's state.
public let state: String
/// The user's zip code.
public let zipCode: String
/// An optional theme that the user prefers.
public let theme: Theme?
public init(
@@ -83,14 +106,25 @@ extension User.Profile {
}
}
/// Represents the fields that can be updated on a user's profile.
///
/// Only fields that are supplied get updated.
public struct Update: Codable, Equatable, Sendable {
/// The user's first name.
public let firstName: String?
/// The user's last name.
public let lastName: String?
/// The user's company name.
public let companyName: String?
/// The user's street address.
public let streetAddress: String?
/// The user's city.
public let city: String?
/// The user's state.
public let state: String?
/// The user's zip code.
public let zipCode: String?
/// An optional theme that the user prefers.
public let theme: Theme?
public init(

View File

@@ -32,8 +32,7 @@ public struct PdfClient: Sendable {
/// - Parameters:
/// - request: The project data used to generate the pdf.
public func generatePdf(request: Request) async throws -> Response {
let html = try await self.html(request)
return try await self.generatePdf(request.project.id, html)
try await self.generatePdf(request.project.id, html(request))
}
}
@@ -76,17 +75,26 @@ extension PdfClient: DependencyKey {
}
extension PdfClient {
/// Container for the data required to generate a pdf for a given project.
/// Represents the data required to generate a pdf for a given project.
public struct Request: Codable, Equatable, Sendable {
/// The project we're generating a pdf for.
public let project: Project
/// The rooms in the project.
public let rooms: [Room]
/// The component pressure losses for the project.
public let componentLosses: [ComponentPressureLoss]
/// The calculated duct sizes for the project.
public let ductSizes: DuctSizes
/// The equipment information for the project.
public let equipmentInfo: EquipmentInfo
public let maxSupplyTEL: EffectiveLength
public let maxReturnTEL: EffectiveLength
/// The max supply equivalent length for the project.
public let maxSupplyTEL: EquivalentLength
/// The max return equivalent length for the project.
public let maxReturnTEL: EquivalentLength
/// The calculated design friction rate for the project.
public let frictionRate: FrictionRate
/// The project wide sensible heat ratio.
public let projectSHR: Double
var totalEquivalentLength: Double {
@@ -99,8 +107,8 @@ extension PdfClient {
componentLosses: [ComponentPressureLoss],
ductSizes: DuctSizes,
equipmentInfo: EquipmentInfo,
maxSupplyTEL: EffectiveLength,
maxReturnTEL: EffectiveLength,
maxSupplyTEL: EquivalentLength,
maxReturnTEL: EquivalentLength,
frictionRate: FrictionRate,
projectSHR: Double
) {
@@ -116,9 +124,12 @@ extension PdfClient {
}
}
/// Represents the response after generating a pdf.
public struct Response: Equatable, Sendable {
/// The path to the html file used to generate the pdf from.
public let htmlPath: String
/// The path to the pdf file.
public let pdfPath: String
public init(htmlPath: String, pdfPath: String) {
@@ -134,7 +145,7 @@ extension PdfClient {
let rooms = Room.mock(projectID: project.id)
let trunks = TrunkSize.mock(projectID: project.id, rooms: rooms)
let equipmentInfo = EquipmentInfo.mock(projectID: project.id)
let equivalentLengths = EffectiveLength.mock(projectID: project.id)
let equivalentLengths = EquivalentLength.mock(projectID: project.id)
return .init(
project: project,

View File

@@ -2,7 +2,7 @@ import Elementary
import ManualDCore
struct EffectiveLengthsTable: HTML, Sendable {
let effectiveLengths: [EffectiveLength]
let effectiveLengths: [EquivalentLength]
var body: some HTML<HTMLTag.table> {
table {
@@ -41,7 +41,7 @@ struct EffectiveLengthsTable: HTML, Sendable {
}
struct EffectiveLengthGroupTable: HTML, Sendable {
let groups: [EffectiveLength.Group]
let groups: [EquivalentLength.FittingGroup]
var body: some HTML<HTMLTag.table> {
table {

View File

@@ -1,9 +0,0 @@
import Foundation
public struct ProjectClientError: Error {
public let reason: String
public init(_ reason: String) {
self.reason = reason
}
}

View File

@@ -15,12 +15,15 @@ extension DependencyValues {
/// Useful helper utilities for project's.
///
/// This is primarily used for implementing logic required to get the needed data
/// for the view controller client to render views.
/// for the view controller to render views.
@DependencyClient
public struct ProjectClient: Sendable {
public var calculateDuctSizes: @Sendable (Project.ID) async throws -> DuctSizes
/// Calculates the room duct sizes for the given project.
public var calculateRoomDuctSizes:
@Sendable (Project.ID) async throws -> [DuctSizes.RoomContainer]
/// Calculates the trunk duct sizes for the given project.
public var calculateTrunkDuctSizes:
@Sendable (Project.ID) async throws -> [DuctSizes.TrunkContainer]
@@ -29,6 +32,13 @@ public struct ProjectClient: Sendable {
public var frictionRate: @Sendable (Project.ID) async throws -> FrictionRateResponse
public var generatePdf: @Sendable (Project.ID) async throws -> Response
public func calculateDuctSizes(_ projectID: Project.ID) async throws -> DuctSizes {
.init(
rooms: try await calculateRoomDuctSizes(projectID),
trunks: try await calculateTrunkDuctSizes(projectID)
)
}
}
extension ProjectClient: TestDependencyKey {
@@ -60,12 +70,12 @@ extension ProjectClient {
public struct FrictionRateResponse: Codable, Equatable, Sendable {
public let componentLosses: [ComponentPressureLoss]
public let equivalentLengths: EffectiveLength.MaxContainer
public let equivalentLengths: EquivalentLength.MaxContainer
public let frictionRate: FrictionRate?
public init(
componentLosses: [ComponentPressureLoss],
equivalentLengths: EffectiveLength.MaxContainer,
equivalentLengths: EquivalentLength.MaxContainer,
frictionRate: FrictionRate? = nil
) {
self.componentLosses = componentLosses

View File

@@ -1,7 +1,7 @@
import DatabaseClient
import ManualDCore
extension DatabaseClient.ComponentLoss {
extension DatabaseClient.ComponentLosses {
func createDefaults(projectID: Project.ID) async throws {
let defaults = ComponentPressureLoss.Create.default(projectID: projectID)

View File

@@ -9,32 +9,18 @@ extension DatabaseClient {
details: Project.Detail
) async throws -> (DuctSizes, DuctSizeSharedRequest) {
let (rooms, shared) = try await calculateRoomDuctSizes(details: details)
let (trunks, _) = try await calculateTrunkDuctSizes(details: details)
return (.init(rooms: rooms, trunks: trunks), shared)
}
func calculateDuctSizes(
projectID: Project.ID
) async throws -> (DuctSizes, DuctSizeSharedRequest, [Room]) {
@Dependency(\.manualD) var manualD
let shared = try await sharedDuctRequest(projectID)
let rooms = try await rooms.fetch(projectID)
return try await (
manualD.calculateDuctSizes(
.init(
rooms: rooms,
trunks: trunkSizes.fetch(projectID),
sharedRequest: shared
trunks: calculateTrunkDuctSizes(details: details, shared: shared)
),
shared,
rooms
shared
)
}
func calculateRoomDuctSizes(
details: Project.Detail
) async throws -> ([DuctSizes.RoomContainer], DuctSizeSharedRequest) {
) async throws -> (rooms: [DuctSizes.RoomContainer], shared: DuctSizeSharedRequest) {
@Dependency(\.manualD) var manualD
let shared = try sharedDuctRequest(details: details)
@@ -42,54 +28,29 @@ extension DatabaseClient {
return (rooms, shared)
}
func calculateRoomDuctSizes(
projectID: Project.ID
) async throws -> ([DuctSizes.RoomContainer], DuctSizeSharedRequest) {
@Dependency(\.manualD) var manualD
let shared = try await sharedDuctRequest(projectID)
return try await (
manualD.calculateRoomSizes(
rooms: rooms.fetch(projectID),
sharedRequest: shared
),
shared
)
}
func calculateTrunkDuctSizes(
details: Project.Detail
) async throws -> ([DuctSizes.TrunkContainer], DuctSizeSharedRequest) {
details: Project.Detail,
shared: DuctSizeSharedRequest? = nil
) async throws -> [DuctSizes.TrunkContainer] {
@Dependency(\.manualD) var manualD
let shared = try sharedDuctRequest(details: details)
let trunks = try await manualD.calculateTrunkSizes(
let sharedRequest: DuctSizeSharedRequest
if let shared {
sharedRequest = shared
} else {
sharedRequest = try sharedDuctRequest(details: details)
}
return try await manualD.calculateTrunkSizes(
rooms: details.rooms,
trunks: details.trunks,
sharedRequest: shared
)
return (trunks, shared)
}
func calculateTrunkDuctSizes(
projectID: Project.ID
) async throws -> ([DuctSizes.TrunkContainer], DuctSizeSharedRequest) {
@Dependency(\.manualD) var manualD
let shared = try await sharedDuctRequest(projectID)
return try await (
manualD.calculateTrunkSizes(
rooms: rooms.fetch(projectID),
trunks: trunkSizes.fetch(projectID),
sharedRequest: shared
),
shared
sharedRequest: sharedRequest
)
}
func sharedDuctRequest(details: Project.Detail) throws -> DuctSizeSharedRequest {
let projectSHR = try details.project.ensuredSHR()
guard
let dfrResponse = designFrictionRate(
componentLosses: details.componentLosses,
@@ -100,10 +61,6 @@ extension DatabaseClient {
throw ProjectClientError("Project not complete.")
}
guard let projectSHR = details.project.sensibleHeatRatio else {
throw ProjectClientError("Project sensible heat ratio not set.")
}
let ensuredTEL = try dfrResponse.ensureMaxContainer()
return .init(
@@ -115,40 +72,14 @@ extension DatabaseClient {
)
}
func sharedDuctRequest(_ projectID: Project.ID) async throws -> DuctSizeSharedRequest {
guard let dfrResponse = try await designFrictionRate(projectID: projectID) else {
throw ProjectClientError("Project not complete.")
}
let ensuredTEL = try dfrResponse.ensureMaxContainer()
return try await .init(
equipmentInfo: dfrResponse.equipmentInfo,
maxSupplyLength: ensuredTEL.supply,
maxReturnLenght: ensuredTEL.return,
designFrictionRate: dfrResponse.designFrictionRate,
projectSHR: ensuredSHR(projectID)
)
}
// Fetches the project sensible heat ratio or throws an error if it's nil.
func ensuredSHR(_ projectID: Project.ID) async throws -> Double {
guard let projectSHR = try await projects.getSensibleHeatRatio(projectID) else {
throw ProjectClientError("Project sensible heat ratio not set.")
}
return projectSHR
}
// Internal container.
struct DesignFrictionRateResponse: Equatable, Sendable {
typealias EnsuredTEL = (supply: EffectiveLength, return: EffectiveLength)
typealias EnsuredTEL = (supply: EquivalentLength, return: EquivalentLength)
let designFrictionRate: Double
let equipmentInfo: EquipmentInfo
let telMaxContainer: EffectiveLength.MaxContainer
let telMaxContainer: EquivalentLength.MaxContainer
func ensureMaxContainer() throws -> EnsuredTEL {
@@ -167,9 +98,9 @@ extension DatabaseClient {
func designFrictionRate(
componentLosses: [ComponentPressureLoss],
equipmentInfo: EquipmentInfo,
equivalentLengths: EffectiveLength.MaxContainer
equivalentLengths: EquivalentLength.MaxContainer
) -> DesignFrictionRateResponse? {
guard let tel = equivalentLengths.total,
guard let tel = equivalentLengths.totalEquivalentLength,
componentLosses.count > 0
else { return nil }
@@ -183,18 +114,13 @@ extension DatabaseClient {
}
func designFrictionRate(
projectID: Project.ID
) async throws -> DesignFrictionRateResponse? {
}
guard let equipmentInfo = try await equipment.fetch(projectID) else {
return nil
extension Project {
func ensuredSHR() throws -> Double {
guard let shr = sensibleHeatRatio else {
throw ProjectClientError("Sensible heat ratio not set on project id: \(id)")
}
return try await designFrictionRate(
componentLosses: componentLoss.fetch(projectID),
equipmentInfo: equipmentInfo,
equivalentLengths: effectiveLength.fetchMax(projectID)
)
return shr
}
}

View File

@@ -0,0 +1,53 @@
import DatabaseClient
import Dependencies
import ManualDClient
import ManualDCore
import PdfClient
extension DatabaseClient {
/// Generate a pdf request for the given project.
func makePdfRequest(_ projectID: Project.ID) async throws -> PdfClient.Request {
@Dependency(\.manualD) var manualD
guard let projectDetails = try await projects.detail(projectID) else {
throw ProjectClientError.notFound(.project(projectID))
}
let (ductSizes, shared) = try await calculateDuctSizes(details: projectDetails)
let frictionRateResponse = try await manualD.frictionRate(details: projectDetails)
guard let frictionRate = frictionRateResponse.frictionRate else {
throw ProjectClientError.notFound(.frictionRate(projectID))
}
return .init(
details: projectDetails,
ductSizes: ductSizes,
shared: shared,
frictionRate: frictionRate
)
}
}
extension PdfClient.Request {
fileprivate init(
details: Project.Detail,
ductSizes: DuctSizes,
shared: DuctSizeSharedRequest,
frictionRate: FrictionRate
) {
self.init(
project: details.project,
rooms: details.rooms,
componentLosses: details.componentLosses,
ductSizes: ductSizes,
equipmentInfo: details.equipmentInfo,
maxSupplyTEL: shared.maxSupplyLength,
maxReturnTEL: shared.maxReturnLenght,
frictionRate: frictionRate,
projectSHR: shared.projectSHR
)
}
}

View File

@@ -4,8 +4,8 @@ import ManualDCore
struct DuctSizeSharedRequest {
let equipmentInfo: EquipmentInfo
let maxSupplyLength: EffectiveLength
let maxReturnLenght: EffectiveLength
let maxSupplyLength: EquivalentLength
let maxReturnLenght: EquivalentLength
let designFrictionRate: Double
let projectSHR: Double
}
@@ -52,7 +52,8 @@ extension ManualDClient {
let coolingCFM = coolingPercent * Double(sharedRequest.equipmentInfo.coolingCFM)
let designCFM = DuctSizes.DesignCFM(heating: heatingCFM, cooling: coolingCFM)
let sizes = try await self.ductSize(
.init(designCFM: Int(designCFM.value), frictionRate: sharedRequest.designFrictionRate)
cfm: designCFM.value,
frictionRate: sharedRequest.designFrictionRate
)
for n in 1...room.registerCount {
@@ -63,7 +64,8 @@ extension ManualDClient {
if let rectangularSize {
let response = try await self.rectangularSize(
.init(round: sizes.finalSize, height: rectangularSize.height)
round: sizes.finalSize,
height: rectangularSize.height
)
rectangularWidth = response.width
}
@@ -111,12 +113,14 @@ extension ManualDClient {
let coolingCFM = coolingPercent * Double(sharedRequest.equipmentInfo.coolingCFM)
let designCFM = DuctSizes.DesignCFM(heating: heatingCFM, cooling: coolingCFM)
let sizes = try await self.ductSize(
.init(designCFM: Int(designCFM.value), frictionRate: sharedRequest.designFrictionRate)
cfm: designCFM.value,
frictionRate: sharedRequest.designFrictionRate
)
var width: Int? = nil
if let height = trunk.height {
let rectangularSize = try await self.rectangularSize(
.init(round: sizes.finalSize, height: height)
round: sizes.finalSize,
height: height
)
width = rectangularSize.width
}
@@ -142,7 +146,7 @@ extension ManualDClient {
extension DuctSizes.SizeContainer {
init(
designCFM: DuctSizes.DesignCFM,
sizes: ManualDClient.DuctSizeResponse,
sizes: ManualDClient.DuctSize,
height: Int?,
width: Int?
) {
@@ -160,7 +164,7 @@ extension DuctSizes.SizeContainer {
init(
designCFM: DuctSizes.DesignCFM,
sizes: ManualDClient.DuctSizeResponse,
sizes: ManualDClient.DuctSize,
rectangularSize: Room.RectangularSize?,
width: Int?
) {

View File

@@ -8,7 +8,7 @@ extension ManualDClient {
func frictionRate(details: Project.Detail) async throws -> ProjectClient.FrictionRateResponse {
let maxContainer = details.maxContainer
guard let totalEquivalentLength = maxContainer.total else {
guard let totalEquivalentLength = maxContainer.totalEquivalentLength else {
return .init(componentLosses: details.componentLosses, equivalentLengths: maxContainer)
}
@@ -19,7 +19,7 @@ extension ManualDClient {
.init(
externalStaticPressure: details.equipmentInfo.staticPressure,
componentPressureLosses: details.componentLosses,
totalEffectiveLength: Int(totalEquivalentLength)
totalEquivalentLength: Int(totalEquivalentLength)
)
)
)
@@ -28,15 +28,15 @@ extension ManualDClient {
func frictionRate(projectID: Project.ID) async throws -> ProjectClient.FrictionRateResponse {
@Dependency(\.database) var database
let componentLosses = try await database.componentLoss.fetch(projectID)
let lengths = try await database.effectiveLength.fetchMax(projectID)
let componentLosses = try await database.componentLosses.fetch(projectID)
let lengths = try await database.equivalentLengths.fetchMax(projectID)
let equipmentInfo = try await database.equipment.fetch(projectID)
guard let staticPressure = equipmentInfo?.staticPressure else {
return .init(componentLosses: componentLosses, equivalentLengths: lengths)
}
guard let totalEquivalentLength = lengths.total else {
guard let totalEquivalentLength = lengths.totalEquivalentLength else {
return .init(componentLosses: componentLosses, equivalentLengths: lengths)
}
@@ -46,8 +46,8 @@ extension ManualDClient {
frictionRate: frictionRate(
.init(
externalStaticPressure: staticPressure,
componentPressureLosses: database.componentLoss.fetch(projectID),
totalEffectiveLength: Int(totalEquivalentLength)
componentPressureLosses: componentLosses,
totalEquivalentLength: Int(totalEquivalentLength)
)
)
)

View File

@@ -1,7 +1,7 @@
import ManualDCore
extension Project.Detail {
var maxContainer: EffectiveLength.MaxContainer {
var maxContainer: EquivalentLength.MaxContainer {
.init(
supply: equivalentLengths.filter({ $0.type == .supply })
.sorted(by: { $0.totalEquivalentLength > $1.totalEquivalentLength })

View File

@@ -15,18 +15,21 @@ extension ProjectClient: DependencyKey {
@Dependency(\.fileClient) var fileClient
return .init(
calculateDuctSizes: { projectID in
try await database.calculateDuctSizes(projectID: projectID).0
},
calculateRoomDuctSizes: { projectID in
try await database.calculateRoomDuctSizes(projectID: projectID).0
guard let details = try await database.projects.detail(projectID) else {
throw ProjectClientError.notFound(.project(projectID))
}
return try await database.calculateRoomDuctSizes(details: details).rooms
},
calculateTrunkDuctSizes: { projectID in
try await database.calculateTrunkDuctSizes(projectID: projectID).0
guard let details = try await database.projects.detail(projectID) else {
throw ProjectClientError.notFound(.project(projectID))
}
return try await database.calculateTrunkDuctSizes(details: details)
},
createProject: { userID, request in
let project = try await database.projects.create(userID, request)
try await database.componentLoss.createDefaults(projectID: project.id)
try await database.componentLosses.createDefaults(projectID: project.id)
return try await .init(
projectID: project.id,
rooms: database.rooms.fetch(project.id),
@@ -42,13 +45,10 @@ extension ProjectClient: DependencyKey {
request: database.makePdfRequest(projectID)
)
let response = try await fileClient.streamFile(
pdfResponse.pdfPath,
{
try await fileClient.removeFile(pdfResponse.htmlPath)
try await fileClient.removeFile(pdfResponse.pdfPath)
}
)
let response = try await fileClient.streamFile(at: pdfResponse.pdfPath) {
try await fileClient.removeFile(pdfResponse.htmlPath)
try await fileClient.removeFile(pdfResponse.pdfPath)
}
response.headers.replaceOrAdd(name: .contentType, value: "application/octet-stream")
response.headers.replaceOrAdd(
@@ -61,50 +61,3 @@ extension ProjectClient: DependencyKey {
}
}
extension DatabaseClient {
fileprivate func makePdfRequest(_ projectID: Project.ID) async throws -> PdfClient.Request {
@Dependency(\.manualD) var manualD
guard let projectDetails = try await projects.detail(projectID) else {
throw ProjectClientError("Project not found. id: \(projectID)")
}
let (ductSizes, shared) = try await calculateDuctSizes(details: projectDetails)
let frictionRateResponse = try await manualD.frictionRate(details: projectDetails)
guard let frictionRate = frictionRateResponse.frictionRate else {
throw ProjectClientError("Friction rate not found. id: \(projectID)")
}
return .init(
details: projectDetails,
ductSizes: ductSizes,
shared: shared,
frictionRate: frictionRate
)
}
}
extension PdfClient.Request {
init(
details: Project.Detail,
ductSizes: DuctSizes,
shared: DuctSizeSharedRequest,
frictionRate: FrictionRate
) {
self.init(
project: details.project,
rooms: details.rooms,
componentLosses: details.componentLosses,
ductSizes: ductSizes,
equipmentInfo: details.equipmentInfo,
maxSupplyTEL: shared.maxSupplyLength,
maxReturnTEL: shared.maxReturnLenght,
frictionRate: frictionRate,
projectSHR: shared.projectSHR
)
}
}

View File

@@ -0,0 +1,35 @@
import Foundation
import ManualDCore
public struct ProjectClientError: Error {
public let reason: String
public init(_ reason: String) {
self.reason = reason
}
static func notFound(_ notFound: NotFound) -> Self {
.init(notFound.reason)
}
enum NotFound {
case project(Project.ID)
case frictionRate(Project.ID)
var reason: String {
switch self {
case .project(let id):
return "Project not found. id: \(id)"
case .frictionRate(let id):
return """
Friction unable to be calculated. id: \(id)
This usually means that not all the required steps have been completed.
Calculating the friction rate requires the component pressure losses to be set and
have a max equivalent length for both the supply and return.
"""
}
}
}
}

View File

@@ -1,4 +1,5 @@
import Elementary
import Tagged
public struct Badge<Inner: HTML>: HTML, Sendable where Inner: Sendable {
@@ -25,4 +26,12 @@ extension Badge where Inner == Number {
public init(number: Double, digits: Int = 2) {
self.inner = Number(number, digits: digits)
}
public init<T>(number: Tagged<T, Int>) {
self.inner = Number(number.rawValue)
}
public init<T>(number: Tagged<T, Double>, digits: Int = 2) {
self.inner = Number(number.rawValue, digits: digits)
}
}

View File

@@ -12,8 +12,8 @@ extension SiteRoute.View.ProjectRoute.EquivalentLengthRoute.StepThree {
}
}
var groups: [EffectiveLength.Group] {
var groups = [EffectiveLength.Group]()
var groups: [EquivalentLength.FittingGroup] {
var groups = [EquivalentLength.FittingGroup]()
for (n, group) in groupGroups.enumerated() {
groups.append(
.init(
@@ -29,7 +29,7 @@ extension SiteRoute.View.ProjectRoute.EquivalentLengthRoute.StepThree {
}
}
extension EffectiveLength.Create {
extension EquivalentLength.Create {
init(
form: SiteRoute.View.ProjectRoute.EquivalentLengthRoute.StepThree,
@@ -45,7 +45,7 @@ extension EffectiveLength.Create {
}
}
extension EffectiveLength.Update {
extension EquivalentLength.Update {
init(
form: SiteRoute.View.ProjectRoute.EquivalentLengthRoute.StepThree,
projectID: Project.ID

View File

@@ -54,14 +54,14 @@ extension ViewController: DependencyKey {
extension ViewController.Request {
func currentUser() throws -> User {
@Dependency(\.authClient.currentUser) var currentUser
@Dependency(\.auth.currentUser) var currentUser
return try currentUser()
}
func authenticate(
_ login: User.Login
) async throws -> User {
@Dependency(\.authClient) var auth
@Dependency(\.auth) var auth
return try await auth.login(login)
}
@@ -69,7 +69,7 @@ extension ViewController.Request {
func createAndAuthenticate(
_ signup: User.Create
) async throws -> User {
@Dependency(\.authClient) var auth
@Dependency(\.auth) var auth
return try await auth.createAndLogin(signup)
}
}

View File

@@ -70,7 +70,7 @@ extension ViewController.Request {
case .submitProfile(let profile):
return await view {
await ResultView {
_ = try await database.userProfile.create(profile)
_ = try await database.userProfiles.create(profile)
let userID = profile.userID
// let user = try currentUser()
return (
@@ -108,7 +108,7 @@ extension ViewController.Request {
get async {
@Dependency(\.database) var database
guard let user = try? currentUser() else { return nil }
return try? await database.userProfile.fetch(user.id)?.theme
return try? await database.userProfiles.fetch(user.id)?.theme
}
}
@@ -366,8 +366,8 @@ extension SiteRoute.View.ProjectRoute.FrictionRateRoute {
return await request.view {
await ResultView {
let equipment = try await database.equipment.fetch(projectID)
let componentLosses = try await database.componentLoss.fetch(projectID)
let lengths = try await database.effectiveLength.fetchMax(projectID)
let componentLosses = try await database.componentLosses.fetch(projectID)
let lengths = try await database.equivalentLengths.fetchMax(projectID)
return (
try await database.projects.getCompletedSteps(projectID),
@@ -407,16 +407,16 @@ extension SiteRoute.View.ProjectRoute.ComponentLossRoute {
return EmptyHTML()
case .delete(let id):
return await view(on: request, projectID: projectID) {
_ = try await database.componentLoss.delete(id)
_ = try await database.componentLosses.delete(id)
}
case .submit(let form):
return await view(on: request, projectID: projectID) {
_ = try await database.componentLoss.create(form)
_ = try await database.componentLosses.create(form)
}
case .update(let id, let form):
return await view(on: request, projectID: projectID) {
_ = try await database.componentLoss.update(id, form)
_ = try await database.componentLosses.update(id, form)
}
}
}
@@ -464,7 +464,7 @@ extension SiteRoute.View.ProjectRoute.EquivalentLengthRoute {
case .delete(let id):
return await ResultView {
try await database.effectiveLength.delete(id)
try await database.equivalentLengths.delete(id)
}
case .index:
@@ -481,16 +481,16 @@ extension SiteRoute.View.ProjectRoute.EquivalentLengthRoute {
case .update(let id, let form):
return await view(on: request, projectID: projectID) {
_ = try await database.effectiveLength.update(id, .init(form: form, projectID: projectID))
_ = try await database.equivalentLengths.update(id, .init(form: form, projectID: projectID))
}
case .submit(let step):
switch step {
case .one(let stepOne):
return await ResultView {
var effectiveLength: EffectiveLength? = nil
var effectiveLength: EquivalentLength? = nil
if let id = stepOne.id {
effectiveLength = try await database.effectiveLength.get(id)
effectiveLength = try await database.equivalentLengths.get(id)
}
return effectiveLength
} onSuccess: { effectiveLength in
@@ -503,9 +503,9 @@ extension SiteRoute.View.ProjectRoute.EquivalentLengthRoute {
case .two(let stepTwo):
return await ResultView {
request.logger.debug("ViewController: Got step two...")
var effectiveLength: EffectiveLength? = nil
var effectiveLength: EquivalentLength? = nil
if let id = stepTwo.id {
effectiveLength = try await database.effectiveLength.get(id)
effectiveLength = try await database.equivalentLengths.get(id)
}
return effectiveLength
} onSuccess: { effectiveLength in
@@ -515,7 +515,7 @@ extension SiteRoute.View.ProjectRoute.EquivalentLengthRoute {
}
case .three(let stepThree):
return await view(on: request, projectID: projectID) {
_ = try await database.effectiveLength.create(
_ = try await database.equivalentLengths.create(
.init(form: stepThree, projectID: projectID)
)
}
@@ -536,7 +536,7 @@ extension SiteRoute.View.ProjectRoute.EquivalentLengthRoute {
try await catching()
return (
try await database.projects.getCompletedSteps(projectID),
try await database.effectiveLength.fetch(projectID)
try await database.equivalentLengths.fetch(projectID)
)
} onSuccess: { (steps, equivalentLengths) in
ProjectView(projectID: projectID, activeTab: .equivalentLength, completedSteps: steps) {
@@ -652,11 +652,11 @@ extension SiteRoute.View.UserRoute.Profile {
return await view(on: request)
case .submit(let form):
return await view(on: request) {
_ = try await database.userProfile.create(form)
_ = try await database.userProfiles.create(form)
}
case .update(let id, let updates):
return await view(on: request) {
_ = try await database.userProfile.update(id, updates)
_ = try await database.userProfiles.update(id, updates)
}
}
}
@@ -673,7 +673,7 @@ extension SiteRoute.View.UserRoute.Profile {
let user = try request.currentUser()
return (
user,
try await database.userProfile.fetch(user.id)
try await database.userProfiles.fetch(user.id)
)
} onSuccess: { (user, profile) in
UserView(user: user, profile: profile)

View File

@@ -7,7 +7,7 @@ import Styleguide
struct EffectiveLengthForm: HTML, Sendable {
static func id(_ equivalentLength: EffectiveLength?) -> String {
static func id(_ equivalentLength: EquivalentLength?) -> String {
let base = "equivalentLengthForm"
guard let equivalentLength else { return base }
return "\(base)_\(equivalentLength.id.uuidString.replacing("-", with: ""))"
@@ -15,15 +15,15 @@ struct EffectiveLengthForm: HTML, Sendable {
let projectID: Project.ID
let dismiss: Bool
let type: EffectiveLength.EffectiveLengthType
let effectiveLength: EffectiveLength?
let type: EquivalentLength.EffectiveLengthType
let effectiveLength: EquivalentLength?
var id: String { Self.id(effectiveLength) }
init(
projectID: Project.ID,
dismiss: Bool,
type: EffectiveLength.EffectiveLengthType = .supply
type: EquivalentLength.EffectiveLengthType = .supply
) {
self.projectID = projectID
self.dismiss = dismiss
@@ -32,7 +32,7 @@ struct EffectiveLengthForm: HTML, Sendable {
}
init(
effectiveLength: EffectiveLength
effectiveLength: EquivalentLength
) {
self.dismiss = true
self.type = effectiveLength.type
@@ -55,7 +55,7 @@ struct EffectiveLengthForm: HTML, Sendable {
struct StepOne: HTML, Sendable {
let projectID: Project.ID
let effectiveLength: EffectiveLength?
let effectiveLength: EquivalentLength?
var route: String {
let baseRoute = SiteRoute.View.router.path(
@@ -97,7 +97,7 @@ struct EffectiveLengthForm: HTML, Sendable {
struct StepTwo: HTML, Sendable {
let projectID: Project.ID
let stepOne: SiteRoute.View.ProjectRoute.EquivalentLengthRoute.StepOne
let effectiveLength: EffectiveLength?
let effectiveLength: EquivalentLength?
var route: String {
let baseRoute = SiteRoute.View.router.path(
@@ -152,7 +152,7 @@ struct EffectiveLengthForm: HTML, Sendable {
struct StepThree: HTML, Sendable {
let projectID: Project.ID
let effectiveLength: EffectiveLength?
let effectiveLength: EquivalentLength?
let stepTwo: SiteRoute.View.ProjectRoute.EquivalentLengthRoute.StepTwo
var route: String {
@@ -254,10 +254,10 @@ struct StraightLengthField: HTML, Sendable {
struct GroupField: HTML, Sendable {
let style: EffectiveLength.EffectiveLengthType
let group: EffectiveLength.Group?
let style: EquivalentLength.EffectiveLengthType
let group: EquivalentLength.FittingGroup?
init(style: EffectiveLength.EffectiveLengthType, group: EffectiveLength.Group? = nil) {
init(style: EquivalentLength.EffectiveLengthType, group: EquivalentLength.FittingGroup? = nil) {
self.style = style
self.group = group
}
@@ -307,7 +307,7 @@ struct GroupField: HTML, Sendable {
struct GroupSelect: HTML, Sendable {
let style: EffectiveLength.EffectiveLengthType
let style: EquivalentLength.EffectiveLengthType
var body: some HTML {
label(.class("select")) {
@@ -328,13 +328,13 @@ struct GroupSelect: HTML, Sendable {
struct GroupTypeSelect: HTML, Sendable {
let projectID: Project.ID
let selected: EffectiveLength.EffectiveLengthType
let selected: EquivalentLength.EffectiveLengthType
var body: some HTML<HTMLTag.label> {
label(.class("select w-full")) {
span(.class("label")) { "Type" }
select(.name("type"), .id("type")) {
for value in EffectiveLength.EffectiveLengthType.allCases {
for value in EquivalentLength.EffectiveLengthType.allCases {
option(
.value("\(value.rawValue)"),
) { value.title }
@@ -345,7 +345,7 @@ struct GroupTypeSelect: HTML, Sendable {
}
}
extension EffectiveLength.EffectiveLengthType {
extension EquivalentLength.EffectiveLengthType {
var title: String { rawValue.capitalized }

View File

@@ -5,9 +5,9 @@ import Styleguide
struct EffectiveLengthsTable: HTML, Sendable {
let effectiveLengths: [EffectiveLength]
let effectiveLengths: [EquivalentLength]
private var sortedLengths: [EffectiveLength] {
private var sortedLengths: [EquivalentLength] {
effectiveLengths.sorted {
$0.totalEquivalentLength > $1.totalEquivalentLength
}
@@ -55,7 +55,7 @@ struct EffectiveLengthsTable: HTML, Sendable {
struct EffectiveLenghtRow: HTML, Sendable {
let effectiveLength: EffectiveLength
let effectiveLength: EquivalentLength
private var deleteRoute: SiteRoute.View {
.project(

View File

@@ -7,14 +7,14 @@ struct EffectiveLengthsView: HTML, Sendable {
@Environment(ProjectViewValue.$projectID) var projectID
let effectiveLengths: [EffectiveLength]
let effectiveLengths: [EquivalentLength]
var supplies: [EffectiveLength] {
var supplies: [EquivalentLength] {
effectiveLengths.filter({ $0.type == .supply })
.sorted { $0.totalEquivalentLength > $1.totalEquivalentLength }
}
var returns: [EffectiveLength] {
var returns: [EquivalentLength] {
effectiveLengths.filter({ $0.type == .return })
.sorted { $0.totalEquivalentLength > $1.totalEquivalentLength }
}

View File

@@ -8,7 +8,7 @@ struct FrictionRateView: HTML, Sendable {
@Environment(ProjectViewValue.$projectID) var projectID
let componentLosses: [ComponentPressureLoss]
let equivalentLengths: EffectiveLength.MaxContainer
let equivalentLengths: EquivalentLength.MaxContainer
let frictionRate: FrictionRate?
private var availableStaticPressure: Double? {

View File

@@ -233,19 +233,19 @@ extension ManualDClient {
func frictionRate(
equipmentInfo: EquipmentInfo?,
componentLosses: [ComponentPressureLoss],
effectiveLength: EffectiveLength.MaxContainer
effectiveLength: EquivalentLength.MaxContainer
) async throws -> FrictionRate? {
guard let staticPressure = equipmentInfo?.staticPressure else {
return nil
}
guard let totalEquivalentLength = effectiveLength.total else {
guard let totalEquivalentLength = effectiveLength.totalEquivalentLength else {
return nil
}
return try await self.frictionRate(
.init(
externalStaticPressure: staticPressure,
componentPressureLosses: componentLosses,
totalEffectiveLength: Int(totalEquivalentLength)
totalEquivalentLength: Int(totalEquivalentLength)
)
)
}

View File

@@ -1,7 +1,7 @@
# TODO's
- [x] Fix theme not working when selected upon signup.
- [ ] Pdf generation
- [x] Pdf generation
- [ ] Add postgres / mysql support
- [ ] Opensource / license ??
- [ ] Figure out domain to host (currently thinking ductcalc.pro)

View File

@@ -78,10 +78,10 @@ struct ProjectRouteTests {
let p = Body {
FormData {
Optionally {
Field("id", default: nil) { EffectiveLength.ID.parser() }
Field("id", default: nil) { EquivalentLength.ID.parser() }
}
Field("name", .string)
Field("type") { EffectiveLength.EffectiveLengthType.parser() }
Field("type") { EquivalentLength.EffectiveLengthType.parser() }
Many {
Field("straightLengths") {
Int.parser()

View File

@@ -0,0 +1,53 @@
import DatabaseClient
import Dependencies
import Foundation
import ManualDCore
import Testing
@Suite
struct ComponentLossTests {
@Test
func happyPaths() async throws {
try await withTestUserAndProject { user, project in
@Dependency(\.database) var database
// let project = try await database.projects.create(user.id, .mock)
let componentLoss = try await database.componentLosses.create(
.init(projectID: project.id, name: "Test", value: 0.2)
)
let fetched = try await database.componentLosses.fetch(project.id)
#expect(fetched == [componentLoss])
let got = try await database.componentLosses.get(componentLoss.id)
#expect(got == componentLoss)
let updated = try await database.componentLosses.update(
componentLoss.id, .init(name: "Updated", value: nil)
)
#expect(updated.id == componentLoss.id)
#expect(updated.value == componentLoss.value)
#expect(updated.name == "Updated")
try await database.componentLosses.delete(componentLoss.id)
}
}
@Test
func notFound() async throws {
try await withDatabase {
@Dependency(\.database.componentLosses) var componentLosses
await #expect(throws: NotFoundError.self) {
try await componentLosses.delete(UUID(0))
}
await #expect(throws: NotFoundError.self) {
try await componentLosses.update(UUID(0), .init(name: "Updated"))
}
}
}
}

View File

@@ -0,0 +1,54 @@
import DatabaseClient
import Dependencies
import Foundation
import ManualDCore
import Testing
@Suite
struct EquipmentTests {
@Test
func happyPath() async throws {
try await withTestUserAndProject { user, project in
@Dependency(\.database) var database
let equipment = try await database.equipment.create(
.init(projectID: project.id, heatingCFM: 1000, coolingCFM: 1000)
)
let fetched = try await database.equipment.fetch(project.id)
#expect(fetched == equipment)
let got = try await database.equipment.get(equipment.id)
#expect(got == equipment)
let updated = try await database.equipment.update(
equipment.id, .init(heatingCFM: 900)
)
#expect(updated.heatingCFM == 900)
#expect(updated.id == equipment.id)
try await database.equipment.delete(equipment.id)
}
}
@Test
func notFound() async throws {
try await withTestUserAndProject { _, project in
@Dependency(\.database.equipment) var equipment
let fetched = try await equipment.fetch(project.id)
#expect(fetched == nil)
await #expect(throws: NotFoundError.self) {
try await equipment.delete(UUID(0))
}
await #expect(throws: NotFoundError.self) {
try await equipment.update(UUID(0), .init(staticPressure: 0.3))
}
}
}
}

View File

@@ -0,0 +1,83 @@
import App
import DatabaseClient
import Dependencies
import Fluent
import FluentSQLiteDriver
import Foundation
import ManualDCore
import NIO
import Vapor
// Helper to create an in-memory database used for testing.
func withDatabase(
setupDependencies: (inout DependencyValues) -> Void = { _ in },
operation: () async throws -> Void
) async throws {
let app = try await Application.make(.testing)
do {
try await configure(app)
let database = app.db
try await app.autoMigrate()
try await withDependencies {
$0.uuid = .incrementing
$0.date = .init { Date() }
$0.database = .live(database: database)
setupDependencies(&$0)
} operation: {
try await operation()
}
try await app.autoRevert()
try await app.asyncShutdown()
} catch {
try? await app.autoRevert()
try await app.asyncShutdown()
throw error
}
}
/// Set's up the database and a test user for running tests that require a
/// a user.
func withTestUser(
setupDependencies: (inout DependencyValues) -> Void = { _ in },
operation: (User) async throws -> Void
) async throws {
try await withDatabase(setupDependencies: setupDependencies) {
@Dependency(\.database.users) var users
let user = try await users.create(
.init(email: "testy@example.com", password: "super-secret", confirmPassword: "super-secret")
)
try await operation(user)
}
}
/// Set's up the database and a test user for running tests that require a
/// a user.
func withTestUserAndProject(
setupDependencies: (inout DependencyValues) -> Void = { _ in },
operation: (User, Project) async throws -> Void
) async throws {
try await withDatabase(setupDependencies: setupDependencies) {
@Dependency(\.database) var database
let user = try await database.users.create(
.init(email: "testy@example.com", password: "super-secret", confirmPassword: "super-secret")
)
let project = try await database.projects.create(user.id, .mock)
try await operation(user, project)
}
}
extension Project.Create {
static let mock = Self(
name: "Testy McTestface",
streetAddress: "1234 Sesame St",
city: "Nowhere",
state: "MN",
zipCode: "55555",
sensibleHeatRatio: 0.83
)
}

View File

@@ -0,0 +1,154 @@
import Dependencies
import DependenciesTestSupport
import Fluent
import FluentSQLiteDriver
import ManualDCore
import Testing
import Vapor
@testable import DatabaseClient
@Suite
struct ProjectTests {
@Test
func projectHappyPaths() async throws {
try await withTestUser { user in
@Dependency(\.database.projects) var projects
let project = try await projects.create(user.id, .mock)
let got = try await projects.get(project.id)
#expect(got == project)
let page = try await projects.fetch(user.id, .init(page: 1, per: 25))
#expect(page.items.first! == project)
let updated = try await projects.update(project.id, .init(sensibleHeatRatio: 0.83))
#expect(updated.sensibleHeatRatio == 0.83)
#expect(updated.id == project.id)
let shr = try await projects.getSensibleHeatRatio(project.id)
#expect(shr == 0.83)
try await projects.delete(project.id)
}
}
@Test
func notFound() async throws {
try await withDatabase {
@Dependency(\.database.projects) var projects
await #expect(throws: NotFoundError.self) {
try await projects.delete(UUID(0))
}
await #expect(throws: NotFoundError.self) {
try await projects.update(UUID(0), .init(name: "Foo"))
}
await #expect(throws: NotFoundError.self) {
try await projects.getSensibleHeatRatio(UUID(0))
}
await #expect(throws: NotFoundError.self) {
try await projects.getCompletedSteps(UUID(0))
}
}
}
@Test
func completedSteps() async throws {
try await withTestUser { user in
@Dependency(\.database) var database
let project = try await database.projects.create(user.id, .mock)
var completed = try await database.projects.getCompletedSteps(project.id)
#expect(completed.equipmentInfo == false)
#expect(completed.equivalentLength == false)
#expect(completed.frictionRate == false)
#expect(completed.rooms == false)
_ = try await database.equipment.create(
.init(projectID: project.id, heatingCFM: 1000, coolingCFM: 1000)
)
completed = try await database.projects.getCompletedSteps(project.id)
#expect(completed.equipmentInfo == true)
_ = try await database.componentLosses.create(
.init(projectID: project.id, name: "Test", value: 0.2)
)
completed = try await database.projects.getCompletedSteps(project.id)
#expect(completed.frictionRate == true)
_ = try await database.rooms.create(
.init(projectID: project.id, name: "Test", heatingLoad: 12345, coolingTotal: 12345)
)
completed = try await database.projects.getCompletedSteps(project.id)
#expect(completed.rooms == true)
_ = try await database.equivalentLengths.create(
.init(
projectID: project.id, name: "Supply", type: .supply, straightLengths: [1], groups: [])
)
completed = try await database.projects.getCompletedSteps(project.id)
// Should not be complete until we have both return and supply for a project.
#expect(completed.equivalentLength == false)
_ = try await database.equivalentLengths.create(
.init(
projectID: project.id, name: "Return", type: .return, straightLengths: [1], groups: [])
)
completed = try await database.projects.getCompletedSteps(project.id)
#expect(completed.equipmentInfo == true)
#expect(completed.equivalentLength == true)
#expect(completed.frictionRate == true)
#expect(completed.rooms == true)
}
}
@Test
func detail() async throws {
try await withTestUser { user in
@Dependency(\.database) var database
let project = try await database.projects.create(user.id, .mock)
var detail = try await database.projects.detail(project.id)
#expect(detail == nil)
let equipment = try await database.equipment.create(
.init(projectID: project.id, heatingCFM: 1000, coolingCFM: 1000)
)
detail = try await database.projects.detail(project.id)
#expect(detail != nil)
let componentLoss = try await database.componentLosses.create(
.init(projectID: project.id, name: "Test", value: 0.2)
)
let room = try await database.rooms.create(
.init(projectID: project.id, name: "Test", heatingLoad: 12345, coolingTotal: 12345)
)
let supplyLength = try await database.equivalentLengths.create(
.init(
projectID: project.id, name: "Supply", type: .supply, straightLengths: [1], groups: [])
)
let returnLength = try await database.equivalentLengths.create(
.init(
projectID: project.id, name: "Return", type: .return, straightLengths: [1], groups: [])
)
detail = try await database.projects.detail(project.id)
#expect(detail?.componentLosses == [componentLoss])
#expect(detail?.equipmentInfo == equipment)
#expect(detail?.rooms == [room])
#expect(detail?.equivalentLengths.contains(supplyLength) == true)
#expect(detail?.equivalentLengths.contains(returnLength) == true)
}
}
}

View File

@@ -0,0 +1,151 @@
import DatabaseClient
import Dependencies
import Foundation
import ManualDCore
import Testing
import Vapor
@testable import DatabaseClient
@Suite
struct UserDatabaseTests {
@Test
func happyPaths() async throws {
try await withDatabase {
@Dependency(\.database.users) var users
let user = try await users.create(
.init(email: "testy@example.com", password: "super-secret", confirmPassword: "super-secret")
)
#expect(user.email == "testy@example.com")
// Test login the user in
let token = try await users.login(
.init(email: user.email, password: "super-secret")
)
#expect(token.userID == user.id)
// Test the same token is returned.
let token2 = try await users.login(
.init(email: user.email, password: "super-secret")
)
#expect(token.id == token2.id)
// Test logging out
try await users.logout(token.id)
try await users.delete(user.id)
let shouldBeNilUser = try await users.get(user.id)
#expect(shouldBeNilUser == nil)
}
}
@Test
func createUserFails() async throws {
try await withDatabase {
@Dependency(\.database.users) var users
await #expect(throws: ValidationError.self) {
try await users.create(.init(email: "", password: "", confirmPassword: ""))
}
await #expect(throws: ValidationError.self) {
try await users.create(.init(email: "testy@example.com", password: "", confirmPassword: ""))
}
await #expect(throws: ValidationError.self) {
try await users.create(
.init(email: "testy@example.com", password: "super-secret", confirmPassword: ""))
}
}
}
@Test
func deleteFailsWithInvalidUserID() async throws {
try await withDatabase {
@Dependency(\.database.users) var users
await #expect(throws: NotFoundError.self) {
try await users.delete(UUID(0))
}
}
}
@Test
func logoutIgnoresUnfoundTokenID() async throws {
try await withDatabase {
@Dependency(\.database.users) var users
try await users.logout(UUID(0))
}
}
@Test
func loginFails() async throws {
try await withDatabase {
@Dependency(\.database.users) var users
await #expect(throws: NotFoundError.self) {
try await users.login(
.init(email: "foo@example.com", password: "super-secret")
)
}
let user = try await users.create(
.init(email: "testy@example.com", password: "super-secret", confirmPassword: "super-secret")
)
// Ensure can not login with invalid password
await #expect(throws: Abort.self) {
try await users.login(
.init(email: user.email, password: "wrong-password")
)
}
}
}
@Test
func userProfileHappyPath() async throws {
try await withTestUser { user in
@Dependency(\.database.userProfiles) var profiles
let profile = try await profiles.create(
.init(
userID: user.id,
firstName: "Testy",
lastName: "McTestface",
companyName: "Acme Co.",
streetAddress: "12345 Sesame St",
city: "Nowhere",
state: "FL",
zipCode: "55555"
)
)
let fetched = try await profiles.fetch(user.id)
#expect(fetched == profile)
let got = try await profiles.get(profile.id)
#expect(got == profile)
let updated = try await profiles.update(profile.id, .init(firstName: "Updated"))
#expect(updated.firstName == "Updated")
#expect(updated.id == profile.id)
try await profiles.delete(profile.id)
}
}
@Test
func testUserProfileFails() async throws {
try await withDatabase {
@Dependency(\.database.userProfiles) var profiles
await #expect(throws: NotFoundError.self) {
try await profiles.delete(UUID(0))
}
await #expect(throws: NotFoundError.self) {
try await profiles.update(UUID(0), .init(firstName: "Foo"))
}
}
}
}

View File

@@ -24,62 +24,16 @@ struct ManualDClientTests {
@Test
func ductSize() async throws {
let response = try await manualD.ductSize(
.init(designCFM: 88, frictionRate: 0.06)
)
let response = try await manualD.ductSize(88, 0.06)
#expect(numberFormatter.string(for: response.calculatedSize) == "6.07")
#expect(response.finalSize == 7)
#expect(response.flexSize == 7)
#expect(response.velocity == 329)
}
// @Test
// func frictionRate() async throws {
// let response = try await manualD.frictionRate(
// .init(
// externalStaticPressure: 0.5,
// componentPressureLosses: .mock,
// totalEffectiveLength: 185
// )
// )
// #expect(numberFormatter.string(for: response.availableStaticPressure) == "0.11")
// #expect(numberFormatter.string(for: response.frictionRate) == "0.06")
// }
// @Test
// func frictionRateFails() async throws {
// await #expect(throws: ManualDError.self) {
// _ = try await manualD.frictionRate(
// .init(
// externalStaticPressure: 0.5,
// componentPressureLosses: .mock,
// totalEffectiveLength: 0
// )
// )
// }
// }
@Test
func totalEffectiveLength() async throws {
let response = try await manualD.totalEquivalentLength(
.init(
trunkLengths: [25],
runoutLengths: [10],
effectiveLengthGroups: [
// NOTE: These are made up and may not correspond to actual manual-d group tel's.
EffectiveLengthGroup(group: 1, letter: "a", effectiveLength: 20, category: .supply),
EffectiveLengthGroup(group: 2, letter: "a", effectiveLength: 30, category: .supply),
EffectiveLengthGroup(group: 3, letter: "a", effectiveLength: 10, category: .supply),
EffectiveLengthGroup(group: 12, letter: "a", effectiveLength: 10, category: .supply),
]
)
)
#expect(response == 105)
}
@Test
func equivalentRectangularDuct() async throws {
let response = try await manualD.rectangularSize(.init(round: 7, height: 8))
let response = try await manualD.rectangularSize(round: 7, height: 8)
#expect(response.height == 8)
#expect(response.width == 5)
}

View File

@@ -18,7 +18,7 @@ struct ViewControllerTests {
func login() async throws {
try await withDependencies {
$0.viewController = .liveValue
$0.authClient = .failing
$0.auth = .failing
} operation: {
@Dependency(\.viewController) var viewController
@@ -31,7 +31,7 @@ struct ViewControllerTests {
func signup() async throws {
try await withDependencies {
$0.viewController = .liveValue
$0.authClient = .failing
$0.auth = .failing
} operation: {
@Dependency(\.viewController) var viewController
@@ -86,7 +86,7 @@ struct ViewControllerTests {
let project = Project.mock
let rooms = Room.mock(projectID: project.id)
let equipment = EquipmentInfo.mock(projectID: project.id)
let tels = EffectiveLength.mock(projectID: project.id)
let tels = EquivalentLength.mock(projectID: project.id)
let componentLosses = ComponentPressureLoss.mock(projectID: project.id)
let trunks = TrunkSize.mock(projectID: project.id, rooms: rooms)
@@ -100,6 +100,12 @@ struct ViewControllerTests {
)
}
let mockDuctSizes = DuctSizes.mock(
equipmentInfo: equipment,
rooms: rooms,
trunks: trunks
)
try await withDefaultDependencies {
$0.database.projects.get = { _ in project }
$0.database.projects.getCompletedSteps = { _ in
@@ -108,13 +114,16 @@ struct ViewControllerTests {
$0.database.projects.getSensibleHeatRatio = { _ in 0.83 }
$0.database.rooms.fetch = { _ in rooms }
$0.database.equipment.fetch = { _ in equipment }
$0.database.effectiveLength.fetch = { _ in tels }
$0.database.effectiveLength.fetchMax = { _ in
$0.database.equivalentLengths.fetch = { _ in tels }
$0.database.equivalentLengths.fetchMax = { _ in
.init(supply: tels.first, return: tels.last)
}
$0.database.componentLoss.fetch = { _ in componentLosses }
$0.projectClient.calculateDuctSizes = { _ in
.mock(equipmentInfo: equipment, rooms: rooms, trunks: trunks)
$0.database.componentLosses.fetch = { _ in componentLosses }
$0.projectClient.calculateRoomDuctSizes = { _ in
mockDuctSizes.rooms
}
$0.projectClient.calculateTrunkDuctSizes = { _ in
mockDuctSizes.trunks
}
} operation: {
@Dependency(\.viewController) var viewController
@@ -163,8 +172,8 @@ struct ViewControllerTests {
return try await withDependencies {
$0.viewController = .liveValue
$0.authClient.currentUser = { user }
$0.database.userProfile.fetch = { _ in profile }
$0.auth.currentUser = { user }
$0.database.userProfiles.fetch = { _ in profile }
$0.manualD = .liveValue
try await updateDependencies(&$0)
} operation: {

36
docker/Dockerfile.test Normal file
View File

@@ -0,0 +1,36 @@
FROM docker.io/swift:6.2-noble
# Make sure all system packages are up to date, and install only essential packages.
RUN export DEBIAN_FRONTEND=noninteractive DEBCONF_NONINTERACTIVE_SEEN=true \
&& apt-get -q update \
&& apt-get -q dist-upgrade -y \
&& apt-get -q install -y \
libjemalloc2 \
ca-certificates \
tzdata \
# If your app or its dependencies import FoundationNetworking, also install `libcurl4`.
libcurl4 \
# If your app or its dependencies import FoundationXML, also install `libxml2`.
# libxml2 \
sqlite3 \
&& rm -r /var/lib/apt/lists/*
# Set up a build area
WORKDIR /app
# First just resolve dependencies.
# This creates a cached layer that can be reused
# as long as your Package.swift/Package.resolved
# files do not change.
COPY ./Package.* ./
RUN swift package resolve \
$([ -f ./Package.resolved ] && echo "--force-resolved-versions" || true)
# Copy entire repo into container
COPY . .
ENV SWIFT_BACKTRACE=enable=no
ENV LOG_LEVEL=debug
CMD ["swift", "test"]

View File

@@ -14,7 +14,20 @@ run:
@swift run App serve --log debug
build-docker file="docker/Dockerfile":
@podman build -f {{file}} -t {{docker_image}}:{{docker_tag}} .
@docker build -f {{file}} -t {{docker_image}}:{{docker_tag}} .
run-docker:
@podman run -it --rm -v $PWD:/app -p 8080:8080 {{docker_image}}:{{docker_tag}}
@docker run -it --rm -v $PWD:/app -p 8080:8080 {{docker_image}}:{{docker_tag}}
test-docker: (build-docker "docker/Dockerfile.test")
@docker run --rm {{docker_image}}:{{docker_tag}} swift test
code-coverage:
@llvm-cov report \
"$(find $(swift build --show-bin-path) -name '*.xctest')" \
-instr-profile=.build/debug/codecov/default.profdata \
-ignore-filename-regex=".build|Tests" \
-use-color
test *ARGS:
@swift test --enable-code-coverage {{ARGS}}