Skip to main content

uz_types/
birth_date.rs

1use chrono::{Datelike, NaiveDate, Utc};
2
3/// Sana formatlari.
4#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
5#[non_exhaustive]
6pub enum DateFormat {
7    /// `YYYY-MM-DD`
8    YmdHyphen,
9    /// `DD-MM-YYYY`
10    DmyHyphen,
11    /// `YYYY.MM.DD`
12    YmdDot,
13    /// `DD.MM.YYYY`
14    DmyDot,
15}
16
17impl DateFormat {
18    /// `strftime` shabloni (chrono uchun).
19    #[must_use]
20    pub const fn pattern(self) -> &'static str {
21        match self {
22            Self::YmdHyphen => "%Y-%m-%d",
23            Self::DmyHyphen => "%d-%m-%Y",
24            Self::YmdDot => "%Y.%m.%d",
25            Self::DmyDot => "%d.%m.%Y",
26        }
27    }
28
29    /// Kun/yil tartibini teskarisiga o'giradi.
30    #[must_use]
31    pub const fn reversed(self) -> Self {
32        match self {
33            Self::YmdHyphen => Self::DmyHyphen,
34            Self::DmyHyphen => Self::YmdHyphen,
35            Self::YmdDot => Self::DmyDot,
36            Self::DmyDot => Self::YmdDot,
37        }
38    }
39}
40
41/// Tug'ilgan sana: `MIN_YEAR` dan keyin va (yaratilish paytida) kelajakda emas.
42///
43/// Kelajak tekshiruvi **monoton**: bir marta qabul qilingan sana keyinchalik hech
44/// qachon rad etilmaydi — shuning uchun replay/`Deserialize` uchun xavfsiz.
45/// Deterministik testlar uchun `*_at(…, today)` variantlari bor.
46///
47/// [`MIN_YEAR`](Self::MIN_YEAR) — **sanity floor**, biznes qoidasi emas: yosh chegarasini
48/// (`>= 18`, `<= 120` va h.k.) [`age_at`](Self::age_at) bilan ilova qatlamida qo'ying.
49#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
50pub struct BirthDate(NaiveDate);
51
52impl BirthDate {
53    /// Standart format.
54    pub const DEFAULT_FORMAT: DateFormat = DateFormat::YmdHyphen;
55    /// Eng erta qabul qilinadigan yil.
56    ///
57    /// 1800 — chunki PINFL 1-raqami `1`/`2` bo'lganda asr 1800 bo'ladi
58    /// ([`Pinfl::century`](crate::Pinfl::century)); `1900` da [`Pinfl::birth_date`]
59    /// bunday PINFL uchun har doim `None` qaytarardi.
60    ///
61    /// [`Pinfl::birth_date`]: crate::Pinfl::birth_date
62    pub const MIN_YEAR: i32 = 1800;
63
64    /// `YYYY-MM-DD` dan (bugun = UTC).
65    pub fn parse(value: &str) -> Result<Self, BirthDateError> {
66        Self::parse_with_format(value, Self::DEFAULT_FORMAT)
67    }
68
69    /// Berilgan formatdan (bugun = UTC).
70    pub fn parse_with_format(value: &str, format: DateFormat) -> Result<Self, BirthDateError> {
71        Self::parse_with_format_at(value, format, Self::today_utc())
72    }
73
74    /// Deterministik variant: "bugun" tashqaridan beriladi.
75    pub fn parse_with_format_at(
76        value: &str,
77        format: DateFormat,
78        today: NaiveDate,
79    ) -> Result<Self, BirthDateError> {
80        let date = NaiveDate::parse_from_str(value.trim(), format.pattern())
81            .map_err(|_| BirthDateError::Date)?;
82        Self::from_naive_date_at(date, today)
83    }
84
85    /// `NaiveDate` dan (bugun = UTC).
86    pub fn from_naive_date(date: NaiveDate) -> Result<Self, BirthDateError> {
87        Self::from_naive_date_at(date, Self::today_utc())
88    }
89
90    /// `NaiveDate` dan, deterministik. Yuqori chegara: `today + 1` (UTC+14 gacha yon berish).
91    pub fn from_naive_date_at(date: NaiveDate, today: NaiveDate) -> Result<Self, BirthDateError> {
92        if date.year() < Self::MIN_YEAR {
93            return Err(BirthDateError::TooOld);
94        }
95        if date > today.succ_opt().unwrap_or(today) {
96            return Err(BirthDateError::FutureDate);
97        }
98        Ok(Self(date))
99    }
100
101    /// Soatga murojaat qilinadigan **yagona** joy.
102    fn today_utc() -> NaiveDate {
103        Utc::now().date_naive()
104    }
105
106    /// Ichki `NaiveDate`.
107    #[inline]
108    #[must_use]
109    pub fn as_naive_date(&self) -> NaiveDate {
110        self.0
111    }
112
113    /// Formatlangan matn.
114    #[must_use]
115    pub fn format_as(&self, format: DateFormat) -> String {
116        self.0.format(format.pattern()).to_string()
117    }
118
119    /// Yil / oy / kun.
120    #[must_use]
121    pub fn year(&self) -> i32 {
122        self.0.year()
123    }
124    /// Oy (1..=12).
125    #[must_use]
126    pub fn month(&self) -> u32 {
127        self.0.month()
128    }
129    /// Kun (1..=31).
130    #[must_use]
131    pub fn day(&self) -> u32 {
132        self.0.day()
133    }
134
135    /// Bugungi (UTC) to'liq yosh.
136    #[must_use]
137    pub fn age(&self) -> u32 {
138        self.age_at(Self::today_utc())
139    }
140
141    /// Berilgan sanadagi to'liq yosh (deterministik).
142    #[must_use]
143    pub fn age_at(&self, date: NaiveDate) -> u32 {
144        if date <= self.0 {
145            return 0;
146        }
147        let mut years = date.year() - self.0.year();
148        if (date.month(), date.day()) < (self.0.month(), self.0.day()) {
149            years -= 1;
150        }
151        u32::try_from(years).unwrap_or(0)
152    }
153}
154
155impl core::fmt::Display for BirthDate {
156    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
157        write!(f, "{}", self.0.format(Self::DEFAULT_FORMAT.pattern()))
158    }
159}
160
161impl core::str::FromStr for BirthDate {
162    type Err = BirthDateError;
163    fn from_str(s: &str) -> Result<Self, BirthDateError> {
164        Self::parse(s)
165    }
166}
167
168impl TryFrom<&str> for BirthDate {
169    type Error = BirthDateError;
170    fn try_from(value: &str) -> Result<Self, BirthDateError> {
171        Self::parse(value)
172    }
173}
174
175impl TryFrom<String> for BirthDate {
176    type Error = BirthDateError;
177    fn try_from(value: String) -> Result<Self, BirthDateError> {
178        Self::parse(&value)
179    }
180}
181
182impl TryFrom<NaiveDate> for BirthDate {
183    type Error = BirthDateError;
184    fn try_from(value: NaiveDate) -> Result<Self, BirthDateError> {
185        Self::from_naive_date(value)
186    }
187}
188
189impl From<BirthDate> for NaiveDate {
190    fn from(value: BirthDate) -> Self {
191        value.0
192    }
193}
194
195impl AsRef<NaiveDate> for BirthDate {
196    fn as_ref(&self) -> &NaiveDate {
197        &self.0
198    }
199}
200
201#[cfg(feature = "serde")]
202impl serde::Serialize for BirthDate {
203    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
204        serializer.collect_str(self)
205    }
206}
207
208#[cfg(feature = "serde")]
209impl<'de> serde::Deserialize<'de> for BirthDate {
210    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
211        crate::serde_support::deserialize_string_newtype(
212            deserializer,
213            "a birth date in YYYY-MM-DD format",
214        )
215    }
216}
217
218#[cfg(any(feature = "sqlx-0_8", feature = "sqlx-0_9"))]
219crate::sqlx_support::sqlx_via!(
220    BirthDate,
221    NaiveDate,
222    |d: NaiveDate| BirthDate::from_naive_date(d),
223    |this: &BirthDate| &this.0
224);
225
226/// `BirthDate` validatsiya xatolari.
227#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
228#[non_exhaustive]
229pub enum BirthDateError {
230    /// Format yoki qiymat noto'g'ri.
231    #[error("invalid birth date format or value")]
232    Date,
233    /// Kelajak sanasi.
234    #[error("birth date cannot be in the future")]
235    FutureDate,
236    /// `MIN_YEAR` dan oldin.
237    #[error(
238        "birth date is too far in the past, year must be >= {}",
239        BirthDate::MIN_YEAR
240    )]
241    TooOld,
242}
243
244#[cfg(test)]
245mod tests {
246    use super::*;
247
248    #[test]
249    fn deterministic_boundaries() {
250        let today = NaiveDate::from_ymd_opt(2026, 9, 3).unwrap();
251        assert!(BirthDate::from_naive_date_at(today.succ_opt().unwrap(), today).is_ok());
252        assert_eq!(
253            BirthDate::parse_with_format_at("2026-09-05", DateFormat::YmdHyphen, today),
254            Err(BirthDateError::FutureDate)
255        );
256        // MIN_YEAR = 1800: PINFL 1-raqami `1`/`2` bo'lganda asr 1800 bo'ladi.
257        assert!(BirthDate::parse("1800-01-01").is_ok());
258        assert_eq!(BirthDate::parse("1799-12-31"), Err(BirthDateError::TooOld));
259        assert_eq!(BirthDate::parse("15.05.1990"), Err(BirthDateError::Date));
260        assert_eq!(BirthDate::parse("1990-05-15").unwrap().age_at(today), 36);
261    }
262}