aboutsummaryrefslogtreecommitdiff
path: root/src/handlers/rating.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/handlers/rating.rs')
-rw-r--r--src/handlers/rating.rs90
1 files changed, 90 insertions, 0 deletions
diff --git a/src/handlers/rating.rs b/src/handlers/rating.rs
new file mode 100644
index 0000000..309c2c6
--- /dev/null
+++ b/src/handlers/rating.rs
@@ -0,0 +1,90 @@
1use crate::models::{AddRating, Customer, Rating};
2use crate::schema::rating::dsl as rating;
3use crate::schema::{customer::dsl::*, product::dsl::*};
4use crate::TPool;
5
6use actix_identity::Identity;
7use actix_web::{web, HttpResponse, Responder};
8use diesel::prelude::*;
9use log::{error, info};
10use serde::Deserialize;
11
12#[derive(Deserialize, Debug)]
13pub struct AddRatingJson {
14 pub comment_text: Option<String>,
15 pub stars: Option<i32>,
16 pub product_id: i32,
17}
18
19pub async fn add_rating(
20 cookie: Identity,
21 rating_details: web::Json<AddRatingJson>,
22 pool: web::Data<TPool>,
23) -> impl Responder {
24 info!("Add rating hit: {:?}", rating_details.product_id);
25 let conn = pool.get().unwrap();
26 if let Some(uname) = cookie.identity() {
27 let selected_user = customer
28 .filter(username.eq(&uname))
29 .limit(1)
30 .first::<Customer>(&conn)
31 .expect("Couldn't connect to DB");
32 let rating_details = rating_details.into_inner();
33 let new_rating = AddRating {
34 comment_text: rating_details.comment_text,
35 stars: rating_details.stars,
36 product_id: rating_details.product_id,
37 customer_id: selected_user.id,
38 };
39 diesel::insert_into(rating::rating)
40 .values(new_rating)
41 .execute(&conn)
42 .expect("Coundn't connect to DB");
43 HttpResponse::Ok().body("Inserted rating successfully!")
44 } else {
45 error!("Unauthorized add rating action!");
46 return HttpResponse::Unauthorized()
47 .body("Need to be logged in to add rating!");
48 }
49}
50
51#[derive(Deserialize, Debug)]
52pub struct RemoveRating {
53 rating_id: i32,
54}
55
56pub async fn remove_rating(
57 cookie: Identity,
58 rating_details: web::Json<RemoveRating>,
59 pool: web::Data<TPool>,
60) -> impl Responder {
61 info!("Remove rating hit: {:?}", rating_details.rating_id);
62 let conn = pool.get().unwrap();
63 if let Some(uname) = cookie.identity() {
64 let selected_user = customer
65 .filter(username.eq(&uname))
66 .limit(1)
67 .first::<Customer>(&conn)
68 .expect("Couldn't connect to DB");
69
70 diesel::delete(
71 rating::rating
72 .filter(rating::customer_id.eq(selected_user.id))
73 .filter(rating::id.eq(rating_details.rating_id)),
74 )
75 .execute(&conn)
76 .expect("Coundn't connect to DB");
77 HttpResponse::Ok().body("Removed successfully!")
78 } else {
79 error!("Unauthorized add to cart action!");
80 return HttpResponse::Unauthorized()
81 .body("Need to be logged in to add to cart!");
82 }
83}
84
85// pub async fn get_product_reviews(
86// product: web::Json<GetProductReviews>,
87// pool: web::Data<TPool>,
88// ) -> impl Responder {
89// unimplemented!()
90// }