stripe_shared/
coupon.rs

1/// A coupon contains information about a percent-off or amount-off discount you
2/// might want to apply to a customer.
3/// Coupons may be applied to [subscriptions](https://stripe.com/docs/api#subscriptions), [invoices](https://stripe.com/docs/api#invoices),.
4/// [checkout sessions](https://stripe.com/docs/api/checkout/sessions), [quotes](https://stripe.com/docs/api#quotes), and more.
5/// Coupons do not work with conventional one-off [charges](https://stripe.com/docs/api#create_charge) or [payment intents](https://stripe.com/docs/api/payment_intents).
6///
7/// For more details see <<https://stripe.com/docs/api/coupons/object>>.
8#[derive(Clone, Debug)]
9#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
10pub struct Coupon {
11    /// Amount (in the `currency` specified) that will be taken off the subtotal of any invoices for this customer.
12    pub amount_off: Option<i64>,
13    pub applies_to: Option<stripe_shared::CouponAppliesTo>,
14    /// Time at which the object was created. Measured in seconds since the Unix epoch.
15    pub created: stripe_types::Timestamp,
16    /// If `amount_off` has been set, the three-letter [ISO code for the currency](https://stripe.com/docs/currencies) of the amount to take off.
17    pub currency: Option<stripe_types::Currency>,
18    /// Coupons defined in each available currency option.
19    /// Each key must be a three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) and a [supported currency](https://stripe.com/docs/currencies).
20    pub currency_options: Option<
21        std::collections::HashMap<stripe_types::Currency, stripe_shared::CouponCurrencyOption>,
22    >,
23    /// One of `forever`, `once`, or `repeating`.
24    /// Describes how long a customer who applies this coupon will get the discount.
25    pub duration: stripe_shared::CouponDuration,
26    /// If `duration` is `repeating`, the number of months the coupon applies.
27    /// Null if coupon `duration` is `forever` or `once`.
28    pub duration_in_months: Option<i64>,
29    /// Unique identifier for the object.
30    pub id: stripe_shared::CouponId,
31    /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode.
32    pub livemode: bool,
33    /// Maximum number of times this coupon can be redeemed, in total, across all customers, before it is no longer valid.
34    pub max_redemptions: Option<i64>,
35    /// Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object.
36    /// This can be useful for storing additional information about the object in a structured format.
37    pub metadata: Option<std::collections::HashMap<String, String>>,
38    /// Name of the coupon displayed to customers on for instance invoices or receipts.
39    pub name: Option<String>,
40    /// Percent that will be taken off the subtotal of any invoices for this customer for the duration of the coupon.
41    /// For example, a coupon with percent_off of 50 will make a $ (or local equivalent)100 invoice $ (or local equivalent)50 instead.
42    pub percent_off: Option<f64>,
43    /// Date after which the coupon can no longer be redeemed.
44    pub redeem_by: Option<stripe_types::Timestamp>,
45    /// Number of times this coupon has been applied to a customer.
46    pub times_redeemed: i64,
47    /// Taking account of the above properties, whether this coupon can still be applied to a customer.
48    pub valid: bool,
49}
50#[doc(hidden)]
51pub struct CouponBuilder {
52    amount_off: Option<Option<i64>>,
53    applies_to: Option<Option<stripe_shared::CouponAppliesTo>>,
54    created: Option<stripe_types::Timestamp>,
55    currency: Option<Option<stripe_types::Currency>>,
56    currency_options: Option<
57        Option<
58            std::collections::HashMap<stripe_types::Currency, stripe_shared::CouponCurrencyOption>,
59        >,
60    >,
61    duration: Option<stripe_shared::CouponDuration>,
62    duration_in_months: Option<Option<i64>>,
63    id: Option<stripe_shared::CouponId>,
64    livemode: Option<bool>,
65    max_redemptions: Option<Option<i64>>,
66    metadata: Option<Option<std::collections::HashMap<String, String>>>,
67    name: Option<Option<String>>,
68    percent_off: Option<Option<f64>>,
69    redeem_by: Option<Option<stripe_types::Timestamp>>,
70    times_redeemed: Option<i64>,
71    valid: Option<bool>,
72}
73
74#[allow(
75    unused_variables,
76    irrefutable_let_patterns,
77    clippy::let_unit_value,
78    clippy::match_single_binding,
79    clippy::single_match
80)]
81const _: () = {
82    use miniserde::de::{Map, Visitor};
83    use miniserde::json::Value;
84    use miniserde::{Deserialize, Result, make_place};
85    use stripe_types::miniserde_helpers::FromValueOpt;
86    use stripe_types::{MapBuilder, ObjectDeser};
87
88    make_place!(Place);
89
90    impl Deserialize for Coupon {
91        fn begin(out: &mut Option<Self>) -> &mut dyn Visitor {
92            Place::new(out)
93        }
94    }
95
96    struct Builder<'a> {
97        out: &'a mut Option<Coupon>,
98        builder: CouponBuilder,
99    }
100
101    impl Visitor for Place<Coupon> {
102        fn map(&mut self) -> Result<Box<dyn Map + '_>> {
103            Ok(Box::new(Builder { out: &mut self.out, builder: CouponBuilder::deser_default() }))
104        }
105    }
106
107    impl MapBuilder for CouponBuilder {
108        type Out = Coupon;
109        fn key(&mut self, k: &str) -> Result<&mut dyn Visitor> {
110            Ok(match k {
111                "amount_off" => Deserialize::begin(&mut self.amount_off),
112                "applies_to" => Deserialize::begin(&mut self.applies_to),
113                "created" => Deserialize::begin(&mut self.created),
114                "currency" => Deserialize::begin(&mut self.currency),
115                "currency_options" => Deserialize::begin(&mut self.currency_options),
116                "duration" => Deserialize::begin(&mut self.duration),
117                "duration_in_months" => Deserialize::begin(&mut self.duration_in_months),
118                "id" => Deserialize::begin(&mut self.id),
119                "livemode" => Deserialize::begin(&mut self.livemode),
120                "max_redemptions" => Deserialize::begin(&mut self.max_redemptions),
121                "metadata" => Deserialize::begin(&mut self.metadata),
122                "name" => Deserialize::begin(&mut self.name),
123                "percent_off" => Deserialize::begin(&mut self.percent_off),
124                "redeem_by" => Deserialize::begin(&mut self.redeem_by),
125                "times_redeemed" => Deserialize::begin(&mut self.times_redeemed),
126                "valid" => Deserialize::begin(&mut self.valid),
127
128                _ => <dyn Visitor>::ignore(),
129            })
130        }
131
132        fn deser_default() -> Self {
133            Self {
134                amount_off: Deserialize::default(),
135                applies_to: Deserialize::default(),
136                created: Deserialize::default(),
137                currency: Deserialize::default(),
138                currency_options: Deserialize::default(),
139                duration: Deserialize::default(),
140                duration_in_months: Deserialize::default(),
141                id: Deserialize::default(),
142                livemode: Deserialize::default(),
143                max_redemptions: Deserialize::default(),
144                metadata: Deserialize::default(),
145                name: Deserialize::default(),
146                percent_off: Deserialize::default(),
147                redeem_by: Deserialize::default(),
148                times_redeemed: Deserialize::default(),
149                valid: Deserialize::default(),
150            }
151        }
152
153        fn take_out(&mut self) -> Option<Self::Out> {
154            let (
155                Some(amount_off),
156                Some(applies_to),
157                Some(created),
158                Some(currency),
159                Some(currency_options),
160                Some(duration),
161                Some(duration_in_months),
162                Some(id),
163                Some(livemode),
164                Some(max_redemptions),
165                Some(metadata),
166                Some(name),
167                Some(percent_off),
168                Some(redeem_by),
169                Some(times_redeemed),
170                Some(valid),
171            ) = (
172                self.amount_off,
173                self.applies_to.take(),
174                self.created,
175                self.currency.take(),
176                self.currency_options.take(),
177                self.duration,
178                self.duration_in_months,
179                self.id.take(),
180                self.livemode,
181                self.max_redemptions,
182                self.metadata.take(),
183                self.name.take(),
184                self.percent_off,
185                self.redeem_by,
186                self.times_redeemed,
187                self.valid,
188            )
189            else {
190                return None;
191            };
192            Some(Self::Out {
193                amount_off,
194                applies_to,
195                created,
196                currency,
197                currency_options,
198                duration,
199                duration_in_months,
200                id,
201                livemode,
202                max_redemptions,
203                metadata,
204                name,
205                percent_off,
206                redeem_by,
207                times_redeemed,
208                valid,
209            })
210        }
211    }
212
213    impl Map for Builder<'_> {
214        fn key(&mut self, k: &str) -> Result<&mut dyn Visitor> {
215            self.builder.key(k)
216        }
217
218        fn finish(&mut self) -> Result<()> {
219            *self.out = self.builder.take_out();
220            Ok(())
221        }
222    }
223
224    impl ObjectDeser for Coupon {
225        type Builder = CouponBuilder;
226    }
227
228    impl FromValueOpt for Coupon {
229        fn from_value(v: Value) -> Option<Self> {
230            let Value::Object(obj) = v else {
231                return None;
232            };
233            let mut b = CouponBuilder::deser_default();
234            for (k, v) in obj {
235                match k.as_str() {
236                    "amount_off" => b.amount_off = FromValueOpt::from_value(v),
237                    "applies_to" => b.applies_to = FromValueOpt::from_value(v),
238                    "created" => b.created = FromValueOpt::from_value(v),
239                    "currency" => b.currency = FromValueOpt::from_value(v),
240                    "currency_options" => b.currency_options = FromValueOpt::from_value(v),
241                    "duration" => b.duration = FromValueOpt::from_value(v),
242                    "duration_in_months" => b.duration_in_months = FromValueOpt::from_value(v),
243                    "id" => b.id = FromValueOpt::from_value(v),
244                    "livemode" => b.livemode = FromValueOpt::from_value(v),
245                    "max_redemptions" => b.max_redemptions = FromValueOpt::from_value(v),
246                    "metadata" => b.metadata = FromValueOpt::from_value(v),
247                    "name" => b.name = FromValueOpt::from_value(v),
248                    "percent_off" => b.percent_off = FromValueOpt::from_value(v),
249                    "redeem_by" => b.redeem_by = FromValueOpt::from_value(v),
250                    "times_redeemed" => b.times_redeemed = FromValueOpt::from_value(v),
251                    "valid" => b.valid = FromValueOpt::from_value(v),
252
253                    _ => {}
254                }
255            }
256            b.take_out()
257        }
258    }
259};
260#[cfg(feature = "serialize")]
261impl serde::Serialize for Coupon {
262    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
263        use serde::ser::SerializeStruct;
264        let mut s = s.serialize_struct("Coupon", 17)?;
265        s.serialize_field("amount_off", &self.amount_off)?;
266        s.serialize_field("applies_to", &self.applies_to)?;
267        s.serialize_field("created", &self.created)?;
268        s.serialize_field("currency", &self.currency)?;
269        s.serialize_field("currency_options", &self.currency_options)?;
270        s.serialize_field("duration", &self.duration)?;
271        s.serialize_field("duration_in_months", &self.duration_in_months)?;
272        s.serialize_field("id", &self.id)?;
273        s.serialize_field("livemode", &self.livemode)?;
274        s.serialize_field("max_redemptions", &self.max_redemptions)?;
275        s.serialize_field("metadata", &self.metadata)?;
276        s.serialize_field("name", &self.name)?;
277        s.serialize_field("percent_off", &self.percent_off)?;
278        s.serialize_field("redeem_by", &self.redeem_by)?;
279        s.serialize_field("times_redeemed", &self.times_redeemed)?;
280        s.serialize_field("valid", &self.valid)?;
281
282        s.serialize_field("object", "coupon")?;
283        s.end()
284    }
285}
286impl stripe_types::Object for Coupon {
287    type Id = stripe_shared::CouponId;
288    fn id(&self) -> &Self::Id {
289        &self.id
290    }
291
292    fn into_id(self) -> Self::Id {
293        self.id
294    }
295}
296stripe_types::def_id!(CouponId);
297#[derive(Copy, Clone, Eq, PartialEq)]
298pub enum CouponDuration {
299    Forever,
300    Once,
301    Repeating,
302}
303impl CouponDuration {
304    pub fn as_str(self) -> &'static str {
305        use CouponDuration::*;
306        match self {
307            Forever => "forever",
308            Once => "once",
309            Repeating => "repeating",
310        }
311    }
312}
313
314impl std::str::FromStr for CouponDuration {
315    type Err = stripe_types::StripeParseError;
316    fn from_str(s: &str) -> Result<Self, Self::Err> {
317        use CouponDuration::*;
318        match s {
319            "forever" => Ok(Forever),
320            "once" => Ok(Once),
321            "repeating" => Ok(Repeating),
322            _ => Err(stripe_types::StripeParseError),
323        }
324    }
325}
326impl std::fmt::Display for CouponDuration {
327    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
328        f.write_str(self.as_str())
329    }
330}
331
332impl std::fmt::Debug for CouponDuration {
333    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
334        f.write_str(self.as_str())
335    }
336}
337impl serde::Serialize for CouponDuration {
338    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
339    where
340        S: serde::Serializer,
341    {
342        serializer.serialize_str(self.as_str())
343    }
344}
345impl miniserde::Deserialize for CouponDuration {
346    fn begin(out: &mut Option<Self>) -> &mut dyn miniserde::de::Visitor {
347        crate::Place::new(out)
348    }
349}
350
351impl miniserde::de::Visitor for crate::Place<CouponDuration> {
352    fn string(&mut self, s: &str) -> miniserde::Result<()> {
353        use std::str::FromStr;
354        self.out = Some(CouponDuration::from_str(s).map_err(|_| miniserde::Error)?);
355        Ok(())
356    }
357}
358
359stripe_types::impl_from_val_with_from_str!(CouponDuration);
360#[cfg(feature = "deserialize")]
361impl<'de> serde::Deserialize<'de> for CouponDuration {
362    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
363        use std::str::FromStr;
364        let s: std::borrow::Cow<'de, str> = serde::Deserialize::deserialize(deserializer)?;
365        Self::from_str(&s).map_err(|_| serde::de::Error::custom("Unknown value for CouponDuration"))
366    }
367}