"""N01 to N05: preferences, consent history and the all-videos export request.""" from sqlalchemy.ext.asyncio import AsyncSession from app.core.config import get_settings from app.core.errors import Conflict, Unprocessable, ValidationFailed from app.modules.accounts.models import Account from app.modules.settings.models import UserSettings from app.modules.settings.repository import ConsentRepository, ExportRepository, SettingsRepository from app.modules.settings.schemas import ( ConsentEnvelope, ConsentIn, ConsentOut, ExportEnvelope, ExportOut, SettingsOut, SettingsPatch, ) FLAGS = ("coach_can_see_sessions", "share_with_parent", "private_links", "clips_as_examples", "help_improve_ai", "notify_results", "notify_coach", "notify_drills", "notify_weekly", "skip_filming_guide") DEFAULTS = {"coach_can_see_sessions": True, "share_with_parent": False, "parent_email": None, "auto_monthly_report": False, "private_links": False, "clips_as_examples": False, "help_improve_ai": False, "notify_results": True, "notify_coach": True, "notify_drills": True, "notify_weekly": True, "skip_filming_guide": False, "version": 1} OPT_INS = ("help_improve_ai", "clips_as_examples") class SettingsService: def __init__(self, db: AsyncSession): self.settings = SettingsRepository(db) self.consents = ConsentRepository(db) self.exports = ExportRepository(db) async def _out(self, account: Account, row: UserSettings | None) -> SettingsOut: values = {k: getattr(row, k) for k in DEFAULTS} if row else dict(DEFAULTS) event = await self.consents.latest(account.id) accepted = event is not None and event.action == "accepted" return SettingsOut(**values, consented_at=event.created_at if accepted else None, consent_version=event.policy_version if accepted else None) # N01 async def get(self, account: Account) -> SettingsOut: return await self._out(account, await self.settings.get(account.id)) # N02 async def update(self, account: Account, body: SettingsPatch) -> SettingsOut: changes = body.model_dump(exclude_unset=True, exclude={"expected_version"}) if not changes: raise ValidationFailed(fields={"body": "Send at least one setting to change."}) for name in (*FLAGS, "auto_monthly_report"): if name in changes and changes[name] is None: raise ValidationFailed(fields={name: "Must be true or false."}) row = await self.settings.locked(account.id) if body.expected_version is not None and body.expected_version != row.version: raise Conflict("This item changed. Refresh and try again.", code="STALE_VERSION") share = changes.get("share_with_parent", row.share_with_parent) email = changes["parent_email"] if "parent_email" in changes else row.parent_email if changes.get("auto_monthly_report") and not (share and email): raise Unprocessable( "Turn on parent sharing and add a parent email first.", code="VALIDATION", fields={"auto_monthly_report": "Requires share_with_parent and parent_email."}) if not share: changes["auto_monthly_report"] = False for name in OPT_INS: if name in changes and changes[name] != getattr(row, name): await self.consents.create(account_id=account.id, category=name, action="accepted" if changes[name] else "withdrawn") await self.settings.update(row, **changes, version=row.version + 1) return await self._out(account, row) # N03 async def accept(self, account: Account, body: ConsentIn) -> ConsentEnvelope: if body.version not in get_settings().consent_versions: raise Conflict("The terms changed. Please review the latest version.", code="TERMS_CHANGED") event = await self.consents.latest(account.id) if event is None or event.action != "accepted" or event.policy_version != body.version: event = await self.consents.create(account_id=account.id, category="analysis", action="accepted", policy_version=body.version) return ConsentEnvelope(consent=ConsentOut(version=event.policy_version, accepted_at=event.created_at)) # N04 async def withdraw(self, account: Account) -> None: event = await self.consents.latest(account.id) if event is not None and event.action == "accepted": await self.consents.create(account_id=account.id, category="analysis", action="withdrawn", policy_version=event.policy_version) # N05 async def request_export(self, account: Account) -> ExportEnvelope: if not account.email: raise Unprocessable("Your account has no email address.", code="EMAIL_UNAVAILABLE") if await self.exports.queued(account.id, "videos") is not None: raise Conflict("An export is already on its way to your email.", code="EXPORT_IN_PROGRESS") job = await self.exports.create(requester_id=account.id, scope="videos", status="queued") return ExportEnvelope(export=ExportOut(id=job.id, status=job.status, requested_at=job.created_at))