feat(audit & reports): stabilize live presence, day intervals and reports logic before topics feature
This commit is contained in:
@@ -2,7 +2,7 @@
|
||||
===============================================================================
|
||||
FILE: modules/web_api/routers/reports.py
|
||||
ROLE: REST API On-Demand генерации отчетов:
|
||||
- Сводка: за СЕГОДНЯ (оперативный контроль, текущий срез).
|
||||
- Сводка: за СЕГОДНЯ (по выбранному snapshot_id или последнему срезу).
|
||||
- Детальный и Упрощенный отчет: строго за ВЧЕРА по финальному срезу Y.
|
||||
===============================================================================
|
||||
"""
|
||||
@@ -40,13 +40,14 @@ class GenerateReportRequest(BaseModel):
|
||||
date: Optional[str] = None # ДД.ММ.ГГГГ
|
||||
time: Optional[str] = None # ЧЧ:ММ
|
||||
report_type: str # 'SVODKA', 'DETAILED', 'SIMPLIFIED', 'ALL'
|
||||
snapshot_id: Optional[str] = None # ⭐️ ID конкретного среза (например: '20261006_1200')
|
||||
|
||||
|
||||
@router.post("/generate")
|
||||
def api_generate_report(req: GenerateReportRequest):
|
||||
"""
|
||||
Генерирует выбранный отчет:
|
||||
- SVODKA: на текущую дату (date).
|
||||
- SVODKA: по выбранному snapshot_id (или на дату/время).
|
||||
- DETAILED / SIMPLIFIED: строго за вчерашний рабочий день по финальному срезу Y.
|
||||
"""
|
||||
target_date = (req.date or DATE_TODAY).replace('_', '.')
|
||||
@@ -54,11 +55,12 @@ def api_generate_report(req: GenerateReportRequest):
|
||||
r_type = req.report_type.upper()
|
||||
results = []
|
||||
|
||||
# 1. Ежедневная сводка (за СЕГОДНЯ)
|
||||
# 1. Ежедневная сводка
|
||||
if r_type in ["SVODKA", "ALL"]:
|
||||
res_svodka = generate_svodka_service(
|
||||
target_date=target_date,
|
||||
target_time=req.time
|
||||
target_time=req.time,
|
||||
snapshot_id=req.snapshot_id # ⭐️ Передаем срез
|
||||
)
|
||||
if res_svodka.get("status") == "success":
|
||||
results.append({
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
"""
|
||||
===============================================================================
|
||||
FILE: modules/web_api/routers/schedules.py
|
||||
ROLE: REST API управления графиками работы и генерации отчетов по опозданиям.
|
||||
===============================================================================
|
||||
"""
|
||||
|
||||
import os
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from pydantic import BaseModel
|
||||
from typing import Optional, List, Dict, Any
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from routers.auth import get_current_user
|
||||
from services.schedules.service import (
|
||||
get_all_templates,
|
||||
get_employee_schedules_list,
|
||||
update_employee_schedule
|
||||
)
|
||||
from services.reports.opozdaniya_builder import build_opozdaniya_workbook
|
||||
from config import DATE_TODAY
|
||||
|
||||
router = APIRouter(prefix="/api/v1/schedules", tags=["Schedules"])
|
||||
|
||||
|
||||
class UpdateScheduleRequest(BaseModel):
|
||||
employee_schedule_id: int
|
||||
template_id: int
|
||||
doc_basis: Optional[str] = None
|
||||
comment: Optional[str] = None
|
||||
date_from: Optional[str] = None
|
||||
date_to: Optional[str] = None
|
||||
|
||||
|
||||
class GenerateLateReportRequest(BaseModel):
|
||||
date_from: Optional[str] = None
|
||||
date_to: Optional[str] = None
|
||||
report_type: str = "WEEKLY"
|
||||
|
||||
|
||||
@router.get("/templates")
|
||||
def api_get_templates(current_user = Depends(get_current_user)):
|
||||
return {"templates": get_all_templates()}
|
||||
|
||||
|
||||
@router.get("/employees")
|
||||
def api_get_employees_schedules(
|
||||
q: Optional[str] = Query(None, description="Поиск по ФИО"),
|
||||
department: Optional[str] = Query(None, description="Фильтр по отделу"),
|
||||
mode: Optional[str] = Query(None, description="Фильтр по режиму работы"),
|
||||
current_user = Depends(get_current_user)
|
||||
):
|
||||
return {"items": get_employee_schedules_list(fio_query=q, department=department, work_mode=mode)}
|
||||
|
||||
|
||||
@router.put("/assign")
|
||||
def api_update_schedule(req: UpdateScheduleRequest, current_user = Depends(get_current_user)):
|
||||
success = update_employee_schedule(
|
||||
employee_schedule_id=req.employee_schedule_id,
|
||||
template_id=req.template_id,
|
||||
doc_basis=req.doc_basis,
|
||||
comment=req.comment,
|
||||
date_from=req.date_from,
|
||||
date_to=req.date_to
|
||||
)
|
||||
if not success:
|
||||
raise HTTPException(status_code=400, detail="Не удалось обновить график сотрудника")
|
||||
return {"status": "success", "message": "График успешно обновлен"}
|
||||
|
||||
|
||||
@router.post("/reports/late-arrivals")
|
||||
def api_generate_late_arrivals_report(req: GenerateLateReportRequest, current_user = Depends(get_current_user)):
|
||||
"""
|
||||
Генерирует Excel-отчет по опозданиям на базе opozdaniya_builder:
|
||||
- за один день (если date_from == date_to)
|
||||
- за рабочий диапазон (по умолчанию за текущую неделю: с ПН по ПТ)
|
||||
"""
|
||||
now = datetime.now()
|
||||
if req.date_from and req.date_to:
|
||||
d_start = datetime.strptime(req.date_from.replace('_', '.'), "%d.%m.%Y")
|
||||
d_end = datetime.strptime(req.date_to.replace('_', '.'), "%d.%m.%Y")
|
||||
else:
|
||||
d_start = now - timedelta(days=now.weekday())
|
||||
d_end = now
|
||||
|
||||
dates = []
|
||||
curr = d_start
|
||||
while curr <= d_end:
|
||||
if curr.weekday() < 5:
|
||||
dates.append(curr.strftime("%d.%m.%Y"))
|
||||
curr += timedelta(days=1)
|
||||
|
||||
if not dates:
|
||||
dates = [DATE_TODAY]
|
||||
|
||||
out_path = build_opozdaniya_workbook(dates)
|
||||
filename = os.path.basename(out_path)
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"filename": filename,
|
||||
"download_url": f"/api/v1/files/download/reports/{filename}",
|
||||
"dates_included": dates
|
||||
}
|
||||
Reference in New Issue
Block a user