Skip to main content

qimen_calendar/
model.rs

1use serde::{Deserialize, Serialize};
2use thiserror::Error;
3
4use crate::Cycle;
5
6/// Civil-clock convention for the day pillar.
7#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize)]
8#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
9#[serde(rename_all = "snake_case")]
10pub enum DayBoundary {
11    /// Change the day pillar at 23:00, at the start of 子时.
12    #[default]
13    ZiStart,
14    /// Change the day pillar at 00:00. The 23:00 子 hour still uses the following
15    /// day's stem for its hour pillar, preserving one pillar across 子时.
16    Midnight,
17}
18
19impl<'de> Deserialize<'de> for DayBoundary {
20    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
21        // The public schema uses a string enum, not Serde's alternative
22        // single-key map representation for externally tagged unit variants.
23        match String::deserialize(deserializer)?.as_str() {
24            "zi_start" => Ok(Self::ZiStart),
25            "midnight" => Ok(Self::Midnight),
26            value => Err(serde::de::Error::unknown_variant(
27                value,
28                &["zi_start", "midnight"],
29            )),
30        }
31    }
32}
33
34const fn default_offset() -> i32 {
35    480
36}
37
38/// Proleptic Gregorian input and explicit calculation conventions.
39///
40/// Missing JSON `minute` and `second` default to zero, `utc_offset_minutes` to
41/// 480 (UTC+08:00), and `day_boundary` to `zi_start`. Unknown fields are rejected
42/// so a misspelled convention cannot silently change the result.
43#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
44#[serde(deny_unknown_fields)]
45#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
46pub struct CalendarRequest {
47    /// Proleptic Gregorian year, inclusive range 1–9999.
48    pub year: i32,
49    /// Gregorian month, 1–12.
50    pub month: u32,
51    /// Gregorian day, validated against the month and year.
52    pub day: u32,
53    /// Local civil hour, 0–23.
54    pub hour: u32,
55    /// Local civil minute, 0–59.
56    #[serde(default)]
57    pub minute: u32,
58    /// Local civil second, 0–59; leap seconds are not accepted.
59    #[serde(default)]
60    pub second: u32,
61    /// Fixed offset east of UTC, in minutes, from −840 through +840.
62    /// Supply the offset actually applicable at the requested date, including DST.
63    #[serde(default = "default_offset")]
64    pub utc_offset_minutes: i32,
65    /// Day-pillar rollover convention.
66    #[serde(default)]
67    pub day_boundary: DayBoundary,
68}
69
70impl CalendarRequest {
71    /// Creates a request at the given hour, in UTC+08:00 with 子初 day rollover.
72    /// Validation is performed by [`crate::calculate`].
73    #[must_use]
74    pub const fn new(year: i32, month: u32, day: u32, hour: u32) -> Self {
75        Self {
76            year,
77            month,
78            day,
79            hour,
80            minute: 0,
81            second: 0,
82            utc_offset_minutes: 480,
83            day_boundary: DayBoundary::ZiStart,
84        }
85    }
86}
87
88/// An unambiguous second-resolution civil timestamp with a fixed UTC offset.
89#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
90#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
91pub struct CivilDateTime {
92    /// Proleptic Gregorian year. Adjacent term timestamps can use 0 or 10000.
93    pub year: i32,
94    /// Gregorian month, 1–12.
95    pub month: u32,
96    /// Gregorian day, 1–31.
97    pub day: u32,
98    /// Local hour, 0–23.
99    pub hour: u32,
100    /// Local minute, 0–59.
101    pub minute: u32,
102    /// Local second, 0–59.
103    pub second: u32,
104    /// Minutes east of UTC.
105    pub utc_offset_minutes: i32,
106}
107
108/// The four sexagenary pillars, with exact term boundaries for year and month.
109#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
110#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
111pub struct FourPillars {
112    /// Year pillar, changing at 立春.
113    pub year: Cycle,
114    /// Month pillar, changing at the twelve 节 instants.
115    pub month: Cycle,
116    /// Day pillar under the selected local-clock rollover convention.
117    pub day: Cycle,
118    /// Hour pillar; 子时 begins at 23:00.
119    pub hour: Cycle,
120}
121
122/// One solar-term boundary in the request's fixed UTC offset.
123#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
124#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
125pub struct SolarTerm {
126    /// Traditional index: 冬至 = 0, 小寒 = 1, …, 大雪 = 23.
127    pub index: u8,
128    /// Chinese name.
129    pub name: String,
130    /// Calculated start instant, at second resolution.
131    pub start: CivilDateTime,
132}
133
134/// Modern Chinese lunar-calendar rules applied to the local Gregorian date.
135///
136/// Months begin on the Beijing civil date containing an astronomical new moon.
137/// Winter solstice belongs to month 11; a thirteen-month winter cycle uses its
138/// first month without a principal term as the leap month. These rules are
139/// extended before their historical adoption and into the future. This is not
140/// a reconstruction of ancient calendar reforms or a lunar calendar recalculated
141/// for the request's timezone.
142#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
143#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
144pub struct LunarDate {
145    /// Lunar calendar year; early input dates in year 1 can belong to year 0.
146    pub year: i32,
147    /// Lunar month number, 1–12.
148    pub month: u32,
149    /// Lunar day number, 1–30.
150    pub day: u32,
151    /// Whether the month is an intercalary month.
152    pub is_leap_month: bool,
153    /// Traditional Chinese display label.
154    pub name: String,
155}
156
157/// Calendar data required for a reproducible Qimen chart.
158#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
159#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
160pub struct CalendarResult {
161    /// Computed year, month, day and hour pillars.
162    pub four_pillars: FourPillars,
163    /// Most recent solar term; equality belongs to this new term.
164    pub solar_term: SolarTerm,
165    /// The following solar term, useful for boundary verification.
166    pub next_solar_term: SolarTerm,
167    /// Chinese lunar calendar label for the input civil date.
168    pub lunar_date: LunarDate,
169}
170
171/// A rejected input or calendar conversion failure.
172#[derive(Debug, Clone, PartialEq, Eq, Error)]
173pub enum CalendarError {
174    /// The public, tested Gregorian year range was exceeded.
175    #[error("year must be between 1 and 9999 inclusive, got {0}")]
176    UnsupportedYear(i32),
177    /// The supplied civil offset exceeds the accepted range.
178    #[error("utc_offset_minutes must be between -840 and 840 inclusive, got {0}")]
179    InvalidUtcOffset(i32),
180    /// An invalid Gregorian date or civil time was supplied.
181    #[error("invalid Gregorian date or time: {0}")]
182    InvalidDateTime(String),
183    /// The astronomical provider could not produce a consistent conversion.
184    #[error("calendar conversion failed: {0}")]
185    ConversionFailed(String),
186}