Skip to main content

datasynth_core/distributions/
timezone.rs

1//! Timezone handling for multi-region synthetic data generation.
2//!
3//! This module provides timezone-aware datetime handling for:
4//! - Entity-specific timezone assignments (by company code pattern)
5//! - UTC to local time conversions
6//! - Consolidation timezone for group reporting
7
8use chrono::{DateTime, NaiveDateTime, Offset, TimeZone, Utc};
9use chrono_tz::Tz;
10use serde::{Deserialize, Serialize};
11use std::collections::HashMap;
12
13/// Timezone configuration for multi-region entities.
14#[derive(Debug, Clone, Serialize, Deserialize)]
15pub struct TimezoneConfig {
16    /// Default timezone for entities without a specific mapping.
17    pub default_timezone: String,
18    /// Entity-to-timezone mappings (supports patterns like "EU_*" -> "Europe/London").
19    pub entity_timezones: HashMap<String, String>,
20    /// Consolidation timezone for group reporting.
21    pub consolidation_timezone: String,
22}
23
24impl Default for TimezoneConfig {
25    fn default() -> Self {
26        Self {
27            default_timezone: "America/New_York".to_string(),
28            entity_timezones: HashMap::new(),
29            consolidation_timezone: "UTC".to_string(),
30        }
31    }
32}
33
34impl TimezoneConfig {
35    /// Creates a new timezone config with the specified default timezone.
36    pub fn new(default_tz: &str) -> Self {
37        Self {
38            default_timezone: default_tz.to_string(),
39            entity_timezones: HashMap::new(),
40            consolidation_timezone: "UTC".to_string(),
41        }
42    }
43
44    /// Sets the consolidation timezone.
45    pub fn with_consolidation(mut self, tz: &str) -> Self {
46        self.consolidation_timezone = tz.to_string();
47        self
48    }
49
50    /// Adds an entity-to-timezone mapping.
51    ///
52    /// Supports pattern matching:
53    /// - Exact match: "1000" -> "America/New_York"
54    /// - Prefix match: "EU_*" -> "Europe/London"
55    /// - Suffix match: "*_APAC" -> "Asia/Singapore"
56    pub fn add_mapping(mut self, entity_pattern: &str, timezone: &str) -> Self {
57        self.entity_timezones
58            .insert(entity_pattern.to_string(), timezone.to_string());
59        self
60    }
61}
62
63/// Handler for timezone operations.
64#[derive(Debug, Clone)]
65pub struct TimezoneHandler {
66    config: TimezoneConfig,
67    /// Parsed default timezone.
68    default_tz: Tz,
69    /// Parsed consolidation timezone.
70    consolidation_tz: Tz,
71    /// Cached parsed entity timezones.
72    entity_tz_cache: HashMap<String, Tz>,
73}
74
75impl TimezoneHandler {
76    /// Creates a new timezone handler from configuration.
77    pub fn new(config: TimezoneConfig) -> Result<Self, TimezoneError> {
78        let default_tz: Tz = config
79            .default_timezone
80            .parse()
81            .map_err(|_| TimezoneError::InvalidTimezone(config.default_timezone.clone()))?;
82
83        let consolidation_tz: Tz = config
84            .consolidation_timezone
85            .parse()
86            .map_err(|_| TimezoneError::InvalidTimezone(config.consolidation_timezone.clone()))?;
87
88        // Pre-parse all entity timezone mappings
89        let mut entity_tz_cache = HashMap::new();
90        for (pattern, tz_name) in &config.entity_timezones {
91            let tz: Tz = tz_name
92                .parse()
93                .map_err(|_| TimezoneError::InvalidTimezone(tz_name.clone()))?;
94            entity_tz_cache.insert(pattern.clone(), tz);
95        }
96
97        Ok(Self {
98            config,
99            default_tz,
100            consolidation_tz,
101            entity_tz_cache,
102        })
103    }
104
105    /// Creates a handler with default US Eastern timezone.
106    pub fn us_eastern() -> Self {
107        Self::new(TimezoneConfig::default()).expect("Default timezone config should be valid")
108    }
109
110    /// Gets the timezone for a specific entity code.
111    ///
112    /// Matches entity code against patterns in this order:
113    /// 1. Exact match
114    /// 2. Prefix patterns (e.g., "EU_*")
115    /// 3. Suffix patterns (e.g., "*_APAC")
116    /// 4. Default timezone
117    pub fn get_entity_timezone(&self, entity_code: &str) -> Tz {
118        // Check exact match first
119        if let Some(tz) = self.entity_tz_cache.get(entity_code) {
120            return *tz;
121        }
122
123        // Check patterns
124        for (pattern, tz) in &self.entity_tz_cache {
125            if let Some(prefix) = pattern.strip_suffix('*') {
126                // Prefix pattern (e.g., "EU_*")
127                if entity_code.starts_with(prefix) {
128                    return *tz;
129                }
130            } else if let Some(suffix) = pattern.strip_prefix('*') {
131                // Suffix pattern (e.g., "*_APAC")
132                if entity_code.ends_with(suffix) {
133                    return *tz;
134                }
135            }
136        }
137
138        self.default_tz
139    }
140
141    /// Converts a local datetime to UTC for a specific entity.
142    pub fn to_utc(&self, local: NaiveDateTime, entity_code: &str) -> DateTime<Utc> {
143        let tz = self.get_entity_timezone(entity_code);
144        tz.from_local_datetime(&local)
145            .single()
146            .unwrap_or_else(|| tz.from_local_datetime(&local).earliest().unwrap())
147            .with_timezone(&Utc)
148    }
149
150    /// Converts a UTC datetime to local time for a specific entity.
151    pub fn to_local(&self, utc: DateTime<Utc>, entity_code: &str) -> NaiveDateTime {
152        let tz = self.get_entity_timezone(entity_code);
153        utc.with_timezone(&tz).naive_local()
154    }
155
156    /// Converts a local datetime to the consolidation timezone.
157    pub fn to_consolidation(&self, local: NaiveDateTime, entity_code: &str) -> DateTime<Tz> {
158        let utc = self.to_utc(local, entity_code);
159        utc.with_timezone(&self.consolidation_tz)
160    }
161
162    /// Returns the consolidation timezone.
163    pub fn consolidation_timezone(&self) -> Tz {
164        self.consolidation_tz
165    }
166
167    /// Returns the default timezone.
168    pub fn default_timezone(&self) -> Tz {
169        self.default_tz
170    }
171
172    /// Returns the timezone name for an entity.
173    pub fn get_timezone_name(&self, entity_code: &str) -> String {
174        self.get_entity_timezone(entity_code).name().to_string()
175    }
176
177    /// Calculates the UTC offset in hours for an entity at a given time.
178    pub fn get_utc_offset_hours(&self, entity_code: &str, at: NaiveDateTime) -> f64 {
179        let tz = self.get_entity_timezone(entity_code);
180        let offset = tz.offset_from_local_datetime(&at).single();
181        match offset {
182            Some(o) => o.fix().local_minus_utc() as f64 / 3600.0,
183            None => 0.0,
184        }
185    }
186
187    /// Returns a reference to the underlying configuration.
188    pub fn config(&self) -> &TimezoneConfig {
189        &self.config
190    }
191}
192
193/// Errors that can occur during timezone operations.
194#[derive(Debug, Clone)]
195pub enum TimezoneError {
196    /// Invalid timezone name.
197    InvalidTimezone(String),
198    /// Ambiguous local time (e.g., during DST transition).
199    AmbiguousTime(NaiveDateTime),
200}
201
202impl std::fmt::Display for TimezoneError {
203    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
204        match self {
205            TimezoneError::InvalidTimezone(tz) => {
206                write!(f, "Invalid timezone: '{}'. Use IANA timezone names.", tz)
207            }
208            TimezoneError::AmbiguousTime(dt) => {
209                write!(f, "Ambiguous local time: {}", dt)
210            }
211        }
212    }
213}
214
215impl std::error::Error for TimezoneError {}
216
217/// Common timezone presets for different regions.
218pub struct TimezonePresets;
219
220impl TimezonePresets {
221    /// US-centric configuration with NY as default.
222    pub fn us_centric() -> TimezoneConfig {
223        TimezoneConfig::new("America/New_York")
224            .with_consolidation("America/New_York")
225            .add_mapping("*_WEST", "America/Los_Angeles")
226            .add_mapping("*_CENTRAL", "America/Chicago")
227            .add_mapping("*_MOUNTAIN", "America/Denver")
228    }
229
230    /// Europe-centric configuration with London as default.
231    pub fn eu_centric() -> TimezoneConfig {
232        TimezoneConfig::new("Europe/London")
233            .with_consolidation("Europe/London")
234            .add_mapping("DE_*", "Europe/Berlin")
235            .add_mapping("FR_*", "Europe/Paris")
236            .add_mapping("CH_*", "Europe/Zurich")
237    }
238
239    /// Asia-Pacific configuration with Singapore as default.
240    pub fn apac_centric() -> TimezoneConfig {
241        TimezoneConfig::new("Asia/Singapore")
242            .with_consolidation("Asia/Singapore")
243            .add_mapping("JP_*", "Asia/Tokyo")
244            .add_mapping("CN_*", "Asia/Shanghai")
245            .add_mapping("IN_*", "Asia/Kolkata")
246            .add_mapping("AU_*", "Australia/Sydney")
247    }
248
249    /// Global configuration with UTC as consolidation.
250    pub fn global_utc() -> TimezoneConfig {
251        TimezoneConfig::new("America/New_York")
252            .with_consolidation("UTC")
253            .add_mapping("US_*", "America/New_York")
254            .add_mapping("EU_*", "Europe/London")
255            .add_mapping("APAC_*", "Asia/Singapore")
256    }
257}
258
259#[cfg(test)]
260mod tests {
261    use super::*;
262    use chrono::Timelike;
263
264    #[test]
265    fn test_default_timezone() {
266        let handler = TimezoneHandler::us_eastern();
267        let tz = handler.get_entity_timezone("UNKNOWN_COMPANY");
268        assert_eq!(tz.name(), "America/New_York");
269    }
270
271    #[test]
272    fn test_exact_match() {
273        let config = TimezoneConfig::new("America/New_York").add_mapping("1000", "Europe/London");
274        let handler = TimezoneHandler::new(config).unwrap();
275
276        assert_eq!(handler.get_entity_timezone("1000").name(), "Europe/London");
277        assert_eq!(
278            handler.get_entity_timezone("2000").name(),
279            "America/New_York"
280        );
281    }
282
283    #[test]
284    fn test_prefix_pattern() {
285        let config = TimezoneConfig::new("America/New_York").add_mapping("EU_*", "Europe/Berlin");
286        let handler = TimezoneHandler::new(config).unwrap();
287
288        assert_eq!(
289            handler.get_entity_timezone("EU_1000").name(),
290            "Europe/Berlin"
291        );
292        assert_eq!(
293            handler.get_entity_timezone("EU_SUBSIDIARY").name(),
294            "Europe/Berlin"
295        );
296        assert_eq!(
297            handler.get_entity_timezone("US_1000").name(),
298            "America/New_York"
299        );
300    }
301
302    #[test]
303    fn test_suffix_pattern() {
304        let config = TimezoneConfig::new("America/New_York").add_mapping("*_APAC", "Asia/Tokyo");
305        let handler = TimezoneHandler::new(config).unwrap();
306
307        assert_eq!(
308            handler.get_entity_timezone("1000_APAC").name(),
309            "Asia/Tokyo"
310        );
311        assert_eq!(
312            handler.get_entity_timezone("CORP_APAC").name(),
313            "Asia/Tokyo"
314        );
315        assert_eq!(
316            handler.get_entity_timezone("1000_US").name(),
317            "America/New_York"
318        );
319    }
320
321    #[test]
322    fn test_to_utc() {
323        let handler = TimezoneHandler::new(TimezoneConfig::new("America/New_York")).unwrap();
324
325        // 10 AM New York time
326        let local =
327            NaiveDateTime::parse_from_str("2024-06-15 10:00:00", "%Y-%m-%d %H:%M:%S").unwrap();
328        let utc = handler.to_utc(local, "US_1000");
329
330        // In June, NY is UTC-4 (EDT)
331        assert_eq!(utc.hour(), 14);
332    }
333
334    #[test]
335    fn test_to_local() {
336        let config = TimezoneConfig::new("America/New_York").add_mapping("EU_*", "Europe/London");
337        let handler = TimezoneHandler::new(config).unwrap();
338
339        // 12:00 UTC
340        let utc = DateTime::parse_from_rfc3339("2024-06-15T12:00:00Z")
341            .unwrap()
342            .with_timezone(&Utc);
343
344        // London in June is UTC+1 (BST)
345        let london_local = handler.to_local(utc, "EU_1000");
346        assert_eq!(london_local.hour(), 13);
347
348        // New York in June is UTC-4 (EDT)
349        let ny_local = handler.to_local(utc, "US_1000");
350        assert_eq!(ny_local.hour(), 8);
351    }
352
353    #[test]
354    fn test_presets() {
355        // Test that presets can be created without errors
356        let _ = TimezoneHandler::new(TimezonePresets::us_centric()).unwrap();
357        let _ = TimezoneHandler::new(TimezonePresets::eu_centric()).unwrap();
358        let _ = TimezoneHandler::new(TimezonePresets::apac_centric()).unwrap();
359        let _ = TimezoneHandler::new(TimezonePresets::global_utc()).unwrap();
360    }
361
362    #[test]
363    fn test_invalid_timezone() {
364        let config = TimezoneConfig::new("Invalid/Timezone");
365        let result = TimezoneHandler::new(config);
366        assert!(result.is_err());
367    }
368}