Skip to main content

ifc_schedule/authoring/
timing.rs

1//! Authoring task times, recurring task times, and time periods.
2//!
3//! Split from the module root: these four writers share the
4//! `IfcTaskTime` slot table, and the root was over the monolith limit.
5
6use ifc_model::{Edit, Entity, EntityId, Model, Transaction, Value};
7
8use super::{optional_text, ScheduleAuthoringResult};
9use crate::error::ScheduleAuthoringError;
10use crate::task::definition::time_slot;
11
12/// Authored fields for `IfcTaskTime`.
13///
14/// Durations are ISO 8601 duration strings and timestamps ISO 8601
15/// datetimes, written exactly as given. Parsing them here would mean this
16/// crate owning calendar arithmetic it deliberately does not.
17#[derive(Debug, Clone, Copy, Default)]
18#[non_exhaustive]
19pub struct TaskTimeDraft<'a> {
20    /// `IfcPhysicalQuantity`-style Name, slot 0.
21    pub name: Option<&'a str>,
22    /// `IfcTaskTime.DurationType`, `WORKTIME` or `ELAPSEDTIME`.
23    pub duration_type: Option<&'a str>,
24    /// `IfcTaskTime.ScheduleDuration`, an ISO 8601 duration.
25    pub schedule_duration: Option<&'a str>,
26    /// `IfcTaskTime.ScheduleStart`.
27    pub schedule_start: Option<&'a str>,
28    /// `IfcTaskTime.ScheduleFinish`.
29    pub schedule_finish: Option<&'a str>,
30    /// `IfcTaskTime.ActualStart`.
31    pub actual_start: Option<&'a str>,
32    /// `IfcTaskTime.ActualFinish`.
33    pub actual_finish: Option<&'a str>,
34    /// `IfcTaskTime.IsCritical`.
35    pub is_critical: Option<bool>,
36    /// `IfcTaskTime.Completion`, a percentage in `0..=100`.
37    pub completion: Option<f64>,
38}
39
40/// Build and validate the shared `IfcTaskTime` attribute vector.
41///
42/// `IfcTaskTimeRecurring` inherits every one of these slots and adds
43/// `Recurrence` at the end, so both writers share this body rather than
44/// duplicating nine slot assignments and two range checks.
45fn task_time_attributes(
46    entity: &'static str,
47    draft: TaskTimeDraft<'_>,
48) -> ScheduleAuthoringResult<Vec<Value>> {
49    if let Some(completion) = draft.completion {
50        if !completion.is_finite() || !(0.0..=100.0).contains(&completion) {
51            return Err(ScheduleAuthoringError::InvalidValue {
52                entity,
53                attribute: "Completion",
54                expected: "a percentage in 0..=100",
55            });
56        }
57    }
58    if let Some(kind) = draft.duration_type {
59        if !["WORKTIME", "ELAPSEDTIME", "NOTDEFINED"]
60            .iter()
61            .any(|known| known.eq_ignore_ascii_case(kind))
62        {
63            return Err(ScheduleAuthoringError::InvalidValue {
64                entity,
65                attribute: "DurationType",
66                expected: "WORKTIME, ELAPSEDTIME or NOTDEFINED",
67            });
68        }
69    }
70    let mut attributes = vec![Value::Null; time_slot::COMPLETION + 1];
71    attributes[0] = optional_text(draft.name);
72    attributes[time_slot::DURATION_TYPE] = draft
73        .duration_type
74        .map_or(Value::Null, |t| Value::Enum(t.into()));
75    attributes[time_slot::SCHEDULE_DURATION] = optional_text(draft.schedule_duration);
76    attributes[time_slot::SCHEDULE_START] = optional_text(draft.schedule_start);
77    attributes[time_slot::SCHEDULE_FINISH] = optional_text(draft.schedule_finish);
78    attributes[time_slot::ACTUAL_START] = optional_text(draft.actual_start);
79    attributes[time_slot::ACTUAL_FINISH] = optional_text(draft.actual_finish);
80    attributes[time_slot::IS_CRITICAL] = draft.is_critical.map_or(Value::Null, Value::Bool);
81    attributes[time_slot::COMPLETION] = draft.completion.map_or(Value::Null, Value::Real);
82    Ok(attributes)
83}
84
85/// Stage an `IfcTaskTime`.
86///
87/// # Errors
88///
89/// Refuses a completion outside `0..=100` and an unknown duration type.
90pub fn create_task_time(
91    tx: &mut Transaction,
92    draft: TaskTimeDraft<'_>,
93) -> ScheduleAuthoringResult<EntityId> {
94    let attributes = task_time_attributes("IFCTASKTIME", draft)?;
95    Ok(tx.create(Entity::new("IFCTASKTIME", attributes)))
96}
97
98/// Stage an `IfcTaskTimeRecurring`.
99///
100/// The recurring form is an `IfcTaskTime` plus a required
101/// `Recurrence` at slot 20. The pattern is what makes the task repeat,
102/// so it is a required argument rather than an optional draft field:
103/// a recurring time with no pattern recurs never.
104///
105/// Binds `model`'s declared release (#235): IFC2X3 declares no
106/// `IfcTaskTimeRecurring` and is refused with `EntityNotInSchema`; IFC4 and
107/// IFC4X3 lay the record out alike.
108///
109/// # Errors
110///
111/// `EntityNotInSchema` for a release without `IfcTaskTimeRecurring`,
112/// `MultipleSchemas` or `UnsupportedSchema` when the header binds no single
113/// known release, those of [`create_task_time`], and `InvalidValue` for a
114/// `recurrence` that is not an `IfcRecurrencePattern`. Nothing is staged
115/// on an error.
116pub fn create_task_time_recurring(
117    tx: &mut Transaction,
118    model: &Model,
119    draft: TaskTimeDraft<'_>,
120    recurrence: EntityId,
121) -> ScheduleAuthoringResult<EntityId> {
122    const ENTITY: &str = "IFCTASKTIMERECURRING";
123    const RECURRENCE_SLOT: usize = 20;
124    crate::release::bind(model)?.require_entity(ENTITY)?;
125    let pattern_is_valid = tx
126        .edits()
127        .iter()
128        .rev()
129        .find_map(|edit| match edit {
130            Edit::Create { id, entity } if *id == recurrence => {
131                Some(entity.type_name.as_ref().to_owned())
132            }
133            _ => None,
134        })
135        .or_else(|| {
136            model
137                .get(recurrence)
138                .map(|entity| entity.type_name.as_ref().to_owned())
139        })
140        .is_some_and(|name| name.eq_ignore_ascii_case("IFCRECURRENCEPATTERN"));
141    if !pattern_is_valid {
142        return Err(ScheduleAuthoringError::InvalidValue {
143            entity: ENTITY,
144            attribute: "Recurrence",
145            expected: "an IfcRecurrencePattern",
146        });
147    }
148    let mut attributes = task_time_attributes(ENTITY, draft)?;
149    attributes.resize(RECURRENCE_SLOT + 1, Value::Null);
150    attributes[RECURRENCE_SLOT] = Value::Ref(recurrence);
151    Ok(tx.create(Entity::new(ENTITY, attributes)))
152}
153
154/// Stage an `IfcTimePeriod`: a start and end time of day.
155///
156/// Place it in a pattern with [`RecurrenceDraft::time_periods`](super::RecurrenceDraft::time_periods).
157/// Takes no model, so it is for IFC4 and IFC4X3 only; [`create_time_period_in`]
158/// checks the model's release.
159///
160/// Both slots are `IfcTime`, a time of day rather than a timestamp,
161/// and both are required. The values are written as given for the
162/// same reason `IfcTaskTime` does not parse its durations: the codec
163/// round-trips text, and reinterpreting it here would lose whatever
164/// the authoring tool meant by it.
165///
166/// # Errors
167///
168/// Refuses a blank start or end.
169pub fn create_time_period(
170    tx: &mut Transaction,
171    start_time: &str,
172    end_time: &str,
173) -> ScheduleAuthoringResult<EntityId> {
174    const ENTITY: &str = "IFCTIMEPERIOD";
175    for (attribute, value) in [("StartTime", start_time), ("EndTime", end_time)] {
176        if value.trim().is_empty() {
177            return Err(ScheduleAuthoringError::InvalidValue {
178                entity: ENTITY,
179                attribute,
180                expected: "a non-empty ISO 8601 time",
181            });
182        }
183    }
184    Ok(tx.create(Entity::new(
185        ENTITY,
186        vec![Value::Text(start_time.into()), Value::Text(end_time.into())],
187    )))
188}
189
190/// [`create_time_period`] bound to `model`'s declared release (#233).
191///
192/// IFC4 and IFC4X3 stage exactly what [`create_time_period`] stages.
193/// IFC2X3 declares no `IfcTimePeriod` and is refused.
194///
195/// # Errors
196///
197/// `EntityNotInSchema` for a release without `IfcTimePeriod`,
198/// `MultipleSchemas` or `UnsupportedSchema` when the header binds no single
199/// known release, and those of [`create_time_period`]. Nothing is staged on
200/// an error.
201pub fn create_time_period_in(
202    tx: &mut Transaction,
203    model: &Model,
204    start_time: &str,
205    end_time: &str,
206) -> ScheduleAuthoringResult<EntityId> {
207    crate::release::bind(model)?.require_entity("IFCTIMEPERIOD")?;
208    create_time_period(tx, start_time, end_time)
209}