|
| 1 | +from typing import Optional, List |
| 2 | +from datetime import datetime, timezone |
| 3 | + |
| 4 | +from todo.repositories.common.mongo_repository import MongoRepository |
| 5 | +from todo.models.team_creation_invite_code import TeamCreationInviteCodeModel |
| 6 | +from todo.repositories.user_repository import UserRepository |
| 7 | + |
| 8 | + |
| 9 | +class TeamCreationInviteCodeRepository(MongoRepository): |
| 10 | + """Repository for team creation invite code operations.""" |
| 11 | + |
| 12 | + collection_name = TeamCreationInviteCodeModel.collection_name |
| 13 | + |
| 14 | + @classmethod |
| 15 | + def is_code_valid(cls, code: str) -> Optional[dict]: |
| 16 | + """Check if a code is available for use (unused).""" |
| 17 | + collection = cls.get_collection() |
| 18 | + try: |
| 19 | + code_data = collection.find_one({"code": code, "is_used": False}) |
| 20 | + return code_data |
| 21 | + except Exception as e: |
| 22 | + raise Exception(f"Error checking if code is valid: {e}") |
| 23 | + |
| 24 | + @classmethod |
| 25 | + def validate_and_consume_code(cls, code: str, used_by: str) -> Optional[dict]: |
| 26 | + """Validate and consume a code in one atomic operation using findOneAndUpdate.""" |
| 27 | + collection = cls.get_collection() |
| 28 | + try: |
| 29 | + current_time = datetime.now(timezone.utc) |
| 30 | + result = collection.find_one_and_update( |
| 31 | + {"code": code, "is_used": False}, |
| 32 | + {"$set": {"is_used": True, "used_by": used_by, "used_at": current_time.isoformat()}}, |
| 33 | + return_document=True, |
| 34 | + ) |
| 35 | + return result |
| 36 | + except Exception as e: |
| 37 | + raise Exception(f"Error validating and consuming code: {e}") |
| 38 | + |
| 39 | + @classmethod |
| 40 | + def create(cls, team_invite_code: TeamCreationInviteCodeModel) -> TeamCreationInviteCodeModel: |
| 41 | + """Create a new team invite code.""" |
| 42 | + collection = cls.get_collection() |
| 43 | + team_invite_code.created_at = datetime.now(timezone.utc) |
| 44 | + |
| 45 | + code_dict = team_invite_code.model_dump(mode="json", by_alias=True, exclude_none=True) |
| 46 | + insert_result = collection.insert_one(code_dict) |
| 47 | + team_invite_code.id = insert_result.inserted_id |
| 48 | + return team_invite_code |
| 49 | + |
| 50 | + @classmethod |
| 51 | + def get_all_codes(cls, page: int = 1, limit: int = 10) -> tuple[List[dict], int]: |
| 52 | + """Get paginated team creation invite codes with user details for created_by and used_by.""" |
| 53 | + collection = cls.get_collection() |
| 54 | + try: |
| 55 | + skip = (page - 1) * limit |
| 56 | + |
| 57 | + total_count = collection.count_documents({}) |
| 58 | + |
| 59 | + codes = list(collection.find().sort("created_at", -1).skip(skip).limit(limit)) |
| 60 | + |
| 61 | + enhanced_codes = [] |
| 62 | + for code in codes: |
| 63 | + created_by_user = None |
| 64 | + used_by_user = None |
| 65 | + |
| 66 | + if code.get("created_by"): |
| 67 | + user = UserRepository.get_by_id(str(code["created_by"])) |
| 68 | + if user: |
| 69 | + created_by_user = {"id": str(user.id), "name": user.name} |
| 70 | + |
| 71 | + if code.get("used_by"): |
| 72 | + user = UserRepository.get_by_id(str(code["used_by"])) |
| 73 | + if user: |
| 74 | + used_by_user = {"id": str(user.id), "name": user.name} |
| 75 | + |
| 76 | + enhanced_code = { |
| 77 | + "id": str(code["_id"]), |
| 78 | + "code": code["code"], |
| 79 | + "description": code.get("description"), |
| 80 | + "created_at": code.get("created_at"), |
| 81 | + "used_at": code.get("used_at"), |
| 82 | + "is_used": code.get("is_used", False), |
| 83 | + "created_by": created_by_user or {}, |
| 84 | + "used_by": used_by_user, |
| 85 | + } |
| 86 | + enhanced_codes.append(enhanced_code) |
| 87 | + |
| 88 | + return enhanced_codes, total_count |
| 89 | + except Exception as e: |
| 90 | + raise Exception(f"Error getting all codes with user details: {e}") |
0 commit comments