use serde::{Deserialize, Serialize};
use crate::client::RazorpayClient;
use crate::error::RazorpayError;
use crate::resources::common::Notes;
use crate::resources::items::Item;
use crate::util::pagination::{Collection, ListOptions};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PlanPeriod {
Daily,
Weekly,
Monthly,
Yearly,
#[serde(other)]
Unknown,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct Plan {
pub id: String,
#[serde(default)]
pub entity: String,
pub period: PlanPeriod,
pub interval: u32,
pub item: Item,
#[serde(default)]
pub notes: Notes,
#[serde(default)]
pub created_at: i64,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct CreatePlanParams {
pub period: PlanPeriod,
pub interval: u32,
pub item: PlanItem,
#[serde(skip_serializing_if = "Option::is_none")]
pub notes: Option<Notes>,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct PlanItem {
pub name: String,
pub amount: i64,
pub currency: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
impl CreatePlanParams {
pub fn new(
period: PlanPeriod,
interval: u32,
name: impl Into<String>,
amount: i64,
currency: impl Into<String>,
) -> Self {
Self {
period,
interval,
item: PlanItem {
name: name.into(),
amount,
currency: currency.into(),
description: None,
},
notes: None,
}
}
pub fn description(mut self, description: impl Into<String>) -> Self {
self.item.description = Some(description.into());
self
}
pub fn notes(mut self, notes: Notes) -> Self {
self.notes = Some(notes);
self
}
}
pub struct PlansClient<'a> {
pub(crate) client: &'a RazorpayClient,
}
impl<'a> PlansClient<'a> {
pub async fn create(&self, params: CreatePlanParams) -> Result<Plan, RazorpayError> {
self.client.post("plans", Some(¶ms)).await
}
pub async fn fetch(&self, id: &str) -> Result<Plan, RazorpayError> {
self.client.get::<(), _>(&format!("plans/{id}"), None).await
}
pub async fn all(&self, options: ListOptions) -> Result<Collection<Plan>, RazorpayError> {
self.client.get("plans", Some(&options)).await
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn plan_serializes_with_nested_item() {
let json =
serde_json::to_string(&CreatePlanParams::new(PlanPeriod::Monthly, 1, "Pro", 100, "INR"))
.unwrap();
assert_eq!(
json,
r#"{"period":"monthly","interval":1,"item":{"name":"Pro","amount":100,"currency":"INR"}}"#
);
}
#[test]
fn unknown_period_decodes_to_fallback() {
let plan: Plan = serde_json::from_str(
r#"{"id":"plan_1","period":"fortnightly","interval":1,
"item":{"id":"item_1","name":"x","amount":1,"currency":"INR"}}"#,
)
.unwrap();
assert_eq!(plan.period, PlanPeriod::Unknown);
}
}