ifc-control 0.3.0

Bounded IFC control semantics: permits, project orders, action requests, and performance history.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
//! Staging the four `IfcControl` subtypes this crate owns.
//!
//! # What a control is
//!
//! A control is a record that governs work rather than describing
//! physical form: a permit that authorises it, an order that
//! commissions it, a request that asks for it, a performance history
//! that records how it behaved. They carry no geometry.
//!
//! # The shape they share
//!
//! All four are `IfcControl` subtypes, so slots 0-5 are fixed:
//! the four `IfcRoot` slots, `ObjectType`, and `Identification`.
//! Three of them then take `PredefinedType`, `Status` and
//! `LongDescription`. `IfcPerformanceHistory` does not: it takes a
//! required `LifeCyclePhase` at slot 6 and its predefined type at
//! slot 7, so a writer that assumes the common tail would file the
//! phase as a status.
//!
//! The positions above are IFC4's. IFC2X3 declares an `IfcControl`
//! without `Identification`, and each control its own tail (#198):
//!
//! ```text
//! IFC2X3_TC1  IfcPermit              ... ObjectType, PermitID
//! IFC2X3_TC1  IfcActionRequest       ... ObjectType, RequestID
//! IFC2X3_TC1  IfcProjectOrder        ... ObjectType, ID, PredefinedType, Status
//! IFC2X3_TC1  IfcPerformanceHistory  ... ObjectType, LifeCyclePhase
//! ```
//!
//! So records are laid out by attribute name from the release's own table
//! (`release.rs`), never by these positions.
//!
//! # USERDEFINED
//!
//! These entities declare no WHERE rules. The `USERDEFINED` token
//! still asserts that a name is given elsewhere, and `ObjectType` is
//! where `IfcObject` puts it. Writing `USERDEFINED` without it
//! produces a record that claims a specific kind and withholds which,
//! so it is refused here even though the schema does not say so.
//!
//! # Work orders
//!
//! `IfcWorkOrder` does not exist in any IFC release: a work order is
//! an `IfcProjectOrder` whose `PredefinedType` is `WORKORDER`. There is
//! deliberately no separate entity or `ControlKind` for it.

use ifc_model::guid::Guid;
use ifc_model::{Entity, EntityId, Model, Transaction, Value};
use ifc_schema::Schema;

use crate::error::{ControlError, ControlResult};
use crate::release::{bind, Release};

/// `IfcPermitTypeEnum`.
const PERMIT: &[&str] = &["ACCESS", "BUILDING", "WORK", "USERDEFINED", "NOTDEFINED"];

/// `IfcProjectOrderTypeEnum`.
const PROJECT_ORDER: &[&str] = &[
    "CHANGEORDER",
    "MAINTENANCEWORKORDER",
    "MOVEORDER",
    "PURCHASEORDER",
    "WORKORDER",
    "USERDEFINED",
    "NOTDEFINED",
];

/// `IfcActionRequestTypeEnum`.
const ACTION_REQUEST: &[&str] = &[
    "EMAIL",
    "FAX",
    "PHONE",
    "POST",
    "VERBAL",
    "USERDEFINED",
    "NOTDEFINED",
];

/// `IfcPerformanceHistoryTypeEnum`.
const PERFORMANCE_HISTORY: &[&str] = &["USERDEFINED", "NOTDEFINED"];

/// Which control is being staged.
///
/// A single enum rather than four writers: the four differ only in
/// type name, predefined-type enum, and whether they carry the
/// `Status`/`LongDescription` tail. Four near-identical functions
/// would drift apart on the next schema revision.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ControlKind {
    /// `IfcPermit`: authorisation to proceed.
    Permit,
    /// `IfcProjectOrder`: an instruction to carry work out.
    ProjectOrder,
    /// `IfcActionRequest`: a request that work be done.
    ActionRequest,
    /// `IfcPerformanceHistory`: recorded in-use behaviour.
    PerformanceHistory,
}

impl ControlKind {
    /// Every control this crate owns, in declaration order.
    pub const ALL: [Self; 4] = [
        Self::Permit,
        Self::ProjectOrder,
        Self::ActionRequest,
        Self::PerformanceHistory,
    ];

    /// STEP type name, upper-case as the catalogue stores it.
    ///
    /// Upper-case because `Entity::new` does not normalise and the
    /// model indexes by the stored string.
    #[must_use]
    pub const fn type_name(self) -> &'static str {
        match self {
            Self::Permit => "IFCPERMIT",
            Self::ProjectOrder => "IFCPROJECTORDER",
            Self::ActionRequest => "IFCACTIONREQUEST",
            Self::PerformanceHistory => "IFCPERFORMANCEHISTORY",
        }
    }

    /// The tokens this entity's own `PredefinedType` enum declares.
    #[must_use]
    pub const fn members(self) -> &'static [&'static str] {
        match self {
            Self::Permit => PERMIT,
            Self::ProjectOrder => PROJECT_ORDER,
            Self::ActionRequest => ACTION_REQUEST,
            Self::PerformanceHistory => PERFORMANCE_HISTORY,
        }
    }
}

/// Attributes shared by every control.
#[derive(Debug, Clone, Copy, Default)]
#[non_exhaustive]
pub struct ControlDraft<'a> {
    /// `Name`.
    pub name: Option<&'a str>,
    /// `Description`.
    pub description: Option<&'a str>,
    /// `ObjectType`, slot 4. Required when the predefined type is
    /// `USERDEFINED`.
    pub object_type: Option<&'a str>,
    /// `Identification`, slot 5: the permit or order number.
    pub identification: Option<&'a str>,
    /// `Status`, slot 7. Not declared by `IfcPerformanceHistory`.
    pub status: Option<&'a str>,
    /// `LongDescription`, slot 8. Not declared by
    /// `IfcPerformanceHistory`.
    pub long_description: Option<&'a str>,
    /// `LifeCyclePhase`, slot 6. Required by
    /// `IfcPerformanceHistory` and declared by no other control.
    pub life_cycle_phase: Option<&'a str>,
}

impl<'a> ControlDraft<'a> {
    /// Starts a draft with every field unset.
    #[must_use]
    pub fn new() -> Self {
        Self {
            name: None,
            description: None,
            object_type: None,
            identification: None,
            status: None,
            long_description: None,
            life_cycle_phase: None,
        }
    }

    /// Sets [`Self::name`]: `Name`.
    #[must_use]
    pub fn name(mut self, value: &'a str) -> Self {
        self.name = Some(value);
        self
    }

    /// Sets [`Self::description`]: `Description`.
    #[must_use]
    pub fn description(mut self, value: &'a str) -> Self {
        self.description = Some(value);
        self
    }

    /// Sets [`Self::object_type`]: `ObjectType`, slot 4. Required when the predefined type is `USERDEFINED`.
    #[must_use]
    pub fn object_type(mut self, value: &'a str) -> Self {
        self.object_type = Some(value);
        self
    }

    /// Sets [`Self::identification`]: `Identification`, slot 5: the permit or order number.
    #[must_use]
    pub fn identification(mut self, value: &'a str) -> Self {
        self.identification = Some(value);
        self
    }

    /// Sets [`Self::status`]: `Status`, slot 7. Not declared by `IfcPerformanceHistory`.
    #[must_use]
    pub fn status(mut self, value: &'a str) -> Self {
        self.status = Some(value);
        self
    }

    /// Sets [`Self::long_description`]: `LongDescription`, slot 8. Not declared by `IfcPerformanceHistory`.
    #[must_use]
    pub fn long_description(mut self, value: &'a str) -> Self {
        self.long_description = Some(value);
        self
    }

    /// Sets [`Self::life_cycle_phase`]: `LifeCyclePhase`, slot 6. Required by `IfcPerformanceHistory` and declared by no other control.
    #[must_use]
    pub fn life_cycle_phase(mut self, value: &'a str) -> Self {
        self.life_cycle_phase = Some(value);
        self
    }
}

fn invalid(
    entity: &'static str,
    attribute: &'static str,
    value: impl Into<String>,
) -> ControlError {
    ControlError::AuthoringInvalid {
        entity,
        attribute,
        value: value.into(),
    }
}

fn text(value: Option<&str>) -> Value {
    value.map_or(Value::Null, |v| Value::Text(v.into()))
}

fn blank(value: Option<&str>) -> bool {
    value.is_none_or(|v| v.trim().is_empty())
}

/// Stage one control record, laid out by attribute name in `schema`.
///
/// `OwnerHistory` is left unset, which IFC4 and IFC4X3 allow. IFC2X3
/// requires it, so an IFC2X3 `schema` is refused with
/// [`ControlError::AuthoringRequired`] instead of written as `$`; use
/// [`create_control_with_owner_history`] there. Before #198 an IFC2X3
/// `IfcPermit`, `IfcActionRequest` or `IfcPerformanceHistory` panicked
/// here, indexing past their six declared attributes.
///
/// # Errors
///
/// Refuses a malformed GlobalId; a blank name; a token outside the
/// entity's own enum; `USERDEFINED` without `object_type`; a
/// `life_cycle_phase` on an entity that does not declare it and a
/// missing one on `IfcPerformanceHistory`; `status` or
/// `long_description` on `IfcPerformanceHistory`; and an entity the
/// schema does not declare. Against the release's own table: a value
/// the entity does not declare there (`AuthoringNotInSchema`, such as an
/// IFC2X3 `PredefinedType` on a permit), one it cannot hold
/// (`AuthoringValueType`), and a required one left unset
/// (`AuthoringRequired`, such as the IFC2X3 `OwnerHistory` or
/// `PermitID`). Nothing is staged on an error.
pub fn create_control(
    tx: &mut Transaction,
    schema: &Schema,
    kind: ControlKind,
    global_id: &str,
    predefined_type: Option<&str>,
    draft: ControlDraft<'_>,
) -> ControlResult<EntityId> {
    let release = Release::of_schema(schema);
    let record = control_record(
        release,
        kind,
        global_id,
        predefined_type,
        draft,
        Value::Null,
    )?;
    Ok(tx.create(record))
}

/// [`create_control`] in `model`'s declared release, with a caller-supplied
/// `IfcOwnerHistory`, which IFC2X3 requires (#198, #202).
///
/// The release is bound from `FILE_SCHEMA` (none binds IFC4). In IFC2X3
/// `Identification` is written as the entity's own identifier
/// (`PermitID`, `RequestID`, `ID`), which IFC2X3 requires; IFC2X3 declares
/// no `PredefinedType` for a permit, an action request or a performance
/// history, no `Status` for a permit or an action request, and no
/// `LongDescription` at all. In IFC4 and IFC4X3 the record is that of
/// [`create_control`] with the reference in the optional slot. The
/// owner history is never invented: build it with `ifc-author`.
///
/// # Errors
///
/// Those of [`create_control`] except the IFC2X3 refusal, and:
/// [`ControlError::MultipleSchemas`] or [`ControlError::UnsupportedSchema`]
/// if the model binds no single known release;
/// [`ControlError::UnknownEntity`] if `owner_history` is neither in the
/// model nor staged; [`ControlError::AuthoringInvalid`] if it is not an
/// `IfcOwnerHistory`. Nothing is staged on an error.
pub fn create_control_with_owner_history(
    tx: &mut Transaction,
    model: &Model,
    kind: ControlKind,
    global_id: &str,
    predefined_type: Option<&str>,
    draft: ControlDraft<'_>,
    owner_history: EntityId,
) -> ControlResult<EntityId> {
    let release = bind(model)?;
    let record = control_record(
        release,
        kind,
        global_id,
        predefined_type,
        draft,
        Value::Ref(owner_history),
    )?;
    release.require_owner_history(tx, model, kind.type_name(), owner_history)?;
    Ok(tx.create(record))
}

/// Validate a draft and lay its record out in `release`.
fn control_record(
    release: Release<'_>,
    kind: ControlKind,
    global_id: &str,
    predefined_type: Option<&str>,
    draft: ControlDraft<'_>,
    owner_history: Value,
) -> ControlResult<Entity> {
    let entity = kind.type_name();
    if release.schema().attributes(entity).is_empty() {
        return Err(ControlError::UnsupportedEntity {
            schema: release.schema().name().to_owned(),
            entity,
        });
    }

    if Guid::parse(global_id).is_none() {
        return Err(invalid(entity, "GlobalId", global_id));
    }
    // `IfcRoot.Name` is optional in the slot table, but a control
    // nobody can name is a record nobody can cite in correspondence.
    if blank(draft.name) {
        return Err(invalid(entity, "Name", "required"));
    }

    if let Some(token) = predefined_type {
        if !kind.members().contains(&token) {
            return Err(invalid(entity, "PredefinedType", token));
        }
        if token == "USERDEFINED" && blank(draft.object_type) {
            return Err(invalid(entity, "ObjectType", "required by USERDEFINED"));
        }
    }

    let history = kind == ControlKind::PerformanceHistory;
    // Attributes the entity does not declare are refused, not
    // dropped: silently discarding a Status writes a file missing
    // data the caller believes they supplied.
    if history {
        if blank(draft.life_cycle_phase) {
            return Err(invalid(entity, "LifeCyclePhase", "required"));
        }
        if draft.status.is_some() {
            return Err(invalid(entity, "Status", "not declared"));
        }
        if draft.long_description.is_some() {
            return Err(invalid(entity, "LongDescription", "not declared"));
        }
    } else if draft.life_cycle_phase.is_some() {
        return Err(invalid(entity, "LifeCyclePhase", "not declared"));
    }

    // Placed by name from the release's own table: IFC2X3 declares six
    // attributes for a permit, where IFC4 declares nine. Indexing by the
    // IFC4 positions is what panicked (#198).
    let mut values = vec![
        ("GlobalId", Value::Text(global_id.into())),
        ("OwnerHistory", owner_history),
        ("Name", text(draft.name)),
        ("Description", text(draft.description)),
        ("ObjectType", text(draft.object_type)),
        ("Identification", text(draft.identification)),
        (
            "PredefinedType",
            predefined_type.map_or(Value::Null, |t| Value::Enum(t.into())),
        ),
    ];
    if history {
        values.push(("LifeCyclePhase", text(draft.life_cycle_phase)));
    } else {
        values.push(("Status", text(draft.status)));
        values.push(("LongDescription", text(draft.long_description)));
    }
    release.record(entity, values)
}