aboutsummaryrefslogtreecommitdiff
path: root/backend/src/handlers/cart_items.rs
blob: e17f4c45c26cf19f23313ac8e76301560e8bbf70 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
use crate::models::{AddCartItem, CartItem, Customer, Product};
use crate::schema::product::dsl as prod;
use crate::schema::{cart_items::dsl::*, customer::dsl::*};
use crate::TPool;

use actix_identity::Identity;
use actix_web::{web, HttpResponse, Responder};
use diesel::prelude::*;
use log::{error, info};
use serde::Serialize;

pub async fn add_to_cart(
    cookie: Identity,
    item_id: String,
    pool: web::Data<TPool>,
) -> impl Responder {
    let item_details = item_id.parse::<i32>().unwrap_or(-1);
    info!("Add to cart hit: {:?}", item_details);
    info!("[cart] Current user: {:?}", cookie.identity());
    let conn = pool.get().unwrap();
    if let Some(uname) = cookie.identity() {
        let selected_user = customer
            .filter(username.eq(&uname))
            .limit(1)
            .first::<Customer>(&conn)
            .expect("Couldn't connect to DB");
        let new_cart_item = AddCartItem {
            cart_id: selected_user.id,
            product_id: item_details,
            quantity: Some(1),
        };
        info!(
            "cart id: {:?}, product id {:?}",
            selected_user.id, item_details
        );
        let current_entry = cart_items
            .filter(cart_id.eq(selected_user.id))
            .filter(product_id.eq(item_details))
            .limit(1)
            .first::<CartItem>(&conn);
        match current_entry {
            Ok(v) => {
                info!("Item already present in cart, increasing quantity.");
                let old_quantity = v.quantity.unwrap_or(1);
                diesel::update(
                    cart_items
                        .filter(cart_id.eq(selected_user.id))
                        .filter(product_id.eq(item_details)),
                )
                .set(quantity.eq(old_quantity + 1))
                .execute(&conn)
                .unwrap();
                return HttpResponse::Ok()
                    .body("Updated quantity successfully!");
            }
            Err(_) => {
                info!("Item not present, adding to cart.");
                diesel::insert_into(cart_items)
                    .values(new_cart_item)
                    .execute(&conn)
                    .expect("Couldn't connect to DB");
                HttpResponse::Ok().body("Inserted successfully!")
            }
        }
    } else {
        error!("Unauthorized add to cart action!");
        return HttpResponse::Unauthorized()
            .body("Need to be logged in to add to cart!");
    }
}

pub async fn remove_from_cart(
    cookie: Identity,
    item_id: String,
    pool: web::Data<TPool>,
) -> impl Responder {
    info!("Remove from cart hit: {:?}", item_id);
    let item_details = item_id.parse::<i32>().unwrap_or(-1);
    let conn = pool.get().unwrap();
    if let Some(uname) = cookie.identity() {
        let selected_user = customer
            .filter(username.eq(&uname))
            .limit(1)
            .first::<Customer>(&conn)
            .expect("Couldn't connect to DB");
        let current_entry = cart_items
            .filter(cart_id.eq(selected_user.id))
            .filter(product_id.eq(item_details))
            .limit(1)
            .first::<CartItem>(&conn);
        match current_entry {
            Ok(v) => {
                info!("Item already present in cart, increasing quantity.");
                let old_quantity = v.quantity.unwrap_or(1);
                if old_quantity == 1 {
                    diesel::delete(
                        cart_items
                            .filter(cart_id.eq(selected_user.id))
                            .filter(product_id.eq(item_details)),
                    )
                    .execute(&conn)
                    .expect("Coundn't connect to DB");
                } else {
                    diesel::update(
                        cart_items
                            .filter(cart_id.eq(selected_user.id))
                            .filter(product_id.eq(item_details)),
                    )
                    .set(quantity.eq(old_quantity - 1))
                    .execute(&conn)
                    .unwrap();
                    return HttpResponse::Ok()
                        .body("Updated quantity successfully!");
                }
                return HttpResponse::Ok()
                    .body("Updated quantity successfully!");
            }
            Err(_) => {
                info!("Item not present.");
                return HttpResponse::InternalServerError()
                    .body("Item not found!");
            }
        }
    } else {
        error!("Unauthorized add to cart action!");
        return HttpResponse::Unauthorized()
            .body("Need to be logged in to add to cart!");
    }
}

#[derive(Serialize)]
struct UserCartItem {
    product_item: Product,
    quantity: i32,
}

pub async fn get_user_cart_items(
    cookie: Identity,
    pool: web::Data<TPool>,
) -> impl Responder {
    let conn = pool.get().unwrap();
    if let Some(uname) = cookie.identity() {
        let selected_user = customer
            .filter(username.eq(&uname))
            .limit(1)
            .first::<Customer>(&conn)
            .expect("Couldn't connect to DB");
        let user_cart_items = cart_items
            .filter(cart_id.eq(selected_user.id))
            .load::<CartItem>(&conn)
            .expect("Couldn't connect to DB");
        let cart_products = user_cart_items
            .into_iter()
            .map(|item| {
                let p = prod::product
                    .filter(prod::id.eq(item.product_id))
                    .limit(1)
                    .first::<Product>(&conn)
                    .expect("Couldn't connect to db");
                UserCartItem {
                    product_item: p,
                    quantity: item.quantity.unwrap_or(1),
                }
            })
            .collect::<Vec<_>>();
        return HttpResponse::Ok().json(&cart_products);
    } else {
        return HttpResponse::Unauthorized()
            .body("Need to be logged in to add to cart!");
    }
}

pub async fn get_user_cart_total(
    cookie: Identity,
    pool: web::Data<TPool>,
) -> impl Responder {
    let conn = pool.get().unwrap();
    if let Some(uname) = cookie.identity() {
        let selected_user = customer
            .filter(username.eq(&uname))
            .limit(1)
            .first::<Customer>(&conn)
            .expect("Couldn't connect to DB");
        let user_cart_items = cart_items
            .filter(cart_id.eq(selected_user.id))
            .load::<CartItem>(&conn)
            .expect("Couldn't connect to DB");
        let cart_total: f32 = user_cart_items
            .into_iter()
            .map(|item| {
                let p = prod::product
                    .filter(prod::id.eq(item.product_id))
                    .limit(1)
                    .first::<Product>(&conn)
                    .expect("Couldn't connect to db");
                return p.price * item.quantity.unwrap_or(1) as f32;
            })
            .sum();
        return HttpResponse::Ok().json(&cart_total);
    } else {
        return HttpResponse::Unauthorized()
            .body("Need to be logged in to add to cart!");
    }
}