Skip to content
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
17 changes: 17 additions & 0 deletions modal_backend/routes/notes.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
NoteInfoPost,
NoteRatingGet,
NoteRatingPost,
NoteStatus,
NoteTextGet,
NoteTextPost,
NotificationGet,
Expand Down Expand Up @@ -185,3 +186,19 @@ async def create_note_images(
session=db.session, type_id=5, **note.model_dump(), admin_id=user.get("id"), status=ModalStatus.ACTIVE
)
return NoteImageGet.model_validate(new_note)


@note.patch("/{id}/status", response_model=NoteStatus)
async def update_note_status(id: int, user=Depends(UnionAuth(scopes=["modal.note.patch"]))) -> NoteStatus:
"""
Архивирует модалку, если она активна

Возвращает модалку в активное состояние, если она в архиве

Права: `["modal.note.patch"]`

Исключение **ObjectNotFound**, если `id` не найден

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

хочется добавить достаточно подробную информацию о том, как работает все.
Но делать это надо только в конце, после того, как исправишь логику работы по моим комментам


"""
updated_note = await NoteService.update_status(db, id=id)
return NoteStatus.model_validate(updated_note)
5 changes: 5 additions & 0 deletions modal_backend/schemas/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,3 +119,8 @@ class GroupGet(Base):
class GroupPost(Base):
group_id: int
name: str


class NoteStatus(Base):
id: int
status: ModalStatus
26 changes: 24 additions & 2 deletions modal_backend/utils/services.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
from datetime import datetime

from requests import Session

from modal_backend.exceptions import AlreadyExists, ObjectNotFound
from modal_backend.models.db import Group, Note, NoteType, Service
from modal_backend.exceptions import AlreadyExists, ForbiddenAction, ObjectNotFound
from modal_backend.models.db import Group, ModalStatus, Note, NoteType, Service
from modal_backend.schemas.base import StatusResponseModel
from modal_backend.schemas.models import GroupPost, NoteTypePost, ServicePost

Expand Down Expand Up @@ -41,6 +43,26 @@ async def get_notes_by_filters(

return notes

@classmethod
async def update_status(cls, db: Session, id: int) -> Note:
note = Note.get(session=db.session, id=id)
group_ids = note.group_ids
for group_id in group_ids:
Group.get(session=db.session, id=group_id)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

https://github.com/profcomff/modal-service-api/blob/main/modal_backend/models/base.py#L60
При вызове метода get может вылететь 404, если не найдено ничего. Если выскакивает 404, то код дальше не пойдет и 404 так и высветится в статусе. План такой, что для групп и сервисов, которые существуют мы модалку сможем вернуть из архива. Поэтому в данном случае лучше использовать db.session.query(...).filter(...) и тд, так как при таком поиске автоматического вылета 404 не будет, максимум вернется пустое значение (так же не забудь is_deleted=true убирать из рассмотрения). А дальше надо подготовить массив групп и сервисов, которые будут отправлены в параметры update

db.session.query(...).filter(...) см пример реализации https://github.com/profcomff/rental-api/blob/main/rental_backend/routes/item.py#L130

То есть если ты пропишешь сперва Group а потом к нему метод get то будет работать наше кастомное решение с дополнительными автоматическими проверками (см самую первую ссылку в этом комменте)

service_ids = note.service_ids
for service_id in service_ids:
Service.get(session=db.session, id=service_id)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

с сервисом аналогично

end_ts = note.end_ts
time = datetime.utcnow()
if note.is_always == False and time >= end_ts:
raise ForbiddenAction(Note)
else:
if note.status == ModalStatus.ACTIVE:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

такая ситуация: time >= end_ts (то есть вчера модалка завершилась) и note.is_always == False (не бесконечное время)
почему тогда мне высветится ForbiddenAction даже без проверки активна ли сейчас модалка или нет?
Если она активна, а я ее в архив хочу отправить, то в текущей реализации несостыковка

updated_note = Note.update(id=id, session=db.session, status=ModalStatus.ARCHIVED)
else:
updated_note = Note.update(id=id, session=db.session, status=ModalStatus.ACTIVE)
return updated_note


class NoteTypeService:
"""
Expand Down
Loading