1use crate::record::{Field, Record, ToRecord};
14use crate::value::Tagged;
15use crate::{BindingError, IfcModel};
16
17#[derive(Debug, Clone, PartialEq)]
19pub struct Cost {
20 pub schedules: Vec<CostSchedule>,
22 pub items: Vec<CostItem>,
24 pub anomalies: Vec<CostAnomaly>,
27}
28
29#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct CostSchedule {
32 pub id: u64,
34 pub global_id: Option<String>,
36 pub name: Option<String>,
38 pub identification: Option<String>,
40 pub status: Option<String>,
42 pub predefined_type: Option<String>,
44 pub items: Vec<u64>,
47}
48
49#[derive(Debug, Clone, PartialEq)]
51pub struct CostItem {
52 pub id: u64,
54 pub global_id: Option<String>,
56 pub name: Option<String>,
58 pub identification: Option<String>,
60 pub description: Option<String>,
62 pub predefined_type: Option<String>,
64 pub parent: Option<u64>,
66 pub children: Vec<u64>,
68 pub values: Vec<CostValue>,
70 pub quantities: Vec<u64>,
73 pub objects: Vec<u64>,
75}
76
77#[derive(Debug, Clone, PartialEq)]
79pub struct CostValue {
80 pub id: u64,
82 pub name: Option<String>,
84 pub description: Option<String>,
86 pub category: Option<String>,
88 pub condition: Option<String>,
90 pub applied_value: Tagged,
93 pub operator: Option<String>,
95 pub unit_basis: Option<UnitBasis>,
97 pub components: Vec<CostValue>,
99}
100
101#[derive(Debug, Clone, PartialEq)]
103pub struct UnitBasis {
104 pub id: u64,
106 pub value: Tagged,
108 pub unit: Option<u64>,
110}
111
112#[derive(Debug, Clone, PartialEq, Eq)]
114pub struct CostAnomaly {
115 pub item: u64,
117 pub kept: u64,
119 pub rejected: u64,
121 pub relation: u64,
123}
124
125impl IfcModel {
126 pub fn cost(&self) -> Result<Cost, BindingError> {
134 #[cfg(feature = "cost")]
135 {
136 read::cost(self)
137 }
138 #[cfg(not(feature = "cost"))]
139 {
140 Err(BindingError::FeatureDisabled("cost"))
141 }
142 }
143}
144
145#[cfg(feature = "cost")]
146mod read {
147 use ifc::cost::{
148 children_of, controlled_by, nesting_anomalies, parent_of, CostAnomaly as Anomaly,
149 CostError, CostValue as View, CostView, MAX_NESTING_DEPTH,
150 };
151 use ifc::EntityId;
152
153 use super::{Cost, CostAnomaly, CostItem, CostSchedule, CostValue, UnitBasis};
154 use crate::value::Tagged;
155 use crate::{BindingError, IfcModel};
156
157 pub(super) fn cost(model: &IfcModel) -> Result<Cost, BindingError> {
158 let inner = &model.inner;
159 let view = CostView::new(inner);
160 let owned = |text: Option<&str>| text.map(str::to_owned);
161 let mut schedules = Vec::new();
162 for schedule in view.schedules().map_err(error)? {
163 let id = schedule.id();
164 schedules.push(CostSchedule {
165 id: id.0,
166 global_id: model.identity(id.0)?.global_id,
167 name: owned(schedule.name()),
168 identification: owned(schedule.identification()),
169 status: owned(schedule.status()),
170 predefined_type: owned(schedule.predefined_type()),
171 items: ids(controlled_by(inner, id)),
172 });
173 }
174 let mut items = Vec::new();
175 for item in view.items() {
176 let id = item.id();
177 let values = item
178 .value_refs()
179 .into_iter()
180 .map(|value| applied(model, id, value, 0, &mut Vec::new()))
181 .collect::<Result<_, _>>()?;
182 items.push(CostItem {
183 id: id.0,
184 global_id: model.identity(id.0)?.global_id,
185 name: owned(item.name()),
186 identification: owned(item.identification()),
187 description: owned(item.description()),
188 predefined_type: owned(item.predefined_type()),
189 parent: parent_of(inner, id).map(|EntityId(id)| id),
190 children: ids(children_of(inner, id)),
191 values,
192 quantities: ids(item.quantity_refs()),
193 objects: ids(controlled_by(inner, id)),
194 });
195 }
196 let anomalies = nesting_anomalies(inner)
197 .into_iter()
198 .filter_map(|anomaly| match anomaly {
199 Anomaly::NestedTwice {
200 item,
201 kept,
202 rejected,
203 relation,
204 } => Some(CostAnomaly {
205 item: item.0,
206 kept: kept.0,
207 rejected: rejected.0,
208 relation: relation.0,
209 }),
210 _ => None,
212 })
213 .collect();
214 Ok(Cost {
215 schedules,
216 items,
217 anomalies,
218 })
219 }
220
221 fn applied(
223 model: &IfcModel,
224 from: EntityId,
225 id: EntityId,
226 depth: usize,
227 path: &mut Vec<EntityId>,
228 ) -> Result<CostValue, BindingError> {
229 if path.contains(&id) || depth > MAX_NESTING_DEPTH {
230 return Err(BindingError::BudgetExceeded(format!(
231 "the cost value tree under #{} cycles or nests deeper than {MAX_NESTING_DEPTH}",
232 from.0
233 )));
234 }
235 let entity = model.inner.get(id).ok_or_else(|| {
236 BindingError::MissingReference(format!("#{} references missing #{}", from.0, id.0))
237 })?;
238 let value = View::new(id, entity);
239 path.push(id);
240 let components = value
241 .component_refs()
242 .into_iter()
243 .map(|component| applied(model, id, component, depth + 1, path))
244 .collect::<Result<_, _>>()?;
245 path.pop();
246 let owned = |text: Option<&str>| text.map(str::to_owned);
247 let unit_basis = value.unit_basis(&model.inner).map(|basis| UnitBasis {
248 id: basis.id.0,
249 value: value
250 .unit_basis_component(&model.inner)
251 .map_or(Tagged::Null, Tagged::from_value),
252 unit: basis.unit.map(|EntityId(id)| id),
253 });
254 Ok(CostValue {
255 id: id.0,
256 name: owned(value.name()),
257 description: owned(value.description()),
258 category: owned(value.category()),
259 condition: owned(value.condition()),
260 applied_value: value
261 .applied_value()
262 .map_or(Tagged::Null, Tagged::from_value),
263 operator: value
264 .operator()
265 .map(|operator| format!("{operator:?}").to_ascii_uppercase()),
266 unit_basis,
267 components,
268 })
269 }
270
271 fn ids(ids: Vec<EntityId>) -> Vec<u64> {
272 ids.into_iter().map(|EntityId(id)| id).collect()
273 }
274
275 fn error(error: CostError) -> BindingError {
276 match error {
277 CostError::UnsupportedSchema { schema } => BindingError::UnsupportedSchema(schema),
278 CostError::MultipleSchemas { schemas } => {
279 BindingError::UnsupportedSchema(format!("{schemas} schemas declared"))
280 }
281 CostError::MissingReference { .. } => BindingError::MissingReference(error.to_string()),
282 other => BindingError::InvalidModel(other.to_string()),
283 }
284 }
285}
286
287impl ToRecord for Cost {
288 fn to_record(&self) -> Record {
289 Record::new(
290 "Cost",
291 vec![
292 ("schedules", Field::records(&self.schedules)),
293 ("items", Field::records(&self.items)),
294 ("anomalies", Field::records(&self.anomalies)),
295 ],
296 )
297 }
298}
299
300impl ToRecord for CostSchedule {
301 fn to_record(&self) -> Record {
302 Record::new(
303 "CostSchedule",
304 vec![
305 ("id", Field::Id(self.id)),
306 ("global_id", Field::text(self.global_id.clone())),
307 ("name", Field::text(self.name.clone())),
308 ("identification", Field::text(self.identification.clone())),
309 ("status", Field::text(self.status.clone())),
310 ("predefined_type", Field::text(self.predefined_type.clone())),
311 ("items", Field::ids(self.items.iter().copied())),
312 ],
313 )
314 }
315}
316
317impl ToRecord for CostItem {
318 fn to_record(&self) -> Record {
319 Record::new(
320 "CostItem",
321 vec![
322 ("id", Field::Id(self.id)),
323 ("global_id", Field::text(self.global_id.clone())),
324 ("name", Field::text(self.name.clone())),
325 ("identification", Field::text(self.identification.clone())),
326 ("description", Field::text(self.description.clone())),
327 ("predefined_type", Field::text(self.predefined_type.clone())),
328 ("parent", Field::id(self.parent)),
329 ("children", Field::ids(self.children.iter().copied())),
330 ("values", Field::records(&self.values)),
331 ("quantities", Field::ids(self.quantities.iter().copied())),
332 ("objects", Field::ids(self.objects.iter().copied())),
333 ],
334 )
335 }
336}
337
338impl ToRecord for CostValue {
339 fn to_record(&self) -> Record {
340 Record::new(
341 "CostValue",
342 vec![
343 ("id", Field::Id(self.id)),
344 ("name", Field::text(self.name.clone())),
345 ("description", Field::text(self.description.clone())),
346 ("category", Field::text(self.category.clone())),
347 ("condition", Field::text(self.condition.clone())),
348 ("applied_value", Field::Value(self.applied_value.clone())),
349 ("operator", Field::text(self.operator.clone())),
350 ("unit_basis", Field::record(self.unit_basis.as_ref())),
351 ("components", Field::records(&self.components)),
352 ],
353 )
354 }
355}
356
357impl ToRecord for UnitBasis {
358 fn to_record(&self) -> Record {
359 Record::new(
360 "UnitBasis",
361 vec![
362 ("id", Field::Id(self.id)),
363 ("value", Field::Value(self.value.clone())),
364 ("unit", Field::id(self.unit)),
365 ],
366 )
367 }
368}
369
370impl ToRecord for CostAnomaly {
371 fn to_record(&self) -> Record {
372 Record::new(
373 "CostAnomaly",
374 vec![
375 ("item", Field::Id(self.item)),
376 ("kept", Field::Id(self.kept)),
377 ("rejected", Field::Id(self.rejected)),
378 ("relation", Field::Id(self.relation)),
379 ],
380 )
381 }
382}