Skip to main content

ifc_schedule/authoring/
owned.rs

1//! The `IfcRoot` writers bound to the model's declared release, with a
2//! caller-supplied `IfcOwnerHistory` (#202).
3//!
4//! `IfcRoot.OwnerHistory` is required in IFC2X3 TC1 and `OPTIONAL` from IFC4
5//! on:
6//!
7//! ```text
8//! IFC2X3_TC1   OwnerHistory : IfcOwnerHistory;
9//! IFC4         OwnerHistory : OPTIONAL IfcOwnerHistory;
10//! IFC4X3_ADD2  OwnerHistory : OPTIONAL IfcOwnerHistory;
11//! ```
12//!
13//! Each writer here runs the draft rules of its plain counterpart, binds
14//! the release (`release.rs`), checks that `owner_history` is an
15//! `IfcOwnerHistory` in the model or staged on the transaction, and places
16//! every attribute by name from the release's table. In IFC4 and IFC4X3 the
17//! record is the plain writer's with the reference in the optional slot.
18//! One is never invented here: build it with `ifc-author`. This follows
19//! `ifc-material` (#77), `ifc-properties` (#191) and `ifc-control` (#198).
20//!
21//! What IFC2X3 TC1 cannot hold is refused, never dropped or approximated:
22//! it declares no `IfcEvent` and no `IfcWorkCalendar`, and its `IfcTask`
23//! has no `LongDescription`, `TaskTime` or `PredefinedType` and requires
24//! `TaskId`. Where IFC2X3 declares another form, the draft carries both
25//! (#214): its `IfcRelSequence.TimeLag` is a required `IfcTimeMeasure`
26//! ([`TimeLag::Seconds`]) rather than an `IfcLagTime`
27//! ([`TimeLag::LagTime`]), and its `IfcWorkControl` dates are
28//! `IfcDateTimeSelect` records ([`DateTimeValue`] record forms, staged here)
29//! rather than ISO 8601 text. A form the bound release does not declare is
30//! refused with `AuthoringValueType`.
31
32use ifc_model::{EntityId, Model, Transaction, Value};
33
34use super::datetime::{patch, DateTimeValue, PLACEHOLDERS};
35use super::procedure::{self, ProcedureDraft};
36use super::{
37    blank, checks, is_user_defined, optional_enum, optional_text, reference_list, EventDraft,
38    ScheduleAuthoringResult, TaskDraft, WorkControlDraft,
39};
40use crate::error::ScheduleAuthoringError;
41use crate::release::{bind, Release};
42use crate::schedule::WorkControlKind;
43use ifc_schema::SchemaVersion;
44
45/// Lay `values` out in `release`, check the owner history, and stage.
46fn stage(
47    tx: &mut Transaction,
48    model: &Model,
49    release: Release,
50    entity: &'static str,
51    values: Vec<(&'static str, Value)>,
52    owner_history: EntityId,
53) -> ScheduleAuthoringResult<EntityId> {
54    let mut named = vec![("OwnerHistory", Value::Ref(owner_history))];
55    named.extend(values);
56    let record = release.record(entity, named)?;
57    release.require_owner_history(tx, model, entity, owner_history)?;
58    Ok(tx.create(record))
59}
60
61/// `IfcRelSequence.TimeLag`, in the form the release declares.
62///
63/// ```text
64/// IFC2X3_TC1   TimeLag : IfcTimeMeasure;          (REAL, required)
65/// IFC4         TimeLag : OPTIONAL IfcLagTime;
66/// IFC4X3_ADD2  TimeLag : OPTIONAL IfcLagTime;
67/// ```
68#[derive(Debug, Clone, Copy, PartialEq)]
69#[non_exhaustive]
70pub enum TimeLag {
71    /// IFC4 and IFC4X3: an `IfcLagTime` reference, as staged by
72    /// [`create_lag_time`](super::create_lag_time).
73    LagTime(EntityId),
74    /// IFC2X3: an `IfcTimeMeasure`, in seconds.
75    Seconds(f64),
76}
77
78impl TimeLag {
79    fn value(self) -> Value {
80        match self {
81            Self::LagTime(id) => Value::Ref(id),
82            Self::Seconds(seconds) => Value::Real(seconds),
83        }
84    }
85}
86
87fn refs(ids: &[EntityId]) -> Value {
88    Value::List(ids.iter().copied().map(Value::Ref).collect())
89}
90
91/// [`create_task`](super::create_task) in the model's declared release, with
92/// a caller-supplied `IfcOwnerHistory`, which IFC2X3 requires.
93///
94/// In IFC2X3 `identification` is written as `IfcTask.TaskId`, which that
95/// release requires.
96///
97/// # Errors
98///
99/// Those of [`create_task`](super::create_task), and:
100/// [`ScheduleAuthoringError::MultipleSchemas`] or
101/// [`ScheduleAuthoringError::UnsupportedSchema`] when the model binds no
102/// single known release; `AuthoringNotInSchema`, `AuthoringValueType` or
103/// `AuthoringRequired` for a value the release does not declare, cannot
104/// hold, or requires (IFC2X3: `long_description`, `task_time`,
105/// `predefined_type`, a missing `identification`);
106/// [`ScheduleAuthoringError::MissingReference`] when `owner_history` is
107/// neither in the model nor staged; and
108/// [`ScheduleAuthoringError::WrongReferenceType`] when it is not an
109/// `IfcOwnerHistory`. Nothing is staged on an error.
110pub fn create_task_with_owner_history(
111    tx: &mut Transaction,
112    model: &Model,
113    draft: TaskDraft<'_>,
114    owner_history: EntityId,
115) -> ScheduleAuthoringResult<EntityId> {
116    let release = bind(model)?;
117    checks::task(&draft)?;
118    let values = vec![
119        ("GlobalId", Value::Text(draft.global_id.into())),
120        ("Name", optional_text(draft.name)),
121        ("Description", optional_text(draft.description)),
122        ("Identification", optional_text(draft.identification)),
123        ("LongDescription", optional_text(draft.long_description)),
124        ("Status", optional_text(draft.status)),
125        ("WorkMethod", optional_text(draft.work_method)),
126        ("IsMilestone", Value::Bool(draft.is_milestone)),
127        (
128            "Priority",
129            draft.priority.map_or(Value::Null, Value::Integer),
130        ),
131        ("TaskTime", draft.task_time.map_or(Value::Null, Value::Ref)),
132        ("PredefinedType", optional_enum(draft.predefined_type)),
133    ];
134    stage(tx, model, release, "IFCTASK", values, owner_history)
135}
136
137/// [`create_sequence`](super::create_sequence) in the model's declared
138/// release, with a caller-supplied `IfcOwnerHistory`.
139///
140/// IFC2X3 requires `TimeLag` as an `IfcTimeMeasure` ([`TimeLag::Seconds`])
141/// and `SequenceType`; IFC4 and IFC4X3 take an `IfcLagTime`
142/// ([`TimeLag::LagTime`]). The other form is refused with
143/// `AuthoringValueType`, and a missing required one with
144/// `AuthoringRequired`. IFC2X3's `IfcSequenceEnum` has no `USERDEFINED`.
145///
146/// # Errors
147///
148/// Those of [`create_sequence`](super::create_sequence), a non-finite
149/// [`TimeLag::Seconds`] (`InvalidValue`), and the release, value and
150/// owner-history refusals of [`create_task_with_owner_history`]. Nothing is
151/// staged on an error.
152#[allow(clippy::too_many_arguments)]
153pub fn create_sequence_with_owner_history(
154    tx: &mut Transaction,
155    model: &Model,
156    global_id: &str,
157    predecessor: EntityId,
158    successor: EntityId,
159    sequence_type: Option<&str>,
160    time_lag: Option<TimeLag>,
161    owner_history: EntityId,
162) -> ScheduleAuthoringResult<EntityId> {
163    let release = bind(model)?;
164    checks::sequence(global_id, predecessor, successor)?;
165    checks::time_lag(time_lag)?;
166    let values = vec![
167        ("GlobalId", Value::Text(global_id.into())),
168        ("RelatingProcess", Value::Ref(predecessor)),
169        ("RelatedProcess", Value::Ref(successor)),
170        ("TimeLag", time_lag.map_or(Value::Null, TimeLag::value)),
171        ("SequenceType", optional_enum(sequence_type)),
172    ];
173    stage(tx, model, release, "IFCRELSEQUENCE", values, owner_history)
174}
175
176/// [`create_work_control`](super::create_work_control) in the model's
177/// declared release, with a caller-supplied `IfcOwnerHistory`.
178///
179/// IFC2X3 declares `CreationDate`, `StartTime` and `FinishTime` as
180/// `IfcDateTimeSelect`: give them as [`DateTimeValue::Date`],
181/// [`DateTimeValue::Time`] or [`DateTimeValue::DateAndTime`], and the
182/// `IfcCalendarDate`, `IfcLocalTime` and `IfcDateAndTime` records are staged
183/// here and referenced (#214). IFC4 and IFC4X3 declare `IfcDateTime` text
184/// ([`DateTimeValue::Text`]). The other form is refused with
185/// `AuthoringValueType`. In IFC2X3 `identification` is written as the
186/// required `Identifier`.
187///
188/// # Errors
189///
190/// Those of [`create_work_control`](super::create_work_control) except the
191/// refusal of record forms, a record form the schema's rules refuse
192/// (`InvalidValue`: a month outside 1..=12, a day the month does not have,
193/// an hour, minute or second out of range, a second without a minute), and
194/// the release, value and owner-history refusals of
195/// [`create_task_with_owner_history`]. Nothing is staged on an error: the
196/// date records are staged only once the work control itself is accepted.
197pub fn create_work_control_with_owner_history(
198    tx: &mut Transaction,
199    model: &Model,
200    kind: WorkControlKind,
201    draft: WorkControlDraft<'_>,
202    owner_history: EntityId,
203) -> ScheduleAuthoringResult<EntityId> {
204    let release = bind(model)?;
205    let type_name = checks::work_control(kind, &draft)?;
206    let dates = [
207        Some(draft.creation_date),
208        Some(draft.start_time),
209        draft.finish_time,
210    ];
211    let provisional = |slot: usize| {
212        dates[slot].map_or(Value::Null, |date: DateTimeValue<'_>| {
213            date.provisional(PLACEHOLDERS[slot])
214        })
215    };
216    let values = vec![
217        ("OwnerHistory", Value::Ref(owner_history)),
218        ("GlobalId", Value::Text(draft.global_id.into())),
219        ("Name", optional_text(draft.name)),
220        ("Description", optional_text(draft.description)),
221        ("Identification", optional_text(draft.identification)),
222        ("CreationDate", provisional(0)),
223        ("Purpose", optional_text(draft.purpose)),
224        ("Duration", optional_text(draft.duration)),
225        ("TotalFloat", optional_text(draft.total_float)),
226        ("StartTime", provisional(1)),
227        ("FinishTime", provisional(2)),
228        ("PredefinedType", optional_enum(draft.predefined_type)),
229    ];
230    // Every refusal before the first edit: the record with placeholders,
231    // then the owner history; only then the date records.
232    let mut record = release.record(type_name, values)?;
233    release.require_owner_history(tx, model, type_name, owner_history)?;
234    patch(tx, &mut record, &dates);
235    Ok(tx.create(record))
236}
237
238/// [`assign_tasks_to_control`](super::assign_tasks_to_control) in the
239/// model's declared release, with a caller-supplied `IfcOwnerHistory`.
240///
241/// `RelatedObjectsType` is left unset, as the plain writer leaves it.
242///
243/// # Errors
244///
245/// Those of [`assign_tasks_to_control`](super::assign_tasks_to_control),
246/// and the release and owner-history refusals of
247/// [`create_task_with_owner_history`]. Nothing is staged on an error.
248pub fn assign_tasks_to_control_with_owner_history(
249    tx: &mut Transaction,
250    model: &Model,
251    global_id: &str,
252    control: EntityId,
253    tasks: &[EntityId],
254    owner_history: EntityId,
255) -> ScheduleAuthoringResult<EntityId> {
256    let release = bind(model)?;
257    checks::assignment(global_id, tasks)?;
258    let values = vec![
259        ("GlobalId", Value::Text(global_id.into())),
260        ("RelatedObjects", refs(tasks)),
261        ("RelatingControl", Value::Ref(control)),
262    ];
263    stage(
264        tx,
265        model,
266        release,
267        "IFCRELASSIGNSTOCONTROL",
268        values,
269        owner_history,
270    )
271}
272
273/// [`nest_tasks`](super::nest_tasks) in the model's declared release, with a
274/// caller-supplied `IfcOwnerHistory`.
275///
276/// # Errors
277///
278/// Those of [`nest_tasks`](super::nest_tasks), and the release and
279/// owner-history refusals of [`create_task_with_owner_history`]. Nothing is
280/// staged on an error.
281pub fn nest_tasks_with_owner_history(
282    tx: &mut Transaction,
283    model: &Model,
284    global_id: &str,
285    parent: EntityId,
286    children: &[EntityId],
287    owner_history: EntityId,
288) -> ScheduleAuthoringResult<EntityId> {
289    let release = bind(model)?;
290    checks::nesting(global_id, parent, children)?;
291    let values = vec![
292        ("GlobalId", Value::Text(global_id.into())),
293        ("RelatingObject", Value::Ref(parent)),
294        ("RelatedObjects", refs(children)),
295    ];
296    stage(tx, model, release, "IFCRELNESTS", values, owner_history)
297}
298
299/// [`create_work_calendar`](super::create_work_calendar) in the model's
300/// declared release, with a caller-supplied `IfcOwnerHistory`.
301///
302/// IFC2X3 declares no `IfcWorkCalendar` and is refused with
303/// `EntityNotInSchema`.
304///
305/// # Errors
306///
307/// Those of [`create_work_calendar`](super::create_work_calendar), and the
308/// release, entity and owner-history refusals of
309/// [`create_task_with_owner_history`]. Nothing is staged on an error.
310#[allow(clippy::too_many_arguments)]
311pub fn create_work_calendar_with_owner_history(
312    tx: &mut Transaction,
313    model: &Model,
314    global_id: &str,
315    name: Option<&str>,
316    working_times: &[EntityId],
317    exception_times: &[EntityId],
318    predefined_type: Option<&str>,
319    owner_history: EntityId,
320) -> ScheduleAuthoringResult<EntityId> {
321    let release = bind(model)?;
322    checks::calendar(global_id, working_times, exception_times)?;
323    let values = vec![
324        ("GlobalId", Value::Text(global_id.into())),
325        ("Name", optional_text(name)),
326        ("WorkingTimes", reference_list(working_times)),
327        ("ExceptionTimes", reference_list(exception_times)),
328        ("PredefinedType", optional_enum(predefined_type)),
329    ];
330    stage(tx, model, release, "IFCWORKCALENDAR", values, owner_history)
331}
332
333/// [`create_event`](super::create_event) in the model's declared release,
334/// with a caller-supplied `IfcOwnerHistory`.
335///
336/// IFC2X3 declares no `IfcEvent` and is refused with `EntityNotInSchema`.
337///
338/// # Errors
339///
340/// Those of [`create_event`](super::create_event), and the release, entity
341/// and owner-history refusals of [`create_task_with_owner_history`].
342/// Nothing is staged on an error.
343pub fn create_event_with_owner_history(
344    tx: &mut Transaction,
345    model: &Model,
346    draft: EventDraft<'_>,
347    owner_history: EntityId,
348) -> ScheduleAuthoringResult<EntityId> {
349    let release = bind(model)?;
350    checks::event(&draft)?;
351    let values = vec![
352        ("GlobalId", Value::Text(draft.global_id.into())),
353        ("Name", optional_text(draft.name)),
354        ("ObjectType", optional_text(draft.object_type)),
355        ("Identification", optional_text(draft.identification)),
356        ("LongDescription", optional_text(draft.long_description)),
357        ("PredefinedType", optional_enum(draft.predefined_type)),
358        ("EventTriggerType", optional_enum(draft.trigger_type)),
359        (
360            "UserDefinedEventTriggerType",
361            optional_text(draft.user_defined_trigger_type),
362        ),
363        (
364            "EventOccurenceTime",
365            draft.occurence_time.map_or(Value::Null, Value::Ref),
366        ),
367    ];
368    stage(tx, model, release, "IFCEVENT", values, owner_history)
369}
370
371/// [`create_procedure`](super::create_procedure) in the model's declared
372/// release, with a caller-supplied `IfcOwnerHistory`.
373///
374/// In IFC2X3 `identification` is written as `ProcedureID` and
375/// `predefined_type` as `ProcedureType`, both required there, and
376/// `user_defined_procedure_type` as `UserDefinedProcedureType`, which
377/// `IfcProcedure.WR4` requires for `USERDEFINED` (#214). IFC4 and IFC4X3
378/// declare no `UserDefinedProcedureType` and refuse a value for it with
379/// `AuthoringNotInSchema`.
380///
381/// # Errors
382///
383/// Those of [`create_procedure`](super::create_procedure) except its
384/// refusal of `user_defined_procedure_type`, an IFC2X3 `USERDEFINED`
385/// without a non-blank `user_defined_procedure_type` (`InvalidValue`, WR4),
386/// and the release, value and owner-history refusals of
387/// [`create_task_with_owner_history`]. Nothing is staged on an error.
388pub fn create_procedure_with_owner_history(
389    tx: &mut Transaction,
390    model: &Model,
391    draft: ProcedureDraft<'_>,
392    owner_history: EntityId,
393) -> ScheduleAuthoringResult<EntityId> {
394    let release = bind(model)?;
395    procedure::check(&draft)?;
396    if release.version() == SchemaVersion::Ifc2x3
397        && is_user_defined(draft.predefined_type)
398        && blank(draft.user_defined_procedure_type)
399    {
400        return Err(ScheduleAuthoringError::InvalidValue {
401            entity: procedure::ENTITY,
402            attribute: "UserDefinedProcedureType",
403            expected: "a label when ProcedureType is USERDEFINED (IFC2X3 WR4)",
404        });
405    }
406    let values = vec![
407        ("GlobalId", Value::Text(draft.global_id.into())),
408        ("Name", optional_text(draft.name)),
409        ("Description", optional_text(draft.description)),
410        ("ObjectType", optional_text(draft.object_type)),
411        ("Identification", optional_text(draft.identification)),
412        ("LongDescription", optional_text(draft.long_description)),
413        ("PredefinedType", optional_enum(draft.predefined_type)),
414        (
415            "UserDefinedProcedureType",
416            optional_text(draft.user_defined_procedure_type),
417        ),
418    ];
419    stage(tx, model, release, procedure::ENTITY, values, owner_history)
420}