Skip to main content

ifc_resource/author/
contact.rs

1//! Authoring roles and addresses.
2//!
3//! Both addresses carry a "say something" rule: `IfcPostalAddress.WR1`
4//! and `IfcTelecomAddress.MinimumDataProvided` each require at least
5//! one contact field. An address with every slot unset parses and
6//! reaches nobody, so it is refused rather than written.
7//!
8//! None of these are `IfcRoot` subtypes: they have no GlobalId and are
9//! referenced from the person, organisation or actor that owns them.
10
11use ifc_model::{EntityId, Value};
12
13use crate::author::editor::{build_entity, text, validate_enum, ResourceEditor};
14use crate::error::{ResourceError, ResourceResult};
15
16/// Draft for one `IfcActorRole`.
17#[derive(Debug, Clone, Copy)]
18#[non_exhaustive]
19pub struct ActorRoleDraft<'a> {
20    /// `Role`, an `IfcRoleEnum` token.
21    pub role: &'a str,
22    /// `UserDefinedRole`. Required when `role` is `USERDEFINED`.
23    pub user_defined_role: Option<&'a str>,
24    /// `Description`.
25    pub description: Option<&'a str>,
26}
27
28impl<'a> ActorRoleDraft<'a> {
29    /// Starts a draft with its required fields; the rest are unset.
30    #[must_use]
31    pub fn new(role: &'a str) -> Self {
32        Self {
33            role,
34            user_defined_role: None,
35            description: None,
36        }
37    }
38
39    /// Sets [`Self::user_defined_role`]: `UserDefinedRole`. Required when `role` is `USERDEFINED`.
40    #[must_use]
41    pub fn user_defined_role(mut self, value: &'a str) -> Self {
42        self.user_defined_role = Some(value);
43        self
44    }
45
46    /// Sets [`Self::description`]: `Description`.
47    #[must_use]
48    pub fn description(mut self, value: &'a str) -> Self {
49        self.description = Some(value);
50        self
51    }
52}
53
54/// Draft for one `IfcPostalAddress`.
55#[derive(Debug, Clone, Copy, Default)]
56#[non_exhaustive]
57pub struct PostalAddressDraft<'a> {
58    /// `Purpose`, an `IfcAddressTypeEnum` token.
59    pub purpose: Option<&'a str>,
60    /// `Description`.
61    pub description: Option<&'a str>,
62    /// `UserDefinedPurpose`. Required when `purpose` is `USERDEFINED`.
63    pub user_defined_purpose: Option<&'a str>,
64    /// `InternalLocation`: a room or desk within the building.
65    pub internal_location: Option<&'a str>,
66    /// `PostalBox`.
67    pub postal_box: Option<&'a str>,
68    /// `Town`.
69    pub town: Option<&'a str>,
70    /// `Region`.
71    pub region: Option<&'a str>,
72    /// `PostalCode`.
73    pub postal_code: Option<&'a str>,
74    /// `Country`.
75    pub country: Option<&'a str>,
76}
77
78impl<'a> PostalAddressDraft<'a> {
79    /// Starts a draft with every field unset.
80    #[must_use]
81    pub fn new() -> Self {
82        Self {
83            purpose: None,
84            description: None,
85            user_defined_purpose: None,
86            internal_location: None,
87            postal_box: None,
88            town: None,
89            region: None,
90            postal_code: None,
91            country: None,
92        }
93    }
94
95    /// Sets [`Self::purpose`]: `Purpose`, an `IfcAddressTypeEnum` token.
96    #[must_use]
97    pub fn purpose(mut self, value: &'a str) -> Self {
98        self.purpose = Some(value);
99        self
100    }
101
102    /// Sets [`Self::description`]: `Description`.
103    #[must_use]
104    pub fn description(mut self, value: &'a str) -> Self {
105        self.description = Some(value);
106        self
107    }
108
109    /// Sets [`Self::user_defined_purpose`]: `UserDefinedPurpose`. Required when `purpose` is `USERDEFINED`.
110    #[must_use]
111    pub fn user_defined_purpose(mut self, value: &'a str) -> Self {
112        self.user_defined_purpose = Some(value);
113        self
114    }
115
116    /// Sets [`Self::internal_location`]: `InternalLocation`: a room or desk within the building.
117    #[must_use]
118    pub fn internal_location(mut self, value: &'a str) -> Self {
119        self.internal_location = Some(value);
120        self
121    }
122
123    /// Sets [`Self::postal_box`]: `PostalBox`.
124    #[must_use]
125    pub fn postal_box(mut self, value: &'a str) -> Self {
126        self.postal_box = Some(value);
127        self
128    }
129
130    /// Sets [`Self::town`]: `Town`.
131    #[must_use]
132    pub fn town(mut self, value: &'a str) -> Self {
133        self.town = Some(value);
134        self
135    }
136
137    /// Sets [`Self::region`]: `Region`.
138    #[must_use]
139    pub fn region(mut self, value: &'a str) -> Self {
140        self.region = Some(value);
141        self
142    }
143
144    /// Sets [`Self::postal_code`]: `PostalCode`.
145    #[must_use]
146    pub fn postal_code(mut self, value: &'a str) -> Self {
147        self.postal_code = Some(value);
148        self
149    }
150
151    /// Sets [`Self::country`]: `Country`.
152    #[must_use]
153    pub fn country(mut self, value: &'a str) -> Self {
154        self.country = Some(value);
155        self
156    }
157}
158
159/// Draft for one `IfcTelecomAddress`.
160#[derive(Debug, Clone, Copy, Default)]
161#[non_exhaustive]
162pub struct TelecomAddressDraft<'a> {
163    /// `Purpose`, an `IfcAddressTypeEnum` token.
164    pub purpose: Option<&'a str>,
165    /// `Description`.
166    pub description: Option<&'a str>,
167    /// `UserDefinedPurpose`. Required when `purpose` is `USERDEFINED`.
168    pub user_defined_purpose: Option<&'a str>,
169    /// `PagerNumber`.
170    pub pager_number: Option<&'a str>,
171    /// `WWWHomePageURL`.
172    pub www_home_page_url: Option<&'a str>,
173}
174
175impl<'a> TelecomAddressDraft<'a> {
176    /// Starts a draft with every field unset.
177    #[must_use]
178    pub fn new() -> Self {
179        Self {
180            purpose: None,
181            description: None,
182            user_defined_purpose: None,
183            pager_number: None,
184            www_home_page_url: None,
185        }
186    }
187
188    /// Sets [`Self::purpose`]: `Purpose`, an `IfcAddressTypeEnum` token.
189    #[must_use]
190    pub fn purpose(mut self, value: &'a str) -> Self {
191        self.purpose = Some(value);
192        self
193    }
194
195    /// Sets [`Self::description`]: `Description`.
196    #[must_use]
197    pub fn description(mut self, value: &'a str) -> Self {
198        self.description = Some(value);
199        self
200    }
201
202    /// Sets [`Self::user_defined_purpose`]: `UserDefinedPurpose`. Required when `purpose` is `USERDEFINED`.
203    #[must_use]
204    pub fn user_defined_purpose(mut self, value: &'a str) -> Self {
205        self.user_defined_purpose = Some(value);
206        self
207    }
208
209    /// Sets [`Self::pager_number`]: `PagerNumber`.
210    #[must_use]
211    pub fn pager_number(mut self, value: &'a str) -> Self {
212        self.pager_number = Some(value);
213        self
214    }
215
216    /// Sets [`Self::www_home_page_url`]: `WWWHomePageURL`.
217    #[must_use]
218    pub fn www_home_page_url(mut self, value: &'a str) -> Self {
219        self.www_home_page_url = Some(value);
220        self
221    }
222}
223
224/// The `LIST [1:?]` attributes of an `IfcTelecomAddress`.
225///
226/// Each is optional as a whole but bounded `[1:?]` when present, so an
227/// empty slice is written as absent rather than as an empty list.
228#[derive(Debug, Clone, Copy, Default)]
229pub struct TelecomLists<'a> {
230    /// `TelephoneNumbers`.
231    pub telephone: &'a [&'a str],
232    /// `FacsimileNumbers`.
233    pub facsimile: &'a [&'a str],
234    /// `ElectronicMailAddresses`.
235    pub email: &'a [&'a str],
236    /// `MessagingIDs`.
237    pub messaging: &'a [&'a str],
238}
239
240/// A `LIST [1:?]` written as absent when empty.
241fn optional_list(values: &[&str]) -> Option<Value> {
242    if values.is_empty() {
243        return None;
244    }
245    Some(Value::List(
246        values.iter().map(|v| Value::Text((*v).into())).collect(),
247    ))
248}
249
250impl ResourceEditor<'_> {
251    /// Stage an `IfcActorRole`.
252    ///
253    /// # Errors
254    ///
255    /// Refuses a token outside `IfcRoleEnum` and `USERDEFINED`
256    /// without a `user_defined_role` (WR1).
257    pub fn create_actor_role(&mut self, draft: ActorRoleDraft<'_>) -> ResourceResult<EntityId> {
258        const ENTITY: &str = "IfcActorRole";
259        validate_enum(self.schema, ENTITY, "Role", draft.role)?;
260        if draft.role.eq_ignore_ascii_case("USERDEFINED")
261            && draft
262                .user_defined_role
263                .is_none_or(|text| text.trim().is_empty())
264        {
265            return Err(ResourceError::SemanticViolation {
266                entity: None,
267                rule: "WR1",
268            });
269        }
270        let entity = build_entity(
271            self.schema,
272            ENTITY,
273            &[
274                ("Role", Some(Value::Enum(draft.role.into()))),
275                ("UserDefinedRole", draft.user_defined_role.map(text)),
276                ("Description", draft.description.map(text)),
277            ],
278        )?;
279        self.commit_create(entity)
280    }
281
282    /// Stage an `IfcPostalAddress`.
283    ///
284    /// `address_lines` is `LIST [1:?]` when present.
285    ///
286    /// # Errors
287    ///
288    /// Refuses a `purpose` outside `IfcAddressTypeEnum`, `USERDEFINED`
289    /// without a `user_defined_purpose`, and an address with no
290    /// locating field at all (WR1).
291    pub fn create_postal_address(
292        &mut self,
293        draft: PostalAddressDraft<'_>,
294        address_lines: &[&str],
295    ) -> ResourceResult<EntityId> {
296        const ENTITY: &str = "IfcPostalAddress";
297        self.validate_address_purpose(ENTITY, draft.purpose, draft.user_defined_purpose)?;
298        // WR1: an address that locates nothing reaches nobody.
299        let locates = !address_lines.is_empty()
300            || draft.internal_location.is_some()
301            || draft.postal_box.is_some()
302            || draft.postal_code.is_some()
303            || draft.town.is_some()
304            || draft.region.is_some()
305            || draft.country.is_some();
306        if !locates {
307            return Err(ResourceError::SemanticViolation {
308                entity: None,
309                rule: "WR1",
310            });
311        }
312        let entity = build_entity(
313            self.schema,
314            ENTITY,
315            &[
316                ("Purpose", draft.purpose.map(|p| Value::Enum(p.into()))),
317                ("Description", draft.description.map(text)),
318                ("UserDefinedPurpose", draft.user_defined_purpose.map(text)),
319                ("InternalLocation", draft.internal_location.map(text)),
320                ("AddressLines", optional_list(address_lines)),
321                ("PostalBox", draft.postal_box.map(text)),
322                ("Town", draft.town.map(text)),
323                ("Region", draft.region.map(text)),
324                ("PostalCode", draft.postal_code.map(text)),
325                ("Country", draft.country.map(text)),
326            ],
327        )?;
328        self.commit_create(entity)
329    }
330
331    /// Stage an `IfcTelecomAddress`.
332    ///
333    /// # Errors
334    ///
335    /// Refuses a `purpose` outside `IfcAddressTypeEnum`, `USERDEFINED`
336    /// without a `user_defined_purpose`, and an address carrying no
337    /// contact route at all (MinimumDataProvided).
338    pub fn create_telecom_address(
339        &mut self,
340        draft: TelecomAddressDraft<'_>,
341        lists: TelecomLists<'_>,
342    ) -> ResourceResult<EntityId> {
343        const ENTITY: &str = "IfcTelecomAddress";
344        self.validate_address_purpose(ENTITY, draft.purpose, draft.user_defined_purpose)?;
345        // MinimumDataProvided: at least one way to reach someone.
346        let reachable = !lists.telephone.is_empty()
347            || !lists.facsimile.is_empty()
348            || !lists.email.is_empty()
349            || !lists.messaging.is_empty()
350            || draft.pager_number.is_some()
351            || draft.www_home_page_url.is_some();
352        if !reachable {
353            return Err(ResourceError::SemanticViolation {
354                entity: None,
355                rule: "MinimumDataProvided",
356            });
357        }
358        let entity = build_entity(
359            self.schema,
360            ENTITY,
361            &[
362                ("Purpose", draft.purpose.map(|p| Value::Enum(p.into()))),
363                ("Description", draft.description.map(text)),
364                ("UserDefinedPurpose", draft.user_defined_purpose.map(text)),
365                ("TelephoneNumbers", optional_list(lists.telephone)),
366                ("FacsimileNumbers", optional_list(lists.facsimile)),
367                ("PagerNumber", draft.pager_number.map(text)),
368                ("ElectronicMailAddresses", optional_list(lists.email)),
369                ("WWWHomePageURL", draft.www_home_page_url.map(text)),
370                ("MessagingIDs", optional_list(lists.messaging)),
371            ],
372        )?;
373        self.commit_create(entity)
374    }
375
376    /// Both addresses share `Purpose` and its USERDEFINED rule.
377    fn validate_address_purpose(
378        &self,
379        entity: &'static str,
380        purpose: Option<&str>,
381        user_defined: Option<&str>,
382    ) -> ResourceResult<()> {
383        let Some(token) = purpose else {
384            return Ok(());
385        };
386        validate_enum(self.schema, entity, "Purpose", token)?;
387        if token.eq_ignore_ascii_case("USERDEFINED")
388            && user_defined.is_none_or(|text| text.trim().is_empty())
389        {
390            return Err(ResourceError::SemanticViolation {
391                entity: None,
392                rule: "USERDEFINED_REQUIRES_USER_DEFINED_PURPOSE",
393            });
394        }
395        Ok(())
396    }
397
398    /// Stage an `IfcOrganizationRelationship`.
399    ///
400    /// # Errors
401    ///
402    /// Refuses a reference that is not an `IfcOrganization`, an empty
403    /// related set (`SET [1:?]`), and an organisation related to itself.
404    pub fn create_organization_relationship(
405        &mut self,
406        name: Option<&str>,
407        description: Option<&str>,
408        relating: EntityId,
409        related: &[EntityId],
410    ) -> ResourceResult<EntityId> {
411        const ENTITY: &str = "IfcOrganizationRelationship";
412        self.check_reference(
413            relating,
414            "RelatingOrganization",
415            "IfcOrganization",
416            relating,
417        )?;
418        if related.is_empty() {
419            return Err(ResourceError::InvalidDraft {
420                entity_type: ENTITY,
421                attribute: "RelatedOrganizations",
422                expected: "at least one organisation, per SET [1:?]",
423            });
424        }
425        for organization in related {
426            self.check_reference(
427                *organization,
428                "RelatedOrganizations",
429                "IfcOrganization",
430                *organization,
431            )?;
432            // A relationship from an organisation to itself states
433            // nothing and makes the graph cyclic at depth one.
434            if *organization == relating {
435                return Err(ResourceError::SemanticViolation {
436                    entity: None,
437                    rule: "RELATING_ORGANIZATION_IS_NOT_RELATED",
438                });
439            }
440        }
441        let entity = build_entity(
442            self.schema,
443            ENTITY,
444            &[
445                ("Name", name.map(text)),
446                ("Description", description.map(text)),
447                ("RelatingOrganization", Some(Value::Ref(relating))),
448                (
449                    "RelatedOrganizations",
450                    Some(Value::List(
451                        related.iter().copied().map(Value::Ref).collect(),
452                    )),
453                ),
454            ],
455        )?;
456        self.commit_create(entity)
457    }
458}