Skip to main content

ifc_approval/
authoring.rs

1//! Transaction-staged authoring for the bounded approval domain.
2//!
3//! `IfcApproval` and the two approval relationships are resources, not
4//! `IfcRoot` subtypes, so they carry no `GlobalId`; never invent one for
5//! them. Only `IfcRelAssociatesApproval` is rooted, and its caller-supplied
6//! GlobalId is validated before staging; it carries `IfcRoot.OwnerHistory`,
7//! which IFC2X3 requires.
8//!
9//! Every writer binds the model's declared release and lays its record out
10//! by attribute name from that release's table (see `release.rs`, #202,
11//! #212). What the release cannot hold is refused, never dropped or
12//! written into a slot that means something else.
13
14use std::collections::HashSet;
15use std::sync::Arc;
16
17use ifc_model::guid::Guid;
18use ifc_model::{Edit, EntityId, Model, Transaction, Value};
19
20use ifc_schema::Schema;
21
22use crate::release::{bind, require_owner_history};
23use crate::{ApprovalError, ApprovalResult};
24
25const APPROVAL: &str = "IFCAPPROVAL";
26const APPROVAL_REL: &str = "IFCAPPROVALRELATIONSHIP";
27const RESOURCE_REL: &str = "IFCRESOURCEAPPROVALRELATIONSHIP";
28const ASSIGNMENT: &str = "IFCRELASSOCIATESAPPROVAL";
29
30/// A date and time for an authoring draft, in the form the release
31/// declares it.
32///
33/// IFC4 and IFC4X3 declare `IfcDateTime`, ISO 8601 text written as given;
34/// IFC2X3 declares `IfcDateTimeSelect`, a reference to an existing or
35/// earlier-staged `IfcCalendarDate`, `IfcLocalTime` or `IfcDateAndTime`.
36/// A form the release does not declare is refused.
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38#[non_exhaustive]
39pub enum DateTimeInput<'a> {
40    /// IFC4/IFC4X3 `IfcDateTime` text.
41    Text(&'a str),
42    /// An IFC2X3 `IfcDateTimeSelect` record.
43    Record(EntityId),
44}
45
46impl<'a> From<&'a str> for DateTimeInput<'a> {
47    fn from(text: &'a str) -> Self {
48        Self::Text(text)
49    }
50}
51
52impl From<EntityId> for DateTimeInput<'_> {
53    fn from(record: EntityId) -> Self {
54        Self::Record(record)
55    }
56}
57
58/// Draft for one `IfcApproval`.
59#[derive(Debug, Clone, Copy, Default)]
60#[non_exhaustive]
61pub struct ApprovalDraft<'a> {
62    /// Optional identifier; at least this or `name` is required.
63    pub identifier: Option<&'a str>,
64    /// Optional name; at least this or `identifier` is required.
65    pub name: Option<&'a str>,
66    /// Optional description.
67    pub description: Option<&'a str>,
68    /// Optional approval time: IFC4/IFC4X3 `IfcDateTime` text, or an
69    /// existing or earlier-staged IFC2X3 `IfcDateTimeSelect` record
70    /// (`ApprovalDateTime`, which IFC2X3 requires).
71    pub time_of_approval: Option<DateTimeInput<'a>>,
72    /// Optional status label.
73    pub status: Option<&'a str>,
74    /// Optional level label.
75    pub level: Option<&'a str>,
76    /// Optional qualifier text.
77    pub qualifier: Option<&'a str>,
78    /// Optional existing or earlier-staged `IfcActorSelect` target.
79    pub requesting_approval: Option<EntityId>,
80    /// Optional existing or earlier-staged `IfcActorSelect` target.
81    pub giving_approval: Option<EntityId>,
82}
83
84impl<'a> ApprovalDraft<'a> {
85    /// Starts a draft with every field unset.
86    #[must_use]
87    pub fn new() -> Self {
88        Self {
89            identifier: None,
90            name: None,
91            description: None,
92            time_of_approval: None,
93            status: None,
94            level: None,
95            qualifier: None,
96            requesting_approval: None,
97            giving_approval: None,
98        }
99    }
100
101    /// Sets [`Self::identifier`]: Optional identifier; at least this or `name` is required.
102    #[must_use]
103    pub fn identifier(mut self, value: &'a str) -> Self {
104        self.identifier = Some(value);
105        self
106    }
107
108    /// Sets [`Self::name`]: Optional name; at least this or `identifier` is required.
109    #[must_use]
110    pub fn name(mut self, value: &'a str) -> Self {
111        self.name = Some(value);
112        self
113    }
114
115    /// Sets [`Self::description`]: Optional description.
116    #[must_use]
117    pub fn description(mut self, value: &'a str) -> Self {
118        self.description = Some(value);
119        self
120    }
121
122    /// Sets [`Self::time_of_approval`]: text, or an IFC2X3 date record.
123    #[must_use]
124    pub fn time_of_approval(mut self, value: impl Into<DateTimeInput<'a>>) -> Self {
125        self.time_of_approval = Some(value.into());
126        self
127    }
128
129    /// Sets [`Self::status`]: Optional status label.
130    #[must_use]
131    pub fn status(mut self, value: &'a str) -> Self {
132        self.status = Some(value);
133        self
134    }
135
136    /// Sets [`Self::level`]: Optional level label.
137    #[must_use]
138    pub fn level(mut self, value: &'a str) -> Self {
139        self.level = Some(value);
140        self
141    }
142
143    /// Sets [`Self::qualifier`]: Optional qualifier text.
144    #[must_use]
145    pub fn qualifier(mut self, value: &'a str) -> Self {
146        self.qualifier = Some(value);
147        self
148    }
149
150    /// Sets [`Self::requesting_approval`]: Optional existing or earlier-staged `IfcActorSelect` target.
151    #[must_use]
152    pub fn requesting_approval(mut self, value: EntityId) -> Self {
153        self.requesting_approval = Some(value);
154        self
155    }
156
157    /// Sets [`Self::giving_approval`]: Optional existing or earlier-staged `IfcActorSelect` target.
158    #[must_use]
159    pub fn giving_approval(mut self, value: EntityId) -> Self {
160        self.giving_approval = Some(value);
161        self
162    }
163}
164
165/// Draft for one direct approval relationship.
166#[derive(Debug, Clone, Copy)]
167#[non_exhaustive]
168pub struct ApprovalRelationshipDraft<'a> {
169    /// Optional relationship name.
170    pub name: Option<&'a str>,
171    /// Optional relationship description.
172    pub description: Option<&'a str>,
173    /// Existing or earlier-staged approval.
174    pub relating_approval: EntityId,
175    /// Non-empty unique related approvals.
176    pub related_approvals: &'a [EntityId],
177}
178
179impl<'a> ApprovalRelationshipDraft<'a> {
180    /// Starts a draft with its required fields; the rest are unset.
181    #[must_use]
182    pub fn new(relating_approval: EntityId, related_approvals: &'a [EntityId]) -> Self {
183        Self {
184            name: None,
185            description: None,
186            relating_approval,
187            related_approvals,
188        }
189    }
190
191    /// Sets [`Self::name`]: Optional relationship name.
192    #[must_use]
193    pub fn name(mut self, value: &'a str) -> Self {
194        self.name = Some(value);
195        self
196    }
197
198    /// Sets [`Self::description`]: Optional relationship description.
199    #[must_use]
200    pub fn description(mut self, value: &'a str) -> Self {
201        self.description = Some(value);
202        self
203    }
204}
205
206/// Draft for one approval-to-resource relationship.
207#[derive(Debug, Clone, Copy)]
208#[non_exhaustive]
209pub struct ResourceApprovalDraft<'a> {
210    /// Optional relationship name.
211    pub name: Option<&'a str>,
212    /// Optional relationship description.
213    pub description: Option<&'a str>,
214    /// Non-empty unique `IfcResourceObjectSelect` targets.
215    pub related_resources: &'a [EntityId],
216    /// Existing or earlier-staged approval.
217    pub relating_approval: EntityId,
218}
219
220impl<'a> ResourceApprovalDraft<'a> {
221    /// Starts a draft with its required fields; the rest are unset.
222    #[must_use]
223    pub fn new(related_resources: &'a [EntityId], relating_approval: EntityId) -> Self {
224        Self {
225            name: None,
226            description: None,
227            related_resources,
228            relating_approval,
229        }
230    }
231
232    /// Sets [`Self::name`]: Optional relationship name.
233    #[must_use]
234    pub fn name(mut self, value: &'a str) -> Self {
235        self.name = Some(value);
236        self
237    }
238
239    /// Sets [`Self::description`]: Optional relationship description.
240    #[must_use]
241    pub fn description(mut self, value: &'a str) -> Self {
242        self.description = Some(value);
243        self
244    }
245}
246
247/// Draft for one rooted approval association to definitions.
248#[derive(Debug, Clone, Copy)]
249#[non_exhaustive]
250pub struct ApprovalAssociationDraft<'a> {
251    /// Compressed IFC GlobalId.
252    pub global_id: &'a str,
253    /// Optional relationship name.
254    pub name: Option<&'a str>,
255    /// Optional relationship description.
256    pub description: Option<&'a str>,
257    /// Non-empty unique `IfcDefinitionSelect` targets.
258    pub related_objects: &'a [EntityId],
259    /// Existing or earlier-staged approval.
260    pub relating_approval: EntityId,
261}
262
263impl<'a> ApprovalAssociationDraft<'a> {
264    /// Starts a draft with its required fields; the rest are unset.
265    #[must_use]
266    pub fn new(
267        global_id: &'a str,
268        related_objects: &'a [EntityId],
269        relating_approval: EntityId,
270    ) -> Self {
271        Self {
272            global_id,
273            name: None,
274            description: None,
275            related_objects,
276            relating_approval,
277        }
278    }
279
280    /// Sets [`Self::name`]: Optional relationship name.
281    #[must_use]
282    pub fn name(mut self, value: &'a str) -> Self {
283        self.name = Some(value);
284        self
285    }
286
287    /// Sets [`Self::description`]: Optional relationship description.
288    #[must_use]
289    pub fn description(mut self, value: &'a str) -> Self {
290        self.description = Some(value);
291        self
292    }
293}
294
295/// Validate and stage one approval in the model's declared release.
296///
297/// # Release
298///
299/// IFC4 and IFC4X3 declare nine attributes and require at least one of
300/// `Identifier` and `Name`. IFC2X3 declares seven and requires `Identifier`,
301/// `Name` and `ApprovalDateTime` (the IFC4 `TimeOfApproval`) as an
302/// `IfcDateTimeSelect` record; it declares no `Status`, `Level`,
303/// `Qualifier`, `RequestingApproval` or `GivingApproval` under those names.
304///
305/// # Errors
306///
307/// Neither identifier nor name; an actor that is not an `IfcActorSelect`; a
308/// date record that is not a date record of the release; a header binding
309/// no single verified release (`MultipleSchemas`, `UnsupportedSchema`); a
310/// value the release does not declare (`AuthoringNotInSchema`) or cannot
311/// hold (`AuthoringValueType`: text where IFC2X3 declares a record, a
312/// record where IFC4 declares text); and a required value left unset
313/// (`AuthoringRequired`). Nothing is staged on an error.
314pub fn create_approval(
315    tx: &mut Transaction,
316    model: &Model,
317    draft: ApprovalDraft<'_>,
318) -> ApprovalResult<EntityId> {
319    let layout = bind(model)?;
320    if draft.identifier.is_none() && draft.name.is_none() {
321        return Err(ApprovalError::AuthoringInvalid {
322            entity: APPROVAL,
323            attribute: "WR",
324            value: "Identifier and Name are both absent".into(),
325        });
326    }
327    for target in [draft.requesting_approval, draft.giving_approval]
328        .into_iter()
329        .flatten()
330    {
331        validate_target_in(layout.schema(), tx, model, target, "IfcActorSelect")?;
332    }
333    let time = match draft.time_of_approval {
334        None => Value::Null,
335        Some(DateTimeInput::Text(text)) => Value::Text(Arc::from(text)),
336        Some(DateTimeInput::Record(target)) => {
337            if let Some((_, declared)) = layout.declared(APPROVAL, "TimeOfApproval") {
338                if layout.admits_entity(&declared.type_name, 8) {
339                    validate_target_in(
340                        layout.schema(),
341                        tx,
342                        model,
343                        target,
344                        declared.type_name.as_str(),
345                    )?;
346                }
347            }
348            Value::Ref(target)
349        }
350    };
351    let record = layout.named_record(
352        APPROVAL,
353        vec![
354            ("Identifier", optional_text(draft.identifier)),
355            ("Name", optional_text(draft.name)),
356            ("Description", optional_text(draft.description)),
357            ("TimeOfApproval", time),
358            ("Status", optional_text(draft.status)),
359            ("Level", optional_text(draft.level)),
360            ("Qualifier", optional_text(draft.qualifier)),
361            (
362                "RequestingApproval",
363                optional_ref(draft.requesting_approval),
364            ),
365            ("GivingApproval", optional_ref(draft.giving_approval)),
366        ],
367    )?;
368    Ok(tx.create(record))
369}
370
371/// Validate and stage one approval-to-approval relationship in the model's
372/// declared release.
373///
374/// IFC2X3 declares a single `RelatedApproval` and a required `Name`; IFC4
375/// and IFC4X3 a set of `RelatedApprovals` and an optional `Name`.
376///
377/// # Errors
378///
379/// An empty, duplicated or self-referencing set; a target that is not an
380/// `IfcApproval`; a header binding no single verified release; in IFC2X3
381/// more than one related approval (`AuthoringValueType`) or no name
382/// (`AuthoringRequired`). Nothing is staged on an error.
383pub fn relate_approvals(
384    tx: &mut Transaction,
385    model: &Model,
386    draft: ApprovalRelationshipDraft<'_>,
387) -> ApprovalResult<EntityId> {
388    let layout = bind(model)?;
389    layout.require_entity(APPROVAL_REL)?;
390    validate_target_in(
391        layout.schema(),
392        tx,
393        model,
394        draft.relating_approval,
395        APPROVAL,
396    )?;
397    validate_set(
398        layout.schema(),
399        tx,
400        model,
401        APPROVAL_REL,
402        "RelatedApprovals",
403        draft.related_approvals,
404        APPROVAL,
405        Some(draft.relating_approval),
406    )?;
407    let single = layout
408        .declared(APPROVAL_REL, "RelatedApprovals")
409        .is_some_and(|(_, declared)| !declared.aggregate);
410    let related = match (single, draft.related_approvals) {
411        (false, related) => refs(related),
412        (true, [one]) => Value::Ref(*one),
413        (true, _) => {
414            return Err(ApprovalError::AuthoringValueType {
415                entity: APPROVAL_REL,
416                attribute: "RelatedApprovals",
417                declared: "IfcApproval",
418                schema: layout.version(),
419            })
420        }
421    };
422    let record = layout.named_record(
423        APPROVAL_REL,
424        vec![
425            ("Name", optional_text(draft.name)),
426            ("Description", optional_text(draft.description)),
427            ("RelatingApproval", Value::Ref(draft.relating_approval)),
428            ("RelatedApprovals", related),
429        ],
430    )?;
431    Ok(tx.create(record))
432}
433
434/// Validate and stage one approval-to-resource relationship in the model's
435/// declared release.
436///
437/// # Errors
438///
439/// An empty or duplicated set; a relating target that is not an
440/// `IfcApproval` or a resource outside `IfcResourceObjectSelect`; a header
441/// binding no single verified release; and an IFC2X3 model, which declares
442/// no `IfcResourceApprovalRelationship` (`EntityNotInSchema`). Nothing is
443/// staged on an error.
444pub fn relate_resource_approval(
445    tx: &mut Transaction,
446    model: &Model,
447    draft: ResourceApprovalDraft<'_>,
448) -> ApprovalResult<EntityId> {
449    let layout = bind(model)?;
450    layout.require_entity(RESOURCE_REL)?;
451    validate_target_in(
452        layout.schema(),
453        tx,
454        model,
455        draft.relating_approval,
456        APPROVAL,
457    )?;
458    validate_set(
459        layout.schema(),
460        tx,
461        model,
462        RESOURCE_REL,
463        "RelatedResourceObjects",
464        draft.related_resources,
465        "IfcResourceObjectSelect",
466        None,
467    )?;
468    let record = layout.named_record(
469        RESOURCE_REL,
470        vec![
471            ("Name", optional_text(draft.name)),
472            ("Description", optional_text(draft.description)),
473            ("RelatedResourceObjects", refs(draft.related_resources)),
474            ("RelatingApproval", Value::Ref(draft.relating_approval)),
475        ],
476    )?;
477    Ok(tx.create(record))
478}
479
480/// Validate and stage one rooted approval association.
481///
482/// # Release
483///
484/// Bound to the model's declared release (#202): the record is laid out by
485/// attribute name from that release's table, and its references are checked
486/// against it (`RelatedObjects` is `IfcDefinitionSelect` in IFC4 and IFC4X3,
487/// `IfcRoot` restricted by WR21 in IFC2X3). `OwnerHistory` is left `$`,
488/// which IFC4 and IFC4X3 allow and IFC2X3 does not, so an IFC2X3 model is
489/// refused with [`ApprovalError::AuthoringRequired`]. Use
490/// [`associate_approval_with_owner_history`] there.
491///
492/// # Errors
493///
494/// A malformed GlobalId, a relating approval that is not an `IfcApproval`,
495/// an empty, duplicated or out-of-type `RelatedObjects`; a model that binds
496/// no single known release ([`ApprovalError::MultipleSchemas`],
497/// [`ApprovalError::UnsupportedSchema`]), and an IFC2X3 model. Nothing is
498/// staged on an error.
499pub fn associate_approval(
500    tx: &mut Transaction,
501    model: &Model,
502    draft: ApprovalAssociationDraft<'_>,
503) -> ApprovalResult<EntityId> {
504    associate(tx, model, draft, None)
505}
506
507/// [`associate_approval`] with a caller-supplied `IfcOwnerHistory`, which
508/// IFC2X3 requires on every `IfcRoot`.
509///
510/// `owner_history` must be in the model or staged earlier on `tx`, and must
511/// be an `IfcOwnerHistory`; one is never invented here (build it with
512/// `ifc-author`). In IFC4 and IFC4X3 the reference fills the optional slot.
513///
514/// # Errors
515///
516/// Those of [`associate_approval`] except the IFC2X3 refusal, and
517/// [`ApprovalError::UnknownEntity`] for an `owner_history` that does not
518/// resolve or [`ApprovalError::AuthoringReferenceType`] for one that is not
519/// an `IfcOwnerHistory`. Nothing is staged on an error.
520pub fn associate_approval_with_owner_history(
521    tx: &mut Transaction,
522    model: &Model,
523    draft: ApprovalAssociationDraft<'_>,
524    owner_history: EntityId,
525) -> ApprovalResult<EntityId> {
526    associate(tx, model, draft, Some(owner_history))
527}
528
529/// Stage an `IfcRelAssociatesApproval`; `None` leaves `OwnerHistory` `$`.
530fn associate(
531    tx: &mut Transaction,
532    model: &Model,
533    draft: ApprovalAssociationDraft<'_>,
534    owner_history: Option<EntityId>,
535) -> ApprovalResult<EntityId> {
536    let layout = bind(model)?;
537    if Guid::parse(draft.global_id).is_none() {
538        return Err(ApprovalError::AuthoringInvalid {
539            entity: ASSIGNMENT,
540            attribute: "GlobalId",
541            value: draft.global_id.into(),
542        });
543    }
544    validate_target_in(
545        layout.schema(),
546        tx,
547        model,
548        draft.relating_approval,
549        APPROVAL,
550    )?;
551    if draft.related_objects.is_empty() {
552        return Err(ApprovalError::AuthoringInvalid {
553            entity: ASSIGNMENT,
554            attribute: "RelatedObjects",
555            value: "empty SET [1:?]".into(),
556        });
557    }
558    let mut seen = HashSet::new();
559    for &target in draft.related_objects {
560        if !seen.insert(target) {
561            return Err(ApprovalError::AuthoringInvalid {
562                entity: ASSIGNMENT,
563                attribute: "RelatedObjects",
564                value: format!("duplicate {target}"),
565            });
566        }
567        let actual =
568            final_type(tx, model, target).ok_or(ApprovalError::UnknownEntity { id: target })?;
569        if !layout.is_definition(actual) {
570            return Err(ApprovalError::AuthoringReferenceType {
571                target,
572                expected: "IfcDefinitionSelect",
573                actual: actual.into(),
574            });
575        }
576    }
577    if let Some(owner_history) = owner_history {
578        require_owner_history(tx, model, owner_history)?;
579    }
580    let record = layout.named_record(
581        ASSIGNMENT,
582        vec![
583            ("GlobalId", text(draft.global_id)),
584            ("OwnerHistory", optional_ref(owner_history)),
585            ("Name", optional_text(draft.name)),
586            ("Description", optional_text(draft.description)),
587            ("RelatedObjects", refs(draft.related_objects)),
588            ("RelatingApproval", Value::Ref(draft.relating_approval)),
589        ],
590    )?;
591    Ok(tx.create(record))
592}
593
594#[allow(clippy::too_many_arguments)]
595fn validate_set(
596    schema: &Schema,
597    tx: &Transaction,
598    model: &Model,
599    kind: &'static str,
600    attribute: &'static str,
601    targets: &[EntityId],
602    expected: &'static str,
603    disallow: Option<EntityId>,
604) -> ApprovalResult<()> {
605    if targets.is_empty() {
606        return Err(ApprovalError::AuthoringInvalid {
607            entity: kind,
608            attribute,
609            value: "empty SET [1:?]".into(),
610        });
611    }
612    let mut seen = HashSet::new();
613    for &target in targets {
614        if !seen.insert(target) {
615            return Err(ApprovalError::AuthoringInvalid {
616                entity: kind,
617                attribute,
618                value: format!("duplicate {target}"),
619            });
620        }
621        if Some(target) == disallow {
622            return Err(ApprovalError::AuthoringInvalid {
623                entity: kind,
624                attribute,
625                value: format!("self reference {target}"),
626            });
627        }
628        validate_target_in(schema, tx, model, target, expected)?;
629    }
630    Ok(())
631}
632
633/// Fail unless `target` resolves, in the model or staged on `tx`, to a type
634/// `schema` accepts as `expected`.
635fn validate_target_in(
636    schema: &Schema,
637    tx: &Transaction,
638    model: &Model,
639    target: EntityId,
640    expected: &'static str,
641) -> ApprovalResult<()> {
642    let actual =
643        final_type(tx, model, target).ok_or(ApprovalError::UnknownEntity { id: target })?;
644    if schema.accepts_type(expected, actual) {
645        Ok(())
646    } else {
647        Err(ApprovalError::AuthoringReferenceType {
648            target,
649            expected,
650            actual: actual.into(),
651        })
652    }
653}
654
655fn final_type<'a>(tx: &'a Transaction, model: &'a Model, id: EntityId) -> Option<&'a str> {
656    for edit in tx.edits().iter().rev() {
657        match edit {
658            Edit::Create {
659                id: edit_id,
660                entity,
661            } if *edit_id == id => return Some(&entity.type_name),
662            Edit::Remove { id: edit_id } if *edit_id == id => return None,
663            Edit::Retype {
664                id: edit_id,
665                type_name,
666            } if *edit_id == id => return Some(type_name),
667            _ => {}
668        }
669    }
670    model.get(id).map(|entity| entity.type_name.as_ref())
671}
672
673fn text(value: &str) -> Value {
674    Value::Text(Arc::from(value))
675}
676fn optional_text(value: Option<&str>) -> Value {
677    value.map_or(Value::Null, text)
678}
679fn optional_ref(value: Option<EntityId>) -> Value {
680    value.map_or(Value::Null, Value::Ref)
681}
682fn refs(values: &[EntityId]) -> Value {
683    Value::List(values.iter().copied().map(Value::Ref).collect())
684}