Skip to main content

razorpay_api/resources/
items.rs

1//! Items — reusable named prices you attach to invoices and plans.
2
3use serde::{Deserialize, Serialize};
4
5use crate::client::RazorpayClient;
6use crate::error::RazorpayError;
7use crate::util::pagination::{Collection, ListOptions};
8
9/// A reusable priced line item.
10#[derive(Debug, Clone, PartialEq, Deserialize)]
11pub struct Item {
12    /// Unique identifier, e.g. `item_7Oxp4hmm6T4SCn`.
13    pub id: String,
14    /// Always `"item"`.
15    #[serde(default)]
16    pub entity: String,
17    /// Display name.
18    pub name: String,
19    /// Longer description.
20    #[serde(default)]
21    pub description: Option<String>,
22    /// Unit price in the smallest currency unit.
23    pub amount: i64,
24    /// ISO 4217 currency code.
25    pub currency: String,
26    /// Whether the item can still be used.
27    #[serde(default)]
28    pub active: bool,
29    /// Unit of measure, e.g. `kg`.
30    #[serde(default)]
31    pub unit: Option<String>,
32    /// HSN code for tax reporting.
33    #[serde(default)]
34    pub hsn_code: Option<String>,
35    /// SAC code for tax reporting.
36    #[serde(default)]
37    pub sac_code: Option<String>,
38    /// Tax rate applied, in basis points.
39    #[serde(default)]
40    pub tax_rate: Option<f64>,
41    /// Creation time as a Unix timestamp in seconds.
42    #[serde(default)]
43    pub created_at: i64,
44}
45
46/// Parameters for creating or updating an [`Item`].
47#[derive(Debug, Clone, Default, PartialEq, Serialize)]
48pub struct ItemParams {
49    /// Display name.
50    #[serde(skip_serializing_if = "Option::is_none")]
51    pub name: Option<String>,
52    /// Longer description.
53    #[serde(skip_serializing_if = "Option::is_none")]
54    pub description: Option<String>,
55    /// Unit price in the smallest currency unit.
56    #[serde(skip_serializing_if = "Option::is_none")]
57    pub amount: Option<i64>,
58    /// ISO 4217 currency code.
59    #[serde(skip_serializing_if = "Option::is_none")]
60    pub currency: Option<String>,
61    /// Whether the item is usable.
62    #[serde(skip_serializing_if = "Option::is_none")]
63    pub active: Option<bool>,
64}
65
66impl ItemParams {
67    /// A new item with the three fields Razorpay requires at creation.
68    pub fn new(name: impl Into<String>, amount: i64, currency: impl Into<String>) -> Self {
69        Self {
70            name: Some(name.into()),
71            amount: Some(amount),
72            currency: Some(currency.into()),
73            ..Self::default()
74        }
75    }
76
77    /// Empty parameters, for partial updates via [`ItemsClient::edit`].
78    pub fn update() -> Self {
79        Self::default()
80    }
81
82    /// Set the description.
83    pub fn description(mut self, description: impl Into<String>) -> Self {
84        self.description = Some(description.into());
85        self
86    }
87
88    /// Set the name.
89    pub fn name(mut self, name: impl Into<String>) -> Self {
90        self.name = Some(name.into());
91        self
92    }
93
94    /// Set the unit price.
95    pub fn amount(mut self, amount: i64) -> Self {
96        self.amount = Some(amount);
97        self
98    }
99
100    /// Activate or deactivate the item.
101    pub fn active(mut self, active: bool) -> Self {
102        self.active = Some(active);
103        self
104    }
105}
106
107/// Item endpoints. Obtain one from [`RazorpayClient::items`].
108pub struct ItemsClient<'a> {
109    pub(crate) client: &'a RazorpayClient,
110}
111
112impl<'a> ItemsClient<'a> {
113    /// Create an item — `POST /v1/items`.
114    pub async fn create(&self, params: ItemParams) -> Result<Item, RazorpayError> {
115        self.client.post("items", Some(&params)).await
116    }
117
118    /// Fetch one item by id — `GET /v1/items/{id}`.
119    pub async fn fetch(&self, id: &str) -> Result<Item, RazorpayError> {
120        self.client.get::<(), _>(&format!("items/{id}"), None).await
121    }
122
123    /// List items — `GET /v1/items`.
124    pub async fn all(&self, options: ListOptions) -> Result<Collection<Item>, RazorpayError> {
125        self.client.get("items", Some(&options)).await
126    }
127
128    /// Update an item — `PATCH /v1/items/{id}`.
129    pub async fn edit(&self, id: &str, params: ItemParams) -> Result<Item, RazorpayError> {
130        self.client.patch(&format!("items/{id}"), Some(&params)).await
131    }
132
133    /// Delete an item — `DELETE /v1/items/{id}`.
134    pub async fn delete(&self, id: &str) -> Result<(), RazorpayError> {
135        self.client
136            .delete::<serde::de::IgnoredAny>(&format!("items/{id}"))
137            .await
138            .map(|_| ())
139    }
140}
141
142#[cfg(test)]
143mod tests {
144    use super::*;
145
146    #[test]
147    fn create_sends_required_fields_only() {
148        let json = serde_json::to_string(&ItemParams::new("Book", 20_000, "INR")).unwrap();
149        assert_eq!(json, r#"{"name":"Book","amount":20000,"currency":"INR"}"#);
150    }
151
152    #[test]
153    fn update_sends_only_changed_fields() {
154        let json = serde_json::to_string(&ItemParams::update().active(false)).unwrap();
155        assert_eq!(json, r#"{"active":false}"#);
156    }
157}