Skip to main content

razorpay_api/resources/
plans.rs

1//! Plans — the billing cadence and price a subscription runs on.
2
3use serde::{Deserialize, Serialize};
4
5use crate::client::RazorpayClient;
6use crate::error::RazorpayError;
7use crate::resources::common::Notes;
8use crate::resources::items::Item;
9use crate::util::pagination::{Collection, ListOptions};
10
11/// How often a plan bills.
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
13#[serde(rename_all = "snake_case")]
14pub enum PlanPeriod {
15    /// Bills every `interval` days.
16    Daily,
17    /// Bills every `interval` weeks.
18    Weekly,
19    /// Bills every `interval` months.
20    Monthly,
21    /// Bills every `interval` years.
22    Yearly,
23    /// A period this crate does not model yet.
24    #[serde(other)]
25    Unknown,
26}
27
28/// A billing plan.
29#[derive(Debug, Clone, PartialEq, Deserialize)]
30pub struct Plan {
31    /// Unique identifier, e.g. `plan_00000000000001`.
32    pub id: String,
33    /// Always `"plan"`.
34    #[serde(default)]
35    pub entity: String,
36    /// The billing unit.
37    pub period: PlanPeriod,
38    /// How many `period` units between charges — `period: Monthly, interval: 3`
39    /// bills quarterly.
40    pub interval: u32,
41    /// The priced item this plan charges.
42    pub item: Item,
43    /// Your metadata.
44    #[serde(default)]
45    pub notes: Notes,
46    /// Creation time as a Unix timestamp in seconds.
47    #[serde(default)]
48    pub created_at: i64,
49}
50
51/// Parameters for creating a [`Plan`].
52#[derive(Debug, Clone, PartialEq, Serialize)]
53pub struct CreatePlanParams {
54    /// The billing unit.
55    pub period: PlanPeriod,
56    /// How many `period` units between charges.
57    pub interval: u32,
58    /// The item this plan bills for.
59    pub item: PlanItem,
60    /// Metadata to attach.
61    #[serde(skip_serializing_if = "Option::is_none")]
62    pub notes: Option<Notes>,
63}
64
65/// The inline item definition sent when creating a plan.
66///
67/// Plans embed their item rather than referencing an existing [`Item`] id.
68#[derive(Debug, Clone, PartialEq, Serialize)]
69pub struct PlanItem {
70    /// Display name shown to the customer.
71    pub name: String,
72    /// Amount charged each cycle, in the smallest currency unit.
73    pub amount: i64,
74    /// ISO 4217 currency code.
75    pub currency: String,
76    /// Longer description.
77    #[serde(skip_serializing_if = "Option::is_none")]
78    pub description: Option<String>,
79}
80
81impl CreatePlanParams {
82    /// A plan billing `amount` every `interval` × `period`.
83    ///
84    /// # Examples
85    ///
86    /// ```
87    /// use razorpay_api::resources::{CreatePlanParams, PlanPeriod};
88    ///
89    /// // ₹499 every month.
90    /// let monthly = CreatePlanParams::new(PlanPeriod::Monthly, 1, "Pro", 49_900, "INR");
91    /// assert_eq!(monthly.interval, 1);
92    ///
93    /// // ₹499 every three months.
94    /// let quarterly = CreatePlanParams::new(PlanPeriod::Monthly, 3, "Pro", 49_900, "INR");
95    /// assert_eq!(quarterly.interval, 3);
96    /// ```
97    pub fn new(
98        period: PlanPeriod,
99        interval: u32,
100        name: impl Into<String>,
101        amount: i64,
102        currency: impl Into<String>,
103    ) -> Self {
104        Self {
105            period,
106            interval,
107            item: PlanItem {
108                name: name.into(),
109                amount,
110                currency: currency.into(),
111                description: None,
112            },
113            notes: None,
114        }
115    }
116
117    /// Describe the item in more detail.
118    pub fn description(mut self, description: impl Into<String>) -> Self {
119        self.item.description = Some(description.into());
120        self
121    }
122
123    /// Attach metadata.
124    pub fn notes(mut self, notes: Notes) -> Self {
125        self.notes = Some(notes);
126        self
127    }
128}
129
130/// Plan endpoints. Obtain one from [`RazorpayClient::plans`].
131///
132/// Plans are immutable once created — to change pricing, create a new plan and
133/// move subscribers to it.
134pub struct PlansClient<'a> {
135    pub(crate) client: &'a RazorpayClient,
136}
137
138impl<'a> PlansClient<'a> {
139    /// Create a plan — `POST /v1/plans`.
140    pub async fn create(&self, params: CreatePlanParams) -> Result<Plan, RazorpayError> {
141        self.client.post("plans", Some(&params)).await
142    }
143
144    /// Fetch one plan by id — `GET /v1/plans/{id}`.
145    pub async fn fetch(&self, id: &str) -> Result<Plan, RazorpayError> {
146        self.client.get::<(), _>(&format!("plans/{id}"), None).await
147    }
148
149    /// List plans — `GET /v1/plans`.
150    pub async fn all(&self, options: ListOptions) -> Result<Collection<Plan>, RazorpayError> {
151        self.client.get("plans", Some(&options)).await
152    }
153}
154
155#[cfg(test)]
156mod tests {
157    use super::*;
158
159    #[test]
160    fn plan_serializes_with_nested_item() {
161        let json =
162            serde_json::to_string(&CreatePlanParams::new(PlanPeriod::Monthly, 1, "Pro", 100, "INR"))
163                .unwrap();
164        assert_eq!(
165            json,
166            r#"{"period":"monthly","interval":1,"item":{"name":"Pro","amount":100,"currency":"INR"}}"#
167        );
168    }
169
170    #[test]
171    fn unknown_period_decodes_to_fallback() {
172        let plan: Plan = serde_json::from_str(
173            r#"{"id":"plan_1","period":"fortnightly","interval":1,
174                "item":{"id":"item_1","name":"x","amount":1,"currency":"INR"}}"#,
175        )
176        .unwrap();
177        assert_eq!(plan.period, PlanPeriod::Unknown);
178    }
179}