Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/mobhub/blob/main/src/reconcile.rs # mobhub Decentralized model and agent weights distribution network Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `mobhub / src / reconcile.rs` 404 lines ยท 12751 bytes Raw Blame History 1 //! Torn faction money log and war payout reconciliation engine. 2 //! Pure, deterministic verification matching in-game disbursements to register rows. 3 4 use regex::Regex; 5 use serde::{Deserialize, Serialize}; 6 use std::collections::{HashMap, HashSet}; 7 use std::sync::LazyLock; 8 9 static GIVE_RE: LazyLock = LazyLock::new(|| { 10 Regex::new(r"(?i)increased\s+]*XID=(\d+)[^>]*>([^<]+)(?:'s|')\s+(?:]*>[^<]*\s+)?money balance by \$([0-9,]+)") 11 .expect("Failed to compile GIVE_RE regex") 12 }); 13 14 static OC_MARKER: LazyLock = LazyLock::new(|| { 15 Regex::new(r"(?i)cut for their role").expect("Failed to compile OC_MARKER regex") 16 }); 17 18 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] 19 pub struct ParsedDisbursement { 20 pub news_id: String, 21 pub recipient_torn_id: i64, 22 pub recipient_name: Option, 23 pub amount: i64, 24 pub occurred_at: Option, 25 pub raw_text: String, 26 } 27 28 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] 29 pub struct RegisterRowForMatch { 30 pub id: i64, 31 pub torn_id: i64, 32 pub amount_owed: i64, 33 pub paid: bool, 34 } 35 36 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] 37 pub struct GiveForMatch { 38 pub news_id: String, 39 pub recipient_torn_id: i64, 40 pub amount: i64, 41 pub occurred_at: Option, 42 } 43 44 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] 45 pub struct MatchDecision { 46 pub news_id: String, 47 pub recipient_torn_id: i64, 48 pub amount: i64, 49 pub matched_register_id: Option, 50 } 51 52 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] 53 pub struct ReconcileSummary { 54 pub matched: usize, 55 pub unmatched: usize, 56 pub scanned: usize, 57 pub decisions: Vec, 58 } 59 60 fn to_rfc3339(unix: i64) -> Option { 61 if unix <= 0 { 62 return None; 63 } 64 chrono::DateTime::from_timestamp(unix, 0).map(|dt| dt.to_rfc3339()) 65 } 66 67 /// Parse faction money-log news entries into payout disbursements. 68 /// Excludes Organized Crime (OC) cuts and non-give money events. 69 pub fn parse_disbursements(raw_news: &serde_json::Value) -> Vec { 70 let mut out = Vec::new(); 71 72 let items: Vec<&serde_json::Value> = if let Some(arr) = raw_news.as_array() { 73 arr.iter().collect() 74 } else if let Some(news_arr) = raw_news.get("news").and_then(|n| n.as_array()) { 75 news_arr.iter().collect() 76 } else if let Some(news_obj) = raw_news.get("news").and_then(|n| n.as_object()) { 77 news_obj.values().collect() 78 } else if let Some(obj) = raw_news.as_object() { 79 obj.values().collect() 80 } else { 81 Vec::new() 82 }; 83 84 for item in items { 85 let text = item 86 .get("text") 87 .and_then(|t| t.as_str()) 88 .or_else(|| item.get("news").and_then(|t| t.as_str())) 89 .unwrap_or(""); 90 91 if text.is_empty() || OC_MARKER.is_match(text) { 92 continue; 93 } 94 95 if let Some(caps) = GIVE_RE.captures(text) { 96 let recipient_torn_id: i64 = match caps.get(1).map(|m| m.as_str().parse()) { 97 Some(Ok(id)) => id, 98 _ => continue, 99 }; 100 101 let recipient_name = caps.get(2).map(|m| m.as_str().to_string()); 102 let amount_str = caps.get(3).map(|m| m.as_str().replace(',', "")).unwrap_or_default(); 103 let amount: i64 = match amount_str.parse() { 104 Ok(a) => a, 105 Err(_) => continue, 106 }; 107 108 let news_id = item 109 .get("id") 110 .and_then(|id| { 111 if let Some(s) = id.as_str() { 112 Some(s.to_string()) 113 } else { 114 id.as_i64().map(|n| n.to_string()) 115 } 116 }) 117 .unwrap_or_else(|| uuid::Uuid::new_v4().to_string()); 118 119 let timestamp = item.get("timestamp").and_then(|t| t.as_i64()).unwrap_or(0); 120 let occurred_at = to_rfc3339(timestamp); 121 122 out.push(ParsedDisbursement { 123 news_id, 124 recipient_torn_id, 125 recipient_name, 126 amount, 127 occurred_at, 128 raw_text: text.to_string(), 129 }); 130 } 131 } 132 133 out 134 } 135 136 /// Match money-log disbursements to unpaid register rows. 137 /// Real-money safety rules: 138 /// 1. Never match an already-paid register row. 139 /// 2. One register row can be claimed by at most one give. 140 /// 3. Pass 1: exact amount match. 141 /// 4. Pass 2: within tolerance percentage. 142 pub fn match_disbursements( 143 gives: &[GiveForMatch], 144 register: &[RegisterRowForMatch], 145 tolerance_pct: f64, 146 ) -> ReconcileSummary { 147 let mut by_torn: HashMap = HashMap::new(); 148 for r in register { 149 by_torn.insert(r.torn_id, r); 150 } 151 152 let mut claimed_register_ids: HashSet = HashSet::new(); 153 for r in register { 154 if r.paid { 155 claimed_register_ids.insert(r.id); 156 } 157 } 158 159 let mut decisions: HashMap = HashMap::new(); 160 for g in gives { 161 decisions.insert( 162 g.news_id.clone(), 163 MatchDecision { 164 news_id: g.news_id.clone(), 165 recipient_torn_id: g.recipient_torn_id, 166 amount: g.amount, 167 matched_register_id: None, 168 }, 169 ); 170 } 171 172 let mut pass = |accept: &dyn Fn(&GiveForMatch, &RegisterRowForMatch) -> bool| { 173 for g in gives { 174 let d = match decisions.get_mut(&g.news_id) { 175 Some(entry) => entry, 176 None => continue, 177 }; 178 if d.matched_register_id.is_some() { 179 continue; 180 } 181 182 let r = match by_torn.get(&g.recipient_torn_id) { 183 Some(&row) => row, 184 None => continue, 185 }; 186 187 if claimed_register_ids.contains(&r.id) { 188 continue; 189 } 190 191 if accept(g, r) { 192 d.matched_register_id = Some(r.id); 193 claimed_register_ids.insert(r.id); 194 } 195 } 196 }; 197 198 // Pass 1: exact amount match 199 pass(&|g, r| r.amount_owed > 0 && g.amount > 0 && g.amount == r.amount_owed); 200 201 // Pass 2: within tolerance 202 pass(&|g, r| { 203 if r.amount_owed <= 0 || g.amount <= 0 { 204 return false; 205 } 206 let max_diff = ((r.amount_owed as f64) * tolerance_pct).round() as i64; 207 let allowed_diff = max_diff.max(1); 208 (g.amount - r.amount_owed).abs() <= allowed_diff 209 }); 210 211 let mut matched = 0; 212 let mut unmatched = 0; 213 let mut ordered_decisions = Vec::new(); 214 215 for g in gives { 216 if let Some(d) = decisions.remove(&g.news_id) { 217 if d.matched_register_id.is_some() { 218 matched += 1; 219 } else { 220 unmatched += 1; 221 } 222 ordered_decisions.push(d); 223 } 224 } 225 226 ReconcileSummary { 227 matched, 228 unmatched, 229 scanned: gives.len(), 230 decisions: ordered_decisions, 231 } 232 } 233 234 /// Verify if a give timestamp falls strictly inside the war payout window. 235 pub fn is_in_war_window( 236 occurred_at_ms: Option, 237 from_ms: Option, 238 to_ms: Option, 239 ) -> bool { 240 match occurred_at_ms { 241 None => to_ms.is_none(), 242 Some(ts) => { 243 if let Some(from) = from_ms { 244 if ts < from { 245 return false; 246 } 247 } 248 if let Some(to) = to_ms { 249 if ts >= to { 250 return false; 251 } 252 } 253 true 254 } 255 } 256 } 257 258 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] 259 pub enum PayoutGivePick { 260 One { give_id: i64, amount: i64 }, 261 None, 262 Ambiguous, 263 } 264 265 /// Pick an exact give for historical closeout with tolerance bounds. 266 pub fn pick_payout_give(owed: i64, gives: &[(i64, i64)], tolerance: f64) -> PayoutGivePick { 267 if owed <= 0 { 268 return PayoutGivePick::None; 269 } 270 271 let lo = ((owed as f64) * (1.0 - tolerance)).round() as i64; 272 let hi = ((owed as f64) * (1.0 + tolerance)).round() as i64; 273 274 let in_band: Vec<&(i64, i64)> = gives 275 .iter() 276 .filter(|(_, amt)| *amt > 0 && *amt >= lo && *amt <= hi) 277 .collect(); 278 279 match in_band.len() { 280 0 => PayoutGivePick::None, 281 1 => PayoutGivePick::One { 282 give_id: in_band[0].0, 283 amount: in_band[0].1, 284 }, 285 _ => PayoutGivePick::Ambiguous, 286 } 287 } 288 289 #[cfg(test)] 290 mod tests { 291 use super::*; 292 use serde_json::json; 293 294 #[test] 295 fn test_parse_disbursements_with_oc_exclusion() { 296 let raw_news = json!({ 297 "news": { 298 "1": { 299 "id": "1001", 300 "timestamp": `1720000000`, 301 "text": "Officer increased TheLastPrimate's money balance by $50,973,248 from $0 to $50,973,248." 302 }, 303 "2": { 304 "id": "1002", 305 "timestamp": `1720000010`, 306 "text": "Officer increased TheLastPrimate's money balance by $1,250,000 as their cut for their role as Planner." 307 }, 308 "3": { 309 "id": "1003", 310 "timestamp": `1720000020`, 311 "text": "MrRazorlove deposited $10,000,000 to faction vault." 312 } 313 } 314 }); 315 316 let parsed = parse_disbursements(&raw_news); 317 assert_eq!(parsed.len(), 1); 318 assert_eq!(parsed[0].news_id, "1001"); 319 assert_eq!(parsed[0].recipient_torn_id, `4027928`); 320 assert_eq!(parsed[0].recipient_name.as_deref(), Some("TheLastPrimate")); 321 assert_eq!(parsed[0].amount, `50973248`); 322 } 323 324 #[test] 325 fn test_match_disbursements_exact_and_tolerance() { 326 let gives = vec![ 327 GiveForMatch { 328 news_id: "g1".to_string(), 329 recipient_torn_id: 1, 330 amount: `1000000`, 331 occurred_at: None, 332 }, 333 GiveForMatch { 334 news_id: "g2".to_string(), 335 recipient_torn_id: 2, 336 amount: 501000, 337 occurred_at: None, 338 }, 339 GiveForMatch { 340 news_id: "g3".to_string(), 341 recipient_torn_id: 3, 342 amount: 250000, 343 occurred_at: None, 344 }, 345 ]; 346 347 let register = vec![ 348 RegisterRowForMatch { 349 id: 101, 350 torn_id: 1, 351 amount_owed: `1000000`, 352 paid: false, 353 }, 354 RegisterRowForMatch { 355 id: 102, 356 torn_id: 2, 357 amount_owed: 500000, 358 paid: false, 359 }, 360 RegisterRowForMatch { 361 id: 103, 362 torn_id: 3, 363 amount_owed: 250000, 364 paid: true, 365 }, 366 ]; 367 368 let res = match_disbursements(&gives, ®ister, 0.005); 369 assert_eq!(res.matched, 2); 370 assert_eq!(res.unmatched, 1); 371 372 let g1_match = res.decisions.iter().find(|d| d.news_id == "g1").unwrap(); 373 assert_eq!(g1_match.matched_register_id, Some(101)); 374 375 let g2_match = res.decisions.iter().find(|d| d.news_id == "g2").unwrap(); 376 assert_eq!(g2_match.matched_register_id, Some(102)); 377 378 let g3_match = res.decisions.iter().find(|d| d.news_id == "g3").unwrap(); 379 assert_eq!(g3_match.matched_register_id, None); 380 } 381 382 #[test] 383 fn test_is_in_war_window() { 384 assert!(is_in_war_window(Some(150), Some(100), Some(200))); 385 assert!(!is_in_war_window(Some(90), Some(100), Some(200))); 386 assert!(!is_in_war_window(Some(200), Some(100), Some(200))); 387 assert!(is_in_war_window(Some(250), Some(100), None)); 388 assert!(!is_in_war_window(None, Some(100), Some(200))); 389 assert!(is_in_war_window(None, Some(100), None)); 390 } 391 392 #[test] 393 fn test_pick_payout_give() { 394 let gives = vec![(1, `1000000`), (2, `2000000`)]; 395 let pick1 = pick_payout_give(`1020000`, &gives, 0.1); 396 assert_eq!(pick1, PayoutGivePick::One { give_id: 1, amount: `1000000` }); 397 398 let pick_ambig = pick_payout_give(`1500000`, &gives, 0.5); 399 assert_eq!(pick_ambig, PayoutGivePick::Ambiguous); 400 401 let pick_none = pick_payout_give(`5000000`, &gives, 0.1); 402 assert_eq!(pick_none, PayoutGivePick::None); 403 } 404 }