Skip to main content

stripe_shared/
recurring.rs

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