ifc-resource 0.3.0

Construction resources: labour, equipment, material, crew, subcontract.
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
//! Authoring roles and addresses.
//!
//! Both addresses carry a "say something" rule: `IfcPostalAddress.WR1`
//! and `IfcTelecomAddress.MinimumDataProvided` each require at least
//! one contact field. An address with every slot unset parses and
//! reaches nobody, so it is refused rather than written.
//!
//! None of these are `IfcRoot` subtypes: they have no GlobalId and are
//! referenced from the person, organisation or actor that owns them.

use ifc_model::{EntityId, Value};

use crate::author::editor::{build_entity, text, validate_enum, ResourceEditor};
use crate::error::{ResourceError, ResourceResult};

/// Draft for one `IfcActorRole`.
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub struct ActorRoleDraft<'a> {
    /// `Role`, an `IfcRoleEnum` token.
    pub role: &'a str,
    /// `UserDefinedRole`. Required when `role` is `USERDEFINED`.
    pub user_defined_role: Option<&'a str>,
    /// `Description`.
    pub description: Option<&'a str>,
}

impl<'a> ActorRoleDraft<'a> {
    /// Starts a draft with its required fields; the rest are unset.
    #[must_use]
    pub fn new(role: &'a str) -> Self {
        Self {
            role,
            user_defined_role: None,
            description: None,
        }
    }

    /// Sets [`Self::user_defined_role`]: `UserDefinedRole`. Required when `role` is `USERDEFINED`.
    #[must_use]
    pub fn user_defined_role(mut self, value: &'a str) -> Self {
        self.user_defined_role = Some(value);
        self
    }

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

/// Draft for one `IfcPostalAddress`.
#[derive(Debug, Clone, Copy, Default)]
#[non_exhaustive]
pub struct PostalAddressDraft<'a> {
    /// `Purpose`, an `IfcAddressTypeEnum` token.
    pub purpose: Option<&'a str>,
    /// `Description`.
    pub description: Option<&'a str>,
    /// `UserDefinedPurpose`. Required when `purpose` is `USERDEFINED`.
    pub user_defined_purpose: Option<&'a str>,
    /// `InternalLocation`: a room or desk within the building.
    pub internal_location: Option<&'a str>,
    /// `PostalBox`.
    pub postal_box: Option<&'a str>,
    /// `Town`.
    pub town: Option<&'a str>,
    /// `Region`.
    pub region: Option<&'a str>,
    /// `PostalCode`.
    pub postal_code: Option<&'a str>,
    /// `Country`.
    pub country: Option<&'a str>,
}

impl<'a> PostalAddressDraft<'a> {
    /// Starts a draft with every field unset.
    #[must_use]
    pub fn new() -> Self {
        Self {
            purpose: None,
            description: None,
            user_defined_purpose: None,
            internal_location: None,
            postal_box: None,
            town: None,
            region: None,
            postal_code: None,
            country: None,
        }
    }

    /// Sets [`Self::purpose`]: `Purpose`, an `IfcAddressTypeEnum` token.
    #[must_use]
    pub fn purpose(mut self, value: &'a str) -> Self {
        self.purpose = 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::user_defined_purpose`]: `UserDefinedPurpose`. Required when `purpose` is `USERDEFINED`.
    #[must_use]
    pub fn user_defined_purpose(mut self, value: &'a str) -> Self {
        self.user_defined_purpose = Some(value);
        self
    }

    /// Sets [`Self::internal_location`]: `InternalLocation`: a room or desk within the building.
    #[must_use]
    pub fn internal_location(mut self, value: &'a str) -> Self {
        self.internal_location = Some(value);
        self
    }

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

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

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

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

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

/// Draft for one `IfcTelecomAddress`.
#[derive(Debug, Clone, Copy, Default)]
#[non_exhaustive]
pub struct TelecomAddressDraft<'a> {
    /// `Purpose`, an `IfcAddressTypeEnum` token.
    pub purpose: Option<&'a str>,
    /// `Description`.
    pub description: Option<&'a str>,
    /// `UserDefinedPurpose`. Required when `purpose` is `USERDEFINED`.
    pub user_defined_purpose: Option<&'a str>,
    /// `PagerNumber`.
    pub pager_number: Option<&'a str>,
    /// `WWWHomePageURL`.
    pub www_home_page_url: Option<&'a str>,
}

impl<'a> TelecomAddressDraft<'a> {
    /// Starts a draft with every field unset.
    #[must_use]
    pub fn new() -> Self {
        Self {
            purpose: None,
            description: None,
            user_defined_purpose: None,
            pager_number: None,
            www_home_page_url: None,
        }
    }

    /// Sets [`Self::purpose`]: `Purpose`, an `IfcAddressTypeEnum` token.
    #[must_use]
    pub fn purpose(mut self, value: &'a str) -> Self {
        self.purpose = 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::user_defined_purpose`]: `UserDefinedPurpose`. Required when `purpose` is `USERDEFINED`.
    #[must_use]
    pub fn user_defined_purpose(mut self, value: &'a str) -> Self {
        self.user_defined_purpose = Some(value);
        self
    }

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

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

/// The `LIST [1:?]` attributes of an `IfcTelecomAddress`.
///
/// Each is optional as a whole but bounded `[1:?]` when present, so an
/// empty slice is written as absent rather than as an empty list.
#[derive(Debug, Clone, Copy, Default)]
pub struct TelecomLists<'a> {
    /// `TelephoneNumbers`.
    pub telephone: &'a [&'a str],
    /// `FacsimileNumbers`.
    pub facsimile: &'a [&'a str],
    /// `ElectronicMailAddresses`.
    pub email: &'a [&'a str],
    /// `MessagingIDs`.
    pub messaging: &'a [&'a str],
}

/// A `LIST [1:?]` written as absent when empty.
fn optional_list(values: &[&str]) -> Option<Value> {
    if values.is_empty() {
        return None;
    }
    Some(Value::List(
        values.iter().map(|v| Value::Text((*v).into())).collect(),
    ))
}

impl ResourceEditor<'_> {
    /// Stage an `IfcActorRole`.
    ///
    /// # Errors
    ///
    /// Refuses a token outside `IfcRoleEnum` and `USERDEFINED`
    /// without a `user_defined_role` (WR1).
    pub fn create_actor_role(&mut self, draft: ActorRoleDraft<'_>) -> ResourceResult<EntityId> {
        const ENTITY: &str = "IfcActorRole";
        validate_enum(self.schema, ENTITY, "Role", draft.role)?;
        if draft.role.eq_ignore_ascii_case("USERDEFINED")
            && draft
                .user_defined_role
                .is_none_or(|text| text.trim().is_empty())
        {
            return Err(ResourceError::SemanticViolation {
                entity: None,
                rule: "WR1",
            });
        }
        let entity = build_entity(
            self.schema,
            ENTITY,
            &[
                ("Role", Some(Value::Enum(draft.role.into()))),
                ("UserDefinedRole", draft.user_defined_role.map(text)),
                ("Description", draft.description.map(text)),
            ],
        )?;
        self.commit_create(entity)
    }

    /// Stage an `IfcPostalAddress`.
    ///
    /// `address_lines` is `LIST [1:?]` when present.
    ///
    /// # Errors
    ///
    /// Refuses a `purpose` outside `IfcAddressTypeEnum`, `USERDEFINED`
    /// without a `user_defined_purpose`, and an address with no
    /// locating field at all (WR1).
    pub fn create_postal_address(
        &mut self,
        draft: PostalAddressDraft<'_>,
        address_lines: &[&str],
    ) -> ResourceResult<EntityId> {
        const ENTITY: &str = "IfcPostalAddress";
        self.validate_address_purpose(ENTITY, draft.purpose, draft.user_defined_purpose)?;
        // WR1: an address that locates nothing reaches nobody.
        let locates = !address_lines.is_empty()
            || draft.internal_location.is_some()
            || draft.postal_box.is_some()
            || draft.postal_code.is_some()
            || draft.town.is_some()
            || draft.region.is_some()
            || draft.country.is_some();
        if !locates {
            return Err(ResourceError::SemanticViolation {
                entity: None,
                rule: "WR1",
            });
        }
        let entity = build_entity(
            self.schema,
            ENTITY,
            &[
                ("Purpose", draft.purpose.map(|p| Value::Enum(p.into()))),
                ("Description", draft.description.map(text)),
                ("UserDefinedPurpose", draft.user_defined_purpose.map(text)),
                ("InternalLocation", draft.internal_location.map(text)),
                ("AddressLines", optional_list(address_lines)),
                ("PostalBox", draft.postal_box.map(text)),
                ("Town", draft.town.map(text)),
                ("Region", draft.region.map(text)),
                ("PostalCode", draft.postal_code.map(text)),
                ("Country", draft.country.map(text)),
            ],
        )?;
        self.commit_create(entity)
    }

    /// Stage an `IfcTelecomAddress`.
    ///
    /// # Errors
    ///
    /// Refuses a `purpose` outside `IfcAddressTypeEnum`, `USERDEFINED`
    /// without a `user_defined_purpose`, and an address carrying no
    /// contact route at all (MinimumDataProvided).
    pub fn create_telecom_address(
        &mut self,
        draft: TelecomAddressDraft<'_>,
        lists: TelecomLists<'_>,
    ) -> ResourceResult<EntityId> {
        const ENTITY: &str = "IfcTelecomAddress";
        self.validate_address_purpose(ENTITY, draft.purpose, draft.user_defined_purpose)?;
        // MinimumDataProvided: at least one way to reach someone.
        let reachable = !lists.telephone.is_empty()
            || !lists.facsimile.is_empty()
            || !lists.email.is_empty()
            || !lists.messaging.is_empty()
            || draft.pager_number.is_some()
            || draft.www_home_page_url.is_some();
        if !reachable {
            return Err(ResourceError::SemanticViolation {
                entity: None,
                rule: "MinimumDataProvided",
            });
        }
        let entity = build_entity(
            self.schema,
            ENTITY,
            &[
                ("Purpose", draft.purpose.map(|p| Value::Enum(p.into()))),
                ("Description", draft.description.map(text)),
                ("UserDefinedPurpose", draft.user_defined_purpose.map(text)),
                ("TelephoneNumbers", optional_list(lists.telephone)),
                ("FacsimileNumbers", optional_list(lists.facsimile)),
                ("PagerNumber", draft.pager_number.map(text)),
                ("ElectronicMailAddresses", optional_list(lists.email)),
                ("WWWHomePageURL", draft.www_home_page_url.map(text)),
                ("MessagingIDs", optional_list(lists.messaging)),
            ],
        )?;
        self.commit_create(entity)
    }

    /// Both addresses share `Purpose` and its USERDEFINED rule.
    fn validate_address_purpose(
        &self,
        entity: &'static str,
        purpose: Option<&str>,
        user_defined: Option<&str>,
    ) -> ResourceResult<()> {
        let Some(token) = purpose else {
            return Ok(());
        };
        validate_enum(self.schema, entity, "Purpose", token)?;
        if token.eq_ignore_ascii_case("USERDEFINED")
            && user_defined.is_none_or(|text| text.trim().is_empty())
        {
            return Err(ResourceError::SemanticViolation {
                entity: None,
                rule: "USERDEFINED_REQUIRES_USER_DEFINED_PURPOSE",
            });
        }
        Ok(())
    }

    /// Stage an `IfcOrganizationRelationship`.
    ///
    /// # Errors
    ///
    /// Refuses a reference that is not an `IfcOrganization`, an empty
    /// related set (`SET [1:?]`), and an organisation related to itself.
    pub fn create_organization_relationship(
        &mut self,
        name: Option<&str>,
        description: Option<&str>,
        relating: EntityId,
        related: &[EntityId],
    ) -> ResourceResult<EntityId> {
        const ENTITY: &str = "IfcOrganizationRelationship";
        self.check_reference(
            relating,
            "RelatingOrganization",
            "IfcOrganization",
            relating,
        )?;
        if related.is_empty() {
            return Err(ResourceError::InvalidDraft {
                entity_type: ENTITY,
                attribute: "RelatedOrganizations",
                expected: "at least one organisation, per SET [1:?]",
            });
        }
        for organization in related {
            self.check_reference(
                *organization,
                "RelatedOrganizations",
                "IfcOrganization",
                *organization,
            )?;
            // A relationship from an organisation to itself states
            // nothing and makes the graph cyclic at depth one.
            if *organization == relating {
                return Err(ResourceError::SemanticViolation {
                    entity: None,
                    rule: "RELATING_ORGANIZATION_IS_NOT_RELATED",
                });
            }
        }
        let entity = build_entity(
            self.schema,
            ENTITY,
            &[
                ("Name", name.map(text)),
                ("Description", description.map(text)),
                ("RelatingOrganization", Some(Value::Ref(relating))),
                (
                    "RelatedOrganizations",
                    Some(Value::List(
                        related.iter().copied().map(Value::Ref).collect(),
                    )),
                ),
            ],
        )?;
        self.commit_create(entity)
    }
}