1use std::collections::HashSet;
4
5use ifc_model::{Budget, Entity, EntityId, Model, Transaction, Value};
6use ifc_schema::{ifc4, Schema, TypeKind};
7
8use crate::author::draft::{AllocationDraft, NestingDraft, ResourceDraft, ResourceTimeDraft};
9use crate::error::{ResourceError, ResourceResult};
10use crate::view::validate_object_assignment;
11use crate::{ResourceKind, ResourceView};
12
13pub struct ResourceEditor<'m> {
19 model: &'m mut Model,
20 pub(crate) schema: &'static Schema,
21}
22
23impl<'m> ResourceEditor<'m> {
24 pub fn for_model(model: &'m mut Model) -> ResourceResult<Self> {
31 let view = ResourceView::for_model(model)?;
32 if view.is_ifc2x3() {
33 return Err(ResourceError::UnsupportedSchema {
34 token: view.schema().name().to_owned(),
35 });
36 }
37 Ok(Self {
38 model,
39 schema: ifc4(),
40 })
41 }
42
43 pub(crate) fn validate_new_global_id(&self, value: &str) -> ResourceResult<()> {
44 validate_global_id(value)?;
45 for (id, entity) in self.model.iter() {
46 let Some(slot) = self
47 .schema
48 .attribute_names(&entity.type_name)
49 .iter()
50 .position(|name| name.eq_ignore_ascii_case("GlobalId"))
51 else {
52 continue;
53 };
54 if entity
55 .attributes
56 .get(slot)
57 .is_some_and(|stored| matches!(stored.unwrap_typed(), Value::Text(stored) if stored.as_ref() == value))
58 {
59 return Err(ResourceError::SemanticViolation {
60 entity: Some(id),
61 rule: "IfcRoot.GlobalId must be unique in the model",
62 });
63 }
64 }
65 Ok(())
66 }
67
68 pub fn create_resource(&mut self, draft: ResourceDraft<'_>) -> ResourceResult<EntityId> {
73 self.validate_new_global_id(draft.global_id)?;
74 let entity_type = resource_entity_type(draft.kind);
75 if let Some(value) = draft.predefined_type {
76 validate_enum(self.schema, entity_type, "PredefinedType", value)?;
77 if value == "USERDEFINED"
78 && draft
79 .object_type
80 .is_none_or(|value| value.trim().is_empty())
81 {
82 return Err(ResourceError::SemanticViolation {
83 entity: None,
84 rule: "USERDEFINED_REQUIRES_OBJECT_TYPE",
85 });
86 }
87 }
88 if let Some(usage) = draft.usage {
89 self.check_reference(usage, "Usage", "IfcResourceTime", usage)?;
90 }
91 for cost in &draft.base_costs {
92 self.check_reference(*cost, "BaseCosts", "IfcAppliedValue", *cost)?;
93 }
94 if let Some(quantity) = draft.base_quantity {
95 self.check_reference(quantity, "BaseQuantity", "IfcPhysicalQuantity", quantity)?;
96 }
97
98 let base_costs = (!draft.base_costs.is_empty()).then(|| refs(&draft.base_costs));
99 let entity = build_entity(
100 self.schema,
101 entity_type,
102 &[
103 ("GlobalId", Some(text(draft.global_id))),
104 ("Name", draft.name.map(text)),
105 ("ObjectType", draft.object_type.map(text)),
106 ("Identification", draft.identification.map(text)),
107 ("LongDescription", draft.long_description.map(text)),
108 ("Usage", draft.usage.map(Value::Ref)),
109 ("BaseCosts", base_costs),
110 ("BaseQuantity", draft.base_quantity.map(Value::Ref)),
111 (
112 "PredefinedType",
113 draft.predefined_type.map(|value| Value::Enum(value.into())),
114 ),
115 ],
116 )?;
117 self.commit_create(entity)
118 }
119
120 pub fn create_resource_type(&mut self, draft: ResourceDraft<'_>) -> ResourceResult<EntityId> {
138 self.validate_new_global_id(draft.global_id)?;
139 let entity_type = resource_type_entity_type(draft.kind);
140 let Some(predefined_type) = draft.predefined_type else {
141 return Err(ResourceError::SemanticViolation {
142 entity: None,
143 rule: "RESOURCE_TYPE_REQUIRES_PREDEFINED_TYPE",
144 });
145 };
146 validate_enum(self.schema, entity_type, "PredefinedType", predefined_type)?;
147 if predefined_type == "USERDEFINED"
148 && draft
149 .object_type
150 .is_none_or(|value| value.trim().is_empty())
151 {
152 return Err(ResourceError::SemanticViolation {
153 entity: None,
154 rule: "USERDEFINED_REQUIRES_OBJECT_TYPE",
155 });
156 }
157 if draft.usage.is_some() {
158 return Err(ResourceError::SemanticViolation {
159 entity: None,
160 rule: "RESOURCE_TYPE_HAS_NO_USAGE",
161 });
162 }
163 for cost in &draft.base_costs {
164 self.check_reference(*cost, "BaseCosts", "IfcAppliedValue", *cost)?;
165 }
166 if let Some(quantity) = draft.base_quantity {
167 self.check_reference(quantity, "BaseQuantity", "IfcPhysicalQuantity", quantity)?;
168 }
169
170 let base_costs = (!draft.base_costs.is_empty()).then(|| refs(&draft.base_costs));
171 let entity = build_entity(
172 self.schema,
173 entity_type,
174 &[
175 ("GlobalId", Some(text(draft.global_id))),
176 ("Name", draft.name.map(text)),
177 ("ApplicableOccurrence", draft.object_type.map(text)),
178 ("Identification", draft.identification.map(text)),
179 ("LongDescription", draft.long_description.map(text)),
180 ("BaseCosts", base_costs),
181 ("BaseQuantity", draft.base_quantity.map(Value::Ref)),
182 ("PredefinedType", Some(Value::Enum(predefined_type.into()))),
183 ],
184 )?;
185 self.commit_create(entity)
186 }
187
188 pub fn create_time(&mut self, draft: ResourceTimeDraft<'_>) -> ResourceResult<EntityId> {
191 for (attribute, value) in [
192 ("ScheduleUsage", draft.schedule_usage),
193 ("ActualUsage", draft.actual_usage),
194 ("RemainingUsage", draft.remaining_usage),
195 ("Completion", draft.completion),
196 ] {
197 if value.is_some_and(|value| !value.is_finite() || value <= 0.0) {
198 return Err(ResourceError::InvalidDraft {
199 entity_type: "IfcResourceTime",
200 attribute,
201 expected: "finite positive ratio",
202 });
203 }
204 }
205 let entity = build_entity(
206 self.schema,
207 "IfcResourceTime",
208 &[
209 ("Name", draft.name.map(text)),
210 ("ScheduleWork", draft.schedule_work.map(text)),
211 ("ScheduleUsage", draft.schedule_usage.map(Value::Real)),
212 ("ScheduleStart", draft.schedule_start.map(text)),
213 ("ScheduleFinish", draft.schedule_finish.map(text)),
214 ("IsOverAllocated", draft.is_over_allocated.map(Value::Bool)),
215 ("StatusTime", draft.status_time.map(text)),
216 ("ActualWork", draft.actual_work.map(text)),
217 ("ActualUsage", draft.actual_usage.map(Value::Real)),
218 ("ActualStart", draft.actual_start.map(text)),
219 ("ActualFinish", draft.actual_finish.map(text)),
220 ("RemainingWork", draft.remaining_work.map(text)),
221 ("RemainingUsage", draft.remaining_usage.map(Value::Real)),
222 ("Completion", draft.completion.map(Value::Real)),
223 ],
224 )?;
225 self.commit_create(entity)
226 }
227
228 pub fn create_allocation(&mut self, draft: AllocationDraft<'_>) -> ResourceResult<EntityId> {
233 self.validate_new_global_id(draft.global_id)?;
234 self.check_reference_select(
235 draft.resource,
236 "RelatingResource",
237 "IfcResourceSelect",
238 &["IfcResource", "IfcTypeResource"],
239 draft.resource,
240 )?;
241 validate_required_unique(draft.resource, "RelatedObjects", &draft.related_objects)?;
242 if let Some(category) = draft.related_objects_type {
243 validate_enum(
244 self.schema,
245 "IfcRelAssignsToResource",
246 "RelatedObjectsType",
247 category,
248 )?;
249 }
250 for target in &draft.related_objects {
251 self.check_reference(
252 draft.resource,
253 "RelatedObjects",
254 "IfcObjectDefinition",
255 *target,
256 )?;
257 if *target == draft.resource {
258 return Err(ResourceError::SemanticViolation {
259 entity: None,
260 rule: "RESOURCE_ASSIGNMENT_NO_SELF_REFERENCE",
261 });
262 }
263 }
264 validate_object_assignment(
265 self.model,
266 self.schema,
267 None,
268 draft.related_objects_type,
269 &draft.related_objects,
270 )?;
271 let entity = build_entity(
272 self.schema,
273 "IfcRelAssignsToResource",
274 &[
275 ("GlobalId", Some(text(draft.global_id))),
276 ("Name", draft.name.map(text)),
277 ("Description", draft.description.map(text)),
278 ("RelatedObjects", Some(refs(&draft.related_objects))),
279 (
280 "RelatedObjectsType",
281 draft
282 .related_objects_type
283 .map(|value| Value::Enum(value.into())),
284 ),
285 ("RelatingResource", Some(Value::Ref(draft.resource))),
286 ],
287 )?;
288 self.commit_create(entity)
289 }
290
291 pub fn create_nesting(&mut self, draft: NestingDraft<'_>) -> ResourceResult<EntityId> {
296 self.validate_new_global_id(draft.global_id)?;
297 self.check_reference(
298 draft.parent,
299 "RelatingObject",
300 "IfcConstructionResource",
301 draft.parent,
302 )?;
303 validate_required_unique(draft.parent, "RelatedObjects", &draft.children)?;
304 for child in &draft.children {
305 self.check_reference(
306 draft.parent,
307 "RelatedObjects",
308 "IfcConstructionResource",
309 *child,
310 )?;
311 if *child == draft.parent {
312 return Err(ResourceError::SemanticViolation {
313 entity: None,
314 rule: "RESOURCE_NESTING_NO_SELF_REFERENCE",
315 });
316 }
317 }
318 {
319 let view = ResourceView::new(self.model, self.schema)?;
320 for child in &draft.children {
321 if view.parent_resource(*child)?.is_some() {
322 return Err(ResourceError::SemanticViolation {
323 entity: Some(*child),
324 rule: "IfcObject.Nests permits at most one resource parent",
325 });
326 }
327 if view
328 .descendants(*child, Budget::DEFAULT)?
329 .contains(&draft.parent)
330 {
331 return Err(ResourceError::SemanticViolation {
332 entity: Some(*child),
333 rule: "resource nesting must remain acyclic",
334 });
335 }
336 }
337 }
338 let entity = build_entity(
339 self.schema,
340 "IfcRelNests",
341 &[
342 ("GlobalId", Some(text(draft.global_id))),
343 ("Name", draft.name.map(text)),
344 ("Description", draft.description.map(text)),
345 ("RelatingObject", Some(Value::Ref(draft.parent))),
346 ("RelatedObjects", Some(refs(&draft.children))),
347 ],
348 )?;
349 self.commit_create(entity)
350 }
351
352 pub(crate) fn check_reference(
353 &self,
354 owner: EntityId,
355 attribute: &'static str,
356 expected: &'static str,
357 target: EntityId,
358 ) -> ResourceResult<()> {
359 self.check_reference_select(owner, attribute, expected, &[expected], target)
360 }
361
362 pub(crate) fn check_reference_select(
363 &self,
364 owner: EntityId,
365 attribute: &'static str,
366 expected: &'static str,
367 members: &[&str],
368 target: EntityId,
369 ) -> ResourceResult<()> {
370 let entity = self
371 .model
372 .get(target)
373 .ok_or(ResourceError::DanglingReference {
374 entity: owner,
375 attribute,
376 target,
377 })?;
378 if !members
379 .iter()
380 .any(|member| self.schema.is_a(&entity.type_name, member))
381 {
382 return Err(ResourceError::WrongReferenceType {
383 entity: owner,
384 attribute,
385 target,
386 expected,
387 actual: entity.type_name.to_string(),
388 });
389 }
390 Ok(())
391 }
392
393 pub(crate) fn commit_create(&mut self, entity: Entity) -> ResourceResult<EntityId> {
394 let mut transaction = Transaction::new(self.model);
395 let expected = transaction.revision();
396 let id = transaction.create(entity);
397 transaction
398 .commit(self.model)
399 .map_err(|_| ResourceError::TransactionConflict {
400 expected,
401 actual: self.model.revision(),
402 })?;
403 Ok(id)
404 }
405}
406
407fn resource_entity_type(kind: ResourceKind) -> &'static str {
408 match kind {
409 ResourceKind::Labor => "IfcLaborResource",
410 ResourceKind::Equipment => "IfcConstructionEquipmentResource",
411 ResourceKind::Crew => "IfcCrewResource",
412 ResourceKind::Material => "IfcConstructionMaterialResource",
413 ResourceKind::Product => "IfcConstructionProductResource",
414 ResourceKind::Subcontract => "IfcSubContractResource",
415 }
416}
417
418fn resource_type_entity_type(kind: ResourceKind) -> &'static str {
424 match kind {
425 ResourceKind::Labor => "IfcLaborResourceType",
426 ResourceKind::Equipment => "IfcConstructionEquipmentResourceType",
427 ResourceKind::Crew => "IfcCrewResourceType",
428 ResourceKind::Material => "IfcConstructionMaterialResourceType",
429 ResourceKind::Product => "IfcConstructionProductResourceType",
430 ResourceKind::Subcontract => "IfcSubContractResourceType",
431 }
432}
433
434pub(crate) fn build_entity(
435 schema: &Schema,
436 entity_type: &'static str,
437 values: &[(&'static str, Option<Value>)],
438) -> ResourceResult<Entity> {
439 if schema.entity(entity_type).is_none() {
440 return Err(ResourceError::InvalidDraft {
441 entity_type,
442 attribute: "<entity>",
443 expected: "entity declared by IFC4",
444 });
445 }
446 let attribute_names = schema.attribute_names(entity_type);
447 let mut attributes = vec![Value::Null; attribute_names.len()];
448 for (name, value) in values {
449 if let Some(value) = value {
450 let slot = attribute_names
451 .iter()
452 .position(|candidate| candidate.eq_ignore_ascii_case(name))
453 .ok_or(ResourceError::InvalidDraft {
454 entity_type,
455 attribute: name,
456 expected: "attribute declared by IFC4",
457 })?;
458 attributes[slot] = value.clone();
459 }
460 }
461 Ok(Entity::new(entity_type, attributes))
462}
463
464pub(crate) fn validate_enum(
465 schema: &Schema,
466 entity_type: &'static str,
467 attribute: &'static str,
468 value: &str,
469) -> ResourceResult<()> {
470 let declared = schema
471 .attributes(entity_type)
472 .iter()
473 .find(|candidate| candidate.name.eq_ignore_ascii_case(attribute))
474 .and_then(|attribute| schema.type_def(&attribute.type_name))
475 .is_some_and(|definition| {
476 matches!(&definition.kind, TypeKind::Enumeration(values) if values.iter().any(|member| member == value))
477 });
478 if !declared {
479 return Err(ResourceError::InvalidEnumeration {
480 entity: None,
481 attribute,
482 value: value.to_owned(),
483 });
484 }
485 Ok(())
486}
487
488fn validate_required_unique(
489 owner: EntityId,
490 attribute: &'static str,
491 values: &[EntityId],
492) -> ResourceResult<()> {
493 if values.is_empty() {
494 return Err(ResourceError::InvalidCardinality {
495 entity: owner,
496 attribute,
497 minimum: 1,
498 actual: 0,
499 });
500 }
501 let mut unique = HashSet::with_capacity(values.len());
502 for value in values {
503 if !unique.insert(*value) {
504 return Err(ResourceError::DuplicateReference {
505 entity: owner,
506 attribute,
507 target: *value,
508 });
509 }
510 }
511 Ok(())
512}
513
514fn validate_global_id(value: &str) -> ResourceResult<()> {
515 if value.len() != 22
516 || !matches!(value.as_bytes().first(), Some(b'0'..=b'3'))
517 || !value
518 .bytes()
519 .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'$')
520 {
521 return Err(ResourceError::InvalidGlobalId);
522 }
523 Ok(())
524}
525
526pub(crate) fn text(value: &str) -> Value {
527 Value::Text(value.into())
528}
529
530pub(crate) fn refs(values: &[EntityId]) -> Value {
531 Value::List(values.iter().copied().map(Value::Ref).collect())
532}
533
534#[derive(Debug, Clone, Copy, Default)]
536#[non_exhaustive]
537pub struct AppliedValueDraft<'a> {
538 pub name: Option<&'a str>,
540 pub description: Option<&'a str>,
542 pub applied_value: Option<EntityId>,
544 pub unit_basis: Option<EntityId>,
546 pub applicable_date: Option<&'a str>,
548 pub fixed_until_date: Option<&'a str>,
550 pub category: Option<&'a str>,
552 pub condition: Option<&'a str>,
554 pub arithmetic_operator: Option<&'a str>,
556}
557
558impl<'a> AppliedValueDraft<'a> {
559 #[must_use]
561 pub fn new() -> Self {
562 Self {
563 name: None,
564 description: None,
565 applied_value: None,
566 unit_basis: None,
567 applicable_date: None,
568 fixed_until_date: None,
569 category: None,
570 condition: None,
571 arithmetic_operator: None,
572 }
573 }
574
575 #[must_use]
577 pub fn name(mut self, value: &'a str) -> Self {
578 self.name = Some(value);
579 self
580 }
581
582 #[must_use]
584 pub fn description(mut self, value: &'a str) -> Self {
585 self.description = Some(value);
586 self
587 }
588
589 #[must_use]
591 pub fn applied_value(mut self, value: EntityId) -> Self {
592 self.applied_value = Some(value);
593 self
594 }
595
596 #[must_use]
598 pub fn unit_basis(mut self, value: EntityId) -> Self {
599 self.unit_basis = Some(value);
600 self
601 }
602
603 #[must_use]
605 pub fn applicable_date(mut self, value: &'a str) -> Self {
606 self.applicable_date = Some(value);
607 self
608 }
609
610 #[must_use]
612 pub fn fixed_until_date(mut self, value: &'a str) -> Self {
613 self.fixed_until_date = Some(value);
614 self
615 }
616
617 #[must_use]
619 pub fn category(mut self, value: &'a str) -> Self {
620 self.category = Some(value);
621 self
622 }
623
624 #[must_use]
626 pub fn condition(mut self, value: &'a str) -> Self {
627 self.condition = Some(value);
628 self
629 }
630
631 #[must_use]
633 pub fn arithmetic_operator(mut self, value: &'a str) -> Self {
634 self.arithmetic_operator = Some(value);
635 self
636 }
637}
638
639impl ResourceEditor<'_> {
640 pub fn create_applied_value(
662 &mut self,
663 draft: AppliedValueDraft<'_>,
664 components: &[EntityId],
665 ) -> ResourceResult<EntityId> {
666 const ENTITY: &str = "IfcAppliedValue";
667 if let Some(operator) = draft.arithmetic_operator {
668 validate_enum(self.schema, ENTITY, "ArithmeticOperator", operator)?;
669 }
670 if draft.arithmetic_operator.is_some() == components.is_empty() {
671 return Err(ResourceError::SemanticViolation {
672 entity: None,
673 rule: "ArithmeticOperator and Components are stated together",
674 });
675 }
676 if let Some(value) = draft.applied_value {
677 self.check_reference_select(
678 value,
679 "AppliedValue",
680 "IfcAppliedValueSelect",
681 &[
682 "IfcMeasureWithUnit",
683 "IfcMonetaryMeasure",
684 "IfcRatioMeasure",
685 "IfcReference",
686 ],
687 value,
688 )?;
689 }
690 if let Some(basis) = draft.unit_basis {
691 self.check_reference(basis, "UnitBasis", "IfcMeasureWithUnit", basis)?;
692 }
693 for component in components {
694 self.check_reference(*component, "Components", ENTITY, *component)?;
695 }
696
697 let entity = build_entity(
698 self.schema,
699 ENTITY,
700 &[
701 ("Name", draft.name.map(text)),
702 ("Description", draft.description.map(text)),
703 ("AppliedValue", draft.applied_value.map(Value::Ref)),
704 ("UnitBasis", draft.unit_basis.map(Value::Ref)),
705 ("ApplicableDate", draft.applicable_date.map(text)),
706 ("FixedUntilDate", draft.fixed_until_date.map(text)),
707 ("Category", draft.category.map(text)),
708 ("Condition", draft.condition.map(text)),
709 ("ArithmeticOperator", draft.arithmetic_operator.map(enum_of)),
710 (
711 "Components",
712 (!components.is_empty()).then(|| refs(components)),
713 ),
714 ],
715 )?;
716 self.commit_create(entity)
717 }
718}
719
720fn enum_of(token: &str) -> Value {
722 Value::Enum(std::sync::Arc::from(token.to_ascii_uppercase()))
723}