Skip to content

Commit

Permalink
Merge pull request #33 from wafflestudio/vote_participation
Browse files Browse the repository at this point in the history
Vote participants
  • Loading branch information
morecleverer authored Jan 19, 2025
2 parents f8df30f + 003a595 commit a136a68
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 6 deletions.
26 changes: 24 additions & 2 deletions snuvote/app/vote/dto/responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,18 +31,26 @@ class VotesListInfoResponse(BaseModel):
create_datetime: Annotated[datetime, AfterValidator(convert_utc_to_ktc_naive)] # UTC 시간대를 KST 시간대로 변환한 뒤 offset-naive로 변환
end_datetime: Annotated[datetime, AfterValidator(convert_utc_to_ktc_naive)] # UTC 시간대를 KST 시간대로 변환한 뒤 offset-naive로 변환
participated: bool
participant_count: int
image: str| None

@staticmethod
def from_vote_user(vote: Vote, user: User) -> "VotesListInfoResponse":

# 해당 유저의 참여 여부도 포함시켜야 함
# 해당 유저의 참여 여부, 전체 참여자 수 계산
participated = False
participant_set = set()
for choice in vote.choices:
for choice_participation in choice.choice_participations:

#해당 유저가 참여했는지 여부
if choice_participation.user_id == user.id:
participated = True
break

#참여자를 집합에 넣기(중복 미포함)
participant_set.add(choice_participation.user_id)



return VotesListInfoResponse(
id=vote.id,
Expand All @@ -51,6 +59,7 @@ def from_vote_user(vote: Vote, user: User) -> "VotesListInfoResponse":
create_datetime=vote.create_datetime,
end_datetime=vote.end_datetime,
participated = participated,
participant_count= len(participant_set),
image= vote.images[0].src if vote.images else None
)

Expand Down Expand Up @@ -149,4 +158,17 @@ class VoteDetailResponse(BaseModel):
choices: List[ChoiceDetailResponse]
comments: List[CommentDetailResponse]
images: List[str]
participant_count: int

#Vote를 받아 참여자 수를 계산함
@staticmethod
def get_participant_count_from_vote(vote: Vote) -> int:

participant_set = set()
for choice in vote.choices:
for choice_participation in choice.choice_participations:
#참여자를 집합에 넣기(중복 미포함)
participant_set.add(choice_participation.user_id)

return len(participant_set)

6 changes: 5 additions & 1 deletion snuvote/app/vote/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,4 +63,8 @@ def __init__(self) -> None:

class CommentNotInThisVoteError(HTTPException):
def __init__(self) -> None:
super().__init__(HTTP_404_NOT_FOUND, "Comment not in this vote")
super().__init__(HTTP_404_NOT_FOUND, "Comment not in this vote")

class InvalidFileExtensionError(HTTPException):
def __init__(self) -> None:
super().__init__(HTTP_400_BAD_REQUEST, "Invalid file extension")
11 changes: 10 additions & 1 deletion snuvote/app/vote/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from fastapi import Depends, UploadFile
from snuvote.database.models import Vote, User, Choice, ChoiceParticipation, Comment
from snuvote.app.vote.store import VoteStore
from snuvote.app.vote.errors import ChoiceNotFoundError, InvalidFieldFormatError, MultipleChoicesError, ParticipationCodeError, ParticipationCodeNotProvidedError, WrongParticipationCodeError, EndedVoteError, CommentNotYoursError, CommentNotInThisVoteError
from snuvote.app.vote.errors import ChoiceNotFoundError, InvalidFieldFormatError, MultipleChoicesError, ParticipationCodeError, ParticipationCodeNotProvidedError, WrongParticipationCodeError, EndedVoteError, CommentNotYoursError, CommentNotInThisVoteError, InvalidFileExtensionError
from snuvote.app.vote.dto.requests import ParticipateVoteRequest, CommentRequest

from datetime import datetime, timedelta, timezone
Expand All @@ -12,6 +12,9 @@
import os
import boto3


ALLOWED_EXTENSIONS = {"jpg", "jpeg", "png", "gif"}

class VoteService:
def __init__(self, vote_store: Annotated[VoteStore, Depends()]) -> None:
self.vote_store = vote_store
Expand Down Expand Up @@ -71,6 +74,12 @@ def add_vote(self,

# 이미지 업로드
if images:
# 확장자가 안 맞으면 오류
for image in images:
filename = image.filename
extension = filename.split(".")[-1].lower() # 확장자 추출 및 소문자로 변환
if extension not in ALLOWED_EXTENSIONS:
raise InvalidFileExtensionError
self.upload_vote_images(vote, images)

return self.vote_store.get_vote_by_vote_id(vote_id=vote.id)
Expand Down
7 changes: 5 additions & 2 deletions snuvote/app/vote/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

from snuvote.app.vote.dto.requests import CreateVoteRequest, ParticipateVoteRequest, CommentRequest
from snuvote.app.vote.dto.responses import OnGoingVotesListResponse, VotesListInfoResponse, VoteDetailResponse, ChoiceDetailResponse, CommentDetailResponse
from snuvote.app.vote.errors import VoteNotFoundError, MultipleChoicesError, ChoiceNotFoundError, CommentNotFoundError
from snuvote.app.vote.errors import VoteNotFoundError, ChoiceNotFoundError, CommentNotFoundError
from datetime import datetime, timedelta, timezone

from snuvote.database.models import User
Expand All @@ -19,6 +19,7 @@

security = HTTPBearer()


#create vote
@vote_router.post("/create", status_code=HTTP_201_CREATED)
def create_vote(
Expand All @@ -27,6 +28,7 @@ def create_vote(
images: List[UploadFile]|None = File(None),
create_vote_json = Form(media_type="multipart/form-data", json_schema_extra=CreateVoteRequest.model_json_schema())
):

create_vote_request = CreateVoteRequest.model_validate_json(create_vote_json)


Expand Down Expand Up @@ -93,7 +95,8 @@ def get_vote(
end_datetime = vote.end_datetime,
choices= [ChoiceDetailResponse.from_choice(choice, user, vote.annonymous_choice, vote.realtime_result) for choice in vote.choices],
comments = [CommentDetailResponse.from_comment_user(comment, user) for comment in vote.comments if comment.is_deleted==False],
images = [image.src for image in vote.images]
images = [image.src for image in vote.images],
participant_count = VoteDetailResponse.get_participant_count_from_vote(vote)
)


Expand Down

0 comments on commit a136a68

Please sign in to comment.