|
| 1 | +from datetime import datetime, timedelta, timezone |
| 2 | +from typing import List, Optional |
| 3 | +from zoneinfo import ZoneInfo |
| 4 | + |
| 5 | +from google.cloud import firestore |
| 6 | + |
| 7 | +from src.Domains.Entities.NotificationSchedule import NotificationSchedule |
| 8 | +from src.firestore_client import firestore_client |
| 9 | + |
| 10 | + |
| 11 | +class NotificationScheduleRepository: |
| 12 | + _collection_name = "notification_schedules" |
| 13 | + _default_notify_time = "12:00" |
| 14 | + _default_timezone = "Asia/Tokyo" |
| 15 | + |
| 16 | + def _collection(self): |
| 17 | + return firestore_client.collection(self._collection_name) |
| 18 | + |
| 19 | + def find_due(self, now_utc: datetime, limit: int = 500) -> List[NotificationSchedule]: |
| 20 | + query = ( |
| 21 | + self._collection() |
| 22 | + .where("enabled", "==", True) |
| 23 | + .where("next_notify_at", "<=", now_utc) |
| 24 | + .order_by("next_notify_at", direction=firestore.Query.ASCENDING) |
| 25 | + .limit(limit) |
| 26 | + ) |
| 27 | + schedules: List[NotificationSchedule] = [] |
| 28 | + for doc in query.stream(): |
| 29 | + data = doc.to_dict() or {} |
| 30 | + data["line_user_id"] = doc.id |
| 31 | + schedules.append(NotificationSchedule(**data)) |
| 32 | + return schedules |
| 33 | + |
| 34 | + def find_by_line_user_id(self, line_user_id: str) -> Optional[NotificationSchedule]: |
| 35 | + snapshot = self._collection().document(line_user_id).get() |
| 36 | + if not snapshot.exists: |
| 37 | + return None |
| 38 | + data = snapshot.to_dict() or {} |
| 39 | + data["line_user_id"] = snapshot.id |
| 40 | + return NotificationSchedule(**data) |
| 41 | + |
| 42 | + def compute_next_notify_at( |
| 43 | + self, |
| 44 | + notify_time: Optional[str], |
| 45 | + timezone_name: Optional[str], |
| 46 | + base_time_utc: datetime, |
| 47 | + ) -> datetime: |
| 48 | + safe_notify_time = notify_time or self._default_notify_time |
| 49 | + safe_timezone = timezone_name or self._default_timezone |
| 50 | + try: |
| 51 | + hour, minute = [int(x) for x in safe_notify_time.split(":", 1)] |
| 52 | + except (ValueError, TypeError): |
| 53 | + hour, minute = [int(x) for x in self._default_notify_time.split(":", 1)] |
| 54 | + |
| 55 | + local_tz = ZoneInfo(safe_timezone) |
| 56 | + local_now = base_time_utc.astimezone(local_tz) |
| 57 | + try: |
| 58 | + next_local = local_now.replace( |
| 59 | + hour=hour, |
| 60 | + minute=minute, |
| 61 | + second=0, |
| 62 | + microsecond=0, |
| 63 | + ) |
| 64 | + except ValueError: |
| 65 | + default_hour, default_minute = [int(x) for x in self._default_notify_time.split(":", 1)] |
| 66 | + next_local = local_now.replace( |
| 67 | + hour=default_hour, |
| 68 | + minute=default_minute, |
| 69 | + second=0, |
| 70 | + microsecond=0, |
| 71 | + ) |
| 72 | + if next_local <= local_now: |
| 73 | + next_local += timedelta(days=1) |
| 74 | + return next_local.astimezone(timezone.utc) |
| 75 | + |
| 76 | + def claim_and_schedule_next(self, line_user_id: str, now_utc: datetime) -> bool: |
| 77 | + doc_ref = self._collection().document(line_user_id) |
| 78 | + transaction = firestore_client.transaction() |
| 79 | + |
| 80 | + @firestore.transactional |
| 81 | + def _claim(tx): |
| 82 | + snapshot = doc_ref.get(transaction=tx) |
| 83 | + if not snapshot.exists: |
| 84 | + return False |
| 85 | + |
| 86 | + data = snapshot.to_dict() or {} |
| 87 | + if not data.get("enabled", True): |
| 88 | + return False |
| 89 | + |
| 90 | + next_notify_at = data.get("next_notify_at") |
| 91 | + if next_notify_at is None: |
| 92 | + return False |
| 93 | + if next_notify_at > now_utc: |
| 94 | + return False |
| 95 | + |
| 96 | + next_at = self.compute_next_notify_at( |
| 97 | + notify_time=data.get("notify_time"), |
| 98 | + timezone_name=data.get("timezone"), |
| 99 | + base_time_utc=now_utc, |
| 100 | + ) |
| 101 | + tx.update( |
| 102 | + doc_ref, |
| 103 | + { |
| 104 | + "next_notify_at": next_at, |
| 105 | + "updated_at": now_utc, |
| 106 | + }, |
| 107 | + ) |
| 108 | + return True |
| 109 | + |
| 110 | + return bool(_claim(transaction)) |
| 111 | + |
| 112 | + def upsert( |
| 113 | + self, |
| 114 | + line_user_id: str, |
| 115 | + notify_time: str = "12:00", |
| 116 | + timezone_name: str = "Asia/Tokyo", |
| 117 | + enabled: Optional[bool] = None, |
| 118 | + base_time_utc: Optional[datetime] = None, |
| 119 | + ) -> NotificationSchedule: |
| 120 | + now_utc = base_time_utc or datetime.now(timezone.utc) |
| 121 | + next_notify_at = self.compute_next_notify_at( |
| 122 | + notify_time=notify_time, |
| 123 | + timezone_name=timezone_name, |
| 124 | + base_time_utc=now_utc, |
| 125 | + ) |
| 126 | + doc_ref = self._collection().document(line_user_id) |
| 127 | + snapshot = doc_ref.get() |
| 128 | + data = snapshot.to_dict() or {} |
| 129 | + merged_enabled = data.get("enabled", True) if enabled is None else enabled |
| 130 | + created_at = data.get("created_at", now_utc) |
| 131 | + payload = { |
| 132 | + "notify_time": notify_time, |
| 133 | + "timezone": timezone_name, |
| 134 | + "enabled": merged_enabled, |
| 135 | + "next_notify_at": next_notify_at, |
| 136 | + "updated_at": now_utc, |
| 137 | + } |
| 138 | + if not snapshot.exists: |
| 139 | + payload["created_at"] = now_utc |
| 140 | + doc_ref.set(payload, merge=True) |
| 141 | + return NotificationSchedule( |
| 142 | + line_user_id=line_user_id, |
| 143 | + notify_time=notify_time, |
| 144 | + timezone=timezone_name, |
| 145 | + enabled=merged_enabled, |
| 146 | + next_notify_at=next_notify_at, |
| 147 | + created_at=created_at, |
| 148 | + updated_at=now_utc, |
| 149 | + ) |
0 commit comments