Skip to content

EventUser table#124

Open
Georgon wants to merge 15 commits intomainfrom
EventUser_table
Open

EventUser table#124
Georgon wants to merge 15 commits intomainfrom
EventUser_table

Conversation

@Georgon
Copy link
Copy Markdown

@Georgon Georgon commented Apr 20, 2026

Добавил новый класс (таблицу) EventUser для задания событий у пользователя. Каждое событие может обладать следующими статусами:
NO_STATUS (автоматические статус для всех событий),
GOING - статус события, на которое пользователь идет,
NOT_GOING - статус события, на которое пользователь не идет,
ATTENDED - статус события, которое пользователь отметил как GOING и время конца события уже прошло.

Для всех типов статусов также организован класс EventUserStatus.

Создан новый файл миграции. Все проверил, табличка создается.

Closes #121

@Georgon Georgon requested a review from petrCher April 20, 2026 13:43
@Georgon Georgon self-assigned this Apr 20, 2026
@github-actions
Copy link
Copy Markdown

💩 Code linting failed, use black and isort to fix it.

@github-actions
Copy link
Copy Markdown

github-actions Bot commented Apr 20, 2026

Code Coverage

Coverage Report
FileStmtsMissCoverMissing
calendar_backend
   __main__.py660%1–16
   exceptions.py13285%8, 14
calendar_backend/methods
   list_calendar.py704930%28–51, 58–64, 71–76, 85–98, 102–113
   utils.py352626%14–19, 23–28, 34–38, 42–46, 52–56
calendar_backend/models
   base.py64198%87
calendar_backend/routes
   base.py74791%75, 80–81, 86–87, 98, 101
calendar_backend/routes/event
   comment.py47687%30, 41–43, 52, 64
   comment_review.py27485%23–29, 41
   event.py112893%38, 45–48, 53, 113, 117
   user_event.py16850%21–42
calendar_backend/routes/group
   group.py38392%26, 42, 58
calendar_backend/routes/lecturer
   comment.py48883%35, 49, 57–61, 70
   comment_review.py25484%21–29, 41
   lecturer.py60887%27, 41, 44, 54, 78–81
   photo.py43588%43, 48, 65, 76, 79
   photo_review.py512061%39–58, 75–77
calendar_backend/routes/models
   base.py60985%36–40, 43, 56, 67, 80
   event.py62395%15, 42, 60
   group.py391659%13–19, 22, 32–38, 41
   lecturer.py46296%21, 31
   room.py21195%13
calendar_backend/routes/room
   room.py39392%26, 44, 58
TOTAL120219983% 

Summary

Tests Skipped Failures Errors Time
34 0 💤 0 ❌ 0 🔥 4.178s ⏱️

@github-actions
Copy link
Copy Markdown

💩 Code linting failed, use black and isort to fix it.

Comment thread calendar_backend/models/db.py Outdated
Comment thread calendar_backend/models/db.py Outdated
@petrCher
Copy link
Copy Markdown
Member

https://github.com/profcomff/rental-api/blob/main/rental_backend/models/__init__.py#L5
посмотри сюда. надо будет добавить класс новый в свой инит

@petrCher petrCher removed this from Viribus Team Apr 20, 2026
@github-actions
Copy link
Copy Markdown

💩 Code linting failed, use black and isort to fix it.

@github-actions
Copy link
Copy Markdown

💩 Code linting failed, use black and isort to fix it.

@github-actions
Copy link
Copy Markdown

💩 Code linting failed, use black and isort to fix it.

@Georgon
Copy link
Copy Markdown
Author

Georgon commented Apr 23, 2026

Добавил новый файл routes/event/user_event.py, где реализована ручка post event/{event_id}/visit/.
Для нее добавлены две Pydentic модели VisitRequest и VisitResponse в отдельном файле visit.py.
В routes/base.py подключил роутер user_event_router.

Логика ручки:

  1. Получаем id пользователя + проверка на авторизацию
  2. Проверка, что событие существует и не удалено
  3. Поиск/создание записи о посещении (с изменением статуса)

Также в прошлый раз забыл добавить в calendar_backend/models/init.py класс EventUserStatus.

@github-actions
Copy link
Copy Markdown

💩 Code linting failed, use black and isort to fix it.

@Georgon
Copy link
Copy Markdown
Author

Georgon commented Apr 23, 2026

Closes #119


@router.post("/{event_id}/visit", response_model=VisitResponse)
async def set_event_visit_status(
event_id: int, visit: VisitRequest, auth: dict = Depends(UnionAuth(scopes=[]))
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.

scopes=[]
удалить

"""
Отметить посещение мероприятия для текущего пользователя.
"""
user_id = auth.get('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.

удалить авторизацию

Comment thread calendar_backend/routes/models/visit.py Outdated
event_id: int
user_id: int
status: EventUserStatus
updated_at: str # ISO-формат
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.

поменять на datetime
аналогично ренталу


if existing:
existing.status = visit.status
db.session.flush()
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.

работа с бд в отдельном классе BaseDbModel

try:
_ = Event.get(event_id, with_deleted=False, session=db.session)
except ObjectNotFound:
raise HTTPException(
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.

у нас есть прям отдельный класс для ошибки ObjectNotFound, импортирую его из exceptions и используй его

)

try:
_ = Event.get(event_id, with_deleted=False, session=db.session)
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.

необязательно делать присвоение пустой переменной, можно просто сделать ивент.гет

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.

и кстати посмотри, если не ошибаюсь то сам нет запрос от класса при отсутствии соответствующей переданной переменной сам вызовет 404 ошибку, так что запрос на ошибку ниже вероятно лишний

)

existing = (
db.session.query(EventUser)
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.

сделать EventUser.query и тд


db.session.commit()

return VisitResponse(
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.

лучше делать VisitResponce.model_validate() реализацию можно посмотреть буквально почти во всех ручках рентала или рейтинга

@petrCher petrCher linked an issue Apr 23, 2026 that may be closed by this pull request

@router.post("/{event_id}/visit", response_model=VisitResponse)
async def set_event_visit_status(
event_id: int, visit: VisitRequest, auth: dict = Depends(UnionAuth(scopes=[]))
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.

@github-actions
Copy link
Copy Markdown

💩 Code linting failed, use black and isort to fix it.

async def set_event_visit_status(
event_id: int,
auth: dict = Depends(UnionAuth()),
visit: str = Query(enum=["no_status", "going", "not_going", "attended"], default="no_status"),
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.

чисто из логики, attended надо убрать, так как пользователь не должен иметь возможность поставить инфу что посещена пара, нелогично

"""
user_id = auth.get('id')

Event.get(event_id, with_deleted=False, session=db.session)
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.

with_deleted=False необязательно прописывать, по умолчанию false

status=visit,
)

db.session.commit()
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.

это лишнее, убрать

status: EventUserStatus


class VisitResponse(BaseModel):
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.

наследованные брать от класса Base из соседнего файла Base, там уже прописано model_config = {"from_attributes": True}

from calendar_backend.models import EventUserStatus


class VisitRequest(BaseModel):
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.

поменять на Base

status: EventUserStatus
updated_at: datetime.datetime

model_config = {"from_attributes": True}
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.

убрать

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

создать новую таблицу сделать post event/{event_id}/visit/

2 participants