datasynth_core/distributions/
timezone.rs1use chrono::{DateTime, NaiveDateTime, Offset, TimeZone, Utc};
9use chrono_tz::Tz;
10use serde::{Deserialize, Serialize};
11use std::collections::HashMap;
12
13#[derive(Debug, Clone, Serialize, Deserialize)]
15pub struct TimezoneConfig {
16 pub default_timezone: String,
18 pub entity_timezones: HashMap<String, String>,
20 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 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 pub fn with_consolidation(mut self, tz: &str) -> Self {
46 self.consolidation_timezone = tz.to_string();
47 self
48 }
49
50 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#[derive(Debug, Clone)]
65pub struct TimezoneHandler {
66 config: TimezoneConfig,
67 default_tz: Tz,
69 consolidation_tz: Tz,
71 entity_tz_cache: HashMap<String, Tz>,
73}
74
75impl TimezoneHandler {
76 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 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 pub fn us_eastern() -> Self {
107 Self::new(TimezoneConfig::default()).expect("Default timezone config should be valid")
108 }
109
110 pub fn get_entity_timezone(&self, entity_code: &str) -> Tz {
118 if let Some(tz) = self.entity_tz_cache.get(entity_code) {
120 return *tz;
121 }
122
123 for (pattern, tz) in &self.entity_tz_cache {
125 if let Some(prefix) = pattern.strip_suffix('*') {
126 if entity_code.starts_with(prefix) {
128 return *tz;
129 }
130 } else if let Some(suffix) = pattern.strip_prefix('*') {
131 if entity_code.ends_with(suffix) {
133 return *tz;
134 }
135 }
136 }
137
138 self.default_tz
139 }
140
141 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 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 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 pub fn consolidation_timezone(&self) -> Tz {
164 self.consolidation_tz
165 }
166
167 pub fn default_timezone(&self) -> Tz {
169 self.default_tz
170 }
171
172 pub fn get_timezone_name(&self, entity_code: &str) -> String {
174 self.get_entity_timezone(entity_code).name().to_string()
175 }
176
177 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 pub fn config(&self) -> &TimezoneConfig {
189 &self.config
190 }
191}
192
193#[derive(Debug, Clone)]
195pub enum TimezoneError {
196 InvalidTimezone(String),
198 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
217pub struct TimezonePresets;
219
220impl TimezonePresets {
221 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 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 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 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 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 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 let utc = DateTime::parse_from_rfc3339("2024-06-15T12:00:00Z")
341 .unwrap()
342 .with_timezone(&Utc);
343
344 let london_local = handler.to_local(utc, "EU_1000");
346 assert_eq!(london_local.hour(), 13);
347
348 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 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}