use serde::{Deserialize, Serialize};
use crate::client::RazorpayClient;
use crate::error::RazorpayError;
use crate::util::pagination::{Collection, ListOptions};
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct Item {
pub id: String,
#[serde(default)]
pub entity: String,
pub name: String,
#[serde(default)]
pub description: Option<String>,
pub amount: i64,
pub currency: String,
#[serde(default)]
pub active: bool,
#[serde(default)]
pub unit: Option<String>,
#[serde(default)]
pub hsn_code: Option<String>,
#[serde(default)]
pub sac_code: Option<String>,
#[serde(default)]
pub tax_rate: Option<f64>,
#[serde(default)]
pub created_at: i64,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize)]
pub struct ItemParams {
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub amount: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub currency: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub active: Option<bool>,
}
impl ItemParams {
pub fn new(name: impl Into<String>, amount: i64, currency: impl Into<String>) -> Self {
Self {
name: Some(name.into()),
amount: Some(amount),
currency: Some(currency.into()),
..Self::default()
}
}
pub fn update() -> Self {
Self::default()
}
pub fn description(mut self, description: impl Into<String>) -> Self {
self.description = Some(description.into());
self
}
pub fn name(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
pub fn amount(mut self, amount: i64) -> Self {
self.amount = Some(amount);
self
}
pub fn active(mut self, active: bool) -> Self {
self.active = Some(active);
self
}
}
pub struct ItemsClient<'a> {
pub(crate) client: &'a RazorpayClient,
}
impl<'a> ItemsClient<'a> {
pub async fn create(&self, params: ItemParams) -> Result<Item, RazorpayError> {
self.client.post("items", Some(¶ms)).await
}
pub async fn fetch(&self, id: &str) -> Result<Item, RazorpayError> {
self.client.get::<(), _>(&format!("items/{id}"), None).await
}
pub async fn all(&self, options: ListOptions) -> Result<Collection<Item>, RazorpayError> {
self.client.get("items", Some(&options)).await
}
pub async fn edit(&self, id: &str, params: ItemParams) -> Result<Item, RazorpayError> {
self.client.patch(&format!("items/{id}"), Some(¶ms)).await
}
pub async fn delete(&self, id: &str) -> Result<(), RazorpayError> {
self.client
.delete::<serde::de::IgnoredAny>(&format!("items/{id}"))
.await
.map(|_| ())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn create_sends_required_fields_only() {
let json = serde_json::to_string(&ItemParams::new("Book", 20_000, "INR")).unwrap();
assert_eq!(json, r#"{"name":"Book","amount":20000,"currency":"INR"}"#);
}
#[test]
fn update_sends_only_changed_fields() {
let json = serde_json::to_string(&ItemParams::update().active(false)).unwrap();
assert_eq!(json, r#"{"active":false}"#);
}
}