1use std::collections::HashSet;
15use std::sync::Arc;
16
17use ifc_model::guid::Guid;
18use ifc_model::{Edit, EntityId, Model, Transaction, Value};
19
20use ifc_schema::Schema;
21
22use crate::release::{bind, require_owner_history};
23use crate::{ApprovalError, ApprovalResult};
24
25const APPROVAL: &str = "IFCAPPROVAL";
26const APPROVAL_REL: &str = "IFCAPPROVALRELATIONSHIP";
27const RESOURCE_REL: &str = "IFCRESOURCEAPPROVALRELATIONSHIP";
28const ASSIGNMENT: &str = "IFCRELASSOCIATESAPPROVAL";
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38#[non_exhaustive]
39pub enum DateTimeInput<'a> {
40 Text(&'a str),
42 Record(EntityId),
44}
45
46impl<'a> From<&'a str> for DateTimeInput<'a> {
47 fn from(text: &'a str) -> Self {
48 Self::Text(text)
49 }
50}
51
52impl From<EntityId> for DateTimeInput<'_> {
53 fn from(record: EntityId) -> Self {
54 Self::Record(record)
55 }
56}
57
58#[derive(Debug, Clone, Copy, Default)]
60#[non_exhaustive]
61pub struct ApprovalDraft<'a> {
62 pub identifier: Option<&'a str>,
64 pub name: Option<&'a str>,
66 pub description: Option<&'a str>,
68 pub time_of_approval: Option<DateTimeInput<'a>>,
72 pub status: Option<&'a str>,
74 pub level: Option<&'a str>,
76 pub qualifier: Option<&'a str>,
78 pub requesting_approval: Option<EntityId>,
80 pub giving_approval: Option<EntityId>,
82}
83
84impl<'a> ApprovalDraft<'a> {
85 #[must_use]
87 pub fn new() -> Self {
88 Self {
89 identifier: None,
90 name: None,
91 description: None,
92 time_of_approval: None,
93 status: None,
94 level: None,
95 qualifier: None,
96 requesting_approval: None,
97 giving_approval: None,
98 }
99 }
100
101 #[must_use]
103 pub fn identifier(mut self, value: &'a str) -> Self {
104 self.identifier = Some(value);
105 self
106 }
107
108 #[must_use]
110 pub fn name(mut self, value: &'a str) -> Self {
111 self.name = Some(value);
112 self
113 }
114
115 #[must_use]
117 pub fn description(mut self, value: &'a str) -> Self {
118 self.description = Some(value);
119 self
120 }
121
122 #[must_use]
124 pub fn time_of_approval(mut self, value: impl Into<DateTimeInput<'a>>) -> Self {
125 self.time_of_approval = Some(value.into());
126 self
127 }
128
129 #[must_use]
131 pub fn status(mut self, value: &'a str) -> Self {
132 self.status = Some(value);
133 self
134 }
135
136 #[must_use]
138 pub fn level(mut self, value: &'a str) -> Self {
139 self.level = Some(value);
140 self
141 }
142
143 #[must_use]
145 pub fn qualifier(mut self, value: &'a str) -> Self {
146 self.qualifier = Some(value);
147 self
148 }
149
150 #[must_use]
152 pub fn requesting_approval(mut self, value: EntityId) -> Self {
153 self.requesting_approval = Some(value);
154 self
155 }
156
157 #[must_use]
159 pub fn giving_approval(mut self, value: EntityId) -> Self {
160 self.giving_approval = Some(value);
161 self
162 }
163}
164
165#[derive(Debug, Clone, Copy)]
167#[non_exhaustive]
168pub struct ApprovalRelationshipDraft<'a> {
169 pub name: Option<&'a str>,
171 pub description: Option<&'a str>,
173 pub relating_approval: EntityId,
175 pub related_approvals: &'a [EntityId],
177}
178
179impl<'a> ApprovalRelationshipDraft<'a> {
180 #[must_use]
182 pub fn new(relating_approval: EntityId, related_approvals: &'a [EntityId]) -> Self {
183 Self {
184 name: None,
185 description: None,
186 relating_approval,
187 related_approvals,
188 }
189 }
190
191 #[must_use]
193 pub fn name(mut self, value: &'a str) -> Self {
194 self.name = Some(value);
195 self
196 }
197
198 #[must_use]
200 pub fn description(mut self, value: &'a str) -> Self {
201 self.description = Some(value);
202 self
203 }
204}
205
206#[derive(Debug, Clone, Copy)]
208#[non_exhaustive]
209pub struct ResourceApprovalDraft<'a> {
210 pub name: Option<&'a str>,
212 pub description: Option<&'a str>,
214 pub related_resources: &'a [EntityId],
216 pub relating_approval: EntityId,
218}
219
220impl<'a> ResourceApprovalDraft<'a> {
221 #[must_use]
223 pub fn new(related_resources: &'a [EntityId], relating_approval: EntityId) -> Self {
224 Self {
225 name: None,
226 description: None,
227 related_resources,
228 relating_approval,
229 }
230 }
231
232 #[must_use]
234 pub fn name(mut self, value: &'a str) -> Self {
235 self.name = Some(value);
236 self
237 }
238
239 #[must_use]
241 pub fn description(mut self, value: &'a str) -> Self {
242 self.description = Some(value);
243 self
244 }
245}
246
247#[derive(Debug, Clone, Copy)]
249#[non_exhaustive]
250pub struct ApprovalAssociationDraft<'a> {
251 pub global_id: &'a str,
253 pub name: Option<&'a str>,
255 pub description: Option<&'a str>,
257 pub related_objects: &'a [EntityId],
259 pub relating_approval: EntityId,
261}
262
263impl<'a> ApprovalAssociationDraft<'a> {
264 #[must_use]
266 pub fn new(
267 global_id: &'a str,
268 related_objects: &'a [EntityId],
269 relating_approval: EntityId,
270 ) -> Self {
271 Self {
272 global_id,
273 name: None,
274 description: None,
275 related_objects,
276 relating_approval,
277 }
278 }
279
280 #[must_use]
282 pub fn name(mut self, value: &'a str) -> Self {
283 self.name = Some(value);
284 self
285 }
286
287 #[must_use]
289 pub fn description(mut self, value: &'a str) -> Self {
290 self.description = Some(value);
291 self
292 }
293}
294
295pub fn create_approval(
315 tx: &mut Transaction,
316 model: &Model,
317 draft: ApprovalDraft<'_>,
318) -> ApprovalResult<EntityId> {
319 let layout = bind(model)?;
320 if draft.identifier.is_none() && draft.name.is_none() {
321 return Err(ApprovalError::AuthoringInvalid {
322 entity: APPROVAL,
323 attribute: "WR",
324 value: "Identifier and Name are both absent".into(),
325 });
326 }
327 for target in [draft.requesting_approval, draft.giving_approval]
328 .into_iter()
329 .flatten()
330 {
331 validate_target_in(layout.schema(), tx, model, target, "IfcActorSelect")?;
332 }
333 let time = match draft.time_of_approval {
334 None => Value::Null,
335 Some(DateTimeInput::Text(text)) => Value::Text(Arc::from(text)),
336 Some(DateTimeInput::Record(target)) => {
337 if let Some((_, declared)) = layout.declared(APPROVAL, "TimeOfApproval") {
338 if layout.admits_entity(&declared.type_name, 8) {
339 validate_target_in(
340 layout.schema(),
341 tx,
342 model,
343 target,
344 declared.type_name.as_str(),
345 )?;
346 }
347 }
348 Value::Ref(target)
349 }
350 };
351 let record = layout.named_record(
352 APPROVAL,
353 vec![
354 ("Identifier", optional_text(draft.identifier)),
355 ("Name", optional_text(draft.name)),
356 ("Description", optional_text(draft.description)),
357 ("TimeOfApproval", time),
358 ("Status", optional_text(draft.status)),
359 ("Level", optional_text(draft.level)),
360 ("Qualifier", optional_text(draft.qualifier)),
361 (
362 "RequestingApproval",
363 optional_ref(draft.requesting_approval),
364 ),
365 ("GivingApproval", optional_ref(draft.giving_approval)),
366 ],
367 )?;
368 Ok(tx.create(record))
369}
370
371pub fn relate_approvals(
384 tx: &mut Transaction,
385 model: &Model,
386 draft: ApprovalRelationshipDraft<'_>,
387) -> ApprovalResult<EntityId> {
388 let layout = bind(model)?;
389 layout.require_entity(APPROVAL_REL)?;
390 validate_target_in(
391 layout.schema(),
392 tx,
393 model,
394 draft.relating_approval,
395 APPROVAL,
396 )?;
397 validate_set(
398 layout.schema(),
399 tx,
400 model,
401 APPROVAL_REL,
402 "RelatedApprovals",
403 draft.related_approvals,
404 APPROVAL,
405 Some(draft.relating_approval),
406 )?;
407 let single = layout
408 .declared(APPROVAL_REL, "RelatedApprovals")
409 .is_some_and(|(_, declared)| !declared.aggregate);
410 let related = match (single, draft.related_approvals) {
411 (false, related) => refs(related),
412 (true, [one]) => Value::Ref(*one),
413 (true, _) => {
414 return Err(ApprovalError::AuthoringValueType {
415 entity: APPROVAL_REL,
416 attribute: "RelatedApprovals",
417 declared: "IfcApproval",
418 schema: layout.version(),
419 })
420 }
421 };
422 let record = layout.named_record(
423 APPROVAL_REL,
424 vec![
425 ("Name", optional_text(draft.name)),
426 ("Description", optional_text(draft.description)),
427 ("RelatingApproval", Value::Ref(draft.relating_approval)),
428 ("RelatedApprovals", related),
429 ],
430 )?;
431 Ok(tx.create(record))
432}
433
434pub fn relate_resource_approval(
445 tx: &mut Transaction,
446 model: &Model,
447 draft: ResourceApprovalDraft<'_>,
448) -> ApprovalResult<EntityId> {
449 let layout = bind(model)?;
450 layout.require_entity(RESOURCE_REL)?;
451 validate_target_in(
452 layout.schema(),
453 tx,
454 model,
455 draft.relating_approval,
456 APPROVAL,
457 )?;
458 validate_set(
459 layout.schema(),
460 tx,
461 model,
462 RESOURCE_REL,
463 "RelatedResourceObjects",
464 draft.related_resources,
465 "IfcResourceObjectSelect",
466 None,
467 )?;
468 let record = layout.named_record(
469 RESOURCE_REL,
470 vec![
471 ("Name", optional_text(draft.name)),
472 ("Description", optional_text(draft.description)),
473 ("RelatedResourceObjects", refs(draft.related_resources)),
474 ("RelatingApproval", Value::Ref(draft.relating_approval)),
475 ],
476 )?;
477 Ok(tx.create(record))
478}
479
480pub fn associate_approval(
500 tx: &mut Transaction,
501 model: &Model,
502 draft: ApprovalAssociationDraft<'_>,
503) -> ApprovalResult<EntityId> {
504 associate(tx, model, draft, None)
505}
506
507pub fn associate_approval_with_owner_history(
521 tx: &mut Transaction,
522 model: &Model,
523 draft: ApprovalAssociationDraft<'_>,
524 owner_history: EntityId,
525) -> ApprovalResult<EntityId> {
526 associate(tx, model, draft, Some(owner_history))
527}
528
529fn associate(
531 tx: &mut Transaction,
532 model: &Model,
533 draft: ApprovalAssociationDraft<'_>,
534 owner_history: Option<EntityId>,
535) -> ApprovalResult<EntityId> {
536 let layout = bind(model)?;
537 if Guid::parse(draft.global_id).is_none() {
538 return Err(ApprovalError::AuthoringInvalid {
539 entity: ASSIGNMENT,
540 attribute: "GlobalId",
541 value: draft.global_id.into(),
542 });
543 }
544 validate_target_in(
545 layout.schema(),
546 tx,
547 model,
548 draft.relating_approval,
549 APPROVAL,
550 )?;
551 if draft.related_objects.is_empty() {
552 return Err(ApprovalError::AuthoringInvalid {
553 entity: ASSIGNMENT,
554 attribute: "RelatedObjects",
555 value: "empty SET [1:?]".into(),
556 });
557 }
558 let mut seen = HashSet::new();
559 for &target in draft.related_objects {
560 if !seen.insert(target) {
561 return Err(ApprovalError::AuthoringInvalid {
562 entity: ASSIGNMENT,
563 attribute: "RelatedObjects",
564 value: format!("duplicate {target}"),
565 });
566 }
567 let actual =
568 final_type(tx, model, target).ok_or(ApprovalError::UnknownEntity { id: target })?;
569 if !layout.is_definition(actual) {
570 return Err(ApprovalError::AuthoringReferenceType {
571 target,
572 expected: "IfcDefinitionSelect",
573 actual: actual.into(),
574 });
575 }
576 }
577 if let Some(owner_history) = owner_history {
578 require_owner_history(tx, model, owner_history)?;
579 }
580 let record = layout.named_record(
581 ASSIGNMENT,
582 vec![
583 ("GlobalId", text(draft.global_id)),
584 ("OwnerHistory", optional_ref(owner_history)),
585 ("Name", optional_text(draft.name)),
586 ("Description", optional_text(draft.description)),
587 ("RelatedObjects", refs(draft.related_objects)),
588 ("RelatingApproval", Value::Ref(draft.relating_approval)),
589 ],
590 )?;
591 Ok(tx.create(record))
592}
593
594#[allow(clippy::too_many_arguments)]
595fn validate_set(
596 schema: &Schema,
597 tx: &Transaction,
598 model: &Model,
599 kind: &'static str,
600 attribute: &'static str,
601 targets: &[EntityId],
602 expected: &'static str,
603 disallow: Option<EntityId>,
604) -> ApprovalResult<()> {
605 if targets.is_empty() {
606 return Err(ApprovalError::AuthoringInvalid {
607 entity: kind,
608 attribute,
609 value: "empty SET [1:?]".into(),
610 });
611 }
612 let mut seen = HashSet::new();
613 for &target in targets {
614 if !seen.insert(target) {
615 return Err(ApprovalError::AuthoringInvalid {
616 entity: kind,
617 attribute,
618 value: format!("duplicate {target}"),
619 });
620 }
621 if Some(target) == disallow {
622 return Err(ApprovalError::AuthoringInvalid {
623 entity: kind,
624 attribute,
625 value: format!("self reference {target}"),
626 });
627 }
628 validate_target_in(schema, tx, model, target, expected)?;
629 }
630 Ok(())
631}
632
633fn validate_target_in(
636 schema: &Schema,
637 tx: &Transaction,
638 model: &Model,
639 target: EntityId,
640 expected: &'static str,
641) -> ApprovalResult<()> {
642 let actual =
643 final_type(tx, model, target).ok_or(ApprovalError::UnknownEntity { id: target })?;
644 if schema.accepts_type(expected, actual) {
645 Ok(())
646 } else {
647 Err(ApprovalError::AuthoringReferenceType {
648 target,
649 expected,
650 actual: actual.into(),
651 })
652 }
653}
654
655fn final_type<'a>(tx: &'a Transaction, model: &'a Model, id: EntityId) -> Option<&'a str> {
656 for edit in tx.edits().iter().rev() {
657 match edit {
658 Edit::Create {
659 id: edit_id,
660 entity,
661 } if *edit_id == id => return Some(&entity.type_name),
662 Edit::Remove { id: edit_id } if *edit_id == id => return None,
663 Edit::Retype {
664 id: edit_id,
665 type_name,
666 } if *edit_id == id => return Some(type_name),
667 _ => {}
668 }
669 }
670 model.get(id).map(|entity| entity.type_name.as_ref())
671}
672
673fn text(value: &str) -> Value {
674 Value::Text(Arc::from(value))
675}
676fn optional_text(value: Option<&str>) -> Value {
677 value.map_or(Value::Null, text)
678}
679fn optional_ref(value: Option<EntityId>) -> Value {
680 value.map_or(Value::Null, Value::Ref)
681}
682fn refs(values: &[EntityId]) -> Value {
683 Value::List(values.iter().copied().map(Value::Ref).collect())
684}