This commit is contained in:
2026-02-19 21:36:58 +00:00
committed by Anibal Angulo
parent 41ba38495b
commit 085e4b8610
37 changed files with 625 additions and 2200 deletions

View File

@@ -1,18 +1,10 @@
"""
Copyright 2025 Google. This software is provided as-is, without warranty or
representation for any use or purpose. Your use of it is subject to your
agreement with Google.
Firestore service for persistent conversation storage.
"""
import logging
from datetime import datetime
from google.cloud import firestore
from ..config import Settings
from ..models import ConversationSessionDTO, ConversationEntryDTO
from ..models.notification import NotificationDTO
from ..models.notification import Notification
logger = logging.getLogger(__name__)
@@ -41,7 +33,7 @@ class FirestoreService:
async def close(self):
"""Close Firestore client."""
await self.db.close()
self.db.close()
logger.info("Firestore client closed")
def _session_ref(self, session_id: str):
@@ -83,7 +75,7 @@ class FirestoreService:
"""
try:
query = (
self.db.collection(self.sessions_collection)
self.db.collection(self.conversations_collection)
.where("telefono", "==", telefono)
.order_by("lastModified", direction=firestore.Query.DESCENDING)
.limit(1)
@@ -122,6 +114,44 @@ class FirestoreService:
)
return False
async def create_session(
self,
session_id: str,
user_id: str,
telefono: str,
pantalla_contexto: str | None = None,
last_message: str | None = None,
) -> ConversationSessionDTO:
"""Create and save a new conversation session to Firestore.
Args:
session_id: Unique session identifier
user_id: User identifier
telefono: User phone number
pantalla_contexto: Optional screen context for the conversation
last_message: Optional last message in the conversation
Returns:
The created session
Raises:
Exception: If session creation or save fails
"""
session = ConversationSessionDTO.create(
session_id=session_id,
user_id=user_id,
telefono=telefono,
pantalla_contexto=pantalla_contexto,
last_message=last_message,
)
doc_ref = self._session_ref(session.sessionId)
data = session.model_dump()
await doc_ref.set(data, merge=True)
logger.info(f"Created new session in Firestore: {session_id}")
return session
async def save_entry(self, session_id: str, entry: ConversationEntryDTO) -> bool:
"""Save conversation entry to Firestore subcollection."""
try:
@@ -196,6 +226,46 @@ class FirestoreService:
)
return False
async def update_pantalla_contexto(
self, session_id: str, pantalla_contexto: str | None
) -> bool:
"""Update the pantallaContexto field for a conversation session.
Args:
session_id: Session ID to update
pantalla_contexto: New pantalla contexto value
Returns:
True if update was successful, False otherwise
"""
try:
doc_ref = self._session_ref(session_id)
doc = await doc_ref.get()
if not doc.exists:
logger.warning(
f"Session {session_id} not found in Firestore. Cannot update pantallaContexto"
)
return False
await doc_ref.update(
{
"pantallaContexto": pantalla_contexto,
"lastModified": datetime.now(),
}
)
logger.debug(
f"Updated pantallaContexto for session {session_id} in Firestore"
)
return True
except Exception as e:
logger.error(
f"Error updating pantallaContexto for session {session_id} in Firestore: {str(e)}"
)
return False
# ====== Notification Methods ======
def _notification_ref(self, notification_id: str):
@@ -204,7 +274,7 @@ class FirestoreService:
notification_id
)
async def save_or_append_notification(self, new_entry: NotificationDTO) -> None:
async def save_or_append_notification(self, new_entry: Notification) -> None:
"""
Save or append notification entry to Firestore.