stripe/resources/generated/
plan.rs

1// ======================================
2// This file was automatically generated.
3// ======================================
4
5use serde::{Deserialize, Serialize};
6
7use crate::client::{Client, Response};
8use crate::ids::PlanId;
9use crate::params::{
10    Deleted, Expand, Expandable, IdOrCreate, List, Metadata, Object, Paginable, RangeQuery,
11    Timestamp,
12};
13use crate::resources::{CreateProduct, Currency, Product};
14
15/// The resource representing a Stripe "Plan".
16///
17/// For more details see <https://stripe.com/docs/api/plans/object>
18#[derive(Clone, Debug, Default, Deserialize, Serialize)]
19pub struct Plan {
20    /// Unique identifier for the object.
21    pub id: PlanId,
22
23    /// Whether the plan can be used for new purchases.
24    #[serde(skip_serializing_if = "Option::is_none")]
25    pub active: Option<bool>,
26
27    /// Specifies a usage aggregation strategy for plans of `usage_type=metered`.
28    ///
29    /// Allowed values are `sum` for summing up all usage during a period, `last_during_period` for using the last usage record reported within a period, `last_ever` for using the last usage record ever (across period bounds) or `max` which uses the usage record with the maximum reported usage during a period.
30    /// Defaults to `sum`.
31    #[serde(skip_serializing_if = "Option::is_none")]
32    pub aggregate_usage: Option<PlanAggregateUsage>,
33
34    /// The unit amount in cents (or local equivalent) to be charged, represented as a whole integer if possible.
35    ///
36    /// Only set if `billing_scheme=per_unit`.
37    #[serde(skip_serializing_if = "Option::is_none")]
38    pub amount: Option<i64>,
39
40    /// The unit amount in cents (or local equivalent) to be charged, represented as a decimal string with at most 12 decimal places.
41    ///
42    /// Only set if `billing_scheme=per_unit`.
43    #[serde(skip_serializing_if = "Option::is_none")]
44    pub amount_decimal: Option<String>,
45
46    /// Describes how to compute the price per period.
47    ///
48    /// Either `per_unit` or `tiered`.
49    /// `per_unit` indicates that the fixed amount (specified in `amount`) will be charged per unit in `quantity` (for plans with `usage_type=licensed`), or per unit of total usage (for plans with `usage_type=metered`).
50    /// `tiered` indicates that the unit pricing will be computed using a tiering strategy as defined using the `tiers` and `tiers_mode` attributes.
51    #[serde(skip_serializing_if = "Option::is_none")]
52    pub billing_scheme: Option<PlanBillingScheme>,
53
54    /// Time at which the object was created.
55    ///
56    /// Measured in seconds since the Unix epoch.
57    #[serde(skip_serializing_if = "Option::is_none")]
58    pub created: Option<Timestamp>,
59
60    /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase.
61    ///
62    /// Must be a [supported currency](https://stripe.com/docs/currencies).
63    #[serde(skip_serializing_if = "Option::is_none")]
64    pub currency: Option<Currency>,
65
66    // Always true for a deleted object
67    #[serde(default)]
68    pub deleted: bool,
69
70    /// The frequency at which a subscription is billed.
71    ///
72    /// One of `day`, `week`, `month` or `year`.
73    #[serde(skip_serializing_if = "Option::is_none")]
74    pub interval: Option<PlanInterval>,
75
76    /// The number of intervals (specified in the `interval` attribute) between subscription billings.
77    ///
78    /// For example, `interval=month` and `interval_count=3` bills every 3 months.
79    #[serde(skip_serializing_if = "Option::is_none")]
80    pub interval_count: Option<u64>,
81
82    /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode.
83    #[serde(skip_serializing_if = "Option::is_none")]
84    pub livemode: Option<bool>,
85
86    /// Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object.
87    ///
88    /// This can be useful for storing additional information about the object in a structured format.
89    #[serde(skip_serializing_if = "Option::is_none")]
90    pub metadata: Option<Metadata>,
91
92    /// A brief description of the plan, hidden from customers.
93    #[serde(skip_serializing_if = "Option::is_none")]
94    pub nickname: Option<String>,
95
96    /// The product whose pricing this plan determines.
97    #[serde(skip_serializing_if = "Option::is_none")]
98    pub product: Option<Expandable<Product>>,
99
100    /// Each element represents a pricing tier.
101    ///
102    /// This parameter requires `billing_scheme` to be set to `tiered`.
103    /// See also the documentation for `billing_scheme`.
104    #[serde(skip_serializing_if = "Option::is_none")]
105    pub tiers: Option<Vec<PlanTier>>,
106
107    /// Defines if the tiering price should be `graduated` or `volume` based.
108    ///
109    /// In `volume`-based tiering, the maximum quantity within a period determines the per unit price.
110    /// In `graduated` tiering, pricing can change as the quantity grows.
111    #[serde(skip_serializing_if = "Option::is_none")]
112    pub tiers_mode: Option<PlanTiersMode>,
113
114    /// Apply a transformation to the reported usage or set quantity before computing the amount billed.
115    ///
116    /// Cannot be combined with `tiers`.
117    #[serde(skip_serializing_if = "Option::is_none")]
118    pub transform_usage: Option<TransformUsage>,
119
120    /// Default number of trial days when subscribing a customer to this plan using [`trial_from_plan=true`](https://stripe.com/docs/api#create_subscription-trial_from_plan).
121    #[serde(skip_serializing_if = "Option::is_none")]
122    pub trial_period_days: Option<u32>,
123
124    /// Configures how the quantity per period should be determined.
125    ///
126    /// Can be either `metered` or `licensed`.
127    /// `licensed` automatically bills the `quantity` set when adding it to a subscription.
128    /// `metered` aggregates the total usage based on usage records.
129    /// Defaults to `licensed`.
130    #[serde(skip_serializing_if = "Option::is_none")]
131    pub usage_type: Option<PlanUsageType>,
132}
133
134impl Plan {
135    /// Returns a list of your plans.
136    pub fn list(client: &Client, params: &ListPlans<'_>) -> Response<List<Plan>> {
137        client.get_query("/plans", params)
138    }
139
140    /// Retrieves the plan with the given ID.
141    pub fn retrieve(client: &Client, id: &PlanId, expand: &[&str]) -> Response<Plan> {
142        client.get_query(&format!("/plans/{}", id), Expand { expand })
143    }
144
145    /// Updates the specified plan by setting the values of the parameters passed.
146    ///
147    /// Any parameters not provided are left unchanged.
148    /// By design, you cannot change a plan’s ID, amount, currency, or billing cycle.
149    pub fn update(client: &Client, id: &PlanId, params: UpdatePlan<'_>) -> Response<Plan> {
150        #[allow(clippy::needless_borrows_for_generic_args)]
151        client.post_form(&format!("/plans/{}", id), &params)
152    }
153
154    /// Deleting plans means new subscribers can’t be added.
155    ///
156    /// Existing subscribers aren’t affected.
157    pub fn delete(client: &Client, id: &PlanId) -> Response<Deleted<PlanId>> {
158        client.delete(&format!("/plans/{}", id))
159    }
160}
161
162impl Object for Plan {
163    type Id = PlanId;
164    fn id(&self) -> Self::Id {
165        self.id.clone()
166    }
167    fn object(&self) -> &'static str {
168        "plan"
169    }
170}
171
172#[derive(Clone, Debug, Default, Deserialize, Serialize)]
173pub struct PlanTier {
174    /// Price for the entire tier.
175    pub flat_amount: Option<i64>,
176
177    /// Same as `flat_amount`, but contains a decimal value with at most 12 decimal places.
178    pub flat_amount_decimal: Option<String>,
179
180    /// Per unit price for units relevant to the tier.
181    pub unit_amount: Option<i64>,
182
183    /// Same as `unit_amount`, but contains a decimal value with at most 12 decimal places.
184    pub unit_amount_decimal: Option<String>,
185
186    /// Up to and including to this quantity will be contained in the tier.
187    pub up_to: Option<i64>,
188}
189
190#[derive(Clone, Debug, Default, Deserialize, Serialize)]
191pub struct TransformUsage {
192    /// Divide usage by this number.
193    pub divide_by: i64,
194
195    /// After division, either round the result `up` or `down`.
196    pub round: TransformUsageRound,
197}
198
199/// The parameters for `Plan::list`.
200#[derive(Clone, Debug, Serialize, Default)]
201pub struct ListPlans<'a> {
202    /// Only return plans that are active or inactive (e.g., pass `false` to list all inactive plans).
203    #[serde(skip_serializing_if = "Option::is_none")]
204    pub active: Option<bool>,
205
206    /// A filter on the list, based on the object `created` field.
207    ///
208    /// The value can be a string with an integer Unix timestamp, or it can be a dictionary with a number of different query options.
209    #[serde(skip_serializing_if = "Option::is_none")]
210    pub created: Option<RangeQuery<Timestamp>>,
211
212    /// A cursor for use in pagination.
213    ///
214    /// `ending_before` is an object ID that defines your place in the list.
215    /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list.
216    #[serde(skip_serializing_if = "Option::is_none")]
217    pub ending_before: Option<PlanId>,
218
219    /// Specifies which fields in the response should be expanded.
220    #[serde(skip_serializing_if = "Expand::is_empty")]
221    pub expand: &'a [&'a str],
222
223    /// A limit on the number of objects to be returned.
224    ///
225    /// Limit can range between 1 and 100, and the default is 10.
226    #[serde(skip_serializing_if = "Option::is_none")]
227    pub limit: Option<u64>,
228
229    /// Only return plans for the given product.
230    #[serde(skip_serializing_if = "Option::is_none")]
231    pub product: Option<IdOrCreate<'a, CreateProduct<'a>>>,
232
233    /// A cursor for use in pagination.
234    ///
235    /// `starting_after` is an object ID that defines your place in the list.
236    /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list.
237    #[serde(skip_serializing_if = "Option::is_none")]
238    pub starting_after: Option<PlanId>,
239}
240
241impl<'a> ListPlans<'a> {
242    pub fn new() -> Self {
243        ListPlans {
244            active: Default::default(),
245            created: Default::default(),
246            ending_before: Default::default(),
247            expand: Default::default(),
248            limit: Default::default(),
249            product: Default::default(),
250            starting_after: Default::default(),
251        }
252    }
253}
254impl Paginable for ListPlans<'_> {
255    type O = Plan;
256    fn set_last(&mut self, item: Self::O) {
257        self.starting_after = Some(item.id());
258    }
259}
260/// The parameters for `Plan::update`.
261#[derive(Clone, Debug, Serialize, Default)]
262pub struct UpdatePlan<'a> {
263    /// Whether the plan is currently available for new subscriptions.
264    #[serde(skip_serializing_if = "Option::is_none")]
265    pub active: Option<bool>,
266
267    /// Specifies which fields in the response should be expanded.
268    #[serde(skip_serializing_if = "Expand::is_empty")]
269    pub expand: &'a [&'a str],
270
271    /// Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object.
272    ///
273    /// This can be useful for storing additional information about the object in a structured format.
274    /// Individual keys can be unset by posting an empty value to them.
275    /// All keys can be unset by posting an empty value to `metadata`.
276    #[serde(skip_serializing_if = "Option::is_none")]
277    pub metadata: Option<Metadata>,
278
279    /// A brief description of the plan, hidden from customers.
280    #[serde(skip_serializing_if = "Option::is_none")]
281    pub nickname: Option<&'a str>,
282
283    /// The product the plan belongs to.
284    ///
285    /// This cannot be changed once it has been used in a subscription or subscription schedule.
286    #[serde(skip_serializing_if = "Option::is_none")]
287    pub product: Option<IdOrCreate<'a, CreateProduct<'a>>>,
288
289    /// Default number of trial days when subscribing a customer to this plan using [`trial_from_plan=true`](https://stripe.com/docs/api#create_subscription-trial_from_plan).
290    #[serde(skip_serializing_if = "Option::is_none")]
291    pub trial_period_days: Option<u32>,
292}
293
294impl<'a> UpdatePlan<'a> {
295    pub fn new() -> Self {
296        UpdatePlan {
297            active: Default::default(),
298            expand: Default::default(),
299            metadata: Default::default(),
300            nickname: Default::default(),
301            product: Default::default(),
302            trial_period_days: Default::default(),
303        }
304    }
305}
306
307/// An enum representing the possible values of an `Plan`'s `aggregate_usage` field.
308#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
309#[serde(rename_all = "snake_case")]
310pub enum PlanAggregateUsage {
311    LastDuringPeriod,
312    LastEver,
313    Max,
314    Sum,
315}
316
317impl PlanAggregateUsage {
318    pub fn as_str(self) -> &'static str {
319        match self {
320            PlanAggregateUsage::LastDuringPeriod => "last_during_period",
321            PlanAggregateUsage::LastEver => "last_ever",
322            PlanAggregateUsage::Max => "max",
323            PlanAggregateUsage::Sum => "sum",
324        }
325    }
326}
327
328impl AsRef<str> for PlanAggregateUsage {
329    fn as_ref(&self) -> &str {
330        self.as_str()
331    }
332}
333
334impl std::fmt::Display for PlanAggregateUsage {
335    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
336        self.as_str().fmt(f)
337    }
338}
339impl std::default::Default for PlanAggregateUsage {
340    fn default() -> Self {
341        Self::LastDuringPeriod
342    }
343}
344
345/// An enum representing the possible values of an `Plan`'s `billing_scheme` field.
346#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
347#[serde(rename_all = "snake_case")]
348pub enum PlanBillingScheme {
349    PerUnit,
350    Tiered,
351}
352
353impl PlanBillingScheme {
354    pub fn as_str(self) -> &'static str {
355        match self {
356            PlanBillingScheme::PerUnit => "per_unit",
357            PlanBillingScheme::Tiered => "tiered",
358        }
359    }
360}
361
362impl AsRef<str> for PlanBillingScheme {
363    fn as_ref(&self) -> &str {
364        self.as_str()
365    }
366}
367
368impl std::fmt::Display for PlanBillingScheme {
369    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
370        self.as_str().fmt(f)
371    }
372}
373impl std::default::Default for PlanBillingScheme {
374    fn default() -> Self {
375        Self::PerUnit
376    }
377}
378
379/// An enum representing the possible values of an `Plan`'s `interval` field.
380#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
381#[serde(rename_all = "snake_case")]
382pub enum PlanInterval {
383    Day,
384    Month,
385    Week,
386    Year,
387}
388
389impl PlanInterval {
390    pub fn as_str(self) -> &'static str {
391        match self {
392            PlanInterval::Day => "day",
393            PlanInterval::Month => "month",
394            PlanInterval::Week => "week",
395            PlanInterval::Year => "year",
396        }
397    }
398}
399
400impl AsRef<str> for PlanInterval {
401    fn as_ref(&self) -> &str {
402        self.as_str()
403    }
404}
405
406impl std::fmt::Display for PlanInterval {
407    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
408        self.as_str().fmt(f)
409    }
410}
411impl std::default::Default for PlanInterval {
412    fn default() -> Self {
413        Self::Day
414    }
415}
416
417/// An enum representing the possible values of an `Plan`'s `tiers_mode` field.
418#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
419#[serde(rename_all = "snake_case")]
420pub enum PlanTiersMode {
421    Graduated,
422    Volume,
423}
424
425impl PlanTiersMode {
426    pub fn as_str(self) -> &'static str {
427        match self {
428            PlanTiersMode::Graduated => "graduated",
429            PlanTiersMode::Volume => "volume",
430        }
431    }
432}
433
434impl AsRef<str> for PlanTiersMode {
435    fn as_ref(&self) -> &str {
436        self.as_str()
437    }
438}
439
440impl std::fmt::Display for PlanTiersMode {
441    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
442        self.as_str().fmt(f)
443    }
444}
445impl std::default::Default for PlanTiersMode {
446    fn default() -> Self {
447        Self::Graduated
448    }
449}
450
451/// An enum representing the possible values of an `Plan`'s `usage_type` field.
452#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
453#[serde(rename_all = "snake_case")]
454pub enum PlanUsageType {
455    Licensed,
456    Metered,
457}
458
459impl PlanUsageType {
460    pub fn as_str(self) -> &'static str {
461        match self {
462            PlanUsageType::Licensed => "licensed",
463            PlanUsageType::Metered => "metered",
464        }
465    }
466}
467
468impl AsRef<str> for PlanUsageType {
469    fn as_ref(&self) -> &str {
470        self.as_str()
471    }
472}
473
474impl std::fmt::Display for PlanUsageType {
475    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
476        self.as_str().fmt(f)
477    }
478}
479impl std::default::Default for PlanUsageType {
480    fn default() -> Self {
481        Self::Licensed
482    }
483}
484
485/// An enum representing the possible values of an `TransformUsage`'s `round` field.
486#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
487#[serde(rename_all = "snake_case")]
488pub enum TransformUsageRound {
489    Down,
490    Up,
491}
492
493impl TransformUsageRound {
494    pub fn as_str(self) -> &'static str {
495        match self {
496            TransformUsageRound::Down => "down",
497            TransformUsageRound::Up => "up",
498        }
499    }
500}
501
502impl AsRef<str> for TransformUsageRound {
503    fn as_ref(&self) -> &str {
504        self.as_str()
505    }
506}
507
508impl std::fmt::Display for TransformUsageRound {
509    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
510        self.as_str().fmt(f)
511    }
512}
513impl std::default::Default for TransformUsageRound {
514    fn default() -> Self {
515        Self::Down
516    }
517}