Skip to main content

uz_types/
pinfl.rs

1use crate::{calendar::is_valid_gregorian_date, macros::string_newtype};
2
3string_newtype! {
4    /// JShShIR / PINFL — 14 raqamli shaxsiy identifikatsiya raqami.
5    ///
6    /// `parse()` faqat **strukturani** (14 ta ASCII raqam) tekshiradi.
7    /// Nazorat raqami, jins/asr belgisi va tug'ilgan sana — query metodlar
8    /// (`is_checksum_valid`, `gender`, `birth_date`) yoki [`Pinfl::parse_strict`].
9    pub struct Pinfl;
10    error = PinflError;
11    expecting = "a PINFL: exactly 14 digits";
12}
13
14/// PINFL 1-raqamidan olinadigan jins.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
16#[non_exhaustive]
17pub enum Gender {
18    /// Erkak (1-raqam toq: 1, 3, 5).
19    Male,
20    /// Ayol (1-raqam juft: 2, 4, 6).
21    Female,
22}
23
24impl Pinfl {
25    /// Uzunlik — aynan 14 raqam.
26    pub const LEN: usize = 14;
27
28    /// Nazorat raqami vaznlari (VM qarori №177, 12.04.2022: "7 3 1" takrorlanadi, modul 10).
29    ///
30    /// Rasmiy manba: <https://lex.uz/uz/docs/-5955665>.
31    const WEIGHTS: [u32; 3] = [7, 3, 1];
32
33    fn normalize(_: &mut str) {}
34
35    fn validate(s: &str) -> Result<(), PinflError> {
36        if !s.is_ascii() {
37            return Err(PinflError::Format);
38        }
39        if s.len() != Self::LEN {
40            return Err(PinflError::Length);
41        }
42        if !s.bytes().all(|b| b.is_ascii_digit()) {
43            return Err(PinflError::Format);
44        }
45        Ok(())
46    }
47
48    /// Struktura + nazorat raqami + jins/asr belgisi + to'liq Gregorian sana.
49    ///
50    /// Sana tekshiruvi `date` feature'idan mustaqil: `31.02` yoki `29.02.1900`
51    /// checksum'i to'g'ri bo'lsa ham [`PinflError::Structure`] qaytaradi.
52    pub fn parse_strict(value: &str) -> Result<Self, PinflError> {
53        let pinfl = Self::parse(value)?;
54        if !pinfl.is_checksum_valid() {
55            return Err(PinflError::Checksum);
56        }
57        if pinfl.gender().is_none() || pinfl.birth_date_parts().is_none() {
58            return Err(PinflError::Structure);
59        }
60        Ok(pinfl)
61    }
62
63    #[inline]
64    fn digit(&self, index: usize) -> u32 {
65        u32::from(self.0.as_bytes()[index] - b'0')
66    }
67
68    /// 14-raqam rasmiy algoritm bo'yicha to'g'rimi (7‑3‑1 vaznlar, mod 10).
69    #[must_use]
70    pub fn is_checksum_valid(&self) -> bool {
71        let sum: u32 = (0..Self::LEN - 1)
72            .map(|i| self.digit(i) * Self::WEIGHTS[i % 3])
73            .sum();
74        sum % 10 == self.digit(Self::LEN - 1)
75    }
76
77    /// 1-raqam: jins (1,3,5 — erkak; 2,4,6 — ayol). Boshqa qiymat → `None`.
78    #[must_use]
79    pub fn gender(&self) -> Option<Gender> {
80        match self.digit(0) {
81            1 | 3 | 5 => Some(Gender::Male),
82            2 | 4 | 6 => Some(Gender::Female),
83            _ => None,
84        }
85    }
86
87    /// 1-raqam: asr (1,2 → 1800; 3,4 → 1900; 5,6 → 2000).
88    #[must_use]
89    pub fn century(&self) -> Option<i32> {
90        match self.digit(0) {
91            1 | 2 => Some(1800),
92            3 | 4 => Some(1900),
93            5 | 6 => Some(2000),
94            _ => None,
95        }
96    }
97
98    /// 2–7 raqamlar `DDMMYY` + asr → `(yil, oy, kun)`.
99    ///
100    /// Faqat to'liq Gregorian sana haqiqiy bo'lsa qiymat qaytaradi.
101    #[must_use]
102    pub fn birth_date_parts(&self) -> Option<(i32, u32, u32)> {
103        let century = self.century()?;
104        let day = self.digit(1) * 10 + self.digit(2);
105        let month = self.digit(3) * 10 + self.digit(4);
106        let year = century + i32::try_from(self.digit(5) * 10 + self.digit(6)).ok()?;
107        is_valid_gregorian_date(year, month, day).then_some((year, month, day))
108    }
109
110    /// 8–10 raqamlar: tug'ilgan hudud kodi.
111    #[inline]
112    #[must_use]
113    pub fn region_code(&self) -> &str {
114        &self.0[7..10]
115    }
116
117    /// 11–13 raqamlar: tartib raqami.
118    #[inline]
119    #[must_use]
120    pub fn serial(&self) -> &str {
121        &self.0[10..13]
122    }
123
124    /// PINFL ichidagi tug'ilgan sana (kalendar bo'yicha haqiqiy bo'lsa).
125    ///
126    /// **Tizim soatiga (UTC) tayanadi** — `BirthDate` kelajak sanasini rad etadi,
127    /// shuning uchun 2000-yillar PINFL'i (`5`/`6` + `YY` kelajakda) bugungi kunga
128    /// qarab `Some`/`None` bo'ladi. Testlarda [`birth_date_at`](Self::birth_date_at).
129    #[cfg(feature = "date")]
130    #[must_use]
131    pub fn birth_date(&self) -> Option<crate::BirthDate> {
132        let (y, m, d) = self.birth_date_parts()?;
133        let date = chrono::NaiveDate::from_ymd_opt(y, m, d)?;
134        crate::BirthDate::from_naive_date(date).ok()
135    }
136
137    /// [`birth_date`](Self::birth_date) ning deterministik varianti — "bugun" tashqaridan.
138    #[cfg(feature = "date")]
139    #[must_use]
140    pub fn birth_date_at(&self, today: chrono::NaiveDate) -> Option<crate::BirthDate> {
141        let (y, m, d) = self.birth_date_parts()?;
142        let date = chrono::NaiveDate::from_ymd_opt(y, m, d)?;
143        crate::BirthDate::from_naive_date_at(date, today).ok()
144    }
145}
146
147/// `Pinfl` validatsiya xatolari.
148#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
149#[non_exhaustive]
150pub enum PinflError {
151    /// 14 ta raqam emas.
152    #[error("pinfl length is invalid, expected 14 digits")]
153    Length,
154    /// Raqamdan boshqa belgi bor.
155    #[error("pinfl format is invalid, expected only digits")]
156    Format,
157    /// Nazorat raqami mos kelmaydi (faqat `parse_strict`).
158    #[error("pinfl checksum is invalid")]
159    Checksum,
160    /// Jins/asr belgisi yoki tug'ilgan sana strukturasi noto'g'ri (faqat `parse_strict`).
161    #[error("pinfl structure is invalid (gender/century digit or birth date)")]
162    Structure,
163}
164
165#[cfg(test)]
166mod tests {
167    use super::*;
168
169    // Rasmiy hujjatlardagi misollar: VM qarori №200 (1996) va №177 (2022).
170    const OFFICIAL_1996: &str = "31210632040244";
171    const OFFICIAL_2022: &str = "31210932040247";
172    const OFFICIAL_2022_FEMALE: &str = "40201902050010";
173
174    #[test]
175    fn official_examples_pass_strict() {
176        for s in [OFFICIAL_1996, OFFICIAL_2022] {
177            let p = Pinfl::parse_strict(s).unwrap();
178            assert!(p.is_checksum_valid());
179            assert_eq!(p.gender(), Some(Gender::Male));
180            assert_eq!(p.century(), Some(1900));
181            assert_eq!(p.region_code(), "204");
182            assert_eq!(p.serial(), "024");
183        }
184        assert_eq!(
185            Pinfl::parse(OFFICIAL_1996).unwrap().birth_date_parts(),
186            Some((1963, 10, 12))
187        );
188        assert_eq!(
189            Pinfl::parse(OFFICIAL_2022).unwrap().birth_date_parts(),
190            Some((1993, 10, 12))
191        );
192
193        let female = Pinfl::parse_strict(OFFICIAL_2022_FEMALE).unwrap();
194        assert!(female.is_checksum_valid());
195        assert_eq!(female.gender(), Some(Gender::Female));
196        assert_eq!(female.century(), Some(1900));
197        assert_eq!(female.birth_date_parts(), Some((1990, 1, 2)));
198        assert_eq!(female.region_code(), "205");
199        assert_eq!(female.serial(), "001");
200    }
201
202    fn with_checksum(body: &str) -> String {
203        assert_eq!(body.len(), Pinfl::LEN - 1);
204        assert!(body.bytes().all(|byte| byte.is_ascii_digit()));
205
206        let sum: u32 = body
207            .bytes()
208            .enumerate()
209            .map(|(index, byte)| u32::from(byte - b'0') * Pinfl::WEIGHTS[index % 3])
210            .sum();
211        format!("{body}{}", sum % 10)
212    }
213
214    #[test]
215    fn strict_parse_requires_a_valid_gregorian_date() {
216        for body in ["3310290204024", "3310490204024", "3290200204024"] {
217            let value = with_checksum(body);
218            assert!(Pinfl::parse(&value).is_ok());
219            assert_eq!(Pinfl::parse_strict(&value), Err(PinflError::Structure));
220        }
221
222        let leap_day = with_checksum("5290200204024");
223        assert!(Pinfl::parse(&leap_day).is_ok());
224        assert!(Pinfl::parse_strict(&leap_day).is_ok());
225        assert_eq!(
226            Pinfl::parse(&leap_day).unwrap().birth_date_parts(),
227            Some((2000, 2, 29))
228        );
229    }
230
231    #[test]
232    fn structural_parse_is_lenient_strict_is_not() {
233        let zeros = "00000000000000";
234        assert!(Pinfl::parse(zeros).is_ok()); // struktura: 14 raqam
235        assert_eq!(Pinfl::parse_strict(zeros), Err(PinflError::Structure)); // checksum 0 == 0, lekin 1-raqam 0
236        assert_eq!(
237            Pinfl::parse_strict("31210632040245"),
238            Err(PinflError::Checksum)
239        );
240        assert_eq!(Pinfl::parse("1234567890123"), Err(PinflError::Length));
241        assert_eq!(Pinfl::parse("123456789012345"), Err(PinflError::Length));
242        assert_eq!(Pinfl::parse("1234567890123a"), Err(PinflError::Format));
243        assert_eq!(Pinfl::parse("З1210632040247"), Err(PinflError::Format));
244    }
245
246    #[cfg(feature = "date")]
247    #[test]
248    fn birth_date_is_extracted() {
249        let p = Pinfl::parse(OFFICIAL_2022).unwrap();
250        assert_eq!(p.birth_date().unwrap().to_string(), "1993-10-12");
251    }
252
253    #[cfg(feature = "date")]
254    #[test]
255    fn birth_date_at_is_deterministic() {
256        let today = chrono::NaiveDate::from_ymd_opt(2026, 9, 3).unwrap();
257
258        // 1-raqam `1`/`2` → asr 1800. BirthDate::MIN_YEAR = 1900 bo'lganda bu
259        // har doim None qaytarardi — MIN_YEAR = 1800 aynan shu teshikni yopdi.
260        let old = Pinfl::parse("11210632040244").unwrap();
261        assert_eq!(old.century(), Some(1800));
262        assert_eq!(
263            old.birth_date_at(today).unwrap().to_string(),
264            "1863-10-12" // 12.10.63 + 1800
265        );
266
267        // 2000-yillar: `5`/`6` + kelajakdagi YY → BirthDate rad etadi (soatga bog'liq emas)
268        let future = Pinfl::parse("51210992040244").unwrap();
269        assert_eq!(future.birth_date_parts(), Some((2099, 10, 12)));
270        assert_eq!(future.birth_date_at(today), None);
271    }
272}