1use 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#[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#[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
143fn 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
181fn 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
198fn 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}