Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fixing comment post route + fixing validation models #74

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 12 additions & 45 deletions rating_api/routes/comment.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,58 +20,25 @@
@comment.post("", response_model=CommentGet)
async def create_comment(lecturer_id: int, comment_info: CommentPost, user=Depends(UnionAuth())) -> CommentGet:
"""
Scopes: `["rating.comment.import"]`
Создает комментарий к преподавателю в базе данных RatingAPI
Для создания комментария нужно быть авторизованным

Для возможности создания комментария с указанием времени создания и изменения необходим скоуп ["rating.comment.import"]
"""
lecturer = Lecturer.get(session=db.session, id=lecturer_id)
now = datetime.datetime.now(tz=datetime.timezone.utc)

if not lecturer:
raise ObjectNotFound(Lecturer, lecturer_id)

has_create_scope = "rating.comment.import" in [scope['name'] for scope in user.get('session_scopes')]
if (comment_info.create_ts or comment_info.update_ts) and not has_create_scope:
raise ForbiddenAction(Comment)

if not has_create_scope:
# Определяем дату, до которой учитываем комментарии для проверки общего лимита.
date_count = datetime.datetime(
now.year + (now.month - settings.COMMENT_FREQUENCY_IN_MONTH) // 12,
(now.month - settings.COMMENT_FREQUENCY_IN_MONTH) % 12,
1,
)
user_comments_count = (
LecturerUserComment.query(session=db.session)
.filter(
LecturerUserComment.user_id == user.get("id"),
LecturerUserComment.update_ts >= date_count,
)
.count()
)
if user_comments_count >= settings.COMMENT_LIMIT:
raise TooManyCommentRequests(settings.COMMENT_FREQUENCY_IN_MONTH, settings.COMMENT_LIMIT)

# Дата, до которой учитываем комментарии для проверки лимита на комментарии конкретному лектору.
cutoff_date_lecturer = datetime.datetime(
now.year + (now.month - settings.COMMENT_LECTURER_FREQUENCE_IN_MONTH) // 12,
(now.month - settings.COMMENT_LECTURER_FREQUENCE_IN_MONTH) % 12,
1,
)
lecturer_comments_count = (
LecturerUserComment.query(session=db.session)
.filter(
LecturerUserComment.user_id == user.get("id"),
LecturerUserComment.lecturer_id == lecturer_id,
LecturerUserComment.update_ts >= cutoff_date_lecturer,
)
.count()
)
if lecturer_comments_count >= settings.COMMENT_TO_LECTURER_LIMIT:
raise TooManyCommentsToLecturer(
settings.COMMENT_LECTURER_FREQUENCE_IN_MONTH, settings.COMMENT_TO_LECTURER_LIMIT
user_comments: list[LecturerUserComment] = (
LecturerUserComment.query(session=db.session).filter(LecturerUserComment.user_id == user.get("id")).all()
)
for user_comment in user_comments:
if datetime.datetime.utcnow() - user_comment.update_ts < datetime.timedelta(
minutes=settings.COMMENT_CREATE_FREQUENCY_IN_MINUTES
):
raise TooManyCommentRequests(
dtime=user_comment.update_ts
+ datetime.timedelta(minutes=settings.COMMENT_CREATE_FREQUENCY_IN_MINUTES)
- datetime.datetime.utcnow()
)

# Сначала добавляем с user_id, который мы получили при авторизации,
Expand Down Expand Up @@ -110,7 +77,7 @@ async def import_comments(
for comment_info in comments_info.comments:
new_comment = Comment.create(
session=db.session,
**comment_info.model_dump(exclude={"is_anonymous"}),
**comment_info.model_dump(),
review_status=ReviewStatus.APPROVED,
)
result.comments.append(new_comment)
Expand Down
15 changes: 14 additions & 1 deletion rating_api/schemas/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,22 @@ def validate_mark(cls, value):
return value


class CommentImport(CommentPost):
class CommentImport(Base):
lecturer_id: int
subject: str | None = None
text: str
create_ts: datetime.datetime | None = None
update_ts: datetime.datetime | None = None
mark_kindness: int
mark_freebie: int
mark_clarity: int

@field_validator('mark_kindness', 'mark_freebie', 'mark_clarity')
@classmethod
def validate_mark(cls, value):
if value not in [-2, -1, 0, 1, 2]:
raise WrongMark()
return value


class CommentImportAll(Base):
Expand Down
2 changes: 1 addition & 1 deletion tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ def lecturers(dbsession):
for fname, lname, mname, timetable_id in lecturers_data
]
lecturers.append(
Lecturer(first_name='test_fname3', last_name='test_lname3', middle_name='test_mname3', timetable_id=3)
Lecturer(first_name='test_fname3', last_name='test_lname3', middle_name='test_mname3', timetable_id=9903)
)
lecturers[-1].is_deleted = True
for lecturer in lecturers:
Expand Down
Loading