Skip to main content

ifc_resource/resource/
type.rs

1//! IFC4 `IfcConstructionResourceType` occurrence-kind projections.
2//!
3//! IFC2X3 declares no resource types: every entry point here refuses with
4//! [`ResourceError::NotInSchema`] under it.
5
6use ifc_model::EntityId;
7
8use crate::error::{ResourceError, ResourceResult};
9use crate::view::Record;
10
11/// Concrete `IfcConstructionResourceType` specialization, matching
12/// `ResourceKind` but for the type-level (catalog) entity rather than the
13/// occurrence.
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15#[non_exhaustive]
16pub enum ResourceTypeKind {
17    /// `IfcLaborResourceType`.
18    Labor,
19    /// `IfcConstructionEquipmentResourceType`.
20    Equipment,
21    /// `IfcCrewResourceType`.
22    Crew,
23    /// `IfcConstructionMaterialResourceType`.
24    Material,
25    /// `IfcConstructionProductResourceType`.
26    Product,
27    /// `IfcSubContractResourceType`.
28    Subcontract,
29}
30
31impl ResourceTypeKind {
32    fn from_type(type_name: &str) -> Option<Self> {
33        if type_name.eq_ignore_ascii_case("IfcLaborResourceType") {
34            Some(Self::Labor)
35        } else if type_name.eq_ignore_ascii_case("IfcConstructionEquipmentResourceType") {
36            Some(Self::Equipment)
37        } else if type_name.eq_ignore_ascii_case("IfcCrewResourceType") {
38            Some(Self::Crew)
39        } else if type_name.eq_ignore_ascii_case("IfcConstructionMaterialResourceType") {
40            Some(Self::Material)
41        } else if type_name.eq_ignore_ascii_case("IfcConstructionProductResourceType") {
42            Some(Self::Product)
43        } else if type_name.eq_ignore_ascii_case("IfcSubContractResourceType") {
44            Some(Self::Subcontract)
45        } else {
46            None
47        }
48    }
49}
50
51#[derive(Debug, Clone, Copy)]
52/// Borrowed projection of a concrete `IfcConstructionResourceType` catalog
53/// entity.
54pub struct ConstructionResourceType<'m, 's> {
55    record: Record<'m, 's>,
56    kind: ResourceTypeKind,
57}
58
59impl<'m, 's> ConstructionResourceType<'m, 's> {
60    pub(crate) fn from_record(record: Record<'m, 's>) -> ResourceResult<Self> {
61        let kind = ResourceTypeKind::from_type(&record.entity.type_name).ok_or_else(|| {
62            ResourceError::WrongType {
63                id: record.id,
64                expected: "concrete IfcConstructionResourceType occurrence",
65                actual: record.entity.type_name.to_string(),
66            }
67        })?;
68        Ok(Self { record, kind })
69    }
70
71    /// The entity id of the projected type.
72    #[must_use]
73    pub fn id(&self) -> EntityId {
74        self.record.id
75    }
76
77    /// Which concrete `IfcConstructionResourceType` subtype this is.
78    #[must_use]
79    pub fn kind(&self) -> ResourceTypeKind {
80        self.kind
81    }
82
83    /// The `Name` attribute.
84    pub fn name(&self) -> ResourceResult<&'m str> {
85        self.record.required_text("Name")
86    }
87
88    /// The `Identification` attribute, when authored.
89    pub fn identification(&self) -> ResourceResult<Option<&'m str>> {
90        self.record.optional_text("Identification")
91    }
92
93    /// The `LongDescription` attribute, when authored.
94    pub fn long_description(&self) -> ResourceResult<Option<&'m str>> {
95        self.record.optional_text("LongDescription")
96    }
97
98    /// The inherited `IfcTypeResource.ResourceType` label, when authored.
99    pub fn resource_type(&self) -> ResourceResult<Option<&'m str>> {
100        self.record.optional_text("ResourceType")
101    }
102
103    /// Enforces the shared `CorrectPredefinedType` WHERE rule across all six
104    /// concrete IFC4 resource-type entities: USERDEFINED requires the
105    /// inherited `IfcTypeResource.ResourceType` label.
106    pub fn predefined_type(&self) -> ResourceResult<Option<&'m str>> {
107        let value = self.record.optional_enum("PredefinedType")?;
108        if value.is_some_and(|value| value.eq_ignore_ascii_case("USERDEFINED"))
109            && self
110                .record
111                .optional_text("ResourceType")?
112                .is_none_or(|value| value.trim().is_empty())
113        {
114            return Err(ResourceError::SemanticViolation {
115                entity: Some(self.record.id),
116                rule: "CorrectPredefinedType requires ResourceType for USERDEFINED",
117            });
118        }
119        Ok(value)
120    }
121
122    /// The `BaseCosts` attribute: applied-value references, when authored.
123    pub fn base_costs(&self) -> ResourceResult<Vec<EntityId>> {
124        self.record
125            .refs("BaseCosts", "IfcAppliedValue", 1, true, false)
126    }
127
128    /// The `BaseQuantity` attribute: the physical-quantity reference, when
129    /// authored.
130    pub fn base_quantity(&self) -> ResourceResult<Option<EntityId>> {
131        self.record
132            .optional_ref("BaseQuantity", "IfcPhysicalQuantity")
133    }
134}
135
136impl<'m, 's> crate::view::ResourceView<'m, 's> {
137    /// Projects a resource-type catalog entry by entity id.
138    pub fn resource_type(&self, id: EntityId) -> ResourceResult<ConstructionResourceType<'m, 's>> {
139        ConstructionResourceType::from_record(self.record(id, "IfcConstructionResourceType")?)
140    }
141
142    /// Resolves the `IfcConstructionResourceType` assigned to a construction
143    /// resource occurrence through `IfcRelDefinesByType`, if any.
144    ///
145    /// An occurrence may be typed by at most one type. A second authored
146    /// relation assigning a *different* type is a modeling defect, reported
147    /// as a typed refusal rather than silently picking the first or last
148    /// match. A repeated relation naming the *same* type states the same fact
149    /// twice and is accepted. (`ifc-material` treats even that as ambiguous
150    /// for its material lookup.)
151    ///
152    /// IFC2X3 declares no `IfcConstructionResourceType`, so this refuses
153    /// with [`ResourceError::NotInSchema`] there instead of answering `None`.
154    pub fn assigned_resource_type(&self, occurrence: EntityId) -> ResourceResult<Option<EntityId>> {
155        self.require_entity("IfcConstructionResourceType")?;
156        self.resource(occurrence)?;
157        let mut found = None;
158        for relation in self.ids_of_ancestor("IfcRelDefinesByType") {
159            let record = self.record(relation, "IfcRelDefinesByType")?;
160            let related = record.refs("RelatedObjects", "IfcObject", 1, false, true)?;
161            if !related.contains(&occurrence) {
162                continue;
163            }
164            let relating_type =
165                record.required_ref("RelatingType", "IfcConstructionResourceType")?;
166            if let Some(existing) = found.replace(relating_type) {
167                if existing != relating_type {
168                    return Err(ResourceError::SemanticViolation {
169                        entity: Some(occurrence),
170                        rule: "IfcTypeObject.Types permits at most one type assignment",
171                    });
172                }
173            }
174        }
175        Ok(found)
176    }
177}