1use serde::{Deserialize, Serialize};
4
5use crate::client::RazorpayClient;
6use crate::error::RazorpayError;
7use crate::resources::common::{Notes, NotesUpdate};
8use crate::util::pagination::{Collection, ListOptions};
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
12#[serde(rename_all = "snake_case")]
13pub enum SubscriptionStatus {
14 Created,
16 Authenticated,
18 Active,
20 Paused,
22 Pending,
24 Halted,
26 Completed,
28 Cancelled,
30 Expired,
32 #[serde(other)]
34 Unknown,
35}
36
37#[derive(Debug, Clone, PartialEq, Deserialize)]
39pub struct Subscription {
40 pub id: String,
42 #[serde(default)]
44 pub entity: String,
45 pub plan_id: String,
47 pub status: SubscriptionStatus,
49 #[serde(default)]
51 pub customer_id: Option<String>,
52 #[serde(default)]
54 pub total_count: u32,
55 #[serde(default)]
57 pub paid_count: u32,
58 #[serde(default)]
60 pub remaining_count: u32,
61 #[serde(default)]
63 pub auth_attempts: u32,
64 #[serde(default)]
66 pub quantity: u32,
67 #[serde(default)]
69 pub short_url: Option<String>,
70 #[serde(default)]
72 pub customer_notify: bool,
73 #[serde(default)]
75 pub current_start: Option<i64>,
76 #[serde(default)]
78 pub current_end: Option<i64>,
79 #[serde(default)]
81 pub start_at: Option<i64>,
82 #[serde(default)]
84 pub end_at: Option<i64>,
85 #[serde(default)]
87 pub ended_at: Option<i64>,
88 #[serde(default)]
90 pub expire_by: Option<i64>,
91 #[serde(default)]
93 pub charge_at: Option<i64>,
94 #[serde(default)]
96 pub addons: Vec<serde_json::Value>,
97 #[serde(default)]
99 pub notes: Notes,
100 #[serde(default)]
102 pub created_at: i64,
103}
104
105impl Subscription {
106 pub fn is_active(&self) -> bool {
108 matches!(self.status, SubscriptionStatus::Active)
109 }
110}
111
112#[derive(Debug, Clone, PartialEq, Serialize)]
114pub struct CreateSubscriptionParams {
115 pub plan_id: String,
117 pub total_count: u32,
119 #[serde(skip_serializing_if = "Option::is_none")]
121 pub quantity: Option<u32>,
122 #[serde(skip_serializing_if = "Option::is_none")]
124 pub customer_notify: Option<u8>,
125 #[serde(skip_serializing_if = "Option::is_none")]
127 pub start_at: Option<i64>,
128 #[serde(skip_serializing_if = "Option::is_none")]
130 pub expire_by: Option<i64>,
131 #[serde(skip_serializing_if = "Option::is_none")]
133 pub customer_id: Option<String>,
134 #[serde(skip_serializing_if = "Option::is_none")]
136 pub notes: Option<Notes>,
137}
138
139impl CreateSubscriptionParams {
140 pub fn new(plan_id: impl Into<String>, total_count: u32) -> Self {
142 Self {
143 plan_id: plan_id.into(),
144 total_count,
145 quantity: None,
146 customer_notify: None,
147 start_at: None,
148 expire_by: None,
149 customer_id: None,
150 notes: None,
151 }
152 }
153
154 pub fn customer_id(mut self, customer_id: impl Into<String>) -> Self {
156 self.customer_id = Some(customer_id.into());
157 self
158 }
159
160 pub fn quantity(mut self, quantity: u32) -> Self {
162 self.quantity = Some(quantity);
163 self
164 }
165
166 pub fn start_at(mut self, start_at: i64) -> Self {
168 self.start_at = Some(start_at);
169 self
170 }
171
172 pub fn customer_notify(mut self, notify: bool) -> Self {
174 self.customer_notify = Some(u8::from(notify));
175 self
176 }
177
178 pub fn notes(mut self, notes: Notes) -> Self {
180 self.notes = Some(notes);
181 self
182 }
183}
184
185#[derive(Debug, Clone, PartialEq, Serialize)]
187struct CancelParams {
188 cancel_at_cycle_end: u8,
189}
190
191#[derive(Debug, Clone, PartialEq, Serialize)]
193struct PauseResumeParams {
194 #[serde(skip_serializing_if = "Option::is_none")]
195 pause_at: Option<&'static str>,
196 #[serde(skip_serializing_if = "Option::is_none")]
197 resume_at: Option<&'static str>,
198}
199
200pub struct SubscriptionsClient<'a> {
202 pub(crate) client: &'a RazorpayClient,
203}
204
205impl<'a> SubscriptionsClient<'a> {
206 pub async fn create(
211 &self,
212 params: CreateSubscriptionParams,
213 ) -> Result<Subscription, RazorpayError> {
214 self.client.post("subscriptions", Some(¶ms)).await
215 }
216
217 pub async fn fetch(&self, id: &str) -> Result<Subscription, RazorpayError> {
219 self.client
220 .get::<(), _>(&format!("subscriptions/{id}"), None)
221 .await
222 }
223
224 pub async fn all(
226 &self,
227 options: ListOptions,
228 ) -> Result<Collection<Subscription>, RazorpayError> {
229 self.client.get("subscriptions", Some(&options)).await
230 }
231
232 pub async fn cancel(
237 &self,
238 id: &str,
239 at_cycle_end: bool,
240 ) -> Result<Subscription, RazorpayError> {
241 let body = CancelParams {
242 cancel_at_cycle_end: u8::from(at_cycle_end),
243 };
244 self.client
245 .post(&format!("subscriptions/{id}/cancel"), Some(&body))
246 .await
247 }
248
249 pub async fn pause(&self, id: &str) -> Result<Subscription, RazorpayError> {
253 let body = PauseResumeParams {
254 pause_at: Some("now"),
255 resume_at: None,
256 };
257 self.client
258 .post(&format!("subscriptions/{id}/pause"), Some(&body))
259 .await
260 }
261
262 pub async fn resume(&self, id: &str) -> Result<Subscription, RazorpayError> {
264 let body = PauseResumeParams {
265 pause_at: None,
266 resume_at: Some("now"),
267 };
268 self.client
269 .post(&format!("subscriptions/{id}/resume"), Some(&body))
270 .await
271 }
272
273 pub async fn edit(&self, id: &str, notes: Notes) -> Result<Subscription, RazorpayError> {
275 self.client
276 .patch(&format!("subscriptions/{id}"), Some(&NotesUpdate::new(notes)))
277 .await
278 }
279
280 pub async fn invoices(
282 &self,
283 id: &str,
284 ) -> Result<Collection<crate::resources::invoices::Invoice>, RazorpayError> {
285 #[derive(Serialize)]
286 struct Query<'q> {
287 subscription_id: &'q str,
288 }
289 self.client
290 .get("invoices", Some(&Query { subscription_id: id }))
291 .await
292 }
293}
294
295#[cfg(test)]
296mod tests {
297 use super::*;
298
299 #[test]
300 fn create_omits_unset_fields() {
301 let json = serde_json::to_string(&CreateSubscriptionParams::new("plan_1", 12)).unwrap();
302 assert_eq!(json, r#"{"plan_id":"plan_1","total_count":12}"#);
303 }
304
305 #[test]
306 fn customer_notify_maps_bool_to_int() {
307 let json = serde_json::to_string(
308 &CreateSubscriptionParams::new("plan_1", 1).customer_notify(true),
309 )
310 .unwrap();
311 assert!(json.contains(r#""customer_notify":1"#));
312 }
313
314 #[test]
315 fn active_helper_reflects_status() {
316 let sub: Subscription = serde_json::from_str(
317 r#"{"id":"sub_1","plan_id":"plan_1","status":"active"}"#,
318 )
319 .unwrap();
320 assert!(sub.is_active());
321 }
322}