5
5
from pydantic import EmailStr
6
6
7
7
from config import db
8
- from utils import get_auth_id , get_auth_id_admin
9
- from models import Prof , Review , ReviewFrontend , Student
8
+ from utils import get_auth_id , get_auth_id_admin , hash_decrypt , hash_encrypt
9
+ from models import Prof , Review , ReviewBackend , ReviewFrontend , Student , VoteAndReviewID
10
10
11
11
# The get_auth_id Dependency validates authentication of the caller
12
12
router = APIRouter (dependencies = [Depends (get_auth_id )])
@@ -65,9 +65,21 @@ async def prof_reviews_get(email: EmailStr, auth_id: str = Depends(get_auth_id))
65
65
if not prof_reviews :
66
66
return None
67
67
68
+ prof_reviews_validated = [
69
+ (k , ReviewBackend (** v )) for k , v in prof_reviews .get ("reviews" , {}).items ()
70
+ ]
71
+
68
72
return [
69
- ReviewFrontend (** v , is_reviewer = (k == auth_id )).model_dump ()
70
- for k , v in prof_reviews .get ("reviews" , {}).items ()
73
+ ReviewFrontend (
74
+ rating = v .rating ,
75
+ content = v .content ,
76
+ dtime = v .dtime ,
77
+ review_id = hash_encrypt (k ),
78
+ is_reviewer = (k == auth_id ),
79
+ votes_aggregate = sum (v .votes .values ()),
80
+ votes_status = v .votes .get (auth_id , 0 ),
81
+ ).model_dump ()
82
+ for k , v in prof_reviews_validated
71
83
]
72
84
73
85
@@ -81,7 +93,17 @@ async def prof_reviews_post(
81
93
review discards any older reviews.
82
94
"""
83
95
await profs_collection .update_one (
84
- {"email" : email }, {"$set" : {f"reviews.{ auth_id } " : review .model_dump ()}}
96
+ {"email" : email },
97
+ [
98
+ {
99
+ "$set" : {
100
+ # do merge objects to keep old votes intact
101
+ f"reviews.{ auth_id } " : {
102
+ "$mergeObjects" : [f"$reviews.{ auth_id } " , review .model_dump ()]
103
+ }
104
+ }
105
+ }
106
+ ],
85
107
)
86
108
87
109
@@ -96,6 +118,29 @@ async def prof_reviews_delete(email: EmailStr, auth_id: str = Depends(get_auth_i
96
118
)
97
119
98
120
121
+ @router .post ("/reviews/{email}/votes" )
122
+ async def course_reviews_votes_post (
123
+ email : EmailStr ,
124
+ post_body : VoteAndReviewID ,
125
+ auth_id : str = Depends (get_auth_id ),
126
+ ):
127
+ """
128
+ Helper to post a vote on a single Review on a Prof.
129
+ """
130
+ review_hash = hash_decrypt (post_body .review_id )
131
+ if not review_hash :
132
+ raise HTTPException (422 , "Invalid review_id value" )
133
+
134
+ await profs_collection .update_one (
135
+ {"email" : email },
136
+ {
137
+ "$set" if post_body .vote else "$unset" : {
138
+ f"reviews.{ review_hash } .votes.{ auth_id } " : post_body .vote
139
+ }
140
+ },
141
+ )
142
+
143
+
99
144
async def student_hash (user : Student ):
100
145
"""
101
146
Internal function to hash a Student object. This hash is used as a review key
0 commit comments