diff --git a/.gitignore b/.gitignore index 5ceb386..93a8f4f 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,7 @@ -venv +venv/ +result/logs/ +result/report* +input/stat* + +*.pyc +__pycache__/ \ No newline at end of file diff --git a/CONTEXT_EXPORT.md b/CONTEXT_EXPORT.md new file mode 100644 index 0000000..10b0606 --- /dev/null +++ b/CONTEXT_EXPORT.md @@ -0,0 +1,157 @@ +# Context export for continuation + +## Project goal +Process computer class attendance logs in several sequential stages with a single entry point. + +## Current structure +- Main entry point: [run.py](run.py) +- Pipeline orchestration: [lib/pipeline.py](lib/pipeline.py) +- Stage 1: [lib/stage_load_settings.py](lib/stage_load_settings.py) +- Stage 2: [lib/stage_process_logs.py](lib/stage_process_logs.py) +- Config: [settings.yaml](settings.yaml) +- Class registry: [data/classes.csv](data/classes.csv) +- Output folder: [result/logs](result/logs) + +## Stage 1 behavior +Loads: +- `settings.yaml` +- `data/classes.csv` + +Current `settings.yaml` keys: +- `year.first_week` +- `year.week` +- `year.schedule` +- `sections` +- `classes` +- `class_ips` +- `processing` + +`processing` currently contains: +- `m1_ip_to_name_switch_date: 2026-04-08` +- `amt_group_id: amt` +- `amt_class_id: АМТ-33` + +## Stage 2 behavior +Reads logs from: +- `input/stat_m1` +- `input/stat_okk1` + +Log format: +- one file per day +- example: `input/stat_m1/m1_202601/13.txt` + +Parsed session output format: +- `station,user,start,end` + +## Grouping rules currently implemented +### okk1 +- Computer names are of the form `{prefix}{station}` +- Files are grouped by class `id` from `classes.csv` + +### m1 before 2026-04-08 +- Source uses IP addresses +- Files are grouped by `ip_group` from `classes.csv` +- The file name is the `ip_group` value, for example: + - `pu.csv` + - `mk.csv` + - `lv.csv` + - `kl.csv` + - `fe.csv` + - `km.csv` + - `mu.csv` + - `amt.csv` + +### m1 from 2026-04-08 onward +- Source uses computer names like `pu-402-1` +- Files are grouped by class `id` from `classes.csv` +- Examples: + - `4а-402.csv` + - `4а-407.csv` + - `4а-806.csv` + - `ИЭиБ-10.csv` + - `МФ-207.csv` + - `ЮФ-309.csv` + - `МК-26.csv` + - `МК-28.csv` + - `МУ-21.csv` + - `ЭГФ-11.csv` + +### AMT exception +- `amt` is always kept as one group in `result/logs/amt.csv` +- This applies across the whole period, including after 2026-04-08 +- AMT does not split into separate class/computer files + +## Important data facts +### `classes.csv` +Columns now are: +- `id` +- `class` +- `description` +- `part` +- `computers` +- `section` +- `prefix` +- `ip_group` + +Notes: +- `part` was added for future use +- `ip_group` is used only for m1 pre-2026-04-08 grouping +- `amt` rows have `ip_group=amt` + +### Current pipeline output +Last verified run produced: +- 25 output files +- 16417 sessions total + +## Output file map +### Class files +- `1-301.csv` +- `1-303.csv` +- `1-503.csv` +- `1-505.csv` +- `3-111.csv` +- `3-115.csv` +- `3-118.csv` +- `3-127.csv` +- `3-522.csv` +- `4а-402.csv` +- `4а-407.csv` +- `4а-806.csv` +- `ИЭиБ-10.csv` +- `МК-26.csv` +- `МК-28.csv` +- `МФ-207.csv` +- `МУ-21.csv` +- `ЭГФ-11.csv` + +### IP-group files +- `amt.csv` +- `fe.csv` +- `kl.csv` +- `km.csv` +- `lv.csv` +- `mk.csv` +- `mu.csv` +- `pu.csv` + +## Known implementation details +- The processor loads `settings.yaml` through `SettingsLoader` in stage 2. +- YAML date values may already be parsed as date objects, so stage 2 handles both strings and date-like values. +- The project runs successfully with: + - `./venv/bin/python run.py` + +## Validation status +- Stage 1: OK +- Stage 2: OK +- AMT special case: OK +- m1 switch date from settings: OK + +## If continuing development +Likely next steps are: +- clean up duplicated or brittle matching logic in `lib/stage_process_logs.py` +- add a third stage for statistics or reporting +- write tests for: + - okk1 class matching + - m1 pre-switch ip_group grouping + - m1 post-switch class-name grouping + - AMT exception behavior diff --git a/README.md b/README.md new file mode 100644 index 0000000..3f00d7a --- /dev/null +++ b/README.md @@ -0,0 +1,118 @@ +# Attendance Processing Pipeline + +Модульная система обработки посещаемости компьютерных классов. + +## Структура проекта + +``` +. +├── run.py # Главная точка входа (запускаемый скрипт) +├── lib/ # Модули обработки +│ ├── __init__.py # Инициализация пакета +│ ├── pipeline.py # Управление этапами обработки +│ ├── stage_load_settings.py # Этап 1: загрузка настроек +│ └── stage_process_logs.py # Этап 2: обработка логов авторизации +├── settings.yaml # Файл конфигурации +├── data/ +│ ├── classes.csv # Информация о компьютерных классах +│ └── all_groups.csv +├── input/ +│ ├── stat_m1/ # Логи факультетских классов +│ └── stat_okk1/ # Логи классов ОСУП +└── result/ + └── logs/ # Выходные CSV файлы с сеансами +``` + +## Использование + +### Запуск с использованием виртуального окружения + +```bash +./venv/bin/python run.py +``` + +Или, если скрипт имеет права на исполнение: + +```bash +./run.py +``` + +## Pipeline Stages + +### Stage 1: Load Settings +- **Модуль**: `lib/stage_load_settings.py` +- **Описание**: Загружает конфигурацию из `settings.yaml` и информацию о классах из `data/classes.csv` +- **Выходные данные**: + - `settings`: Словарь с конфигурацией (sections, class_ips, расписание и т.д.) + - `classes`: DataFrame с информацией о классах + +### Stage 2: Process Authentication Logs +- **Модуль**: `lib/stage_process_logs.py` +- **Описание**: Обрабатывает логи авторизации Windows из файлов в `input/stat_m1` и `input/stat_okk1` +- **Функциональность**: + - Парсит логи авторизации для извлечения сеансов пользователей + - Группирует пары событий входа/выхода в сеансы с временем начала и завершения + - Для классов okk1 и m1 (после 08.04.2026): использует имена компьютеров формата `{prefix}{station}` + - Для классов m1 (до 08.04.2026): определяет класс по IP-адресу, используя маски подсетей из `settings.yaml` + - Группирует результаты по классам и создает CSV файлы в `result/logs/` +- **Входные данные**: Текстовые файлы логов по дням (например, `input/stat_m1/m1_202601/13.txt`) +- **Выходные данные**: CSV файлы формата + ```csv + station,user,start,end + 115k1,bashimovaa,2025-12-17 13:02:24,2025-12-17 14:04:23 + 301k2,azmukhanovir1,2026-01-21 10:17:42,2026-01-21 13:24:39 + ``` + +## Как работает pipeline + +Pipeline состоит из последовательных этапов обработки. Каждый этап: + +1. **Загружается динамически** из модуля в `lib/` +2. **Выполняется с контекстом** (доступ к рабочему каталогу и результатам предыдущих этапов) +3. **Возвращает результат**, который сохраняется в общем контексте для использования на следующих этапах + +## Добавление нового этапа + +1. Создайте новый модуль в `lib/stage_*.py` +2. Реализуйте функцию `run_stage(workspace_root: Path)` -> Dict[str, Any] +3. Добавьте этап в `lib/pipeline.py`: + +```python +pipeline.add_stage(Stage( + name="Your Stage Name", + description="Description of what this stage does", + module_name="stage_your_module" +)) +``` + +## Требования + +- Python 3.8+ +- PyYAML +- pandas + +Установка зависимостей в venv: + +```bash +./venv/bin/pip install pyyaml pandas +``` + +## Примеры результатов + +После запуска pipeline в папке `result/logs/` создаются CSV файлы для каждого класса, имеющего данные в логах. + +Пример файла `result/logs/3-115.csv`: +``` +station,user,start,end +115k1,bashimovaa,2025-12-17 13:02:24,2025-12-17 14:04:23 +115k3,khemraeva,2025-12-17 13:02:43,2025-12-17 13:50:10 +115k2,shirievo,2025-12-17 13:03:27,2025-12-17 13:31:25 +``` + +Пример файла `result/logs/МФ-207.csv` (использует IP адреса до 08.04.2026): +``` +station,user,start,end +10.3.1.157,romanovapa,2025-12-11 15:47:59,2025-12-11 15:48:19 +10.3.1.187,darinadd,2025-12-11 15:48:39,2025-12-11 15:49:00 +``` + diff --git a/data/classes.csv b/data/classes.csv index 9ac90ba..e539126 100644 --- a/data/classes.csv +++ b/data/classes.csv @@ -1,26 +1,26 @@ -id,class,description,computers,section,prefix -"3-111","3/111 (Наб.р.Свияги,3корп","Учебный корпус 3, ауд. 111 (ОСУП)",13,okk1,111k -"3-115","3/115 (Наб.р.Свияги,3корп","Учебный корпус 3, ауд. 115 (ОСУП)",15,okk1,115k -"3-118","3/118 (Наб.р.Свияги,3корп","Учебный корпус 3, ауд. 118 (ОСУП)",16,okk1,118k -"3-127","3/127 (Наб.р.Свияги,3корп","Учебный корпус 3, ауд. 127 (ОСУП)",13,okk1,127k -"3-522","3/522 (Наб.р.Свияги,3корп","Учебный корпус 3, ауд. 522 (ОСУП)",11,okk1,522k -"1-301","301 (Наб.р.Свияги,1корп)","Учебный корпус 1, ауд. 301 (ОСУП)",10,okk1,301k -"1-303","303 (Наб.р.Свияги,1корп)","Учебный корпус 1, ауд. 303 (ОСУП)",10,okk1,303k -"1-503","503 (Наб.р.Свияги,1корп)","Учебный корпус 1, ауд. 503 (ОСУП)",10,okk1,503k -"1-505","505 (Наб.р.Свияги,1корп)","Учебный корпус 1, ауд. 505 (ОСУП)",10,okk1,505k -"4а-402","402 (Пушкинская,4А)","ул. Пушкинская, д. 4а, ауд. 402 (ОСУП)",16,m1,pu-402- -"4а-407","407 (Пушкинская,4А)","ул. Пушкинская, д. 4а, ауд. 407 (ОСУП)",15,m1,pu-407- -"4а-806","806 (Пушкинская,4А)","ул. Пушкинская, д. 4а, ауд. 806 (ОСУП)",16,m1,pu-806- -"ИЭиБ-10","10 (Федерации,29)","ул. Федерации, д. 29, ауд. 10 (ИЭиБ)",10,m1,fe-1- -"МФ-207","207 (Ливчака,2/1)","ул. Архитектора Ливчака, д. 2/1, ауд. 207 (МФ)",10,m1,kl-207- -"ЮФ-309","309 (Гончарова,40/9)","ул. Гончарова, д. 40/9, ауд. 309 (ЮФ)",11,m1,km-309- -"МУ-21","21 (Гимова,1)","ул. Гимова, д. 1, ауд. 21 (Муз. училище)",10,m1,mu-21- -"ЭГФ-11","11 (Львовский,5)","ул. Бульвар Львовский, д. 5, ауд. 11 (Зав. ЭГФ)",11,m1,lv-11- -"ЭГФ-14","14 (Львовский,5)","ул. Бульвар Львовский, д. 5, ауд. 14 (Зав. ЭГФ)",10,m1,lv-14- -"МК-26","26 (Аблукова,31)","ул. Аблукова, д. 31, ауд. 26 (Мед. колледж)",9,m1,mk-26- -"МК-28","28 (Аблукова,31)","ул. Аблукова, д. 31, ауд. 28 (Мед. колледж)",10,m1,mk-28- -"АМТ-33","33 (Наб.р.Свияги,158)","ул. Набережная р. Свияги, д. 158, ауд. 33 (АМТ)",9,m1,amt -"АМТ-34","34 (Наб.р.Свияги,158)","ул. Набережная р. Свияги, д. 158, ауд. 34 (АМТ)",11,m1,amt -"АМТ-35","35 (Наб.р.Свияги,158)","ул. Набережная р. Свияги, д. 158, ауд. 35 (АМТ)",15,m1,amt -"АМТ-36","36 (Наб.р.Свияги,158)","ул. Набережная р. Свияги, д. 158, ауд. 36 (АМТ)",11,m1,amt -"АМТ-39","39 (Наб.р.Свияги,158)","ул. Набережная р. Свияги, д. 158, ауд. 39 (АМТ)",11,m1,amt \ No newline at end of file +id,class,description,part,computers,section,prefix,ip_group +"3-111","3/111 (Наб.р.Свияги,3корп","ауд. 3/111","ОСУП",13,okk1,111k,"" +"3-115","3/115 (Наб.р.Свияги,3корп","ауд. 3/115","ОСУП",15,okk1,115k,"" +"3-118","3/118 (Наб.р.Свияги,3корп","ауд. 3/118","ОСУП",16,okk1,118k,"" +"3-127","3/127 (Наб.р.Свияги,3корп","ауд. 3/127","ОСУП",13,okk1,127k,"" +"3-522","3/522 (Наб.р.Свияги,3корп","ауд. 3/522","ОСУП",11,okk1,522k,"" +"1-301","301 (Наб.р.Свияги,1корп)", "ауд. 1/301","ОСУП",10,okk1,301k,"" +"1-303","303 (Наб.р.Свияги,1корп)", "ауд. 1/303","ОСУП",10,okk1,303k,"" +"1-503","503 (Наб.р.Свияги,1корп)", "ауд. 1/503","ОСУП",10,okk1,503k,"" +"1-505","505 (Наб.р.Свияги,1корп)", "ауд. 1/505","ОСУП",10,okk1,505k,"" +"4а-402","402 (Пушкинская,4А)","ул. Пушкинская, д. 4а, ауд. 402 (ОСУП)","ОСУП",16,m1,pu-402-,pu +"4а-407","407 (Пушкинская,4А)","ул. Пушкинская, д. 4а, ауд. 407 (ОСУП)","ОСУП",15,m1,pu-407-,pu +"4а-806","806 (Пушкинская,4А)","ул. Пушкинская, д. 4а, ауд. 806 (ОСУП)","ОСУП",16,m1,pu-806-,pu +"ИЭиБ-10","10 (Федерации,29)","ул. Федерации, д. 29, ауд. 10 (ИЭиБ)","Факультеты",10,m1,fe-1-,fe +"МФ-207","207 (Ливчака,2/1)","ул. Архитектора Ливчака, д. 2/1, ауд. 207 (МФ)","Факультеты",10,m1,kl-207-,kl +"ЮФ-309","309 (Гончарова,40/9)","ул. Гончарова, д. 40/9, ауд. 309 (ЮФ)","Факультеты",11,m1,km-309-,km +"МУ-21","21 (Гимова,1)","ул. Гимова, д. 1, ауд. 21 (Муз. училище)","Факультеты",10,m1,mu-21-,mu +"ЭГФ-11","11 (Львовский,5)","ул. Бульвар Львовский, д. 5, ауд. 11 (Зав. ЭГФ)","Факультеты",11,m1,lv-11-,lv +"ЭГФ-14","14 (Львовский,5)","ул. Бульвар Львовский, д. 5, ауд. 14 (Зав. ЭГФ)","Факультеты",10,m1,lv-14-,lv +"МК-26","26 (Аблукова,31)","ул. Аблукова, д. 31, ауд. 26 (Мед. колледж)","Факультеты",9,m1,mk-26-,mk +"МК-28","28 (Аблукова,31)","ул. Аблукова, д. 31, ауд. 28 (Мед. колледж)","Факультеты",10,m1,mk-28-,mk +"АМТ-33","33 (Наб.р.Свияги,158)","ул. Набережная р. Свияги, д. 158, ауд. 33 (АМТ)","АМТ",9,m1,amt,amt +"АМТ-34","34 (Наб.р.Свияги,158)","ул. Набережная р. Свияги, д. 158, ауд. 34 (АМТ)","АМТ",11,m1,amt,amt +"АМТ-35","35 (Наб.р.Свияги,158)","ул. Набережная р. Свияги, д. 158, ауд. 35 (АМТ)","АМТ",15,m1,amt,amt +"АМТ-36","36 (Наб.р.Свияги,158)","ул. Набережная р. Свияги, д. 158, ауд. 36 (АМТ)","АМТ",11,m1,amt,amt +"АМТ-39","39 (Наб.р.Свияги,158)","ул. Набережная р. Свияги, д. 158, ауд. 39 (АМТ)","АМТ",11,m1,amt,amt diff --git a/input/.gitkeep b/input/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/lib/__init__.py b/lib/__init__.py new file mode 100644 index 0000000..932f60c --- /dev/null +++ b/lib/__init__.py @@ -0,0 +1 @@ +"""Library for processing computer class attendance data.""" diff --git a/lib/pipeline.py b/lib/pipeline.py new file mode 100644 index 0000000..30f6250 --- /dev/null +++ b/lib/pipeline.py @@ -0,0 +1,149 @@ +"""Main pipeline for processing attendance data.""" + +from pathlib import Path +from typing import Dict, Any, List +from dataclasses import dataclass +import inspect + + +@dataclass +class Stage: + """Represents a processing stage.""" + + name: str + description: str + module_name: str + run_function: str = "run_stage" + + +class Pipeline: + """Manages the execution of sequential processing stages.""" + + def __init__(self, workspace_root: Path): + """ + Initialize the pipeline. + + Args: + workspace_root: Root directory of the project + """ + self.workspace_root = Path(workspace_root) + self.stages: List[Stage] = [] + self.context: Dict[str, Any] = {"workspace_root": workspace_root} + + def add_stage(self, stage: Stage) -> None: + """ + Add a stage to the pipeline. + + Args: + stage: Stage to add + """ + self.stages.append(stage) + + def run(self) -> Dict[str, Any]: + """ + Execute all stages in sequence. + + Returns: + Final context with results from all stages + """ + print("=" * 60) + print("ATTENDANCE PROCESSING PIPELINE") + print("=" * 60) + + for i, stage in enumerate(self.stages, 1): + print(f"\n[Stage {i}] {stage.name}") + print(f"Description: {stage.description}") + print("-" * 60) + + try: + # Dynamically import and run the stage + module = self._import_stage(stage.module_name) + run_func = getattr(module, stage.run_function) + + # Run the stage with current context. + # Stages may accept either (workspace_root) or (workspace_root, context). + params = inspect.signature(run_func).parameters + if len(params) >= 2: + result = run_func(self.workspace_root, self.context) + else: + result = run_func(self.workspace_root) + + # Store result in context + self.context[stage.module_name] = result + + print(f"✓ Stage completed successfully\n") + + except Exception as e: + print(f"✗ Stage failed with error: {str(e)}\n") + raise + + print("=" * 60) + print("PIPELINE COMPLETED SUCCESSFULLY") + print("=" * 60) + + return self.context + + def _import_stage(self, module_name: str): + """ + Dynamically import a stage module. + + Args: + module_name: Name of the module to import + + Returns: + Imported module + """ + import importlib + + full_module_name = f"lib.{module_name}" + return importlib.import_module(full_module_name) + + +def create_default_pipeline(workspace_root: Path) -> Pipeline: + """ + Create a pipeline with default stages. + + Args: + workspace_root: Root directory of the project + + Returns: + Configured pipeline ready to run + """ + pipeline = Pipeline(workspace_root) + + # Stage 1: Load settings + pipeline.add_stage(Stage( + name="Load Settings", + description="Load configuration from settings.yaml and class data from classes.csv", + module_name="stage_load_settings" + )) + + # Stage 2: Process logs + pipeline.add_stage(Stage( + name="Process Authentication Logs", + description="Extract sessions from Windows authentication logs and group by class", + module_name="stage_process_logs" + )) + + # Stage 3: Parse university schedule export (placeholder for now) + pipeline.add_stage(Stage( + name="Parse University Schedule", + description="Prepare schedule data for future group attendance calculations", + module_name="stage_parse_schedule" + )) + + # Stage 4: Build report data + pipeline.add_stage(Stage( + name="Build Report Data", + description="Aggregate processed sessions into JSON report data", + module_name="stage_build_report_data" + )) + + # Stage 5: Generate HTML reports + pipeline.add_stage(Stage( + name="Generate HTML Reports", + description="Create standalone HTML reports for groups and classes", + module_name="stage_generate_reports_html" + )) + + return pipeline diff --git a/lib/stage_build_report_data.py b/lib/stage_build_report_data.py new file mode 100644 index 0000000..16e8591 --- /dev/null +++ b/lib/stage_build_report_data.py @@ -0,0 +1,552 @@ +"""Stage 4: Build JSON data used by HTML reports.""" + +from __future__ import annotations + +import csv +import json +from dataclasses import asdict, dataclass +from datetime import datetime, timezone, date, timedelta, time +from pathlib import Path +from typing import Dict, Any, List, Optional, Tuple + +import pandas as pd + +from lib.stage_load_settings import SettingsLoader + + +@dataclass +class ReportItem: + """Aggregated statistics for one output group/class file.""" + + group_id: str + kind: str + title: str + source_rows: int + unique_users: int + unique_stations: int + total_minutes: float + first_start: Optional[str] + last_end: Optional[str] + by_date: Dict[str, int] + top_users: List[Dict[str, Any]] + weeks: List[Dict[str, Any]] + + +def _load_context_config( + workspace_root: Path, context: Dict[str, Any] | None +) -> Dict[str, Any]: + if context and "stage_load_settings" in context: + return context["stage_load_settings"] + loader = SettingsLoader(workspace_root) + return loader.get_config() + + +def _safe_float_minutes(start: str, end: str) -> float: + try: + start_dt = datetime.fromisoformat(start) + end_dt = datetime.fromisoformat(end) + except ValueError: + return 0.0 + + delta = end_dt - start_dt + return max(delta.total_seconds() / 60.0, 0.0) + + +def _parse_dt(value: str) -> Optional[datetime]: + try: + return datetime.fromisoformat(value) + except ValueError: + return None + + +def _parse_date_value(value: Any) -> Optional[date]: + if isinstance(value, datetime): + return value.date() + if hasattr(value, "year") and hasattr(value, "month") and hasattr(value, "day"): + try: + return date(value.year, value.month, value.day) + except ValueError: + return None + if value is None: + return None + + text = str(value).strip() + if not text: + return None + + for fmt in ("%Y-%m-%d", "%d.%m.%Y"): + try: + return datetime.strptime(text, fmt).date() + except ValueError: + continue + return None + + +def _normalize_week_type(value: Any) -> Optional[str]: + if value is None: + return None + + text = str(value).strip().upper() + mapping = { + "I": "I", + "1": "I", + "Н": "I", + "НЕЧЕТ": "I", + "НЕЧЁТ": "I", + "НЕЧЕТНАЯ": "I", + "НЕЧЁТНАЯ": "I", + "II": "II", + "2": "II", + "Ч": "II", + "ЧЕТ": "II", + "ЧЁТ": "II", + "ЧЕТНАЯ": "II", + "ЧЁТНАЯ": "II", + } + return mapping.get(text) + + +def _weekday_from_value(value: Any) -> Optional[int]: + if value is None: + return None + + if isinstance(value, int): + if 1 <= value <= 6: + return value + if 0 <= value <= 5: + return value + 1 + + text = str(value).strip().upper() + mapping = { + "1": 1, + "2": 2, + "3": 3, + "4": 4, + "5": 5, + "6": 6, + "ПН": 1, + "ПОНЕДЕЛЬНИК": 1, + "ВТ": 2, + "ВТОРНИК": 2, + "СР": 3, + "СРЕДА": 3, + "ЧТ": 4, + "ЧЕТВЕРГ": 4, + "ЧЕТВЕРК": 4, + "ПТ": 5, + "ПЯТНИЦА": 5, + "СБ": 6, + "СУББОТА": 6, + } + return mapping.get(text) + + +def _normalize_lesson_windows(settings: Dict[str, Any]) -> List[Tuple[int, time, time]]: + year = settings.get("year", {}) if isinstance(settings, dict) else {} + windows: List[Tuple[int, time, time]] = [] + + for item in year.get("schedule", []) or []: + lesson = item.get("lesson") + if lesson is None: + continue + try: + lesson_num = int(lesson) + except (TypeError, ValueError): + continue + + start_raw = str(item.get("start", "")).strip() + end_raw = str(item.get("end", "")).strip() + if not start_raw or not end_raw: + continue + + try: + start_t = time.fromisoformat(start_raw).replace(tzinfo=None) + end_t = time.fromisoformat(end_raw).replace(tzinfo=None) + except ValueError: + continue + + windows.append((lesson_num, start_t, end_t)) + + windows.sort(key=lambda x: x[0]) + return windows + + +def _compute_week_type(monday: date, first_week: date) -> str: + first_monday = first_week - timedelta(days=first_week.weekday()) + delta_weeks = (monday - first_monday).days // 7 + return "I" if delta_weeks % 2 == 0 else "II" + + +def _parse_schedule_rules(schedule: Dict[str, Any]) -> Dict[str, Any]: + exact: Dict[Tuple[str, str], set[int]] = {} + recurring: List[Dict[str, Any]] = [] + + for entry in schedule.get("group_lessons", []) or []: + if not isinstance(entry, dict): + continue + + class_id = ( + entry.get("class_id") + or entry.get("class") + or entry.get("room_id") + or entry.get("room") + ) + if not class_id: + continue + + lesson_raw = entry.get("lesson") or entry.get("pair") + try: + lesson = int(lesson_raw) + except (TypeError, ValueError): + continue + + date_value = _parse_date_value(entry.get("date")) + if date_value: + key = (str(class_id), date_value.isoformat()) + if key not in exact: + exact[key] = set() + exact[key].add(lesson) + continue + + weekday = _weekday_from_value(entry.get("weekday") or entry.get("day")) + week_type = _normalize_week_type(entry.get("week_type") or entry.get("week")) + recurring.append( + { + "class_id": str(class_id), + "lesson": lesson, + "weekday": weekday, + "week_type": week_type, + } + ) + + return {"exact": exact, "recurring": recurring} + + +def _has_schedule_lesson( + schedule_rules: Dict[str, Any], + class_id: str, + target_date: date, + lesson: int, + week_type: str, +) -> bool: + exact = schedule_rules.get("exact", {}) + recurring = schedule_rules.get("recurring", []) + + key = (class_id, target_date.isoformat()) + lessons = exact.get(key) + if lessons and lesson in lessons: + return True + + weekday_num = target_date.weekday() + 1 + for rule in recurring: + if rule.get("class_id") != class_id: + continue + if rule.get("lesson") != lesson: + continue + + rule_weekday = rule.get("weekday") + if rule_weekday and rule_weekday != weekday_num: + continue + + rule_week_type = rule.get("week_type") + if rule_week_type and rule_week_type != week_type: + continue + + return True + + return False + + +def _session_overlaps_lesson( + start_dt: datetime, + end_dt: datetime, + target_date: date, + lesson_start: time, + lesson_end: time, +) -> bool: + lesson_start_dt = datetime.combine(target_date, lesson_start) + lesson_end_dt = datetime.combine(target_date, lesson_end) + return start_dt <= lesson_end_dt and end_dt >= lesson_start_dt + + +def _class_display_name(classes_df: pd.DataFrame, group_id: str) -> Dict[str, str]: + """Return a display label and type for a CSV output file.""" + class_rows = classes_df[classes_df["id"] == group_id] + if not class_rows.empty: + row = class_rows.iloc[0] + return { + "kind": "class", + "title": str(row.get("class") or row.get("description") or group_id), + } + + ip_rows = classes_df[classes_df["ip_group"] == group_id] + if not ip_rows.empty: + labels = [str(value) for value in ip_rows["id"].tolist()] + room_name = str(ip_rows.iloc[0].get("section") or group_id) + title = f"{group_id} ({', '.join(labels)})" + return {"kind": "ip_group", "title": title} + + return {"kind": "unknown", "title": group_id} + + +def _aggregate_csv( + file_path: Path, + classes_df: pd.DataFrame, + report_start: date, + report_end: date, + first_week: date, + lesson_windows: List[Tuple[int, time, time]], + schedule_rules: Dict[str, Any], +) -> Tuple[ReportItem, set[str]]: + group_id = file_path.stem + display = _class_display_name(classes_df, group_id) + + with open(file_path, "r", encoding="utf-8", newline="") as f: + reader = csv.DictReader(f) + rows = [row for row in reader if row] + + filtered_rows = [] + for row in rows: + start_value = str(row.get("start", "")) + start_dt = _parse_dt(start_value) + if not start_dt: + continue + if report_start <= start_dt.date() <= report_end: + filtered_rows.append(row) + + users_set: set[str] = set() + + users = [str(row.get("user", "")) for row in filtered_rows if row.get("user")] + stations = [str(row.get("station", "")) for row in filtered_rows if row.get("station")] + for user in users: + clean_user = user.strip() + if clean_user: + users_set.add(clean_user) + + by_date: Dict[str, int] = {} + total_minutes = 0.0 + starts: List[datetime] = [] + ends: List[datetime] = [] + auth_presence: Dict[date, Dict[int, bool]] = {} + + for row in filtered_rows: + start_value = str(row.get("start", "")) + end_value = str(row.get("end", "")) + start_dt = _parse_dt(start_value) + end_dt = _parse_dt(end_value) + if not start_dt or not end_dt: + continue + + total_minutes += _safe_float_minutes(start_value, end_value) + + if start_dt: + starts.append(start_dt) + by_date[start_dt.date().isoformat()] = by_date.get(start_dt.date().isoformat(), 0) + 1 + if end_dt: + ends.append(end_dt) + + target_date = start_dt.date() + if target_date not in auth_presence: + auth_presence[target_date] = {} + for lesson_num, lesson_start, lesson_end in lesson_windows: + if _session_overlaps_lesson(start_dt, end_dt, target_date, lesson_start, lesson_end): + auth_presence[target_date][lesson_num] = True + + weeks: List[Dict[str, Any]] = [] + weekday_names = ["ПН", "ВТ", "СР", "ЧТ", "ПТ", "СБ"] + monday = report_start - timedelta(days=report_start.weekday()) + while monday <= report_end: + saturday = monday + timedelta(days=5) + week_type = _compute_week_type(monday, first_week) + + daily_rows: List[str] = [] + days_payload: List[Dict[str, Any]] = [] + code_counts = {"0": 0, "1": 0, "2": 0, "3": 0} + + for day_offset in range(6): + current_day = monday + timedelta(days=day_offset) + weekday_name = weekday_names[day_offset] + + row_codes: List[str] = [] + for lesson_num in range(1, 9): + in_period = report_start <= current_day <= report_end + has_schedule = ( + _has_schedule_lesson(schedule_rules, group_id, current_day, lesson_num, week_type) + if in_period + else False + ) + has_auth = bool(auth_presence.get(current_day, {}).get(lesson_num, False)) if in_period else False + + if not has_schedule and not has_auth: + code = "0" + elif has_schedule and not has_auth: + code = "1" + elif not has_schedule and has_auth: + code = "2" + else: + code = "3" + + row_codes.append(code) + code_counts[code] += 1 + + row_text = "".join(row_codes) + daily_rows.append(row_text) + days_payload.append( + { + "date": current_day.isoformat(), + "weekday": weekday_name, + "lessons": row_text, + } + ) + + weeks.append( + { + "long": f"{monday.strftime('%d.%m.%Y')} - {saturday.strftime('%d.%m.%Y')} ({week_type})", + "short": f"{monday.strftime('%d.%m')} ({week_type})", + "week_type": week_type, + "monday": monday.isoformat(), + "saturday": saturday.isoformat(), + "days": days_payload, + "daily_summary": daily_rows, + "code_counts": code_counts, + } + ) + + monday += timedelta(days=7) + + user_counts = pd.Series(users).value_counts() if users else pd.Series(dtype=int) + top_users = [ + {"user": str(name), "sessions": int(count)} + for name, count in user_counts.head(10).items() + ] + + return ReportItem( + group_id=group_id, + kind=display["kind"], + title=display["title"], + source_rows=len(filtered_rows), + unique_users=len(set(users)), + unique_stations=len(set(stations)), + total_minutes=round(total_minutes, 1), + first_start=min(starts).isoformat(sep=" ") if starts else None, + last_end=max(ends).isoformat(sep=" ") if ends else None, + by_date=dict(sorted(by_date.items())), + top_users=top_users, + weeks=weeks, + ), users_set + + +def _build_group_report(schedule: Dict[str, Any]) -> Dict[str, Any]: + return { + "available": bool(schedule.get("available")), + "lesson_windows": schedule.get("lesson_windows", []), + "group_lessons": schedule.get("group_lessons", []), + "items": [], + "note": schedule.get("note", "Schedule data is not available yet."), + } + + +def _build_class_report(items: List[ReportItem], total_users: int) -> Dict[str, Any]: + total_sessions = sum(item.source_rows for item in items) + + return { + "available": True, + "summary": { + "files": len(items), + "sessions": total_sessions, + "users": total_users, + }, + "items": [asdict(item) for item in items], + } + + +def run_stage( + workspace_root: Path, + context: Dict[str, Any] | None = None, +) -> Dict[str, Any]: + """Aggregate processed sessions into JSON files for later HTML rendering.""" + config = _load_context_config(workspace_root, context) + settings = config["settings"] + classes_df = config["classes"] + + logs_dir = workspace_root / "result" / "logs" + reports_dir = workspace_root / "result" / "reports" + reports_dir.mkdir(parents=True, exist_ok=True) + + report_start = _parse_date_value(settings.get("report_start")) + report_end = _parse_date_value(settings.get("report_end")) + first_week = _parse_date_value(settings.get("year", {}).get("first_week")) + + if report_start is None or report_end is None: + raise ValueError("settings.yaml must contain report_start and report_end") + if first_week is None: + raise ValueError("settings.yaml must contain year.first_week") + if report_start > report_end: + raise ValueError("report_start cannot be later than report_end") + + lesson_windows = _normalize_lesson_windows(settings) + + schedule = {} + if context and "stage_parse_schedule" in context: + schedule = context["stage_parse_schedule"].get("schedule", {}) + schedule_rules = _parse_schedule_rules(schedule) + + items: List[ReportItem] = [] + all_users: set[str] = set() + if logs_dir.exists(): + for file_path in sorted(logs_dir.glob("*.csv")): + try: + item, users_set = _aggregate_csv( + file_path=file_path, + classes_df=classes_df, + report_start=report_start, + report_end=report_end, + first_week=first_week, + lesson_windows=lesson_windows, + schedule_rules=schedule_rules, + ) + items.append(item) + all_users.update(users_set) + except Exception as exc: + print(f"Warning: failed to aggregate {file_path.name}: {exc}") + + group_report = { + "generated_at": datetime.now(timezone.utc).isoformat(), + "workspace_root": str(workspace_root), + "source_logs_dir": str(logs_dir), + "report_start": report_start.isoformat(), + "report_end": report_end.isoformat(), + "schedule": schedule, + "report": _build_group_report(schedule), + } + + class_report = { + "generated_at": datetime.now(timezone.utc).isoformat(), + "workspace_root": str(workspace_root), + "source_logs_dir": str(logs_dir), + "report_start": report_start.isoformat(), + "report_end": report_end.isoformat(), + "report": _build_class_report(items, len(all_users)), + } + + group_json = reports_dir / "report_groups.json" + class_json = reports_dir / "report_classes.json" + + with open(group_json, "w", encoding="utf-8") as f: + json.dump(group_report, f, ensure_ascii=False, indent=2) + + with open(class_json, "w", encoding="utf-8") as f: + json.dump(class_report, f, ensure_ascii=False, indent=2) + + print("✓ Report data built") + print(f" - JSON files: {group_json.name}, {class_json.name}") + print(f" - Class report items: {len(items)}") + print(f" - Report period: {report_start.isoformat()} .. {report_end.isoformat()}") + print(" - Group report: schedule not available yet") + + return { + "group_json": str(group_json), + "class_json": str(class_json), + "group_report": group_report, + "class_report": class_report, + } diff --git a/lib/stage_generate_reports_html.py b/lib/stage_generate_reports_html.py new file mode 100644 index 0000000..d323f76 --- /dev/null +++ b/lib/stage_generate_reports_html.py @@ -0,0 +1,1121 @@ +"""Stage 5: Generate standalone HTML reports.""" + +from __future__ import annotations + +import html +import json +from collections import defaultdict +from pathlib import Path +from typing import Dict, Any, List + +from lib.stage_load_settings import SettingsLoader + + +def _load_json(path: Path) -> Dict[str, Any]: + with open(path, "r", encoding="utf-8") as f: + return json.load(f) + + +def _escape(value: Any) -> str: + return html.escape("" if value is None else str(value)) + + +def _load_text(path: Path) -> str: + with open(path, "r", encoding="utf-8") as f: + return f.read() + + +def _render_template( + template_html: str, + title: str, + hint: str, + content: str, + css_text: str, + js_text: str, +) -> str: + style_tag = f"" if css_text.strip() else "" + script_tag = f"" if js_text.strip() else "" + + return ( + template_html + .replace("{{HINT}}", _escape(hint)) + .replace("{{CONTENT}}", content) + .replace("{{STYLE_TAG}}", style_tag) + .replace("{{SCRIPT_TAG}}", script_tag) + ) + + +def _summary_cards(cards: List[Dict[str, Any]]) -> str: + parts = ["
"] + for card in cards: + parts.append( + "
" + f"
{_escape(card.get('value'))}
" + f"
{_escape(card.get('label'))}
" + "
" + ) + parts.append("
") + return "\n".join(parts) + + +def _table(headers: List[str], rows: List[List[str]], table_class: str = "") -> str: + body = [f"", ""] + for header in headers: + body.append(f"") + body.append("") + if rows: + for row in rows: + body.append("") + for cell in row: + body.append(f"") + body.append("") + else: + body.append( + f"" + ) + body.append("
{_escape(header)}
{cell}
Нет данных.
") + return "".join(body) + + +def _chart_script(container_id: str, data: List[Dict[str, Any]]) -> str: + payload = json.dumps(data, ensure_ascii=False) + return f""" + + """ + + +def _base_styles() -> str: + return """ + + """ + + +def _base_script() -> str: + return """ + + """ + + +def _render_group_report(data: Dict[str, Any]) -> str: + report = data.get("report", {}) + schedule = data.get("schedule", {}) + lesson_windows = schedule.get("lesson_windows", []) or report.get("lesson_windows", []) + items = report.get("items", []) or [] + + cards = [ + {"value": len(lesson_windows), "label": "Шаблонов пар"}, + {"value": len(items), "label": "Групповых записей"}, + {"value": "нет", "label": "Расписание университета"}, + ] + + lesson_rows = [ + [ + _escape(item.get("lesson")), + _escape(item.get("start")), + _escape(item.get("end")), + ] + for item in lesson_windows + ] + + body = [ + _summary_cards(cards), + "
Отчёт по группам будет заполняться после появления выгрузки из расписания университета.
", + "
", + "

Шаблон пар

", + _table(["Пара", "Начало", "Окончание"], lesson_rows), + "
", + "

Пояснение

", + f"

{_escape(report.get('note', 'Schedule data is not available yet.'))}

", + "

После добавления выгрузки расписания здесь появятся данные о том, какая группа должна быть в каком компьютерном классе на конкретной паре.

", + "
", + "
", + ] + + return "".join(body) + + +def _report_part_name(classes_df, group_id: str) -> str: + class_rows = classes_df[classes_df["id"] == group_id] + if not class_rows.empty: + return str(class_rows.iloc[0].get("part") or "") + + ip_rows = classes_df[classes_df["ip_group"] == group_id] + if not ip_rows.empty: + return str(ip_rows.iloc[0].get("part") or "") + + return "" + + +def _report_display_name(classes_df, group_id: str) -> str: + class_rows = classes_df[classes_df["id"] == group_id] + if not class_rows.empty: + return str(class_rows.iloc[0].get("class") or class_rows.iloc[0].get("description") or group_id) + + ip_rows = classes_df[classes_df["ip_group"] == group_id] + if not ip_rows.empty: + row = ip_rows.iloc[0] + labels = [str(value) for value in ip_rows["id"].tolist()] + if group_id == "amt": + return str(row.get("class") or row.get("description") or "АМТ") + return f"{group_id} ({', '.join(labels)})" + + return group_id + + +def _merge_week_entries(items: List[Dict[str, Any]]) -> List[Dict[str, Any]]: + if not items: + return [] + + merged = {} + for item in items: + for week in item.get("weeks", []): + key = week.get("monday") or week.get("long") + if key not in merged: + merged[key] = { + "long": week.get("long"), + "short": week.get("short"), + "week_type": week.get("week_type"), + "monday": week.get("monday"), + "saturday": week.get("saturday"), + "days": [ + { + "date": day.get("date"), + "weekday": day.get("weekday"), + "lessons": [str(cell) for cell in str(day.get("lessons", "")).strip()], + } + for day in week.get("days", []) + ], + "code_counts": {"0": 0, "1": 0, "2": 0, "3": 0}, + } + else: + current_days = merged[key]["days"] + for idx, day in enumerate(week.get("days", [])): + incoming = [str(cell) for cell in str(day.get("lessons", "")).strip()] + if idx >= len(current_days): + current_days.append({ + "date": day.get("date"), + "weekday": day.get("weekday"), + "lessons": incoming, + }) + else: + current_days[idx]["lessons"] = [ + _merge_code_values([prev, new]) + for prev, new in zip(current_days[idx]["lessons"], incoming) + ] + + for code, value in week.get("code_counts", {}).items(): + merged[key]["code_counts"][str(code)] += int(value) + + if not merged[key]["days"]: + merged[key]["days"] = [] + + if len(merged[key]["days"]) < len(week.get("days", [])): + merged[key]["days"] = [ + { + "date": day.get("date"), + "weekday": day.get("weekday"), + "lessons": [str(cell) for cell in str(day.get("lessons", "")).strip()], + } + for day in week.get("days", []) + ] + + ordered = sorted(merged.values(), key=lambda item: item.get("monday") or item.get("long") or "") + for week in ordered: + week["daily_summary"] = ["".join(day["lessons"]) for day in week.get("days", [])] + week["total_pairs"] = sum(int(v) for v in week.get("code_counts", {}).values()) + week["conducted"] = int(week.get("code_counts", {}).get("3", 0)) + week["missed"] = int(week.get("code_counts", {}).get("1", 0)) + week["other"] = int(week.get("code_counts", {}).get("2", 0)) + return ordered + + +def _merge_code_values(values: List[str]) -> str: + values = [str(value) for value in values if str(value)] + if "3" in values: + return "3" + if "2" in values: + return "2" + if "1" in values: + return "1" + return "0" + + +def _format_percent(value: int, total: int) -> str: + if total <= 0: + return f"{value} (0%)" + percent = round(value * 100 / total) + return f"{value} ({percent}%)" + + +def _render_stacked_chart(weeks: List[Dict[str, Any]]) -> str: + if not weeks: + return "
Нет данных.
" + + chart_width = max(720, len(weeks) * 92) + chart_height = 280 + bar_width = 42 + max_value = max( + max(int(week.get("conducted", 0)), int(week.get("missed", 0)), int(week.get("other", 0))) + for week in weeks + ) or 1 + + def height(value: int) -> int: + return max(2, round((value / max_value) * 180)) if value else 0 + + parts = [ + f"
" + ] + baseline = 210 + for idx, week in enumerate(weeks): + x = 70 + idx * 92 + counts = [ + ("1", int(week.get("missed", 0)), "code-1"), + ("2", int(week.get("other", 0)), "code-2"), + ("3", int(week.get("conducted", 0)), "code-3"), + ] + current_bottom = baseline + parts.append(f"{_escape(week.get('short'))}") + for code, value, cls in counts: + seg_h = height(value) + if seg_h: + parts.append( + f"" + ) + current_bottom -= seg_h + parts.append( + f"{int(week.get('total_pairs', 0))}" + ) + parts.append("
") + return "".join(parts) + + +def _render_scheme_table(week: Dict[str, Any]) -> str: + rows = [] + days = week.get("days", []) or [] + for day in days: + cells = [] + for code in str(day.get("lessons", "")): + cells.append(f"") + while len(cells) < 8: + cells.append("") + rows.append( + "" + f"{_escape(day.get('weekday'))}" + + "".join(f"{cell}" for cell in cells[:8]) + + "" + ) + return ( + "" + + "".join(f"" for i in range(1, 9)) + + "" + + "".join(rows) + + "
День{i}
" + ) + + +def _render_class_block(item: Dict[str, Any]) -> str: + weeks = item.get("weeks", []) or [] + total_pairs = sum(int(week.get("total_pairs", 0)) for week in weeks) + conducted = sum(int(week.get("conducted", 0)) for week in weeks) + missed = sum(int(week.get("missed", 0)) for week in weeks) + other = sum(int(week.get("other", 0)) for week in weeks) + + rows = [] + for week in weeks: + total = int(week.get("total_pairs", 0)) + rows.append( + "" + f"{_escape(week.get('long'))}" + f"{total}" + f"{_format_percent(int(week.get('conducted', 0)), total)}" + f"{_format_percent(int(week.get('missed', 0)), total)}" + f"{_format_percent(int(week.get('other', 0)), total)}" + f"{_render_scheme_table(week)}" + "" + ) + + return ( + f"
" + "
" + f"
{_escape(item.get('section_title'))}

{_escape(item.get('label'))}

" + "
" + f"
{_render_stacked_chart(weeks)}
" + "
" + "" + "" + + "".join(rows) + + "
НеделяВсего парПар проведеноПар пропущеноИные парыСхема
" + ) + + +def _section_button(label: str, section_id: str, active: bool) -> str: + cls = "nav-btn active" if active else "nav-btn" + return f"" + + +def _class_button(label: str, class_id: str, active: bool, section_id: str) -> str: + cls = "nav-btn class-btn active" if active else "nav-btn class-btn" + return ( + f"" + ) + + +def _load_context_config(workspace_root: Path, context: Dict[str, Any] | None) -> Dict[str, Any]: + if context and "stage_load_settings" in context: + return context["stage_load_settings"] + loader = SettingsLoader(workspace_root) + return loader.get_config() + + +def _section_title_map(classes_df) -> Dict[str, str]: + titles = {} + for _, row in classes_df.iterrows(): + part = str(row.get("part") or "").strip() + if part and part not in titles: + titles[part] = part + return titles + + +def _row_order_map(classes_df) -> Dict[str, int]: + order = {} + for idx, row in classes_df.reset_index(drop=True).iterrows(): + group_id = str(row.get("id") or "").strip() + ip_group = str(row.get("ip_group") or "").strip() + if group_id and group_id not in order: + order[group_id] = idx + if ip_group and ip_group not in order: + order[ip_group] = idx + return order + + +def _part_for_group(classes_df, group_id: str) -> str: + class_rows = classes_df[classes_df["id"] == group_id] + if not class_rows.empty: + return str(class_rows.iloc[0].get("part") or "") + + ip_rows = classes_df[classes_df["ip_group"] == group_id] + if not ip_rows.empty: + return str(ip_rows.iloc[0].get("part") or "") + + return "" + + +def _display_label(classes_df, group_id: str) -> str: + if group_id == "amt": + return "АМТ" + if group_id == "before_804": + return "до 8.04" + + class_rows = classes_df[classes_df["id"] == group_id] + if not class_rows.empty: + return str(class_rows.iloc[0].get("id") or group_id) + + ip_rows = classes_df[classes_df["ip_group"] == group_id] + if not ip_rows.empty: + return str(ip_rows.iloc[0].get("id") or group_id) + + return group_id + + +def _aggregate_items(source_items: List[Dict[str, Any]], *, item_id: str, label: str, part_title: str) -> Dict[str, Any]: + merged_weeks = _merge_week_entries(source_items) + title_bits = [] + for item in source_items: + title_bits.append(str(item.get("title") or item.get("label") or item.get("id") or "")) + return { + "id": item_id, + "group_id": item_id, + "label": label, + "title": label, + "part_id": part_title, + "section_title": part_title, + "weeks": merged_weeks, + "is_aggregate": True, + "source_labels": [bit for bit in title_bits if bit], + } + + +def _build_class_report_model(workspace_root: Path, context: Dict[str, Any] | None) -> Dict[str, Any]: + config = _load_context_config(workspace_root, context) + classes_df = config["classes"] + settings = config["settings"] + + reports_dir = workspace_root / "result" / "reports" + class_json = reports_dir / "report_classes.json" + report_data = _load_json(class_json) + raw_items = report_data.get("report", {}).get("items", []) or [] + + order_map = _row_order_map(classes_df) + section_titles = [str(section.get("name") or section.get("id") or "") for section in settings.get("sections", [])] + + visible_items: List[Dict[str, Any]] = [] + item_by_id: Dict[str, Dict[str, Any]] = {} + for raw in raw_items: + group_id = str(raw.get("group_id") or "") + part_title = _part_for_group(classes_df, group_id) + if not part_title: + continue + + item = { + "id": group_id, + "group_id": group_id, + "label": _display_label(classes_df, group_id), + "title": str(raw.get("title") or group_id), + "part_id": part_title, + "section_title": part_title, + "weeks": raw.get("weeks", []) or [], + "order": order_map.get(group_id, 9999), + "is_aggregate": False, + } + item_by_id[group_id] = item + visible_items.append(item) + + section_groups: Dict[str, List[Dict[str, Any]]] = defaultdict(list) + for item in visible_items: + section_groups[item["part_id"]].append(item) + + # Build synthetic "before 8.04" aggregates for sections where the data existed as ip-group groups. + aggregate_sources = { + "ОСУП": ["pu"], + "Факультеты": ["fe", "kl", "km", "lv", "mk", "mu"], + } + for part_title, source_ids in aggregate_sources.items(): + sources = [item_by_id[group_id] for group_id in source_ids if group_id in item_by_id] + if sources: + section_groups[part_title].insert(0, _aggregate_items(sources, item_id=f"{part_title.lower()}-before-804", label="до 8.04", part_title=part_title)) + + # Keep AMT as one item, even though it is aggregated already. + for part_title in list(section_groups.keys()): + section_groups[part_title].sort(key=lambda item: (0 if item.get("is_aggregate") else 1, item.get("order", 9999), item.get("label", ""))) + + # The section title order follows settings.yaml; fall back to parts discovered in the data. + ordered_sections: List[Dict[str, Any]] = [] + used_parts = set() + for section_name in section_titles: + if section_name in section_groups: + ordered_sections.append({"id": section_name, "title": section_name, "items": section_groups[section_name]}) + used_parts.add(section_name) + for part_title, items in section_groups.items(): + if part_title not in used_parts: + ordered_sections.append({"id": part_title, "title": part_title, "items": items}) + + active_section = ordered_sections[0]["id"] if ordered_sections else "" + active_class = ordered_sections[0]["items"][0]["id"] if ordered_sections and ordered_sections[0]["items"] else "" + + return { + "generated_at": report_data.get("generated_at"), + "report_start": report_data.get("report_start"), + "report_end": report_data.get("report_end"), + "sections": ordered_sections, + "active_section": active_section, + "active_class": active_class, + } + + +def _render_class_report(workspace_root: Path, context: Dict[str, Any] | None) -> str: + config = _load_context_config(workspace_root, context) + classes_df = config["classes"] + settings = config["settings"] + + reports_dir = workspace_root / "result" / "reports" + class_json = reports_dir / "report_classes.json" + report_data = _load_json(class_json) + raw_items = report_data.get("report", {}).get("items", []) or [] + + def part_for_group(group_id: str) -> str: + class_rows = classes_df[classes_df["id"] == group_id] + if not class_rows.empty: + return str(class_rows.iloc[0].get("part") or "") + ip_rows = classes_df[classes_df["ip_group"] == group_id] + if not ip_rows.empty: + return str(ip_rows.iloc[0].get("part") or "") + return "" + + def display_label(group_id: str) -> str: + if group_id == "amt": + return "АМТ" + if group_id == "before_804": + return "до 8.04" + class_rows = classes_df[classes_df["id"] == group_id] + if not class_rows.empty: + return str(class_rows.iloc[0].get("id") or group_id) + ip_rows = classes_df[classes_df["ip_group"] == group_id] + if not ip_rows.empty: + return str(ip_rows.iloc[0].get("id") or group_id) + return group_id + + def row_order_map() -> Dict[str, int]: + order = {} + for idx, row in classes_df.reset_index(drop=True).iterrows(): + gid = str(row.get("id") or "").strip() + ipg = str(row.get("ip_group") or "").strip() + if gid and gid not in order: + order[gid] = idx + if ipg and ipg not in order: + order[ipg] = idx + return order + + def merge_code_values(values: List[str]) -> str: + values = [str(value) for value in values if str(value)] + if "3" in values: + return "3" + if "2" in values: + return "2" + if "1" in values: + return "1" + return "0" + + def merge_weeks(source_items: List[Dict[str, Any]]) -> List[Dict[str, Any]]: + merged = {} + for item in source_items: + for week in item.get("weeks", []) or []: + key = week.get("monday") or week.get("long") + if key not in merged: + merged[key] = { + "long": week.get("long"), + "short": week.get("short"), + "week_type": week.get("week_type"), + "monday": week.get("monday"), + "saturday": week.get("saturday"), + "days": [ + { + "date": day.get("date"), + "weekday": day.get("weekday"), + "lessons": list(str(day.get("lessons", ""))), + } + for day in week.get("days", []) or [] + ], + "code_counts": {"0": 0, "1": 0, "2": 0, "3": 0}, + } + else: + current_days = merged[key]["days"] + for idx, day in enumerate(week.get("days", []) or []): + incoming = list(str(day.get("lessons", ""))) + if idx >= len(current_days): + current_days.append({ + "date": day.get("date"), + "weekday": day.get("weekday"), + "lessons": incoming, + }) + else: + current_days[idx]["lessons"] = [ + merge_code_values([prev, new]) + for prev, new in zip(current_days[idx]["lessons"], incoming) + ] + + for code, value in (week.get("code_counts", {}) or {}).items(): + merged[key]["code_counts"][str(code)] += int(value) + + ordered = sorted(merged.values(), key=lambda item: item.get("monday") or item.get("long") or "") + for week in ordered: + week["daily_summary"] = ["".join(day["lessons"]) for day in week.get("days", [])] + week["total_pairs"] = sum(int(v) for v in week.get("code_counts", {}).values()) + week["conducted"] = int(week.get("code_counts", {}).get("3", 0)) + week["missed"] = int(week.get("code_counts", {}).get("1", 0)) + week["other"] = int(week.get("code_counts", {}).get("2", 0)) + return ordered + + def aggregate_items(source_items: List[Dict[str, Any]], *, item_id: str, label: str, part_title: str) -> Dict[str, Any]: + return { + "id": item_id, + "group_id": item_id, + "label": label, + "title": label, + "part_id": part_title, + "section_title": part_title, + "weeks": merge_weeks(source_items), + "is_aggregate": True, + "order": -1, + } + + order_map = row_order_map() + items: List[Dict[str, Any]] = [] + item_by_group: Dict[str, Dict[str, Any]] = {} + for raw in raw_items: + group_id = str(raw.get("group_id") or "") + part_title = part_for_group(group_id) + if not part_title: + continue + item = { + "id": group_id, + "group_id": group_id, + "label": display_label(group_id), + "title": str(raw.get("title") or group_id), + "part_id": part_title, + "section_title": part_title, + "weeks": raw.get("weeks", []) or [], + "order": order_map.get(group_id, 9999), + "is_aggregate": False, + } + item_by_group[group_id] = item + items.append(item) + + sections: List[Dict[str, Any]] = [] + wanted_order = [str(section.get("name") or section.get("id") or "") for section in settings.get("sections", [])] + grouped: Dict[str, List[Dict[str, Any]]] = defaultdict(list) + for item in items: + grouped[item["part_id"]].append(item) + + aggregate_sources = { + "ОСУП": ["pu"], + "Факультеты": ["fe", "kl", "km", "lv", "mk", "mu"], + } + for part_title, source_ids in aggregate_sources.items(): + sources = [item_by_group[group_id] for group_id in source_ids if group_id in item_by_group] + if sources: + grouped[part_title].insert(0, aggregate_items(sources, item_id=f"{part_title.lower()}-before-804", label="до 8.04", part_title=part_title)) + + for part_title, section_items in grouped.items(): + section_items.sort(key=lambda item: (0 if item.get("is_aggregate") else 1, item.get("order", 9999), item.get("label", ""))) + + used = set() + for part_title in wanted_order: + if part_title in grouped: + sections.append({"id": part_title, "title": part_title, "items": grouped[part_title]}) + used.add(part_title) + for part_title, section_items in grouped.items(): + if part_title not in used: + sections.append({"id": part_title, "title": part_title, "items": section_items}) + + active_section = sections[0]["id"] if sections else "" + active_class = sections[0]["items"][0]["id"] if sections and sections[0]["items"] else "" + + def format_percent(value: int, total: int) -> str: + if total <= 0: + return f"{value} (0%)" + return f"{value} ({round(value * 100 / total)}%)" + + def render_scheme_table(week: Dict[str, Any]) -> str: + rows = [] + for day in week.get("days", []) or []: + codes = list(str(day.get("lessons", ""))) + while len(codes) < 8: + codes.append("0") + cells = "".join(f"" for code in codes[:8]) + rows.append(f"{_escape(day.get('weekday'))}{cells}") + return ( + "" + + "".join(f"" for i in range(1, 9)) + + "" + + "".join(rows) + + "
День{i}
" + ) + + def render_chart(weeks: List[Dict[str, Any]]) -> str: + if not weeks: + return "
Нет данных.
" + width = max(720, len(weeks) * 92) + height = 280 + bar_width = 42 + max_value = max(max(int(w.get("conducted", 0)), int(w.get("missed", 0)), int(w.get("other", 0))) for w in weeks) or 1 + + def seg_h(value: int) -> int: + return max(2, round((value / max_value) * 180)) if value else 0 + + out = [f"
"] + baseline = 210 + for idx, week in enumerate(weeks): + x = 70 + idx * 92 + current_bottom = baseline + out.append(f"{_escape(week.get('short'))}") + for cls, value in [("code-1", int(week.get("missed", 0))), ("code-2", int(week.get("other", 0))), ("code-3", int(week.get("conducted", 0)))] : + h = seg_h(value) + if h: + out.append(f"") + current_bottom -= h + out.append(f"{int(week.get('total_pairs', 0))}") + out.append("
") + return "".join(out) + + def render_block(item: Dict[str, Any]) -> str: + weeks = item.get("weeks", []) or [] + total_pairs = sum(int(w.get("total_pairs", 0)) for w in weeks) + conducted = sum(int(w.get("conducted", 0)) for w in weeks) + missed = sum(int(w.get("missed", 0)) for w in weeks) + other = sum(int(w.get("other", 0)) for w in weeks) + rows = [] + for week in weeks: + total = int(week.get("total_pairs", 0)) + rows.append( + "" + f"{_escape(week.get('long'))}" + f"{total}" + f"{format_percent(int(week.get('conducted', 0)), total)}" + f"{format_percent(int(week.get('missed', 0)), total)}" + f"{format_percent(int(week.get('other', 0)), total)}" + f"{render_scheme_table(week)}" + "" + ) + return ( + f"
" + "
" + f"
{_escape(item.get('section_title'))}

{_escape(item.get('title'))}

" + "
" + f"
{render_chart(weeks)}
" + "
" + "" + "" + + "".join(rows) + + "
НеделяВсего парПар проведеноПар пропущеноИные парыСхема
" + ) + + screen_nav = _render_screen_nav(sections, active_section, active_class) + print_nav = _render_print_nav(sections) + blocks = "".join(render_block(item) for section in sections for item in section.get("items", [])) + data_script = f"" + + return screen_nav + print_nav + f"
{blocks}
" + data_script + + +def run_stage( + workspace_root: Path, + context: Dict[str, Any] | None = None, +) -> Dict[str, Any]: + """Generate standalone HTML reports from the JSON payloads.""" + reports_dir = workspace_root / "result" / "reports" + group_json = reports_dir / "report_groups.json" + class_json = reports_dir / "report_classes.json" + + if not group_json.exists() or not class_json.exists(): + raise FileNotFoundError( + "Report JSON files were not found. Run the previous stage first." + ) + + template_dir = workspace_root / "template" + report_css_path = template_dir / "report.css" + class_template_path = template_dir / "report_class.html" + group_template_path = template_dir / "report_group.html" + class_js_path = template_dir / "report_class.js" + group_js_path = template_dir / "report_group.js" + + required_files = [ + report_css_path, + class_template_path, + group_template_path, + class_js_path, + group_js_path, + ] + missing_files = [str(path) for path in required_files if not path.exists()] + if missing_files: + missing = "\n".join(missing_files) + raise FileNotFoundError(f"Template files are missing:\n{missing}") + + group_data = _load_json(group_json) + _load_json(class_json) + + css_text = _load_text(report_css_path) + class_template = _load_text(class_template_path) + group_template = _load_text(group_template_path) + class_js = _load_text(class_js_path) + group_js = _load_text(group_js_path) + + group_html = _render_template( + template_html=group_template, + title="Отчёт по группам", + hint="Статус: шаблон отчёта готов, данные расписания пока отсутствуют.", + content=_render_group_report(group_data), + css_text=css_text, + js_text=group_js, + ) + class_html = _render_template( + template_html=class_template, + title="Отчёт по классам", + hint="Статистика по результатам обработки логов посещаемости.", + content=_render_class_report(workspace_root, context), + css_text=css_text, + js_text=class_js, + ) + + group_html_path = workspace_root / "result" / "report_groups.html" + class_html_path = workspace_root / "result" / "report_classes.html" + + with open(group_html_path, "w", encoding="utf-8") as f: + f.write(group_html) + + with open(class_html_path, "w", encoding="utf-8") as f: + f.write(class_html) + + print("✓ HTML reports generated") + print(f" - {group_html_path.name}") + print(f" - {class_html_path.name}") + + return { + "group_html": str(group_html_path), + "class_html": str(class_html_path), + } diff --git a/lib/stage_generate_reports_html_jinja.py b/lib/stage_generate_reports_html_jinja.py new file mode 100644 index 0000000..ac8c826 --- /dev/null +++ b/lib/stage_generate_reports_html_jinja.py @@ -0,0 +1,393 @@ +"""Stage 5: Generate standalone HTML reports using Jinja2 templates.""" + +from __future__ import annotations + +import json +from collections import defaultdict +from datetime import date, datetime, timedelta +from pathlib import Path +from typing import Any, Dict, List, Optional + +import pandas as pd +from jinja2 import Environment, FileSystemLoader, select_autoescape + +from lib.stage_load_settings import SettingsLoader + + +def _load_json(path: Path) -> Dict[str, Any]: + with open(path, "r", encoding="utf-8") as f: + return json.load(f) + + +def _load_text(path: Path) -> str: + with open(path, "r", encoding="utf-8") as f: + return f.read() + + +def _parse_date(value: Any) -> Optional[date]: + if isinstance(value, datetime): + return value.date() + if hasattr(value, "year") and hasattr(value, "month") and hasattr(value, "day"): + try: + return date(value.year, value.month, value.day) + except ValueError: + return None + if value is None: + return None + + text = str(value).strip() + if not text: + return None + + for fmt in ("%Y-%m-%d", "%d.%m.%Y"): + try: + return datetime.strptime(text, fmt).date() + except ValueError: + pass + return None + + +def _load_context_config(workspace_root: Path, context: Dict[str, Any] | None) -> Dict[str, Any]: + if context and "stage_load_settings" in context: + return context["stage_load_settings"] + loader = SettingsLoader(workspace_root) + return loader.get_config() + + +def _part_name(classes_df: pd.DataFrame, group_id: str) -> str: + class_rows = classes_df[classes_df["id"] == group_id] + if not class_rows.empty: + return str(class_rows.iloc[0].get("part") or "") + + ip_rows = classes_df[classes_df["ip_group"] == group_id] + if not ip_rows.empty: + return str(ip_rows.iloc[0].get("part") or "") + + return "" + + +def _display_label(classes_df: pd.DataFrame, group_id: str) -> str: + if group_id == "amt": + return "АМТ" + + class_rows = classes_df[classes_df["id"] == group_id] + if not class_rows.empty: + return str(class_rows.iloc[0].get("id") or group_id) + + ip_rows = classes_df[classes_df["ip_group"] == group_id] + if not ip_rows.empty: + row = ip_rows.iloc[0] + return str(row.get("id") or group_id) + + return group_id + + +def _row_order_map(classes_df: pd.DataFrame) -> Dict[str, int]: + order: Dict[str, int] = {} + for idx, row in classes_df.reset_index(drop=True).iterrows(): + gid = str(row.get("id") or "").strip() + ipg = str(row.get("ip_group") or "").strip() + if gid and gid not in order: + order[gid] = idx + if ipg and ipg not in order: + order[ipg] = idx + return order + + +def _merge_code(a: str, b: str) -> str: + values = [str(x) for x in (a, b) if str(x)] + if "3" in values: + return "3" + if "2" in values: + return "2" + if "1" in values: + return "1" + return "0" + + +def _merge_weeks(source_items: List[Dict[str, Any]]) -> List[Dict[str, Any]]: + merged: Dict[str, Dict[str, Any]] = {} + + for item in source_items: + for week in item.get("weeks", []) or []: + key = week.get("monday") or week.get("long") or week.get("short") + if key not in merged: + merged[key] = { + "long": week.get("long"), + "short": week.get("short"), + "week_type": week.get("week_type"), + "monday": week.get("monday"), + "saturday": week.get("saturday"), + "days": [ + { + "date": day.get("date"), + "weekday": day.get("weekday"), + "codes": list(str(day.get("lessons", "")))[:8], + } + for day in week.get("days", []) or [] + ], + "code_counts": {"0": 0, "1": 0, "2": 0, "3": 0}, + } + else: + current_days = merged[key]["days"] + for idx, day in enumerate(week.get("days", []) or []): + incoming = list(str(day.get("lessons", "")))[:8] + if idx >= len(current_days): + current_days.append({ + "date": day.get("date"), + "weekday": day.get("weekday"), + "codes": incoming, + }) + else: + current_days[idx]["codes"] = [ + _merge_code(prev, new) + for prev, new in zip(current_days[idx]["codes"], incoming) + ] + + for code, count in (week.get("code_counts", {}) or {}).items(): + merged[key]["code_counts"][str(code)] += int(count) + + ordered = sorted(merged.values(), key=lambda item: item.get("monday") or item.get("long") or "") + for week in ordered: + week["daily_summary"] = ["".join(day["codes"]) for day in week.get("days", [])] + week["total_pairs"] = sum(int(v) for v in week.get("code_counts", {}).values()) + week["conducted"] = int(week.get("code_counts", {}).get("3", 0)) + week["missed"] = int(week.get("code_counts", {}).get("1", 0)) + week["other"] = int(week.get("code_counts", {}).get("2", 0)) + return ordered + + +def _format_percent(value: int, total: int) -> str: + if total <= 0: + return f"{value} (0%)" + return f"{value} ({round(value * 100 / total)}%)" + + +def _build_week_chart(weeks: List[Dict[str, Any]]) -> str: + if not weeks: + return "
Нет данных.
" + + width = max(720, len(weeks) * 92) + height = 280 + bar_width = 42 + max_value = max( + max(int(w.get("conducted", 0)), int(w.get("missed", 0)), int(w.get("other", 0))) + for w in weeks + ) or 1 + + def bar_height(value: int) -> int: + return max(2, round((value / max_value) * 180)) if value else 0 + + pieces = [ + f"" + ] + baseline = 210 + for index, week in enumerate(weeks): + x = 70 + index * 92 + current_bottom = baseline + pieces.append( + f"{week.get('short')}" + ) + for cls_name, value in [("code-1", int(week.get("missed", 0))), ("code-2", int(week.get("other", 0))), ("code-3", int(week.get("conducted", 0)))]: + h = bar_height(value) + if h: + pieces.append( + f"" + ) + current_bottom -= h + pieces.append( + f"{int(week.get('total_pairs', 0))}" + ) + pieces.append("") + return "".join(pieces) + + +def _build_scheme_table(week: Dict[str, Any]) -> str: + rows = [] + for day in week.get("days", []) or []: + codes = list(day.get("codes", []))[:8] + while len(codes) < 8: + codes.append("0") + cells = "".join( + f"" + for code in codes + ) + rows.append(f"{day.get('weekday')}{cells}") + + return ( + "" + + "".join(f"" for i in range(1, 9)) + + "" + + "".join(rows) + + "
День{i}
" + ) + + +def _build_class_block(item: Dict[str, Any]) -> Dict[str, Any]: + weeks = item.get("weeks", []) or [] + for week in weeks: + total = int(week.get("total_pairs", 0)) + week["conducted_display"] = _format_percent(int(week.get("conducted", 0)), total) + week["missed_display"] = _format_percent(int(week.get("missed", 0)), total) + week["other_display"] = _format_percent(int(week.get("other", 0)), total) + week["scheme_html"] = _build_scheme_table(week) + + item["weeks"] = weeks + item["chart_svg"] = _build_week_chart(weeks) + return item + + +def _aggregate_item(source_items: List[Dict[str, Any]], item_id: str, label: str, part_title: str) -> Dict[str, Any]: + return _build_class_block( + { + "id": item_id, + "label": label, + "title": label, + "part_id": part_title, + "section_title": part_title, + "weeks": _merge_weeks(source_items), + "is_aggregate": True, + } + ) + + +def _build_class_report_model(workspace_root: Path, context: Dict[str, Any] | None) -> Dict[str, Any]: + config = _load_context_config(workspace_root, context) + classes_df: pd.DataFrame = config["classes"] + settings = config["settings"] + + report_json = _load_json(workspace_root / "result" / "reports" / "report_classes.json") + raw_items = report_json.get("report", {}).get("items", []) or [] + raw_by_id = {str(item.get("group_id") or ""): item for item in raw_items} + + part_order = [str(part).strip() for part in classes_df["part"].fillna("").tolist() if str(part).strip()] + ordered_parts: List[str] = [] + for part in part_order: + if part not in ordered_parts: + ordered_parts.append(part) + + order_map = _row_order_map(classes_df) + + sections: List[Dict[str, Any]] = [] + for part in ordered_parts: + section_items: List[Dict[str, Any]] = [] + + if part == "Факультеты": + faculty_sources = [raw_by_id[g] for g in ["fe", "kl", "km", "lv", "mk", "mu"] if g in raw_by_id] + if faculty_sources: + section_items.append(_aggregate_item(faculty_sources, "before_804", "до 8.04", part)) + + for raw in raw_items: + group_id = str(raw.get("group_id") or "") + if _part_name(classes_df, group_id) != part: + continue + section_items.append( + _build_class_block( + { + "id": group_id, + "label": _display_label(classes_df, group_id), + "title": str(raw.get("title") or group_id), + "part_id": part, + "section_title": part, + "weeks": raw.get("weeks", []) or [], + "order": order_map.get(group_id, 9999), + "is_aggregate": False, + } + ) + ) + + section_items.sort(key=lambda item: (0 if item.get("is_aggregate") else 1, item.get("order", 9999), item.get("label", ""))) + if section_items: + sections.append({"id": part, "title": part, "items": section_items}) + + active_section = sections[0]["id"] if sections else "" + active_class = sections[0]["items"][0]["id"] if sections and sections[0]["items"] else "" + + report = { + "title": "Отчёт по классам", + "period": { + "start": report_json.get("report_start"), + "end": report_json.get("report_end"), + }, + "sections": sections, + "active_section": active_section, + "active_class": active_class, + "group_count": len(raw_items), + "class_count": len(sections), + } + return report + + +def _build_group_report_model(workspace_root: Path) -> Dict[str, Any]: + group_json = _load_json(workspace_root / "result" / "reports" / "report_groups.json") + schedule = group_json.get("schedule", {}) or {} + return { + "title": "Отчёт по группам", + "note": schedule.get("note", "Schedule data is not available yet."), + "lesson_windows": schedule.get("lesson_windows", []) or [], + } + + +def _render_jinja(template_path: Path, context: Dict[str, Any]) -> str: + env = Environment( + loader=FileSystemLoader(str(template_path.parent)), + autoescape=select_autoescape(["html", "xml"]), + ) + template = env.get_template(template_path.name) + return template.render(**context) + + +def run_stage(workspace_root: Path, context: Dict[str, Any] | None = None) -> Dict[str, Any]: + """Generate standalone HTML reports from Jinja templates.""" + template_dir = workspace_root / "template" + required = [ + template_dir / "report_class.html", + template_dir / "report_group.html", + template_dir / "report.css", + template_dir / "report_class.js", + template_dir / "report_group.js", + ] + missing = [str(path) for path in required if not path.exists()] + if missing: + raise FileNotFoundError("Template files are missing:\n" + "\n".join(missing)) + + css_text = _load_text(template_dir / "report.css") + class_js = _load_text(template_dir / "report_class.js") + group_js = _load_text(template_dir / "report_group.js") + + class_report = _build_class_report_model(workspace_root, context) + group_report = _build_group_report_model(workspace_root) + + class_html = _render_jinja( + template_dir / "report_class.html", + { + "title": class_report["title"], + "hint": f"Период: {class_report['period']['start']} — {class_report['period']['end']}", + "css_text": css_text, + "js_text": class_js, + "report": class_report, + "report_json": json.dumps(class_report, ensure_ascii=False), + }, + ) + group_html = _render_jinja( + template_dir / "report_group.html", + { + "title": group_report["title"], + "hint": group_report["note"], + "css_text": css_text, + "js_text": group_js, + "report": group_report, + "report_json": json.dumps(group_report, ensure_ascii=False), + }, + ) + + out_group = workspace_root / "result" / "report_groups.html" + out_class = workspace_root / "result" / "report_classes.html" + out_group.write_text(group_html, encoding="utf-8") + out_class.write_text(class_html, encoding="utf-8") + + print("✓ HTML reports generated") + print(f" - {out_group.name}") + print(f" - {out_class.name}") + + return {"group_html": str(out_group), "class_html": str(out_class)} diff --git a/lib/stage_load_settings.py b/lib/stage_load_settings.py new file mode 100644 index 0000000..b1387cd --- /dev/null +++ b/lib/stage_load_settings.py @@ -0,0 +1,94 @@ +"""Stage 1: Load configuration settings and class information.""" + +import yaml +import pandas as pd +from pathlib import Path +from typing import Dict, Any + + +class SettingsLoader: + """Load and manage configuration settings and class data.""" + + def __init__(self, workspace_root: Path): + """ + Initialize the settings loader. + + Args: + workspace_root: Root directory of the project + """ + self.workspace_root = Path(workspace_root) + self.settings = None + self.classes_df = None + + def load_settings(self) -> Dict[str, Any]: + """ + Load settings from settings.yaml. + + Returns: + Dictionary with configuration settings + """ + settings_path = self.workspace_root / "settings.yaml" + + if not settings_path.exists(): + raise FileNotFoundError(f"Settings file not found: {settings_path}") + + with open(settings_path, "r", encoding="utf-8") as f: + self.settings = yaml.safe_load(f) + + return self.settings + + def load_classes(self) -> pd.DataFrame: + """ + Load class information from classes.csv. + + Returns: + DataFrame with class information + """ + classes_path = self.workspace_root / "data" / "classes.csv" + + if not classes_path.exists(): + raise FileNotFoundError(f"Classes file not found: {classes_path}") + + self.classes_df = pd.read_csv(classes_path) + return self.classes_df + + def get_config(self) -> Dict[str, Any]: + """ + Get complete configuration including settings and classes. + + Returns: + Dictionary with loaded configuration + """ + if self.settings is None: + self.load_settings() + if self.classes_df is None: + self.load_classes() + + return { + "settings": self.settings, + "classes": self.classes_df, + } + + +def run_stage( + workspace_root: Path, + context: Dict[str, Any] | None = None, +) -> Dict[str, Any]: + """ + Execute the settings loading stage. + + Args: + workspace_root: Root directory of the project + + Returns: + Dictionary with loaded configuration + """ + loader = SettingsLoader(workspace_root) + config = loader.get_config() + + print("✓ Settings loaded successfully") + print(f" - Sections: {len(config['settings'].get('sections', []))}") + print(f" - Classes: {len(config['classes'])}") + print(f" - IP ranges: {len(config['settings'].get('class_ips', {}))}") + + return config diff --git a/lib/stage_parse_schedule.py b/lib/stage_parse_schedule.py new file mode 100644 index 0000000..a70d5d9 --- /dev/null +++ b/lib/stage_parse_schedule.py @@ -0,0 +1,58 @@ +"""Stage 3: Prepare university schedule data. + +This stage is intentionally a placeholder for the time being. The project +already stores lesson time windows in settings.yaml, but the actual university +schedule export is not available yet. +""" + +from __future__ import annotations + +from datetime import datetime, timezone +from pathlib import Path +from typing import Dict, Any + +from lib.stage_load_settings import SettingsLoader + + +def _normalize_schedule(settings: Dict[str, Any]) -> Dict[str, Any]: + """Extract the schedule section from settings in a stable JSON-friendly form.""" + year = settings.get("year", {}) if isinstance(settings, dict) else {} + lessons = [] + + for item in year.get("schedule", []) or []: + lessons.append( + { + "lesson": item.get("lesson"), + "start": str(item.get("start")), + "end": str(item.get("end")), + } + ) + + return { + "available": False, + "source": None, + "generated_at": datetime.now(timezone.utc).isoformat(), + "lesson_windows": lessons, + "group_lessons": [], + "note": "University schedule export is not available yet.", + } + + +def run_stage( + workspace_root: Path, + context: Dict[str, Any] | None = None, +) -> Dict[str, Any]: + """Create a placeholder schedule payload for the later stages.""" + if context and "stage_load_settings" in context: + config = context["stage_load_settings"] + else: + loader = SettingsLoader(workspace_root) + config = loader.get_config() + + schedule = _normalize_schedule(config["settings"]) + + print("✓ Schedule stage initialized") + print(" - Source export: not available yet") + print(f" - Lesson windows: {len(schedule['lesson_windows'])}") + + return {"schedule": schedule} diff --git a/lib/stage_process_logs.py b/lib/stage_process_logs.py new file mode 100644 index 0000000..f39a56b --- /dev/null +++ b/lib/stage_process_logs.py @@ -0,0 +1,508 @@ +"""Stage 2: Process authentication logs and create session records.""" + +import re +from pathlib import Path +from typing import Dict, Any, List, Tuple, Optional +from dataclasses import dataclass +from datetime import datetime +import pandas as pd +import ipaddress + + +@dataclass +class LogEntry: + """Represents a single log entry.""" + + timestamp: datetime + username: str + computer: str + ip_address: Optional[str] = None + + +@dataclass +class Session: + """Represents a user session.""" + + station: str + user: str + start: datetime + end: datetime + + +class LogProcessor: + """Process authentication logs and generate session records.""" + + def __init__(self, workspace_root: Path, config: Dict[str, Any]): + """ + Initialize the log processor. + + Args: + workspace_root: Root directory of the project + config: Configuration dictionary from stage 1 + """ + self.workspace_root = Path(workspace_root) + self.config = config + self.settings = config["settings"] + self.classes_df = config["classes"] + self.processing = self.settings.get("processing", {}) + switch_date_value = self.processing.get("m1_ip_to_name_switch_date", "2026-04-08") + if isinstance(switch_date_value, datetime): + self.m1_ip_to_name_switch_date = switch_date_value.date() + elif hasattr(switch_date_value, "year") and hasattr(switch_date_value, "month") and hasattr(switch_date_value, "day"): + self.m1_ip_to_name_switch_date = switch_date_value + else: + self.m1_ip_to_name_switch_date = datetime.strptime(str(switch_date_value), "%Y-%m-%d").date() + self.amt_group_id = self.processing.get("amt_group_id", "amt") + self.amt_class_id = self.processing.get("amt_class_id", "АМТ-33") + + # Build IP to class mapping + self._build_ip_class_mapping() + + def _build_ip_class_mapping(self) -> None: + """Build a mapping from IP prefixes to class information.""" + self.ip_to_classes = {} + + class_ips = self.settings.get("class_ips", {}) + + # Create a mapping from IP prefix to classes that use it + for _, row in self.classes_df.iterrows(): + prefix = row["prefix"] + + # Extract the IP prefix from the full prefix + # e.g., "pu-402-" -> "pu", "amt" -> "amt" + ip_prefix = prefix.split("-")[0] + + if ip_prefix in class_ips: + ip_subnet = class_ips[ip_prefix] + if ip_subnet not in self.ip_to_classes: + self.ip_to_classes[ip_subnet] = [] + self.ip_to_classes[ip_subnet].append(row) + + def _parse_log_entry(self, line: str, section: str) -> Optional[LogEntry]: + """ + Parse a single log entry line. + + Args: + line: Log line to parse + section: Section (okk1 or m1) + + Returns: + LogEntry or None if line is empty/invalid + """ + line = line.strip() + if not line: + return None + + # Parse: YYYY-MM-DD HH:MM:SS username computer_or_ip + parts = line.split() + + if len(parts) < 2: + return None + + try: + timestamp = datetime.fromisoformat(f"{parts[0]} {parts[1]}") + except (ValueError, IndexError): + return None + + # Handle cases where username or computer might be missing + username = "" + computer = "" + ip_address = None + + if len(parts) >= 3: + username = parts[2] + if len(parts) >= 4: + fourth_field = parts[3] + + # Check if it's an IP address + if self._is_ip_address(fourth_field): + ip_address = fourth_field + computer = fourth_field + else: + computer = fourth_field + + # Skip entries without username or computer + if not username or not computer: + return None + + return LogEntry( + timestamp=timestamp, + username=username, + computer=computer, + ip_address=ip_address + ) + + @staticmethod + def _is_ip_address(s: str) -> bool: + """Check if a string is an IP address.""" + try: + ipaddress.ip_address(s) + return True + except ValueError: + return False + + def _find_class_for_ip(self, ip_address: str) -> Optional[str]: + """ + Find class ID for a given IP address. + + Args: + ip_address: IP address to look up + + Returns: + Class ID or None if not found + """ + try: + ip = ipaddress.ip_address(ip_address) + except ValueError: + return None + + # Check exact matches first + for subnet_str, classes in self.ip_to_classes.items(): + # Convert subnet string to a proper network + try: + # If it's just an IP without CIDR, try to match Class C subnet (/24) + if "/" not in subnet_str: + # Try as exact IP first + if str(ip) == subnet_str: + return classes[0]["id"] if classes else None + + # Try as network address with /24 + try: + subnet = ipaddress.ip_network(f"{subnet_str}/24", strict=False) + if ip in subnet: + return classes[0]["id"] if classes else None + except ValueError: + pass + else: + # For subnets with explicit CIDR, check if IP is in range + subnet = ipaddress.ip_network(subnet_str, strict=False) + if ip in subnet: + return classes[0]["id"] if classes else None + except ValueError: + continue + + return None + + def _find_class_for_computer(self, computer: str, section: str) -> Optional[str]: + """ + Find class ID for a computer in a given section. + + Args: + computer: Computer name (e.g., "303k1" for okk1, "pu-402-1" for m1) + section: Section (okk1 or m1) + + Returns: + Class ID or None + """ + if section == "okk1": + # For okk1, extract prefix from computer name + # e.g., "303k1" -> "303k" (but we need to find the exact class) + # Extract the room/class part (digits only at end) + match = re.match(r"^(.+?)(\d+)$", computer) + if not match: + return None + + prefix_part = match.group(1) # e.g., "303k" + + # Find matching class by prefix + for _, row in self.classes_df.iterrows(): + if row["prefix"] == prefix_part: + return row["id"] + elif section == "m1": + # For m1, format is like "pu-402-1" (prefix-class-station) + if computer == "amt": + return self.amt_class_id + + parts = computer.split("-") + if len(parts) >= 2: + # Reconstruct the prefix from parts + # "pu-402-1" -> look for class with prefix starting with "pu" + prefix_start = parts[0] + + # Find matching class + for _, row in self.classes_df.iterrows(): + row_prefix = row["prefix"] + # Check if the computer prefix matches this class + # e.g., row_prefix "pu-402-" matches computer "pu-402-1" + if row_prefix.startswith(prefix_start + "-"): + # Check if the class part matches + if computer.startswith(row_prefix): + return row["id"] + + return None + + def process_files(self) -> Dict[str, List[Session]]: + """ + Process all log files and extract sessions. + + Returns: + Dictionary mapping class/group IDs to lists of sessions + """ + sessions_by_group = {} + + input_dir = self.workspace_root / "input" + + # Process both sections + for section_dir in ["stat_m1", "stat_okk1"]: + section_path = input_dir / section_dir + + if not section_path.exists(): + continue + + section = section_dir.split("_")[1] # Extract okk1 or m1 + + # Process each month directory + for month_dir in sorted(section_path.iterdir()): + if not month_dir.is_dir(): + continue + + # Process each day file + for day_file in sorted(month_dir.glob("*.txt")): + entries = self._read_log_file(day_file, section) + sessions = self._extract_sessions(entries, section, day_file) + + # Group by class + for session in sessions: + if session.station: + # Determine class ID from session data + class_info = self._find_class_from_session( + session, section, day_file + ) + if class_info: + session_date = class_info.get('date') + group_id = class_info['class_id'] + + # For m1 before the switch date, group by ip_group. + if section == "m1" and class_info.get('ip_group'): + if class_info['ip_group'] == self.amt_group_id: + group_id = self.amt_group_id + elif session_date and session_date < self.m1_ip_to_name_switch_date: + group_id = class_info['ip_group'] + + if group_id: + if group_id not in sessions_by_group: + sessions_by_group[group_id] = [] + sessions_by_group[group_id].append(session) + + return sessions_by_group + + def _read_log_file( + self, file_path: Path, section: str + ) -> List[Tuple[str, LogEntry]]: + """ + Read and parse a log file. + + Args: + file_path: Path to log file + section: Section (okk1 or m1) + + Returns: + List of (computer_identifier, LogEntry) tuples + """ + entries = {} + + try: + with open(file_path, "r", encoding="utf-8", errors="ignore") as f: + for line in f: + entry = self._parse_log_entry(line, section) + if entry: + key = f"{entry.username}:{entry.computer}" + if key not in entries: + entries[key] = [] + entries[key].append(entry) + except Exception as e: + print(f"Warning: Error reading {file_path}: {e}") + + # Flatten to list of entries + result = [] + for entries_list in entries.values(): + for entry in entries_list: + result.append((entry.computer, entry)) + + return result + + def _extract_sessions( + self, entries: List[Tuple[str, LogEntry]], section: str, file_path: Path + ) -> List[Session]: + """ + Extract sessions from log entries. + + Args: + entries: List of parsed log entries + section: Section (okk1 or m1) + file_path: Path to the log file + + Returns: + List of extracted sessions + """ + sessions = [] + + # Group entries by (username, computer) + grouped = {} + for computer, entry in entries: + key = (entry.username, computer) + if key not in grouped: + grouped[key] = [] + grouped[key].append(entry) + + # Extract sessions from grouped entries + for (username, computer), entry_list in grouped.items(): + # Sort by timestamp + entry_list.sort(key=lambda e: e.timestamp) + + # Pair consecutive entries + for i in range(0, len(entry_list) - 1, 2): + start_entry = entry_list[i] + end_entry = entry_list[i + 1] + + sessions.append(Session( + station=computer, + user=username, + start=start_entry.timestamp, + end=end_entry.timestamp + )) + + return sessions + + def _find_class_from_session( + self, session: Session, section: str, file_path: Path + ) -> Optional[dict]: + """ + Find the class ID for a session. + + Args: + session: Session to find class for + section: Section (okk1 or m1) + file_path: Path to the log file being processed + + Returns: + Dict with 'class_id', 'ip_group', and 'date', or None + """ + # Extract date from file path + date_str = file_path.stem # e.g., "13" + month_str = file_path.parent.name # e.g., "m1_202601" + + # Try to parse the date + try: + month_part = month_str.split("_")[1] # e.g., "202601" + session_date = datetime.strptime( + f"{month_part}{date_str:0>2}", "%Y%m%d" + ).date() + except (ValueError, IndexError): + session_date = None + + # For IP addresses, use IP-based lookup + if self._is_ip_address(session.station): + # Check the date cutoff for m1 (08.04.2026) + cutoff_date = datetime.strptime("20260408", "%Y%m%d").date() + + if session_date and session_date < cutoff_date: + class_id = self._find_class_for_ip(session.station) + if class_id: + # Get ip_group for this class + class_row = self.classes_df[self.classes_df['id'] == class_id] + if not class_row.empty: + ip_group = class_row.iloc[0].get('ip_group', '') + return { + 'class_id': class_id, + 'ip_group': ip_group if ip_group else None, + 'date': session_date + } + return None + + # For computer names, extract class + if section == "m1" and session.station == "amt": + return { + 'class_id': self.amt_class_id, + 'ip_group': self.amt_group_id, + 'date': session_date + } + class_id = self._find_class_for_computer(session.station, section) + if class_id: + return { + 'class_id': class_id, + 'ip_group': None, + 'date': session_date + } + + return None + + def write_results(self, sessions_by_class: Dict[str, List[Session]]) -> None: + """ + Write session results to CSV files. + + Args: + sessions_by_class: Dictionary mapping class/group IDs to sessions + """ + output_dir = self.workspace_root / "result" / "logs" + output_dir.mkdir(parents=True, exist_ok=True) + + for group_id, sessions in sessions_by_class.items(): + # Create safe filename from group_id + # Escape any problematic characters + safe_filename = group_id.replace("/", "-").replace(" ", "_") + output_file = output_dir / f"{safe_filename}.csv" + + # Create DataFrame + data = [ + { + "station": session.station, + "user": session.user, + "start": session.start.isoformat(sep=" "), + "end": session.end.isoformat(sep=" "), + } + for session in sessions + ] + + df = pd.DataFrame(data) + df = df.sort_values(["start"]) + + # Write to CSV + df.to_csv(output_file, index=False) + + +def run_stage( + workspace_root: Path, + context: Dict[str, Any] | None = None, +) -> Dict[str, Any]: + """ + Execute the log processing stage. + + Args: + workspace_root: Root directory of the project + + Returns: + Dictionary with processing results + """ + # Load config from stage 1, if it is already present in the pipeline context. + if context and "stage_load_settings" in context: + config = context["stage_load_settings"] + else: + from lib.stage_load_settings import SettingsLoader + + loader = SettingsLoader(workspace_root) + config = loader.get_config() + + # Process logs + processor = LogProcessor(workspace_root, config) + sessions_by_group = processor.process_files() + processor.write_results(sessions_by_group) + + # Print statistics + total_sessions = sum(len(sessions) for sessions in sessions_by_group.values()) + + print("✓ Logs processed successfully") + print(f" - Groups/Classes with data: {len(sessions_by_group)}") + print(f" - Total sessions: {total_sessions}") + + # Also show per-group statistics + for group_id in sorted(sessions_by_group.keys()): + count = len(sessions_by_group[group_id]) + # Try to identify if it's ip_group by checking if value is single letter + group_type = "(ip_group)" if group_id == "amt" or (len(group_id) <= 3 and group_id.islower()) else "(class)" + print(f" • {group_id}: {count} sessions {group_type}") + + return { + "sessions_by_group": sessions_by_group, + "output_dir": str(workspace_root / "result" / "logs"), + } diff --git a/output/.gitkeep b/output/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/result/.gitkeep b/result/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/run.py b/run.py new file mode 100755 index 0000000..a152940 --- /dev/null +++ b/run.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python3 +"""Main entry point for attendance processing pipeline.""" + +import sys +from pathlib import Path + +# Add workspace root to path +workspace_root = Path(__file__).parent +sys.path.insert(0, str(workspace_root)) + +from lib.pipeline import create_default_pipeline + + +def main(): + """Execute the attendance processing pipeline.""" + try: + pipeline = create_default_pipeline(workspace_root) + context = pipeline.run() + return 0 + except Exception as e: + print(f"Error: {str(e)}", file=sys.stderr) + return 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/settings.yaml b/settings.yaml index 12c54d7..e604a68 100644 --- a/settings.yaml +++ b/settings.yaml @@ -1,3 +1,40 @@ +report_start: 2026-02-09 +report_end: 2026-04-17 + +year: + first_week: 2026-01-05 + week: + - ПН + - ВТ + - СР + - ЧТ + - ПТ + - СБ + schedule: + - lesson: 1 + start: 08:00:00+04:00 + end: 09:20:00+04:00 + - lesson: 2 + start: 09:30:00+04:00 + end: 10:50:00+04:00 + - lesson: 3 + start: 11:00:00+04:00 + end: 12:20:00+04:00 + - lesson: 4 + start: 12:45:00+04:00 + end: 14:05:00+04:00 + - lesson: 5 + start: 14:15:00+04:00 + end: 15:35:00+04:00 + - lesson: 6 + start: 15:45:00+04:00 + end: 17:05:00+04:00 + - lesson: 7 + start: 17:15:00+04:00 + end: 18:35:00+04:00 + - lesson: 8 + start: 18:40:00+04:00 + end: 20:00:00+04:00 sections: - id: okk1 @@ -5,9 +42,6 @@ sections: - id: m1 name: Классы факультетов -classes: - - class_ips: pu: 10.4.8.0 mk: 10.10.19.0 @@ -17,3 +51,8 @@ class_ips: fe: 10.5.0.0 amt: 10.2.225.108 kl: 10.3.1.0 + +processing: + m1_ip_to_name_switch_date: 2026-04-08 + amt_group_id: amt + amt_class_id: АМТ-33 diff --git a/template/report.css b/template/report.css new file mode 100644 index 0000000..c7f0e29 --- /dev/null +++ b/template/report.css @@ -0,0 +1,498 @@ +:root { + color-scheme: light; + --bg: #f7f8fb; + --panel: #ffffff; + --text: #1b1f2a; + --muted: #667085; + --line: #d9e0ea; + --accent: #2563eb; + --accent-2: #0f766e; + --shadow: 0 8px 24px rgba(15, 23, 42, 0.08); + --bad: #ef4444; + --warn: #f59e0b; + --good: #22c55e; + --empty: #e5e7eb; +} + +* { box-sizing: border-box; } +body { + margin: 0; + font-family: Inter, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; + color: var(--text); + background: var(--bg); +} + +.page { + max-width: 1440px; + margin: 0 auto; + padding: 24px; +} + +.header { + display: flex; + justify-content: space-between; + gap: 16px; + align-items: flex-start; + margin-bottom: 18px; +} + +.title h1 { + margin: 0 0 8px; + font-size: 30px; +} + +.title p { + margin: 0; + color: var(--muted); +} + +.actions { + display: flex; + gap: 12px; + flex-wrap: wrap; +} + +.btn { + border: 1px solid var(--line); + background: var(--panel); + border-radius: 12px; + padding: 10px 14px; + cursor: pointer; + box-shadow: var(--shadow); +} + +.btn.primary { + background: linear-gradient(135deg, var(--accent), #4f46e5); + color: white; + border-color: transparent; +} + +.section, +.class-block, +.screen-nav, +.print-nav { + background: var(--panel); + border: 1px solid var(--line); + border-radius: 18px; + box-shadow: var(--shadow); +} + +.section { + padding: 20px; +} + +.section h2, +.print-nav h2 { + margin: 0 0 16px; + font-size: 22px; +} + +.cards { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); + gap: 14px; + margin-bottom: 18px; +} + +.card { + border: 1px solid var(--line); + border-radius: 16px; + padding: 16px; + background: linear-gradient(180deg, #fff, #fbfcff); +} + +.card-value { + font-size: 26px; + font-weight: 700; + line-height: 1.1; +} + +.card-label { + color: var(--muted); + margin-top: 6px; +} + +.muted { color: var(--muted); } + +.screen-nav { + padding: 14px; + margin-bottom: 20px; +} + +.section-nav, +.class-nav-group { + display: flex; + gap: 10px; + flex-wrap: wrap; +} + +.class-nav { + margin-top: 12px; +} + +.class-nav-group { display: none; } +.class-nav-group.active { display: flex; } + +.nav-btn { + border: 1px solid var(--line); + background: #fff; + color: var(--text); + border-radius: 999px; + padding: 10px 14px; + cursor: pointer; + transition: 0.15s ease; +} + +.nav-btn:hover { border-color: var(--accent); } +.nav-btn.active { + background: var(--accent); + border-color: var(--accent); + color: #fff; +} + +.print-nav { + display: none; + padding: 18px 20px; + margin-bottom: 20px; +} + +.print-nav-section + .print-nav-section { margin-top: 14px; } +.print-nav-section h3 { margin: 0 0 8px; } +.print-nav-section ul { margin: 0; padding-left: 18px; } + +.report-section { margin-bottom: 26px; } + +.class-block { + display: none; + padding: 20px; + margin-bottom: 18px; +} + +.class-block.active { display: block; } + +.class-head { + display: flex; + justify-content: space-between; + gap: 12px; + align-items: flex-start; + margin-bottom: 14px; +} + +.class-kicker { + color: var(--muted); + font-size: 12px; + text-transform: uppercase; + letter-spacing: 0.06em; + margin-bottom: 4px; +} + +.class-head h3 { + margin: 0; + font-size: 24px; +} + +.class-note { + margin-top: 6px; + color: var(--muted); + font-size: 13px; +} + +.class-chart { + overflow-x: auto; + margin-bottom: 16px; +} + +.week-chart { + width: 100%; + height: auto; + min-width: 720px; +} + +.chart-week-label { + font-size: 12px; + fill: var(--text); +} + +.chart-count { + font-size: 12px; + fill: var(--text); + font-weight: 600; +} + +.week-bar.code-1 { fill: var(--bad); } +.week-bar.code-2 { fill: var(--warn); } +.week-bar.code-3 { fill: var(--good); } + +.class-table, +.scheme-table, +.table { + width: 100%; + border-collapse: collapse; +} + +.class-table th, +.class-table td, +.scheme-table th, +.scheme-table td, +.table th, +.table td { + border-bottom: 1px solid var(--line); + padding: 10px 12px; + vertical-align: top; + text-align: left; +} + +.class-table th, +.scheme-table th, +.table th { + font-size: 13px; + color: var(--muted); + text-transform: uppercase; + letter-spacing: 0.04em; + background: #f8fafc; +} + +.week-label { white-space: nowrap; } +.num { white-space: nowrap; } + +.scheme-cell-wrap { min-width: 420px; } + +.scheme-table { + width: 100%; + min-width: 420px; + border: 1px solid var(--line); + border-radius: 12px; + overflow: hidden; +} + +.scheme-table th, +.scheme-table td { + padding: 6px; + text-align: center; +} + +.scheme-table thead th:first-child, +.scheme-table tbody th { + text-align: left; + white-space: nowrap; +} + +.scheme-cell { + display: inline-block; + width: 18px; + height: 18px; + border-radius: 4px; + background: var(--empty); + border: 1px solid rgba(0, 0, 0, 0.06); +} + +.scheme-cell.code-0 { background: var(--empty); } +.scheme-cell.code-1 { background: var(--bad); } +.scheme-cell.code-2 { background: var(--warn); } +.scheme-cell.code-3 { background: var(--good); } + +.code-1 { color: var(--bad); } +.code-2 { color: var(--warn); } +.code-3 { color: var(--good); } + +@media print { + body { background: #fff; } + .page { max-width: none; padding: 0; } + .screen-nav, + .actions { display: none !important; } + .print-nav { display: block; } + .class-block { display: block !important; box-shadow: none; break-inside: avoid; page-break-inside: avoid; } + .section, .class-block, .print-nav { box-shadow: none; } + .table th, .class-table th { position: static; } +} +:root { + color-scheme: light; + --bg: #f7f8fb; + --panel: #ffffff; + --text: #1b1f2a; + --muted: #667085; + --line: #d9e0ea; + --accent: #2563eb; + --accent-2: #0f766e; + --shadow: 0 8px 24px rgba(15, 23, 42, 0.08); +} + +* { box-sizing: border-box; } +body { + margin: 0; + font-family: Inter, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; + color: var(--text); + background: var(--bg); +} + +.page { + max-width: 1400px; + margin: 0 auto; + padding: 24px; +} + +.header { + display: flex; + justify-content: space-between; + gap: 16px; + align-items: flex-start; + margin-bottom: 20px; +} + +.title h1 { + margin: 0 0 8px; + font-size: 30px; +} + +.title p { + margin: 0; + color: var(--muted); +} + +.actions { + display: flex; + gap: 12px; + flex-wrap: wrap; +} + +.btn { + border: 1px solid var(--line); + background: var(--panel); + border-radius: 12px; + padding: 10px 14px; + cursor: pointer; + box-shadow: var(--shadow); +} + +.btn.primary { + background: linear-gradient(135deg, var(--accent), #4f46e5); + color: white; + border-color: transparent; +} + +.section { + background: var(--panel); + border: 1px solid var(--line); + border-radius: 18px; + padding: 20px; + margin-bottom: 20px; + box-shadow: var(--shadow); +} + +.section h2 { + margin: 0 0 16px; + font-size: 22px; +} + +.cards { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); + gap: 14px; +} + +.card { + border: 1px solid var(--line); + border-radius: 16px; + padding: 16px; + background: linear-gradient(180deg, #fff, #fbfcff); +} + +.card-value { + font-size: 26px; + font-weight: 700; + line-height: 1.1; +} + +.card-label { + color: var(--muted); + margin-top: 6px; +} + +.table { + width: 100%; + border-collapse: collapse; +} + +.table th, +.table td { + border-bottom: 1px solid var(--line); + padding: 10px 12px; + vertical-align: top; + text-align: left; +} + +.table th { + font-size: 13px; + color: var(--muted); + text-transform: uppercase; + letter-spacing: 0.04em; + background: #f8fafc; + position: sticky; + top: 0; + z-index: 1; +} + +.muted { color: var(--muted); } + +.pill { + display: inline-block; + padding: 4px 8px; + border-radius: 999px; + background: #e8eefb; + color: #274a8a; + font-size: 12px; + font-weight: 600; +} + +.grid-2 { + display: grid; + grid-template-columns: 1.3fr 1fr; + gap: 16px; +} + +.chart-wrap { + min-height: 80px; + overflow-x: auto; +} + +.bar-chart { + width: 100%; + height: auto; + overflow: visible; +} + +.chart-label { + font-size: 12px; + fill: #1b1f2a; + dominant-baseline: middle; +} + +.chart-value { + font-size: 12px; + fill: #334155; + dominant-baseline: middle; + font-weight: 600; +} + +.chart-track { fill: #e8edf5; } +.chart-bar { fill: var(--accent); } +.chart-bar.secondary { fill: var(--accent-2); } + +.note { + padding: 14px 16px; + border-left: 4px solid var(--accent); + background: #eff6ff; + border-radius: 12px; + margin-bottom: 18px; +} + +.nowrap { white-space: nowrap; } + +@media print { + body { background: white; } + .page { max-width: none; padding: 0; } + .actions { display: none; } + .section, .card { box-shadow: none; } + .section { break-inside: avoid; } + .table th { position: static; } +} diff --git a/template/report_class.html b/template/report_class.html new file mode 100644 index 0000000..e6bfc74 --- /dev/null +++ b/template/report_class.html @@ -0,0 +1,141 @@ + + + + + + {{ title }} + + + +
+
+
+

{{ title }}

+

{{ hint }}

+
+
+ +
+
+ +
+
+ {% for section in report.sections %} + + {% endfor %} +
+ +
+ {% for section in report.sections %} +
+ {% for item in section.items %} + + {% endfor %} +
+ {% endfor %} +
+
+ + + +
+ {% for section in report.sections %} +
+ {% for item in section.items %} +
+
+
+
{{ section.title }}
+

{{ item.label }}

+ {% if item.source_labels %} +
{{ item.source_labels | join(', ') }}
+ {% endif %} +
+
+ +
+{{ item.chart_svg | safe }} +
+ +
+ + + + + + + + + + + + + {% for week in item.weeks %} + + + + + + + + + {% endfor %} + +
НеделяВсего парПар проведеноПар пропущеноИные парыСхема
{{ week.long }}{{ week.total_pairs }}{{ week.conducted_display }}{{ week.missed_display }}{{ week.other_display }}{{ week.scheme_html | safe }}
+
+
+ {% endfor %} +
+ {% endfor %} +
+
+ + + + + + + + + + + {{TITLE}} + {{STYLE_TAG}} + + +
+
+
+

{{TITLE}}

+

{{HINT}}

+
+
+ +
+
+ {{CONTENT}} +
+ {{SCRIPT_TAG}} + + diff --git a/template/report_class.js b/template/report_class.js new file mode 100644 index 0000000..d5036ee --- /dev/null +++ b/template/report_class.js @@ -0,0 +1,73 @@ +(function () { + function qs(selector, root) { + return (root || document).querySelector(selector); + } + + function qsa(selector, root) { + return Array.from((root || document).querySelectorAll(selector)); + } + + function setActiveSection(sectionId) { + qsa('.section-nav .nav-btn[data-section]').forEach((btn) => { + btn.classList.toggle('active', btn.dataset.section === sectionId); + }); + + qsa('.class-nav-group').forEach((group) => { + group.classList.toggle('active', group.dataset.section === sectionId); + }); + + const firstButton = qs(`.class-nav-group.active .class-btn[data-class-id]`); + if (firstButton) { + setActiveClass(firstButton.dataset.classId, false); + } + } + + function setActiveClass(classId, scrollIntoView) { + qsa('.class-btn[data-class-id]').forEach((btn) => { + btn.classList.toggle('active', btn.dataset.classId === classId); + }); + + qsa('.class-block[data-class-id]').forEach((block) => { + const active = block.dataset.classId === classId; + block.classList.toggle('active', active); + if (active && scrollIntoView) { + block.scrollIntoView({ behavior: 'smooth', block: 'start' }); + } + }); + } + + function init() { + const report = window.__CLASS_REPORT__ || {}; + const activeSection = report.active_section || ''; + const activeClass = report.active_class || ''; + + qsa('.section-nav .nav-btn[data-section]').forEach((btn) => { + btn.addEventListener('click', () => setActiveSection(btn.dataset.section)); + }); + + qsa('.class-btn[data-class-id]').forEach((btn) => { + btn.addEventListener('click', () => setActiveClass(btn.dataset.classId, true)); + }); + + if (activeSection) { + setActiveSection(activeSection); + } + + if (activeClass) { + setActiveClass(activeClass, false); + } + } + + window.printReport = function printReport() { + window.print(); + }; + + if (document.readyState === 'loading') { + document.addEventListener('DOMContentLoaded', init); + } else { + init(); + } +})(); +function printReport() { + window.print(); +} diff --git a/template/report_group.html b/template/report_group.html new file mode 100644 index 0000000..429b9ef --- /dev/null +++ b/template/report_group.html @@ -0,0 +1,77 @@ + + + + + + {{ title }} + + + +
+
+
+

{{ title }}

+

{{ hint }}

+
+
+ +
+
+ +
+

Шаблон пар

+ {% if report.lesson_windows %} + + + + + + {% for item in report.lesson_windows %} + + + + + + {% endfor %} + +
ПараНачалоОкончание
{{ item.lesson }}{{ item.start }}{{ item.end }}
+ {% else %} +
Нет данных.
+ {% endif %} +
+
+ + + + + + + + + + + {{TITLE}} + {{STYLE_TAG}} + + +
+
+
+

{{TITLE}}

+

{{HINT}}

+
+
+ +
+
+ {{CONTENT}} +
+ {{SCRIPT_TAG}} + + diff --git a/template/report_group.js b/template/report_group.js new file mode 100644 index 0000000..67a519a --- /dev/null +++ b/template/report_group.js @@ -0,0 +1,6 @@ +window.printReport = function printReport() { + window.print(); +}; +function printReport() { + window.print(); +}