Skip to main content

ifc_control/
authoring.rs

1//! Staging the four `IfcControl` subtypes this crate owns.
2//!
3//! # What a control is
4//!
5//! A control is a record that governs work rather than describing
6//! physical form: a permit that authorises it, an order that
7//! commissions it, a request that asks for it, a performance history
8//! that records how it behaved. They carry no geometry.
9//!
10//! # The shape they share
11//!
12//! All four are `IfcControl` subtypes, so slots 0-5 are fixed:
13//! the four `IfcRoot` slots, `ObjectType`, and `Identification`.
14//! Three of them then take `PredefinedType`, `Status` and
15//! `LongDescription`. `IfcPerformanceHistory` does not: it takes a
16//! required `LifeCyclePhase` at slot 6 and its predefined type at
17//! slot 7, so a writer that assumes the common tail would file the
18//! phase as a status.
19//!
20//! The positions above are IFC4's. IFC2X3 declares an `IfcControl`
21//! without `Identification`, and each control its own tail (#198):
22//!
23//! ```text
24//! IFC2X3_TC1  IfcPermit              ... ObjectType, PermitID
25//! IFC2X3_TC1  IfcActionRequest       ... ObjectType, RequestID
26//! IFC2X3_TC1  IfcProjectOrder        ... ObjectType, ID, PredefinedType, Status
27//! IFC2X3_TC1  IfcPerformanceHistory  ... ObjectType, LifeCyclePhase
28//! ```
29//!
30//! So records are laid out by attribute name from the release's own table
31//! (`release.rs`), never by these positions.
32//!
33//! # USERDEFINED
34//!
35//! These entities declare no WHERE rules. The `USERDEFINED` token
36//! still asserts that a name is given elsewhere, and `ObjectType` is
37//! where `IfcObject` puts it. Writing `USERDEFINED` without it
38//! produces a record that claims a specific kind and withholds which,
39//! so it is refused here even though the schema does not say so.
40//!
41//! # Work orders
42//!
43//! `IfcWorkOrder` does not exist in any IFC release: a work order is
44//! an `IfcProjectOrder` whose `PredefinedType` is `WORKORDER`. There is
45//! deliberately no separate entity or `ControlKind` for it.
46
47use ifc_model::guid::Guid;
48use ifc_model::{Entity, EntityId, Model, Transaction, Value};
49use ifc_schema::Schema;
50
51use crate::error::{ControlError, ControlResult};
52use crate::release::{bind, Release};
53
54/// `IfcPermitTypeEnum`.
55const PERMIT: &[&str] = &["ACCESS", "BUILDING", "WORK", "USERDEFINED", "NOTDEFINED"];
56
57/// `IfcProjectOrderTypeEnum`.
58const PROJECT_ORDER: &[&str] = &[
59    "CHANGEORDER",
60    "MAINTENANCEWORKORDER",
61    "MOVEORDER",
62    "PURCHASEORDER",
63    "WORKORDER",
64    "USERDEFINED",
65    "NOTDEFINED",
66];
67
68/// `IfcActionRequestTypeEnum`.
69const ACTION_REQUEST: &[&str] = &[
70    "EMAIL",
71    "FAX",
72    "PHONE",
73    "POST",
74    "VERBAL",
75    "USERDEFINED",
76    "NOTDEFINED",
77];
78
79/// `IfcPerformanceHistoryTypeEnum`.
80const PERFORMANCE_HISTORY: &[&str] = &["USERDEFINED", "NOTDEFINED"];
81
82/// Which control is being staged.
83///
84/// A single enum rather than four writers: the four differ only in
85/// type name, predefined-type enum, and whether they carry the
86/// `Status`/`LongDescription` tail. Four near-identical functions
87/// would drift apart on the next schema revision.
88#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89#[non_exhaustive]
90pub enum ControlKind {
91    /// `IfcPermit`: authorisation to proceed.
92    Permit,
93    /// `IfcProjectOrder`: an instruction to carry work out.
94    ProjectOrder,
95    /// `IfcActionRequest`: a request that work be done.
96    ActionRequest,
97    /// `IfcPerformanceHistory`: recorded in-use behaviour.
98    PerformanceHistory,
99}
100
101impl ControlKind {
102    /// Every control this crate owns, in declaration order.
103    pub const ALL: [Self; 4] = [
104        Self::Permit,
105        Self::ProjectOrder,
106        Self::ActionRequest,
107        Self::PerformanceHistory,
108    ];
109
110    /// STEP type name, upper-case as the catalogue stores it.
111    ///
112    /// Upper-case because `Entity::new` does not normalise and the
113    /// model indexes by the stored string.
114    #[must_use]
115    pub const fn type_name(self) -> &'static str {
116        match self {
117            Self::Permit => "IFCPERMIT",
118            Self::ProjectOrder => "IFCPROJECTORDER",
119            Self::ActionRequest => "IFCACTIONREQUEST",
120            Self::PerformanceHistory => "IFCPERFORMANCEHISTORY",
121        }
122    }
123
124    /// The tokens this entity's own `PredefinedType` enum declares.
125    #[must_use]
126    pub const fn members(self) -> &'static [&'static str] {
127        match self {
128            Self::Permit => PERMIT,
129            Self::ProjectOrder => PROJECT_ORDER,
130            Self::ActionRequest => ACTION_REQUEST,
131            Self::PerformanceHistory => PERFORMANCE_HISTORY,
132        }
133    }
134}
135
136/// Attributes shared by every control.
137#[derive(Debug, Clone, Copy, Default)]
138pub struct ControlDraft<'a> {
139    /// `Name`.
140    pub name: Option<&'a str>,
141    /// `Description`.
142    pub description: Option<&'a str>,
143    /// `ObjectType`, slot 4. Required when the predefined type is
144    /// `USERDEFINED`.
145    pub object_type: Option<&'a str>,
146    /// `Identification`, slot 5: the permit or order number.
147    pub identification: Option<&'a str>,
148    /// `Status`, slot 7. Not declared by `IfcPerformanceHistory`.
149    pub status: Option<&'a str>,
150    /// `LongDescription`, slot 8. Not declared by
151    /// `IfcPerformanceHistory`.
152    pub long_description: Option<&'a str>,
153    /// `LifeCyclePhase`, slot 6. Required by
154    /// `IfcPerformanceHistory` and declared by no other control.
155    pub life_cycle_phase: Option<&'a str>,
156}
157
158fn invalid(
159    entity: &'static str,
160    attribute: &'static str,
161    value: impl Into<String>,
162) -> ControlError {
163    ControlError::AuthoringInvalid {
164        entity,
165        attribute,
166        value: value.into(),
167    }
168}
169
170fn text(value: Option<&str>) -> Value {
171    value.map_or(Value::Null, |v| Value::Text(v.into()))
172}
173
174fn blank(value: Option<&str>) -> bool {
175    value.is_none_or(|v| v.trim().is_empty())
176}
177
178/// Stage one control record, laid out by attribute name in `schema`.
179///
180/// `OwnerHistory` is left unset, which IFC4 and IFC4X3 allow. IFC2X3
181/// requires it, so an IFC2X3 `schema` is refused with
182/// [`ControlError::AuthoringRequired`] instead of written as `$`; use
183/// [`create_control_with_owner_history`] there. Before #198 an IFC2X3
184/// `IfcPermit`, `IfcActionRequest` or `IfcPerformanceHistory` panicked
185/// here, indexing past their six declared attributes.
186///
187/// # Errors
188///
189/// Refuses a malformed GlobalId; a blank name; a token outside the
190/// entity's own enum; `USERDEFINED` without `object_type`; a
191/// `life_cycle_phase` on an entity that does not declare it and a
192/// missing one on `IfcPerformanceHistory`; `status` or
193/// `long_description` on `IfcPerformanceHistory`; and an entity the
194/// schema does not declare. Against the release's own table: a value
195/// the entity does not declare there (`AuthoringNotInSchema`, such as an
196/// IFC2X3 `PredefinedType` on a permit), one it cannot hold
197/// (`AuthoringValueType`), and a required one left unset
198/// (`AuthoringRequired`, such as the IFC2X3 `OwnerHistory` or
199/// `PermitID`). Nothing is staged on an error.
200pub fn create_control(
201    tx: &mut Transaction,
202    schema: &Schema,
203    kind: ControlKind,
204    global_id: &str,
205    predefined_type: Option<&str>,
206    draft: ControlDraft<'_>,
207) -> ControlResult<EntityId> {
208    let release = Release::of_schema(schema);
209    let record = control_record(
210        release,
211        kind,
212        global_id,
213        predefined_type,
214        draft,
215        Value::Null,
216    )?;
217    Ok(tx.create(record))
218}
219
220/// [`create_control`] in `model`'s declared release, with a caller-supplied
221/// `IfcOwnerHistory`, which IFC2X3 requires (#198, #202).
222///
223/// The release is bound from `FILE_SCHEMA` (none binds IFC4). In IFC2X3
224/// `Identification` is written as the entity's own identifier
225/// (`PermitID`, `RequestID`, `ID`), which IFC2X3 requires; IFC2X3 declares
226/// no `PredefinedType` for a permit, an action request or a performance
227/// history, no `Status` for a permit or an action request, and no
228/// `LongDescription` at all. In IFC4 and IFC4X3 the record is that of
229/// [`create_control`] with the reference in the optional slot. The
230/// owner history is never invented: build it with `ifc-author`.
231///
232/// # Errors
233///
234/// Those of [`create_control`] except the IFC2X3 refusal, and:
235/// [`ControlError::MultipleSchemas`] or [`ControlError::UnsupportedSchema`]
236/// if the model binds no single known release;
237/// [`ControlError::UnknownEntity`] if `owner_history` is neither in the
238/// model nor staged; [`ControlError::AuthoringInvalid`] if it is not an
239/// `IfcOwnerHistory`. Nothing is staged on an error.
240pub fn create_control_with_owner_history(
241    tx: &mut Transaction,
242    model: &Model,
243    kind: ControlKind,
244    global_id: &str,
245    predefined_type: Option<&str>,
246    draft: ControlDraft<'_>,
247    owner_history: EntityId,
248) -> ControlResult<EntityId> {
249    let release = bind(model)?;
250    let record = control_record(
251        release,
252        kind,
253        global_id,
254        predefined_type,
255        draft,
256        Value::Ref(owner_history),
257    )?;
258    release.require_owner_history(tx, model, kind.type_name(), owner_history)?;
259    Ok(tx.create(record))
260}
261
262/// Validate a draft and lay its record out in `release`.
263fn control_record(
264    release: Release<'_>,
265    kind: ControlKind,
266    global_id: &str,
267    predefined_type: Option<&str>,
268    draft: ControlDraft<'_>,
269    owner_history: Value,
270) -> ControlResult<Entity> {
271    let entity = kind.type_name();
272    if release.schema().attributes(entity).is_empty() {
273        return Err(ControlError::UnsupportedEntity {
274            schema: release.schema().name().to_owned(),
275            entity,
276        });
277    }
278
279    if Guid::parse(global_id).is_none() {
280        return Err(invalid(entity, "GlobalId", global_id));
281    }
282    // `IfcRoot.Name` is optional in the slot table, but a control
283    // nobody can name is a record nobody can cite in correspondence.
284    if blank(draft.name) {
285        return Err(invalid(entity, "Name", "required"));
286    }
287
288    if let Some(token) = predefined_type {
289        if !kind.members().contains(&token) {
290            return Err(invalid(entity, "PredefinedType", token));
291        }
292        if token == "USERDEFINED" && blank(draft.object_type) {
293            return Err(invalid(entity, "ObjectType", "required by USERDEFINED"));
294        }
295    }
296
297    let history = kind == ControlKind::PerformanceHistory;
298    // Attributes the entity does not declare are refused, not
299    // dropped: silently discarding a Status writes a file missing
300    // data the caller believes they supplied.
301    if history {
302        if blank(draft.life_cycle_phase) {
303            return Err(invalid(entity, "LifeCyclePhase", "required"));
304        }
305        if draft.status.is_some() {
306            return Err(invalid(entity, "Status", "not declared"));
307        }
308        if draft.long_description.is_some() {
309            return Err(invalid(entity, "LongDescription", "not declared"));
310        }
311    } else if draft.life_cycle_phase.is_some() {
312        return Err(invalid(entity, "LifeCyclePhase", "not declared"));
313    }
314
315    // Placed by name from the release's own table: IFC2X3 declares six
316    // attributes for a permit, where IFC4 declares nine. Indexing by the
317    // IFC4 positions is what panicked (#198).
318    let mut values = vec![
319        ("GlobalId", Value::Text(global_id.into())),
320        ("OwnerHistory", owner_history),
321        ("Name", text(draft.name)),
322        ("Description", text(draft.description)),
323        ("ObjectType", text(draft.object_type)),
324        ("Identification", text(draft.identification)),
325        (
326            "PredefinedType",
327            predefined_type.map_or(Value::Null, |t| Value::Enum(t.into())),
328        ),
329    ];
330    if history {
331        values.push(("LifeCyclePhase", text(draft.life_cycle_phase)));
332    } else {
333        values.push(("Status", text(draft.status)));
334        values.push(("LongDescription", text(draft.long_description)));
335    }
336    release.record(entity, values)
337}