Skip to main content

ifc_systems/authoring/
services.rs

1//! Authoring `IfcRelServicesBuildings`: the structures a system serves
2//! (#230).
3//!
4//! Deprecated (#492): `ifc_spatial::serve_buildings` and
5//! `ifc_spatial::serve_buildings_with_owner_history` are the canonical
6//! writers of this relationship, with the same rules. These stay, with
7//! their own error type, for compatibility; sibling domain crates do not
8//! depend on one another, so they keep their bodies rather than forward.
9//!
10//! Both writers bind the model's declared release and check, against that
11//! release's own table, that the relating end is an `IfcSystem` and every
12//! served end is what `RelatedBuildings` admits there
13//! (`IfcSpatialStructureElement` in IFC2X3, `IfcSpatialElement` in IFC4 and
14//! IFC4X3). `IfcSystem.ServicesBuildings` is `SET [0:1]`, so a system that
15//! already has one, in the model or staged on the transaction, is refused.
16//! Every check runs before anything is staged.
17//!
18//! The IFC4X3 `ServicesFacilities` side is an
19//! `IfcRelReferencedInSpatialStructure` listing the system; author it with
20//! [`reference_in_spatial_structure`](super::reference_in_spatial_structure).
21
22use std::collections::BTreeSet;
23
24use ifc_model::{Edit, EntityId, Model, Transaction, Value};
25
26use super::error::invalid;
27use super::release::{bind, projected_type, Release};
28use super::{check_related, refs, SystemAuthoringError, SystemAuthoringResult};
29use crate::system::services::slot;
30
31const ENTITY: &str = "IFCRELSERVICESBUILDINGS";
32
33/// Stage an `IfcRelServicesBuildings` in `model`'s declared release, with
34/// `OwnerHistory` `$`: `system` serves `buildings`.
35///
36/// IFC2X3 requires `OwnerHistory`, so there this refuses with
37/// [`AuthoringRequired`](SystemAuthoringError::AuthoringRequired); use
38/// [`serve_buildings_with_owner_history`].
39///
40/// # Errors
41///
42/// [`Invalid`](SystemAuthoringError::Invalid) for a malformed GlobalId, an
43/// empty or repeating building set, the system among its own buildings, or a
44/// system that already services buildings (`ServicesBuildings` is
45/// `SET [0:1]`);
46/// [`MultipleSchemas`](SystemAuthoringError::MultipleSchemas) or
47/// [`UnsupportedSchema`](SystemAuthoringError::UnsupportedSchema) when the
48/// header binds no single verified release;
49/// [`MissingReference`](SystemAuthoringError::MissingReference) for a system
50/// or building neither in the model nor staged;
51/// [`WrongReferenceType`](SystemAuthoringError::WrongReferenceType) for a
52/// system that is not an `IfcSystem`, or a building the release's
53/// `RelatedBuildings` does not admit. Nothing is staged on an error.
54#[deprecated(
55    since = "0.5.0",
56    note = "use ifc_spatial::serve_buildings, the canonical IfcRelServicesBuildings writer (#492)"
57)]
58pub fn serve_buildings(
59    tx: &mut Transaction,
60    model: &Model,
61    global_id: &str,
62    system: EntityId,
63    buildings: &[EntityId],
64) -> SystemAuthoringResult<EntityId> {
65    serve(tx, model, global_id, system, buildings, None)
66}
67
68/// [`serve_buildings`] with a caller-supplied `IfcOwnerHistory`, which
69/// IFC2X3 requires.
70///
71/// # Errors
72///
73/// Those of [`serve_buildings`] except the IFC2X3 `AuthoringRequired`, and
74/// [`MissingReference`](SystemAuthoringError::MissingReference) or
75/// [`WrongReferenceType`](SystemAuthoringError::WrongReferenceType) for an
76/// `owner_history` that is absent or not an `IfcOwnerHistory`. Nothing is
77/// staged on an error.
78#[deprecated(
79    since = "0.5.0",
80    note = "use ifc_spatial::serve_buildings_with_owner_history, the canonical IfcRelServicesBuildings writer (#492)"
81)]
82pub fn serve_buildings_with_owner_history(
83    tx: &mut Transaction,
84    model: &Model,
85    global_id: &str,
86    system: EntityId,
87    buildings: &[EntityId],
88    owner_history: EntityId,
89) -> SystemAuthoringResult<EntityId> {
90    serve(tx, model, global_id, system, buildings, Some(owner_history))
91}
92
93fn serve(
94    tx: &mut Transaction,
95    model: &Model,
96    global_id: &str,
97    system: EntityId,
98    buildings: &[EntityId],
99    owner_history: Option<EntityId>,
100) -> SystemAuthoringResult<EntityId> {
101    let release = bind(model)?;
102    check_related(
103        ENTITY,
104        "RelatedBuildings",
105        global_id,
106        system,
107        buildings,
108        "system",
109    )?;
110    let mut seen = BTreeSet::new();
111    if let Some(repeated) = buildings.iter().find(|id| !seen.insert(**id)) {
112        return Err(invalid(
113            ENTITY,
114            "RelatedBuildings",
115            format!("repeats {repeated}"),
116        ));
117    }
118    require(release, tx, model, "RelatingSystem", system)?;
119    for &building in buildings {
120        require(release, tx, model, "RelatedBuildings", building)?;
121    }
122    if let Some(existing) = services_of(tx, model, system) {
123        return Err(invalid(
124            ENTITY,
125            "RelatingSystem",
126            format!("{system} already services buildings through {existing}"),
127        ));
128    }
129    let values = vec![
130        ("GlobalId", Value::Text(global_id.into())),
131        ("RelatingSystem", Value::Ref(system)),
132        ("RelatedBuildings", refs(buildings)),
133    ];
134    match owner_history {
135        Some(owner_history) => release.stage(tx, model, ENTITY, values, owner_history),
136        None => {
137            let record = release.record(ENTITY, values)?;
138            Ok(tx.create(record))
139        }
140    }
141}
142
143/// Fail unless `target` exists (in the model or staged) with a type the
144/// release's `IfcRelServicesBuildings.attribute` admits.
145fn require(
146    release: Release,
147    tx: &Transaction,
148    model: &Model,
149    attribute: &'static str,
150    target: EntityId,
151) -> SystemAuthoringResult<()> {
152    let actual =
153        projected_type(tx, model, target).ok_or(SystemAuthoringError::MissingReference {
154            entity: ENTITY,
155            attribute,
156            target,
157        })?;
158    let schema = release.schema();
159    let declared = schema
160        .attributes(ENTITY)
161        .into_iter()
162        .find(|a| a.name.eq_ignore_ascii_case(attribute))
163        .map(|a| a.type_name.as_str())
164        .ok_or(SystemAuthoringError::EntityNotInSchema {
165            entity: ENTITY,
166            schema: release.version(),
167        })?;
168    if schema.accepts_type(declared, &actual) {
169        Ok(())
170    } else {
171        Err(SystemAuthoringError::WrongReferenceType {
172            entity: ENTITY,
173            attribute,
174            target,
175            actual: actual.to_ascii_uppercase(),
176            expected: declared,
177        })
178    }
179}
180
181/// An `IfcRelServicesBuildings` whose `RelatingSystem` is `system` once `tx`
182/// commits, if any.
183fn services_of(tx: &Transaction, model: &Model, system: EntityId) -> Option<EntityId> {
184    let staged = tx.edits().iter().filter_map(|edit| match edit {
185        Edit::Create { id, .. } => Some(*id),
186        _ => None,
187    });
188    let mut candidates: Vec<EntityId> = model.ids_of_type(ENTITY).to_vec();
189    candidates.extend(staged);
190    candidates.sort_unstable();
191    candidates.dedup();
192    candidates.into_iter().find(|&id| {
193        projected_type(tx, model, id).is_some_and(|t| t.eq_ignore_ascii_case(ENTITY))
194            && projected_system(tx, model, id) == Some(system)
195    })
196}
197
198/// `RelatingSystem` of relationship `id` once `tx` commits.
199fn projected_system(tx: &Transaction, model: &Model, id: EntityId) -> Option<EntityId> {
200    for edit in tx.edits().iter().rev() {
201        match edit {
202            Edit::Remove { id: removed } if *removed == id => return None,
203            Edit::SetAttribute {
204                id: edited,
205                slot: at,
206                value,
207            } if *edited == id && *at == slot::RELATING_SYSTEM => {
208                return match value {
209                    Value::Ref(system) => Some(*system),
210                    _ => None,
211                }
212            }
213            Edit::Create {
214                id: created,
215                entity,
216            } if *created == id => {
217                return match entity.attributes.get(slot::RELATING_SYSTEM) {
218                    Some(Value::Ref(system)) => Some(*system),
219                    _ => None,
220                }
221            }
222            _ => {}
223        }
224    }
225    match model.get(id)?.attributes.get(slot::RELATING_SYSTEM)? {
226        Value::Ref(system) => Some(*system),
227        _ => None,
228    }
229}