backend: add push token API and FCM delivery pipeline

This commit is contained in:
Codex
2026-03-09 23:12:19 +03:00
parent e82178fcc3
commit 74b086b9c8
11 changed files with 296 additions and 13 deletions

View File

@@ -1,6 +1,9 @@
from datetime import datetime, timezone
from sqlalchemy import delete, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.notifications.models import NotificationLog
from app.notifications.models import NotificationLog, PushDeviceToken
async def create_notification_log(db: AsyncSession, *, user_id: int, event_type: str, payload: str) -> None:
@@ -8,8 +11,6 @@ async def create_notification_log(db: AsyncSession, *, user_id: int, event_type:
async def list_user_notifications(db: AsyncSession, *, user_id: int, limit: int = 50) -> list[NotificationLog]:
from sqlalchemy import select
result = await db.execute(
select(NotificationLog)
.where(NotificationLog.user_id == user_id)
@@ -17,3 +18,63 @@ async def list_user_notifications(db: AsyncSession, *, user_id: int, limit: int
.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())