from sqlalchemy import select from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import Session from app.core.utils.time import utc_now from app.modules.feishu.models import FeishuAppTicket APP_TICKET_EVENT_TYPE = "app_ticket" APP_TICKET_PAYLOAD_KEY = "app_ticket" class FeishuAppTicketService: """Persist the latest ticket received through a verified Feishu event.""" def __init__(self, db: Session): self.db = db def get_ticket(self, app_id: str) -> str | None: app_id_value = str(app_id).strip() if not app_id_value: return None return self.db.scalar( select(FeishuAppTicket.app_ticket).where( FeishuAppTicket.app_id == app_id_value ) ) def store_verified(self, app_id: str, ticket: str) -> FeishuAppTicket: app_id_value = str(app_id).strip() ticket_value = str(ticket).strip() if not app_id_value or not ticket_value: raise ValueError("Verified Feishu app ticket fields are required") now = utc_now() record = self.db.execute( select(FeishuAppTicket) .where(FeishuAppTicket.app_id == app_id_value) .with_for_update() ).scalar_one_or_none() if record is None: record = FeishuAppTicket( app_id=app_id_value, app_ticket=ticket_value, received_at=now, updated_at=now, ) try: with self.db.begin_nested(): self.db.add(record) self.db.flush() except IntegrityError: record = self.db.execute( select(FeishuAppTicket) .where(FeishuAppTicket.app_id == app_id_value) .with_for_update() ).scalar_one() record.app_ticket = ticket_value record.received_at = now record.updated_at = now self.db.commit() self.db.refresh(record) return record