morozovka-portal/app/modules/notifications_routes.py

64 lines
2.7 KiB
Python

"""Роуты для уведомлений (in-app колокольчик)."""
from flask import render_template, jsonify, session
from sqlmodel import Session, select
from ..db import engine
from ..models import Notification
from ..helpers import login_required
def register(app):
@app.route("/api/notifications")
@login_required
def api_notifications_list():
uid = session.get("user_id")
with Session(engine) as s:
items = s.exec(select(Notification).where(Notification.user_id == uid)
.order_by(Notification.created_at.desc()).limit(20)).all()
unread = s.exec(select(Notification).where(Notification.user_id == uid)
.where(Notification.is_read == False)).all()
return jsonify({
"items": [{"id": n.id, "title": n.title, "body": n.body,
"link_url": n.link_url, "kind": n.kind, "is_read": n.is_read,
"created_at": n.created_at.isoformat() + "Z"} for n in items],
"unread": len(unread)})
@app.route("/api/notifications/count")
@login_required
def api_notifications_count():
uid = session.get("user_id")
with Session(engine) as s:
unread = s.exec(select(Notification).where(Notification.user_id == uid)
.where(Notification.is_read == False)).all()
return jsonify({"unread": len(unread)})
@app.route("/api/notifications/<int:nid>/read", methods=["POST"])
@login_required
def api_notifications_read(nid):
uid = session.get("user_id")
with Session(engine) as s:
n = s.get(Notification, nid)
if not n or n.user_id != uid: return jsonify({"ok": False}), 403
n.is_read = True; s.add(n); s.commit()
return jsonify({"ok": True})
@app.route("/api/notifications/read-all", methods=["POST"])
@login_required
def api_notifications_read_all():
uid = session.get("user_id")
with Session(engine) as s:
for n in s.exec(select(Notification).where(Notification.user_id == uid)
.where(Notification.is_read == False)).all():
n.is_read = True; s.add(n)
s.commit()
return jsonify({"ok": True})
@app.route("/notifications")
@login_required
def notifications_page():
uid = session.get("user_id")
with Session(engine) as s:
items = s.exec(select(Notification).where(Notification.user_id == uid)
.order_by(Notification.created_at.desc()).limit(100)).all()
return render_template("notifications_page.html", notifications=items)