81 lines
2.3 KiB
Python
81 lines
2.3 KiB
Python
from datetime import datetime, timezone
|
|
|
|
from sqlalchemy import delete, select
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.notifications.models import NotificationLog, PushDeviceToken
|
|
|
|
|
|
async def create_notification_log(db: AsyncSession, *, user_id: int, event_type: str, payload: str) -> None:
|
|
db.add(NotificationLog(user_id=user_id, event_type=event_type, payload=payload))
|
|
|
|
|
|
async def list_user_notifications(db: AsyncSession, *, user_id: int, limit: int = 50) -> list[NotificationLog]:
|
|
result = await db.execute(
|
|
select(NotificationLog)
|
|
.where(NotificationLog.user_id == user_id)
|
|
.order_by(NotificationLog.id.desc())
|
|
.limit(limit)
|
|
)
|
|
return list(result.scalars().all())
|
|
|
|
|
|
async def upsert_push_device_token(
|
|
db: AsyncSession,
|
|
*,
|
|
user_id: int,
|
|
platform: str,
|
|
token: str,
|
|
device_id: str | None,
|
|
app_version: str | None,
|
|
) -> PushDeviceToken:
|
|
result = await db.execute(
|
|
select(PushDeviceToken).where(
|
|
PushDeviceToken.user_id == user_id,
|
|
PushDeviceToken.platform == platform,
|
|
PushDeviceToken.token == token,
|
|
)
|
|
)
|
|
existing = result.scalar_one_or_none()
|
|
if existing is not None:
|
|
existing.device_id = device_id
|
|
existing.app_version = app_version
|
|
existing.updated_at = datetime.now(timezone.utc)
|
|
await db.flush()
|
|
return existing
|
|
|
|
record = PushDeviceToken(
|
|
user_id=user_id,
|
|
platform=platform,
|
|
token=token,
|
|
device_id=device_id,
|
|
app_version=app_version,
|
|
)
|
|
db.add(record)
|
|
await db.flush()
|
|
return record
|
|
|
|
|
|
async def delete_push_device_token(
|
|
db: AsyncSession,
|
|
*,
|
|
user_id: int,
|
|
platform: str,
|
|
token: str,
|
|
) -> int:
|
|
result = await db.execute(
|
|
delete(PushDeviceToken).where(
|
|
PushDeviceToken.user_id == user_id,
|
|
PushDeviceToken.platform == platform,
|
|
PushDeviceToken.token == token,
|
|
)
|
|
)
|
|
return int(result.rowcount or 0)
|
|
|
|
|
|
async def list_push_tokens_for_user(db: AsyncSession, *, user_id: int) -> list[PushDeviceToken]:
|
|
result = await db.execute(
|
|
select(PushDeviceToken).where(PushDeviceToken.user_id == user_id).order_by(PushDeviceToken.id.asc())
|
|
)
|
|
return list(result.scalars().all())
|