Skip to main content

ifc_cost/mutation/
value.rs

1//! Cost values, monetary units and currency relationships, laid out by name
2//! in the model's declared release (#213).
3//!
4//! The three records differ between releases, from the EXPRESS sources:
5//!
6//! ```text
7//! IfcCostValue
8//!   IFC2X3_TC1 (8)   Name, Description, AppliedValue, UnitBasis,
9//!                    ApplicableDate (IfcDateTimeSelect),
10//!                    FixedUntilDate (IfcDateTimeSelect), CostType (required),
11//!                    Condition
12//!   IFC4, IFC4X3 (10) Name, Description, AppliedValue, UnitBasis,
13//!                    ApplicableDate (IfcDate), FixedUntilDate (IfcDate),
14//!                    Category, Condition, ArithmeticOperator, Components
15//! IfcMonetaryUnit
16//!   IFC2X3_TC1       Currency : IfcCurrencyEnum
17//!   IFC4, IFC4X3     Currency : IfcLabel
18//! IfcCurrencyRelationship
19//!   IFC2X3_TC1 (5)   RelatingMonetaryUnit, RelatedMonetaryUnit, ExchangeRate,
20//!                    RateDateTime (IfcDateAndTime, required), RateSource
21//!   IFC4, IFC4X3 (7) Name, Description, RelatingMonetaryUnit,
22//!                    RelatedMonetaryUnit, ExchangeRate,
23//!                    RateDateTime (IfcDateTime, optional), RateSource
24//! ```
25//!
26//! IFC4 renamed `CostType` to `Category` (see `release.rs`). IFC2X3 composes
27//! cost values through `IfcAppliedValueRelationship`, which this crate does
28//! not author, so a [`CostValueKind::Components`] draft is refused there.
29//! IFC2X3 dates are record forms of [`DateTimeValue`], staged by the writer.
30
31use 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
41/// Validate and stage one scalar or explicitly composed cost value in the
42/// model's declared release.
43///
44/// # Errors
45///
46/// A non-finite amount, an empty or non-`IfcCostValue` component list; a
47/// header binding no single verified release (`MultipleSchemas`,
48/// `UnsupportedSchema`); a date record form the schema's rules refuse
49/// (`InvalidValue`); a value in the form the release does not declare
50/// (`AuthoringValueType`: IFC2X3 dates are `IfcDateTimeSelect` records,
51/// IFC4 and IFC4X3 dates `IfcDate` text); a composed value in IFC2X3
52/// (`AuthoringNotInSchema`: it declares no `ArithmeticOperator` or
53/// `Components`); and an IFC2X3 value without a `category`
54/// (`AuthoringRequired`: `CostType` is required there). Nothing is staged
55/// on an error: date records are staged only once the value is accepted.
56pub 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
131/// Check a date's record form against the schema's rules, and that the
132/// release declares the form it takes: text for `IfcDate`/`IfcDateTime`,
133/// the record entity for an IFC2X3 `IfcDateTimeSelect` or `IfcDateAndTime`.
134fn 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        // Text is checked against the declared type by `record`.
143        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
182/// Stage an `IfcMonetaryUnit` in the model's declared release.
183///
184/// IFC4 and IFC4X3 declare `Currency` an `IfcLabel`, written as given. The
185/// reader resolves a file's currency by matching this text, which is why a
186/// blank one is refused rather than written: it would leave every cost
187/// value denominated in nothing. IFC2X3 declares an `IfcCurrencyEnum`: the
188/// label must name one of its enumerators and is written as that
189/// enumerator, never as text.
190///
191/// # Errors
192///
193/// A blank currency; a header binding no single verified release
194/// (`MultipleSchemas`, `UnsupportedSchema`); and in IFC2X3 a currency
195/// `IfcCurrencyEnum` does not list (`AuthoringValueType`).
196pub 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
229/// Stage an `IfcCurrencyRelationship`: an exchange rate between two
230/// monetary units, in the model's declared release.
231///
232/// The rate is an `IfcPositiveRatioMeasure`, so zero and negative rates are
233/// refused: a rate of zero would value every converted cost at nothing,
234/// which is a conversion nobody meant to state. `rate_date_time` is
235/// `IfcDateTime` text in IFC4 and IFC4X3, where it is optional; IFC2X3
236/// requires it as an `IfcDateAndTime` record
237/// ([`DateTimeValue::DateAndTime`]), which the writer stages.
238///
239/// # Errors
240///
241/// A reference that is not an `IfcMonetaryUnit`, a unit related to itself,
242/// a non-positive or non-finite rate; a header binding no single verified
243/// release; a date the schema's rules refuse (`InvalidValue`) or in a form
244/// the release does not declare (`AuthoringValueType`); and in IFC2X3 a
245/// missing `rate_date_time` (`AuthoringRequired`). Nothing is staged on an
246/// error.
247pub 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}