Skip to main content

qimen_core/
request.rs

1//! Optional calculation settings without coupling the calendar crate to Qimen.
2
3use serde::{Deserialize, Deserializer, Serialize, de};
4use serde_json::{Map, Value};
5use std::fmt;
6
7use crate::{Chart, ChartRequest, Error, ExtensionOptions};
8
9/// A reusable deterministic calculator configured once for many civil inputs.
10///
11/// The default enables no extensions. Each selected annotation records its rule
12/// in the result. Configuration does not change the base chart construction.
13///
14/// ```
15/// let calculator = qimen_core::Calculator::new(qimen_core::ExtensionOptions::all());
16/// let chart = calculator.calculate(&qimen_core::ChartRequest::new(2026, 9, 18, 18))?;
17/// assert!(chart.extensions.is_some());
18/// # Ok::<(), qimen_core::Error>(())
19/// ```
20#[derive(Debug, Clone, Default, PartialEq, Eq)]
21pub struct Calculator {
22    extensions: ExtensionOptions,
23}
24
25impl Calculator {
26    /// Creates a calculator with explicitly selected extension rules.
27    #[must_use]
28    pub const fn new(extensions: ExtensionOptions) -> Self {
29        Self { extensions }
30    }
31
32    /// Returns the immutable configuration used for every calculation.
33    #[must_use]
34    pub const fn extensions(&self) -> &ExtensionOptions {
35        &self.extensions
36    }
37
38    /// Calculates one chart, validating the civil input before any annotations.
39    pub fn calculate(&self, request: &ChartRequest) -> Result<Chart, Error> {
40        calculate_with_options(request, &self.extensions)
41    }
42}
43
44/// Calculates a chart with per-call extension settings.
45///
46/// [`crate::calculate`] remains the convenient entry point with all extensions
47/// disabled. Both paths use exactly the same calendrical and plate calculations.
48pub fn calculate_with_options(
49    request: &ChartRequest,
50    extensions: &ExtensionOptions,
51) -> Result<Chart, Error> {
52    let mut chart = crate::calculate(request)?;
53    if !extensions.is_empty() {
54        chart.extensions = Some(crate::extensions::calculate(&chart, extensions));
55    }
56    Ok(chart)
57}
58
59/// The shared JSON/MCP request: civil fields plus optional `extensions`.
60///
61/// Civil fields retain their original flat JSON layout. Rust stores them in the
62/// independent calendar request, avoiding a second copy of its validation rules.
63/// Unknown civil fields, extension names, and rule values are rejected.
64#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
65#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
66#[serde(deny_unknown_fields)]
67pub struct CalculationRequest {
68    /// Gregorian civil input; serialized at the top level of the JSON object.
69    #[serde(flatten)]
70    pub calendar: ChartRequest,
71    /// Optional annotations, all disabled when omitted or empty.
72    #[serde(default, skip_serializing_if = "ExtensionOptions::is_empty")]
73    pub extensions: ExtensionOptions,
74}
75
76impl CalculationRequest {
77    /// Calculates with the supplied calendar input and extension configuration.
78    pub fn calculate(&self) -> Result<Chart, Error> {
79        calculate_with_options(&self.calendar, &self.extensions)
80    }
81}
82
83impl From<ChartRequest> for CalculationRequest {
84    fn from(calendar: ChartRequest) -> Self {
85        Self {
86            calendar,
87            extensions: ExtensionOptions::default(),
88        }
89    }
90}
91
92impl<'de> Deserialize<'de> for CalculationRequest {
93    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
94        // Serde's derived flatten + deny_unknown_fields combination cannot be
95        // relied on for strict nested requests. Remove only our owned key, then
96        // pass all remaining civil keys through CalendarRequest's strict parser.
97        deserializer.deserialize_map(RequestVisitor)
98    }
99}
100
101struct RequestVisitor;
102
103impl<'de> de::Visitor<'de> for RequestVisitor {
104    type Value = CalculationRequest;
105
106    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
107        formatter.write_str("civil date fields and optional named extensions")
108    }
109
110    fn visit_map<A: de::MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
111        let mut civil = Map::new();
112        let mut extensions = None;
113        while let Some(key) = map.next_key::<String>()? {
114            if key == "extensions" {
115                if extensions.is_some() {
116                    return Err(de::Error::duplicate_field("extensions"));
117                }
118                // Validate the object and rule shapes before the option derive.
119                extensions = Some(map.next_value::<OptionsObject>()?.0);
120            } else {
121                if civil.contains_key(&key) {
122                    return Err(de::Error::custom(format!("duplicate field `{key}`")));
123                }
124                civil.insert(key, map.next_value::<Value>()?);
125            }
126        }
127        let calendar = serde_json::from_value(Value::Object(civil)).map_err(de::Error::custom)?;
128        Ok(CalculationRequest {
129            calendar,
130            extensions: extensions.unwrap_or_default(),
131        })
132    }
133}
134
135// Struct derives can also accept positional sequences; the public request
136// contract requires an object of string/null rules. Check duplicate keys and
137// shapes before passing the values through ExtensionOptions' named-rule parser.
138struct OptionsObject(ExtensionOptions);
139
140impl<'de> Deserialize<'de> for OptionsObject {
141    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
142        struct OptionsVisitor;
143
144        impl<'de> de::Visitor<'de> for OptionsVisitor {
145            type Value = OptionsObject;
146
147            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
148                formatter.write_str("an object of named extension rules")
149            }
150
151            fn visit_map<A: de::MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
152                let mut rules = Map::new();
153                while let Some(key) = map.next_key::<String>()? {
154                    if rules.contains_key(&key) {
155                        return Err(de::Error::custom(format!("duplicate field `{key}`")));
156                    }
157                    let rule = map.next_value::<Option<String>>()?;
158                    rules.insert(key, rule.map_or(Value::Null, Value::String));
159                }
160                serde_json::from_value(Value::Object(rules))
161                    .map(OptionsObject)
162                    .map_err(de::Error::custom)
163            }
164        }
165
166        deserializer.deserialize_map(OptionsVisitor)
167    }
168}