66from fastapi import APIRouter , Depends , Query
77from fastapi_sqlalchemy import db
88
9- from rating_api .exceptions import ForbiddenAction , ObjectNotFound , TooManyCommentRequests
9+ from rating_api .exceptions import ForbiddenAction , ObjectNotFound , TooManyCommentRequests , TooManyCommentsToLecturer
1010from rating_api .models import Comment , Lecturer , LecturerUserComment , ReviewStatus
1111from rating_api .schemas .base import StatusResponseModel
1212from rating_api .schemas .models import CommentGet , CommentGetAll , CommentImportAll , CommentPost
@@ -27,6 +27,8 @@ async def create_comment(lecturer_id: int, comment_info: CommentPost, user=Depen
2727 Для возможности создания комментария с указанием времени создания и изменения необходим скоуп ["rating.comment.import"]
2828 """
2929 lecturer = Lecturer .get (session = db .session , id = lecturer_id )
30+ now = datetime .datetime .now (tz = datetime .timezone .utc )
31+
3032 if not lecturer :
3133 raise ObjectNotFound (Lecturer , lecturer_id )
3234
@@ -35,23 +37,53 @@ async def create_comment(lecturer_id: int, comment_info: CommentPost, user=Depen
3537 raise ForbiddenAction (Comment )
3638
3739 if not has_create_scope :
38- user_comments : list [LecturerUserComment ] = (
39- LecturerUserComment .query (session = db .session ).filter (LecturerUserComment .user_id == user .get ("id" )).all ()
40+ # Определяем дату, до которой учитываем комментарии для проверки общего лимита.
41+ date_count = datetime .datetime (
42+ now .year + (now .month - settings .COMMENT_FREQUENCY_IN_MONTH ) // 12 ,
43+ (now .month - settings .COMMENT_FREQUENCY_IN_MONTH ) % 12 ,
44+ 1 ,
45+ )
46+ user_comments_count = (
47+ LecturerUserComment .query (session = db .session )
48+ .filter (
49+ LecturerUserComment .user_id == user .get ("id" ),
50+ LecturerUserComment .update_ts >= date_count ,
51+ )
52+ .count ()
53+ )
54+ if user_comments_count >= settings .COMMENT_LIMIT :
55+ raise TooManyCommentRequests (settings .COMMENT_FREQUENCY_IN_MONTH , settings .COMMENT_LIMIT )
56+
57+ # Дата, до которой учитываем комментарии для проверки лимита на комментарии конкретному лектору.
58+ cutoff_date_lecturer = datetime .datetime (
59+ now .year + (now .month - settings .COMMENT_LECTURER_FREQUENCE_IN_MONTH ) // 12 ,
60+ (now .month - settings .COMMENT_LECTURER_FREQUENCE_IN_MONTH ) % 12 ,
61+ 1 ,
62+ )
63+ lecturer_comments_count = (
64+ LecturerUserComment .query (session = db .session )
65+ .filter (
66+ LecturerUserComment .user_id == user .get ("id" ),
67+ LecturerUserComment .lecturer_id == lecturer_id ,
68+ LecturerUserComment .update_ts >= cutoff_date_lecturer ,
69+ )
70+ .count ()
4071 )
41- for user_comment in user_comments :
42- if datetime .datetime .utcnow () - user_comment .update_ts < datetime .timedelta (
43- minutes = settings .COMMENT_CREATE_FREQUENCY_IN_MINUTES
44- ):
45- raise TooManyCommentRequests (
46- dtime = user_comment .update_ts
47- + datetime .timedelta (minutes = settings .COMMENT_CREATE_FREQUENCY_IN_MINUTES )
48- - datetime .datetime .utcnow ()
49- )
72+ if lecturer_comments_count >= settings .COMMENT_TO_LECTURER_LIMIT :
73+ raise TooManyCommentsToLecturer (
74+ settings .COMMENT_LECTURER_FREQUENCE_IN_MONTH , settings .COMMENT_TO_LECTURER_LIMIT
75+ )
5076
5177 # Сначала добавляем с user_id, который мы получили при авторизации,
5278 # в LecturerUserComment, чтобы нельзя было слишком быстро добавлять комментарии
53- LecturerUserComment .create (session = db .session , lecturer_id = lecturer_id , user_id = user .get ('id' ))
54-
79+ create_ts = datetime .datetime (now .year , now .month , 1 )
80+ LecturerUserComment .create (
81+ session = db .session ,
82+ lecturer_id = lecturer_id ,
83+ user_id = user .get ('id' ),
84+ create_ts = create_ts ,
85+ update_ts = create_ts ,
86+ )
5587 # Обрабатываем анонимность комментария, и удаляем этот флаг чтобы добавить запись в БД
5688 user_id = None if comment_info .is_anonymous else user .get ('id' )
5789
0 commit comments