Skip to main content

ifc_cost/mutation/
control.rs

1//! Cost items, schedules and their relationships, laid out by name in the
2//! model's declared release (#202).
3//!
4//! `IfcRoot.OwnerHistory` is required in IFC2X3 TC1 and `OPTIONAL` from
5//! IFC4 on:
6//!
7//! ```text
8//! IFC2X3_TC1   OwnerHistory : IfcOwnerHistory;
9//! IFC4         OwnerHistory : OPTIONAL IfcOwnerHistory;
10//! IFC4X3_ADD2  OwnerHistory : OPTIONAL IfcOwnerHistory;
11//! ```
12//!
13//! The writers that leave it unset refuse an IFC2X3 model with
14//! [`CostAuthoringError::AuthoringRequired`] instead of writing `$`. The
15//! `*_with_owner_history` variants take a caller-supplied `IfcOwnerHistory`
16//! (in the model or staged on the transaction); one is never invented here.
17//! This follows `ifc-material` (#77), `ifc-properties` (#191) and
18//! `ifc-classification` (#194).
19//!
20//! IFC2X3 also declares less: `IfcCostItem` has only the five `IfcControl`
21//! attributes (no `Identification`, `PredefinedType`, `CostValues` or
22//! `CostQuantities`), and `IfcCostSchedule` requires `ID` and
23//! `PredefinedType` and types its dates as `IfcDateTimeSelect` records,
24//! which [`CostScheduleDraft`] carries as [`DateTimeValue`] record forms and
25//! the writer stages (#214). A draft value the release cannot hold is
26//! refused, never dropped.
27//!
28//! [`CostAuthoringError::AuthoringRequired`]: super::CostAuthoringError::AuthoringRequired
29
30use ifc_model::{EntityId, Model, Transaction, Value};
31
32use super::datetime::{patch, DateTimeValue, PLACEHOLDERS};
33use super::draft::{
34    CostItemDraft, CostItemType, CostScheduleDraft, CostScheduleType, NestingDraft,
35    ScheduleAssignmentDraft,
36};
37use super::release::{bind, Release};
38use super::validate::{guid, invalid, non_empty_unique, reference_type, validate_nesting};
39use super::value::{optional_enum, optional_text, refs};
40use super::CostAuthoringResult;
41
42/// Validate and stage one cost item in the model's declared release, with
43/// `OwnerHistory` unset.
44///
45/// All references may target the model or entities staged earlier in `tx`.
46///
47/// # Errors
48///
49/// A malformed or duplicate GlobalId; `USERDEFINED` without `ObjectType`; a
50/// cost value that is not an `IfcCostValue`; a header binding no single
51/// known release (`MultipleSchemas`, `UnsupportedSchema`); a value the
52/// release does not declare (`AuthoringNotInSchema`: IFC2X3 has no
53/// `Identification`, `PredefinedType` or `CostValues`); and an IFC2X3
54/// model, which requires `OwnerHistory` (`AuthoringRequired`: use
55/// [`create_cost_item_with_owner_history`]). Nothing is staged on an error.
56pub fn create_cost_item(
57    tx: &mut Transaction,
58    model: &Model,
59    draft: CostItemDraft<'_>,
60) -> CostAuthoringResult<EntityId> {
61    cost_item(tx, model, draft, None)
62}
63
64/// [`create_cost_item`] with a caller-supplied `IfcOwnerHistory`, which
65/// IFC2X3 requires.
66///
67/// # Errors
68///
69/// Those of [`create_cost_item`] except the IFC2X3 refusal, and an
70/// `owner_history` that does not resolve (`MissingReference`) or is not an
71/// `IfcOwnerHistory` (`WrongReferenceType`).
72pub fn create_cost_item_with_owner_history(
73    tx: &mut Transaction,
74    model: &Model,
75    draft: CostItemDraft<'_>,
76    owner_history: EntityId,
77) -> CostAuthoringResult<EntityId> {
78    cost_item(tx, model, draft, Some(owner_history))
79}
80
81fn cost_item(
82    tx: &mut Transaction,
83    model: &Model,
84    draft: CostItemDraft<'_>,
85    owner_history: Option<EntityId>,
86) -> CostAuthoringResult<EntityId> {
87    const ENTITY: &str = "IFCCOSTITEM";
88    let release = bind(model)?;
89    guid(tx, model, ENTITY, draft.global_id)?;
90    if draft.predefined_type == Some(CostItemType::UserDefined) && draft.object_type.is_none() {
91        return Err(invalid(
92            ENTITY,
93            "ObjectType",
94            "required for USERDEFINED PredefinedType",
95        ));
96    }
97    for target in draft.cost_values {
98        reference_type(tx, model, ENTITY, "CostValues", *target, "IFCCOSTVALUE")?;
99    }
100    let record = release.record(
101        ENTITY,
102        vec![
103            ("GlobalId", Value::Text(draft.global_id.into())),
104            (
105                "OwnerHistory",
106                owner_history.map_or(Value::Null, Value::Ref),
107            ),
108            ("Name", optional_text(draft.name)),
109            ("Description", optional_text(draft.description)),
110            ("ObjectType", optional_text(draft.object_type)),
111            ("Identification", optional_text(draft.identification)),
112            (
113                "PredefinedType",
114                optional_enum(draft.predefined_type.map(CostItemType::token)),
115            ),
116            ("CostValues", optional_refs(draft.cost_values)),
117        ],
118    )?;
119    stage(tx, model, release, ENTITY, record, owner_history)
120}
121
122/// Validate and stage one cost schedule in the model's declared release,
123/// with `OwnerHistory` unset.
124///
125/// # Errors
126///
127/// A malformed or duplicate GlobalId; `USERDEFINED` without `ObjectType`;
128/// a header binding no single known release; a date record form the
129/// schema's rules refuse (`InvalidValue`: a month outside 1..=12, a day the
130/// month does not have, an hour, minute or second out of range, a second
131/// without a minute); a date in the form the release does not declare
132/// (`AuthoringValueType`: IFC2X3 types `SubmittedOn` and `UpdateDate` as
133/// `IfcDateTimeSelect` records, IFC4 and IFC4X3 as `IfcDateTime` text); a
134/// required value left unset (`AuthoringRequired`: IFC2X3 requires `ID`,
135/// written from `identification`, and `PredefinedType`); and an IFC2X3
136/// model, which requires `OwnerHistory` (use
137/// [`create_cost_schedule_with_owner_history`]). Nothing is staged on an
138/// error: IFC2X3 date records are staged only once the schedule itself is
139/// accepted.
140pub fn create_cost_schedule(
141    tx: &mut Transaction,
142    model: &Model,
143    draft: CostScheduleDraft<'_>,
144) -> CostAuthoringResult<EntityId> {
145    cost_schedule(tx, model, draft, None)
146}
147
148/// [`create_cost_schedule`] with a caller-supplied `IfcOwnerHistory`, which
149/// IFC2X3 requires.
150///
151/// # Errors
152///
153/// Those of [`create_cost_schedule`] except the IFC2X3 owner-history
154/// refusal, and the owner-history refusals of
155/// [`create_cost_item_with_owner_history`].
156pub fn create_cost_schedule_with_owner_history(
157    tx: &mut Transaction,
158    model: &Model,
159    draft: CostScheduleDraft<'_>,
160    owner_history: EntityId,
161) -> CostAuthoringResult<EntityId> {
162    cost_schedule(tx, model, draft, Some(owner_history))
163}
164
165fn cost_schedule(
166    tx: &mut Transaction,
167    model: &Model,
168    draft: CostScheduleDraft<'_>,
169    owner_history: Option<EntityId>,
170) -> CostAuthoringResult<EntityId> {
171    const ENTITY: &str = "IFCCOSTSCHEDULE";
172    let release = bind(model)?;
173    guid(tx, model, ENTITY, draft.global_id)?;
174    if draft.predefined_type == Some(CostScheduleType::UserDefined) && draft.object_type.is_none() {
175        return Err(invalid(
176            ENTITY,
177            "ObjectType",
178            "required for USERDEFINED PredefinedType",
179        ));
180    }
181    let dates = [draft.submitted_on, draft.update_date];
182    for date in dates.iter().flatten() {
183        date.check()?;
184    }
185    let provisional = |slot: usize| {
186        dates[slot].map_or(Value::Null, |date: DateTimeValue<'_>| {
187            date.provisional(PLACEHOLDERS[slot])
188        })
189    };
190    let mut record = release.record(
191        ENTITY,
192        vec![
193            ("GlobalId", Value::Text(draft.global_id.into())),
194            (
195                "OwnerHistory",
196                owner_history.map_or(Value::Null, Value::Ref),
197            ),
198            ("Name", optional_text(draft.name)),
199            ("Description", optional_text(draft.description)),
200            ("ObjectType", optional_text(draft.object_type)),
201            ("Identification", optional_text(draft.identification)),
202            (
203                "PredefinedType",
204                optional_enum(draft.predefined_type.map(CostScheduleType::token)),
205            ),
206            ("Status", optional_text(draft.status)),
207            ("SubmittedOn", provisional(0)),
208            ("UpdateDate", provisional(1)),
209        ],
210    )?;
211    // Every refusal before the first edit: the record with placeholders,
212    // then the owner history; only then the date records.
213    if let Some(owner_history) = owner_history {
214        release.require_owner_history(tx, model, ENTITY, owner_history)?;
215    }
216    patch(tx, &mut record, &dates);
217    Ok(tx.create(record))
218}
219
220/// Validate and stage ordered cost-item nesting, with `OwnerHistory` unset.
221///
222/// Self-reference, duplicate children, second parents, and projected cycles
223/// are refused.
224///
225/// # Errors
226///
227/// Those refusals, a malformed or duplicate GlobalId, a parent or child
228/// that is not an `IfcCostItem`, a header binding no single known release,
229/// and an IFC2X3 model, which requires `OwnerHistory` (use
230/// [`nest_cost_items_with_owner_history`]). Nothing is staged on an error.
231pub fn nest_cost_items(
232    tx: &mut Transaction,
233    model: &Model,
234    draft: NestingDraft<'_>,
235) -> CostAuthoringResult<EntityId> {
236    nesting(tx, model, draft, None)
237}
238
239/// [`nest_cost_items`] with a caller-supplied `IfcOwnerHistory`, which
240/// IFC2X3 requires.
241///
242/// # Errors
243///
244/// Those of [`nest_cost_items`] except the IFC2X3 refusal, and the
245/// owner-history refusals of [`create_cost_item_with_owner_history`].
246pub fn nest_cost_items_with_owner_history(
247    tx: &mut Transaction,
248    model: &Model,
249    draft: NestingDraft<'_>,
250    owner_history: EntityId,
251) -> CostAuthoringResult<EntityId> {
252    nesting(tx, model, draft, Some(owner_history))
253}
254
255fn nesting(
256    tx: &mut Transaction,
257    model: &Model,
258    draft: NestingDraft<'_>,
259    owner_history: Option<EntityId>,
260) -> CostAuthoringResult<EntityId> {
261    const ENTITY: &str = "IFCRELNESTS";
262    let release = bind(model)?;
263    guid(tx, model, ENTITY, draft.global_id)?;
264    non_empty_unique(ENTITY, "RelatedObjects", draft.children)?;
265    reference_type(
266        tx,
267        model,
268        ENTITY,
269        "RelatingObject",
270        draft.parent,
271        "IFCCOSTITEM",
272    )?;
273    for child in draft.children {
274        reference_type(tx, model, ENTITY, "RelatedObjects", *child, "IFCCOSTITEM")?;
275    }
276    validate_nesting(tx, model, draft.parent, draft.children)?;
277    let record = release.record(
278        ENTITY,
279        vec![
280            ("GlobalId", Value::Text(draft.global_id.into())),
281            (
282                "OwnerHistory",
283                owner_history.map_or(Value::Null, Value::Ref),
284            ),
285            ("RelatingObject", Value::Ref(draft.parent)),
286            ("RelatedObjects", refs(draft.children)),
287        ],
288    )?;
289    stage(tx, model, release, ENTITY, record, owner_history)
290}
291
292/// Validate and stage a schedule-to-items `IfcRelAssignsToControl`, with
293/// `OwnerHistory` unset.
294///
295/// `RelatedObjectsType` is left unset. IFC4 redeclares it as
296/// `OPTIONAL IfcStrippedOptional`, a BOOLEAN retained only so older
297/// files still parse; the IFC2x3 reading, where it named the common
298/// type of the related objects, no longer applies. Writing `.CONTROL.`
299/// there put an enumeration token in a boolean slot -- a file that
300/// parses and is wrong. The constraint that every target is an exact
301/// `IfcCostItem` is still enforced, by the reference check below.
302///
303/// # Errors
304///
305/// A malformed or duplicate GlobalId; an empty or duplicated item list; a
306/// schedule that is not an `IfcCostSchedule` or an item that is not an
307/// `IfcCostItem`; a header binding no single known release; and an IFC2X3
308/// model, which requires `OwnerHistory` (use
309/// [`assign_schedule_items_with_owner_history`]). Nothing is staged on an
310/// error.
311pub fn assign_schedule_items(
312    tx: &mut Transaction,
313    model: &Model,
314    draft: ScheduleAssignmentDraft<'_>,
315) -> CostAuthoringResult<EntityId> {
316    schedule_assignment(tx, model, draft, None)
317}
318
319/// [`assign_schedule_items`] with a caller-supplied `IfcOwnerHistory`,
320/// which IFC2X3 requires.
321///
322/// # Errors
323///
324/// Those of [`assign_schedule_items`] except the IFC2X3 refusal, and the
325/// owner-history refusals of [`create_cost_item_with_owner_history`].
326pub fn assign_schedule_items_with_owner_history(
327    tx: &mut Transaction,
328    model: &Model,
329    draft: ScheduleAssignmentDraft<'_>,
330    owner_history: EntityId,
331) -> CostAuthoringResult<EntityId> {
332    schedule_assignment(tx, model, draft, Some(owner_history))
333}
334
335fn schedule_assignment(
336    tx: &mut Transaction,
337    model: &Model,
338    draft: ScheduleAssignmentDraft<'_>,
339    owner_history: Option<EntityId>,
340) -> CostAuthoringResult<EntityId> {
341    const ENTITY: &str = "IFCRELASSIGNSTOCONTROL";
342    let release = bind(model)?;
343    guid(tx, model, ENTITY, draft.global_id)?;
344    non_empty_unique(ENTITY, "RelatedObjects", draft.items)?;
345    reference_type(
346        tx,
347        model,
348        ENTITY,
349        "RelatingControl",
350        draft.schedule,
351        "IFCCOSTSCHEDULE",
352    )?;
353    for item in draft.items {
354        reference_type(tx, model, ENTITY, "RelatedObjects", *item, "IFCCOSTITEM")?;
355    }
356    let record = release.record(
357        ENTITY,
358        vec![
359            ("GlobalId", Value::Text(draft.global_id.into())),
360            (
361                "OwnerHistory",
362                owner_history.map_or(Value::Null, Value::Ref),
363            ),
364            ("RelatedObjects", refs(draft.items)),
365            // RelatedObjectsType: stripped in IFC4, deliberately unset.
366            ("RelatedObjectsType", Value::Null),
367            ("RelatingControl", Value::Ref(draft.schedule)),
368        ],
369    )?;
370    stage(tx, model, release, ENTITY, record, owner_history)
371}
372
373/// Check the owner history, then stage `record`: every refusal comes
374/// before the one edit.
375fn stage(
376    tx: &mut Transaction,
377    model: &Model,
378    release: Release,
379    entity: &'static str,
380    record: ifc_model::Entity,
381    owner_history: Option<EntityId>,
382) -> CostAuthoringResult<EntityId> {
383    if let Some(owner_history) = owner_history {
384        release.require_owner_history(tx, model, entity, owner_history)?;
385    }
386    Ok(tx.create(record))
387}
388
389fn optional_refs(ids: &[EntityId]) -> Value {
390    if ids.is_empty() {
391        Value::Null
392    } else {
393        refs(ids)
394    }
395}