1use chrono::NaiveDate;
10use datasynth_core::models::{
11 CrossProcessLink, CrossProcessLinkType, EntityGraph, EntityNode, GraphEntityId,
12 GraphEntityType, GraphMetadata, RelationshipEdge, RelationshipStrengthCalculator,
13 RelationshipType, VendorNetwork,
14};
15use datasynth_core::utils::seeded_rng;
16use rand::prelude::*;
17use rand_chacha::ChaCha8Rng;
18use rust_decimal::Decimal;
19use std::collections::{HashMap, HashSet};
20
21#[derive(Debug, Clone)]
23pub struct EntityGraphConfig {
24 pub enabled: bool,
26 pub cross_process: CrossProcessConfig,
28 pub strength_config: StrengthConfig,
30 pub include_organizational: bool,
32 pub include_document: bool,
34}
35
36impl Default for EntityGraphConfig {
37 fn default() -> Self {
38 Self {
39 enabled: false,
40 cross_process: CrossProcessConfig::default(),
41 strength_config: StrengthConfig::default(),
42 include_organizational: true,
43 include_document: true,
44 }
45 }
46}
47
48#[derive(Debug, Clone)]
50pub struct CrossProcessConfig {
51 pub enable_inventory_links: bool,
53 pub enable_return_flows: bool,
55 pub enable_payment_links: bool,
57 pub enable_ic_bilateral: bool,
59 pub inventory_link_rate: f64,
61 pub payment_link_rate: f64,
63}
64
65impl Default for CrossProcessConfig {
66 fn default() -> Self {
67 Self {
68 enable_inventory_links: true,
69 enable_return_flows: true,
70 enable_payment_links: true,
71 enable_ic_bilateral: true,
72 inventory_link_rate: 0.30,
73 payment_link_rate: 0.80,
74 }
75 }
76}
77
78#[derive(Debug, Clone)]
80pub struct StrengthConfig {
81 pub transaction_volume_weight: f64,
83 pub transaction_count_weight: f64,
85 pub duration_weight: f64,
87 pub recency_weight: f64,
89 pub mutual_connections_weight: f64,
91 pub recency_half_life_days: u32,
93}
94
95impl Default for StrengthConfig {
96 fn default() -> Self {
97 Self {
98 transaction_volume_weight: 0.30,
99 transaction_count_weight: 0.25,
100 duration_weight: 0.20,
101 recency_weight: 0.15,
102 mutual_connections_weight: 0.10,
103 recency_half_life_days: 90,
104 }
105 }
106}
107
108#[derive(Debug, Clone)]
110pub struct TransactionSummary {
111 pub total_volume: Decimal,
113 pub transaction_count: u32,
115 pub first_transaction_date: NaiveDate,
117 pub last_transaction_date: NaiveDate,
119 pub related_entities: HashSet<String>,
121}
122
123impl Default for TransactionSummary {
124 fn default() -> Self {
125 Self {
126 total_volume: Decimal::ZERO,
127 transaction_count: 0,
128 first_transaction_date: NaiveDate::from_ymd_opt(2020, 1, 1)
129 .expect("valid default date"),
130 last_transaction_date: NaiveDate::from_ymd_opt(2020, 1, 1).expect("valid default date"),
131 related_entities: HashSet::new(),
132 }
133 }
134}
135
136#[derive(Debug, Clone)]
138pub struct GoodsReceiptRef {
139 pub document_id: String,
141 pub material_id: String,
143 pub quantity: Decimal,
145 pub receipt_date: NaiveDate,
147 pub vendor_id: String,
149 pub company_code: String,
151}
152
153#[derive(Debug, Clone)]
155pub struct DeliveryRef {
156 pub document_id: String,
158 pub material_id: String,
160 pub quantity: Decimal,
162 pub delivery_date: NaiveDate,
164 pub customer_id: String,
166 pub company_code: String,
168}
169
170pub struct EntityGraphGenerator {
172 rng: ChaCha8Rng,
173 seed: u64,
174 config: EntityGraphConfig,
175 strength_calculator: RelationshipStrengthCalculator,
176}
177
178impl EntityGraphGenerator {
179 pub fn new(seed: u64) -> Self {
181 Self::with_config(seed, EntityGraphConfig::default())
182 }
183
184 pub fn with_config(seed: u64, config: EntityGraphConfig) -> Self {
186 let strength_calculator = RelationshipStrengthCalculator {
187 weights: datasynth_core::models::StrengthWeights {
188 transaction_volume_weight: config.strength_config.transaction_volume_weight,
189 transaction_count_weight: config.strength_config.transaction_count_weight,
190 duration_weight: config.strength_config.duration_weight,
191 recency_weight: config.strength_config.recency_weight,
192 mutual_connections_weight: config.strength_config.mutual_connections_weight,
193 },
194 recency_half_life_days: config.strength_config.recency_half_life_days,
195 ..Default::default()
196 };
197
198 Self {
199 rng: seeded_rng(seed, 0),
200 seed,
201 config,
202 strength_calculator,
203 }
204 }
205
206 pub fn generate_entity_graph(
208 &mut self,
209 company_code: &str,
210 as_of_date: NaiveDate,
211 vendors: &[EntitySummary],
212 customers: &[EntitySummary],
213 transaction_summaries: &HashMap<(String, String), TransactionSummary>,
214 ) -> EntityGraph {
215 let mut graph = EntityGraph::new();
216 graph.metadata = GraphMetadata {
217 company_code: Some(company_code.to_string()),
218 created_date: Some(as_of_date),
219 total_transaction_volume: Decimal::ZERO,
220 date_range: None,
221 };
222
223 if !self.config.enabled {
224 return graph;
225 }
226
227 let company_id = GraphEntityId::new(GraphEntityType::Company, company_code);
229 graph.add_node(EntityNode::new(
230 company_id.clone(),
231 format!("Company {}", company_code),
232 as_of_date,
233 ));
234
235 for vendor in vendors {
237 let vendor_id = GraphEntityId::new(GraphEntityType::Vendor, &vendor.entity_id);
238 let node = EntityNode::new(vendor_id.clone(), &vendor.name, as_of_date)
239 .with_company(company_code);
240 graph.add_node(node);
241
242 let edge = RelationshipEdge::new(
244 company_id.clone(),
245 vendor_id,
246 RelationshipType::BuysFrom,
247 vendor.first_activity_date,
248 );
249 graph.add_edge(edge);
250 }
251
252 for customer in customers {
254 let customer_id = GraphEntityId::new(GraphEntityType::Customer, &customer.entity_id);
255 let node = EntityNode::new(customer_id.clone(), &customer.name, as_of_date)
256 .with_company(company_code);
257 graph.add_node(node);
258
259 let edge = RelationshipEdge::new(
261 company_id.clone(),
262 customer_id,
263 RelationshipType::SellsTo,
264 customer.first_activity_date,
265 );
266 graph.add_edge(edge);
267 }
268
269 let total_connections = transaction_summaries.len().max(1);
271 for ((from_id, to_id), summary) in transaction_summaries {
272 let from_entity_id = self.infer_entity_id(from_id);
273 let to_entity_id = self.infer_entity_id(to_id);
274
275 let days_since_last = (as_of_date - summary.last_transaction_date)
277 .num_days()
278 .max(0) as u32;
279 let relationship_days = (as_of_date - summary.first_transaction_date)
280 .num_days()
281 .max(1) as u32;
282
283 let components = self.strength_calculator.calculate(
284 summary.total_volume,
285 summary.transaction_count,
286 relationship_days,
287 days_since_last,
288 summary.related_entities.len(),
289 total_connections,
290 );
291
292 let rel_type = self.infer_relationship_type(&from_entity_id, &to_entity_id);
293
294 let edge = RelationshipEdge::new(
295 from_entity_id,
296 to_entity_id,
297 rel_type,
298 summary.first_transaction_date,
299 )
300 .with_strength_components(components);
301
302 graph.add_edge(edge);
303 }
304
305 graph.metadata.total_transaction_volume =
307 transaction_summaries.values().map(|s| s.total_volume).sum();
308
309 graph
310 }
311
312 pub fn generate_cross_process_links(
314 &mut self,
315 goods_receipts: &[GoodsReceiptRef],
316 deliveries: &[DeliveryRef],
317 ) -> Vec<CrossProcessLink> {
318 let mut links = Vec::new();
319
320 if !self.config.cross_process.enable_inventory_links {
321 return links;
322 }
323
324 let deliveries_by_material: HashMap<String, Vec<&DeliveryRef>> =
326 deliveries.iter().fold(HashMap::new(), |mut acc, del| {
327 acc.entry(del.material_id.clone()).or_default().push(del);
328 acc
329 });
330
331 for gr in goods_receipts {
333 if self.rng.gen::<f64>() > self.config.cross_process.inventory_link_rate {
334 continue;
335 }
336
337 if let Some(matching_deliveries) = deliveries_by_material.get(&gr.material_id) {
338 let valid_deliveries: Vec<_> = matching_deliveries
341 .iter()
342 .filter(|d| {
343 d.delivery_date >= gr.receipt_date && d.company_code == gr.company_code
344 })
345 .collect();
346
347 if !valid_deliveries.is_empty() {
348 let delivery = valid_deliveries[self.rng.gen_range(0..valid_deliveries.len())];
349
350 let linked_qty = gr.quantity.min(delivery.quantity);
352
353 links.push(CrossProcessLink::new(
354 &gr.material_id,
355 "P2P",
356 &gr.document_id,
357 "O2C",
358 &delivery.document_id,
359 CrossProcessLinkType::InventoryMovement,
360 linked_qty,
361 delivery.delivery_date,
362 ));
363 }
364 }
365 }
366
367 links
368 }
369
370 pub fn generate_from_vendor_network(
372 &mut self,
373 vendor_network: &VendorNetwork,
374 as_of_date: NaiveDate,
375 ) -> EntityGraph {
376 let mut graph = EntityGraph::new();
377 graph.metadata = GraphMetadata {
378 company_code: Some(vendor_network.company_code.clone()),
379 created_date: Some(as_of_date),
380 total_transaction_volume: vendor_network.statistics.total_annual_spend,
381 date_range: None,
382 };
383
384 if !self.config.enabled {
385 return graph;
386 }
387
388 let company_id = GraphEntityId::new(GraphEntityType::Company, &vendor_network.company_code);
390 graph.add_node(EntityNode::new(
391 company_id.clone(),
392 format!("Company {}", vendor_network.company_code),
393 as_of_date,
394 ));
395
396 for (vendor_id, relationship) in &vendor_network.relationships {
398 let entity_id = GraphEntityId::new(GraphEntityType::Vendor, vendor_id);
399 let node = EntityNode::new(entity_id.clone(), vendor_id, as_of_date)
400 .with_company(&vendor_network.company_code)
401 .with_attribute("tier", format!("{:?}", relationship.tier))
402 .with_attribute("cluster", format!("{:?}", relationship.cluster))
403 .with_attribute(
404 "strategic_level",
405 format!("{:?}", relationship.strategic_importance),
406 );
407 graph.add_node(node);
408
409 if let Some(parent_id) = &relationship.parent_vendor {
411 let parent_entity_id = GraphEntityId::new(GraphEntityType::Vendor, parent_id);
412 let edge = RelationshipEdge::new(
413 entity_id.clone(),
414 parent_entity_id,
415 RelationshipType::SuppliesTo,
416 relationship.start_date,
417 )
418 .with_strength(relationship.relationship_score());
419 graph.add_edge(edge);
420 } else {
421 let edge = RelationshipEdge::new(
423 entity_id,
424 company_id.clone(),
425 RelationshipType::SuppliesTo,
426 relationship.start_date,
427 )
428 .with_strength(relationship.relationship_score());
429 graph.add_edge(edge);
430 }
431 }
432
433 graph
434 }
435
436 fn infer_entity_id(&self, id: &str) -> GraphEntityId {
438 if id.starts_with("V-") || id.starts_with("VN-") {
439 GraphEntityId::new(GraphEntityType::Vendor, id)
440 } else if id.starts_with("C-") || id.starts_with("CU-") {
441 GraphEntityId::new(GraphEntityType::Customer, id)
442 } else if id.starts_with("E-") || id.starts_with("EM-") {
443 GraphEntityId::new(GraphEntityType::Employee, id)
444 } else if id.starts_with("MAT-") || id.starts_with("M-") {
445 GraphEntityId::new(GraphEntityType::Material, id)
446 } else if id.starts_with("PO-") {
447 GraphEntityId::new(GraphEntityType::PurchaseOrder, id)
448 } else if id.starts_with("SO-") {
449 GraphEntityId::new(GraphEntityType::SalesOrder, id)
450 } else if id.starts_with("INV-") || id.starts_with("IV-") {
451 GraphEntityId::new(GraphEntityType::Invoice, id)
452 } else if id.starts_with("PAY-") || id.starts_with("PM-") {
453 GraphEntityId::new(GraphEntityType::Payment, id)
454 } else {
455 GraphEntityId::new(GraphEntityType::Company, id)
456 }
457 }
458
459 fn infer_relationship_type(
461 &self,
462 from: &GraphEntityId,
463 to: &GraphEntityId,
464 ) -> RelationshipType {
465 match (&from.entity_type, &to.entity_type) {
466 (GraphEntityType::Company, GraphEntityType::Vendor) => RelationshipType::BuysFrom,
467 (GraphEntityType::Company, GraphEntityType::Customer) => RelationshipType::SellsTo,
468 (GraphEntityType::Vendor, GraphEntityType::Company) => RelationshipType::SuppliesTo,
469 (GraphEntityType::Customer, GraphEntityType::Company) => RelationshipType::SourcesFrom,
470 (GraphEntityType::PurchaseOrder, GraphEntityType::Invoice) => {
471 RelationshipType::References
472 }
473 (GraphEntityType::Invoice, GraphEntityType::Payment) => RelationshipType::FulfilledBy,
474 (GraphEntityType::Payment, GraphEntityType::Invoice) => RelationshipType::AppliesTo,
475 (GraphEntityType::Employee, GraphEntityType::Employee) => RelationshipType::ReportsTo,
476 (GraphEntityType::Employee, GraphEntityType::Department) => RelationshipType::WorksIn,
477 _ => RelationshipType::References,
478 }
479 }
480
481 pub fn reset(&mut self) {
483 self.rng = seeded_rng(self.seed, 0);
484 }
485}
486
487#[derive(Debug, Clone)]
489pub struct EntitySummary {
490 pub entity_id: String,
492 pub name: String,
494 pub first_activity_date: NaiveDate,
496 pub entity_type: GraphEntityType,
498 pub attributes: HashMap<String, String>,
500}
501
502impl EntitySummary {
503 pub fn new(
505 entity_id: impl Into<String>,
506 name: impl Into<String>,
507 entity_type: GraphEntityType,
508 first_activity_date: NaiveDate,
509 ) -> Self {
510 Self {
511 entity_id: entity_id.into(),
512 name: name.into(),
513 first_activity_date,
514 entity_type,
515 attributes: HashMap::new(),
516 }
517 }
518}
519
520#[cfg(test)]
521#[allow(clippy::unwrap_used)]
522mod tests {
523 use super::*;
524
525 #[test]
526 fn test_entity_graph_generation() {
527 let config = EntityGraphConfig {
528 enabled: true,
529 ..Default::default()
530 };
531
532 let mut gen = EntityGraphGenerator::with_config(42, config);
533
534 let vendors = vec![
535 EntitySummary::new(
536 "V-001",
537 "Acme Supplies",
538 GraphEntityType::Vendor,
539 NaiveDate::from_ymd_opt(2023, 1, 1).unwrap(),
540 ),
541 EntitySummary::new(
542 "V-002",
543 "Global Parts",
544 GraphEntityType::Vendor,
545 NaiveDate::from_ymd_opt(2023, 3, 1).unwrap(),
546 ),
547 ];
548
549 let customers = vec![EntitySummary::new(
550 "C-001",
551 "Contoso Corp",
552 GraphEntityType::Customer,
553 NaiveDate::from_ymd_opt(2023, 2, 1).unwrap(),
554 )];
555
556 let graph = gen.generate_entity_graph(
557 "1000",
558 NaiveDate::from_ymd_opt(2024, 1, 1).unwrap(),
559 &vendors,
560 &customers,
561 &HashMap::new(),
562 );
563
564 assert_eq!(graph.nodes.len(), 4);
566 assert_eq!(graph.edges.len(), 3);
568 }
569
570 #[test]
571 fn test_cross_process_link_generation() {
572 let config = EntityGraphConfig {
573 enabled: true,
574 cross_process: CrossProcessConfig {
575 enable_inventory_links: true,
576 inventory_link_rate: 1.0, ..Default::default()
578 },
579 ..Default::default()
580 };
581
582 let mut gen = EntityGraphGenerator::with_config(42, config);
583
584 let goods_receipts = vec![GoodsReceiptRef {
585 document_id: "GR-001".to_string(),
586 material_id: "MAT-100".to_string(),
587 quantity: Decimal::from(100),
588 receipt_date: NaiveDate::from_ymd_opt(2024, 1, 1).unwrap(),
589 vendor_id: "V-001".to_string(),
590 company_code: "1000".to_string(),
591 }];
592
593 let deliveries = vec![DeliveryRef {
594 document_id: "DEL-001".to_string(),
595 material_id: "MAT-100".to_string(),
596 quantity: Decimal::from(50),
597 delivery_date: NaiveDate::from_ymd_opt(2024, 1, 15).unwrap(),
598 customer_id: "C-001".to_string(),
599 company_code: "1000".to_string(),
600 }];
601
602 let links = gen.generate_cross_process_links(&goods_receipts, &deliveries);
603
604 assert_eq!(links.len(), 1);
605 assert_eq!(links[0].material_id, "MAT-100");
606 assert_eq!(links[0].source_document_id, "GR-001");
607 assert_eq!(links[0].target_document_id, "DEL-001");
608 assert_eq!(links[0].link_type, CrossProcessLinkType::InventoryMovement);
609 }
610
611 #[test]
612 fn test_disabled_graph_generation() {
613 let config = EntityGraphConfig {
614 enabled: false,
615 ..Default::default()
616 };
617
618 let mut gen = EntityGraphGenerator::with_config(42, config);
619
620 let graph = gen.generate_entity_graph(
621 "1000",
622 NaiveDate::from_ymd_opt(2024, 1, 1).unwrap(),
623 &[],
624 &[],
625 &HashMap::new(),
626 );
627
628 assert!(graph.nodes.is_empty());
629 }
630
631 #[test]
632 fn test_entity_id_inference() {
633 let gen = EntityGraphGenerator::new(42);
634
635 let vendor_id = gen.infer_entity_id("V-001");
636 assert_eq!(vendor_id.entity_type, GraphEntityType::Vendor);
637
638 let customer_id = gen.infer_entity_id("C-001");
639 assert_eq!(customer_id.entity_type, GraphEntityType::Customer);
640
641 let po_id = gen.infer_entity_id("PO-12345");
642 assert_eq!(po_id.entity_type, GraphEntityType::PurchaseOrder);
643 }
644
645 #[test]
646 fn test_relationship_type_inference() {
647 let gen = EntityGraphGenerator::new(42);
648
649 let company_id = GraphEntityId::new(GraphEntityType::Company, "1000");
650 let vendor_id = GraphEntityId::new(GraphEntityType::Vendor, "V-001");
651
652 let rel_type = gen.infer_relationship_type(&company_id, &vendor_id);
653 assert_eq!(rel_type, RelationshipType::BuysFrom);
654
655 let rel_type = gen.infer_relationship_type(&vendor_id, &company_id);
656 assert_eq!(rel_type, RelationshipType::SuppliesTo);
657 }
658}