Skip to main content

aylis_data/
value.rs

1//! Valores dos campos: [`Value`] (o "Variant" tipado), [`Decimal`] para dinheiro e
2//! [`Date`]/[`Time`]/[`DateTime`].
3
4use std::cmp::Ordering;
5use std::fmt;
6
7/// Valor de um campo. `Null` é explícito (como o `IsNull` do `TField`).
8#[derive(Clone, Debug, Default, PartialEq)]
9pub enum Value {
10    #[default]
11    Null,
12    Bool(bool),
13    Int(i64),
14    Float(f64),
15    /// Ponto fixo exato (dinheiro), como o `Currency`/BCD do Delphi.
16    Decimal(Decimal),
17    String(String),
18    Date(Date),
19    Time(Time),
20    DateTime(DateTime),
21    /// Um instante (a hora do pedido, o log de auditoria), guardado em UTC e mostrado no
22    /// fuso de quem vê, como o `ftTimeStampOffset` do FireDAC.
23    Timestamp(Timestamp),
24    Blob(Vec<u8>),
25}
26
27impl Value {
28    pub fn is_null(&self) -> bool {
29        matches!(self, Value::Null)
30    }
31
32    pub fn as_bool(&self) -> Option<bool> {
33        match self {
34            Value::Bool(b) => Some(*b),
35            _ => None,
36        }
37    }
38
39    pub fn as_i64(&self) -> Option<i64> {
40        match self {
41            Value::Int(v) => Some(*v),
42            Value::Float(v) if v.fract() == 0.0 => Some(*v as i64),
43            Value::Decimal(d) => d.to_i64(),
44            _ => None,
45        }
46    }
47
48    pub fn as_f64(&self) -> Option<f64> {
49        match self {
50            Value::Int(v) => Some(*v as f64),
51            Value::Float(v) => Some(*v),
52            Value::Decimal(d) => Some(d.to_f64()),
53            _ => None,
54        }
55    }
56
57    pub fn as_decimal(&self) -> Option<Decimal> {
58        match self {
59            Value::Decimal(d) => Some(*d),
60            Value::Int(v) => Some(Decimal::new(*v as i128, 0)),
61            Value::Float(v) => Decimal::from_f64(*v, 6),
62            _ => None,
63        }
64    }
65
66    pub fn as_str(&self) -> Option<&str> {
67        match self {
68            Value::String(s) => Some(s),
69            _ => None,
70        }
71    }
72
73    pub fn as_date(&self) -> Option<Date> {
74        match self {
75            Value::Date(d) => Some(*d),
76            Value::DateTime(dt) => Some(dt.date),
77            Value::Timestamp(ts) => Some(ts.to_local().date),
78            _ => None,
79        }
80    }
81
82    pub fn kind_name(&self) -> &'static str {
83        match self {
84            Value::Null => "nulo",
85            Value::Bool(_) => "lógico",
86            Value::Int(_) => "inteiro",
87            Value::Float(_) => "número",
88            Value::Decimal(_) => "decimal",
89            Value::String(_) => "texto",
90            Value::Date(_) => "data",
91            Value::Time(_) => "hora",
92            Value::DateTime(_) => "data e hora",
93            Value::Timestamp(_) => "instante",
94            Value::Blob(_) => "binário",
95        }
96    }
97}
98
99/// Texto neutro (ISO): `2024-05-01`, `13:45:00`, `1234.56`. A formatação para o usuário
100/// fica com o `Field` (display_format e idioma).
101impl fmt::Display for Value {
102    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103        match self {
104            Value::Null => Ok(()),
105            Value::Bool(b) => write!(f, "{b}"),
106            Value::Int(v) => write!(f, "{v}"),
107            Value::Float(v) => write!(f, "{v}"),
108            Value::Decimal(d) => write!(f, "{d}"),
109            Value::String(s) => f.write_str(s),
110            Value::Date(d) => write!(f, "{d}"),
111            Value::Time(t) => write!(f, "{t}"),
112            Value::DateTime(dt) => write!(f, "{dt}"),
113            Value::Timestamp(ts) => write!(f, "{ts}"),
114            Value::Blob(b) => write!(f, "({} bytes)", b.len()),
115        }
116    }
117}
118
119impl From<bool> for Value {
120    fn from(v: bool) -> Self {
121        Value::Bool(v)
122    }
123}
124
125impl From<i32> for Value {
126    fn from(v: i32) -> Self {
127        Value::Int(v as i64)
128    }
129}
130
131impl From<i64> for Value {
132    fn from(v: i64) -> Self {
133        Value::Int(v)
134    }
135}
136
137impl From<f64> for Value {
138    fn from(v: f64) -> Self {
139        Value::Float(v)
140    }
141}
142
143impl From<&str> for Value {
144    fn from(v: &str) -> Self {
145        Value::String(v.to_string())
146    }
147}
148
149impl From<String> for Value {
150    fn from(v: String) -> Self {
151        Value::String(v)
152    }
153}
154
155impl From<Decimal> for Value {
156    fn from(v: Decimal) -> Self {
157        Value::Decimal(v)
158    }
159}
160
161impl From<Date> for Value {
162    fn from(v: Date) -> Self {
163        Value::Date(v)
164    }
165}
166
167impl From<Time> for Value {
168    fn from(v: Time) -> Self {
169        Value::Time(v)
170    }
171}
172
173impl From<DateTime> for Value {
174    fn from(v: DateTime) -> Self {
175        Value::DateTime(v)
176    }
177}
178
179impl From<Timestamp> for Value {
180    fn from(v: Timestamp) -> Self {
181        Value::Timestamp(v)
182    }
183}
184
185impl<T: Into<Value>> From<Option<T>> for Value {
186    fn from(v: Option<T>) -> Self {
187        v.map_or(Value::Null, Into::into)
188    }
189}
190
191// ---------------------------------------------------------------------------
192
193/// Número decimal de ponto fixo: `mantissa × 10^-scale`. Exato para dinheiro.
194#[derive(Clone, Copy, Debug)]
195pub struct Decimal {
196    mantissa: i128,
197    scale: u8,
198}
199
200impl Decimal {
201    pub const ZERO: Decimal = Decimal { mantissa: 0, scale: 0 };
202
203    /// `Decimal::new(12345, 2)` = 123,45.
204    pub const fn new(mantissa: i128, scale: u8) -> Self {
205        Self { mantissa, scale }
206    }
207
208    pub fn mantissa(&self) -> i128 {
209        self.mantissa
210    }
211
212    pub fn scale(&self) -> u8 {
213        self.scale
214    }
215
216    /// Lê `"-1234.56"` (separador decimal `.`, sem separador de milhar).
217    pub fn parse(text: &str) -> Option<Decimal> {
218        Self::parse_with(text, '.')
219    }
220
221    /// Lê com o separador decimal dado (sem separador de milhar).
222    pub fn parse_with(text: &str, decimal_separator: char) -> Option<Decimal> {
223        let text = text.trim();
224        let (negative, digits) = match text.strip_prefix('-') {
225            Some(rest) => (true, rest),
226            None => (false, text.strip_prefix('+').unwrap_or(text)),
227        };
228        let (int, frac) = match digits.split_once(decimal_separator) {
229            Some((i, f)) => (i, f),
230            None => (digits, ""),
231        };
232        if (int.is_empty() && frac.is_empty())
233            || !int.chars().all(|c| c.is_ascii_digit())
234            || !frac.chars().all(|c| c.is_ascii_digit())
235            || frac.len() > 28
236        {
237            return None;
238        }
239        let mut mantissa: i128 = 0;
240        for c in int.chars().chain(frac.chars()) {
241            mantissa = mantissa.checked_mul(10)?.checked_add(c.to_digit(10)? as i128)?;
242        }
243        Some(Decimal { mantissa: if negative { -mantissa } else { mantissa }, scale: frac.len() as u8 })
244    }
245
246    /// Converte arredondando para `scale` casas.
247    pub fn from_f64(value: f64, scale: u8) -> Option<Decimal> {
248        if !value.is_finite() {
249            return None;
250        }
251        let factor = 10f64.powi(scale as i32);
252        Some(Decimal { mantissa: (value * factor).round() as i128, scale })
253    }
254
255    pub fn to_f64(&self) -> f64 {
256        self.mantissa as f64 / 10f64.powi(self.scale as i32)
257    }
258
259    pub fn to_i64(&self) -> Option<i64> {
260        let r = self.checked_rescale(0, Rounding::HalfUp)?;
261        i64::try_from(r.mantissa).ok()
262    }
263
264    /// Muda o número de casas, arredondando metade para longe do zero. Entra em pânico se o
265    /// número não couber (só com valores perto de 10³⁸); para tratar, [`checked_rescale`](Self::checked_rescale).
266    pub fn rescale(&self, scale: u8) -> Decimal {
267        self.checked_rescale(scale, Rounding::HalfUp).unwrap_or_else(|| panic!("estouro do decimal: {self} com {scale} casas"))
268    }
269
270    /// Muda o número de casas, arredondando do jeito `mode`; `None` se não couber.
271    pub fn checked_rescale(&self, scale: u8, mode: Rounding) -> Option<Decimal> {
272        if scale > MAX_SCALE {
273            return None;
274        }
275        match scale.cmp(&self.scale) {
276            Ordering::Equal => Some(*self),
277            Ordering::Greater => Some(Decimal { mantissa: self.mantissa.checked_mul(10i128.checked_pow((scale - self.scale) as u32)?)?, scale }),
278            Ordering::Less => Some(Decimal { mantissa: div_round(self.mantissa, 10i128.pow((self.scale - scale) as u32), mode)?, scale }),
279        }
280    }
281
282    /// Arredonda para `scale` casas do jeito `mode` (o `RoundTo` do Delphi, com o modo).
283    pub fn round(&self, scale: u8, mode: Rounding) -> Option<Decimal> {
284        self.checked_rescale(scale, mode)
285    }
286
287    pub fn checked_add(&self, other: &Decimal) -> Option<Decimal> {
288        let scale = self.scale.max(other.scale);
289        let (a, b) = (self.checked_rescale(scale, Rounding::HalfUp)?, other.checked_rescale(scale, Rounding::HalfUp)?);
290        Some(Decimal { mantissa: a.mantissa.checked_add(b.mantissa)?, scale })
291    }
292
293    pub fn checked_sub(&self, other: &Decimal) -> Option<Decimal> {
294        self.checked_add(&Decimal { mantissa: other.mantissa.checked_neg()?, scale: other.scale })
295    }
296
297    /// O produto exato (as casas somam); se passar de [`MAX_SCALE`], arredonda metade para
298    /// cima até caber.
299    pub fn checked_mul(&self, other: &Decimal) -> Option<Decimal> {
300        let product = Decimal { mantissa: self.mantissa.checked_mul(other.mantissa)?, scale: self.scale.checked_add(other.scale)? };
301        if product.scale > MAX_SCALE { product.reduce(MAX_SCALE, Rounding::HalfUp) } else { Some(product) }
302    }
303
304    /// A divisão exata com `scale` casas no resultado, arredondada do jeito `mode` (sem passar
305    /// por `f64`: 0,30 / 0,10 = 3). `None` se `other` é zero ou se não couber.
306    pub fn checked_div(&self, other: &Decimal, scale: u8, mode: Rounding) -> Option<Decimal> {
307        if other.mantissa == 0 || scale > MAX_SCALE {
308            return None;
309        }
310        // resultado = (a / 10^sa) / (b / 10^sb), com `scale` casas: a · 10^(scale + sb − sa) / b.
311        let exponent = scale as i32 + other.scale as i32 - self.scale as i32;
312        let (n, d) = if exponent >= 0 {
313            (self.mantissa.checked_mul(10i128.checked_pow(exponent as u32)?)?, other.mantissa)
314        } else {
315            (self.mantissa, other.mantissa.checked_mul(10i128.checked_pow((-exponent) as u32)?)?)
316        };
317        Some(Decimal { mantissa: div_round(n, d, mode)?, scale })
318    }
319
320    /// As casas da divisão quando ninguém diz quantas: as do maior dos dois mais 4, como o
321    /// `Currency` do Delphi (100,00 / 3 = 33,333333).
322    pub fn default_div_scale(&self, other: &Decimal) -> u8 {
323        (self.scale.max(other.scale) + 4).min(MAX_SCALE)
324    }
325
326    /// Corta casas até `scale` (só para menos casas).
327    fn reduce(&self, scale: u8, mode: Rounding) -> Option<Decimal> {
328        Some(Decimal { mantissa: div_round(self.mantissa, 10i128.checked_pow((self.scale - scale) as u32)?, mode)?, scale })
329    }
330
331    pub fn is_negative(&self) -> bool {
332        self.mantissa < 0
333    }
334
335    /// Partes inteira e fracionária (com `scale` dígitos), sem sinal.
336    pub(crate) fn parts(&self) -> (u128, String) {
337        let abs = self.mantissa.unsigned_abs();
338        let factor = 10u128.pow(self.scale as u32);
339        let frac = abs % factor;
340        let frac = if self.scale == 0 { String::new() } else { format!("{frac:0width$}", width = self.scale as usize) };
341        (abs / factor, frac)
342    }
343}
344
345/// O máximo de casas de um [`Decimal`] (o `i128` guarda uns 38 dígitos no total).
346pub const MAX_SCALE: u8 = 28;
347
348/// Como arredondar ao cortar casas.
349#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
350pub enum Rounding {
351    /// Metade para longe do zero: 2,345 → 2,35 (o `SimpleRoundTo` do Delphi). O padrão.
352    #[default]
353    HalfUp,
354    /// Metade para o par, o "bancário": 2,345 → 2,34 e 2,355 → 2,36 (o `Round` do Delphi).
355    HalfEven,
356    /// Corta as casas: 2,349 → 2,34 (o `Trunc`).
357    Truncate,
358    /// Para longe do zero sempre que sobra algo: 2,341 → 2,35.
359    Up,
360}
361
362impl aylis_core::prop::PropEnum for Rounding {
363    const NAMES: &'static [&'static str] = &["half_up", "half_even", "truncate", "up"];
364
365    fn from_index(index: usize) -> Option<Self> {
366        [Rounding::HalfUp, Rounding::HalfEven, Rounding::Truncate, Rounding::Up].get(index).copied()
367    }
368
369    fn index(self) -> usize {
370        self as usize
371    }
372}
373
374impl Rounding {
375    /// Pelo nome (`"half_even"`); `None` se não for um dos quatro.
376    pub fn from_name(name: &str) -> Option<Rounding> {
377        use aylis_core::prop::PropEnum;
378        Rounding::NAMES.iter().position(|n| n.eq_ignore_ascii_case(name)).and_then(Rounding::from_index)
379    }
380}
381
382/// `n / d` arredondado do jeito `mode` (`d` diferente de zero). `None` só no caso que não
383/// cabe (`i128::MIN / −1`).
384fn div_round(n: i128, d: i128, mode: Rounding) -> Option<i128> {
385    let q = n.checked_div(d)?;
386    let r = n % d;
387    if r == 0 {
388        return Some(q);
389    }
390    let away = if (n < 0) != (d < 0) { -1 } else { 1 };
391    let (r, d) = (r.unsigned_abs(), d.unsigned_abs());
392    // Comparar o resto com a metade sem dobrar (dobrar poderia estourar).
393    let half = r.cmp(&(d - r));
394    let bump = match mode {
395        Rounding::Truncate => false,
396        Rounding::Up => true,
397        Rounding::HalfUp => half != Ordering::Less,
398        Rounding::HalfEven => half == Ordering::Greater || (half == Ordering::Equal && q % 2 != 0),
399    };
400    if bump { q.checked_add(away) } else { Some(q) }
401}
402
403/// Os operadores, como o `Currency` do Delphi. Estouro entra em pânico (como os inteiros);
404/// para tratar, os `checked_*`. A divisão usa [`Decimal::default_div_scale`] e arredonda
405/// metade para cima; dividir por zero entra em pânico.
406impl std::ops::Add for Decimal {
407    type Output = Decimal;
408    fn add(self, other: Decimal) -> Decimal {
409        self.checked_add(&other).unwrap_or_else(|| panic!("estouro do decimal: {self} + {other}"))
410    }
411}
412
413impl std::ops::Sub for Decimal {
414    type Output = Decimal;
415    fn sub(self, other: Decimal) -> Decimal {
416        self.checked_sub(&other).unwrap_or_else(|| panic!("estouro do decimal: {self} - {other}"))
417    }
418}
419
420impl std::ops::Mul for Decimal {
421    type Output = Decimal;
422    fn mul(self, other: Decimal) -> Decimal {
423        self.checked_mul(&other).unwrap_or_else(|| panic!("estouro do decimal: {self} * {other}"))
424    }
425}
426
427impl std::ops::Div for Decimal {
428    type Output = Decimal;
429    fn div(self, other: Decimal) -> Decimal {
430        assert!(other.mantissa != 0, "divisão por zero: {self} / {other}");
431        self.checked_div(&other, self.default_div_scale(&other), Rounding::HalfUp).unwrap_or_else(|| panic!("estouro do decimal: {self} / {other}"))
432    }
433}
434
435impl std::ops::Neg for Decimal {
436    type Output = Decimal;
437    fn neg(self) -> Decimal {
438        Decimal { mantissa: self.mantissa.checked_neg().expect("estouro do decimal ao trocar o sinal"), scale: self.scale }
439    }
440}
441
442impl From<i64> for Decimal {
443    fn from(v: i64) -> Self {
444        Decimal { mantissa: v as i128, scale: 0 }
445    }
446}
447
448impl PartialEq for Decimal {
449    fn eq(&self, other: &Self) -> bool {
450        self.cmp(other) == Ordering::Equal
451    }
452}
453
454impl Eq for Decimal {}
455
456impl PartialOrd for Decimal {
457    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
458        Some(self.cmp(other))
459    }
460}
461
462impl Ord for Decimal {
463    fn cmp(&self, other: &Self) -> Ordering {
464        let scale = self.scale.max(other.scale);
465        match (self.checked_rescale(scale, Rounding::HalfUp), other.checked_rescale(scale, Rounding::HalfUp)) {
466            (Some(a), Some(b)) => a.mantissa.cmp(&b.mantissa),
467            // Perto de 10³⁸ as casas não cabem: a parte inteira decide (e a fração, se empatar).
468            _ => {
469                let (a, b) = (self.parts(), other.parts());
470                let signed = |neg: bool, o: Ordering| if neg { o.reverse() } else { o };
471                match (self.is_negative(), other.is_negative()) {
472                    (true, false) => Ordering::Less,
473                    (false, true) => Ordering::Greater,
474                    (neg, _) => signed(neg, a.0.cmp(&b.0).then_with(|| {
475                        let width = a.1.len().max(b.1.len());
476                        format!("{:0<width$}", a.1).cmp(&format!("{:0<width$}", b.1))
477                    })),
478                }
479            }
480        }
481    }
482}
483
484impl fmt::Display for Decimal {
485    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
486        let (int, frac) = self.parts();
487        let sign = if self.is_negative() { "-" } else { "" };
488        if frac.is_empty() { write!(f, "{sign}{int}") } else { write!(f, "{sign}{int}.{frac}") }
489    }
490}
491
492// ---------------------------------------------------------------------------
493
494/// Data do calendário (sem fuso).
495#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
496pub struct Date {
497    year: i32,
498    month: u8,
499    day: u8,
500}
501
502impl Date {
503    /// `None` se a data não existir (31/02, mês 13...).
504    pub fn new(year: i32, month: u8, day: u8) -> Option<Date> {
505        (1..=12).contains(&month).then_some(())?;
506        (day >= 1 && day <= days_in_month(year, month)).then_some(Date { year, month, day })
507    }
508
509    pub fn year(&self) -> i32 {
510        self.year
511    }
512
513    pub fn month(&self) -> u8 {
514        self.month
515    }
516
517    pub fn day(&self) -> u8 {
518        self.day
519    }
520
521    /// Dias desde 1970-01-01 (negativos antes).
522    pub fn to_days(&self) -> i64 {
523        let (y, m, d) = (self.year as i64 - i64::from(self.month <= 2), self.month as i64, self.day as i64);
524        let era = y.div_euclid(400);
525        let yoe = y - era * 400;
526        let doy = (153 * (m + if m > 2 { -3 } else { 9 }) + 2) / 5 + d - 1;
527        era * 146_097 + yoe * 365 + yoe / 4 - yoe / 100 + doy - 719_468
528    }
529
530    /// A data `days` dias depois de 1970-01-01.
531    pub fn from_days(days: i64) -> Option<Date> {
532        let z = days + 719_468;
533        let era = z.div_euclid(146_097);
534        let doe = z - era * 146_097;
535        let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
536        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
537        let mp = (5 * doy + 2) / 153;
538        let d = (doy - (153 * mp + 2) / 5 + 1) as u8;
539        let m = if mp < 10 { mp + 3 } else { mp - 9 } as u8;
540        let y = yoe + era * 400 + i64::from(m <= 2);
541        Date::new(i32::try_from(y).ok()?, m, d)
542    }
543
544    /// Hoje, no horário local (o `Date` do Delphi): em Brasília, às 22h ainda é hoje.
545    pub fn today() -> Date {
546        DateTime::now().date
547    }
548
549    /// Lê `yyyy-mm-dd`.
550    pub fn parse_iso(text: &str) -> Option<Date> {
551        let mut parts = text.trim().splitn(3, '-');
552        let y = parts.next()?.parse().ok()?;
553        let m = parts.next()?.parse().ok()?;
554        let d = parts.next()?.parse().ok()?;
555        Date::new(y, m, d)
556    }
557}
558
559impl fmt::Display for Date {
560    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
561        write!(f, "{:04}-{:02}-{:02}", self.year, self.month, self.day)
562    }
563}
564
565pub fn is_leap_year(year: i32) -> bool {
566    (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
567}
568
569pub fn days_in_month(year: i32, month: u8) -> u8 {
570    match month {
571        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
572        4 | 6 | 9 | 11 => 30,
573        2 if is_leap_year(year) => 29,
574        2 => 28,
575        _ => 0,
576    }
577}
578
579/// Hora do dia.
580#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
581pub struct Time {
582    hour: u8,
583    minute: u8,
584    second: u8,
585    millisecond: u16,
586}
587
588impl Time {
589    pub fn new(hour: u8, minute: u8, second: u8) -> Option<Time> {
590        Self::with_millis(hour, minute, second, 0)
591    }
592
593    pub fn with_millis(hour: u8, minute: u8, second: u8, millisecond: u16) -> Option<Time> {
594        (hour < 24 && minute < 60 && second < 60 && millisecond < 1000).then_some(Time { hour, minute, second, millisecond })
595    }
596
597    pub fn hour(&self) -> u8 {
598        self.hour
599    }
600
601    pub fn minute(&self) -> u8 {
602        self.minute
603    }
604
605    pub fn second(&self) -> u8 {
606        self.second
607    }
608
609    pub fn millisecond(&self) -> u16 {
610        self.millisecond
611    }
612
613    /// Lê `hh:nn`, `hh:nn:ss` ou `hh:nn:ss.fff` (sem fuso; veja [`DateTime::parse_iso`]).
614    pub fn parse_iso(text: &str) -> Option<Time> {
615        let mut parts = text.trim().split(':');
616        let h = parts.next()?.parse().ok()?;
617        let m = parts.next()?.parse().ok()?;
618        let (s, ms) = match parts.next() {
619            None => (0, 0),
620            Some(s) => {
621                let (whole, frac) = s.split_once('.').unwrap_or((s, ""));
622                // Os três primeiros dígitos da fração (o resto não cabe em milissegundos).
623                let digits: String = frac.chars().take(3).collect();
624                let ms = if digits.is_empty() { 0 } else { format!("{digits:0<3}").parse().ok()? };
625                (whole.parse().ok()?, ms)
626            }
627        };
628        if parts.next().is_some() {
629            return None;
630        }
631        Time::with_millis(h, m, s, ms)
632    }
633
634    fn seconds_of_day(&self) -> i64 {
635        self.hour as i64 * 3600 + self.minute as i64 * 60 + self.second as i64
636    }
637}
638
639impl fmt::Display for Time {
640    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
641        write!(f, "{:02}:{:02}:{:02}", self.hour, self.minute, self.second)
642    }
643}
644
645/// Data e hora.
646#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
647pub struct DateTime {
648    pub date: Date,
649    pub time: Time,
650}
651
652impl DateTime {
653    pub fn new(date: Date, time: Time) -> Self {
654        Self { date, time }
655    }
656
657    /// Lê `yyyy-mm-ddThh:nn:ss` (ou com espaço no lugar do `T`, com fração de segundo). Com
658    /// fuso (`Z`, `-03:00`, `+0530`), o instante vira o horário local desta tela: um backend
659    /// que manda `13:00:00Z` mostra 10:00 em Brasília. O fuso nunca é ignorado.
660    pub fn parse_iso(text: &str) -> Option<DateTime> {
661        let text = text.trim();
662        let (d, t) = text.split_once(['T', ' ']).unwrap_or((text, "00:00:00"));
663        let (t, offset) = split_offset(t)?;
664        let local = DateTime { date: Date::parse_iso(d)?, time: Time::parse_iso(t)? };
665        match offset {
666            None => Some(local),
667            Some(offset) => DateTime::from_unix_local(local.to_unix() - offset, local.time.millisecond()),
668        }
669    }
670
671    /// Segundos desde 1970, lendo esta data e hora como se fosse UTC.
672    pub fn to_unix(&self) -> i64 {
673        self.date.to_days() * 86_400 + self.time.seconds_of_day()
674    }
675
676    /// A data e a hora (sem fuso) de `secs` segundos desde 1970.
677    pub fn from_unix(secs: i64, millisecond: u16) -> Option<DateTime> {
678        let date = Date::from_days(secs.div_euclid(86_400))?;
679        let s = secs.rem_euclid(86_400);
680        let time = Time::with_millis((s / 3600) as u8, (s / 60 % 60) as u8, (s % 60) as u8, millisecond)?;
681        Some(DateTime { date, time })
682    }
683
684    /// O instante `utc` (segundos desde 1970) no horário local desta tela (com horário de
685    /// verão, pelo sistema; sem a plataforma, como nos testes, o local é o UTC).
686    pub fn from_unix_local(utc: i64, millisecond: u16) -> Option<DateTime> {
687        DateTime::from_unix(utc + aylis_core::platform::local_offset(utc), millisecond)
688    }
689
690    /// Agora, no horário local (o `Now` do Delphi).
691    pub fn now() -> DateTime {
692        let since = web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).unwrap_or_default();
693        DateTime::from_unix_local(since.as_secs() as i64, since.subsec_millis() as u16).expect("o relógio do sistema dá uma data válida")
694    }
695}
696
697/// Separa o fuso do fim da hora: `"10:00:00-03:00"` → (`"10:00:00"`, −10800 segundos);
698/// `Z` é o UTC; sem fuso, `None`. `None` no todo se o fuso for inválido.
699fn split_offset(time: &str) -> Option<(&str, Option<i64>)> {
700    if let Some(t) = time.strip_suffix(['Z', 'z']) {
701        return Some((t, Some(0)));
702    }
703    // O sinal do fuso vem depois dos dois-pontos da hora (não confunde com nada antes).
704    let Some(at) = time.rfind(['+', '-']).filter(|&i| i > 0) else { return Some((time, None)) };
705    let (t, zone) = time.split_at(at);
706    let sign = if zone.starts_with('-') { -1 } else { 1 };
707    let digits: String = zone[1..].chars().filter(|c| *c != ':').collect();
708    let (h, m) = match digits.len() {
709        2 => (digits.parse::<i64>().ok()?, 0),
710        4 => (digits[..2].parse::<i64>().ok()?, digits[2..].parse::<i64>().ok()?),
711        _ => return None,
712    };
713    (h <= 14 && m < 60).then_some((t, Some(sign * (h * 3600 + m * 60))))
714}
715
716impl fmt::Display for DateTime {
717    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
718        write!(f, "{}T{}", self.date, self.time)
719    }
720}
721
722/// Um instante: milissegundos desde 1970 em UTC. É o mesmo momento em qualquer fuso; para
723/// mostrar, vira o horário local de quem vê ([`to_local`](Self::to_local)). Use para o que
724/// aconteceu num momento (a hora do pedido, a última alteração); para uma data ou hora do
725/// calendário (vencimento, aniversário), o [`DateTime`].
726#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
727pub struct Timestamp {
728    millis: i64,
729}
730
731impl Timestamp {
732    pub fn from_unix_millis(millis: i64) -> Timestamp {
733        Timestamp { millis }
734    }
735
736    pub fn unix_millis(&self) -> i64 {
737        self.millis
738    }
739
740    pub fn now() -> Timestamp {
741        let since = web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).unwrap_or_default();
742        Timestamp { millis: since.as_millis() as i64 }
743    }
744
745    /// O horário local desta tela neste instante.
746    pub fn to_local(&self) -> DateTime {
747        DateTime::from_unix_local(self.millis.div_euclid(1000), self.millis.rem_euclid(1000) as u16).expect("um instante válido")
748    }
749
750    /// O instante de um horário local desta tela (o que o usuário digitou).
751    pub fn from_local(local: DateTime) -> Timestamp {
752        let wall = local.to_unix();
753        // O fuso depende do instante (horário de verão): a primeira conta usa o fuso do
754        // horário de parede, e a segunda acerta com o do instante encontrado.
755        let first = wall - aylis_core::platform::local_offset(wall);
756        let utc = wall - aylis_core::platform::local_offset(first);
757        Timestamp { millis: utc * 1000 + local.time.millisecond() as i64 }
758    }
759
760    /// Lê ISO com fuso (`2026-11-02T13:00:00Z`, `...-03:00`); sem fuso, é o horário local.
761    pub fn parse_iso(text: &str) -> Option<Timestamp> {
762        let text = text.trim();
763        let (d, t) = text.split_once(['T', ' ']).unwrap_or((text, "00:00:00"));
764        let (t, offset) = split_offset(t)?;
765        let wall = DateTime { date: Date::parse_iso(d)?, time: Time::parse_iso(t)? };
766        Some(match offset {
767            Some(offset) => Timestamp { millis: (wall.to_unix() - offset) * 1000 + wall.time.millisecond() as i64 },
768            None => Timestamp::from_local(wall),
769        })
770    }
771}
772
773/// Em UTC, com milissegundos: `2026-11-02T13:00:00.000Z` (o que o protocolo manda).
774impl fmt::Display for Timestamp {
775    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
776        let utc = DateTime::from_unix(self.millis.div_euclid(1000), 0).ok_or(fmt::Error)?;
777        write!(f, "{}T{}.{:03}Z", utc.date, utc.time, self.millis.rem_euclid(1000))
778    }
779}