Загрузка данных


from flask import Blueprint, render_template, request
from flask_login import login_required, current_user

from app.models import Intern, User
from app.services.statistics import intern_stats, center_stats
from app.utils import parse_period

main_bp = Blueprint("main", __name__)


@main_bp.route("/")
@login_required
def dashboard():
    date_from, date_to = parse_period(default_days=30)

    if current_user.is_admin:
        mentors = User.query.filter_by(role="mentor").order_by(User.full_name).all()
        mentor_id = request.args.get("mentor_id", type=int)

        q = Intern.query
        if mentor_id:
            q = q.filter_by(mentor_id=mentor_id)
        interns = q.order_by(Intern.full_name).all()

        rows = [
            {"intern": i, "stats": intern_stats(i.id, date_from, date_to)}
            for i in interns
        ]
        overview = center_stats(date_from, date_to, mentor_id)

        return render_template(
            "dashboard/admin.html",
            rows=rows, mentors=mentors,
            selected_mentor=mentor_id,
            overview=overview,
            date_from=date_from, date_to=date_to,
        )

    # Наставник
    interns = (
        Intern.query.filter_by(mentor_id=current_user.id)
        .order_by(Intern.full_name).all()
    )
    rows = [
        {"intern": i, "stats": intern_stats(i.id, date_from, date_to)}
        for i in interns
    ]
    overview = center_stats(date_from, date_to, current_user.id)

    return render_template(
        "dashboard/mentor.html",
        rows=rows, overview=overview,
        date_from=date_from, date_to=date_to,
    )