ifc_schedule/calendar/definition.rs
1//! `IfcWorkCalendar`, the working/exception times it declares, and their
2//! recurrence patterns and time periods.
3//!
4//! # Read by name in the declared release (#234)
5//!
6//! The readers bind the model's declared release like the task readers
7//! (#212) and find every attribute by name in its table. IFC4 ADD2 TC1 and
8//! IFC4X3 ADD2 lay the records out alike, except that IFC4X3 names
9//! `IfcWorkTime.Start` and `Finish` `StartDate` and `FinishDate`. IFC2X3 TC1
10//! declares none of these entities, so an IFC2X3 model has no calendars.
11//! IFC4X1, IFC4X2 and a header with several schemas are refused.
12//!
13//! # Slots, verified against IFC4 EXPRESS
14//!
15//! The slot modules below are the IFC4/IFC4X3 positions the modelless
16//! writers lay records out with; the readers never go through them.
17//!
18//! `IfcWorkCalendar` is an `IfcControl`, so the first six slots are inherited:
19//!
20//! ```text
21//! 0 GlobalId 1 OwnerHistory 2 Name
22//! 3 Description 4 ObjectType 5 Identification (IfcControl)
23//! 6 WorkingTimes 7 ExceptionTimes 8 PredefinedType
24//!
25//! IfcWorkTime (IfcSchedulingTime)
26//! 0 Name 1 DataOrigin 2 UserDefinedDataOrigin
27//! 3 RecurrencePattern 4 Start 5 Finish
28//!
29//! IfcRecurrencePattern
30//! 0 RecurrenceType 1 DayComponent 2 WeekdayComponent
31//! 3 MonthComponent 4 Position 5 Interval
32//! 6 Occurrences 7 TimePeriods
33//!
34//! IfcTimePeriod
35//! 0 StartTime 1 EndTime
36//! ```
37//!
38//! # Working times and exception times are both `IfcWorkTime`
39//!
40//! They differ only by which slot holds them: slot 6 declares when work
41//! happens, slot 7 declares when it does not. Same entity type, opposite
42//! meaning -- so a reader that collects "all the IfcWorkTimes" and treats them
43//! uniformly turns holidays into working days.
44
45use ifc_model::{Entity, EntityId, Model, Value};
46
47use crate::error::ScheduleReadError;
48use crate::release::ReadRelease;
49use crate::SchemaVersion;
50
51/// `IfcWorkCalendar` slots.
52pub mod slot {
53 /// `GlobalId` (from `IfcRoot`).
54 pub const GLOBAL_ID: usize = 0;
55 /// `Name` (from `IfcRoot`).
56 pub const NAME: usize = 2;
57 /// `Identification` (from `IfcControl`).
58 pub const IDENTIFICATION: usize = 5;
59 /// `WorkingTimes`: when work happens.
60 pub const WORKING_TIMES: usize = 6;
61 /// `ExceptionTimes`: when it does not.
62 pub const EXCEPTION_TIMES: usize = 7;
63 /// `PredefinedType`.
64 pub const PREDEFINED_TYPE: usize = 8;
65}
66
67/// `IfcWorkTime` slots.
68pub mod work_time_slot {
69 /// `Name`.
70 pub const NAME: usize = 0;
71 /// `RecurrencePattern`.
72 pub const RECURRENCE_PATTERN: usize = 3;
73 /// `Start`.
74 pub const START: usize = 4;
75 /// `Finish`.
76 pub const FINISH: usize = 5;
77}
78
79/// `IfcRecurrencePattern` slots.
80pub mod recurrence_slot {
81 /// `RecurrenceType`. Required by the schema.
82 pub const RECURRENCE_TYPE: usize = 0;
83 /// `DayComponent`.
84 pub const DAY_COMPONENT: usize = 1;
85 /// `WeekdayComponent`.
86 pub const WEEKDAY_COMPONENT: usize = 2;
87 /// `MonthComponent`.
88 pub const MONTH_COMPONENT: usize = 3;
89 /// `Position`, for `MONTHLY_BY_POSITION` and friends.
90 pub const POSITION: usize = 4;
91 /// `Interval`.
92 pub const INTERVAL: usize = 5;
93 /// `Occurrences`.
94 pub const OCCURRENCES: usize = 6;
95 /// `TimePeriods`, a list of `IfcTimePeriod` (#233).
96 pub const TIME_PERIODS: usize = 7;
97}
98
99/// `IfcTimePeriod` slots (IFC4 and IFC4X3; IFC2X3 has no `IfcTimePeriod`).
100pub mod time_period_slot {
101 /// `StartTime`, an `IfcTime`. Required by the schema.
102 pub const START_TIME: usize = 0;
103 /// `EndTime`, an `IfcTime`. Required by the schema.
104 pub const END_TIME: usize = 1;
105}
106
107/// Whether a period declares work or an exception to it.
108#[derive(Debug, Clone, Copy, PartialEq, Eq)]
109#[non_exhaustive]
110pub enum WorkTimeRole {
111 /// From `WorkingTimes`: work happens in this period.
112 Working,
113 /// From `ExceptionTimes`: work does not happen in this period.
114 Exception,
115}
116
117/// How a work period repeats.
118///
119/// `IfcRecurrenceTypeEnum`, verified against IFC4 EXPRESS.
120#[derive(Debug, Clone, Copy, PartialEq, Eq)]
121#[non_exhaustive]
122pub enum RecurrenceType {
123 /// `.DAILY.`
124 Daily,
125 /// `.WEEKLY.`
126 Weekly,
127 /// `.MONTHLY_BY_DAY_OF_MONTH.`
128 MonthlyByDayOfMonth,
129 /// `.MONTHLY_BY_POSITION.`
130 MonthlyByPosition,
131 /// `.BY_DAY_COUNT.`
132 ByDayCount,
133 /// `.BY_WEEKDAY_COUNT.`
134 ByWeekdayCount,
135 /// `.YEARLY_BY_DAY_OF_MONTH.`
136 YearlyByDayOfMonth,
137 /// `.YEARLY_BY_POSITION.`
138 YearlyByPosition,
139}
140
141impl RecurrenceType {
142 fn parse(token: &str) -> Option<Self> {
143 Some(match token {
144 "DAILY" => Self::Daily,
145 "WEEKLY" => Self::Weekly,
146 "MONTHLY_BY_DAY_OF_MONTH" => Self::MonthlyByDayOfMonth,
147 "MONTHLY_BY_POSITION" => Self::MonthlyByPosition,
148 "BY_DAY_COUNT" => Self::ByDayCount,
149 "BY_WEEKDAY_COUNT" => Self::ByWeekdayCount,
150 "YEARLY_BY_DAY_OF_MONTH" => Self::YearlyByDayOfMonth,
151 "YEARLY_BY_POSITION" => Self::YearlyByPosition,
152 _ => return None,
153 })
154 }
155}
156
157/// A recurrence pattern as authored.
158///
159/// Not expanded into concrete dates: expansion needs a calendar library and a
160/// bounded window, and an unbounded pattern (`Occurrences` absent) has no
161/// finite expansion at all. The stated shape is returned and expansion is left
162/// to a caller who can supply both.
163#[derive(Debug, Clone, PartialEq, Eq)]
164#[non_exhaustive]
165pub struct Recurrence {
166 /// The entity.
167 pub id: EntityId,
168 /// How it repeats.
169 pub recurrence_type: Option<RecurrenceType>,
170 /// `DayComponent`: days of the month it applies to, 1 through 31
171 /// (#233).
172 pub days: Vec<i64>,
173 /// Weekdays it applies to, 1 = Monday through 7 = Sunday.
174 pub weekdays: Vec<i64>,
175 /// `MonthComponent`: months it applies to, 1 = January through
176 /// 12 = December (#233).
177 pub months: Vec<i64>,
178 /// The ordinal position within the period, for positional patterns.
179 ///
180 /// `MONTHLY_BY_POSITION` uses it as "the 2nd Tuesday"; a negative value
181 /// counts from the end of the period.
182 pub position: Option<i64>,
183 /// The interval between occurrences.
184 pub interval: Option<i64>,
185 /// How many times it repeats, if bounded.
186 pub occurrences: Option<i64>,
187 /// `TimePeriods`: the times of day each occurrence spans, in authored
188 /// order (#233). A reference that is not an `IfcTimePeriod` is not
189 /// listed.
190 pub time_periods: Vec<TimePeriod>,
191}
192
193/// An `IfcTimePeriod`: a start and end time of day, as authored (#233).
194///
195/// Both are `IfcTime` strings and are not parsed, for the same reason
196/// dates are not: interpreting them is calendar arithmetic this crate
197/// leaves to the caller.
198#[derive(Debug, Clone, PartialEq, Eq)]
199#[non_exhaustive]
200pub struct TimePeriod {
201 /// The `IfcTimePeriod` entity.
202 pub id: EntityId,
203 /// `StartTime`, as authored.
204 pub start_time: Option<String>,
205 /// `EndTime`, as authored.
206 pub end_time: Option<String>,
207}
208
209impl Recurrence {
210 /// Whether the pattern states a finite number of occurrences.
211 ///
212 /// An unbounded pattern is legal and common ("every Monday, forever"), so
213 /// a caller expanding one must impose its own window.
214 #[must_use]
215 pub fn is_bounded(&self) -> bool {
216 self.occurrences.is_some()
217 }
218}
219
220/// One working or exception period.
221#[derive(Debug, Clone, PartialEq)]
222#[non_exhaustive]
223pub struct WorkTime {
224 /// The `IfcWorkTime` entity.
225 pub id: EntityId,
226 /// Whether this declares work or an exception.
227 pub role: WorkTimeRole,
228 /// The period name, as authored.
229 pub name: Option<String>,
230 /// `DataOrigin` (`IfcDataOriginEnum`), the token without its dots
231 /// (#234).
232 pub data_origin: Option<String>,
233 /// `UserDefinedDataOrigin`, as authored (#234).
234 pub user_defined_data_origin: Option<String>,
235 /// Start date, as authored: IFC4's `Start`, IFC4X3's `StartDate`.
236 pub start: Option<String>,
237 /// Finish date, as authored: IFC4's `Finish`, IFC4X3's `FinishDate`.
238 pub finish: Option<String>,
239 /// The recurrence pattern, if the period repeats.
240 pub recurrence: Option<Recurrence>,
241}
242
243const CALENDAR: &str = "IFCWORKCALENDAR";
244const WORK_TIME: &str = "IFCWORKTIME";
245const PATTERN: &str = "IFCRECURRENCEPATTERN";
246const PERIOD: &str = "IFCTIMEPERIOD";
247
248/// A borrowed view of an `IfcWorkCalendar`, read against one release.
249#[derive(Debug, Clone, Copy)]
250pub struct WorkCalendar<'m> {
251 id: EntityId,
252 entity: &'m Entity,
253 release: ReadRelease,
254}
255
256impl<'m> WorkCalendar<'m> {
257 /// The entity id in the file.
258 #[must_use]
259 pub fn id(&self) -> EntityId {
260 self.id
261 }
262
263 /// The release this calendar is read against.
264 #[must_use]
265 pub fn release(&self) -> SchemaVersion {
266 self.release.version()
267 }
268
269 fn text(&self, attribute: &'static str) -> Option<&'m str> {
270 self.release.text(CALENDAR, self.entity, attribute)
271 }
272
273 /// The `GlobalId` string.
274 #[must_use]
275 pub fn global_id(&self) -> Option<&'m str> {
276 self.text("GlobalId")
277 }
278
279 /// The calendar name.
280 #[must_use]
281 pub fn name(&self) -> Option<&'m str> {
282 self.text("Name")
283 }
284
285 /// The user-facing identification code.
286 #[must_use]
287 pub fn identification(&self) -> Option<&'m str> {
288 self.text("Identification")
289 }
290
291 /// The predefined type token, without its dots.
292 #[must_use]
293 pub fn predefined_type(&self) -> Option<&'m str> {
294 self.release.token(CALENDAR, self.entity, "PredefinedType")
295 }
296
297 /// Periods when work happens.
298 #[must_use]
299 pub fn working_times(&self, model: &Model) -> Vec<WorkTime> {
300 self.times(model, "WorkingTimes", WorkTimeRole::Working)
301 }
302
303 /// Periods when work does not happen, such as holidays.
304 #[must_use]
305 pub fn exception_times(&self, model: &Model) -> Vec<WorkTime> {
306 self.times(model, "ExceptionTimes", WorkTimeRole::Exception)
307 }
308
309 fn times(&self, model: &Model, attribute: &'static str, role: WorkTimeRole) -> Vec<WorkTime> {
310 let mut refs = Vec::new();
311 if let Some(v) = self.release.value(CALENDAR, self.entity, attribute) {
312 v.for_each_ref(&mut |id| refs.push(id));
313 }
314 refs.into_iter()
315 .filter_map(|id| read_work_time(self.release, model, id, role))
316 .collect()
317 }
318}
319
320fn read_work_time(
321 release: ReadRelease,
322 model: &Model,
323 id: EntityId,
324 role: WorkTimeRole,
325) -> Option<WorkTime> {
326 let entity = model.get(id)?;
327 if !release.is_a(&entity.type_name, WORK_TIME) {
328 return None;
329 }
330 let text = |attribute| {
331 release
332 .text(WORK_TIME, entity, attribute)
333 .map(str::to_string)
334 };
335 let recurrence = release
336 .reference(WORK_TIME, entity, "RecurrencePattern")
337 .and_then(|pattern| read_recurrence(release, model, pattern));
338 Some(WorkTime {
339 id,
340 role,
341 name: text("Name"),
342 data_origin: release
343 .token(WORK_TIME, entity, "DataOrigin")
344 .map(str::to_string),
345 user_defined_data_origin: text("UserDefinedDataOrigin"),
346 start: text("Start"),
347 finish: text("Finish"),
348 recurrence,
349 })
350}
351
352/// The `IfcRecurrencePattern` `id`, read by name in the model's declared
353/// release (#233, #234).
354///
355/// For patterns referenced from somewhere other than a work calendar, such
356/// as `IfcTaskTimeRecurring.Recurrence` (also reachable through
357/// [`TaskTime::recurrence`](crate::TaskTime::recurrence)). `Ok(None)` when
358/// `id` is absent or not an `IfcRecurrencePattern` of that release; IFC2X3
359/// declares none.
360///
361/// # Errors
362///
363/// [`ScheduleReadError::UnsupportedSchema`] or
364/// [`ScheduleReadError::MultipleSchemas`] for a header the readers cannot
365/// bind; a header with no schema reads as IFC4.
366pub fn recurrence_pattern(
367 model: &Model,
368 id: EntityId,
369) -> Result<Option<Recurrence>, ScheduleReadError> {
370 Ok(read_recurrence(ReadRelease::of(model)?, model, id))
371}
372
373pub(crate) fn read_recurrence(
374 release: ReadRelease,
375 model: &Model,
376 id: EntityId,
377) -> Option<Recurrence> {
378 let entity = model.get(id)?;
379 if !release.is_a(&entity.type_name, PATTERN) {
380 return None;
381 }
382 let mut time_periods = Vec::new();
383 if let Some(value) = release.value(PATTERN, entity, "TimePeriods") {
384 value.for_each_ref(&mut |period| {
385 if let Some(period) = read_time_period(release, model, period) {
386 time_periods.push(period);
387 }
388 });
389 }
390 let integer = |attribute| {
391 release
392 .value(PATTERN, entity, attribute)
393 .and_then(|v| v.unwrap_typed().as_i64())
394 };
395 let integers = |attribute| match release.value(PATTERN, entity, attribute) {
396 Some(Value::List(items)) => items
397 .iter()
398 .filter_map(|item| item.unwrap_typed().as_i64())
399 .collect(),
400 _ => Vec::new(),
401 };
402 Some(Recurrence {
403 id,
404 recurrence_type: release
405 .token(PATTERN, entity, "RecurrenceType")
406 .and_then(RecurrenceType::parse),
407 days: integers("DayComponent"),
408 weekdays: integers("WeekdayComponent"),
409 months: integers("MonthComponent"),
410 position: integer("Position"),
411 interval: integer("Interval"),
412 occurrences: integer("Occurrences"),
413 time_periods,
414 })
415}
416
417fn read_time_period(release: ReadRelease, model: &Model, id: EntityId) -> Option<TimePeriod> {
418 let entity = model.get(id)?;
419 if !release.is_a(&entity.type_name, PERIOD) {
420 return None;
421 }
422 let text = |attribute| release.text(PERIOD, entity, attribute).map(str::to_string);
423 Some(TimePeriod {
424 id,
425 start_time: text("StartTime"),
426 end_time: text("EndTime"),
427 })
428}
429
430/// Every work calendar in the model, in file order, read against the
431/// model's declared release (#234).
432///
433/// IFC2X3 declares no `IfcWorkCalendar`, so an IFC2X3 model has none.
434///
435/// # Errors
436///
437/// [`ScheduleReadError::UnsupportedSchema`] or
438/// [`ScheduleReadError::MultipleSchemas`] for a header the readers cannot
439/// bind; a header with no schema reads as IFC4.
440pub fn read_work_calendars(model: &Model) -> Result<Vec<WorkCalendar<'_>>, ScheduleReadError> {
441 Ok(calendars_in(model, ReadRelease::of(model)?))
442}
443
444/// Every work calendar in the model, in file order.
445///
446/// Reads against the model's declared release when the readers can bind
447/// it. A header they cannot bind (IFC4X1, IFC4X2, several schemas) is read
448/// as IFC4, as this function always did; [`read_work_calendars`] refuses it
449/// instead.
450#[deprecated(
451 note = "reads an unverified or multi-schema header as IFC4; use `read_work_calendars`, which refuses it (#234)"
452)]
453#[must_use]
454pub fn work_calendars(model: &Model) -> Vec<WorkCalendar<'_>> {
455 ReadRelease::of(model)
456 .or_else(|_| ReadRelease::of_version(SchemaVersion::Ifc4))
457 .map_or_else(|_| Vec::new(), |release| calendars_in(model, release))
458}
459
460fn calendars_in(model: &Model, release: ReadRelease) -> Vec<WorkCalendar<'_>> {
461 if !release.declares(CALENDAR) {
462 return Vec::new();
463 }
464 release
465 .instances_of(model, CALENDAR)
466 .into_iter()
467 .filter_map(|id| {
468 Some(WorkCalendar {
469 id,
470 entity: model.get(id)?,
471 release,
472 })
473 })
474 .collect()
475}