1use ifc_model::{EntityId, Model, Transaction, Value};
32
33use crate::ArithmeticOperator;
34
35use super::datetime::{patch, DateTimeValue, PLACEHOLDERS};
36use super::draft::{CostValueDraft, CostValueKind};
37use super::release::{bind, Release};
38use super::validate::{invalid, reference_type};
39use super::{CostAuthoringError, CostAuthoringResult};
40
41pub fn create_cost_value(
57 tx: &mut Transaction,
58 model: &Model,
59 draft: CostValueDraft<'_>,
60) -> CostAuthoringResult<EntityId> {
61 const ENTITY: &str = "IFCCOSTVALUE";
62 let release = bind(model)?;
63 let (applied_value, operator, components) = match draft.kind {
64 CostValueKind::Monetary(amount) => {
65 if !amount.is_finite() {
66 return Err(invalid(
67 ENTITY,
68 "AppliedValue",
69 "expected a finite monetary amount",
70 ));
71 }
72 (
73 Value::Typed {
74 type_name: "IFCMONETARYMEASURE".into(),
75 value: Box::new(Value::Real(amount)),
76 },
77 Value::Null,
78 Value::Null,
79 )
80 }
81 CostValueKind::Components {
82 operator,
83 components,
84 } => {
85 if components.is_empty() {
86 return Err(invalid(
87 ENTITY,
88 "Components",
89 "expected at least one component",
90 ));
91 }
92 for target in components {
93 reference_type(tx, model, ENTITY, "Components", *target, ENTITY)?;
94 }
95 (
96 Value::Null,
97 Value::Enum(operator_token(operator).into()),
98 refs(components),
99 )
100 }
101 };
102 let dates = [draft.applicable_date, draft.fixed_until_date];
103 for (date, attribute) in dates.iter().zip(["ApplicableDate", "FixedUntilDate"]) {
104 if let Some(date) = date {
105 check_date(release, ENTITY, attribute, *date)?;
106 }
107 }
108 let provisional = |slot: usize| {
109 dates[slot].map_or(Value::Null, |date: DateTimeValue<'_>| {
110 date.provisional(PLACEHOLDERS[slot])
111 })
112 };
113 let mut record = release.record(
114 ENTITY,
115 vec![
116 ("Name", optional_text(draft.name)),
117 ("Description", optional_text(draft.description)),
118 ("AppliedValue", applied_value),
119 ("ApplicableDate", provisional(0)),
120 ("FixedUntilDate", provisional(1)),
121 ("Category", optional_text(draft.category)),
122 ("Condition", optional_text(draft.condition)),
123 ("ArithmeticOperator", operator),
124 ("Components", components),
125 ],
126 )?;
127 patch(tx, &mut record, &dates);
128 Ok(tx.create(record))
129}
130
131fn check_date(
135 release: Release,
136 entity: &'static str,
137 attribute: &'static str,
138 date: DateTimeValue<'_>,
139) -> CostAuthoringResult<()> {
140 date.check()?;
141 let fits = match date.record_type() {
142 None => true,
144 Some(record) => release.accepts_record(entity, attribute, record)?,
145 };
146 if fits {
147 return Ok(());
148 }
149 let declared = release
150 .schema()
151 .attributes(entity)
152 .into_iter()
153 .find(|declared| declared.name.eq_ignore_ascii_case(attribute))
154 .map_or("", |declared| declared.type_name.as_str());
155 Err(CostAuthoringError::AuthoringValueType {
156 entity,
157 attribute,
158 declared,
159 schema: release.version(),
160 })
161}
162
163fn operator_token(operator: ArithmeticOperator) -> &'static str {
164 match operator {
165 ArithmeticOperator::Add => "ADD",
166 ArithmeticOperator::Divide => "DIVIDE",
167 ArithmeticOperator::Multiply => "MULTIPLY",
168 ArithmeticOperator::Subtract => "SUBTRACT",
169 }
170}
171
172pub(crate) fn optional_text(value: Option<&str>) -> Value {
173 value.map_or(Value::Null, |value| Value::Text(value.into()))
174}
175pub(crate) fn optional_enum(value: Option<&str>) -> Value {
176 value.map_or(Value::Null, |value| Value::Enum(value.into()))
177}
178pub(crate) fn refs(ids: &[EntityId]) -> Value {
179 Value::List(ids.iter().copied().map(Value::Ref).collect())
180}
181
182pub fn create_monetary_unit(
197 tx: &mut Transaction,
198 model: &Model,
199 currency: &str,
200) -> CostAuthoringResult<EntityId> {
201 const ENTITY: &str = "IFCMONETARYUNIT";
202 let release = bind(model)?;
203 if currency.trim().is_empty() {
204 return Err(invalid(ENTITY, "Currency", "expected a currency label"));
205 }
206 let (_, declaration) = release.declared(ENTITY, "Currency")?;
207 let value = match release
208 .schema()
209 .type_def(&declaration.type_name)
210 .map(|t| &t.kind)
211 {
212 Some(ifc_schema::TypeKind::Enumeration(_)) => {
213 let token = release.enumerator(ENTITY, "Currency", currency)?.ok_or(
214 CostAuthoringError::AuthoringValueType {
215 entity: ENTITY,
216 attribute: "Currency",
217 declared: declaration.type_name.as_str(),
218 schema: release.version(),
219 },
220 )?;
221 Value::Enum(token.into())
222 }
223 _ => Value::Text(currency.into()),
224 };
225 let record = release.record(ENTITY, vec![("Currency", value)])?;
226 Ok(tx.create(record))
227}
228
229pub fn create_currency_relationship(
248 tx: &mut Transaction,
249 model: &Model,
250 relating: EntityId,
251 related: EntityId,
252 exchange_rate: f64,
253 rate_date_time: Option<DateTimeValue<'_>>,
254) -> CostAuthoringResult<EntityId> {
255 const ENTITY: &str = "IFCCURRENCYRELATIONSHIP";
256 let release = bind(model)?;
257 for (target, attribute) in [
258 (relating, "RelatingMonetaryUnit"),
259 (related, "RelatedMonetaryUnit"),
260 ] {
261 reference_type(tx, model, ENTITY, attribute, target, "IFCMONETARYUNIT")?;
262 }
263 if relating == related {
264 return Err(invalid(
265 ENTITY,
266 "RelatedMonetaryUnit",
267 "expected a unit other than the relating one",
268 ));
269 }
270 if !exchange_rate.is_finite() || exchange_rate <= 0.0 {
271 return Err(invalid(
272 ENTITY,
273 "ExchangeRate",
274 "expected a positive finite ratio",
275 ));
276 }
277 if let Some(date) = rate_date_time {
278 check_date(release, ENTITY, "RateDateTime", date)?;
279 }
280 let dates = [rate_date_time];
281 let mut record = release.record(
282 ENTITY,
283 vec![
284 ("RelatingMonetaryUnit", Value::Ref(relating)),
285 ("RelatedMonetaryUnit", Value::Ref(related)),
286 ("ExchangeRate", Value::Real(exchange_rate)),
287 (
288 "RateDateTime",
289 rate_date_time.map_or(Value::Null, |date| date.provisional(PLACEHOLDERS[0])),
290 ),
291 ],
292 )?;
293 patch(tx, &mut record, &dates);
294 Ok(tx.create(record))
295}