Skip to main content

casdoor_rust_sdk/
order.rs

1// Copyright 2026 The Casdoor Authors. All Rights Reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//      http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use serde::{Deserialize, Serialize};
16
17use crate::client::{get_owner, Client, PostBody, Response};
18use crate::error::Result;
19use crate::serde_util::null_to_default;
20
21/// Order has the same definition as
22/// <https://github.com/casdoor/casdoor/blob/master/object/order.go>.
23#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
24#[serde(rename_all = "camelCase", default)]
25pub struct Order {
26    pub owner: String,
27    pub name: String,
28    pub created_time: String,
29    pub update_time: String,
30    pub display_name: String,
31
32    // Product info.
33    #[serde(deserialize_with = "null_to_default")]
34    pub products: Vec<String>,
35    #[serde(deserialize_with = "null_to_default")]
36    pub product_infos: Vec<ProductInfo>,
37
38    // User info.
39    pub user: String,
40
41    // Payment info.
42    pub payment: String,
43    pub price: f64,
44    pub currency: String,
45
46    // Order state.
47    pub state: String,
48    pub message: String,
49
50    // Coupon info.
51    pub coupon_name: String,
52    /// The discount amount applied by the coupon.
53    pub coupon_discount: f64,
54}
55
56/// One product of an [`Order`].
57#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
58#[serde(rename_all = "camelCase", default)]
59pub struct ProductInfo {
60    pub owner: String,
61    pub name: String,
62    pub created_time: String,
63    pub display_name: String,
64    pub image: String,
65    pub detail: String,
66    pub price: f64,
67    pub currency: String,
68    pub is_recharge: bool,
69    pub quantity: i32,
70    pub pricing_name: String,
71    pub plan_name: String,
72}
73
74impl Order {
75    /// Return the Casdoor object ID (`"owner/name"`) of the order.
76    pub fn get_id(&self) -> String {
77        format!("{}/{}", self.owner, self.name)
78    }
79}
80
81impl Client {
82    /// Get the orders of the client's organization.
83    pub async fn get_orders(&self) -> Result<Vec<Order>> {
84        self.get_list("get-orders", &[("owner", &self.config.organization_name)])
85            .await
86    }
87
88    /// Get one page of the orders of the client's organization, together with the total
89    /// number of the orders.
90    pub async fn get_pagination_orders(
91        &self,
92        p: i32,
93        page_size: i32,
94        query: &[(&str, &str)],
95    ) -> Result<(Vec<Order>, i32)> {
96        self.get_pagination(
97            "get-orders",
98            &self.config.organization_name,
99            p,
100            page_size,
101            query,
102        )
103        .await
104    }
105
106    /// Get the orders of one user.
107    pub async fn get_user_orders(&self, user_name: &str) -> Result<Vec<Order>> {
108        self.get_list(
109            "get-user-orders",
110            &[
111                ("owner", &self.config.organization_name),
112                ("user", user_name),
113            ],
114        )
115        .await
116    }
117
118    /// Get one order by name.
119    pub async fn get_order(&self, name: &str) -> Result<Option<Order>> {
120        self.get_object("get-order", &[("id", &self.get_id(name))])
121            .await
122    }
123
124    /// Add an order.
125    pub async fn add_order(&self, order: &Order) -> Result<bool> {
126        Ok(self.modify_order("add-order", order, &[]).await?.1)
127    }
128
129    /// Update an order.
130    pub async fn update_order(&self, order: &Order) -> Result<bool> {
131        Ok(self.modify_order("update-order", order, &[]).await?.1)
132    }
133
134    /// Delete an order.
135    pub async fn delete_order(&self, order: &Order) -> Result<bool> {
136        Ok(self.modify_order("delete-order", order, &[]).await?.1)
137    }
138
139    /// Cancel an order by name.
140    pub async fn cancel_order(&self, name: &str) -> Result<bool> {
141        let response = self
142            .do_post(
143                "cancel-order",
144                &[("id", &self.get_id(name))],
145                PostBody::Raw(Vec::new()),
146            )
147            .await?;
148
149        Ok(response.data.as_str() == Some("Affected"))
150    }
151
152    async fn modify_order(
153        &self,
154        action: &str,
155        order: &Order,
156        columns: &[&str],
157    ) -> Result<(Response, bool)> {
158        let mut order = order.clone();
159        order.owner = get_owner(&order.owner, &self.config.organization_name);
160
161        let id = format!("{}/{}", order.owner, order.name);
162        self.modify_object(action, &id, &order, columns).await
163    }
164}