Skip to main content

ifc_spatial/authoring/
services.rs

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