stripe/resources/generated/
plan.rs

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