konnektoren_core/marketplace/
cart.rs

1use super::Product;
2use serde::{Deserialize, Serialize};
3
4/// A cart that contains products.
5#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
6pub struct Cart {
7    pub products: Vec<Product>,
8}
9
10impl Cart {
11    pub fn new() -> Self {
12        Self { products: vec![] }
13    }
14
15    pub fn add_product(&mut self, product: Product) {
16        if self.products.iter().any(|p| p.id == product.id) {
17            return;
18        }
19        self.products.push(product);
20    }
21
22    pub fn remove_product(&mut self, product_id: &str) {
23        self.products
24            .retain(|product| product.id.as_deref() != Some(product_id));
25    }
26
27    pub fn total_price(&self) -> f64 {
28        self.products
29            .iter()
30            .fold(0.0, |acc, product| acc + product.price.unwrap_or(0.0))
31    }
32}
33
34#[cfg(test)]
35mod tests {
36    use super::*;
37
38    #[test]
39    fn test_new_cart() {
40        let cart = Cart::new();
41        assert_eq!(cart.products.len(), 0);
42    }
43
44    #[test]
45    fn test_add_product() {
46        let mut cart = Cart::new();
47        let product = Product::new("Test".to_string(), "Test".to_string());
48        cart.add_product(product.clone());
49        assert_eq!(cart.products.len(), 1);
50        assert_eq!(cart.products[0], product);
51    }
52
53    #[test]
54    fn test_remove_product() {
55        let mut cart = Cart::new();
56        let product = Product::new("Test".to_string(), "Test".to_string());
57        cart.add_product(product.clone());
58        cart.remove_product(product.id.as_deref().unwrap());
59        assert_eq!(cart.products.len(), 0);
60    }
61
62    #[test]
63    fn test_total_price() {
64        let mut cart = Cart::new();
65        let product1 = Product {
66            id: Some("1".to_string()),
67            name: "Test".to_string(),
68            description: "Test".to_string(),
69            price: Some(10.0),
70            image: None,
71            tags: vec![],
72            path: None,
73        };
74        let product2 = Product {
75            id: Some("2".to_string()),
76            name: "Test".to_string(),
77            description: "Test".to_string(),
78            price: Some(20.0),
79            image: None,
80            tags: vec![],
81            path: None,
82        };
83        cart.add_product(product1);
84        cart.add_product(product2);
85        // Product with price 0
86        cart.add_product(Product::default());
87        assert_eq!(cart.total_price(), 30.0);
88    }
89}