stripe_shared/
recurring.rs

1#[derive(Clone, Debug)]
2#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
3#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
4pub struct Recurring {
5    /// The frequency at which a subscription is billed. One of `day`, `week`, `month` or `year`.
6    pub interval: RecurringInterval,
7    /// The number of intervals (specified in the `interval` attribute) between subscription billings.
8    /// For example, `interval=month` and `interval_count=3` bills every 3 months.
9    pub interval_count: u64,
10    /// The meter tracking the usage of a metered price
11    pub meter: Option<String>,
12    /// Default number of trial days when subscribing a customer to this price using [`trial_from_plan=true`](https://stripe.com/docs/api#create_subscription-trial_from_plan).
13    pub trial_period_days: Option<u32>,
14    /// Configures how the quantity per period should be determined.
15    /// Can be either `metered` or `licensed`.
16    /// `licensed` automatically bills the `quantity` set when adding it to a subscription.
17    /// `metered` aggregates the total usage based on usage records.
18    /// Defaults to `licensed`.
19    pub usage_type: RecurringUsageType,
20}
21#[doc(hidden)]
22pub struct RecurringBuilder {
23    interval: Option<RecurringInterval>,
24    interval_count: Option<u64>,
25    meter: Option<Option<String>>,
26    trial_period_days: Option<Option<u32>>,
27    usage_type: Option<RecurringUsageType>,
28}
29
30#[allow(
31    unused_variables,
32    irrefutable_let_patterns,
33    clippy::let_unit_value,
34    clippy::match_single_binding,
35    clippy::single_match
36)]
37const _: () = {
38    use miniserde::de::{Map, Visitor};
39    use miniserde::json::Value;
40    use miniserde::{Deserialize, Result, make_place};
41    use stripe_types::miniserde_helpers::FromValueOpt;
42    use stripe_types::{MapBuilder, ObjectDeser};
43
44    make_place!(Place);
45
46    impl Deserialize for Recurring {
47        fn begin(out: &mut Option<Self>) -> &mut dyn Visitor {
48            Place::new(out)
49        }
50    }
51
52    struct Builder<'a> {
53        out: &'a mut Option<Recurring>,
54        builder: RecurringBuilder,
55    }
56
57    impl Visitor for Place<Recurring> {
58        fn map(&mut self) -> Result<Box<dyn Map + '_>> {
59            Ok(Box::new(Builder { out: &mut self.out, builder: RecurringBuilder::deser_default() }))
60        }
61    }
62
63    impl MapBuilder for RecurringBuilder {
64        type Out = Recurring;
65        fn key(&mut self, k: &str) -> Result<&mut dyn Visitor> {
66            Ok(match k {
67                "interval" => Deserialize::begin(&mut self.interval),
68                "interval_count" => Deserialize::begin(&mut self.interval_count),
69                "meter" => Deserialize::begin(&mut self.meter),
70                "trial_period_days" => Deserialize::begin(&mut self.trial_period_days),
71                "usage_type" => Deserialize::begin(&mut self.usage_type),
72                _ => <dyn Visitor>::ignore(),
73            })
74        }
75
76        fn deser_default() -> Self {
77            Self {
78                interval: Deserialize::default(),
79                interval_count: Deserialize::default(),
80                meter: Deserialize::default(),
81                trial_period_days: Deserialize::default(),
82                usage_type: Deserialize::default(),
83            }
84        }
85
86        fn take_out(&mut self) -> Option<Self::Out> {
87            let (
88                Some(interval),
89                Some(interval_count),
90                Some(meter),
91                Some(trial_period_days),
92                Some(usage_type),
93            ) = (
94                self.interval.take(),
95                self.interval_count,
96                self.meter.take(),
97                self.trial_period_days,
98                self.usage_type.take(),
99            )
100            else {
101                return None;
102            };
103            Some(Self::Out { interval, interval_count, meter, trial_period_days, usage_type })
104        }
105    }
106
107    impl Map for Builder<'_> {
108        fn key(&mut self, k: &str) -> Result<&mut dyn Visitor> {
109            self.builder.key(k)
110        }
111
112        fn finish(&mut self) -> Result<()> {
113            *self.out = self.builder.take_out();
114            Ok(())
115        }
116    }
117
118    impl ObjectDeser for Recurring {
119        type Builder = RecurringBuilder;
120    }
121
122    impl FromValueOpt for Recurring {
123        fn from_value(v: Value) -> Option<Self> {
124            let Value::Object(obj) = v else {
125                return None;
126            };
127            let mut b = RecurringBuilder::deser_default();
128            for (k, v) in obj {
129                match k.as_str() {
130                    "interval" => b.interval = FromValueOpt::from_value(v),
131                    "interval_count" => b.interval_count = FromValueOpt::from_value(v),
132                    "meter" => b.meter = FromValueOpt::from_value(v),
133                    "trial_period_days" => b.trial_period_days = FromValueOpt::from_value(v),
134                    "usage_type" => b.usage_type = FromValueOpt::from_value(v),
135                    _ => {}
136                }
137            }
138            b.take_out()
139        }
140    }
141};
142/// The frequency at which a subscription is billed. One of `day`, `week`, `month` or `year`.
143#[derive(Clone, Eq, PartialEq)]
144#[non_exhaustive]
145pub enum RecurringInterval {
146    Day,
147    Month,
148    Week,
149    Year,
150    /// An unrecognized value from Stripe. Should not be used as a request parameter.
151    Unknown(String),
152}
153impl RecurringInterval {
154    pub fn as_str(&self) -> &str {
155        use RecurringInterval::*;
156        match self {
157            Day => "day",
158            Month => "month",
159            Week => "week",
160            Year => "year",
161            Unknown(v) => v,
162        }
163    }
164}
165
166impl std::str::FromStr for RecurringInterval {
167    type Err = std::convert::Infallible;
168    fn from_str(s: &str) -> Result<Self, Self::Err> {
169        use RecurringInterval::*;
170        match s {
171            "day" => Ok(Day),
172            "month" => Ok(Month),
173            "week" => Ok(Week),
174            "year" => Ok(Year),
175            v => {
176                tracing::warn!("Unknown value '{}' for enum '{}'", v, "RecurringInterval");
177                Ok(Unknown(v.to_owned()))
178            }
179        }
180    }
181}
182impl std::fmt::Display for RecurringInterval {
183    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
184        f.write_str(self.as_str())
185    }
186}
187
188impl std::fmt::Debug for RecurringInterval {
189    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
190        f.write_str(self.as_str())
191    }
192}
193#[cfg(feature = "serialize")]
194impl serde::Serialize for RecurringInterval {
195    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
196    where
197        S: serde::Serializer,
198    {
199        serializer.serialize_str(self.as_str())
200    }
201}
202impl miniserde::Deserialize for RecurringInterval {
203    fn begin(out: &mut Option<Self>) -> &mut dyn miniserde::de::Visitor {
204        crate::Place::new(out)
205    }
206}
207
208impl miniserde::de::Visitor for crate::Place<RecurringInterval> {
209    fn string(&mut self, s: &str) -> miniserde::Result<()> {
210        use std::str::FromStr;
211        self.out = Some(RecurringInterval::from_str(s).expect("infallible"));
212        Ok(())
213    }
214}
215
216stripe_types::impl_from_val_with_from_str!(RecurringInterval);
217#[cfg(feature = "deserialize")]
218impl<'de> serde::Deserialize<'de> for RecurringInterval {
219    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
220        use std::str::FromStr;
221        let s: std::borrow::Cow<'de, str> = serde::Deserialize::deserialize(deserializer)?;
222        Ok(Self::from_str(&s).expect("infallible"))
223    }
224}
225/// Configures how the quantity per period should be determined.
226/// Can be either `metered` or `licensed`.
227/// `licensed` automatically bills the `quantity` set when adding it to a subscription.
228/// `metered` aggregates the total usage based on usage records.
229/// Defaults to `licensed`.
230#[derive(Clone, Eq, PartialEq)]
231#[non_exhaustive]
232pub enum RecurringUsageType {
233    Licensed,
234    Metered,
235    /// An unrecognized value from Stripe. Should not be used as a request parameter.
236    Unknown(String),
237}
238impl RecurringUsageType {
239    pub fn as_str(&self) -> &str {
240        use RecurringUsageType::*;
241        match self {
242            Licensed => "licensed",
243            Metered => "metered",
244            Unknown(v) => v,
245        }
246    }
247}
248
249impl std::str::FromStr for RecurringUsageType {
250    type Err = std::convert::Infallible;
251    fn from_str(s: &str) -> Result<Self, Self::Err> {
252        use RecurringUsageType::*;
253        match s {
254            "licensed" => Ok(Licensed),
255            "metered" => Ok(Metered),
256            v => {
257                tracing::warn!("Unknown value '{}' for enum '{}'", v, "RecurringUsageType");
258                Ok(Unknown(v.to_owned()))
259            }
260        }
261    }
262}
263impl std::fmt::Display for RecurringUsageType {
264    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
265        f.write_str(self.as_str())
266    }
267}
268
269impl std::fmt::Debug for RecurringUsageType {
270    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
271        f.write_str(self.as_str())
272    }
273}
274#[cfg(feature = "serialize")]
275impl serde::Serialize for RecurringUsageType {
276    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
277    where
278        S: serde::Serializer,
279    {
280        serializer.serialize_str(self.as_str())
281    }
282}
283impl miniserde::Deserialize for RecurringUsageType {
284    fn begin(out: &mut Option<Self>) -> &mut dyn miniserde::de::Visitor {
285        crate::Place::new(out)
286    }
287}
288
289impl miniserde::de::Visitor for crate::Place<RecurringUsageType> {
290    fn string(&mut self, s: &str) -> miniserde::Result<()> {
291        use std::str::FromStr;
292        self.out = Some(RecurringUsageType::from_str(s).expect("infallible"));
293        Ok(())
294    }
295}
296
297stripe_types::impl_from_val_with_from_str!(RecurringUsageType);
298#[cfg(feature = "deserialize")]
299impl<'de> serde::Deserialize<'de> for RecurringUsageType {
300    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
301        use std::str::FromStr;
302        let s: std::borrow::Cow<'de, str> = serde::Deserialize::deserialize(deserializer)?;
303        Ok(Self::from_str(&s).expect("infallible"))
304    }
305}