diff --git a/CLAUDE.md b/CLAUDE.md index 737d084..d04d8af 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -8,77 +8,93 @@ F1tness Parser is a FastAPI-based web application that parses fitness training d - **Obsidian Notes**: Markdown tables with `# DD.MM.YYYY (trainer-session)` headers - **Apple Notes**: Bold markdown tables with `**DD.MM.YYYY (trainer-session)**` headers -The application uses a layered architecture with parsers, models, services, and API endpoints. +The project is split into two applications in one repository: +- `backend/` - FastAPI JSON API (parsers, models, services, PostgreSQL) +- `frontend/` - static site on plain HTML + CSS + JS (ES modules, no build step), served by nginx, which also proxies `/api/` to the backend ## Development Commands -### Local Development -```bash -# Start development server -python run.py +The project is developed and run **only in Docker**: there is no local Python setup. Everything below runs inside the `fastapi-app` container (backend code lives in `backend/`, inside the container it is `/app`) (`.env` must have `POSTGRES_DATABASE_HOST=postgres`, see `.env.example`). -# Start with Docker Compose (includes PostgreSQL) +### Docker Development +```bash +# Start backend (:8000) + frontend (:8080) + PostgreSQL (applies migrations on start, hot reload for backend/app/) +# Open http://localhost:8080 docker compose up --build -# Run migrations manually -python -c "from migrations.runner import MigrationRunner; from app.config import settings; import asyncio; asyncio.run(MigrationRunner(settings.get_postgres_database_url()).run_migrations())" +# Apply migrations manually (Alembic; the app itself does NOT migrate on startup) +docker compose exec fastapi-app alembic upgrade head + +# Create a migration after changing tables in app/core/database/tables.py +# (-u keeps the generated file owned by you instead of root) +docker compose exec -u "$(id -u):$(id -g)" fastapi-app alembic revision --autogenerate -m "describe change" + +# Import all Obsidian + Apple notes into the database +docker compose exec fastapi-app python -m app.cli import [--replace] + +# Stop (keeps the data) / stop and drop the database volume +docker compose down +docker compose down -v ``` +Rebuild (`--build`) is needed only after changing `requirements*.txt`, `Dockerfile` or `pyproject.toml`. ### Testing +Tests that need a database use a separate `_test` database (`TEST_DATABASE_URL`, created automatically). Without it they are skipped. ```bash -# Run tests -pytest +# Run all tests +docker compose exec fastapi-app pytest # Run specific test file -pytest tests/test_core/test_obsidian_parser.py +docker compose exec fastapi-app pytest tests/test_core/test_obsidian_parser.py -# Run tests with coverage -pytest --cov=app +# Without a running stack (starts postgres, runs once, removes the container) +docker compose run --rm fastapi-app pytest ``` ### Type Checking ```bash -# Run type checking -mypy app/ +docker compose exec fastapi-app mypy app/ ``` ## Architecture ### Core Components -**Parser Architecture**: The system uses a base parser class (`app/core/parsers/base.py`) with format-specific implementations: +**Parser Architecture**: The system uses a base parser class (`backend/app/core/parsers/base.py`) with format-specific implementations: - `ObsidianNotesParser` - handles Obsidian markdown format - `AppleNotesParser` - handles Apple notes format - Each parser includes exercise name mapping for normalization -**Data Models**: Located in `app/core/dto/training.py`: +**Data Models**: Located in `backend/app/core/dto/training.py`: - `Training` - represents a workout session - `Exercise` - individual exercise with multiple approaches - `Approach` - single set with weight and reps -**API Structure**: -- `/api/v1/` - REST API endpoints -- `/app/` - Web interface endpoints -- Static files served from `app/static/` -- Templates in `app/templates/` +**API Structure** (backend, JSON only): +- `/api/v1/trainings/`, `/api/v1/exercises/`, `/api/v1/exercises/progress/?name=`, `/api/v1/parser/parse/`, `/api/v1/health/` + +**Frontend** (`frontend/`): +- `index.html`, `exercises.html`, `parse.html` - pages; `js/common.js` (API + DOM helpers), `js/table.js` (search/sort/paging), one module per page +- `vendor/` - Bootstrap CSS and Chart.js (the only third-party code) +- `nginx.conf` - serves static files and proxies `/api/` to `fastapi-app:8000` (same origin, no CORS) ### Database -The application supports both SQLite (default) and PostgreSQL. Database migrations are handled by a custom migration runner in `migrations/runner.py` that reads SQL files from `migrations/sql/`. +The backend uses PostgreSQL through async SQLAlchemy (asyncpg). tables are described with SQLAlchemy Core (no ORM) in `backend/app/core/database/tables.py`, `TrainingRepository` (`backend/app/core/database/repository.py`) is the data access layer, and a session is injected into endpoints with `Depends(get_session)`. Schema migrations are handled by Alembic (`alembic.ini`, `migrations/`); the URL is taken from `app/config.py`. -Configuration is managed through `app/config.py` using Pydantic settings with `.env` file support. +Configuration is managed through `backend/app/config.py` using Pydantic settings with `.env` file support. ### Key Files -- `app/main.py` - FastAPI application setup with lifespan management -- `app/config.py` - Application configuration and database settings -- `run.py` - Development server entry point -- `migrations/runner.py` - Custom database migration system -- `compose.yaml` - Docker Compose setup with PostgreSQL +- `backend/app/main.py` - FastAPI application setup with lifespan management +- `backend/app/config.py` - Application configuration and database settings +- `backend/run.py` - Standalone uvicorn runner (unused: Docker starts uvicorn from `compose.yaml`) +- `backend/migrations/` - Alembic environment and versions +- `compose.yaml` - Docker Compose setup: backend, frontend, PostgreSQL ## Environment Setup -Copy `.env.example` to `.env` and configure: +Copy `.env.example` to `.env` (repo root) and configure: - PostgreSQL connection settings - Debug mode - PYTHONPATH (for Docker) diff --git a/README.md b/README.md index 4a28bc8..752dd70 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,17 @@ Приложение для парсинга текстовых файлов тренировок +## Структура +- `backend/` - FastAPI, JSON API (`/api/v1/...`), PostgreSQL +- `frontend/` - статический сайт на HTML + CSS + JS, раздаётся nginx, запросы `/api/` проксирует на бэкенд + +## Запуск +```bash +docker compose up --build +docker compose exec fastapi-app python -m app.cli import # загрузить заметки в базу +``` +Сайт: http://localhost:8080, API и документация: http://localhost:8000/docs + ## Поддерживаемые записи Работает с двумя категорями записей: - Obsidian notes diff --git a/app/api/v1/endpoints/trainings.py b/app/api/v1/endpoints/trainings.py deleted file mode 100644 index 07b8d79..0000000 --- a/app/api/v1/endpoints/trainings.py +++ /dev/null @@ -1,62 +0,0 @@ -from datetime import datetime -import logging -from fastapi import APIRouter - -from app.core.database.connection import SQLiteExecutor -from app.core.database.models.approach import ApproachOps -from app.core.database.models.training import TrainingOps -from app.core.database.models.exercise import ExerciseOps -from app.core.dto.training import TrainingDTO -from app.core.parsers.obsidian import parse_training_data - - -sqllite_executor = SQLiteExecutor() - -router = APIRouter() - - -@router.get("/obsidian/") -async def obsidian_trainings_list(): - return {"data": parse_training_data()} - - -@router.get("/test/create/") -async def create_sample_training(): - test_training = TrainingDTO(date=datetime.now().date(), trainer="Stepka") - training_executor = TrainingOps(sqllite_executor) - result_id = await training_executor.create(test_training) - return {"status": "ok", "create_id": result_id} - - -@router.get("/test/get/list/") -async def get_trainings_list(): - training_executor = TrainingOps(sqllite_executor) - results = await training_executor.list() - return {"status": "ok", "create_id": results} - - -@router.delete("/test/delete/") -async def delete_by_ids(): - training_executor = TrainingOps(sqllite_executor) - await training_executor.delete(list_of_ids=[4,5,6]) - return {"status": "ok"} - - -@router.post("/test/create/") -async def create_full_training(): - training_executor = TrainingOps(sqllite_executor) - exercise_executor = ExerciseOps(sqllite_executor) - approach_executor = ApproachOps(sqllite_executor) - sample_training_data: TrainingDTO = parse_training_data()[-1] - logging.info(sample_training_data) - training_id: int = await training_executor.create(sample_training_data) - if sample_training_data.exercises: - for exercise in sample_training_data.exercises: - exercise.training_id = training_id - exercise_id: int = await exercise_executor.create(exercise) - if exercise.approaches: - for approach in exercise.approaches: - approach.exercise_id = exercise_id - await approach_executor.create(approach) - - return {"status": "ok"} diff --git a/app/api/v1/web.py b/app/api/v1/web.py deleted file mode 100644 index a75a8e5..0000000 --- a/app/api/v1/web.py +++ /dev/null @@ -1,47 +0,0 @@ -import logging -from fastapi import APIRouter, Request, Form -from fastapi.responses import HTMLResponse -from fastapi.templating import Jinja2Templates - -from app.core.parsers.obsidian import ObsidianNotesParser, parse_training_data -from app.core.templates.templates import BaseTemplateResponse - -web_router = APIRouter() -templates = Jinja2Templates(directory="app/templates") -template_renderer = BaseTemplateResponse(templates) - - -@web_router.get("/", response_class=HTMLResponse) -async def home(request: Request): - """Home page""" - - return template_renderer.render( - request, - "index.html", - ) - - -@web_router.get("/obsidian/list/", response_class=HTMLResponse) -async def obsidian_list(request: Request): - data = parse_training_data() - return template_renderer.render( - request=request, template_name="trainings.html", context={"trainings": data} - ) - - -@web_router.get("/obsidian/parse", response_class=HTMLResponse) -async def obsidian_parse_form(request: Request): - return template_renderer.render( - request=request, template_name="obsidian/parser.html", context={"trainings": {}} - ) - - -@web_router.post("/obsidian/parse", response_class=HTMLResponse) -async def obsidian_parse(request: Request, training_data: str = Form(...)): - logging.error(training_data) - op = ObsidianNotesParser() - result = op.parse(data=training_data) - logging.error(result) - return template_renderer.render( - request=request, template_name="trainings.html", context={"trainings": result} - ) diff --git a/app/core/database/connection.py b/app/core/database/connection.py deleted file mode 100644 index 97d508a..0000000 --- a/app/core/database/connection.py +++ /dev/null @@ -1,36 +0,0 @@ -from typing import Dict, List, Any -import aiosqlite -from app.config import settings - - -class SQLiteExecutor: - """Executor для SQL запросов в БД SQLlite""" - def __init__(self) -> None: - self._db_path = settings.SQLITE_DATABASE_PATH - - async def execute_query( - self, query: str, params: tuple = () - ) -> List[Dict[str, Any]]: - """Выполнить запрос, который не должен вносить изменения в БД. - - :param query: SQL запрос - :param params: Параметры, которые нужно передать вместе с запросом - :return: Список, выдаваемый aiosqlite - """ - async with aiosqlite.connect(self._db_path) as db: - db.row_factory = aiosqlite.Row - cursor = await db.execute(query, params) - rows = await cursor.fetchall() - return [dict(row) for row in rows] - - async def execute_mod_query(self, query: str, params: tuple = ()) -> int: - """Выполнить запрос, который что-то изменяет в БД. - - :param query: SQL запрос - :param params: Параметры, которые нужно передать вместе с запросом - :return: Список, выдаваемый aiosqlite - """ - async with aiosqlite.connect(self._db_path) as db: - cursor = await db.execute(query, params) - await db.commit() - return cursor.lastrowid if cursor.lastrowid else cursor.rowcount diff --git a/app/core/database/models/approach.py b/app/core/database/models/approach.py deleted file mode 100644 index 3cfcb19..0000000 --- a/app/core/database/models/approach.py +++ /dev/null @@ -1,26 +0,0 @@ -from typing import List, Dict, Any -from app.core.database.connection import SQLiteExecutor -from app.core.dto.training import ApproachDTO - - -class ApproachOps: - TABLE_NAME: str = "approaches" - - def __init__(self, executor: SQLiteExecutor) -> None: - self._executor = executor - - async def create(self, approach: ApproachDTO) -> int: - query = f"INSERT INTO {self.TABLE_NAME} (exercise_id, weight, reps) VALUES (?, ?, ?)" - return await self._executor.execute_mod_query( - query, (approach.exercise_id, approach.weight, approach.reps) - ) - - async def list(self) -> List[Dict[str, Any]]: - query = f"SELECT * FROM {self.TABLE_NAME}" - return await self._executor.execute_query(query) - - async def delete(self, list_of_ids: List[int]) -> None: - placeholders: str = ",".join("?" * len(list_of_ids)) - query = f"DELETE FROM {self.TABLE_NAME} WHERE id IN ({placeholders})" - await self._executor.execute_mod_query(query, tuple(list_of_ids)) - return None diff --git a/app/core/database/models/exercise.py b/app/core/database/models/exercise.py deleted file mode 100644 index a453799..0000000 --- a/app/core/database/models/exercise.py +++ /dev/null @@ -1,26 +0,0 @@ -from typing import List, Dict, Any -from app.core.database.connection import SQLiteExecutor -from app.core.dto.training import ExerciseDTO - - -class ExerciseOps: - TABLE_NAME: str = "exercises" - - def __init__(self, executor: SQLiteExecutor) -> None: - self._executor = executor - - async def create(self, exercise: ExerciseDTO) -> int: - query = f"INSERT INTO {self.TABLE_NAME} (training_id, name, splitted_weight) VALUES (?, ?, ?)" - return await self._executor.execute_mod_query( - query, (exercise.training_id, exercise.name, exercise.splitted_weight) - ) - - async def list(self) -> List[Dict[str, Any]]: - query = f"SELECT * FROM {self.TABLE_NAME}" - return await self._executor.execute_query(query) - - async def delete(self, list_of_ids: List[int]) -> None: - placeholders: str = ",".join("?" * len(list_of_ids)) - query = f"DELETE FROM {self.TABLE_NAME} WHERE id IN ({placeholders})" - await self._executor.execute_mod_query(query, tuple(list_of_ids)) - return None diff --git a/app/core/database/models/training.py b/app/core/database/models/training.py deleted file mode 100644 index 5ea30c3..0000000 --- a/app/core/database/models/training.py +++ /dev/null @@ -1,26 +0,0 @@ -from typing import List, Dict, Any -from app.core.database.connection import SQLiteExecutor -from app.core.dto.training import TrainingDTO - - -class TrainingOps: - TABLE_NAME: str = "trainings" - - def __init__(self, executor: SQLiteExecutor) -> None: - self._executor = executor - - async def create(self, training: TrainingDTO) -> int: - query = f"INSERT INTO {self.TABLE_NAME} (date, trainer) VALUES (?, ?)" - return await self._executor.execute_mod_query( - query, (training.date, training.trainer) - ) - - async def list(self) -> List[Dict[str, Any]]: - query = f"SELECT * FROM {self.TABLE_NAME}" - return await self._executor.execute_query(query) - - async def delete(self, list_of_ids: List[int]) -> None: - placeholders: str = ",".join("?" * len(list_of_ids)) - query = f"DELETE FROM {self.TABLE_NAME} WHERE id IN ({placeholders})" - await self._executor.execute_mod_query(query, tuple(list_of_ids)) - return None diff --git a/app/core/dto/training.py b/app/core/dto/training.py deleted file mode 100644 index c853add..0000000 --- a/app/core/dto/training.py +++ /dev/null @@ -1,25 +0,0 @@ -from typing import List, Optional -from pydantic import BaseModel -from datetime import date - - -class ApproachDTO(BaseModel): - id: Optional[int] = None - exercise_id: Optional[int] = None - weight: float - reps: int - - -class ExerciseDTO(BaseModel): - id: Optional[int] = None - training_id: Optional[int] = None - name: str - splitted_weight: bool = False - approaches: Optional[List[ApproachDTO]] = None - - -class TrainingDTO(BaseModel): - id: Optional[int] = None - date: date - trainer: Optional[str] = None - exercises: Optional[List[ExerciseDTO]] = None diff --git a/app/core/parsers/apple.py b/app/core/parsers/apple.py deleted file mode 100644 index 68b6acc..0000000 --- a/app/core/parsers/apple.py +++ /dev/null @@ -1,84 +0,0 @@ -import re -from typing import List, Tuple -from datetime import datetime - -from app.core.dto.training import TrainingDTO -from app.core.parsers.apple_mapper import unique_apple_exercises_mapper -from app.core.parsers.base import BaseNotesParser - - -class AppleNotesParser(BaseNotesParser): - """Parser for Apple Notes format training data.""" - - def __init__(self): - super().__init__("complete_data/apple.md", unique_apple_exercises_mapper) - - def filter_training_data(self, training_data: str) -> str: - """Filter Apple-specific training data format.""" - cleaned_text = re.sub( - r"^\|(\s+|-*|\s-*\s)\|(\s+|-*|\s-*\s)\|(\s+|-*|\s-*\s)\|$", - "", - training_data, - flags=re.MULTILINE, - ) - cleaned_text = re.sub(r"^\n", "", cleaned_text, flags=re.MULTILINE) - lines = cleaned_text.splitlines() - redundant_lines = [ - "| | | |", - "|---|---|---|", - "|**Упражнение**|**Вес**|**Подходы**|", - ] - filtered_lines = [line for line in lines if line not in redundant_lines] - return "\n".join(filtered_lines) - - def parse_training_header(self, training_data_line: str) -> Tuple[bool, str, str, str]: - """Parse Apple Notes training header format.""" - pattern: str = ( - r"^\*\*(?P\d+.\d+.\d+)\s\((?P.+)(-(?P.+))?\)\*\*" - ) - match = re.search(pattern, training_data_line) - if match: - date = match.group("date").strip() - trainer = match.group("trainer").strip() - if match.group("year_counter"): - year_count = match.group("year_counter").strip() - else: - year_count = "0" - return True, date, trainer, year_count - return False, "", "", "" - - def create_training_from_date(self, date_str: str) -> TrainingDTO: - """Create Training object from date string with fallback parsing.""" - try: - return TrainingDTO( - date=datetime.strptime(date_str, "%d.%m.%Y").date(), exercises=[] - ) - except ValueError: - return TrainingDTO( - date=datetime.strptime(date_str, "%d.%m.%y").date(), exercises=[] - ) - - def parse(self, data: str) -> List[TrainingDTO]: - """Parse Apple Notes training data from string input.""" - # Override the data file reading with direct string input - original_method = self.read_data_file - self.read_data_file = lambda _: data - - try: - trainings = self.parse_and_map_training_data() - return trainings - finally: - # Restore original method - self.read_data_file = original_method - - -def parse_training_data() -> List[TrainingDTO]: - """Parse Apple Notes training data.""" - parser = AppleNotesParser() - return parser.parse_training_data() - - -def remap_unique_exercises(apple_trainings: List[TrainingDTO]) -> List[TrainingDTO]: - """Remap exercise names using Apple-specific mapping (deprecated - use parser.parse_and_map_training_data()).""" - parser = AppleNotesParser() - return parser.apply_exercise_mapping(apple_trainings) diff --git a/app/core/parsers/base.py b/app/core/parsers/base.py deleted file mode 100644 index 4b10e6a..0000000 --- a/app/core/parsers/base.py +++ /dev/null @@ -1,140 +0,0 @@ -import os -from typing import List, Tuple, Dict, Optional - -from app.core.dto.training import ApproachDTO, ExerciseDTO, TrainingDTO -from app.core.utils.date_refactor import parse_training_date - - -class BaseNotesParser: - """Base class for parsing training data from different note formats.""" - - def __init__(self, data_file_name: str, exercise_mapper: Optional[Dict[str, str]] = None): - self.data_file_name = data_file_name - self.project_root = os.getcwd() - self.exercise_mapper = exercise_mapper or {} - - def get_data_path(self) -> str: - return os.path.join(self.project_root, "data") - - def get_data_file_path(self, file_name: str) -> str: - return os.path.join(self.get_data_path(), file_name) - - def read_data_file(self, file_name: str) -> str: - path_to_file = self.get_data_file_path(file_name) - with open(path_to_file, "r") as f: - content = f.read() - return content - - def serialize_exercise(self, reps: str, weight: str, name: str) -> ExerciseDTO: - """Convert raw exercise data into Exercise object with approaches.""" - reps_list: List[int] = [int(rep) for rep in reps.split("-")] - weight_splitted: bool = False - weight_list: List[float] = [] - - if weight: - weight_str_list: List[str] = [weight for weight in weight.split("-")] - if any(split_anchor in weight_str_list[0] for split_anchor in ["x", "х"]): - weight_splitted = True - splitter = "x" if "x" in weight_str_list[0] else "х" - weight_list = [ - float(xweight.split(splitter)[0]) for xweight in weight_str_list - ] - else: - weight_list = [float(w) for w in weight_str_list] - - approaches = [] - if not weight: - for rep_index in range(0, len(reps_list)): - approach = ApproachDTO(weight=0.0, reps=reps_list[rep_index]) - approaches.append(approach) - else: - weight_pointer = 0 - for rep_index in range(0, len(reps_list)): - approach = ApproachDTO( - weight=weight_list[weight_pointer], reps=reps_list[rep_index] - ) - if rep_index < len(weight_list) - 1: - weight_pointer += 1 - approaches.append(approach) - - exercise = ExerciseDTO( - name=name, approaches=approaches, splitted_weight=weight_splitted - ) - return exercise - - def parse_training_exercises(self, exercise_line: str) -> ExerciseDTO: - """Parse exercise data from a table row.""" - stripped: List[str] = [entry.strip() for entry in exercise_line.split("|")][ - 1:-1 - ] - for entry in stripped: - if entry in ["Упражнение", "Вес", "Подходы"]: - raise ValueError - if stripped: - if "---" in stripped[0]: - raise ValueError - if len(stripped) != 3: - raise ValueError - return self.serialize_exercise( - name=stripped[0], weight=stripped[1], reps=stripped[2] - ) - raise ValueError("No valid exercise data found") - - def filter_training_data(self, training_data: str) -> str: - """Filter and clean training data. Override in subclasses for specific formats.""" - return training_data - - def parse_training_header( - self, training_data_line: str - ) -> Tuple[bool, str, str, str]: - """Parse training header. Override in subclasses for specific formats.""" - raise NotImplementedError("Subclasses must implement parse_training_header") - - def create_training_from_date(self, date_str: str) -> TrainingDTO: - """Create Training object from date string using utility function.""" - return TrainingDTO(date=parse_training_date(date_str), exercises=[]) - - def parse_training_data(self) -> List[TrainingDTO]: - """Main parsing method. Override for specific parsing logic.""" - training_data = self.filter_training_data( - self.read_data_file(self.data_file_name) - ) - lines = training_data.splitlines() - current_training = None - trains = [] - - for index, line in enumerate(lines): - header_parsed, date, _, _ = self.parse_training_header(line) - if index == len(lines) - 1: - trains.append(current_training) - if header_parsed: - trains.append(current_training) - current_training = self.create_training_from_date(date) - continue - try: - exr = self.parse_training_exercises(line) - if current_training: - current_training.exercises.append(exr) - except ValueError: - pass - - return [train for train in trains if train is not None] - - def apply_exercise_mapping(self, trainings: List[TrainingDTO]) -> List[TrainingDTO]: - """Apply exercise name mapping to all trainings.""" - for training in trainings: - if not training or not training.exercises: - continue - for exercise in training.exercises: - if not exercise: - continue - mapped_name = self.exercise_mapper.get(exercise.name) - if mapped_name is not None: - exercise.name = mapped_name - return trainings - - def parse_and_map_training_data(self) -> List[TrainingDTO]: - """Parse training data and apply exercise mapping.""" - trainings = self.parse_training_data() - return self.apply_exercise_mapping(trainings) - diff --git a/app/core/parsers/obsidian.py b/app/core/parsers/obsidian.py deleted file mode 100644 index a97366d..0000000 --- a/app/core/parsers/obsidian.py +++ /dev/null @@ -1,62 +0,0 @@ -import re -from typing import List, Tuple - -from app.core.dto.training import TrainingDTO -from app.core.parsers.obsidian_mapper import obsidian_unique_exercies_mapping -from app.core.parsers.base import BaseNotesParser - - -class ObsidianNotesParser(BaseNotesParser): - """Parser for Obsidian Notes format training data.""" - - def __init__(self): - super().__init__( - data_file_name="complete_data/obsidian.md", - exercise_mapper=obsidian_unique_exercies_mapping, - ) - - def filter_training_data(self, training_data: str) -> str: - """Filter Obsidian-specific training data format.""" - cleaned_text = re.sub(r"^\s*?\n", "", training_data, flags=re.MULTILINE) - return cleaned_text - - def parse_training_header( - self, training_data_line: str - ) -> Tuple[bool, str, str, str]: - """Parse Obsidian Notes training header format.""" - pattern: str = ( - r"#\s(?P\d+.\d+.\d+)\s\((?P.+)-(?P.+)\)" - ) - match = re.search(pattern, training_data_line) - if match: - date = match.group("date").strip() - trainer = match.group("trainer").strip() - year_count = match.group("year_counter").strip() - return True, date, trainer, year_count - return False, "", "", "" - - def parse(self, data: str) -> List[TrainingDTO]: - """Parse Obsidian training data from string input.""" - # Override the data file reading with direct string input - original_method = self.read_data_file - self.read_data_file = lambda _: data - - try: - trainings = self.parse_and_map_training_data() - return trainings - finally: - # Restore original method - self.read_data_file = original_method - - -def parse_training_data() -> List[TrainingDTO]: - """Parse Obsidian Notes training data.""" - parser = ObsidianNotesParser() - return parser.parse_training_data() - - -def remap_unique_exercises(obsidian_trainings: List[TrainingDTO]) -> List[TrainingDTO]: - """Remap exercise names using Obsidian-specific mapping (deprecated - use parser.parse_and_map_training_data()).""" - parser = ObsidianNotesParser() - return parser.apply_exercise_mapping(obsidian_trainings) - diff --git a/app/core/templates/templates.py b/app/core/templates/templates.py deleted file mode 100644 index 80b668d..0000000 --- a/app/core/templates/templates.py +++ /dev/null @@ -1,30 +0,0 @@ -from typing import Optional -from fastapi import Request -from fastapi.templating import Jinja2Templates - - -class BaseTemplateResponse: - """Базовый метод для рендеринга Jinja2 темплейтов. - - Нужен в первую очередь для того, чтобы подставлять какие-то дефолтные значения (которые есть - на всех страницах) в переменные темплейтов - - Attributes: - templates: Формат темплейтов, используемых в проекте - """ - def __init__(self, templates: Jinja2Templates): - self.templates = templates - - def render( - self, request: Request, template_name: str, context: Optional[dict] = None - ): - base_context = { - "request": request, - "title": "Fitness stats", - "app_name": "Fitness parser" - } - - if context: - base_context.update(context) - - return self.templates.TemplateResponse(template_name, base_context) diff --git a/app/schemas/__init__.py b/app/schemas/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/app/static/css/main.css b/app/static/css/main.css deleted file mode 100644 index fe6e869..0000000 --- a/app/static/css/main.css +++ /dev/null @@ -1,30 +0,0 @@ -/* Custom styles for Fitness Parser */ - -body { - font-family: Arial, sans-serif; - line-height: 1.6; - color: #333; -} - -.navbar-brand { - font-size: 1.5rem; -} - -.card { - border: 1px solid #ddd; - margin-bottom: 1rem; -} - -.card:hover { - box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); -} - -.btn { - font-weight: 500; -} - -/* Footer */ -footer { - margin-top: auto; - border-top: 1px solid #ddd; -} \ No newline at end of file diff --git a/app/static/js/bootstrap.bundle.min.js b/app/static/js/bootstrap.bundle.min.js deleted file mode 100644 index b1999d9..0000000 --- a/app/static/js/bootstrap.bundle.min.js +++ /dev/null @@ -1,7 +0,0 @@ -/*! - * Bootstrap v5.3.2 (https://getbootstrap.com/) - * Copyright 2011-2023 The Bootstrap Authors (https://github.com/twbs/bootstrap/graphs/contributors) - * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) - */ -!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).bootstrap=e()}(this,(function(){"use strict";const t=new Map,e={set(e,i,n){t.has(e)||t.set(e,new Map);const s=t.get(e);s.has(i)||0===s.size?s.set(i,n):console.error(`Bootstrap doesn't allow more than one instance per element. Bound instance: ${Array.from(s.keys())[0]}.`)},get:(e,i)=>t.has(e)&&t.get(e).get(i)||null,remove(e,i){if(!t.has(e))return;const n=t.get(e);n.delete(i),0===n.size&&t.delete(e)}},i="transitionend",n=t=>(t&&window.CSS&&window.CSS.escape&&(t=t.replace(/#([^\s"#']+)/g,((t,e)=>`#${CSS.escape(e)}`))),t),s=t=>{t.dispatchEvent(new Event(i))},o=t=>!(!t||"object"!=typeof t)&&(void 0!==t.jquery&&(t=t[0]),void 0!==t.nodeType),r=t=>o(t)?t.jquery?t[0]:t:"string"==typeof t&&t.length>0?document.querySelector(n(t)):null,a=t=>{if(!o(t)||0===t.getClientRects().length)return!1;const e="visible"===getComputedStyle(t).getPropertyValue("visibility"),i=t.closest("details:not([open])");if(!i)return e;if(i!==t){const e=t.closest("summary");if(e&&e.parentNode!==i)return!1;if(null===e)return!1}return e},l=t=>!t||t.nodeType!==Node.ELEMENT_NODE||!!t.classList.contains("disabled")||(void 0!==t.disabled?t.disabled:t.hasAttribute("disabled")&&"false"!==t.getAttribute("disabled")),c=t=>{if(!document.documentElement.attachShadow)return null;if("function"==typeof t.getRootNode){const e=t.getRootNode();return e instanceof ShadowRoot?e:null}return t instanceof ShadowRoot?t:t.parentNode?c(t.parentNode):null},h=()=>{},d=t=>{t.offsetHeight},u=()=>window.jQuery&&!document.body.hasAttribute("data-bs-no-jquery")?window.jQuery:null,f=[],p=()=>"rtl"===document.documentElement.dir,m=t=>{var e;e=()=>{const e=u();if(e){const i=t.NAME,n=e.fn[i];e.fn[i]=t.jQueryInterface,e.fn[i].Constructor=t,e.fn[i].noConflict=()=>(e.fn[i]=n,t.jQueryInterface)}},"loading"===document.readyState?(f.length||document.addEventListener("DOMContentLoaded",(()=>{for(const t of f)t()})),f.push(e)):e()},g=(t,e=[],i=t)=>"function"==typeof t?t(...e):i,_=(t,e,n=!0)=>{if(!n)return void g(t);const o=(t=>{if(!t)return 0;let{transitionDuration:e,transitionDelay:i}=window.getComputedStyle(t);const n=Number.parseFloat(e),s=Number.parseFloat(i);return n||s?(e=e.split(",")[0],i=i.split(",")[0],1e3*(Number.parseFloat(e)+Number.parseFloat(i))):0})(e)+5;let r=!1;const a=({target:n})=>{n===e&&(r=!0,e.removeEventListener(i,a),g(t))};e.addEventListener(i,a),setTimeout((()=>{r||s(e)}),o)},b=(t,e,i,n)=>{const s=t.length;let o=t.indexOf(e);return-1===o?!i&&n?t[s-1]:t[0]:(o+=i?1:-1,n&&(o=(o+s)%s),t[Math.max(0,Math.min(o,s-1))])},v=/[^.]*(?=\..*)\.|.*/,y=/\..*/,w=/::\d+$/,A={};let E=1;const T={mouseenter:"mouseover",mouseleave:"mouseout"},C=new Set(["click","dblclick","mouseup","mousedown","contextmenu","mousewheel","DOMMouseScroll","mouseover","mouseout","mousemove","selectstart","selectend","keydown","keypress","keyup","orientationchange","touchstart","touchmove","touchend","touchcancel","pointerdown","pointermove","pointerup","pointerleave","pointercancel","gesturestart","gesturechange","gestureend","focus","blur","change","reset","select","submit","focusin","focusout","load","unload","beforeunload","resize","move","DOMContentLoaded","readystatechange","error","abort","scroll"]);function O(t,e){return e&&`${e}::${E++}`||t.uidEvent||E++}function x(t){const e=O(t);return t.uidEvent=e,A[e]=A[e]||{},A[e]}function k(t,e,i=null){return Object.values(t).find((t=>t.callable===e&&t.delegationSelector===i))}function L(t,e,i){const n="string"==typeof e,s=n?i:e||i;let o=I(t);return C.has(o)||(o=t),[n,s,o]}function S(t,e,i,n,s){if("string"!=typeof e||!t)return;let[o,r,a]=L(e,i,n);if(e in T){const t=t=>function(e){if(!e.relatedTarget||e.relatedTarget!==e.delegateTarget&&!e.delegateTarget.contains(e.relatedTarget))return t.call(this,e)};r=t(r)}const l=x(t),c=l[a]||(l[a]={}),h=k(c,r,o?i:null);if(h)return void(h.oneOff=h.oneOff&&s);const d=O(r,e.replace(v,"")),u=o?function(t,e,i){return function n(s){const o=t.querySelectorAll(e);for(let{target:r}=s;r&&r!==this;r=r.parentNode)for(const a of o)if(a===r)return P(s,{delegateTarget:r}),n.oneOff&&N.off(t,s.type,e,i),i.apply(r,[s])}}(t,i,r):function(t,e){return function i(n){return P(n,{delegateTarget:t}),i.oneOff&&N.off(t,n.type,e),e.apply(t,[n])}}(t,r);u.delegationSelector=o?i:null,u.callable=r,u.oneOff=s,u.uidEvent=d,c[d]=u,t.addEventListener(a,u,o)}function D(t,e,i,n,s){const o=k(e[i],n,s);o&&(t.removeEventListener(i,o,Boolean(s)),delete e[i][o.uidEvent])}function $(t,e,i,n){const s=e[i]||{};for(const[o,r]of Object.entries(s))o.includes(n)&&D(t,e,i,r.callable,r.delegationSelector)}function I(t){return t=t.replace(y,""),T[t]||t}const N={on(t,e,i,n){S(t,e,i,n,!1)},one(t,e,i,n){S(t,e,i,n,!0)},off(t,e,i,n){if("string"!=typeof e||!t)return;const[s,o,r]=L(e,i,n),a=r!==e,l=x(t),c=l[r]||{},h=e.startsWith(".");if(void 0===o){if(h)for(const i of Object.keys(l))$(t,l,i,e.slice(1));for(const[i,n]of Object.entries(c)){const s=i.replace(w,"");a&&!e.includes(s)||D(t,l,r,n.callable,n.delegationSelector)}}else{if(!Object.keys(c).length)return;D(t,l,r,o,s?i:null)}},trigger(t,e,i){if("string"!=typeof e||!t)return null;const n=u();let s=null,o=!0,r=!0,a=!1;e!==I(e)&&n&&(s=n.Event(e,i),n(t).trigger(s),o=!s.isPropagationStopped(),r=!s.isImmediatePropagationStopped(),a=s.isDefaultPrevented());const l=P(new Event(e,{bubbles:o,cancelable:!0}),i);return a&&l.preventDefault(),r&&t.dispatchEvent(l),l.defaultPrevented&&s&&s.preventDefault(),l}};function P(t,e={}){for(const[i,n]of Object.entries(e))try{t[i]=n}catch(e){Object.defineProperty(t,i,{configurable:!0,get:()=>n})}return t}function M(t){if("true"===t)return!0;if("false"===t)return!1;if(t===Number(t).toString())return Number(t);if(""===t||"null"===t)return null;if("string"!=typeof t)return t;try{return JSON.parse(decodeURIComponent(t))}catch(e){return t}}function j(t){return t.replace(/[A-Z]/g,(t=>`-${t.toLowerCase()}`))}const F={setDataAttribute(t,e,i){t.setAttribute(`data-bs-${j(e)}`,i)},removeDataAttribute(t,e){t.removeAttribute(`data-bs-${j(e)}`)},getDataAttributes(t){if(!t)return{};const e={},i=Object.keys(t.dataset).filter((t=>t.startsWith("bs")&&!t.startsWith("bsConfig")));for(const n of i){let i=n.replace(/^bs/,"");i=i.charAt(0).toLowerCase()+i.slice(1,i.length),e[i]=M(t.dataset[n])}return e},getDataAttribute:(t,e)=>M(t.getAttribute(`data-bs-${j(e)}`))};class H{static get Default(){return{}}static get DefaultType(){return{}}static get NAME(){throw new Error('You have to implement the static method "NAME", for each component!')}_getConfig(t){return t=this._mergeConfigObj(t),t=this._configAfterMerge(t),this._typeCheckConfig(t),t}_configAfterMerge(t){return t}_mergeConfigObj(t,e){const i=o(e)?F.getDataAttribute(e,"config"):{};return{...this.constructor.Default,..."object"==typeof i?i:{},...o(e)?F.getDataAttributes(e):{},..."object"==typeof t?t:{}}}_typeCheckConfig(t,e=this.constructor.DefaultType){for(const[n,s]of Object.entries(e)){const e=t[n],r=o(e)?"element":null==(i=e)?`${i}`:Object.prototype.toString.call(i).match(/\s([a-z]+)/i)[1].toLowerCase();if(!new RegExp(s).test(r))throw new TypeError(`${this.constructor.NAME.toUpperCase()}: Option "${n}" provided type "${r}" but expected type "${s}".`)}var i}}class W extends H{constructor(t,i){super(),(t=r(t))&&(this._element=t,this._config=this._getConfig(i),e.set(this._element,this.constructor.DATA_KEY,this))}dispose(){e.remove(this._element,this.constructor.DATA_KEY),N.off(this._element,this.constructor.EVENT_KEY);for(const t of Object.getOwnPropertyNames(this))this[t]=null}_queueCallback(t,e,i=!0){_(t,e,i)}_getConfig(t){return t=this._mergeConfigObj(t,this._element),t=this._configAfterMerge(t),this._typeCheckConfig(t),t}static getInstance(t){return e.get(r(t),this.DATA_KEY)}static getOrCreateInstance(t,e={}){return this.getInstance(t)||new this(t,"object"==typeof e?e:null)}static get VERSION(){return"5.3.2"}static get DATA_KEY(){return`bs.${this.NAME}`}static get EVENT_KEY(){return`.${this.DATA_KEY}`}static eventName(t){return`${t}${this.EVENT_KEY}`}}const B=t=>{let e=t.getAttribute("data-bs-target");if(!e||"#"===e){let i=t.getAttribute("href");if(!i||!i.includes("#")&&!i.startsWith("."))return null;i.includes("#")&&!i.startsWith("#")&&(i=`#${i.split("#")[1]}`),e=i&&"#"!==i?n(i.trim()):null}return e},z={find:(t,e=document.documentElement)=>[].concat(...Element.prototype.querySelectorAll.call(e,t)),findOne:(t,e=document.documentElement)=>Element.prototype.querySelector.call(e,t),children:(t,e)=>[].concat(...t.children).filter((t=>t.matches(e))),parents(t,e){const i=[];let n=t.parentNode.closest(e);for(;n;)i.push(n),n=n.parentNode.closest(e);return i},prev(t,e){let i=t.previousElementSibling;for(;i;){if(i.matches(e))return[i];i=i.previousElementSibling}return[]},next(t,e){let i=t.nextElementSibling;for(;i;){if(i.matches(e))return[i];i=i.nextElementSibling}return[]},focusableChildren(t){const e=["a","button","input","textarea","select","details","[tabindex]",'[contenteditable="true"]'].map((t=>`${t}:not([tabindex^="-"])`)).join(",");return this.find(e,t).filter((t=>!l(t)&&a(t)))},getSelectorFromElement(t){const e=B(t);return e&&z.findOne(e)?e:null},getElementFromSelector(t){const e=B(t);return e?z.findOne(e):null},getMultipleElementsFromSelector(t){const e=B(t);return e?z.find(e):[]}},R=(t,e="hide")=>{const i=`click.dismiss${t.EVENT_KEY}`,n=t.NAME;N.on(document,i,`[data-bs-dismiss="${n}"]`,(function(i){if(["A","AREA"].includes(this.tagName)&&i.preventDefault(),l(this))return;const s=z.getElementFromSelector(this)||this.closest(`.${n}`);t.getOrCreateInstance(s)[e]()}))},q=".bs.alert",V=`close${q}`,K=`closed${q}`;class Q extends W{static get NAME(){return"alert"}close(){if(N.trigger(this._element,V).defaultPrevented)return;this._element.classList.remove("show");const t=this._element.classList.contains("fade");this._queueCallback((()=>this._destroyElement()),this._element,t)}_destroyElement(){this._element.remove(),N.trigger(this._element,K),this.dispose()}static jQueryInterface(t){return this.each((function(){const e=Q.getOrCreateInstance(this);if("string"==typeof t){if(void 0===e[t]||t.startsWith("_")||"constructor"===t)throw new TypeError(`No method named "${t}"`);e[t](this)}}))}}R(Q,"close"),m(Q);const X='[data-bs-toggle="button"]';class Y extends W{static get NAME(){return"button"}toggle(){this._element.setAttribute("aria-pressed",this._element.classList.toggle("active"))}static jQueryInterface(t){return this.each((function(){const e=Y.getOrCreateInstance(this);"toggle"===t&&e[t]()}))}}N.on(document,"click.bs.button.data-api",X,(t=>{t.preventDefault();const e=t.target.closest(X);Y.getOrCreateInstance(e).toggle()})),m(Y);const U=".bs.swipe",G=`touchstart${U}`,J=`touchmove${U}`,Z=`touchend${U}`,tt=`pointerdown${U}`,et=`pointerup${U}`,it={endCallback:null,leftCallback:null,rightCallback:null},nt={endCallback:"(function|null)",leftCallback:"(function|null)",rightCallback:"(function|null)"};class st extends H{constructor(t,e){super(),this._element=t,t&&st.isSupported()&&(this._config=this._getConfig(e),this._deltaX=0,this._supportPointerEvents=Boolean(window.PointerEvent),this._initEvents())}static get Default(){return it}static get DefaultType(){return nt}static get NAME(){return"swipe"}dispose(){N.off(this._element,U)}_start(t){this._supportPointerEvents?this._eventIsPointerPenTouch(t)&&(this._deltaX=t.clientX):this._deltaX=t.touches[0].clientX}_end(t){this._eventIsPointerPenTouch(t)&&(this._deltaX=t.clientX-this._deltaX),this._handleSwipe(),g(this._config.endCallback)}_move(t){this._deltaX=t.touches&&t.touches.length>1?0:t.touches[0].clientX-this._deltaX}_handleSwipe(){const t=Math.abs(this._deltaX);if(t<=40)return;const e=t/this._deltaX;this._deltaX=0,e&&g(e>0?this._config.rightCallback:this._config.leftCallback)}_initEvents(){this._supportPointerEvents?(N.on(this._element,tt,(t=>this._start(t))),N.on(this._element,et,(t=>this._end(t))),this._element.classList.add("pointer-event")):(N.on(this._element,G,(t=>this._start(t))),N.on(this._element,J,(t=>this._move(t))),N.on(this._element,Z,(t=>this._end(t))))}_eventIsPointerPenTouch(t){return this._supportPointerEvents&&("pen"===t.pointerType||"touch"===t.pointerType)}static isSupported(){return"ontouchstart"in document.documentElement||navigator.maxTouchPoints>0}}const ot=".bs.carousel",rt=".data-api",at="next",lt="prev",ct="left",ht="right",dt=`slide${ot}`,ut=`slid${ot}`,ft=`keydown${ot}`,pt=`mouseenter${ot}`,mt=`mouseleave${ot}`,gt=`dragstart${ot}`,_t=`load${ot}${rt}`,bt=`click${ot}${rt}`,vt="carousel",yt="active",wt=".active",At=".carousel-item",Et=wt+At,Tt={ArrowLeft:ht,ArrowRight:ct},Ct={interval:5e3,keyboard:!0,pause:"hover",ride:!1,touch:!0,wrap:!0},Ot={interval:"(number|boolean)",keyboard:"boolean",pause:"(string|boolean)",ride:"(boolean|string)",touch:"boolean",wrap:"boolean"};class xt extends W{constructor(t,e){super(t,e),this._interval=null,this._activeElement=null,this._isSliding=!1,this.touchTimeout=null,this._swipeHelper=null,this._indicatorsElement=z.findOne(".carousel-indicators",this._element),this._addEventListeners(),this._config.ride===vt&&this.cycle()}static get Default(){return Ct}static get DefaultType(){return Ot}static get NAME(){return"carousel"}next(){this._slide(at)}nextWhenVisible(){!document.hidden&&a(this._element)&&this.next()}prev(){this._slide(lt)}pause(){this._isSliding&&s(this._element),this._clearInterval()}cycle(){this._clearInterval(),this._updateInterval(),this._interval=setInterval((()=>this.nextWhenVisible()),this._config.interval)}_maybeEnableCycle(){this._config.ride&&(this._isSliding?N.one(this._element,ut,(()=>this.cycle())):this.cycle())}to(t){const e=this._getItems();if(t>e.length-1||t<0)return;if(this._isSliding)return void N.one(this._element,ut,(()=>this.to(t)));const i=this._getItemIndex(this._getActive());if(i===t)return;const n=t>i?at:lt;this._slide(n,e[t])}dispose(){this._swipeHelper&&this._swipeHelper.dispose(),super.dispose()}_configAfterMerge(t){return t.defaultInterval=t.interval,t}_addEventListeners(){this._config.keyboard&&N.on(this._element,ft,(t=>this._keydown(t))),"hover"===this._config.pause&&(N.on(this._element,pt,(()=>this.pause())),N.on(this._element,mt,(()=>this._maybeEnableCycle()))),this._config.touch&&st.isSupported()&&this._addTouchEventListeners()}_addTouchEventListeners(){for(const t of z.find(".carousel-item img",this._element))N.on(t,gt,(t=>t.preventDefault()));const t={leftCallback:()=>this._slide(this._directionToOrder(ct)),rightCallback:()=>this._slide(this._directionToOrder(ht)),endCallback:()=>{"hover"===this._config.pause&&(this.pause(),this.touchTimeout&&clearTimeout(this.touchTimeout),this.touchTimeout=setTimeout((()=>this._maybeEnableCycle()),500+this._config.interval))}};this._swipeHelper=new st(this._element,t)}_keydown(t){if(/input|textarea/i.test(t.target.tagName))return;const e=Tt[t.key];e&&(t.preventDefault(),this._slide(this._directionToOrder(e)))}_getItemIndex(t){return this._getItems().indexOf(t)}_setActiveIndicatorElement(t){if(!this._indicatorsElement)return;const e=z.findOne(wt,this._indicatorsElement);e.classList.remove(yt),e.removeAttribute("aria-current");const i=z.findOne(`[data-bs-slide-to="${t}"]`,this._indicatorsElement);i&&(i.classList.add(yt),i.setAttribute("aria-current","true"))}_updateInterval(){const t=this._activeElement||this._getActive();if(!t)return;const e=Number.parseInt(t.getAttribute("data-bs-interval"),10);this._config.interval=e||this._config.defaultInterval}_slide(t,e=null){if(this._isSliding)return;const i=this._getActive(),n=t===at,s=e||b(this._getItems(),i,n,this._config.wrap);if(s===i)return;const o=this._getItemIndex(s),r=e=>N.trigger(this._element,e,{relatedTarget:s,direction:this._orderToDirection(t),from:this._getItemIndex(i),to:o});if(r(dt).defaultPrevented)return;if(!i||!s)return;const a=Boolean(this._interval);this.pause(),this._isSliding=!0,this._setActiveIndicatorElement(o),this._activeElement=s;const l=n?"carousel-item-start":"carousel-item-end",c=n?"carousel-item-next":"carousel-item-prev";s.classList.add(c),d(s),i.classList.add(l),s.classList.add(l),this._queueCallback((()=>{s.classList.remove(l,c),s.classList.add(yt),i.classList.remove(yt,c,l),this._isSliding=!1,r(ut)}),i,this._isAnimated()),a&&this.cycle()}_isAnimated(){return this._element.classList.contains("slide")}_getActive(){return z.findOne(Et,this._element)}_getItems(){return z.find(At,this._element)}_clearInterval(){this._interval&&(clearInterval(this._interval),this._interval=null)}_directionToOrder(t){return p()?t===ct?lt:at:t===ct?at:lt}_orderToDirection(t){return p()?t===lt?ct:ht:t===lt?ht:ct}static jQueryInterface(t){return this.each((function(){const e=xt.getOrCreateInstance(this,t);if("number"!=typeof t){if("string"==typeof t){if(void 0===e[t]||t.startsWith("_")||"constructor"===t)throw new TypeError(`No method named "${t}"`);e[t]()}}else e.to(t)}))}}N.on(document,bt,"[data-bs-slide], [data-bs-slide-to]",(function(t){const e=z.getElementFromSelector(this);if(!e||!e.classList.contains(vt))return;t.preventDefault();const i=xt.getOrCreateInstance(e),n=this.getAttribute("data-bs-slide-to");return n?(i.to(n),void i._maybeEnableCycle()):"next"===F.getDataAttribute(this,"slide")?(i.next(),void i._maybeEnableCycle()):(i.prev(),void i._maybeEnableCycle())})),N.on(window,_t,(()=>{const t=z.find('[data-bs-ride="carousel"]');for(const e of t)xt.getOrCreateInstance(e)})),m(xt);const kt=".bs.collapse",Lt=`show${kt}`,St=`shown${kt}`,Dt=`hide${kt}`,$t=`hidden${kt}`,It=`click${kt}.data-api`,Nt="show",Pt="collapse",Mt="collapsing",jt=`:scope .${Pt} .${Pt}`,Ft='[data-bs-toggle="collapse"]',Ht={parent:null,toggle:!0},Wt={parent:"(null|element)",toggle:"boolean"};class Bt extends W{constructor(t,e){super(t,e),this._isTransitioning=!1,this._triggerArray=[];const i=z.find(Ft);for(const t of i){const e=z.getSelectorFromElement(t),i=z.find(e).filter((t=>t===this._element));null!==e&&i.length&&this._triggerArray.push(t)}this._initializeChildren(),this._config.parent||this._addAriaAndCollapsedClass(this._triggerArray,this._isShown()),this._config.toggle&&this.toggle()}static get Default(){return Ht}static get DefaultType(){return Wt}static get NAME(){return"collapse"}toggle(){this._isShown()?this.hide():this.show()}show(){if(this._isTransitioning||this._isShown())return;let t=[];if(this._config.parent&&(t=this._getFirstLevelChildren(".collapse.show, .collapse.collapsing").filter((t=>t!==this._element)).map((t=>Bt.getOrCreateInstance(t,{toggle:!1})))),t.length&&t[0]._isTransitioning)return;if(N.trigger(this._element,Lt).defaultPrevented)return;for(const e of t)e.hide();const e=this._getDimension();this._element.classList.remove(Pt),this._element.classList.add(Mt),this._element.style[e]=0,this._addAriaAndCollapsedClass(this._triggerArray,!0),this._isTransitioning=!0;const i=`scroll${e[0].toUpperCase()+e.slice(1)}`;this._queueCallback((()=>{this._isTransitioning=!1,this._element.classList.remove(Mt),this._element.classList.add(Pt,Nt),this._element.style[e]="",N.trigger(this._element,St)}),this._element,!0),this._element.style[e]=`${this._element[i]}px`}hide(){if(this._isTransitioning||!this._isShown())return;if(N.trigger(this._element,Dt).defaultPrevented)return;const t=this._getDimension();this._element.style[t]=`${this._element.getBoundingClientRect()[t]}px`,d(this._element),this._element.classList.add(Mt),this._element.classList.remove(Pt,Nt);for(const t of this._triggerArray){const e=z.getElementFromSelector(t);e&&!this._isShown(e)&&this._addAriaAndCollapsedClass([t],!1)}this._isTransitioning=!0,this._element.style[t]="",this._queueCallback((()=>{this._isTransitioning=!1,this._element.classList.remove(Mt),this._element.classList.add(Pt),N.trigger(this._element,$t)}),this._element,!0)}_isShown(t=this._element){return t.classList.contains(Nt)}_configAfterMerge(t){return t.toggle=Boolean(t.toggle),t.parent=r(t.parent),t}_getDimension(){return this._element.classList.contains("collapse-horizontal")?"width":"height"}_initializeChildren(){if(!this._config.parent)return;const t=this._getFirstLevelChildren(Ft);for(const e of t){const t=z.getElementFromSelector(e);t&&this._addAriaAndCollapsedClass([e],this._isShown(t))}}_getFirstLevelChildren(t){const e=z.find(jt,this._config.parent);return z.find(t,this._config.parent).filter((t=>!e.includes(t)))}_addAriaAndCollapsedClass(t,e){if(t.length)for(const i of t)i.classList.toggle("collapsed",!e),i.setAttribute("aria-expanded",e)}static jQueryInterface(t){const e={};return"string"==typeof t&&/show|hide/.test(t)&&(e.toggle=!1),this.each((function(){const i=Bt.getOrCreateInstance(this,e);if("string"==typeof t){if(void 0===i[t])throw new TypeError(`No method named "${t}"`);i[t]()}}))}}N.on(document,It,Ft,(function(t){("A"===t.target.tagName||t.delegateTarget&&"A"===t.delegateTarget.tagName)&&t.preventDefault();for(const t of z.getMultipleElementsFromSelector(this))Bt.getOrCreateInstance(t,{toggle:!1}).toggle()})),m(Bt);var zt="top",Rt="bottom",qt="right",Vt="left",Kt="auto",Qt=[zt,Rt,qt,Vt],Xt="start",Yt="end",Ut="clippingParents",Gt="viewport",Jt="popper",Zt="reference",te=Qt.reduce((function(t,e){return t.concat([e+"-"+Xt,e+"-"+Yt])}),[]),ee=[].concat(Qt,[Kt]).reduce((function(t,e){return t.concat([e,e+"-"+Xt,e+"-"+Yt])}),[]),ie="beforeRead",ne="read",se="afterRead",oe="beforeMain",re="main",ae="afterMain",le="beforeWrite",ce="write",he="afterWrite",de=[ie,ne,se,oe,re,ae,le,ce,he];function ue(t){return t?(t.nodeName||"").toLowerCase():null}function fe(t){if(null==t)return window;if("[object Window]"!==t.toString()){var e=t.ownerDocument;return e&&e.defaultView||window}return t}function pe(t){return t instanceof fe(t).Element||t instanceof Element}function me(t){return t instanceof fe(t).HTMLElement||t instanceof HTMLElement}function ge(t){return"undefined"!=typeof ShadowRoot&&(t instanceof fe(t).ShadowRoot||t instanceof ShadowRoot)}const _e={name:"applyStyles",enabled:!0,phase:"write",fn:function(t){var e=t.state;Object.keys(e.elements).forEach((function(t){var i=e.styles[t]||{},n=e.attributes[t]||{},s=e.elements[t];me(s)&&ue(s)&&(Object.assign(s.style,i),Object.keys(n).forEach((function(t){var e=n[t];!1===e?s.removeAttribute(t):s.setAttribute(t,!0===e?"":e)})))}))},effect:function(t){var e=t.state,i={popper:{position:e.options.strategy,left:"0",top:"0",margin:"0"},arrow:{position:"absolute"},reference:{}};return Object.assign(e.elements.popper.style,i.popper),e.styles=i,e.elements.arrow&&Object.assign(e.elements.arrow.style,i.arrow),function(){Object.keys(e.elements).forEach((function(t){var n=e.elements[t],s=e.attributes[t]||{},o=Object.keys(e.styles.hasOwnProperty(t)?e.styles[t]:i[t]).reduce((function(t,e){return t[e]="",t}),{});me(n)&&ue(n)&&(Object.assign(n.style,o),Object.keys(s).forEach((function(t){n.removeAttribute(t)})))}))}},requires:["computeStyles"]};function be(t){return t.split("-")[0]}var ve=Math.max,ye=Math.min,we=Math.round;function Ae(){var t=navigator.userAgentData;return null!=t&&t.brands&&Array.isArray(t.brands)?t.brands.map((function(t){return t.brand+"/"+t.version})).join(" "):navigator.userAgent}function Ee(){return!/^((?!chrome|android).)*safari/i.test(Ae())}function Te(t,e,i){void 0===e&&(e=!1),void 0===i&&(i=!1);var n=t.getBoundingClientRect(),s=1,o=1;e&&me(t)&&(s=t.offsetWidth>0&&we(n.width)/t.offsetWidth||1,o=t.offsetHeight>0&&we(n.height)/t.offsetHeight||1);var r=(pe(t)?fe(t):window).visualViewport,a=!Ee()&&i,l=(n.left+(a&&r?r.offsetLeft:0))/s,c=(n.top+(a&&r?r.offsetTop:0))/o,h=n.width/s,d=n.height/o;return{width:h,height:d,top:c,right:l+h,bottom:c+d,left:l,x:l,y:c}}function Ce(t){var e=Te(t),i=t.offsetWidth,n=t.offsetHeight;return Math.abs(e.width-i)<=1&&(i=e.width),Math.abs(e.height-n)<=1&&(n=e.height),{x:t.offsetLeft,y:t.offsetTop,width:i,height:n}}function Oe(t,e){var i=e.getRootNode&&e.getRootNode();if(t.contains(e))return!0;if(i&&ge(i)){var n=e;do{if(n&&t.isSameNode(n))return!0;n=n.parentNode||n.host}while(n)}return!1}function xe(t){return fe(t).getComputedStyle(t)}function ke(t){return["table","td","th"].indexOf(ue(t))>=0}function Le(t){return((pe(t)?t.ownerDocument:t.document)||window.document).documentElement}function Se(t){return"html"===ue(t)?t:t.assignedSlot||t.parentNode||(ge(t)?t.host:null)||Le(t)}function De(t){return me(t)&&"fixed"!==xe(t).position?t.offsetParent:null}function $e(t){for(var e=fe(t),i=De(t);i&&ke(i)&&"static"===xe(i).position;)i=De(i);return i&&("html"===ue(i)||"body"===ue(i)&&"static"===xe(i).position)?e:i||function(t){var e=/firefox/i.test(Ae());if(/Trident/i.test(Ae())&&me(t)&&"fixed"===xe(t).position)return null;var i=Se(t);for(ge(i)&&(i=i.host);me(i)&&["html","body"].indexOf(ue(i))<0;){var n=xe(i);if("none"!==n.transform||"none"!==n.perspective||"paint"===n.contain||-1!==["transform","perspective"].indexOf(n.willChange)||e&&"filter"===n.willChange||e&&n.filter&&"none"!==n.filter)return i;i=i.parentNode}return null}(t)||e}function Ie(t){return["top","bottom"].indexOf(t)>=0?"x":"y"}function Ne(t,e,i){return ve(t,ye(e,i))}function Pe(t){return Object.assign({},{top:0,right:0,bottom:0,left:0},t)}function Me(t,e){return e.reduce((function(e,i){return e[i]=t,e}),{})}const je={name:"arrow",enabled:!0,phase:"main",fn:function(t){var e,i=t.state,n=t.name,s=t.options,o=i.elements.arrow,r=i.modifiersData.popperOffsets,a=be(i.placement),l=Ie(a),c=[Vt,qt].indexOf(a)>=0?"height":"width";if(o&&r){var h=function(t,e){return Pe("number"!=typeof(t="function"==typeof t?t(Object.assign({},e.rects,{placement:e.placement})):t)?t:Me(t,Qt))}(s.padding,i),d=Ce(o),u="y"===l?zt:Vt,f="y"===l?Rt:qt,p=i.rects.reference[c]+i.rects.reference[l]-r[l]-i.rects.popper[c],m=r[l]-i.rects.reference[l],g=$e(o),_=g?"y"===l?g.clientHeight||0:g.clientWidth||0:0,b=p/2-m/2,v=h[u],y=_-d[c]-h[f],w=_/2-d[c]/2+b,A=Ne(v,w,y),E=l;i.modifiersData[n]=((e={})[E]=A,e.centerOffset=A-w,e)}},effect:function(t){var e=t.state,i=t.options.element,n=void 0===i?"[data-popper-arrow]":i;null!=n&&("string"!=typeof n||(n=e.elements.popper.querySelector(n)))&&Oe(e.elements.popper,n)&&(e.elements.arrow=n)},requires:["popperOffsets"],requiresIfExists:["preventOverflow"]};function Fe(t){return t.split("-")[1]}var He={top:"auto",right:"auto",bottom:"auto",left:"auto"};function We(t){var e,i=t.popper,n=t.popperRect,s=t.placement,o=t.variation,r=t.offsets,a=t.position,l=t.gpuAcceleration,c=t.adaptive,h=t.roundOffsets,d=t.isFixed,u=r.x,f=void 0===u?0:u,p=r.y,m=void 0===p?0:p,g="function"==typeof h?h({x:f,y:m}):{x:f,y:m};f=g.x,m=g.y;var _=r.hasOwnProperty("x"),b=r.hasOwnProperty("y"),v=Vt,y=zt,w=window;if(c){var A=$e(i),E="clientHeight",T="clientWidth";A===fe(i)&&"static"!==xe(A=Le(i)).position&&"absolute"===a&&(E="scrollHeight",T="scrollWidth"),(s===zt||(s===Vt||s===qt)&&o===Yt)&&(y=Rt,m-=(d&&A===w&&w.visualViewport?w.visualViewport.height:A[E])-n.height,m*=l?1:-1),s!==Vt&&(s!==zt&&s!==Rt||o!==Yt)||(v=qt,f-=(d&&A===w&&w.visualViewport?w.visualViewport.width:A[T])-n.width,f*=l?1:-1)}var C,O=Object.assign({position:a},c&&He),x=!0===h?function(t,e){var i=t.x,n=t.y,s=e.devicePixelRatio||1;return{x:we(i*s)/s||0,y:we(n*s)/s||0}}({x:f,y:m},fe(i)):{x:f,y:m};return f=x.x,m=x.y,l?Object.assign({},O,((C={})[y]=b?"0":"",C[v]=_?"0":"",C.transform=(w.devicePixelRatio||1)<=1?"translate("+f+"px, "+m+"px)":"translate3d("+f+"px, "+m+"px, 0)",C)):Object.assign({},O,((e={})[y]=b?m+"px":"",e[v]=_?f+"px":"",e.transform="",e))}const Be={name:"computeStyles",enabled:!0,phase:"beforeWrite",fn:function(t){var e=t.state,i=t.options,n=i.gpuAcceleration,s=void 0===n||n,o=i.adaptive,r=void 0===o||o,a=i.roundOffsets,l=void 0===a||a,c={placement:be(e.placement),variation:Fe(e.placement),popper:e.elements.popper,popperRect:e.rects.popper,gpuAcceleration:s,isFixed:"fixed"===e.options.strategy};null!=e.modifiersData.popperOffsets&&(e.styles.popper=Object.assign({},e.styles.popper,We(Object.assign({},c,{offsets:e.modifiersData.popperOffsets,position:e.options.strategy,adaptive:r,roundOffsets:l})))),null!=e.modifiersData.arrow&&(e.styles.arrow=Object.assign({},e.styles.arrow,We(Object.assign({},c,{offsets:e.modifiersData.arrow,position:"absolute",adaptive:!1,roundOffsets:l})))),e.attributes.popper=Object.assign({},e.attributes.popper,{"data-popper-placement":e.placement})},data:{}};var ze={passive:!0};const Re={name:"eventListeners",enabled:!0,phase:"write",fn:function(){},effect:function(t){var e=t.state,i=t.instance,n=t.options,s=n.scroll,o=void 0===s||s,r=n.resize,a=void 0===r||r,l=fe(e.elements.popper),c=[].concat(e.scrollParents.reference,e.scrollParents.popper);return o&&c.forEach((function(t){t.addEventListener("scroll",i.update,ze)})),a&&l.addEventListener("resize",i.update,ze),function(){o&&c.forEach((function(t){t.removeEventListener("scroll",i.update,ze)})),a&&l.removeEventListener("resize",i.update,ze)}},data:{}};var qe={left:"right",right:"left",bottom:"top",top:"bottom"};function Ve(t){return t.replace(/left|right|bottom|top/g,(function(t){return qe[t]}))}var Ke={start:"end",end:"start"};function Qe(t){return t.replace(/start|end/g,(function(t){return Ke[t]}))}function Xe(t){var e=fe(t);return{scrollLeft:e.pageXOffset,scrollTop:e.pageYOffset}}function Ye(t){return Te(Le(t)).left+Xe(t).scrollLeft}function Ue(t){var e=xe(t),i=e.overflow,n=e.overflowX,s=e.overflowY;return/auto|scroll|overlay|hidden/.test(i+s+n)}function Ge(t){return["html","body","#document"].indexOf(ue(t))>=0?t.ownerDocument.body:me(t)&&Ue(t)?t:Ge(Se(t))}function Je(t,e){var i;void 0===e&&(e=[]);var n=Ge(t),s=n===(null==(i=t.ownerDocument)?void 0:i.body),o=fe(n),r=s?[o].concat(o.visualViewport||[],Ue(n)?n:[]):n,a=e.concat(r);return s?a:a.concat(Je(Se(r)))}function Ze(t){return Object.assign({},t,{left:t.x,top:t.y,right:t.x+t.width,bottom:t.y+t.height})}function ti(t,e,i){return e===Gt?Ze(function(t,e){var i=fe(t),n=Le(t),s=i.visualViewport,o=n.clientWidth,r=n.clientHeight,a=0,l=0;if(s){o=s.width,r=s.height;var c=Ee();(c||!c&&"fixed"===e)&&(a=s.offsetLeft,l=s.offsetTop)}return{width:o,height:r,x:a+Ye(t),y:l}}(t,i)):pe(e)?function(t,e){var i=Te(t,!1,"fixed"===e);return i.top=i.top+t.clientTop,i.left=i.left+t.clientLeft,i.bottom=i.top+t.clientHeight,i.right=i.left+t.clientWidth,i.width=t.clientWidth,i.height=t.clientHeight,i.x=i.left,i.y=i.top,i}(e,i):Ze(function(t){var e,i=Le(t),n=Xe(t),s=null==(e=t.ownerDocument)?void 0:e.body,o=ve(i.scrollWidth,i.clientWidth,s?s.scrollWidth:0,s?s.clientWidth:0),r=ve(i.scrollHeight,i.clientHeight,s?s.scrollHeight:0,s?s.clientHeight:0),a=-n.scrollLeft+Ye(t),l=-n.scrollTop;return"rtl"===xe(s||i).direction&&(a+=ve(i.clientWidth,s?s.clientWidth:0)-o),{width:o,height:r,x:a,y:l}}(Le(t)))}function ei(t){var e,i=t.reference,n=t.element,s=t.placement,o=s?be(s):null,r=s?Fe(s):null,a=i.x+i.width/2-n.width/2,l=i.y+i.height/2-n.height/2;switch(o){case zt:e={x:a,y:i.y-n.height};break;case Rt:e={x:a,y:i.y+i.height};break;case qt:e={x:i.x+i.width,y:l};break;case Vt:e={x:i.x-n.width,y:l};break;default:e={x:i.x,y:i.y}}var c=o?Ie(o):null;if(null!=c){var h="y"===c?"height":"width";switch(r){case Xt:e[c]=e[c]-(i[h]/2-n[h]/2);break;case Yt:e[c]=e[c]+(i[h]/2-n[h]/2)}}return e}function ii(t,e){void 0===e&&(e={});var i=e,n=i.placement,s=void 0===n?t.placement:n,o=i.strategy,r=void 0===o?t.strategy:o,a=i.boundary,l=void 0===a?Ut:a,c=i.rootBoundary,h=void 0===c?Gt:c,d=i.elementContext,u=void 0===d?Jt:d,f=i.altBoundary,p=void 0!==f&&f,m=i.padding,g=void 0===m?0:m,_=Pe("number"!=typeof g?g:Me(g,Qt)),b=u===Jt?Zt:Jt,v=t.rects.popper,y=t.elements[p?b:u],w=function(t,e,i,n){var s="clippingParents"===e?function(t){var e=Je(Se(t)),i=["absolute","fixed"].indexOf(xe(t).position)>=0&&me(t)?$e(t):t;return pe(i)?e.filter((function(t){return pe(t)&&Oe(t,i)&&"body"!==ue(t)})):[]}(t):[].concat(e),o=[].concat(s,[i]),r=o[0],a=o.reduce((function(e,i){var s=ti(t,i,n);return e.top=ve(s.top,e.top),e.right=ye(s.right,e.right),e.bottom=ye(s.bottom,e.bottom),e.left=ve(s.left,e.left),e}),ti(t,r,n));return a.width=a.right-a.left,a.height=a.bottom-a.top,a.x=a.left,a.y=a.top,a}(pe(y)?y:y.contextElement||Le(t.elements.popper),l,h,r),A=Te(t.elements.reference),E=ei({reference:A,element:v,strategy:"absolute",placement:s}),T=Ze(Object.assign({},v,E)),C=u===Jt?T:A,O={top:w.top-C.top+_.top,bottom:C.bottom-w.bottom+_.bottom,left:w.left-C.left+_.left,right:C.right-w.right+_.right},x=t.modifiersData.offset;if(u===Jt&&x){var k=x[s];Object.keys(O).forEach((function(t){var e=[qt,Rt].indexOf(t)>=0?1:-1,i=[zt,Rt].indexOf(t)>=0?"y":"x";O[t]+=k[i]*e}))}return O}function ni(t,e){void 0===e&&(e={});var i=e,n=i.placement,s=i.boundary,o=i.rootBoundary,r=i.padding,a=i.flipVariations,l=i.allowedAutoPlacements,c=void 0===l?ee:l,h=Fe(n),d=h?a?te:te.filter((function(t){return Fe(t)===h})):Qt,u=d.filter((function(t){return c.indexOf(t)>=0}));0===u.length&&(u=d);var f=u.reduce((function(e,i){return e[i]=ii(t,{placement:i,boundary:s,rootBoundary:o,padding:r})[be(i)],e}),{});return Object.keys(f).sort((function(t,e){return f[t]-f[e]}))}const si={name:"flip",enabled:!0,phase:"main",fn:function(t){var e=t.state,i=t.options,n=t.name;if(!e.modifiersData[n]._skip){for(var s=i.mainAxis,o=void 0===s||s,r=i.altAxis,a=void 0===r||r,l=i.fallbackPlacements,c=i.padding,h=i.boundary,d=i.rootBoundary,u=i.altBoundary,f=i.flipVariations,p=void 0===f||f,m=i.allowedAutoPlacements,g=e.options.placement,_=be(g),b=l||(_!==g&&p?function(t){if(be(t)===Kt)return[];var e=Ve(t);return[Qe(t),e,Qe(e)]}(g):[Ve(g)]),v=[g].concat(b).reduce((function(t,i){return t.concat(be(i)===Kt?ni(e,{placement:i,boundary:h,rootBoundary:d,padding:c,flipVariations:p,allowedAutoPlacements:m}):i)}),[]),y=e.rects.reference,w=e.rects.popper,A=new Map,E=!0,T=v[0],C=0;C=0,S=L?"width":"height",D=ii(e,{placement:O,boundary:h,rootBoundary:d,altBoundary:u,padding:c}),$=L?k?qt:Vt:k?Rt:zt;y[S]>w[S]&&($=Ve($));var I=Ve($),N=[];if(o&&N.push(D[x]<=0),a&&N.push(D[$]<=0,D[I]<=0),N.every((function(t){return t}))){T=O,E=!1;break}A.set(O,N)}if(E)for(var P=function(t){var e=v.find((function(e){var i=A.get(e);if(i)return i.slice(0,t).every((function(t){return t}))}));if(e)return T=e,"break"},M=p?3:1;M>0&&"break"!==P(M);M--);e.placement!==T&&(e.modifiersData[n]._skip=!0,e.placement=T,e.reset=!0)}},requiresIfExists:["offset"],data:{_skip:!1}};function oi(t,e,i){return void 0===i&&(i={x:0,y:0}),{top:t.top-e.height-i.y,right:t.right-e.width+i.x,bottom:t.bottom-e.height+i.y,left:t.left-e.width-i.x}}function ri(t){return[zt,qt,Rt,Vt].some((function(e){return t[e]>=0}))}const ai={name:"hide",enabled:!0,phase:"main",requiresIfExists:["preventOverflow"],fn:function(t){var e=t.state,i=t.name,n=e.rects.reference,s=e.rects.popper,o=e.modifiersData.preventOverflow,r=ii(e,{elementContext:"reference"}),a=ii(e,{altBoundary:!0}),l=oi(r,n),c=oi(a,s,o),h=ri(l),d=ri(c);e.modifiersData[i]={referenceClippingOffsets:l,popperEscapeOffsets:c,isReferenceHidden:h,hasPopperEscaped:d},e.attributes.popper=Object.assign({},e.attributes.popper,{"data-popper-reference-hidden":h,"data-popper-escaped":d})}},li={name:"offset",enabled:!0,phase:"main",requires:["popperOffsets"],fn:function(t){var e=t.state,i=t.options,n=t.name,s=i.offset,o=void 0===s?[0,0]:s,r=ee.reduce((function(t,i){return t[i]=function(t,e,i){var n=be(t),s=[Vt,zt].indexOf(n)>=0?-1:1,o="function"==typeof i?i(Object.assign({},e,{placement:t})):i,r=o[0],a=o[1];return r=r||0,a=(a||0)*s,[Vt,qt].indexOf(n)>=0?{x:a,y:r}:{x:r,y:a}}(i,e.rects,o),t}),{}),a=r[e.placement],l=a.x,c=a.y;null!=e.modifiersData.popperOffsets&&(e.modifiersData.popperOffsets.x+=l,e.modifiersData.popperOffsets.y+=c),e.modifiersData[n]=r}},ci={name:"popperOffsets",enabled:!0,phase:"read",fn:function(t){var e=t.state,i=t.name;e.modifiersData[i]=ei({reference:e.rects.reference,element:e.rects.popper,strategy:"absolute",placement:e.placement})},data:{}},hi={name:"preventOverflow",enabled:!0,phase:"main",fn:function(t){var e=t.state,i=t.options,n=t.name,s=i.mainAxis,o=void 0===s||s,r=i.altAxis,a=void 0!==r&&r,l=i.boundary,c=i.rootBoundary,h=i.altBoundary,d=i.padding,u=i.tether,f=void 0===u||u,p=i.tetherOffset,m=void 0===p?0:p,g=ii(e,{boundary:l,rootBoundary:c,padding:d,altBoundary:h}),_=be(e.placement),b=Fe(e.placement),v=!b,y=Ie(_),w="x"===y?"y":"x",A=e.modifiersData.popperOffsets,E=e.rects.reference,T=e.rects.popper,C="function"==typeof m?m(Object.assign({},e.rects,{placement:e.placement})):m,O="number"==typeof C?{mainAxis:C,altAxis:C}:Object.assign({mainAxis:0,altAxis:0},C),x=e.modifiersData.offset?e.modifiersData.offset[e.placement]:null,k={x:0,y:0};if(A){if(o){var L,S="y"===y?zt:Vt,D="y"===y?Rt:qt,$="y"===y?"height":"width",I=A[y],N=I+g[S],P=I-g[D],M=f?-T[$]/2:0,j=b===Xt?E[$]:T[$],F=b===Xt?-T[$]:-E[$],H=e.elements.arrow,W=f&&H?Ce(H):{width:0,height:0},B=e.modifiersData["arrow#persistent"]?e.modifiersData["arrow#persistent"].padding:{top:0,right:0,bottom:0,left:0},z=B[S],R=B[D],q=Ne(0,E[$],W[$]),V=v?E[$]/2-M-q-z-O.mainAxis:j-q-z-O.mainAxis,K=v?-E[$]/2+M+q+R+O.mainAxis:F+q+R+O.mainAxis,Q=e.elements.arrow&&$e(e.elements.arrow),X=Q?"y"===y?Q.clientTop||0:Q.clientLeft||0:0,Y=null!=(L=null==x?void 0:x[y])?L:0,U=I+K-Y,G=Ne(f?ye(N,I+V-Y-X):N,I,f?ve(P,U):P);A[y]=G,k[y]=G-I}if(a){var J,Z="x"===y?zt:Vt,tt="x"===y?Rt:qt,et=A[w],it="y"===w?"height":"width",nt=et+g[Z],st=et-g[tt],ot=-1!==[zt,Vt].indexOf(_),rt=null!=(J=null==x?void 0:x[w])?J:0,at=ot?nt:et-E[it]-T[it]-rt+O.altAxis,lt=ot?et+E[it]+T[it]-rt-O.altAxis:st,ct=f&&ot?function(t,e,i){var n=Ne(t,e,i);return n>i?i:n}(at,et,lt):Ne(f?at:nt,et,f?lt:st);A[w]=ct,k[w]=ct-et}e.modifiersData[n]=k}},requiresIfExists:["offset"]};function di(t,e,i){void 0===i&&(i=!1);var n,s,o=me(e),r=me(e)&&function(t){var e=t.getBoundingClientRect(),i=we(e.width)/t.offsetWidth||1,n=we(e.height)/t.offsetHeight||1;return 1!==i||1!==n}(e),a=Le(e),l=Te(t,r,i),c={scrollLeft:0,scrollTop:0},h={x:0,y:0};return(o||!o&&!i)&&(("body"!==ue(e)||Ue(a))&&(c=(n=e)!==fe(n)&&me(n)?{scrollLeft:(s=n).scrollLeft,scrollTop:s.scrollTop}:Xe(n)),me(e)?((h=Te(e,!0)).x+=e.clientLeft,h.y+=e.clientTop):a&&(h.x=Ye(a))),{x:l.left+c.scrollLeft-h.x,y:l.top+c.scrollTop-h.y,width:l.width,height:l.height}}function ui(t){var e=new Map,i=new Set,n=[];function s(t){i.add(t.name),[].concat(t.requires||[],t.requiresIfExists||[]).forEach((function(t){if(!i.has(t)){var n=e.get(t);n&&s(n)}})),n.push(t)}return t.forEach((function(t){e.set(t.name,t)})),t.forEach((function(t){i.has(t.name)||s(t)})),n}var fi={placement:"bottom",modifiers:[],strategy:"absolute"};function pi(){for(var t=arguments.length,e=new Array(t),i=0;iNumber.parseInt(t,10))):"function"==typeof t?e=>t(e,this._element):t}_getPopperConfig(){const t={placement:this._getPlacement(),modifiers:[{name:"preventOverflow",options:{boundary:this._config.boundary}},{name:"offset",options:{offset:this._getOffset()}}]};return(this._inNavbar||"static"===this._config.display)&&(F.setDataAttribute(this._menu,"popper","static"),t.modifiers=[{name:"applyStyles",enabled:!1}]),{...t,...g(this._config.popperConfig,[t])}}_selectMenuItem({key:t,target:e}){const i=z.find(".dropdown-menu .dropdown-item:not(.disabled):not(:disabled)",this._menu).filter((t=>a(t)));i.length&&b(i,e,t===Ti,!i.includes(e)).focus()}static jQueryInterface(t){return this.each((function(){const e=qi.getOrCreateInstance(this,t);if("string"==typeof t){if(void 0===e[t])throw new TypeError(`No method named "${t}"`);e[t]()}}))}static clearMenus(t){if(2===t.button||"keyup"===t.type&&"Tab"!==t.key)return;const e=z.find(Ni);for(const i of e){const e=qi.getInstance(i);if(!e||!1===e._config.autoClose)continue;const n=t.composedPath(),s=n.includes(e._menu);if(n.includes(e._element)||"inside"===e._config.autoClose&&!s||"outside"===e._config.autoClose&&s)continue;if(e._menu.contains(t.target)&&("keyup"===t.type&&"Tab"===t.key||/input|select|option|textarea|form/i.test(t.target.tagName)))continue;const o={relatedTarget:e._element};"click"===t.type&&(o.clickEvent=t),e._completeHide(o)}}static dataApiKeydownHandler(t){const e=/input|textarea/i.test(t.target.tagName),i="Escape"===t.key,n=[Ei,Ti].includes(t.key);if(!n&&!i)return;if(e&&!i)return;t.preventDefault();const s=this.matches(Ii)?this:z.prev(this,Ii)[0]||z.next(this,Ii)[0]||z.findOne(Ii,t.delegateTarget.parentNode),o=qi.getOrCreateInstance(s);if(n)return t.stopPropagation(),o.show(),void o._selectMenuItem(t);o._isShown()&&(t.stopPropagation(),o.hide(),s.focus())}}N.on(document,Si,Ii,qi.dataApiKeydownHandler),N.on(document,Si,Pi,qi.dataApiKeydownHandler),N.on(document,Li,qi.clearMenus),N.on(document,Di,qi.clearMenus),N.on(document,Li,Ii,(function(t){t.preventDefault(),qi.getOrCreateInstance(this).toggle()})),m(qi);const Vi="backdrop",Ki="show",Qi=`mousedown.bs.${Vi}`,Xi={className:"modal-backdrop",clickCallback:null,isAnimated:!1,isVisible:!0,rootElement:"body"},Yi={className:"string",clickCallback:"(function|null)",isAnimated:"boolean",isVisible:"boolean",rootElement:"(element|string)"};class Ui extends H{constructor(t){super(),this._config=this._getConfig(t),this._isAppended=!1,this._element=null}static get Default(){return Xi}static get DefaultType(){return Yi}static get NAME(){return Vi}show(t){if(!this._config.isVisible)return void g(t);this._append();const e=this._getElement();this._config.isAnimated&&d(e),e.classList.add(Ki),this._emulateAnimation((()=>{g(t)}))}hide(t){this._config.isVisible?(this._getElement().classList.remove(Ki),this._emulateAnimation((()=>{this.dispose(),g(t)}))):g(t)}dispose(){this._isAppended&&(N.off(this._element,Qi),this._element.remove(),this._isAppended=!1)}_getElement(){if(!this._element){const t=document.createElement("div");t.className=this._config.className,this._config.isAnimated&&t.classList.add("fade"),this._element=t}return this._element}_configAfterMerge(t){return t.rootElement=r(t.rootElement),t}_append(){if(this._isAppended)return;const t=this._getElement();this._config.rootElement.append(t),N.on(t,Qi,(()=>{g(this._config.clickCallback)})),this._isAppended=!0}_emulateAnimation(t){_(t,this._getElement(),this._config.isAnimated)}}const Gi=".bs.focustrap",Ji=`focusin${Gi}`,Zi=`keydown.tab${Gi}`,tn="backward",en={autofocus:!0,trapElement:null},nn={autofocus:"boolean",trapElement:"element"};class sn extends H{constructor(t){super(),this._config=this._getConfig(t),this._isActive=!1,this._lastTabNavDirection=null}static get Default(){return en}static get DefaultType(){return nn}static get NAME(){return"focustrap"}activate(){this._isActive||(this._config.autofocus&&this._config.trapElement.focus(),N.off(document,Gi),N.on(document,Ji,(t=>this._handleFocusin(t))),N.on(document,Zi,(t=>this._handleKeydown(t))),this._isActive=!0)}deactivate(){this._isActive&&(this._isActive=!1,N.off(document,Gi))}_handleFocusin(t){const{trapElement:e}=this._config;if(t.target===document||t.target===e||e.contains(t.target))return;const i=z.focusableChildren(e);0===i.length?e.focus():this._lastTabNavDirection===tn?i[i.length-1].focus():i[0].focus()}_handleKeydown(t){"Tab"===t.key&&(this._lastTabNavDirection=t.shiftKey?tn:"forward")}}const on=".fixed-top, .fixed-bottom, .is-fixed, .sticky-top",rn=".sticky-top",an="padding-right",ln="margin-right";class cn{constructor(){this._element=document.body}getWidth(){const t=document.documentElement.clientWidth;return Math.abs(window.innerWidth-t)}hide(){const t=this.getWidth();this._disableOverFlow(),this._setElementAttributes(this._element,an,(e=>e+t)),this._setElementAttributes(on,an,(e=>e+t)),this._setElementAttributes(rn,ln,(e=>e-t))}reset(){this._resetElementAttributes(this._element,"overflow"),this._resetElementAttributes(this._element,an),this._resetElementAttributes(on,an),this._resetElementAttributes(rn,ln)}isOverflowing(){return this.getWidth()>0}_disableOverFlow(){this._saveInitialAttribute(this._element,"overflow"),this._element.style.overflow="hidden"}_setElementAttributes(t,e,i){const n=this.getWidth();this._applyManipulationCallback(t,(t=>{if(t!==this._element&&window.innerWidth>t.clientWidth+n)return;this._saveInitialAttribute(t,e);const s=window.getComputedStyle(t).getPropertyValue(e);t.style.setProperty(e,`${i(Number.parseFloat(s))}px`)}))}_saveInitialAttribute(t,e){const i=t.style.getPropertyValue(e);i&&F.setDataAttribute(t,e,i)}_resetElementAttributes(t,e){this._applyManipulationCallback(t,(t=>{const i=F.getDataAttribute(t,e);null!==i?(F.removeDataAttribute(t,e),t.style.setProperty(e,i)):t.style.removeProperty(e)}))}_applyManipulationCallback(t,e){if(o(t))e(t);else for(const i of z.find(t,this._element))e(i)}}const hn=".bs.modal",dn=`hide${hn}`,un=`hidePrevented${hn}`,fn=`hidden${hn}`,pn=`show${hn}`,mn=`shown${hn}`,gn=`resize${hn}`,_n=`click.dismiss${hn}`,bn=`mousedown.dismiss${hn}`,vn=`keydown.dismiss${hn}`,yn=`click${hn}.data-api`,wn="modal-open",An="show",En="modal-static",Tn={backdrop:!0,focus:!0,keyboard:!0},Cn={backdrop:"(boolean|string)",focus:"boolean",keyboard:"boolean"};class On extends W{constructor(t,e){super(t,e),this._dialog=z.findOne(".modal-dialog",this._element),this._backdrop=this._initializeBackDrop(),this._focustrap=this._initializeFocusTrap(),this._isShown=!1,this._isTransitioning=!1,this._scrollBar=new cn,this._addEventListeners()}static get Default(){return Tn}static get DefaultType(){return Cn}static get NAME(){return"modal"}toggle(t){return this._isShown?this.hide():this.show(t)}show(t){this._isShown||this._isTransitioning||N.trigger(this._element,pn,{relatedTarget:t}).defaultPrevented||(this._isShown=!0,this._isTransitioning=!0,this._scrollBar.hide(),document.body.classList.add(wn),this._adjustDialog(),this._backdrop.show((()=>this._showElement(t))))}hide(){this._isShown&&!this._isTransitioning&&(N.trigger(this._element,dn).defaultPrevented||(this._isShown=!1,this._isTransitioning=!0,this._focustrap.deactivate(),this._element.classList.remove(An),this._queueCallback((()=>this._hideModal()),this._element,this._isAnimated())))}dispose(){N.off(window,hn),N.off(this._dialog,hn),this._backdrop.dispose(),this._focustrap.deactivate(),super.dispose()}handleUpdate(){this._adjustDialog()}_initializeBackDrop(){return new Ui({isVisible:Boolean(this._config.backdrop),isAnimated:this._isAnimated()})}_initializeFocusTrap(){return new sn({trapElement:this._element})}_showElement(t){document.body.contains(this._element)||document.body.append(this._element),this._element.style.display="block",this._element.removeAttribute("aria-hidden"),this._element.setAttribute("aria-modal",!0),this._element.setAttribute("role","dialog"),this._element.scrollTop=0;const e=z.findOne(".modal-body",this._dialog);e&&(e.scrollTop=0),d(this._element),this._element.classList.add(An),this._queueCallback((()=>{this._config.focus&&this._focustrap.activate(),this._isTransitioning=!1,N.trigger(this._element,mn,{relatedTarget:t})}),this._dialog,this._isAnimated())}_addEventListeners(){N.on(this._element,vn,(t=>{"Escape"===t.key&&(this._config.keyboard?this.hide():this._triggerBackdropTransition())})),N.on(window,gn,(()=>{this._isShown&&!this._isTransitioning&&this._adjustDialog()})),N.on(this._element,bn,(t=>{N.one(this._element,_n,(e=>{this._element===t.target&&this._element===e.target&&("static"!==this._config.backdrop?this._config.backdrop&&this.hide():this._triggerBackdropTransition())}))}))}_hideModal(){this._element.style.display="none",this._element.setAttribute("aria-hidden",!0),this._element.removeAttribute("aria-modal"),this._element.removeAttribute("role"),this._isTransitioning=!1,this._backdrop.hide((()=>{document.body.classList.remove(wn),this._resetAdjustments(),this._scrollBar.reset(),N.trigger(this._element,fn)}))}_isAnimated(){return this._element.classList.contains("fade")}_triggerBackdropTransition(){if(N.trigger(this._element,un).defaultPrevented)return;const t=this._element.scrollHeight>document.documentElement.clientHeight,e=this._element.style.overflowY;"hidden"===e||this._element.classList.contains(En)||(t||(this._element.style.overflowY="hidden"),this._element.classList.add(En),this._queueCallback((()=>{this._element.classList.remove(En),this._queueCallback((()=>{this._element.style.overflowY=e}),this._dialog)}),this._dialog),this._element.focus())}_adjustDialog(){const t=this._element.scrollHeight>document.documentElement.clientHeight,e=this._scrollBar.getWidth(),i=e>0;if(i&&!t){const t=p()?"paddingLeft":"paddingRight";this._element.style[t]=`${e}px`}if(!i&&t){const t=p()?"paddingRight":"paddingLeft";this._element.style[t]=`${e}px`}}_resetAdjustments(){this._element.style.paddingLeft="",this._element.style.paddingRight=""}static jQueryInterface(t,e){return this.each((function(){const i=On.getOrCreateInstance(this,t);if("string"==typeof t){if(void 0===i[t])throw new TypeError(`No method named "${t}"`);i[t](e)}}))}}N.on(document,yn,'[data-bs-toggle="modal"]',(function(t){const e=z.getElementFromSelector(this);["A","AREA"].includes(this.tagName)&&t.preventDefault(),N.one(e,pn,(t=>{t.defaultPrevented||N.one(e,fn,(()=>{a(this)&&this.focus()}))}));const i=z.findOne(".modal.show");i&&On.getInstance(i).hide(),On.getOrCreateInstance(e).toggle(this)})),R(On),m(On);const xn=".bs.offcanvas",kn=".data-api",Ln=`load${xn}${kn}`,Sn="show",Dn="showing",$n="hiding",In=".offcanvas.show",Nn=`show${xn}`,Pn=`shown${xn}`,Mn=`hide${xn}`,jn=`hidePrevented${xn}`,Fn=`hidden${xn}`,Hn=`resize${xn}`,Wn=`click${xn}${kn}`,Bn=`keydown.dismiss${xn}`,zn={backdrop:!0,keyboard:!0,scroll:!1},Rn={backdrop:"(boolean|string)",keyboard:"boolean",scroll:"boolean"};class qn extends W{constructor(t,e){super(t,e),this._isShown=!1,this._backdrop=this._initializeBackDrop(),this._focustrap=this._initializeFocusTrap(),this._addEventListeners()}static get Default(){return zn}static get DefaultType(){return Rn}static get NAME(){return"offcanvas"}toggle(t){return this._isShown?this.hide():this.show(t)}show(t){this._isShown||N.trigger(this._element,Nn,{relatedTarget:t}).defaultPrevented||(this._isShown=!0,this._backdrop.show(),this._config.scroll||(new cn).hide(),this._element.setAttribute("aria-modal",!0),this._element.setAttribute("role","dialog"),this._element.classList.add(Dn),this._queueCallback((()=>{this._config.scroll&&!this._config.backdrop||this._focustrap.activate(),this._element.classList.add(Sn),this._element.classList.remove(Dn),N.trigger(this._element,Pn,{relatedTarget:t})}),this._element,!0))}hide(){this._isShown&&(N.trigger(this._element,Mn).defaultPrevented||(this._focustrap.deactivate(),this._element.blur(),this._isShown=!1,this._element.classList.add($n),this._backdrop.hide(),this._queueCallback((()=>{this._element.classList.remove(Sn,$n),this._element.removeAttribute("aria-modal"),this._element.removeAttribute("role"),this._config.scroll||(new cn).reset(),N.trigger(this._element,Fn)}),this._element,!0)))}dispose(){this._backdrop.dispose(),this._focustrap.deactivate(),super.dispose()}_initializeBackDrop(){const t=Boolean(this._config.backdrop);return new Ui({className:"offcanvas-backdrop",isVisible:t,isAnimated:!0,rootElement:this._element.parentNode,clickCallback:t?()=>{"static"!==this._config.backdrop?this.hide():N.trigger(this._element,jn)}:null})}_initializeFocusTrap(){return new sn({trapElement:this._element})}_addEventListeners(){N.on(this._element,Bn,(t=>{"Escape"===t.key&&(this._config.keyboard?this.hide():N.trigger(this._element,jn))}))}static jQueryInterface(t){return this.each((function(){const e=qn.getOrCreateInstance(this,t);if("string"==typeof t){if(void 0===e[t]||t.startsWith("_")||"constructor"===t)throw new TypeError(`No method named "${t}"`);e[t](this)}}))}}N.on(document,Wn,'[data-bs-toggle="offcanvas"]',(function(t){const e=z.getElementFromSelector(this);if(["A","AREA"].includes(this.tagName)&&t.preventDefault(),l(this))return;N.one(e,Fn,(()=>{a(this)&&this.focus()}));const i=z.findOne(In);i&&i!==e&&qn.getInstance(i).hide(),qn.getOrCreateInstance(e).toggle(this)})),N.on(window,Ln,(()=>{for(const t of z.find(In))qn.getOrCreateInstance(t).show()})),N.on(window,Hn,(()=>{for(const t of z.find("[aria-modal][class*=show][class*=offcanvas-]"))"fixed"!==getComputedStyle(t).position&&qn.getOrCreateInstance(t).hide()})),R(qn),m(qn);const Vn={"*":["class","dir","id","lang","role",/^aria-[\w-]*$/i],a:["target","href","title","rel"],area:[],b:[],br:[],col:[],code:[],div:[],em:[],hr:[],h1:[],h2:[],h3:[],h4:[],h5:[],h6:[],i:[],img:["src","srcset","alt","title","width","height"],li:[],ol:[],p:[],pre:[],s:[],small:[],span:[],sub:[],sup:[],strong:[],u:[],ul:[]},Kn=new Set(["background","cite","href","itemtype","longdesc","poster","src","xlink:href"]),Qn=/^(?!javascript:)(?:[a-z0-9+.-]+:|[^&:/?#]*(?:[/?#]|$))/i,Xn=(t,e)=>{const i=t.nodeName.toLowerCase();return e.includes(i)?!Kn.has(i)||Boolean(Qn.test(t.nodeValue)):e.filter((t=>t instanceof RegExp)).some((t=>t.test(i)))},Yn={allowList:Vn,content:{},extraClass:"",html:!1,sanitize:!0,sanitizeFn:null,template:"
"},Un={allowList:"object",content:"object",extraClass:"(string|function)",html:"boolean",sanitize:"boolean",sanitizeFn:"(null|function)",template:"string"},Gn={entry:"(string|element|function|null)",selector:"(string|element)"};class Jn extends H{constructor(t){super(),this._config=this._getConfig(t)}static get Default(){return Yn}static get DefaultType(){return Un}static get NAME(){return"TemplateFactory"}getContent(){return Object.values(this._config.content).map((t=>this._resolvePossibleFunction(t))).filter(Boolean)}hasContent(){return this.getContent().length>0}changeContent(t){return this._checkContent(t),this._config.content={...this._config.content,...t},this}toHtml(){const t=document.createElement("div");t.innerHTML=this._maybeSanitize(this._config.template);for(const[e,i]of Object.entries(this._config.content))this._setContent(t,i,e);const e=t.children[0],i=this._resolvePossibleFunction(this._config.extraClass);return i&&e.classList.add(...i.split(" ")),e}_typeCheckConfig(t){super._typeCheckConfig(t),this._checkContent(t.content)}_checkContent(t){for(const[e,i]of Object.entries(t))super._typeCheckConfig({selector:e,entry:i},Gn)}_setContent(t,e,i){const n=z.findOne(i,t);n&&((e=this._resolvePossibleFunction(e))?o(e)?this._putElementInTemplate(r(e),n):this._config.html?n.innerHTML=this._maybeSanitize(e):n.textContent=e:n.remove())}_maybeSanitize(t){return this._config.sanitize?function(t,e,i){if(!t.length)return t;if(i&&"function"==typeof i)return i(t);const n=(new window.DOMParser).parseFromString(t,"text/html"),s=[].concat(...n.body.querySelectorAll("*"));for(const t of s){const i=t.nodeName.toLowerCase();if(!Object.keys(e).includes(i)){t.remove();continue}const n=[].concat(...t.attributes),s=[].concat(e["*"]||[],e[i]||[]);for(const e of n)Xn(e,s)||t.removeAttribute(e.nodeName)}return n.body.innerHTML}(t,this._config.allowList,this._config.sanitizeFn):t}_resolvePossibleFunction(t){return g(t,[this])}_putElementInTemplate(t,e){if(this._config.html)return e.innerHTML="",void e.append(t);e.textContent=t.textContent}}const Zn=new Set(["sanitize","allowList","sanitizeFn"]),ts="fade",es="show",is=".modal",ns="hide.bs.modal",ss="hover",os="focus",rs={AUTO:"auto",TOP:"top",RIGHT:p()?"left":"right",BOTTOM:"bottom",LEFT:p()?"right":"left"},as={allowList:Vn,animation:!0,boundary:"clippingParents",container:!1,customClass:"",delay:0,fallbackPlacements:["top","right","bottom","left"],html:!1,offset:[0,6],placement:"top",popperConfig:null,sanitize:!0,sanitizeFn:null,selector:!1,template:'',title:"",trigger:"hover focus"},ls={allowList:"object",animation:"boolean",boundary:"(string|element)",container:"(string|element|boolean)",customClass:"(string|function)",delay:"(number|object)",fallbackPlacements:"array",html:"boolean",offset:"(array|string|function)",placement:"(string|function)",popperConfig:"(null|object|function)",sanitize:"boolean",sanitizeFn:"(null|function)",selector:"(string|boolean)",template:"string",title:"(string|element|function)",trigger:"string"};class cs extends W{constructor(t,e){if(void 0===vi)throw new TypeError("Bootstrap's tooltips require Popper (https://popper.js.org)");super(t,e),this._isEnabled=!0,this._timeout=0,this._isHovered=null,this._activeTrigger={},this._popper=null,this._templateFactory=null,this._newContent=null,this.tip=null,this._setListeners(),this._config.selector||this._fixTitle()}static get Default(){return as}static get DefaultType(){return ls}static get NAME(){return"tooltip"}enable(){this._isEnabled=!0}disable(){this._isEnabled=!1}toggleEnabled(){this._isEnabled=!this._isEnabled}toggle(){this._isEnabled&&(this._activeTrigger.click=!this._activeTrigger.click,this._isShown()?this._leave():this._enter())}dispose(){clearTimeout(this._timeout),N.off(this._element.closest(is),ns,this._hideModalHandler),this._element.getAttribute("data-bs-original-title")&&this._element.setAttribute("title",this._element.getAttribute("data-bs-original-title")),this._disposePopper(),super.dispose()}show(){if("none"===this._element.style.display)throw new Error("Please use show on visible elements");if(!this._isWithContent()||!this._isEnabled)return;const t=N.trigger(this._element,this.constructor.eventName("show")),e=(c(this._element)||this._element.ownerDocument.documentElement).contains(this._element);if(t.defaultPrevented||!e)return;this._disposePopper();const i=this._getTipElement();this._element.setAttribute("aria-describedby",i.getAttribute("id"));const{container:n}=this._config;if(this._element.ownerDocument.documentElement.contains(this.tip)||(n.append(i),N.trigger(this._element,this.constructor.eventName("inserted"))),this._popper=this._createPopper(i),i.classList.add(es),"ontouchstart"in document.documentElement)for(const t of[].concat(...document.body.children))N.on(t,"mouseover",h);this._queueCallback((()=>{N.trigger(this._element,this.constructor.eventName("shown")),!1===this._isHovered&&this._leave(),this._isHovered=!1}),this.tip,this._isAnimated())}hide(){if(this._isShown()&&!N.trigger(this._element,this.constructor.eventName("hide")).defaultPrevented){if(this._getTipElement().classList.remove(es),"ontouchstart"in document.documentElement)for(const t of[].concat(...document.body.children))N.off(t,"mouseover",h);this._activeTrigger.click=!1,this._activeTrigger[os]=!1,this._activeTrigger[ss]=!1,this._isHovered=null,this._queueCallback((()=>{this._isWithActiveTrigger()||(this._isHovered||this._disposePopper(),this._element.removeAttribute("aria-describedby"),N.trigger(this._element,this.constructor.eventName("hidden")))}),this.tip,this._isAnimated())}}update(){this._popper&&this._popper.update()}_isWithContent(){return Boolean(this._getTitle())}_getTipElement(){return this.tip||(this.tip=this._createTipElement(this._newContent||this._getContentForTemplate())),this.tip}_createTipElement(t){const e=this._getTemplateFactory(t).toHtml();if(!e)return null;e.classList.remove(ts,es),e.classList.add(`bs-${this.constructor.NAME}-auto`);const i=(t=>{do{t+=Math.floor(1e6*Math.random())}while(document.getElementById(t));return t})(this.constructor.NAME).toString();return e.setAttribute("id",i),this._isAnimated()&&e.classList.add(ts),e}setContent(t){this._newContent=t,this._isShown()&&(this._disposePopper(),this.show())}_getTemplateFactory(t){return this._templateFactory?this._templateFactory.changeContent(t):this._templateFactory=new Jn({...this._config,content:t,extraClass:this._resolvePossibleFunction(this._config.customClass)}),this._templateFactory}_getContentForTemplate(){return{".tooltip-inner":this._getTitle()}}_getTitle(){return this._resolvePossibleFunction(this._config.title)||this._element.getAttribute("data-bs-original-title")}_initializeOnDelegatedTarget(t){return this.constructor.getOrCreateInstance(t.delegateTarget,this._getDelegateConfig())}_isAnimated(){return this._config.animation||this.tip&&this.tip.classList.contains(ts)}_isShown(){return this.tip&&this.tip.classList.contains(es)}_createPopper(t){const e=g(this._config.placement,[this,t,this._element]),i=rs[e.toUpperCase()];return bi(this._element,t,this._getPopperConfig(i))}_getOffset(){const{offset:t}=this._config;return"string"==typeof t?t.split(",").map((t=>Number.parseInt(t,10))):"function"==typeof t?e=>t(e,this._element):t}_resolvePossibleFunction(t){return g(t,[this._element])}_getPopperConfig(t){const e={placement:t,modifiers:[{name:"flip",options:{fallbackPlacements:this._config.fallbackPlacements}},{name:"offset",options:{offset:this._getOffset()}},{name:"preventOverflow",options:{boundary:this._config.boundary}},{name:"arrow",options:{element:`.${this.constructor.NAME}-arrow`}},{name:"preSetPlacement",enabled:!0,phase:"beforeMain",fn:t=>{this._getTipElement().setAttribute("data-popper-placement",t.state.placement)}}]};return{...e,...g(this._config.popperConfig,[e])}}_setListeners(){const t=this._config.trigger.split(" ");for(const e of t)if("click"===e)N.on(this._element,this.constructor.eventName("click"),this._config.selector,(t=>{this._initializeOnDelegatedTarget(t).toggle()}));else if("manual"!==e){const t=e===ss?this.constructor.eventName("mouseenter"):this.constructor.eventName("focusin"),i=e===ss?this.constructor.eventName("mouseleave"):this.constructor.eventName("focusout");N.on(this._element,t,this._config.selector,(t=>{const e=this._initializeOnDelegatedTarget(t);e._activeTrigger["focusin"===t.type?os:ss]=!0,e._enter()})),N.on(this._element,i,this._config.selector,(t=>{const e=this._initializeOnDelegatedTarget(t);e._activeTrigger["focusout"===t.type?os:ss]=e._element.contains(t.relatedTarget),e._leave()}))}this._hideModalHandler=()=>{this._element&&this.hide()},N.on(this._element.closest(is),ns,this._hideModalHandler)}_fixTitle(){const t=this._element.getAttribute("title");t&&(this._element.getAttribute("aria-label")||this._element.textContent.trim()||this._element.setAttribute("aria-label",t),this._element.setAttribute("data-bs-original-title",t),this._element.removeAttribute("title"))}_enter(){this._isShown()||this._isHovered?this._isHovered=!0:(this._isHovered=!0,this._setTimeout((()=>{this._isHovered&&this.show()}),this._config.delay.show))}_leave(){this._isWithActiveTrigger()||(this._isHovered=!1,this._setTimeout((()=>{this._isHovered||this.hide()}),this._config.delay.hide))}_setTimeout(t,e){clearTimeout(this._timeout),this._timeout=setTimeout(t,e)}_isWithActiveTrigger(){return Object.values(this._activeTrigger).includes(!0)}_getConfig(t){const e=F.getDataAttributes(this._element);for(const t of Object.keys(e))Zn.has(t)&&delete e[t];return t={...e,..."object"==typeof t&&t?t:{}},t=this._mergeConfigObj(t),t=this._configAfterMerge(t),this._typeCheckConfig(t),t}_configAfterMerge(t){return t.container=!1===t.container?document.body:r(t.container),"number"==typeof t.delay&&(t.delay={show:t.delay,hide:t.delay}),"number"==typeof t.title&&(t.title=t.title.toString()),"number"==typeof t.content&&(t.content=t.content.toString()),t}_getDelegateConfig(){const t={};for(const[e,i]of Object.entries(this._config))this.constructor.Default[e]!==i&&(t[e]=i);return t.selector=!1,t.trigger="manual",t}_disposePopper(){this._popper&&(this._popper.destroy(),this._popper=null),this.tip&&(this.tip.remove(),this.tip=null)}static jQueryInterface(t){return this.each((function(){const e=cs.getOrCreateInstance(this,t);if("string"==typeof t){if(void 0===e[t])throw new TypeError(`No method named "${t}"`);e[t]()}}))}}m(cs);const hs={...cs.Default,content:"",offset:[0,8],placement:"right",template:'',trigger:"click"},ds={...cs.DefaultType,content:"(null|string|element|function)"};class us extends cs{static get Default(){return hs}static get DefaultType(){return ds}static get NAME(){return"popover"}_isWithContent(){return this._getTitle()||this._getContent()}_getContentForTemplate(){return{".popover-header":this._getTitle(),".popover-body":this._getContent()}}_getContent(){return this._resolvePossibleFunction(this._config.content)}static jQueryInterface(t){return this.each((function(){const e=us.getOrCreateInstance(this,t);if("string"==typeof t){if(void 0===e[t])throw new TypeError(`No method named "${t}"`);e[t]()}}))}}m(us);const fs=".bs.scrollspy",ps=`activate${fs}`,ms=`click${fs}`,gs=`load${fs}.data-api`,_s="active",bs="[href]",vs=".nav-link",ys=`${vs}, .nav-item > ${vs}, .list-group-item`,ws={offset:null,rootMargin:"0px 0px -25%",smoothScroll:!1,target:null,threshold:[.1,.5,1]},As={offset:"(number|null)",rootMargin:"string",smoothScroll:"boolean",target:"element",threshold:"array"};class Es extends W{constructor(t,e){super(t,e),this._targetLinks=new Map,this._observableSections=new Map,this._rootElement="visible"===getComputedStyle(this._element).overflowY?null:this._element,this._activeTarget=null,this._observer=null,this._previousScrollData={visibleEntryTop:0,parentScrollTop:0},this.refresh()}static get Default(){return ws}static get DefaultType(){return As}static get NAME(){return"scrollspy"}refresh(){this._initializeTargetsAndObservables(),this._maybeEnableSmoothScroll(),this._observer?this._observer.disconnect():this._observer=this._getNewObserver();for(const t of this._observableSections.values())this._observer.observe(t)}dispose(){this._observer.disconnect(),super.dispose()}_configAfterMerge(t){return t.target=r(t.target)||document.body,t.rootMargin=t.offset?`${t.offset}px 0px -30%`:t.rootMargin,"string"==typeof t.threshold&&(t.threshold=t.threshold.split(",").map((t=>Number.parseFloat(t)))),t}_maybeEnableSmoothScroll(){this._config.smoothScroll&&(N.off(this._config.target,ms),N.on(this._config.target,ms,bs,(t=>{const e=this._observableSections.get(t.target.hash);if(e){t.preventDefault();const i=this._rootElement||window,n=e.offsetTop-this._element.offsetTop;if(i.scrollTo)return void i.scrollTo({top:n,behavior:"smooth"});i.scrollTop=n}})))}_getNewObserver(){const t={root:this._rootElement,threshold:this._config.threshold,rootMargin:this._config.rootMargin};return new IntersectionObserver((t=>this._observerCallback(t)),t)}_observerCallback(t){const e=t=>this._targetLinks.get(`#${t.target.id}`),i=t=>{this._previousScrollData.visibleEntryTop=t.target.offsetTop,this._process(e(t))},n=(this._rootElement||document.documentElement).scrollTop,s=n>=this._previousScrollData.parentScrollTop;this._previousScrollData.parentScrollTop=n;for(const o of t){if(!o.isIntersecting){this._activeTarget=null,this._clearActiveClass(e(o));continue}const t=o.target.offsetTop>=this._previousScrollData.visibleEntryTop;if(s&&t){if(i(o),!n)return}else s||t||i(o)}}_initializeTargetsAndObservables(){this._targetLinks=new Map,this._observableSections=new Map;const t=z.find(bs,this._config.target);for(const e of t){if(!e.hash||l(e))continue;const t=z.findOne(decodeURI(e.hash),this._element);a(t)&&(this._targetLinks.set(decodeURI(e.hash),e),this._observableSections.set(e.hash,t))}}_process(t){this._activeTarget!==t&&(this._clearActiveClass(this._config.target),this._activeTarget=t,t.classList.add(_s),this._activateParents(t),N.trigger(this._element,ps,{relatedTarget:t}))}_activateParents(t){if(t.classList.contains("dropdown-item"))z.findOne(".dropdown-toggle",t.closest(".dropdown")).classList.add(_s);else for(const e of z.parents(t,".nav, .list-group"))for(const t of z.prev(e,ys))t.classList.add(_s)}_clearActiveClass(t){t.classList.remove(_s);const e=z.find(`${bs}.${_s}`,t);for(const t of e)t.classList.remove(_s)}static jQueryInterface(t){return this.each((function(){const e=Es.getOrCreateInstance(this,t);if("string"==typeof t){if(void 0===e[t]||t.startsWith("_")||"constructor"===t)throw new TypeError(`No method named "${t}"`);e[t]()}}))}}N.on(window,gs,(()=>{for(const t of z.find('[data-bs-spy="scroll"]'))Es.getOrCreateInstance(t)})),m(Es);const Ts=".bs.tab",Cs=`hide${Ts}`,Os=`hidden${Ts}`,xs=`show${Ts}`,ks=`shown${Ts}`,Ls=`click${Ts}`,Ss=`keydown${Ts}`,Ds=`load${Ts}`,$s="ArrowLeft",Is="ArrowRight",Ns="ArrowUp",Ps="ArrowDown",Ms="Home",js="End",Fs="active",Hs="fade",Ws="show",Bs=".dropdown-toggle",zs=`:not(${Bs})`,Rs='[data-bs-toggle="tab"], [data-bs-toggle="pill"], [data-bs-toggle="list"]',qs=`.nav-link${zs}, .list-group-item${zs}, [role="tab"]${zs}, ${Rs}`,Vs=`.${Fs}[data-bs-toggle="tab"], .${Fs}[data-bs-toggle="pill"], .${Fs}[data-bs-toggle="list"]`;class Ks extends W{constructor(t){super(t),this._parent=this._element.closest('.list-group, .nav, [role="tablist"]'),this._parent&&(this._setInitialAttributes(this._parent,this._getChildren()),N.on(this._element,Ss,(t=>this._keydown(t))))}static get NAME(){return"tab"}show(){const t=this._element;if(this._elemIsActive(t))return;const e=this._getActiveElem(),i=e?N.trigger(e,Cs,{relatedTarget:t}):null;N.trigger(t,xs,{relatedTarget:e}).defaultPrevented||i&&i.defaultPrevented||(this._deactivate(e,t),this._activate(t,e))}_activate(t,e){t&&(t.classList.add(Fs),this._activate(z.getElementFromSelector(t)),this._queueCallback((()=>{"tab"===t.getAttribute("role")?(t.removeAttribute("tabindex"),t.setAttribute("aria-selected",!0),this._toggleDropDown(t,!0),N.trigger(t,ks,{relatedTarget:e})):t.classList.add(Ws)}),t,t.classList.contains(Hs)))}_deactivate(t,e){t&&(t.classList.remove(Fs),t.blur(),this._deactivate(z.getElementFromSelector(t)),this._queueCallback((()=>{"tab"===t.getAttribute("role")?(t.setAttribute("aria-selected",!1),t.setAttribute("tabindex","-1"),this._toggleDropDown(t,!1),N.trigger(t,Os,{relatedTarget:e})):t.classList.remove(Ws)}),t,t.classList.contains(Hs)))}_keydown(t){if(![$s,Is,Ns,Ps,Ms,js].includes(t.key))return;t.stopPropagation(),t.preventDefault();const e=this._getChildren().filter((t=>!l(t)));let i;if([Ms,js].includes(t.key))i=e[t.key===Ms?0:e.length-1];else{const n=[Is,Ps].includes(t.key);i=b(e,t.target,n,!0)}i&&(i.focus({preventScroll:!0}),Ks.getOrCreateInstance(i).show())}_getChildren(){return z.find(qs,this._parent)}_getActiveElem(){return this._getChildren().find((t=>this._elemIsActive(t)))||null}_setInitialAttributes(t,e){this._setAttributeIfNotExists(t,"role","tablist");for(const t of e)this._setInitialAttributesOnChild(t)}_setInitialAttributesOnChild(t){t=this._getInnerElement(t);const e=this._elemIsActive(t),i=this._getOuterElement(t);t.setAttribute("aria-selected",e),i!==t&&this._setAttributeIfNotExists(i,"role","presentation"),e||t.setAttribute("tabindex","-1"),this._setAttributeIfNotExists(t,"role","tab"),this._setInitialAttributesOnTargetPanel(t)}_setInitialAttributesOnTargetPanel(t){const e=z.getElementFromSelector(t);e&&(this._setAttributeIfNotExists(e,"role","tabpanel"),t.id&&this._setAttributeIfNotExists(e,"aria-labelledby",`${t.id}`))}_toggleDropDown(t,e){const i=this._getOuterElement(t);if(!i.classList.contains("dropdown"))return;const n=(t,n)=>{const s=z.findOne(t,i);s&&s.classList.toggle(n,e)};n(Bs,Fs),n(".dropdown-menu",Ws),i.setAttribute("aria-expanded",e)}_setAttributeIfNotExists(t,e,i){t.hasAttribute(e)||t.setAttribute(e,i)}_elemIsActive(t){return t.classList.contains(Fs)}_getInnerElement(t){return t.matches(qs)?t:z.findOne(qs,t)}_getOuterElement(t){return t.closest(".nav-item, .list-group-item")||t}static jQueryInterface(t){return this.each((function(){const e=Ks.getOrCreateInstance(this);if("string"==typeof t){if(void 0===e[t]||t.startsWith("_")||"constructor"===t)throw new TypeError(`No method named "${t}"`);e[t]()}}))}}N.on(document,Ls,Rs,(function(t){["A","AREA"].includes(this.tagName)&&t.preventDefault(),l(this)||Ks.getOrCreateInstance(this).show()})),N.on(window,Ds,(()=>{for(const t of z.find(Vs))Ks.getOrCreateInstance(t)})),m(Ks);const Qs=".bs.toast",Xs=`mouseover${Qs}`,Ys=`mouseout${Qs}`,Us=`focusin${Qs}`,Gs=`focusout${Qs}`,Js=`hide${Qs}`,Zs=`hidden${Qs}`,to=`show${Qs}`,eo=`shown${Qs}`,io="hide",no="show",so="showing",oo={animation:"boolean",autohide:"boolean",delay:"number"},ro={animation:!0,autohide:!0,delay:5e3};class ao extends W{constructor(t,e){super(t,e),this._timeout=null,this._hasMouseInteraction=!1,this._hasKeyboardInteraction=!1,this._setListeners()}static get Default(){return ro}static get DefaultType(){return oo}static get NAME(){return"toast"}show(){N.trigger(this._element,to).defaultPrevented||(this._clearTimeout(),this._config.animation&&this._element.classList.add("fade"),this._element.classList.remove(io),d(this._element),this._element.classList.add(no,so),this._queueCallback((()=>{this._element.classList.remove(so),N.trigger(this._element,eo),this._maybeScheduleHide()}),this._element,this._config.animation))}hide(){this.isShown()&&(N.trigger(this._element,Js).defaultPrevented||(this._element.classList.add(so),this._queueCallback((()=>{this._element.classList.add(io),this._element.classList.remove(so,no),N.trigger(this._element,Zs)}),this._element,this._config.animation)))}dispose(){this._clearTimeout(),this.isShown()&&this._element.classList.remove(no),super.dispose()}isShown(){return this._element.classList.contains(no)}_maybeScheduleHide(){this._config.autohide&&(this._hasMouseInteraction||this._hasKeyboardInteraction||(this._timeout=setTimeout((()=>{this.hide()}),this._config.delay)))}_onInteraction(t,e){switch(t.type){case"mouseover":case"mouseout":this._hasMouseInteraction=e;break;case"focusin":case"focusout":this._hasKeyboardInteraction=e}if(e)return void this._clearTimeout();const i=t.relatedTarget;this._element===i||this._element.contains(i)||this._maybeScheduleHide()}_setListeners(){N.on(this._element,Xs,(t=>this._onInteraction(t,!0))),N.on(this._element,Ys,(t=>this._onInteraction(t,!1))),N.on(this._element,Us,(t=>this._onInteraction(t,!0))),N.on(this._element,Gs,(t=>this._onInteraction(t,!1)))}_clearTimeout(){clearTimeout(this._timeout),this._timeout=null}static jQueryInterface(t){return this.each((function(){const e=ao.getOrCreateInstance(this,t);if("string"==typeof t){if(void 0===e[t])throw new TypeError(`No method named "${t}"`);e[t](this)}}))}}return R(ao),m(ao),{Alert:Q,Button:Y,Carousel:xt,Collapse:Bt,Dropdown:qi,Modal:On,Offcanvas:qn,Popover:us,ScrollSpy:Es,Tab:Ks,Toast:ao,Tooltip:cs}})); -//# sourceMappingURL=bootstrap.bundle.min.js.map \ No newline at end of file diff --git a/app/static/js/jquery-3.7.1.min.js b/app/static/js/jquery-3.7.1.min.js deleted file mode 100644 index 7f37b5d..0000000 --- a/app/static/js/jquery-3.7.1.min.js +++ /dev/null @@ -1,2 +0,0 @@ -/*! jQuery v3.7.1 | (c) OpenJS Foundation and other contributors | jquery.org/license */ -!function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(ie,e){"use strict";var oe=[],r=Object.getPrototypeOf,ae=oe.slice,g=oe.flat?function(e){return oe.flat.call(e)}:function(e){return oe.concat.apply([],e)},s=oe.push,se=oe.indexOf,n={},i=n.toString,ue=n.hasOwnProperty,o=ue.toString,a=o.call(Object),le={},v=function(e){return"function"==typeof e&&"number"!=typeof e.nodeType&&"function"!=typeof e.item},y=function(e){return null!=e&&e===e.window},C=ie.document,u={type:!0,src:!0,nonce:!0,noModule:!0};function m(e,t,n){var r,i,o=(n=n||C).createElement("script");if(o.text=e,t)for(r in u)(i=t[r]||t.getAttribute&&t.getAttribute(r))&&o.setAttribute(r,i);n.head.appendChild(o).parentNode.removeChild(o)}function x(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?n[i.call(e)]||"object":typeof e}var t="3.7.1",l=/HTML$/i,ce=function(e,t){return new ce.fn.init(e,t)};function c(e){var t=!!e&&"length"in e&&e.length,n=x(e);return!v(e)&&!y(e)&&("array"===n||0===t||"number"==typeof t&&0+~]|"+ge+")"+ge+"*"),x=new RegExp(ge+"|>"),j=new RegExp(g),A=new RegExp("^"+t+"$"),D={ID:new RegExp("^#("+t+")"),CLASS:new RegExp("^\\.("+t+")"),TAG:new RegExp("^("+t+"|[*])"),ATTR:new RegExp("^"+p),PSEUDO:new RegExp("^"+g),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+ge+"*(even|odd|(([+-]|)(\\d*)n|)"+ge+"*(?:([+-]|)"+ge+"*(\\d+)|))"+ge+"*\\)|)","i"),bool:new RegExp("^(?:"+f+")$","i"),needsContext:new RegExp("^"+ge+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+ge+"*((?:-\\d)?\\d*)"+ge+"*\\)|)(?=[^-]|$)","i")},N=/^(?:input|select|textarea|button)$/i,q=/^h\d$/i,L=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,H=/[+~]/,O=new RegExp("\\\\[\\da-fA-F]{1,6}"+ge+"?|\\\\([^\\r\\n\\f])","g"),P=function(e,t){var n="0x"+e.slice(1)-65536;return t||(n<0?String.fromCharCode(n+65536):String.fromCharCode(n>>10|55296,1023&n|56320))},M=function(){V()},R=J(function(e){return!0===e.disabled&&fe(e,"fieldset")},{dir:"parentNode",next:"legend"});try{k.apply(oe=ae.call(ye.childNodes),ye.childNodes),oe[ye.childNodes.length].nodeType}catch(e){k={apply:function(e,t){me.apply(e,ae.call(t))},call:function(e){me.apply(e,ae.call(arguments,1))}}}function I(t,e,n,r){var i,o,a,s,u,l,c,f=e&&e.ownerDocument,p=e?e.nodeType:9;if(n=n||[],"string"!=typeof t||!t||1!==p&&9!==p&&11!==p)return n;if(!r&&(V(e),e=e||T,C)){if(11!==p&&(u=L.exec(t)))if(i=u[1]){if(9===p){if(!(a=e.getElementById(i)))return n;if(a.id===i)return k.call(n,a),n}else if(f&&(a=f.getElementById(i))&&I.contains(e,a)&&a.id===i)return k.call(n,a),n}else{if(u[2])return k.apply(n,e.getElementsByTagName(t)),n;if((i=u[3])&&e.getElementsByClassName)return k.apply(n,e.getElementsByClassName(i)),n}if(!(h[t+" "]||d&&d.test(t))){if(c=t,f=e,1===p&&(x.test(t)||m.test(t))){(f=H.test(t)&&U(e.parentNode)||e)==e&&le.scope||((s=e.getAttribute("id"))?s=ce.escapeSelector(s):e.setAttribute("id",s=S)),o=(l=Y(t)).length;while(o--)l[o]=(s?"#"+s:":scope")+" "+Q(l[o]);c=l.join(",")}try{return k.apply(n,f.querySelectorAll(c)),n}catch(e){h(t,!0)}finally{s===S&&e.removeAttribute("id")}}}return re(t.replace(ve,"$1"),e,n,r)}function W(){var r=[];return function e(t,n){return r.push(t+" ")>b.cacheLength&&delete e[r.shift()],e[t+" "]=n}}function F(e){return e[S]=!0,e}function $(e){var t=T.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function B(t){return function(e){return fe(e,"input")&&e.type===t}}function _(t){return function(e){return(fe(e,"input")||fe(e,"button"))&&e.type===t}}function z(t){return function(e){return"form"in e?e.parentNode&&!1===e.disabled?"label"in e?"label"in e.parentNode?e.parentNode.disabled===t:e.disabled===t:e.isDisabled===t||e.isDisabled!==!t&&R(e)===t:e.disabled===t:"label"in e&&e.disabled===t}}function X(a){return F(function(o){return o=+o,F(function(e,t){var n,r=a([],e.length,o),i=r.length;while(i--)e[n=r[i]]&&(e[n]=!(t[n]=e[n]))})})}function U(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}function V(e){var t,n=e?e.ownerDocument||e:ye;return n!=T&&9===n.nodeType&&n.documentElement&&(r=(T=n).documentElement,C=!ce.isXMLDoc(T),i=r.matches||r.webkitMatchesSelector||r.msMatchesSelector,r.msMatchesSelector&&ye!=T&&(t=T.defaultView)&&t.top!==t&&t.addEventListener("unload",M),le.getById=$(function(e){return r.appendChild(e).id=ce.expando,!T.getElementsByName||!T.getElementsByName(ce.expando).length}),le.disconnectedMatch=$(function(e){return i.call(e,"*")}),le.scope=$(function(){return T.querySelectorAll(":scope")}),le.cssHas=$(function(){try{return T.querySelector(":has(*,:jqfake)"),!1}catch(e){return!0}}),le.getById?(b.filter.ID=function(e){var t=e.replace(O,P);return function(e){return e.getAttribute("id")===t}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&C){var n=t.getElementById(e);return n?[n]:[]}}):(b.filter.ID=function(e){var n=e.replace(O,P);return function(e){var t="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return t&&t.value===n}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&C){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),b.find.TAG=function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):t.querySelectorAll(e)},b.find.CLASS=function(e,t){if("undefined"!=typeof t.getElementsByClassName&&C)return t.getElementsByClassName(e)},d=[],$(function(e){var t;r.appendChild(e).innerHTML="",e.querySelectorAll("[selected]").length||d.push("\\["+ge+"*(?:value|"+f+")"),e.querySelectorAll("[id~="+S+"-]").length||d.push("~="),e.querySelectorAll("a#"+S+"+*").length||d.push(".#.+[+~]"),e.querySelectorAll(":checked").length||d.push(":checked"),(t=T.createElement("input")).setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),r.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&d.push(":enabled",":disabled"),(t=T.createElement("input")).setAttribute("name",""),e.appendChild(t),e.querySelectorAll("[name='']").length||d.push("\\["+ge+"*name"+ge+"*="+ge+"*(?:''|\"\")")}),le.cssHas||d.push(":has"),d=d.length&&new RegExp(d.join("|")),l=function(e,t){if(e===t)return a=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n||(1&(n=(e.ownerDocument||e)==(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!le.sortDetached&&t.compareDocumentPosition(e)===n?e===T||e.ownerDocument==ye&&I.contains(ye,e)?-1:t===T||t.ownerDocument==ye&&I.contains(ye,t)?1:o?se.call(o,e)-se.call(o,t):0:4&n?-1:1)}),T}for(e in I.matches=function(e,t){return I(e,null,null,t)},I.matchesSelector=function(e,t){if(V(e),C&&!h[t+" "]&&(!d||!d.test(t)))try{var n=i.call(e,t);if(n||le.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(e){h(t,!0)}return 0":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(O,P),e[3]=(e[3]||e[4]||e[5]||"").replace(O,P),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||I.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&I.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return D.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&j.test(n)&&(t=Y(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(O,P).toLowerCase();return"*"===e?function(){return!0}:function(e){return fe(e,t)}},CLASS:function(e){var t=s[e+" "];return t||(t=new RegExp("(^|"+ge+")"+e+"("+ge+"|$)"))&&s(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(n,r,i){return function(e){var t=I.attr(e,n);return null==t?"!="===r:!r||(t+="","="===r?t===i:"!="===r?t!==i:"^="===r?i&&0===t.indexOf(i):"*="===r?i&&-1:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function T(e,n,r){return v(n)?ce.grep(e,function(e,t){return!!n.call(e,t,e)!==r}):n.nodeType?ce.grep(e,function(e){return e===n!==r}):"string"!=typeof n?ce.grep(e,function(e){return-1)[^>]*|#([\w-]+))$/;(ce.fn.init=function(e,t,n){var r,i;if(!e)return this;if(n=n||k,"string"==typeof e){if(!(r="<"===e[0]&&">"===e[e.length-1]&&3<=e.length?[null,e,null]:S.exec(e))||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof ce?t[0]:t,ce.merge(this,ce.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:C,!0)),w.test(r[1])&&ce.isPlainObject(t))for(r in t)v(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return(i=C.getElementById(r[2]))&&(this[0]=i,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):v(e)?void 0!==n.ready?n.ready(e):e(ce):ce.makeArray(e,this)}).prototype=ce.fn,k=ce(C);var E=/^(?:parents|prev(?:Until|All))/,j={children:!0,contents:!0,next:!0,prev:!0};function A(e,t){while((e=e[t])&&1!==e.nodeType);return e}ce.fn.extend({has:function(e){var t=ce(e,this),n=t.length;return this.filter(function(){for(var e=0;e\x20\t\r\n\f]*)/i,Ce=/^$|^module$|\/(?:java|ecma)script/i;xe=C.createDocumentFragment().appendChild(C.createElement("div")),(be=C.createElement("input")).setAttribute("type","radio"),be.setAttribute("checked","checked"),be.setAttribute("name","t"),xe.appendChild(be),le.checkClone=xe.cloneNode(!0).cloneNode(!0).lastChild.checked,xe.innerHTML="",le.noCloneChecked=!!xe.cloneNode(!0).lastChild.defaultValue,xe.innerHTML="",le.option=!!xe.lastChild;var ke={thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};function Se(e,t){var n;return n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&fe(e,t)?ce.merge([e],n):n}function Ee(e,t){for(var n=0,r=e.length;n",""]);var je=/<|&#?\w+;/;function Ae(e,t,n,r,i){for(var o,a,s,u,l,c,f=t.createDocumentFragment(),p=[],d=0,h=e.length;d\s*$/g;function Re(e,t){return fe(e,"table")&&fe(11!==t.nodeType?t:t.firstChild,"tr")&&ce(e).children("tbody")[0]||e}function Ie(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function We(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Fe(e,t){var n,r,i,o,a,s;if(1===t.nodeType){if(_.hasData(e)&&(s=_.get(e).events))for(i in _.remove(t,"handle events"),s)for(n=0,r=s[i].length;n").attr(n.scriptAttrs||{}).prop({charset:n.scriptCharset,src:n.url}).on("load error",i=function(e){r.remove(),i=null,e&&t("error"===e.type?404:200,e.type)}),C.head.appendChild(r[0])},abort:function(){i&&i()}}});var Jt,Kt=[],Zt=/(=)\?(?=&|$)|\?\?/;ce.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Kt.pop()||ce.expando+"_"+jt.guid++;return this[e]=!0,e}}),ce.ajaxPrefilter("json jsonp",function(e,t,n){var r,i,o,a=!1!==e.jsonp&&(Zt.test(e.url)?"url":"string"==typeof e.data&&0===(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&Zt.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0])return r=e.jsonpCallback=v(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(Zt,"$1"+r):!1!==e.jsonp&&(e.url+=(At.test(e.url)?"&":"?")+e.jsonp+"="+r),e.converters["script json"]=function(){return o||ce.error(r+" was not called"),o[0]},e.dataTypes[0]="json",i=ie[r],ie[r]=function(){o=arguments},n.always(function(){void 0===i?ce(ie).removeProp(r):ie[r]=i,e[r]&&(e.jsonpCallback=t.jsonpCallback,Kt.push(r)),o&&v(i)&&i(o[0]),o=i=void 0}),"script"}),le.createHTMLDocument=((Jt=C.implementation.createHTMLDocument("").body).innerHTML="
",2===Jt.childNodes.length),ce.parseHTML=function(e,t,n){return"string"!=typeof e?[]:("boolean"==typeof t&&(n=t,t=!1),t||(le.createHTMLDocument?((r=(t=C.implementation.createHTMLDocument("")).createElement("base")).href=C.location.href,t.head.appendChild(r)):t=C),o=!n&&[],(i=w.exec(e))?[t.createElement(i[1])]:(i=Ae([e],t,o),o&&o.length&&ce(o).remove(),ce.merge([],i.childNodes)));var r,i,o},ce.fn.load=function(e,t,n){var r,i,o,a=this,s=e.indexOf(" ");return-1").append(ce.parseHTML(e)).find(r):e)}).always(n&&function(e,t){a.each(function(){n.apply(this,o||[e.responseText,t,e])})}),this},ce.expr.pseudos.animated=function(t){return ce.grep(ce.timers,function(e){return t===e.elem}).length},ce.offset={setOffset:function(e,t,n){var r,i,o,a,s,u,l=ce.css(e,"position"),c=ce(e),f={};"static"===l&&(e.style.position="relative"),s=c.offset(),o=ce.css(e,"top"),u=ce.css(e,"left"),("absolute"===l||"fixed"===l)&&-1<(o+u).indexOf("auto")?(a=(r=c.position()).top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(u)||0),v(t)&&(t=t.call(e,n,ce.extend({},s))),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):c.css(f)}},ce.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){ce.offset.setOffset(this,t,e)});var e,n,r=this[0];return r?r.getClientRects().length?(e=r.getBoundingClientRect(),n=r.ownerDocument.defaultView,{top:e.top+n.pageYOffset,left:e.left+n.pageXOffset}):{top:0,left:0}:void 0},position:function(){if(this[0]){var e,t,n,r=this[0],i={top:0,left:0};if("fixed"===ce.css(r,"position"))t=r.getBoundingClientRect();else{t=this.offset(),n=r.ownerDocument,e=r.offsetParent||n.documentElement;while(e&&(e===n.body||e===n.documentElement)&&"static"===ce.css(e,"position"))e=e.parentNode;e&&e!==r&&1===e.nodeType&&((i=ce(e).offset()).top+=ce.css(e,"borderTopWidth",!0),i.left+=ce.css(e,"borderLeftWidth",!0))}return{top:t.top-i.top-ce.css(r,"marginTop",!0),left:t.left-i.left-ce.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent;while(e&&"static"===ce.css(e,"position"))e=e.offsetParent;return e||J})}}),ce.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,i){var o="pageYOffset"===i;ce.fn[t]=function(e){return M(this,function(e,t,n){var r;if(y(e)?r=e:9===e.nodeType&&(r=e.defaultView),void 0===n)return r?r[i]:e[t];r?r.scrollTo(o?r.pageXOffset:n,o?n:r.pageYOffset):e[t]=n},t,e,arguments.length)}}),ce.each(["top","left"],function(e,n){ce.cssHooks[n]=Ye(le.pixelPosition,function(e,t){if(t)return t=Ge(e,n),_e.test(t)?ce(e).position()[n]+"px":t})}),ce.each({Height:"height",Width:"width"},function(a,s){ce.each({padding:"inner"+a,content:s,"":"outer"+a},function(r,o){ce.fn[o]=function(e,t){var n=arguments.length&&(r||"boolean"!=typeof e),i=r||(!0===e||!0===t?"margin":"border");return M(this,function(e,t,n){var r;return y(e)?0===o.indexOf("outer")?e["inner"+a]:e.document.documentElement["client"+a]:9===e.nodeType?(r=e.documentElement,Math.max(e.body["scroll"+a],r["scroll"+a],e.body["offset"+a],r["offset"+a],r["client"+a])):void 0===n?ce.css(e,t,i):ce.style(e,t,n,i)},s,n?e:void 0,n)}})}),ce.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){ce.fn[t]=function(e){return this.on(t,e)}}),ce.fn.extend({bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},hover:function(e,t){return this.on("mouseenter",e).on("mouseleave",t||e)}}),ce.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,n){ce.fn[n]=function(e,t){return 0 - - - - {% block title %}{{ title }}{% endblock %} - Fitness Parser - - - - - {% block extra_head %}{% endblock %} - - - - - - -
- {% block content %}{% endblock %} -
- - - - - - {% block extra_scripts %}{% endblock %} - - diff --git a/app/templates/index.html b/app/templates/index.html deleted file mode 100644 index fba1570..0000000 --- a/app/templates/index.html +++ /dev/null @@ -1,12 +0,0 @@ -{% extends "base.html" %} - -{% block content %} -
-
-
-
Fitness parser playground
-
-
-
- -{% endblock %} diff --git a/app/templates/obsidian/parser.html b/app/templates/obsidian/parser.html deleted file mode 100644 index 8360bf2..0000000 --- a/app/templates/obsidian/parser.html +++ /dev/null @@ -1,49 +0,0 @@ -{% extends "base.html" %} {% block content %} -

Parse training data

-
-
- - -
- -
- -
-
-
-{% if result %} -
-

Result:

-
{{ result }}
-
-{% endif %} - - -{% endblock %} diff --git a/app/templates/trainings.html b/app/templates/trainings.html deleted file mode 100644 index aab5774..0000000 --- a/app/templates/trainings.html +++ /dev/null @@ -1,43 +0,0 @@ -{% extends "base.html" %} - -{% block content %} -

Training Sessions

- -{% if trainings %} -

Total trainings: {{ trainings|length }}

- - {% for training in trainings %} -
-

Date: {{ training.date }}

- - {% if training.exercises %} -

Exercises: {{ training.exercises|length }}

- - {% for exercise in training.exercises %} -
-

{{ exercise.name }}

- {% if exercise.splitted_weight %} - (Split Weight) - {% endif %} - -
    - {% for approach in exercise.approaches %} -
  • {{ approach.weight }}kg x {{ approach.reps }} reps
  • - {% endfor %} -
-
- {% endfor %} - - {% else %} -

No exercises recorded

- {% endif %} -
- -
- {% endfor %} - -{% else %} -

No training data available

-{% endif %} - -{% endblock %} \ No newline at end of file diff --git a/.dockerignore b/backend/.dockerignore similarity index 96% rename from .dockerignore rename to backend/.dockerignore index 8e5c944..40b3d57 100644 --- a/.dockerignore +++ b/backend/.dockerignore @@ -35,7 +35,6 @@ ENV/ Thumbs.db # Project specific -uv.lock .mypy_cache .opencode diff --git a/Dockerfile b/backend/Dockerfile similarity index 56% rename from Dockerfile rename to backend/Dockerfile index 64d2908..be69ea8 100644 --- a/Dockerfile +++ b/backend/Dockerfile @@ -8,14 +8,17 @@ RUN apt-get update && apt-get install -y \ build-essential \ && rm -rf /var/lib/apt/lists/* -# Copy pyproject.toml first for better caching -COPY pyproject.toml ./ +# Copy requirements first for better caching +COPY requirements.txt requirements-dev.txt ./ -# Install Python dependencies -RUN pip install --no-cache-dir -e . +# Install Python dependencies (the project is run only in Docker, so dev tools +# like pytest and mypy are part of the image) +RUN pip install --no-cache-dir -r requirements-dev.txt # Copy application code +COPY pyproject.toml alembic.ini ./ COPY ./app ./app +COPY ./migrations ./migrations COPY ./data ./data COPY ./tests ./tests @@ -26,4 +29,4 @@ ENV PYTHONPATH=/app EXPOSE 8000 # Command will be overridden by docker-compose -CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"] \ No newline at end of file +CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"] diff --git a/backend/alembic.ini b/backend/alembic.ini new file mode 100644 index 0000000..5108aaa --- /dev/null +++ b/backend/alembic.ini @@ -0,0 +1,149 @@ +# A generic, single database configuration. + +[alembic] +# path to migration scripts. +# this is typically a path given in POSIX (e.g. forward slashes) +# format, relative to the token %(here)s which refers to the location of this +# ini file +script_location = %(here)s/migrations + +# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s +# Uncomment the line below if you want the files to be prepended with date and time +# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file +# for all available tokens +file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s +# Or organize into date-based subdirectories (requires recursive_version_locations = true) +# file_template = %%(year)d/%%(month).2d/%%(day).2d_%%(hour).2d%%(minute).2d_%%(second).2d_%%(rev)s_%%(slug)s + +# sys.path path, will be prepended to sys.path if present. +# defaults to the current working directory. for multiple paths, the path separator +# is defined by "path_separator" below. +prepend_sys_path = . + +# timezone to use when rendering the date within the migration file +# as well as the filename. +# If specified, requires the tzdata library which can be installed by adding +# `alembic[tz]` to the pip requirements. +# string value is passed to ZoneInfo() +# leave blank for localtime +# timezone = + +# max length of characters to apply to the "slug" field +# truncate_slug_length = 40 + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + +# set to 'true' to allow .pyc and .pyo files without +# a source .py file to be detected as revisions in the +# versions/ directory +# sourceless = false + +# version location specification; This defaults +# to /versions. When using multiple version +# directories, initial revisions must be specified with --version-path. +# The path separator used here should be the separator specified by "path_separator" +# below. +# version_locations = %(here)s/bar:%(here)s/bat:%(here)s/alembic/versions + +# path_separator; This indicates what character is used to split lists of file +# paths, including version_locations and prepend_sys_path within configparser +# files such as alembic.ini. +# The default rendered in new alembic.ini files is "os", which uses os.pathsep +# to provide os-dependent path splitting. +# +# Note that in order to support legacy alembic.ini files, this default does NOT +# take place if path_separator is not present in alembic.ini. If this +# option is omitted entirely, fallback logic is as follows: +# +# 1. Parsing of the version_locations option falls back to using the legacy +# "version_path_separator" key, which if absent then falls back to the legacy +# behavior of splitting on spaces and/or commas. +# 2. Parsing of the prepend_sys_path option falls back to the legacy +# behavior of splitting on spaces, commas, or colons. +# +# Valid values for path_separator are: +# +# path_separator = : +# path_separator = ; +# path_separator = space +# path_separator = newline +# +# Use os.pathsep. Default configuration used for new projects. +path_separator = os + + +# set to 'true' to search source files recursively +# in each "version_locations" directory +# new in Alembic version 1.10 +# recursive_version_locations = false + +# the output encoding used when revision files +# are written from script.py.mako +# output_encoding = utf-8 + +# database URL. This is consumed by the user-maintained env.py script only. +# other means of configuring database URLs may be customized within the env.py +# file. +sqlalchemy.url = driver://user:pass@localhost/dbname + + +[post_write_hooks] +# post_write_hooks defines scripts or Python functions that are run +# on newly generated revision scripts. See the documentation for further +# detail and examples + +# format using "black" - use the console_scripts runner, against the "black" entrypoint +# hooks = black +# black.type = console_scripts +# black.entrypoint = black +# black.options = -l 79 REVISION_SCRIPT_FILENAME + +# lint with attempts to fix using "ruff" - use the module runner, against the "ruff" module +# hooks = ruff +# ruff.type = module +# ruff.module = ruff +# ruff.options = check --fix REVISION_SCRIPT_FILENAME + +# Alternatively, use the exec runner to execute a binary found on your PATH +# hooks = ruff +# ruff.type = exec +# ruff.executable = ruff +# ruff.options = check --fix REVISION_SCRIPT_FILENAME + +# Logging configuration. This is also consumed by the user-maintained +# env.py script only. +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARNING +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARNING +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/app/__init__.py b/backend/app/__init__.py similarity index 100% rename from app/__init__.py rename to backend/app/__init__.py diff --git a/app/api/__init__.py b/backend/app/api/__init__.py similarity index 100% rename from app/api/__init__.py rename to backend/app/api/__init__.py diff --git a/backend/app/api/deps.py b/backend/app/api/deps.py new file mode 100644 index 0000000..c0256a0 --- /dev/null +++ b/backend/app/api/deps.py @@ -0,0 +1,11 @@ +from fastapi import Depends +from sqlalchemy.ext.asyncio import AsyncSession + +from app.core.database.connection import get_session +from app.core.database.repository import TrainingRepository + + +def get_training_repository( + session: AsyncSession = Depends(get_session), +) -> TrainingRepository: + return TrainingRepository(session) diff --git a/app/api/v1/__init__.py b/backend/app/api/v1/__init__.py similarity index 100% rename from app/api/v1/__init__.py rename to backend/app/api/v1/__init__.py diff --git a/backend/app/api/v1/exercises.py b/backend/app/api/v1/exercises.py new file mode 100644 index 0000000..1a81bd2 --- /dev/null +++ b/backend/app/api/v1/exercises.py @@ -0,0 +1,71 @@ +from typing import List, Optional + +from fastapi import APIRouter, Depends, HTTPException + +from app.api.deps import get_training_repository +from app.core.database.repository import TrainingRepository +from app.core.dto.training import ExerciseNameDTO +from app.core.metrics import Record, summarize +from app.schemas.exercises import ( + ExerciseProgressResponse, + RecordResponse, + SessionMetricsResponse, + SessionRowResponse, +) + +router = APIRouter() + + +def record_response(record: Optional[Record]) -> Optional[RecordResponse]: + return RecordResponse(value=record.value, date=record.date) if record else None + + +@router.get("/", response_model=List[ExerciseNameDTO]) +async def list_exercise_names( + repository: TrainingRepository = Depends(get_training_repository), +): + """Distinct exercise names with the number of times each was done.""" + return await repository.list_exercise_names() + + +@router.get("/progress/", response_model=ExerciseProgressResponse) +async def exercise_progress( + name: str, + repository: TrainingRepository = Depends(get_training_repository), +): + """The whole history of the exercise with progress metrics. + + The name is matched exactly, but case-insensitively: what was typed may differ in case. + """ + names_by_casefold = { + item.name.casefold(): item.name + for item in await repository.list_exercise_names() + } + exact_name = names_by_casefold.get(name.strip().casefold()) + if exact_name is None: + raise HTTPException(status_code=404, detail="Exercise not found") + + progress = summarize(await repository.exercise_history(exact_name)) + return ExerciseProgressResponse( + name=exact_name, + weighted=progress.weighted, + max_weight=progress.max_weight, + best_primary=record_response(progress.best_primary), + best_secondary=record_response(progress.best_secondary), + first_primary=progress.first_primary, + last_primary=progress.last_primary, + primary_change=progress.primary_change, + primary_change_percent=progress.primary_change_percent, + rows=[ + SessionRowResponse( + date=row.session.date, + trainer=row.session.trainer, + splitted_weight=row.session.splitted_weight, + approaches=row.session.approaches, + metrics=SessionMetricsResponse.model_validate( + row.metrics, from_attributes=True + ), + ) + for row in progress.rows + ], + ) diff --git a/app/api/v1/endpoints/health.py b/backend/app/api/v1/health.py similarity index 100% rename from app/api/v1/endpoints/health.py rename to backend/app/api/v1/health.py diff --git a/app/api/v1/endpoints/parser.py b/backend/app/api/v1/parser.py similarity index 90% rename from app/api/v1/endpoints/parser.py rename to backend/app/api/v1/parser.py index 3646519..e998f69 100644 --- a/app/api/v1/endpoints/parser.py +++ b/backend/app/api/v1/parser.py @@ -1,5 +1,4 @@ from fastapi import APIRouter, HTTPException -from typing import List from app.schemas.parser import ParseRequest, ParseResponse from app.core.services.parser_service import ParserService @@ -7,7 +6,7 @@ router = APIRouter() parser_service = ParserService() -@router.post("/parse/", response_model=List[ParseResponse]) +@router.post("/parse/", response_model=list[ParseResponse]) async def parse_training_data(request: ParseRequest): try: result = await parser_service.parse_data(request) diff --git a/app/api/v1/api.py b/backend/app/api/v1/router.py similarity index 66% rename from app/api/v1/api.py rename to backend/app/api/v1/router.py index 5cc7f25..01c7990 100644 --- a/app/api/v1/api.py +++ b/backend/app/api/v1/router.py @@ -1,8 +1,9 @@ from fastapi import APIRouter -from app.api.v1.endpoints import parser, health, trainings +from app.api.v1 import exercises, parser, health, trainings api_router = APIRouter() api_router.include_router(health.router, prefix="/health", tags=["health"]) api_router.include_router(parser.router, prefix="/parser", tags=["parser"]) api_router.include_router(trainings.router, prefix="/trainings", tags=["trainings"]) +api_router.include_router(exercises.router, prefix="/exercises", tags=["exercises"]) diff --git a/backend/app/api/v1/trainings.py b/backend/app/api/v1/trainings.py new file mode 100644 index 0000000..2f0b956 --- /dev/null +++ b/backend/app/api/v1/trainings.py @@ -0,0 +1,34 @@ +from typing import List + +from fastapi import APIRouter, Depends, HTTPException + +from app.api.deps import get_training_repository +from app.core.database.repository import TrainingRepository +from app.core.dto.training import TrainingDTO +from app.core.parsers.obsidian import parse_training_data + + +router = APIRouter() + + +@router.get("/obsidian/") +async def obsidian_trainings_list(): + return {"data": parse_training_data()} + + +@router.get("/", response_model=List[TrainingDTO]) +async def get_trainings_list( + repository: TrainingRepository = Depends(get_training_repository), +): + return await repository.list() + + +@router.delete("/{training_id}/") +async def delete_training( + training_id: int, + repository: TrainingRepository = Depends(get_training_repository), +): + deleted = await repository.delete([training_id]) + if not deleted: + raise HTTPException(status_code=404, detail="Training not found") + return {"status": "ok"} diff --git a/backend/app/cli.py b/backend/app/cli.py new file mode 100644 index 0000000..09d8354 --- /dev/null +++ b/backend/app/cli.py @@ -0,0 +1,64 @@ +"""Command line helpers. + + python -m app.cli import [--replace] + +Imports all trainings from the Obsidian and Apple notes into the database. +The schema must already exist (`alembic upgrade head`). +""" + +import argparse +import asyncio +import logging + +from app.config import settings +from app.core.database.connection import create_engine, create_session_factory +from app.core.database.repository import TrainingRepository +from app.core.parsers.apple import AppleNotesParser +from app.core.parsers.obsidian import ObsidianNotesParser + + +async def import_notes(replace: bool) -> None: + parsers = [ObsidianNotesParser(), AppleNotesParser()] + trainings = [] + for parser in parsers: + parsed = parser.parse_file() + print( + f"{type(parser).__name__}: {len(parsed)} trainings, " + f"{len(parser.errors)} skipped lines" + ) + trainings.extend(parsed) + + engine = create_engine(settings.get_postgres_database_url()) + try: + async with create_session_factory(engine)() as session: + repository = TrainingRepository(session) + existing = await repository.count() + if existing and not replace: + raise SystemExit( + f"Database already has {existing} trainings, " + "use --replace to overwrite them" + ) + if replace: + await repository.delete_all() + await repository.save_many(trainings) + finally: + await engine.dispose() + print(f"Imported {len(trainings)} trainings") + + +def main() -> None: + logging.basicConfig(level=logging.WARNING) + arg_parser = argparse.ArgumentParser(prog="app.cli") + subcommands = arg_parser.add_subparsers(dest="command", required=True) + import_parser = subcommands.add_parser("import", help="import notes into the DB") + import_parser.add_argument( + "--replace", action="store_true", help="delete existing trainings first" + ) + args = arg_parser.parse_args() + + if args.command == "import": + asyncio.run(import_notes(replace=args.replace)) + + +if __name__ == "__main__": + main() diff --git a/app/config.py b/backend/app/config.py similarity index 61% rename from app/config.py rename to backend/app/config.py index 7e2f71c..487e61c 100644 --- a/app/config.py +++ b/backend/app/config.py @@ -1,17 +1,16 @@ -from pydantic_settings import BaseSettings, SettingsConfigDict from typing import Optional +from urllib.parse import quote + +from pydantic_settings import BaseSettings, SettingsConfigDict class Settings(BaseSettings): # Base app settings - model_config = SettingsConfigDict(env_file=".env") + model_config = SettingsConfigDict(env_file=".env", extra="ignore") app_name: str = "F1tness Parser API" version: str = "0.0.1" debug: bool = False - # SQLite database settings - SQLITE_DATABASE_PATH: str = "fitness.db" - # Postgres database settings POSTGRES_DATABASE_URL: Optional[str] = None POSTGRES_DATABASE_HOST: str = "localhost" @@ -20,16 +19,15 @@ class Settings(BaseSettings): POSTGRES_DATABASE_USER: str = "postgres" POSTGRES_DATABASE_PASSWORD: str = "password" - def get_postgres_database_url(self, async_driver: bool = True) -> str: - """Method for receiving relational database URL""" + def get_postgres_database_url(self) -> str: + """SQLAlchemy async URL. POSTGRES_DATABASE_URL, if set, takes precedence.""" - # If POSTGRES_DATABASE_URL is somehow set in env file - return it if self.POSTGRES_DATABASE_URL: return self.POSTGRES_DATABASE_URL - driver = "postgresql+asyncpg" if async_driver else "postgresql" return ( - f"{driver}://{self.POSTGRES_DATABASE_USER}:{self.POSTGRES_DATABASE_PASSWORD}" + f"postgresql+asyncpg://{quote(self.POSTGRES_DATABASE_USER)}" + f":{quote(self.POSTGRES_DATABASE_PASSWORD)}" f"@{self.POSTGRES_DATABASE_HOST}" f":{self.POSTGRES_DATABASE_PORT}/{self.POSTGRES_DATABASE_DB}" ) diff --git a/app/api/v1/endpoints/__init__.py b/backend/app/core/__init__.py similarity index 100% rename from app/api/v1/endpoints/__init__.py rename to backend/app/core/__init__.py diff --git a/app/core/__init__.py b/backend/app/core/database/__init__.py similarity index 100% rename from app/core/__init__.py rename to backend/app/core/database/__init__.py diff --git a/backend/app/core/database/connection.py b/backend/app/core/database/connection.py new file mode 100644 index 0000000..b2a6ab0 --- /dev/null +++ b/backend/app/core/database/connection.py @@ -0,0 +1,24 @@ +from typing import AsyncIterator + +from fastapi import Request +from sqlalchemy.ext.asyncio import ( + AsyncEngine, + AsyncSession, + async_sessionmaker, + create_async_engine, +) + + +def create_engine(database_url: str) -> AsyncEngine: + return create_async_engine(database_url) + + +def create_session_factory(engine: AsyncEngine) -> async_sessionmaker[AsyncSession]: + # expire_on_commit=False keeps ids/attributes readable after commit + return async_sessionmaker(engine, expire_on_commit=False) + + +async def get_session(request: Request) -> AsyncIterator[AsyncSession]: + """FastAPI dependency: one session per request, factory is set in the app lifespan.""" + async with request.app.state.session_factory() as session: + yield session diff --git a/backend/app/core/database/repository.py b/backend/app/core/database/repository.py new file mode 100644 index 0000000..38dd4dd --- /dev/null +++ b/backend/app/core/database/repository.py @@ -0,0 +1,169 @@ +from collections import defaultdict +from typing import Dict, List, Optional, Sequence + +from sqlalchemy import delete, func, insert, select, text +from sqlalchemy.ext.asyncio import AsyncSession + +from app.core.database.tables import approaches, exercises, trainings +from app.core.dto.training import ( + ApproachDTO, + ExerciseDTO, + ExerciseNameDTO, + ExerciseSessionDTO, + TrainingDTO, +) + + +class TrainingRepository: + """Storage for trainings together with their exercises and approaches (SQLAlchemy Core).""" + + def __init__(self, session: AsyncSession) -> None: + self._session = session + + async def save(self, training: TrainingDTO) -> int: + return (await self.save_many([training]))[0] + + async def save_many(self, items: Sequence[TrainingDTO]) -> List[int]: + """Save all trainings in a single transaction, returns their ids.""" + if not items: + return [] + training_ids = await self._insert_returning_ids( + trainings, + [{"date": item.date, "trainer": item.trainer} for item in items], + ) + + exercise_rows = [] + exercise_dtos = [] + for training_id, item in zip(training_ids, items): + for exercise in item.exercises: + exercise_rows.append( + { + "training_id": training_id, + "name": exercise.name, + "splitted_weight": exercise.splitted_weight, + } + ) + exercise_dtos.append(exercise) + if exercise_rows: + exercise_ids = await self._insert_returning_ids(exercises, exercise_rows) + approach_rows = [ + {"exercise_id": exercise_id, "weight": a.weight, "reps": a.reps} + for exercise_id, exercise in zip(exercise_ids, exercise_dtos) + for a in exercise.approaches + ] + if approach_rows: + await self._session.execute(insert(approaches), approach_rows) + + await self._session.commit() + return training_ids + + async def list(self) -> List[TrainingDTO]: + training_rows = ( + await self._session.execute( + select(trainings).order_by(trainings.c.date.desc(), trainings.c.id.desc()) + ) + ).all() + approaches_by_exercise = await self._approaches_by_exercise() + exercises_by_training: Dict[int, List[ExerciseDTO]] = defaultdict(list) + exercise_rows = await self._session.execute( + select(exercises).order_by(exercises.c.id) + ) + for row in exercise_rows: + exercises_by_training[row.training_id].append( + ExerciseDTO( + id=row.id, + training_id=row.training_id, + name=row.name, + splitted_weight=row.splitted_weight, + approaches=approaches_by_exercise[row.id], + ) + ) + return [ + TrainingDTO( + id=row.id, + date=row.date, + trainer=row.trainer, + exercises=exercises_by_training[row.id], + ) + for row in training_rows + ] + + async def list_exercise_names(self) -> List[ExerciseNameDTO]: + """Distinct exercise names with the number of times each was done.""" + query = select( + exercises.c.name, func.count(exercises.c.id).label("times") + ).group_by(exercises.c.name) + result = await self._session.execute(query) + names = [ExerciseNameDTO(name=row.name, count=row.times) for row in result] + # Sorted here, not in SQL: the order must not depend on DB collation + return sorted(names, key=lambda item: item.name.casefold()) + + async def exercise_history(self, name: str) -> List[ExerciseSessionDTO]: + """Every occurrence of the exercise, newest first.""" + query = ( + select( + exercises.c.id, + exercises.c.splitted_weight, + trainings.c.date, + trainings.c.trainer, + ) + .join(trainings, trainings.c.id == exercises.c.training_id) + .where(exercises.c.name == name) + .order_by(trainings.c.date.desc(), exercises.c.id.desc()) + ) + rows = (await self._session.execute(query)).all() + approaches_by_exercise = await self._approaches_by_exercise( + [row.id for row in rows] + ) + return [ + ExerciseSessionDTO( + date=row.date, + trainer=row.trainer, + splitted_weight=row.splitted_weight, + approaches=approaches_by_exercise[row.id], + ) + for row in rows + ] + + async def count(self) -> int: + return await self._session.scalar(select(func.count(trainings.c.id))) or 0 + + async def delete(self, list_of_ids: List[int]) -> int: + """Delete trainings by ids (exercises and approaches go with them).""" + result = await self._session.execute( + delete(trainings).where(trainings.c.id.in_(list_of_ids)) + ) + await self._session.commit() + return result.rowcount # type: ignore[attr-defined] + + async def delete_all(self) -> None: + await self._session.execute( + text("TRUNCATE trainings RESTART IDENTITY CASCADE") + ) + await self._session.commit() + + async def _insert_returning_ids(self, table, rows: List[dict]) -> List[int]: + """Bulk insert, ids come back in the order of `rows`.""" + result = await self._session.execute( + insert(table).returning(table.c.id, sort_by_parameter_order=True), rows + ) + return list(result.scalars()) + + async def _approaches_by_exercise( + self, exercise_ids: Optional[Sequence[int]] = None + ) -> Dict[int, List[ApproachDTO]]: + """Approaches grouped by exercise id (all of them when no ids are given).""" + query = select(approaches).order_by(approaches.c.id) + if exercise_ids is not None: + query = query.where(approaches.c.exercise_id.in_(exercise_ids)) + grouped: Dict[int, List[ApproachDTO]] = defaultdict(list) + for row in await self._session.execute(query): + grouped[row.exercise_id].append( + ApproachDTO( + id=row.id, + exercise_id=row.exercise_id, + weight=row.weight, + reps=row.reps, + ) + ) + return grouped diff --git a/backend/app/core/database/tables.py b/backend/app/core/database/tables.py new file mode 100644 index 0000000..6b66284 --- /dev/null +++ b/backend/app/core/database/tables.py @@ -0,0 +1,54 @@ +from sqlalchemy import ( + Boolean, + Column, + Date, + DateTime, + Float, + ForeignKey, + Integer, + MetaData, + String, + Table, + func, +) + +metadata = MetaData() + +trainings = Table( + "trainings", + metadata, + Column("id", Integer, primary_key=True), + Column("date", Date, nullable=False, index=True), + Column("trainer", String(100)), + Column("created_at", DateTime(timezone=True), nullable=False, server_default=func.now()), +) + +exercises = Table( + "exercises", + metadata, + Column("id", Integer, primary_key=True), + Column( + "training_id", + ForeignKey("trainings.id", ondelete="CASCADE"), + nullable=False, + index=True, + ), + Column("name", String(255), nullable=False, index=True), + Column("splitted_weight", Boolean, nullable=False, server_default="false"), + Column("created_at", DateTime(timezone=True), nullable=False, server_default=func.now()), +) + +approaches = Table( + "approaches", + metadata, + Column("id", Integer, primary_key=True), + Column( + "exercise_id", + ForeignKey("exercises.id", ondelete="CASCADE"), + nullable=False, + index=True, + ), + Column("weight", Float, nullable=False), + Column("reps", Integer, nullable=False), + Column("created_at", DateTime(timezone=True), nullable=False, server_default=func.now()), +) diff --git a/app/core/database/__init__.py b/backend/app/core/dto/__init__.py similarity index 100% rename from app/core/database/__init__.py rename to backend/app/core/dto/__init__.py diff --git a/backend/app/core/dto/training.py b/backend/app/core/dto/training.py new file mode 100644 index 0000000..c9e10e8 --- /dev/null +++ b/backend/app/core/dto/training.py @@ -0,0 +1,45 @@ +from pydantic import BaseModel, ConfigDict, Field +from datetime import date + + +class DTOBase(BaseModel): + # Allows TrainingDTO.model_validate() + model_config = ConfigDict(from_attributes=True) + + +class ApproachDTO(DTOBase): + id: int | None = None + exercise_id: int | None = None + weight: float + reps: int + + +class ExerciseDTO(DTOBase): + id: int | None = None + training_id: int | None = None + name: str + splitted_weight: bool = False + approaches: list[ApproachDTO] = Field(default_factory=list) + + +class TrainingDTO(DTOBase): + id: int | None = None + date: date + trainer: str | None = None + exercises: list[ExerciseDTO] = Field(default_factory=list) + + +class ExerciseNameDTO(DTOBase): + """Distinct exercise name and how many times it was done.""" + + name: str + count: int + + +class ExerciseSessionDTO(DTOBase): + """One occurrence of an exercise in the history of that exercise.""" + + date: date + trainer: str | None = None + splitted_weight: bool = False + approaches: list[ApproachDTO] = Field(default_factory=list) diff --git a/backend/app/core/metrics.py b/backend/app/core/metrics.py new file mode 100644 index 0000000..2bae95c --- /dev/null +++ b/backend/app/core/metrics.py @@ -0,0 +1,120 @@ +"""Progress metrics of an exercise computed from its history. + +Weighted exercises are tracked by the estimated one-rep max (e1RM) and by the +volume load; exercises done without extra weight (pull-ups, dips) by the best +set and the total number of reps. +""" + +from dataclasses import dataclass +from datetime import date +from typing import List, Optional, Sequence + +from app.core.dto.training import ApproachDTO, ExerciseSessionDTO + + +def estimate_1rm(weight: float, reps: int) -> float: + """Epley formula: weight * (1 + reps / 30). A single rep is the weight itself.""" + return weight if reps <= 1 else weight * (1 + reps / 30) + + +@dataclass(frozen=True) +class SessionMetrics: + max_weight: float + e1rm: Optional[float] # best set by e1RM, None when there are no weighted sets + volume: float # sum of weight * reps over weighted sets + total_reps: int # all sets, with or without weight + best_reps: int # reps of the best set + + +def session_metrics(approaches: Sequence[ApproachDTO]) -> SessionMetrics: + # Sets without weight (warm-ups, bodyweight) don't count for e1RM and volume + weighted_sets = [approach for approach in approaches if approach.weight > 0] + return SessionMetrics( + max_weight=max((approach.weight for approach in approaches), default=0.0), + e1rm=max( + (estimate_1rm(approach.weight, approach.reps) for approach in weighted_sets), + default=None, + ), + volume=sum(approach.weight * approach.reps for approach in weighted_sets), + total_reps=sum(approach.reps for approach in approaches), + best_reps=max((approach.reps for approach in approaches), default=0), + ) + + +@dataclass(frozen=True) +class SessionRow: + session: ExerciseSessionDTO + metrics: SessionMetrics + + +@dataclass(frozen=True) +class Record: + value: float + date: date + + +@dataclass(frozen=True) +class ExerciseProgress: + # True if any session has weighted sets: then e1RM and volume are the main + # metrics, otherwise reps of the best set and total reps + weighted: bool + rows: List[SessionRow] # same order as the history: newest first + max_weight: float + best_primary: Optional[Record] # e1RM / best set reps + best_secondary: Optional[Record] # volume / total reps of a session + first_primary: Optional[float] # in the oldest session that has the metric + last_primary: Optional[float] # in the newest session that has the metric + + @property + def primary_change(self) -> Optional[float]: + """Absolute change of the main metric between the first and the last session.""" + if self.first_primary is None or self.last_primary is None: + return None + return self.last_primary - self.first_primary + + @property + def primary_change_percent(self) -> Optional[float]: + change = self.primary_change + if change is None or not self.first_primary: + return None + return change / self.first_primary * 100 + + +def summarize(history: Sequence[ExerciseSessionDTO]) -> ExerciseProgress: + """Progress of an exercise; history is newest first (as the repository returns it).""" + rows = [SessionRow(item, session_metrics(item.approaches)) for item in history] + weighted = any(row.metrics.e1rm is not None for row in rows) + + def primary(row: SessionRow) -> Optional[float]: + return row.metrics.e1rm if weighted else float(row.metrics.best_reps) + + def secondary(row: SessionRow) -> float: + return row.metrics.volume if weighted else float(row.metrics.total_reps) + + best_primary: Optional[Record] = None + best_secondary: Optional[Record] = None + first_primary: Optional[float] = None + last_primary: Optional[float] = None + + # Oldest first: a record is kept on the date it was first reached + for row in reversed(rows): + value = primary(row) + if value is not None: + if first_primary is None: + first_primary = value + last_primary = value + if best_primary is None or value > best_primary.value: + best_primary = Record(value, row.session.date) + extra = secondary(row) + if best_secondary is None or extra > best_secondary.value: + best_secondary = Record(extra, row.session.date) + + return ExerciseProgress( + weighted=weighted, + rows=rows, + max_weight=max((row.metrics.max_weight for row in rows), default=0.0), + best_primary=best_primary, + best_secondary=best_secondary, + first_primary=first_primary, + last_primary=last_primary, + ) diff --git a/app/core/database/models/__init__.py b/backend/app/core/parsers/__init__.py similarity index 100% rename from app/core/database/models/__init__.py rename to backend/app/core/parsers/__init__.py diff --git a/backend/app/core/parsers/apple.py b/backend/app/core/parsers/apple.py new file mode 100644 index 0000000..1843e40 --- /dev/null +++ b/backend/app/core/parsers/apple.py @@ -0,0 +1,52 @@ +import re +from typing import List, Optional + +from app.core.dto.training import TrainingDTO +from app.core.parsers.apple_mapper import unique_apple_exercises_mapper +from app.core.parsers.base import BaseNotesParser, TrainingHeader + + +class AppleNotesParser(BaseNotesParser): + """Parser for Apple Notes format training data.""" + + HEADER_PATTERN = re.compile( + r"^\*\*(?P\d+.\d+.\d+)\s\((?P.+?)(?:-(?P[^)]+))?\)\*\*" + ) + REDUNDANT_LINES = [ + "| | | |", + "|---|---|---|", + "|**Упражнение**|**Вес**|**Подходы**|", + ] + + def __init__(self): + super().__init__("complete_data/apple.md", unique_apple_exercises_mapper) + + def filter_training_data(self, training_data: str) -> str: + """Filter Apple-specific training data format.""" + cleaned_text = re.sub( + r"^\|(\s+|-*|\s-*\s)\|(\s+|-*|\s-*\s)\|(\s+|-*|\s-*\s)\|$", + "", + training_data, + flags=re.MULTILINE, + ) + cleaned_text = re.sub(r"^\n", "", cleaned_text, flags=re.MULTILINE) + lines = cleaned_text.splitlines() + filtered_lines = [line for line in lines if line not in self.REDUNDANT_LINES] + return "\n".join(filtered_lines) + + def parse_training_header(self, training_data_line: str) -> Optional[TrainingHeader]: + """Parse Apple Notes training header format.""" + match = self.HEADER_PATTERN.search(training_data_line) + if not match: + return None + year_counter = match.group("year_counter") + return TrainingHeader( + date=match.group("date").strip(), + trainer=match.group("trainer").strip(), + year_counter=year_counter.strip() if year_counter else None, + ) + + +def parse_training_data() -> List[TrainingDTO]: + """Parse Apple Notes training data.""" + return AppleNotesParser().parse_file() diff --git a/app/core/parsers/apple_mapper.py b/backend/app/core/parsers/apple_mapper.py similarity index 98% rename from app/core/parsers/apple_mapper.py rename to backend/app/core/parsers/apple_mapper.py index 49bbdd3..1d81355 100644 --- a/app/core/parsers/apple_mapper.py +++ b/backend/app/core/parsers/apple_mapper.py @@ -179,6 +179,7 @@ unique_apple_exercises_mapper = { "Жим от груди сидя в тренажере (около трицепс машины)": "Жим от груди сидя в тренажере (рычаги)", "Жим от груди сидя в тренажёре": "Жим от груди сидя в тренажере (рычаги)", "Жим от груди сидя в тренажёре (блинчики)": "Жим от груди сидя в тренажере (рычаги)", + "Жим от груди сидя в тренажере (блинчики)": "Жим от груди сидя в тренажере (рычаги)", "Силовой тренажер": "Жим от груди сидя в тренажере (рычаги)", # Жим от плеч вверх в тренажере (рычаги) @@ -239,6 +240,7 @@ unique_apple_exercises_mapper = { "Разгибание рук стоя с канатом": "Отжимание на трицепс в кроссовере", "Трацепс": "Отжимание на трицепс в кроссовере", "Трицепс вниз у стойки": "Отжимание на трицепс в кроссовере", + "Отжимания на трицепс в кроссовере": "Отжимание на трицепс в кроссовере", # Подтягивания "Подтягивание на заднюю дельту в петлях": "Подтягивания", @@ -253,6 +255,7 @@ unique_apple_exercises_mapper = { # Подъем гантелей на бицепс стоя "Гантели": "Подъем гантелей на бицепс стоя", "Жим гантелей стоя": "Подъем гантелей на бицепс стоя", + "Подъем гантелей стоя": "Подъем гантелей на бицепс стоя", "Сгибание рук с гантелями стоя": "Подъем гантелей на бицепс стоя", "Сгибание рук с гантелями стоя ям": "Подъем гантелей на бицепс стоя", diff --git a/backend/app/core/parsers/base.py b/backend/app/core/parsers/base.py new file mode 100644 index 0000000..30fdf4d --- /dev/null +++ b/backend/app/core/parsers/base.py @@ -0,0 +1,139 @@ +import logging +import os +from typing import Dict, List, NamedTuple, Optional + +from app.core.dto.training import ApproachDTO, ExerciseDTO, TrainingDTO +from app.core.utils.date_refactor import parse_training_date + +TABLE_HEADER_CELLS = {"Упражнение", "Вес", "Подходы"} + + +class ParseError(ValueError): + """Raised when a line looks like training data but can't be parsed.""" + + +class TrainingHeader(NamedTuple): + date: str + trainer: str + year_counter: Optional[str] = None + + +class BaseNotesParser: + """Base class for parsing training data from different note formats.""" + + def __init__(self, data_file_name: str, exercise_mapper: Optional[Dict[str, str]] = None): + self.data_file_name = data_file_name + self.project_root = os.getcwd() + self.exercise_mapper = exercise_mapper or {} + # Lines skipped by the last parse() call + self.errors: List[str] = [] + + def get_data_path(self) -> str: + return os.path.join(self.project_root, "data") + + def get_data_file_path(self, file_name: str) -> str: + return os.path.join(self.get_data_path(), file_name) + + def read_data_file(self, file_name: str) -> str: + path_to_file = self.get_data_file_path(file_name) + with open(path_to_file, "r", encoding="utf-8") as f: + content = f.read() + return content + + def serialize_exercise(self, reps: str, weight: str, name: str) -> ExerciseDTO: + """Convert raw exercise data into Exercise object with approaches.""" + try: + reps_list: List[int] = [int(rep) for rep in reps.split("-")] + # "15х2" (cyrillic х) and "15x2" mean the same: 15 kg per hand + weight_tokens: List[str] = weight.replace("х", "x").split("-") if weight else [] + # "0-12х2-16х2": the first approach may have no weight, so check all of them + weight_splitted: bool = any("x" in token for token in weight_tokens) + weight_list: List[float] = [float(w.split("x")[0]) for w in weight_tokens] + except ValueError as e: + raise ParseError(f"name={name!r}, weight={weight!r}, reps={reps!r}") from e + + # Last weight is reused for the remaining approaches + approaches = [ + ApproachDTO( + weight=weight_list[min(index, len(weight_list) - 1)] if weight_list else 0.0, + reps=rep, + ) + for index, rep in enumerate(reps_list) + ] + return ExerciseDTO( + name=name, approaches=approaches, splitted_weight=weight_splitted + ) + + def parse_exercise_row(self, exercise_line: str) -> Optional[ExerciseDTO]: + """Parse exercise data from a table row. + + Returns None for lines that are not exercise rows (headings, separators, text) + and raises ParseError for rows that are exercises but are malformed. + """ + if "|" not in exercise_line: + return None + cells: List[str] = [entry.strip() for entry in exercise_line.split("|")][1:-1] + if not cells or "---" in cells[0] or TABLE_HEADER_CELLS & set(cells): + return None + if len(cells) != 3: + raise ParseError(f"expected 3 columns, got {len(cells)}") + name, weight, reps = cells + return self.serialize_exercise(name=name, weight=weight, reps=reps) + + def filter_training_data(self, training_data: str) -> str: + """Filter and clean training data. Override in subclasses for specific formats.""" + return training_data + + def parse_training_header(self, training_data_line: str) -> Optional[TrainingHeader]: + """Parse training header. Override in subclasses for specific formats.""" + raise NotImplementedError("Subclasses must implement parse_training_header") + + def parse(self, data: str, map_names: bool = True) -> List[TrainingDTO]: + """Parse trainings from a string with notes.""" + self.errors = [] + lines = self.filter_training_data(data).splitlines() + trainings: List[TrainingDTO] = [] + current_training: Optional[TrainingDTO] = None + + for line_number, line in enumerate(lines, start=1): + header = self.parse_training_header(line) + if header: + try: + current_training = TrainingDTO( + date=parse_training_date(header.date), trainer=header.trainer + ) + except ValueError as e: + # Exercises below belong to an unknown training, skip them + current_training = None + self._report_error(line_number, line, e) + continue + trainings.append(current_training) + continue + + if current_training is None: + continue + try: + exercise = self.parse_exercise_row(line) + except ParseError as e: + self._report_error(line_number, line, e) + continue + if exercise: + current_training.exercises.append(exercise) + + return self.apply_exercise_mapping(trainings) if map_names else trainings + + def parse_file(self, map_names: bool = True) -> List[TrainingDTO]: + """Parse trainings from the parser's data file.""" + return self.parse(self.read_data_file(self.data_file_name), map_names=map_names) + + def _report_error(self, line_number: int, line: str, error: Exception) -> None: + message = f"line {line_number}: {error} ({line.strip()!r})" + self.errors.append(message) + logging.warning(f"{type(self).__name__} skipped {message}") + + def apply_exercise_mapping(self, trainings: List[TrainingDTO]) -> List[TrainingDTO]: + """Apply exercise name mapping to all trainings.""" + for training in trainings: + for exercise in training.exercises or []: + exercise.name = self.exercise_mapper.get(exercise.name, exercise.name) + return trainings diff --git a/backend/app/core/parsers/obsidian.py b/backend/app/core/parsers/obsidian.py new file mode 100644 index 0000000..814bf1d --- /dev/null +++ b/backend/app/core/parsers/obsidian.py @@ -0,0 +1,41 @@ +import re +from typing import List, Optional + +from app.core.dto.training import TrainingDTO +from app.core.parsers.obsidian_mapper import obsidian_unique_exercies_mapping +from app.core.parsers.base import BaseNotesParser, TrainingHeader + + +class ObsidianNotesParser(BaseNotesParser): + """Parser for Obsidian Notes format training data.""" + + HEADER_PATTERN = re.compile( + r"#\s(?P\d+.\d+.\d+)\s\((?P.+)-(?P.+)\)" + ) + + def __init__(self): + super().__init__( + data_file_name="complete_data/obsidian.md", + exercise_mapper=obsidian_unique_exercies_mapping, + ) + + def filter_training_data(self, training_data: str) -> str: + """Filter Obsidian-specific training data format.""" + cleaned_text = re.sub(r"^\s*?\n", "", training_data, flags=re.MULTILINE) + return cleaned_text + + def parse_training_header(self, training_data_line: str) -> Optional[TrainingHeader]: + """Parse Obsidian Notes training header format.""" + match = self.HEADER_PATTERN.search(training_data_line) + if not match: + return None + return TrainingHeader( + date=match.group("date").strip(), + trainer=match.group("trainer").strip(), + year_counter=match.group("year_counter").strip(), + ) + + +def parse_training_data() -> List[TrainingDTO]: + """Parse Obsidian Notes training data.""" + return ObsidianNotesParser().parse_file() diff --git a/app/core/parsers/obsidian_mapper.py b/backend/app/core/parsers/obsidian_mapper.py similarity index 100% rename from app/core/parsers/obsidian_mapper.py rename to backend/app/core/parsers/obsidian_mapper.py diff --git a/app/core/parsers/text_data.py b/backend/app/core/parsers/text_data.py similarity index 81% rename from app/core/parsers/text_data.py rename to backend/app/core/parsers/text_data.py index 294217c..0f6f655 100644 --- a/app/core/parsers/text_data.py +++ b/backend/app/core/parsers/text_data.py @@ -12,8 +12,8 @@ def parse_old_data() -> List[TrainingDTO]: obsidian_parser = ObsidianNotesParser() apple_parser = AppleNotesParser() - o_trainings = obsidian_parser.parse_and_map_training_data() - a_trainings = apple_parser.parse_and_map_training_data() + o_trainings = obsidian_parser.parse_file() + a_trainings = apple_parser.parse_file() return o_trainings + a_trainings diff --git a/app/core/dto/__init__.py b/backend/app/core/services/__init__.py similarity index 100% rename from app/core/dto/__init__.py rename to backend/app/core/services/__init__.py diff --git a/app/core/services/parser_service.py b/backend/app/core/services/parser_service.py similarity index 100% rename from app/core/services/parser_service.py rename to backend/app/core/services/parser_service.py diff --git a/app/core/parsers/__init__.py b/backend/app/core/utils/__init__.py similarity index 100% rename from app/core/parsers/__init__.py rename to backend/app/core/utils/__init__.py diff --git a/app/core/utils/date_refactor.py b/backend/app/core/utils/date_refactor.py similarity index 51% rename from app/core/utils/date_refactor.py rename to backend/app/core/utils/date_refactor.py index 29b6f22..bc160f2 100644 --- a/app/core/utils/date_refactor.py +++ b/backend/app/core/utils/date_refactor.py @@ -1,21 +1,23 @@ import re from datetime import date +DATE_PATTERNS = [ + r"^(?P[0-9]{2})\.(?P[0-9]{2})\.(?P[0-9]{4})", + r"^(?P[0-9]{2})\.(?P[0-9]{2})\.(?P[0-9]{2})(?![0-9])", + r"^(?P[0-9]{4})\-(?P[0-9]{2})\-(?P[0-9]{2})", + r"^(?P[0-9]{4})\.(?P[0-9]{2})\.(?P[0-9]{2})", +] + def parse_training_date(raw_date: str) -> date: - patterns = [ - r"^(?P[0-9]{2})\.(?P[0-9]{2})\.(?P[0-9]{4})*", - r"^(?P[0-9]{4})\-(?P[0-9]{2})\-(?P[0-9]{2})*", - r"^(?P[0-9]{4})\.(?P[0-9]{2})\.(?P[0-9]{2})*", - r"^(?P[0-9]{2})\.(?P[0-9]{2})\.(?P[0-9]{4})*", - ] - - for pattern in patterns: + for pattern in DATE_PATTERNS: match = re.match(pattern, raw_date) if match: day = int(match.group("day")) month = int(match.group("month")) year = int(match.group("year")) + if year < 100: + year += 2000 return date(year, month, day) raise ValueError(f"Не удалось найти дату в строке: {raw_date}") diff --git a/app/core/utils/enums.py b/backend/app/core/utils/enums.py similarity index 100% rename from app/core/utils/enums.py rename to backend/app/core/utils/enums.py diff --git a/app/main.py b/backend/app/main.py similarity index 58% rename from app/main.py rename to backend/app/main.py index d852401..051a8bc 100644 --- a/app/main.py +++ b/backend/app/main.py @@ -2,13 +2,10 @@ import logging from contextlib import asynccontextmanager from fastapi import FastAPI -from fastapi.staticfiles import StaticFiles -from fastapi.templating import Jinja2Templates -from app.api.v1.api import api_router -from app.api.v1.web import web_router +from app.api.v1.router import api_router from app.config import settings -from migrations.runner import MigrationRunner +from app.core.database.connection import create_engine, create_session_factory # TODO: Replace level with settings value logging.basicConfig( @@ -18,10 +15,11 @@ logging.basicConfig( @asynccontextmanager async def lifespan(app: FastAPI): - logging.info(f"\n\n{settings.get_postgres_database_url()}") - runner = MigrationRunner(settings.get_postgres_database_url()) - await runner.run_migrations() + # Schema is managed by Alembic: run `alembic upgrade head` before starting the app + engine = create_engine(settings.get_postgres_database_url()) + app.state.session_factory = create_session_factory(engine) yield + await engine.dispose() # TODO: (#ToLearn) Почитать про lifespan в FastAPI приложениях @@ -32,13 +30,8 @@ app = FastAPI( lifespan=lifespan, ) -app.mount("/static", StaticFiles(directory="app/static"), name="static") - -templates = Jinja2Templates(directory="app/templates") - # Include routers app.include_router(api_router, prefix="/api/v1") -app.include_router(web_router, prefix="/app") @app.get("/") diff --git a/app/sandbox.py b/backend/app/sandbox.py similarity index 87% rename from app/sandbox.py rename to backend/app/sandbox.py index b7956ab..cc93d9e 100644 --- a/app/sandbox.py +++ b/backend/app/sandbox.py @@ -5,10 +5,10 @@ from pprint import pprint om = ObsidianNotesParser() -o_mapped_trainings = om.parse_training_data() +o_mapped_trainings = om.parse_file() am = AppleNotesParser() -a_mapped_trainings = am.parse_training_data() +a_mapped_trainings = am.parse_file() combined_list = o_mapped_trainings + a_mapped_trainings print(len(combined_list)) diff --git a/app/core/services/__init__.py b/backend/app/schemas/__init__.py similarity index 100% rename from app/core/services/__init__.py rename to backend/app/schemas/__init__.py diff --git a/backend/app/schemas/exercises.py b/backend/app/schemas/exercises.py new file mode 100644 index 0000000..a9c39ab --- /dev/null +++ b/backend/app/schemas/exercises.py @@ -0,0 +1,40 @@ +from datetime import date +from typing import List, Optional + +from pydantic import BaseModel + +from app.core.dto.training import ApproachDTO + + +class SessionMetricsResponse(BaseModel): + max_weight: float + e1rm: Optional[float] + volume: float + total_reps: int + best_reps: int + + +class SessionRowResponse(BaseModel): + date: date + trainer: Optional[str] + splitted_weight: bool + approaches: List[ApproachDTO] + metrics: SessionMetricsResponse + + +class RecordResponse(BaseModel): + value: float + date: date + + +class ExerciseProgressResponse(BaseModel): + name: str + weighted: bool + max_weight: float + best_primary: Optional[RecordResponse] + best_secondary: Optional[RecordResponse] + first_primary: Optional[float] + last_primary: Optional[float] + primary_change: Optional[float] + primary_change_percent: Optional[float] + rows: List[SessionRowResponse] # newest first diff --git a/app/schemas/parser.py b/backend/app/schemas/parser.py similarity index 86% rename from app/schemas/parser.py rename to backend/app/schemas/parser.py index a9492c6..1ffcdea 100644 --- a/app/schemas/parser.py +++ b/backend/app/schemas/parser.py @@ -28,4 +28,5 @@ class ExerciseResponse(BaseModel): class ParseResponse(BaseModel): date: date + trainer: Optional[str] = None exercises: Optional[List[ExerciseResponse]] \ No newline at end of file diff --git a/data/Anomalies.md b/backend/data/Anomalies.md similarity index 100% rename from data/Anomalies.md rename to backend/data/Anomalies.md diff --git a/data/apple.md b/backend/data/apple.md similarity index 100% rename from data/apple.md rename to backend/data/apple.md diff --git a/data/apple_2.md b/backend/data/apple_2.md similarity index 100% rename from data/apple_2.md rename to backend/data/apple_2.md diff --git a/data/apple_3.md b/backend/data/apple_3.md similarity index 100% rename from data/apple_3.md rename to backend/data/apple_3.md diff --git a/data/apple_4.md b/backend/data/apple_4.md similarity index 100% rename from data/apple_4.md rename to backend/data/apple_4.md diff --git a/data/apple_5.md b/backend/data/apple_5.md similarity index 100% rename from data/apple_5.md rename to backend/data/apple_5.md diff --git a/data/apple_full.md b/backend/data/apple_full.md similarity index 100% rename from data/apple_full.md rename to backend/data/apple_full.md diff --git a/data/apple_original_backup.md b/backend/data/apple_original_backup.md similarity index 100% rename from data/apple_original_backup.md rename to backend/data/apple_original_backup.md diff --git a/data/complete_data/apple.md b/backend/data/complete_data/apple.md similarity index 98% rename from data/complete_data/apple.md rename to backend/data/complete_data/apple.md index 93d0c6d..a89baaa 100644 --- a/data/complete_data/apple.md +++ b/backend/data/complete_data/apple.md @@ -86,7 +86,7 @@ |---|---|---| |Подтягивания|Синяя резинка|7-5-4-4| |Тяга горизонтального блока|45|12-12-12-12| -|Тяга вертикального блока обратным хватом|49.8х2-45|10-10-9| +|Тяга вертикального блока обратным хватом|49.8-45|10-10-9| |Отжимания|+5|4-5-4| |Подъем ног в висе||10-10-8| @@ -304,7 +304,7 @@ |Жим от груди лежа (гантели)|16x2-18x2|12-8-10| |Сведение рук пек дек|37|12-12-12-12| |Подъем штанги стоя|20|12-11-9-9| -|Молоты стоя|20-20-18|10-9-12| +|Молоты стоя|20х2-20х2-18х2|10-9-12| **01.12.2023 (с56)**  @@ -402,7 +402,7 @@ |---|---|---| |Гравитрон|57-47|12-9-7-6| |Гребная тяга с упором в грудь|37|12-12-12| -|Тяга гантели в наклоне|18|12-12-12-12| +|Тяга гантели в наклоне|18х2|12-12-12-12| |Подъем штанги стоя|20|13-12-12| |Жим от плеч вверх (гантели)|20х2|7-7-12| @@ -463,7 +463,7 @@ |Упражнение|Вес|Подходы| |---|---|---| |Болгарские выпады|8x2-10x2|12-12-12| -|Румынская тяга|32|12-12-12| +|Румынская тяга|16х2|12-12-12| |Дельт-машина |47-57-47|12-10-12-12| |Дельт-машина|27|12-12-12-12| |Жим от плеч вверх (гантели)|14x2|12-12-11-10| @@ -526,7 +526,7 @@ |---|---|---| |Подтягивания|0-0-47-47|4-3-9-8| |Тяга штанги в наклоне|20-40|11-12-12-12| -|Тяга одной рукой в кроссовере на колене|41|12-12-12| +|Тяга одной рукой в кроссовере на колене|20.5х2|12-12-12| |Жим от груди сидя в тренажере (блинчики)|20x2|12-12-12| |Сведение рук пек дек|47-37|6-11-10| @@ -673,7 +673,7 @@ |Упражнение|Вес|Подходы| |---|---|---| |Подтягивания|0-0-0-47|5-4-3-11| -|Тяга гантелей к поясу лежа на животе на скамье 45°|28-36|12-12-12-12| +|Тяга гантелей к поясу лежа на животе на скамье 45°|14х2-18х2|12-12-12-12| |Гребная тяга с упором в грудь|37-47|12-11-10| |Жим от груди сидя в тренажере (блинчики)|20x2-25x2|12-12-12| |Сведение рук пек дек|47-37|11-9-12-11| @@ -683,7 +683,7 @@ |Упражнение|Вес|Подходы| |---|---|---| |Разгибание ног сидя|47-67-77|12-12-12-12| -|Румынская тяга|44|12-12-12| +|Румынская тяга|22х2|12-12-12| |Жим от плеч вверх (гантели)|14x2-16x2|12-12-12-10| |Дельт-машина|47|12-12-12| |Разведение рук в наклоне|8х2|12-12-12| @@ -866,7 +866,7 @@ |Упражнение|Вес|Подходы| |---|---|---| |Разгибание ног сидя|58-77-86|12-12-12-10-10| -|Румынская тяга|40|12-12-12-12| +|Румынская тяга|20х2|12-12-12-12| |Махи гантелей в стороны стоя|8х8-10х10|12-12-12| |Разведение рук пек дек|27|12-12-10| |Жим от плеч вверх (гантели)|16х2|12-12| @@ -878,7 +878,7 @@ |Подтягивания||8-6-4| |Тяга горизонтального блока|58.6-58.6-54|12-12-12-12| |Тяга вертикального блока обратным хватом|49.8|12-12-12| -|Жим от груди сидя в тренажере (блинчики)|67-87|12-12-10-10| +|Жим от груди сидя в тренажере (блинчики)|33.5х2-43.5х2|12-12-10-10| |Брусья|47|9-9-9| **10.07.2024 (с108-54)** @@ -1019,7 +1019,7 @@ |---|---|---| |Гравитрон|47-37|12-9-8| |Тяга горизонтального блока|48.9-54.4|12-12-12-12| -|Тяга гантели в наклоне|22-22-24|12-12-12| +|Тяга гантели в наклоне|22х2-22х2-24х2|12-12-12| |Жим от груди сидя в тренажере (кирпичики)|77|12-12-10-8| |Баттерфляй|57-47|10-12-12| @@ -1062,7 +1062,7 @@ |Гравитрон|47|12-12-9-10| |Гребная тяга с упором в грудь|47|12-13-11| |Тяга гантели в наклоне|20 на каждую руку|12-12-12| -|Жим от груди сидя в тренажере (блинчики)|30-50|14-12-12-12| +|Жим от груди сидя в тренажере (блинчики)|15х2-25х2|14-12-12-12| |Сведение рук пек дек|37|12-12-12| **08.05.2024 (solo-35)** diff --git a/data/complete_data/obsidian.md b/backend/data/complete_data/obsidian.md similarity index 73% rename from data/complete_data/obsidian.md rename to backend/data/complete_data/obsidian.md index ac063e5..b6ea55a 100644 --- a/data/complete_data/obsidian.md +++ b/backend/data/complete_data/obsidian.md @@ -1,3 +1,792 @@ +# 2026-10-21 (solo-107) + +| Упражнение | Вес | Подходы | +| ------------------------------------------- | -------- | ----------- | +| Подтягивания | 78.5 | 12-10-8-8 | +| Тяга Т-грифа | 40-45 | 12-8-8-8 | +| Жим от груди сидя в тренажере (блинчики) | 30х2 | 11-10-9-6 | +| Разгибание ног сидя | 100 | 12-12-10-12 | +| Разведение ног сидя в тренажёре (кирпичики) | 70-75-80 | 12-12-10 | + +# 2026-10-19 (solo-106) + +| Упражнение | Вес | Подходы | +| -------------------------------------- | ------ | ----------- | +| Подъем штанги стоя | 35 | 10-9-9-8 | +| Отжимания на трицепс в кроссовере | 55-60 | 12-12-10-10 | +| Разведение рук с гантелей из-за головы | 27.5 | 10-9-8-9 | +| Жим от плеч вверх (гантели) | 22.5х2 | 8-8-9-8 | +| Отведение рук пек дек (1 рука) | 22х2 | 12-12-12-12 | + +# 2026-10-17 (solo-105) + +| Упражнение | Вес | Подходы | +| ------------------------------------- | ------ | --------- | +| Подтягивания | 78.9 | 11-10-7-7 | +| Тяга вертикального блока узким хватом | 55 | 8-9-8-9 | +| Жим от груди лежа (гантели) | 27.5х2 | 10-8-7-7 | +| Сведение рук пек дек | 60 | 10-9-9-9 | +| Поворот гири на лямке | 12.5х2 | 10-11-11 | + +# 2026-10-15 (solo-104) + +| Упражнение | Вес | Подходы | +| -------------------------------------- | ----------- | ----------- | +| Подъем гантелей стоя | 20х2 | 12-11-10-10 | +| Молоты стоя | 20х2 | 11-11-10-10 | +| Разведение рук с гантелей из-за головы | 27.5 | 8-10-9-10 | +| Жим от плеч вверх (гантели) | 20х2-22.5х2 | 12-10-7-8 | +| Махи гантелей в стороны стоя | 15х2 | 10-10-9-10 | + +# 2026-10-12 (solo-103) + +| Упражнение | Вес | Подходы | +| ----------------------------------------- | ------ | --------- | +| Подтягивания | 79.5 | 11-10-7-7 | +| Тяга горизонтального блока | 55-65 | 12-8-8-9 | +| Жим от груди лежа (гантели) | 27.5х2 | 10-8-8-7 | +| Жим от груди сидя в тренажере (кирпичики) | 70-80 | 12-7-8-8 | +| Пресс на скамье | | 12-12-12 | + +# 2026-10-10 (solo-102) + +| Упражнение | Вес | Подходы | +| ---------------------------------------- | ------ | ----------- | +| Бицепс в тренажере | 25 | 10-8-8-7 | +| Подъем гантелей стоя | 17.5х2 | 12-12-10-10 | +| Французский жим лежа (штанга) | 30 | 10-10-7-8 | +| Жим от плеч вверх в тренажере (блинчики) | 17.5х2 | 8-7-8-7 | +| Поворот гири на лямке | 12х2 | 10-10-9-9 | + +# 2026-10-07 (solo-101) + +| Упражнение | Вес | Подходы | +| -------------------------------------- | ------------------- | ----------- | +| Подтягивания | 79 | 10-10-8-8 | +| Гребная тяга с упором в грудь (1 рука) | 15х2-20х2-25х2-30х2 | 12-12-12-12 | +| Жим от груди лежа (гантели) | 27.5х2 | 10-8-7-6 | +| Разгибание ног сидя | 90-100 | 12-12-11-11 | +| Икроножные сидя | 40-50 | 12-12-12 | + +# 2026-10-05 (solo-100) + +| Упражнение | Вес | Подходы | +| -------------------------------------- | ---------- | --------- | +| Бицепс в тренажере | 25 | 10-8-8-7 | +| Французский жим лежа (штанга) | 30 | 10-10-9-7 | +| Разведение рук с гантелей из-за головы | 25-25-27.5 | 11-12-8-7 | +| Жим от плеч вверх (гантели) | 22.5x2 | 8-8-8-7 | +| Поворот гири на лямке | 10х2-12х2 | 12-10-7-8 | +# 2026-10-03 (solo-99) + +| Упражнение | Вес | Подходы | +| ---------------------------------------- | ----------- | ----------- | +| Подтягивания | 79.3 | 10-8-7-7 | +| Тяга гантели в наклоне | 27.5х2-30х2 | 12-9-10-10 | +| Жим от груди сидя в тренажере (блинчики) | 30х2 | 10-10-7-7 | +| Сведение рук пек дек | 55 | 10-10-10-10 | +| Поворот гири на лямке | 10х2 | 12-12-12-12 | + +# 2026-10-01 (solo-98) + +| Упражнение | Вес | Подходы | +| -------------------------------------- | ----------- | ----------- | +| Подъем гантелей стоя | 17.5x2-20x2 | 12-10-10-10 | +| Французский жим лежа (штанга) | 30 | 9-10-8-7 | +| Разведение рук с гантелей из-за головы | 22.5 | 10-10-10-10 | +| Жим от плеч вверх (гантели) | 20х2-22.5х2 | 12-8-6-7 | +| Махи гантелей в стороны стоя | 12.5х2-15х2 | 12-11-8 | + +# 2026-09-28 (solo-97) + +| Упражнение | Вес | Подходы | +| ------------------------------------ | ----- | ----------- | +| Подтягивания | 79.3 | 9-8-8-6 | +| Тяга вертикального блока (кирпичики) | 80-90 | 12-9-10-9 | +| Жим от груди лежа (гантели) | 25х2 | 10-9-8-7 | +| Сведение рук пек дек | 55 | 11-9-8-9 | +| Пресс на скамье | | 12-12-12-12 | + +# 2026-09-19 (solo-96) + +| Упражнение | Вес | Подходы | +| -------------------------------------- | ------ | ----------- | +| Бицепс в тренажере | 25 | 11-8-7-7 | +| Молоты стоя | 17.5х2 | 11-11-12-10 | +| Разведение рук с гантелей из-за головы | 25 | 8-9-10-11 | +| Жим от плеч вверх (гантели) | 20х2 | 12-10-9-10 | +| Махи гантелей в стороны стоя | 15х2 | 10-11-10-11 | + +# 2026-09-14 (solo-95) + +| Упражнение | Вес | Подходы | +| ---------------------------------------- | ------------------ | ---------- | +| Подтягивания | 80 | 10-10-8-7 | +| Тяга Т-грифа | 40-45 | 12-10-9-8 | +| Жим от груди сидя в тренажере (блинчики) | 30х2 | 12-10-8-8 | +| Жим от груди лежа (гантели) | 27.5х2-27.5х2-25х2 | 6-6-7-7 | +| Поворот гири на лямке | 10х2-12х2-10х2 | 12-7-12-12 | + +# 2026-09-12 (solo-94) + +| Упражнение | Вес | Подходы | +| --------------------------------- | ----- | ----------- | +| Бицепс в тренажере | 25 | 11-9-7-7 | +| Отведение рук пек дек | 35-40 | 12-12-10-11 | +| Французский жим лежа (штанга) | 30 | 8-8-8-8 | +| Отжимания на трицепс в кроссовере | 50 | 12-12-12-12 | +| Пресс на скамье | | 14-12-12-12 | + +# 2026-09-09 (solo-93) + +| Упражнение | Вес | Подходы | +| ------------------------------------ | --------- | ----------- | +| Подтягивания | 79.4 | 11-9-7-7 | +| Тяга вертикального блока (кирпичики) | 50-55 | 12-10-10-10 | +| Жим от груди лежа (гантели) | 27.5х2 | 10-8-8-7 | +| Отжимания на брусьях | 79.4 | 8-7-7-7 | +| Махи рукой в кроссовере | 20х2-21х2 | 12-10-11-11 | + +# 2026-09-07 (solo-92) + +| Упражнение | Вес | Подходы | +| -------------------------------------- | ---- | ----------- | +| Подъем штанги стоя | 35 | 11-9-8-8 | +| Французский жим лежа (штанга) | 30 | 12-10-8-6 | +| Разведение рук с гантелей из-за головы | 25 | 10-10-8-8 | +| Жим от плеч вверх (гантели) | 20х2 | 11-11-8-11 | +| Пресс на скамье | | 12-12-12-12 | + +# 2026-09-05 (solo-91) + +| Упражнение | Вес | Подходы | +| ----------------------------------------- | ----- | ----------- | +| Подтягивания | 79.9 | 12-8-6-6 | +| Тяга вертикального блока узким хватом | 50 | 12-11-9-10 | +| Сведение рук пек дек | 55 | 12-12-12-12 | +| Жим от груди сидя в тренажере (кирпичики) | 60-65 | 12-10-11-12 | +| Жим от плеч вверх в тренажере (кирпичики) | 35-40 | 12-10-10-10 | + +# 2026-08-20 (solo-90) + +| Упражнение | Вес | Подходы | +| -------------------------------------- | ------ | ----------- | +| Бицепс в тренажере | 25 | 12-10-10-9 | +| Молоты стоя | 17.5х2 | 12-12-12-12 | +| Французский жим лежа (штанга) | 30 | 10-10-8-5 | +| Разведение рук с гантелей из-за головы | 22.5 | 12-12-12-12 | +| Поворот гири на лямке | 10х2 | 12-12-12-12 | + +# 2026-08-17 (solo-89) + +| Упражнение | Вес | Подходы | +| ------------------------------------- | ------ | ---------- | +| Подтягивания | 78.3 | 12-10-8-7 | +| Тяга вертикального блока узким хватом | 50-55 | 12-10-9-9 | +| Жим от груди лежа (гантели) | 27.5x2 | 10-8-8-6 | +| Сведение рук пек дек | 60 | 10-10-10-9 | +| Махи рукой в кроссовере | 20х2 | 12-12-12 | + +# 2026-08-15 (solo-88) + +| Упражнение | Вес | Подходы | +| ------------------------------------ | ----------- | ----------- | +| Подъем штанги стоя | 35-35-30 | 9-7-12-9 | +| Подъем гантелей стоя обратным хватом | 15х2-17.5х2 | 12-12-12-12 | +| Французский жим лежа (штанга) | 30 | 10-10-9-7 | +| Жим от плеч вверх (гантели) | 22.5х2-20х2 | 8-10-10-10 | +| Махи гантелей в стороны стоя | 15х2 | 12-11-11-11 | + +# 2026-08-13 (solo-87) + +| Упражнение | Вес | Подходы | +| ---------------------------------------- | ------ | ----------- | +| Подтягивания | 77.6 | 12-8-8-7 | +| Тяга Т-грифа | 45 | 10-9-10-9 | +| Жим от груди лежа (гантели) | 27.5х2 | 10-8-7-8 | +| Жим от груди сидя в тренажере (блинчики) | 30х2 | 8-9-8-8 | +| Пресс на скамье | | 12-12-12-12 | + +# 2026-08-10 (solo-86) + +| Упражнение | Вес | Подходы | +| -------------------------------------- | ------ | ----------- | +| Подъем гантелей стоя | 20х2 | 12-12-10-10 | +| Французский жим лежа (штанга) | 30 | 10-9-8-7 | +| Разведение рук с гантелей из-за головы | 25 | 12-12-12-12 | +| Жим от плеч вверх (гантели) | 22.5х2 | 10-9-7-7 | +| Поворот гири на лямке | 10х2 | 12-12-12-12 | + +# 2026-08-08 (solo-85) + +| Упражнение | Вес | Подходы | +| ---------------------------------------- | ----- | ----------- | +| Подтягивания | 78.1 | 12-10-7-7 | +| Тяга вертикального блока узким хватом | 50-55 | 12-10-11-10 | +| Жим от груди сидя в тренажере (блинчики) | 30х2 | 12-9-8-7 | +| Сведение рук пек дек | 60 | 10-11-10-9 | +| Пресс на скамье | | 12-12-12-12 | + +# 2026-08-06 (solo-84) + +| Упражнение | Вес | Подходы | +| ---------------------------------------- | ----------- | ----------- | +| Подъем гантелей стоя | 20х2 | 12-12-10-10 | +| Французский жим лежа (штанга) | 30 | 10-10-10-8 | +| Разведение рук с гантелей из-за головы | 25 | 9-10-10-12 | +| Жим от плеч вверх в тренажере (блинчики) | 15х2-17.5х2 | 12-10-7-9 | +| Махи рукой в кроссовере | 20х2 | 12-12-12-12 | + +# 2026-08-03 (solo-83) + +| Упражнение | Вес | Подходы | +| ----------------------------------------- | ----------- | ---------- | +| Подтягивания | 78.9 | 12-12-9-7 | +| Тяга Т-грифа | 45 | 10-9-10-10 | +| Жим от груди лежа (гантели) | 27.5х2 | 10-9-8-7 | +| Сведение рук пек дек | 65 | 9-9-8-8 | +| Жим от плеч вверх в тренажере (кирпичики) | 40-45-45-40 | 12-9-6 | + +# 2026-08-01 (solo-82) + +| Упражнение | Вес | Подходы | +| -------------------------------------- | -------- | ----------- | +| Подъем гантелей стоя | 20х2 | 12-10-10-10 | +| Бицепс в тренажере | 25-25-20 | 10-7-10-10 | +| Отжимания на трицепс в кроссовере | 65-60 | 10-12-11-10 | +| Разведение рук с гантелей из-за головы | 25 | 8-10-10-8 | +| Поворот гири на лямке | 10х2 | 12-12-12 | + +# 2026-07-29 (solo-81) + +| Упражнение | Вес | Подходы | +| ---------------------------------------- | ---- | ---------- | +| Подтягивания | 78.6 | 11-10-9-8 | +| Тяга вертикального блока узким хватом | 60 | 10-10-9-7 | +| Жим от груди сидя в тренажере (блинчики) | 30х2 | 12-9-8-7 | +| Сведение рук пек дек | 60 | 10-9-10-10 | +| Пресс на скамье | | 12-12-12 | + +# 2026-07-24 (solo-80) + +| Упражнение | Вес | Подходы | +| -------------------------------------- | ----------- | ----------- | +| Бицепс в тренажере | 25 | 12-10-8-8 | +| Молоты стоя | 15х2-17.5х2 | 12-12-12-12 | +| Французский жим лежа (штанга) | 30 | 12-10-8-8 | +| Разведение рук с гантелей из-за головы | 25 | 8-10-10-10 | +| Поворот гири на лямке | 10х2 | 12-12-12 | + +# 2026-07-22 (solo-79) + +| Упражнение | Вес | Подходы | +| ----------------------------------------- | -------- | ----------- | +| Подтягивания | 78 | 12-10-9-8 | +| Тяга Т-грифа | 40 | 11-12-11-9 | +| Жим от груди сидя в тренажере (кирпичики) | 60-70-75 | 15-12-10-9 | +| Жим от груди лежа (гантели) | 25х2 | 9-8-9-8 | +| Пресс на скамье | | 12-12-12-12 | + +# 2026-07-20 (solo-78) + +| Упражнение | Вес | Подходы | +| ---------------------------------------- | ---- | ----------- | +| Подъем штанги стоя | 35 | 10-10-8-8 | +| Французский жим лежа (штанга) | 30 | 12-10-10-8 | +| Разведение рук с гантелей из-за головы | 25 | 10-12-11-10 | +| Жим от плеч вверх в тренажере (блинчики) | 15х2 | 12-12-9-10 | +| Поворот гири на лямке | 10х2 | 12-12-12-12 | + +# 2026-07-18 (solo-77) + +| Упражнение | Вес | Подходы | +| ------------------------------------------- | -------- | ----------- | +| Подтягивания | 78 | 11-9-8-7 | +| Тяга горизонтального блока | 50-60-65 | 12-12-9-9 | +| Разведение рук пек дек | 35 | 12-12-9-10 | +| Сгибание ног лежа | 45-50 | 12-12-10-8 | +| Разведение ног сидя в тренажёре (кирпичики) | 85 | 12-12-12-12 | + +# 2026-07-16 (solo-76) + +| Упражнение | Вес | Подходы | +| ----------------------------------------- | ----------- | ----------- | +| Подъем гантелей стоя | 17.5х2-20х2 | 12-11-10-10 | +| Отжимания на трицепс в кроссовере | 50-55 | 12-12-12-12 | +| Бицепс в тренажере | 20-25 | 12-10-8-7 | +| Жим от плеч вверх в тренажере (кирпичики) | 40-45 | 12-12-9-8 | +| Махи гантелей в стороны стоя | 12.5х2 | 12-12-12-12 | + +# 2026-07-13 (solo-75) + +| Упражнение | Вес | Подходы | +| ---------------------------------------- | --------- | ---------- | +| Подтягивания | 78.1 | 12-10-8-7 | +| Тяга вертикального блока узким хватом | 50-55 | 12-10-10-8 | +| Жим от груди сидя в тренажере (блинчики) | 25х2-30х2 | 12-10-8-6 | +| Брусья | 78.1 | 10-8-10-8 | +| Пресс на скамье | | 12-12-12 | + +# 2026-07-11 (solo-74) + +| Упражнение | Вес | Подходы | +| ------------------------------------------- | -------- | ----------- | +| Подъем штанги стоя | 35 | 10-9-8-7 | +| Французский жим лежа (штанга) | 30 | 10-10-9-7 | +| Поворот гири на лямке | 10х2 | 12-12-12-12 | +| Разведение ног сидя в тренажёре (кирпичики) | 80-80-85 | 12-12-12-12 | +| Икроножные сидя | 40-50-55 | 12-12-12-12 | + +# 2026-07-09 (solo-73) + +| Упражнение | Вес | Подходы | +| ----------------------------------------- | ------ | ----------- | +| Подтягивания | 78.1 | 12-9-8-7 | +| Тяга Т-грифа | 40 | 10-10-10-10 | +| Жим от груди сидя в тренажере (кирпичики) | 70-80 | 12-12-8-10 | +| Жим от груди лежа (гантели) | 22.5х2 | 10-10-10-10 | +| Пресс на скамье | | 12-12-12-12 | + +# 2026-07-06 (solo-72) + +| Упражнение | Вес | Подходы | +| ----------------------------------------- | ------- | ----------- | +| Разгибание ног сидя | 100-110 | 12-10-12-10 | +| Гиперэкстензия | 15 | 12-12-9-9 | +| Подъем гантелей стоя | 17.5х2 | 12-12-10-10 | +| Французский жим лежа (штанга) | 30 | 10-9-8-7 | +| Жим от плеч вверх в тренажере (кирпичики) | 50-45 | 7-9 | + +# 2026-07-04 (solo-71) + +| Упражнение | Вес | Подходы | +| ----------------------------------------- | ----- | ----------- | +| Подтягивания | 78.4 | 10-8-7-6 | +| Гребная тяга с упором в грудь | 80-85 | 12-10-10-10 | +| Жим от груди сидя в тренажере (кирпичики) | 70-75 | 12-10-10-7 | +| Сведение рук пек дек | 55 | 12-10-10-10 | +| Пресс на скамье | | 14-12-12 | + +# 2026-07-02 (solo-70) + +| Упражнение | Вес | Подходы | +| -------------------------------------- | ---- | ----------- | +| Бицепс в тренажере | 25 | 12-8-8-7 | +| Французский жим лежа (штанга) | 30 | 10-9-8-8 | +| Разведение рук с гантелей из-за головы | 25 | 9-10-10-8 | +| Жим от плеч вверх (гантели) | 20х2 | 12-10-10-8 | +| Поворот гири на лямке | 10х2 | 12-12-11-11 | + +# 2026-06-29 (solo-69) + +| Упражнение | Вес | Подходы | +| ---------------------------------------- | ---- | ----------- | +| Подтягивания | 78.1 | 12-11-9-8 | +| Тяга вертикального блока узким хватом | 50 | 12-10-11-10 | +| Жим от груди сидя в тренажере (блинчики) | 25х2 | 12-12-10-9 | +| Сведение рук пек дек | 55 | 11-11-10-11 | +| Пресс на скамье | | 12-12-12-12 | + +# 2026-06-26 (solo-68) + +| Упражнение | Вес | Подходы | +| ----------------------------- | ------ | ----------- | +| Подъем гантелей стоя | 17.5х2 | 12-12-12-12 | +| Молоты стоя | 17.5х2 | 12-12-12-12 | +| Французский жим лежа (штанга) | 30 | 9-9-7-7 | +| Махи гантелей в стороны стоя | 15х2 | 12-11-11-10 | +| Поворот гири на лямке | 10х2 | 12-12-12-12 | + +# 2026-06-24 (solo-67) + +| Упражнение | Вес | Подходы | +| ---------------------------------------- | ----- | ----------- | +| Подтягивания | 77.5 | 12-10-8-7 | +| Тяга горизонтального блока | 55-65 | 12-9-9-9 | +| Сведение рук пек дек | 50-55 | 12-12-12-10 | +| Жим от груди сидя в тренажере (блинчики) | 25х2 | 9-10-8-10 | +| Пресс на скамье | | 12-12-12-12 | + +# 2026-06-22 (solo-66) + +| Упражнение | Вес | Подходы | +| -------------------------------------- | ------ | ----------- | +| Подъем штанги стоя | 30-35 | 12-7-8-7 | +| Бицепс в тренажере | 25-20 | 10-10-10-9 | +| Французский жим лежа (штанга) | 30 | 11-10-8-6 | +| Разведение рук с гантелей из-за головы | 25 | 10-10-9-8 | +| Махи гантелей в стороны стоя | 12.5х2 | 12-12-12-12 | + +# 2026-06-22 (solo-66) + +| Упражнение | Вес | Подходы | +| -------------------------------------- | ------ | ----------- | +| Подъем штанги стоя | 30-35 | 12-7-8-7 | +| Бицепс в тренажере | 25-20 | 10-10-10-9 | +| Французский жим лежа (штанга) | 30 | 11-10-8-6 | +| Разведение рук с гантелей из-за головы | 25 | 10-10-9-8 | +| Махи гантелей в стороны стоя | 12.5х2 | 12-12-12-12 | + +# 2026-06-20 (solo-65) + +| Упражнение | Вес | Подходы | +| ------------------------------------------- | ----- | ----------- | +| Подтягивания | 78 | 12-10-8-7 | +| Тяга Т-грифа | 30-40 | 12-10-10-10 | +| Сгибание ног лежа | 45-50 | 12-11-10-7 | +| Разведение ног сидя в тренажёре (кирпичики) | 50-80 | 12-12-12-12 | +| Икроножные сидя | 40-45 | 12-12-12-12 | + +# 2026-06-17 (solo-64) + +| Упражнение | Вес | Подходы | +| ---------------------------------------- | -------- | ----------- | +| Подъем штанги стоя | 30-35-30 | 12-7-11-9 | +| Разведение рук с гантелей из-за головы | 22.5-25 | 12-12-12-12 | +| Отжимания на трицепс в кроссовере | 55 | 12-12-11-10 | +| Махи рукой в кроссовере | 20х2 | 12-12-12-12 | +| Жим от плеч вверх в тренажере (блинчики) | 15х2 | 12-11-6 | + +# 2026-06-15 (solo-63) + +| Упражнение | Вес | Подходы | +| ----------------------------------------- | -------- | ----------- | +| Подтягивания | 78.5 | 13-9-8-7 | +| Тяга вертикального блока узким хватом | 50-60-55 | 12-8-9-9 | +| Жим от груди сидя в тренажере (кирпичики) | 65-75-80 | 12-12-11-8 | +| Гиперэкстензия | 15 | 12-12-12-10 | +| Разгибание ног сидя | 90-100 | 12-12-9-10 | + +# 2026-06-11 (solo-62) + +| Упражнение | Вес | Подходы | +| ----------------------------------------- | ---- | ----------- | +| Подтягивания обратным хватом | 78 | 10-9-8-6 | +| Бицепс в тренажере | 25 | 7-8-7-7 | +| Французский жим лежа (штанга) | 30 | 11-9-8-9 | +| Махи рукой в кроссовере | 20х2 | 12-12-12-12 | +| Жим от плеч вверх в тренажере (кирпичики) | 40 | 12-11-11-7 | + +# 2026-06-08 (solo-61) + +| Упражнение | Вес | Подходы | +| ----------------------------------------- | -------- | ----------- | +| Подтягивания | 78.1 | 13-11-9-6 | +| Гребная тяга с упором в грудь | 60-70-75 | 15-12-12-12 | +| Жим от груди сидя в тренажере (кирпичики) | 70-75 | 12-12-10-8 | +| Сведение рук пек дек | 60 | 8-8-8-9 | +| Подъем ног в висе | 78.1 | 10-10-7 | + +# 2026-06-06 (solo-60) + +| Упражнение | Вес | Подходы | +| ---------------------------------------- | ----------- | --------- | +| Подъем штанги стоя | 30-35 | 12-7-7-7 | +| Молоты стоя | 17.5х2-20х2 | 12-9-9-10 | +| Разведение рук с гантелей из-за головы | 25-27.5 | 12-8-8-7 | +| Жим от плеч вверх в тренажере (блинчики) | 15х2 | 12-10-9-8 | +| Махи гантелей в стороны стоя | 12.5x2-15x2 | 12-11-9 | + +# 2026-06-04 (solo-59) + +| Упражнение | Вес | Подходы | +| ------------------------ | ----------- | ----------- | +| Подтягивания | 77.9 | 11-8-8-6 | +| Тяга вертикального блока | 50-55 | 12-11-11-11 | +| Тяга Т-грифа | 35-40 | 12-10-11-11 | +| Сгибание ног лежа | 50 | 12-12-11-9 | +| Икроножные сидя | 40-45-45-50 | 12-11-12-12 | + +# 2026-06-01 (solo-58) + +| Упражнение | Вес | Подходы | +| -------------------------------------- | -------- | ----------- | +| Подтягивания обратным хватом | 78.3 | 10-9-6-6 | +| Бицепс в тренажере | 25-25-20 | 9-7-11-10 | +| Разведение рук с гантелей из-за головы | 22.5 | 10-10-10-10 | +| Брусья (гравитрон) | 40-30 | 12-11-10-9 | +| Поворот гири на лямке | 10х2 | 12-12-11 | + +# 2026-05-30 (solo-57) + +| Упражнение | Вес | Подходы | +| ---------------------------------------- | ----------- | --------- | +| Подтягивания | 78.2 | 11-5-5-6 | +| Тяга горизонтального блока | 60-70-65-70 | 12-7-10-7 | +| Отведение рук пек дек | 30-35 | 12-9-10-9 | +| Сведение рук пек дек | 65-70-65 | 12-7-11-7 | +| Жим от груди сидя в тренажере (блинчики) | 20х2 | 12-12-12 | + +# 2026-05-28 (solo-56) + +| Упражнение | Вес | Подходы | +| ---------------------------------------- | -------- | ----------- | +| Подъем штанги стоя | 30-35-30 | 12-6-12-9 | +| Французский жим лежа (штанга) | 30 | 8-8-7-7 | +| Разведение рук с гантелей из-за головы | 20-22.5 | 11-9-9-8 | +| Жим от плеч вверх в тренажере (блинчики) | 15х2 | 10-10-9-9 | +| Махи рукой в кроссовере | 20х2 | 12-12-12-12 | + +# 2026-05-25 (solo-55) + +| Упражнение | Вес | Подходы | +| ------------------- | -------- | ----------- | +| Подтягивания | 77.8 | 11-8-7-7 | +| Тяга Т-грифа | 40-45 | 12-9-9-10 | +| Икроножные сидя | 30-40-45 | 12-12-12-12 | +| Разгибание ног сидя | 90-100 | 12-12-11-12 | +| Пресс на скамье | | 13-12 | + +# 2026-05-23 (solo-54) + +| Упражнение | Вес | Подходы | +| ---------------------------------------- | -------- | ----------- | +| Бицепс в тренажере | 25 | 10-8-8-8 | +| Подъем гантелей стоя обратным хватом | 17.5х2 | 12-12-12-12 | +| Французский жим лежа (штанга) | 30-30-25 | 8-8-11-8 | +| Жим от плеч вверх в тренажере (блинчики) | 15х2 | 10-8-9-7 | +| Поворот гири на лямке | 10х2 | 12-10-10-11 | + +# 2026-05-21 (solo-53) + +| Упражнение | Вес | Подходы | +| ---------------------------------------- | -------------- | ----------- | +| Подтягивания | 77.8 | 11-9-6-7 | +| Тяга вертикального блока узким хватом | 55 | 11-10-9-7 | +| Жим от груди сидя в тренажере (блинчики) | 30х2-30х2-35х2 | 10-10-7-6 | +| Сведение рук пек дек | 55 | 11-11-10-10 | +| Махи рукой в кроссовере | 22х2-21х2 | 10-10-10-11 | + +# 2026-05-18 (solo-52) + +| Упражнение | Вес | Подходы | +| -------------------------------------- | ------ | ----------- | +| Подъем штанги стоя | 35-30 | 10-12-10-10 | +| Молоты стоя | 17.5х2 | 12-11-12-12 | +| Французский жим лежа (штанга) | 30 | 10-10-8-7 | +| Разведение рук с гантелей из-за головы | 22.5 | 9-10-9-8 | +| Пресс на скамье | 79.1 | 13-12-12-12 | + +# 2026-05-16 (solo-51) + +| Упражнение | Вес | Подходы | +| ---------------------------------------- | ----------- | ----------- | +| Подтягивания | 78 | 12-8-8-6 | +| Тяга Т-грифа | 40-45 | 12-9-8-8 | +| Жим от груди лежа (гантели) | 25х2-27.5х2 | 12-8-8-7 | +| Жим от груди сидя в тренажере (блинчики) | 30х2 | 8-7-7-7 | +| Махи рукой в кроссовере | 20х2 | 12-12-11-12 | + +# 2026-05-14 (solo-50) + +| Упражнение | Вес | Подходы | +| -------------------------------------- | ----------- | ----------- | +| Подъем гантелей стоя | 17.5х2-20х2 | 12-12-9-10 | +| Отжимания на трицепс в кроссовере | 65-65-60 | 10-10-12-10 | +| Разведение рук с гантелей из-за головы | 22.5 | 10-10-9-8 | +| Жим от плеч вверх (гантели) | 22.5х2 | 7-8-8-7 | +| Поворот гири на лямке | 10х2 | 12-11-10-11 | + +# 2026-05-11 (solo-49) + +| Упражнение | Вес | Подходы | +| -------------------------- | ----- | ----------- | +| Подтягивания | 77.6 | 10-9-7-7 | +| Тяга горизонтального блока | 60-65 | 12-10-10-10 | +| Брусья | 77.6 | 10-10-9-6 | +| Сведение рук пек дек | 65 | 9-7-7-6 | +| Пресс на скамье | | 12-12-12-12 | + +# 2026-05-09 (solo-48) + +| Упражнение | Вес | Подходы | +| ---------------------------------------- | ------------------ | ----------- | +| Подъем гантелей стоя | 17.5х2-17.5х2-20х2 | 12-12-8-8 | +| Бицепс в тренажере | 25-20 | 8-10-10-10 | +| Французский жим лежа (штанга) | 30 | 9-9-7-7 | +| Жим от плеч вверх в тренажере (блинчики) | 17.5х2 | 7-7-7-7 | +| Махи рукой в кроссовере | 20х2 | 12-12-12-12 | + +# 2026-05-07 (solo-47) + +| Упражнение | Вес | Подходы | +| ----------------------------------------- | ------- | ---------- | +| Подтягивания | 78 | 12-10-7-6 | +| Тяга вертикального блока узким хватом | 50-55 | 12-8-8-8 | +| Приседания | 30-32.5 | 12-9-8-8 | +| Икроножные сидя | 45 | 10-13-9-12 | +| Жим от груди сидя в тренажере (кирпичики) | 70-80 | 12-11-10 | + +# 2026-05-04 (solo-46) + +| Упражнение | Вес | Подходы | +| -------------------------------------- | ------- | ---------- | +| Подъем штанги стоя | 35 | 12-10-8-8 | +| Подъем гантелей стоя | 17.5х2 | 10-10-10-9 | +| Разведение рук с гантелей из-за головы | 22.5-25 | 12-11-11-8 | +| Жим от плеч вверх (гантели) | 22.5х2 | 9-10-8-8 | +| Махи гантелей в стороны стоя | 15х2 | 12-11-11 | + +# 2026-05-02 (solo-46) + +| Упражнение | Вес | Подходы | +| ---------------------------------------- | --------------- | ---------- | +| Подтягивания | 77.4 | 10-8-6-7 | +| Тяга Т-грифа | 35-45 | 12-7-8-8 | +| Жим от груди сидя в тренажере (блинчики) | 15х2-25х2-35х2 | 15-12-6-6 | +| Сведение рук пек дек | 60 | 10-9-9-9 | +| Гакк-приседания | 0-5х2-10х2-15х2 | 12-12-12-9 | + +# 2026-04-30 (solo-45) + +| Упражнение | Вес | Подходы | +| ---------------------------------------- | ----------- | ----------- | +| Подтягивания обратным хватом | 77.6 | 9-7-7-7 | +| Бицепс в тренажере | 25 | 8-7-8-7 | +| Французский жим лежа (штанга) | 30 | 9-8-7-6 | +| Жим от плеч вверх в тренажере (блинчики) | 15х2-17.5х2 | 11-8-8-6 | +| Поворот гири на лямке | 8х2 | 12-12-12-12 | + +# 2026-04-27 (solo-44) + +| Упражнение | Вес | Подходы | +| -------------------------- | -------- | ---------- | +| Подтягивания | 78.1 | 12-9-7-6 | +| Тяга горизонтального блока | 65-70-65 | 12-7-11-9 | +| Сгибание ног сидя | 50-60 | 12-12-10-9 | +| Икроножные сидя | 35-40-45 | 12-12-10-9 | +| Махи рукой в кроссовере | 20х2 | 12-12-12 | + +# 2026-04-25 (solo-43) + +| Упражнение | Вес | Подходы | +| ----------------------------- | ------------------ | ----------- | +| Подъем штанги стоя | 30 | 12-12-11-12 | +| Молоты стоя | 17.5х2-20х2-17.5x2 | 12-8-12-12 | +| Французский жим лежа (штанга) | 30-23-28 | 12-12-8-7 | +| Гиперэкстензия | 15 | 12-12-10-9 | +| Пресс на скамье | | 12-12-12-12 | + +# 2026-04-23 (solo-42) + +| Упражнение | Вес | Подходы | +| ------------------- | ----------- | ----------- | +| Разгибание ног сидя | 90-100-110 | 12-12-10-11 | +| Жим ногами | 100-110-120 | 12-12-9-10 | +| Сгибание ног лежа | 40-55 | 12-11-9-8 | +| Икроножные сидя | 20-25-30-35 | 12-12-12-12 | +| Пресс на скамье | | 12-12-12-12 | + +# 2026-04-20 (solo-41) + +| Упражнение | Вес | Подходы | +| ----------------------------------------- | ----------- | ----------- | +| Подтягивания | 78.0 | 10-9-5-7 | +| Тяга Т-грифа | 30-40-45-40 | 12-11-8-12 | +| Жим от груди лежа (гантели) | 25х2-30х2 | 12-7-7-5 | +| Жим от груди сидя в тренажере (кирпичики) | 75 | 9-9-9-8 | +| Пресс на скамье | 78.0 | 12-12-12-12 | + +# 2026-04-18 (solo-40) + +| Упражнение | Вес | Подходы | +| -------------------------------------- | --------- | ----------- | +| Подтягивания обратным хватом | 78.3 | 9-8-7-6 | +| Подъем гантелей стоя | 20х2 | 8-8-7-6 | +| Французский жим лежа (штанга) | 30 | 10-8-7-7 | +| Разведение рук с гантелей из-за головы | 22.5 | 10-7-9-9 | +| Махи рукой в кроссовере | 20х2-22х2 | 12-10-10-12 | + +# 2026-04-16 (solo-39) + +| Упражнение | Вес | Подходы | +| ----------------------------------------- | -------------- | --------- | +| Подтягивания | 77.7 | 12-7-8-8 | +| Тяга вертикального блока (блинчики) | 20х2-25х2 | 12-7-7-7 | +| Сведение рук пек дек | 70 | 10-10-9-7 | +| Жим от груди сидя в тренажере (кирпичики) | 70-75 | 12-8-9-9 | +| Махи рукой в кроссовере | 17х2-18х2-19х2 | 12-12-11 | + +# 2026-04-13 (solo-38) + +| Упражнение | Вес | Подходы | +| ---------------------------------------- | ----------- | --------- | +| Подтягивания обратным хватом | 78.7 | 10-8-7-6 | +| Бицепс в тренажере | 25-20 | 8-10-9-8 | +| Жим от плеч вверх в тренажере (блинчики) | 17.5х2 | 11-10-7-8 | +| Французский жим лежа (гантели) | 15х2 | 7-6-5-6 | +| Махи гантелей в стороны стоя | 17.5х2-15х2 | 9-10-10-9 | + +# 2026-04-11 (solo-37) + +| Упражнение | Вес | Подходы | +| --------------------------- | ----------- | ----------- | +| Подтягивания | 77.8 | 13-9-7-6 | +| Тяга гантели в наклоне | 32.5х2-35х2 | 12-12-12-9 | +| Жим от груди лежа (гантели) | 25х2 | 11-10-8-7 | +| Сведение рук пек дек | 65 | 7-7-7-7 | +| Пресс на скамье | | 13-12-12-12 | + +# 2026-04-09 (solo-36) + +| Упражнение | Вес | Подходы | +| -------------------------------------- | ----------------------- | ----------- | +| Подъем гантелей стоя | 20х2-22.5x2-22.5х2-20х2 | 12-7-7-7 | +| Французский жим лежа (штанга) | 30-30-25 | 7-6-10-10 | +| Разведение рук с гантелей из-за головы | 22.5 | 10-10-10-12 | +| Жим от плеч вверх (гантели) | 20х2-22.5х2 | 12-10-9-7 | +| Махи гантелей в стороны стоя | 15х2-17.5x2 | 12-8-9-10 | + +# 2026-04-06 (solo-35) + +| Упражнение | Вес | Подходы | +| --------------------------- | ----------- | --------- | +| Подтягивания | 78.1 | 12-10-8-7 | +| Тяга вертикального блока | 50-55 | 12-9-9-10 | +| Жим от груди лежа (гантели) | 25х2-27.5х2 | 12-10-8-7 | +| Сведение рук пек дек | 65 | 10-9-10-8 | +| Брусья | 78.1 | 9-7-8-6 | + +# 2026-04-04 (solo-34) + +| Упражнение | Вес | Подходы | +| ---------------------------------------- | ---------------- | ----------- | +| Бицепс в тренажере | 30-25 | 7-8-8-6 | +| Молоты стоя | 20х2-20х2-17.5х2 | 12-10-12-12 | +| Французский жим лежа (штанга) | 30 | 8-8-7-7 | +| Жим от плеч вверх в тренажере (блинчики) | 15х2 | 11-11-8-9 | +| Махи гантелей в стороны стоя | 15х2 | 10-12-12-12 | + +# 2026-04-02 (solo-33) + +| Упражнение | Вес | Подходы | +| ---------------------------------------- | --------- | ----------- | +| Подтягивания | 78.1 | 12-8-8-6 | +| Тяга Т-грифа | 30-40 | 12-11-11-10 | +| Жим от груди сидя в тренажере (блинчики) | 25х2-30х2 | 12-11-9-8 | +| Брусья | 78.1 | 9-7-8-8 | +| Махи рукой в кроссовере | 17х2 | 12-12-12-12 | + +# 2026-03-30 (solo-32) + +| Упражнение | Вес | Подходы | +| ------------------------------------ | ----------- | ----------- | +| Подъем штанги стоя | 35 | 12-12-12-9 | +| Французский жим лежа (штанга) | 30 | 11-9-8-6 | +| Подъем гантелей стоя обратным хватом | 17.5х2-20х2 | 12-12-12-9 | +| Жим от плеч вверх (гантели) в наклоне | 20х2-22.5х2 | 12-10-8-8 | +| Махи гантелей в стороны стоя | 15х2 | 12-12-12-12 | + +# 2026-03-26 (solo-31) + +| Упражнение | Вес | Подходы | +| -------------------------------- | ---------------- | ----------- | +| Подтягивания | | 13-8-7-6 | +| Тяга гантели в наклоне | 25х2-30х2-32.5х2 | 12-12-12-10 | +| Жим лежа (штанга) | 50-70 | 12-6-5-5 | +| Сведение рук пек дек | 60-65 | 12-8-9-8 | +| Махи руки в сторону в кроссовере | 15х2-16х2 | 12-12-12-12 | + # 2026-03-23 (solo-30) | Упражнение | Вес | Подходы | @@ -1322,7 +2111,7 @@ | Гребная тяга с упором в грудь | 75 | 12-12-12-12 | | Тяга Т-грифа | 32.5-35 | 12-12-12-12 | | Жим от груди лежа (гантели) | 22.5х2 | 12-12-12-10 | -| махи рукой в кроссовере | 10x2 | 12-12-12-12 | +| Махи рукой в кроссовере | 10x2 | 12-12-12-12 | # 2025-04-26 (solo-41) @@ -1459,7 +2248,7 @@ | ----------------------------- | -------- | ----------- | | Подтягивания | | 10-7-6-5 | | Гребная тяга с упором в грудь | 55-65-70 | 12-12-12-12 | -| Тяга штанги в наклоне | 15х2 | 12-12-12-12 | +| Тяга штанги в наклоне | 30 | 12-12-12-12 | | Махи гантелей в стороны стоя| 10х2 | 12-12-12-12 | | Жим от плеч вверх (гантели)| 20х2 | 10-10-8-8 | @@ -1498,7 +2287,7 @@ | Упражнение | Вес | Подходы | | ----------------------------- | --------- | ----------- | | Подтягивания | | 10-7-6 | -| Тяга штанги в наклоне | 10х2-15х2 | 12-12-12-12 | +| Тяга штанги в наклоне | 20-30 | 12-12-12-12 | | Тяга гантели в наклоне | 25х2 | 12-12-12-12 | | Разведение рук пек дек | 30 | 12-12-10-8 | | Жим от плеч вверх в тренажере (кирпичики)| 35 | 12-12-11-9 | @@ -1612,7 +2401,7 @@ | ---------------------- | ----------- | ----------- | | Разгибание ног сидя | 75-75-90 | 12-16-12-12 | | Жим ногами | 100-120-140 | 12-12-12-12 | -| Икроножные стоя | 25-40-45 | 12-12-12-12 | +| Икроножные стоя | 12.5х2-20х2-22.5х2 | 12-12-12-12 | | Жим от плеч вверх (гантели) | 20х2 | 9-12-10-8 | | Разведение рук пек дек | 35 | 12-12-12 | @@ -1692,7 +2481,7 @@ | --------------------------------------- | --------- | -------- | | Болгарские выпады | 12х2-20х2 | 8-6-6 | | Сгибание ног сидя | 77-86 | 12-12-12 | -| Икроножные стоя | 34 | 11-10-12 | +| Икроножные стоя | 17х2 | 11-10-12 | | Жим от плеч вверх в тренажере (блинчики) | 13x2-17x2 | 12-12-12 | | Дельт-машина | 47 | 12-12-12 | | Разведение рук пек дек | 37 | 12-9 | @@ -1816,7 +2605,7 @@ | Разгибание ног сидя | 49-81-90 | 12-12-12 | | Жим ногами | 75-125-150 | 12-12-10 | | Гиперэкстензия | 10-15 | 12-12-12 | -| Махи рукой в кроссовере | 13.9 | 12-12-12 | +| Махи рукой в кроссовере | 13.9х2 | 12-12-12 | | Дельт-машина | 47 | 12-11-12 | | Разведение рук пек дек | 37 | 9-9-8 | @@ -1960,7 +2749,7 @@ | Упражнение | Вес | Подходы | | -------------------------- | --------- | -------- | | Подтягивания | | 10-7-5 | -| Тяга гантели в наклоне | 24-26 | 12-12-12 | +| Тяга гантели в наклоне | 24х2-26х2 | 12-12-12 | | Жим от груди лежа (гантели) | 20х2-22х2 | 12-12-9 | | Тяга горизонтального блока | 47-47-57 | 12-12-12 | | Тяга вертикального блока | 47 | 12-12-12 | @@ -2024,7 +2813,7 @@ | ----------------------------------------- | ----------- | ---------- | | Подтягивания | | 9-7-6 | | Тяга горизонтального блока | 57 | 12-12-12 | -| Тяга гантели в наклоне | 26 | 12-12-12 | +| Тяга гантели в наклоне | 26х2 | 12-12-12 | | Жим от груди сидя в тренажере (блинчики)| 20x2-30x2-30x2-20x2 | 12-11-9-10 | | Махи гантелей в стороны стоя| 9х2 | 12-12-12 | | Трицепс машина | 77-87 | 12-12-9 | @@ -2088,7 +2877,7 @@ | ---------------------------- | -------------- | --------- | | Подтягивания | | 10-6-6 | | Гребная тяга с упором в грудь | 47-51 | 12-12-12 | -| Тяга гантели в наклоне | 26-28 | 12-12-12 | +| Тяга гантели в наклоне | 26х2-28х2 | 12-12-12 | | Жим от груди лежа (гантели) | 18х2-24х2-22х2 | 12-10-7-8 | | Сведение рук пек дек| 37 | 12-12-12 | | Брусья | 37 | 12-9-9 | @@ -2098,7 +2887,7 @@ | Упражнение | Вес | Подходы | | ----------------------------- | -------- | ----------- | | Разгибание ног сидя | 62-82-90 | 12-12-11-10 | -| Румынская тяга | 40 | 12-12-12 | +| Румынская тяга | 20х2 | 12-12-12 | | Икроножные сидя | 27 | 16-15-14 | | Разведение рук пек дек | 47 | 12-12-12 | | Жим от плеч вверх (гантели) | 18х2 | 11-12-12 | @@ -2119,7 +2908,7 @@ | Упражнение | Вес | Подходы | | ------------------------ | ---------- | ----------- | | Разгибание ног сидя | 59-77-81.5 | 12-12-12-12 | -| Румынская тяга | 40 | 12-12-12 | +| Румынская тяга | 20х2 | 12-12-12 | | Икроножные сидя | 27.2 | 12-12-12 | | Жим от плеч вверх (гантели) | 16x2-18x2 | 12-12-12 | | Дельт-машина | 47 | 12-12-10 | diff --git a/data/obsidian.md b/backend/data/obsidian.md similarity index 100% rename from data/obsidian.md rename to backend/data/obsidian.md diff --git a/data/obsidian_original_backup.md b/backend/data/obsidian_original_backup.md similarity index 100% rename from data/obsidian_original_backup.md rename to backend/data/obsidian_original_backup.md diff --git a/data/test.py b/backend/data/test.py similarity index 100% rename from data/test.py rename to backend/data/test.py diff --git a/dump_trainings.py b/backend/dump_trainings.py similarity index 90% rename from dump_trainings.py rename to backend/dump_trainings.py index 45afe28..ee6b394 100644 --- a/dump_trainings.py +++ b/backend/dump_trainings.py @@ -22,10 +22,6 @@ def dump_trainings_to_json(trainings: List[TrainingDTO], filename="trainings.jso def main(): # Parse Obsidian notes obsidian_trainings = odp() - for training in obsidian_trainings: - for exercise in training.exercises: - print(exercise.name) - # Parse Apple notes apple_trainings = adp() diff --git a/backend/migrations/README b/backend/migrations/README new file mode 100644 index 0000000..e0d0858 --- /dev/null +++ b/backend/migrations/README @@ -0,0 +1 @@ +Generic single-database configuration with an async dbapi. \ No newline at end of file diff --git a/backend/migrations/env.py b/backend/migrations/env.py new file mode 100644 index 0000000..115e949 --- /dev/null +++ b/backend/migrations/env.py @@ -0,0 +1,99 @@ +import asyncio +from logging.config import fileConfig + +from sqlalchemy import pool +from sqlalchemy.engine import Connection +from sqlalchemy.ext.asyncio import async_engine_from_config + +from alembic import context + +from app.config import settings +from app.core.database.tables import metadata + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +config = context.config + +# The URL comes from app settings (.env), not from alembic.ini. +# "%" is escaped because the value goes through configparser interpolation. +config.set_main_option( + "sqlalchemy.url", settings.get_postgres_database_url().replace("%", "%%") +) + +# Interpret the config file for Python logging. +# This line sets up loggers basically. +if config.config_file_name is not None: + fileConfig(config.config_file_name, disable_existing_loggers=False) + +# add your model's MetaData object here +# for 'autogenerate' support +target_metadata = metadata + +# other values from the config, defined by the needs of env.py, +# can be acquired: +# my_important_option = config.get_main_option("my_important_option") +# ... etc. + + +def run_migrations_offline() -> None: + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + + Calls to context.execute() here emit the given string to the + script output. + + """ + url = config.get_main_option("sqlalchemy.url") + context.configure( + url=url, + target_metadata=target_metadata, + literal_binds=True, + dialect_opts={"paramstyle": "named"}, + compare_type=True, + ) + + with context.begin_transaction(): + context.run_migrations() + + +def do_run_migrations(connection: Connection) -> None: + context.configure( + connection=connection, target_metadata=target_metadata, compare_type=True + ) + + with context.begin_transaction(): + context.run_migrations() + + +async def run_async_migrations() -> None: + """In this scenario we need to create an Engine + and associate a connection with the context. + + """ + + connectable = async_engine_from_config( + config.get_section(config.config_ini_section, {}), + prefix="sqlalchemy.", + poolclass=pool.NullPool, + ) + + async with connectable.connect() as connection: + await connection.run_sync(do_run_migrations) + + await connectable.dispose() + + +def run_migrations_online() -> None: + """Run migrations in 'online' mode.""" + + asyncio.run(run_async_migrations()) + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/backend/migrations/script.py.mako b/backend/migrations/script.py.mako new file mode 100644 index 0000000..1101630 --- /dev/null +++ b/backend/migrations/script.py.mako @@ -0,0 +1,28 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision: str = ${repr(up_revision)} +down_revision: Union[str, Sequence[str], None] = ${repr(down_revision)} +branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)} +depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)} + + +def upgrade() -> None: + """Upgrade schema.""" + ${upgrades if upgrades else "pass"} + + +def downgrade() -> None: + """Downgrade schema.""" + ${downgrades if downgrades else "pass"} diff --git a/backend/migrations/versions/2026_10_22_2248-08ba8bee6328_initial_schema.py b/backend/migrations/versions/2026_10_22_2248-08ba8bee6328_initial_schema.py new file mode 100644 index 0000000..c6e965c --- /dev/null +++ b/backend/migrations/versions/2026_10_22_2248-08ba8bee6328_initial_schema.py @@ -0,0 +1,66 @@ +"""initial schema + +Revision ID: 08ba8bee6328 +Revises: +Create Date: 2026-10-22 22:48:54.728389 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = '08ba8bee6328' +down_revision: Union[str, Sequence[str], None] = None +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + """Upgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('trainings', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('date', sa.Date(), nullable=False), + sa.Column('trainer', sa.String(length=100), nullable=True), + sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_trainings_date'), 'trainings', ['date'], unique=False) + op.create_table('exercises', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('training_id', sa.Integer(), nullable=False), + sa.Column('name', sa.String(length=255), nullable=False), + sa.Column('splitted_weight', sa.Boolean(), server_default='false', nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False), + sa.ForeignKeyConstraint(['training_id'], ['trainings.id'], ondelete='CASCADE'), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_exercises_name'), 'exercises', ['name'], unique=False) + op.create_index(op.f('ix_exercises_training_id'), 'exercises', ['training_id'], unique=False) + op.create_table('approaches', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('exercise_id', sa.Integer(), nullable=False), + sa.Column('weight', sa.Float(), nullable=False), + sa.Column('reps', sa.Integer(), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False), + sa.ForeignKeyConstraint(['exercise_id'], ['exercises.id'], ondelete='CASCADE'), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_approaches_exercise_id'), 'approaches', ['exercise_id'], unique=False) + # ### end Alembic commands ### + + +def downgrade() -> None: + """Downgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + op.drop_index(op.f('ix_approaches_exercise_id'), table_name='approaches') + op.drop_table('approaches') + op.drop_index(op.f('ix_exercises_training_id'), table_name='exercises') + op.drop_index(op.f('ix_exercises_name'), table_name='exercises') + op.drop_table('exercises') + op.drop_index(op.f('ix_trainings_date'), table_name='trainings') + op.drop_table('trainings') + # ### end Alembic commands ### diff --git a/backend/pyproject.toml b/backend/pyproject.toml new file mode 100644 index 0000000..18c7249 --- /dev/null +++ b/backend/pyproject.toml @@ -0,0 +1,15 @@ +[project] +name = "f1tness-parser" +version = "0.1.0" +description = "Add your description here" +readme = "README.md" +requires-python = ">=3.13" +# Dependencies live in requirements.txt / requirements-dev.txt + +[tool.pytest.ini_options] +asyncio_mode = "auto" +asyncio_default_fixture_loop_scope = "function" + +[tools.pyright] +venvPath = "." +venv = ".venv" diff --git a/backend/requirements-dev.txt b/backend/requirements-dev.txt new file mode 100644 index 0000000..9f0733d --- /dev/null +++ b/backend/requirements-dev.txt @@ -0,0 +1,7 @@ +-r requirements.txt + +pytest==8.4.1 +pytest-asyncio==1.4.0 +mypy==1.17.1 +types-grpcio==1.0.0.20250703 +types-protobuf==6.30.2.20250822 diff --git a/backend/requirements.txt b/backend/requirements.txt new file mode 100644 index 0000000..582eb64 --- /dev/null +++ b/backend/requirements.txt @@ -0,0 +1,8 @@ +fastapi==0.116.1 +uvicorn[standard]==0.35.0 +pydantic==2.11.7 +pydantic-settings==2.10.1 +python-dotenv==1.1.1 +sqlalchemy[asyncio]==2.1.6 +asyncpg==0.32.0 +alembic==1.20.1 diff --git a/run.py b/backend/run.py similarity index 100% rename from run.py rename to backend/run.py diff --git a/app/core/templates/__init__.py b/backend/tests/__init__.py similarity index 100% rename from app/core/templates/__init__.py rename to backend/tests/__init__.py diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py new file mode 100644 index 0000000..b1151af --- /dev/null +++ b/backend/tests/conftest.py @@ -0,0 +1,67 @@ +"""Shared fixtures for tests that need a real PostgreSQL. + +In docker compose TEST_DATABASE_URL is already set (database `_test`). +Elsewhere set it to a throwaway database whose name ends with `_test`; it is +created if missing and its tables are emptied by every test that uses `session`. +Without TEST_DATABASE_URL those tests are skipped. +""" + +import asyncio +import os + +import pytest +from alembic import command +from alembic.config import Config +from sqlalchemy import text +from sqlalchemy.engine import make_url +from sqlalchemy.ext.asyncio import create_async_engine + +from app.config import settings +from app.core.database.connection import create_engine, create_session_factory +from app.core.database.repository import TrainingRepository + +TEST_DATABASE_URL = os.environ.get("TEST_DATABASE_URL") + + +async def ensure_test_database(url: str) -> None: + """Create the test database if it doesn't exist yet.""" + target = make_url(url) + name = target.database or "" + if not name.endswith("_test"): + pytest.fail(f"Refusing to run: database {name!r} must end with '_test'") + + admin_engine = create_async_engine( + target.set(database="postgres"), isolation_level="AUTOCOMMIT" + ) + try: + async with admin_engine.connect() as conn: + exists = await conn.scalar( + text("SELECT 1 FROM pg_database WHERE datname = :name"), {"name": name} + ) + if not exists: + quoted = name.replace('"', '""') + await conn.execute(text(f'CREATE DATABASE "{quoted}"')) + finally: + await admin_engine.dispose() + + +@pytest.fixture +async def alembic_config(monkeypatch) -> Config: + if not TEST_DATABASE_URL: + pytest.skip("TEST_DATABASE_URL is not set") + await ensure_test_database(TEST_DATABASE_URL) + # migrations/env.py takes the URL from settings + monkeypatch.setattr(settings, "POSTGRES_DATABASE_URL", TEST_DATABASE_URL) + return Config("alembic.ini") + + +@pytest.fixture +async def session(alembic_config): + """Session on a migrated and emptied test database.""" + # env.py runs its own event loop, so alembic goes to a thread + await asyncio.to_thread(command.upgrade, alembic_config, "head") + engine = create_engine(TEST_DATABASE_URL) + async with create_session_factory(engine)() as session: + await TrainingRepository(session).delete_all() + yield session + await engine.dispose() diff --git a/app/core/utils/__init__.py b/backend/tests/test_core/__init__.py similarity index 100% rename from app/core/utils/__init__.py rename to backend/tests/test_core/__init__.py diff --git a/backend/tests/test_core/test_metrics.py b/backend/tests/test_core/test_metrics.py new file mode 100644 index 0000000..fe0597e --- /dev/null +++ b/backend/tests/test_core/test_metrics.py @@ -0,0 +1,116 @@ +from datetime import date + +import pytest + +from app.core.dto.training import ApproachDTO, ExerciseSessionDTO +from app.core.metrics import estimate_1rm, session_metrics, summarize + + +def make_session(day: int, *sets: tuple, month: int = 1) -> ExerciseSessionDTO: + return ExerciseSessionDTO( + date=date(2025, month, day), + approaches=[ApproachDTO(weight=weight, reps=reps) for weight, reps in sets], + ) + + +def test_estimate_1rm_uses_epley_formula(): + assert estimate_1rm(140, 12) == pytest.approx(196) + assert estimate_1rm(100, 10) == pytest.approx(133.333, rel=1e-4) + + +def test_single_rep_is_the_weight_itself(): + assert estimate_1rm(100, 1) == 100 + + +def test_session_metrics_of_weighted_sets(): + metrics = session_metrics(make_session(1, (100, 12), (110, 10)).approaches) + + assert metrics.max_weight == 110 + assert metrics.e1rm == pytest.approx(max(140.0, 110 * (1 + 10 / 30))) + assert metrics.volume == 100 * 12 + 110 * 10 + assert metrics.total_reps == 22 + assert metrics.best_reps == 12 + + +def test_sets_without_weight_count_only_as_reps(): + metrics = session_metrics(make_session(1, (0, 7), (47, 12)).approaches) + + assert metrics.e1rm == pytest.approx(estimate_1rm(47, 12)) + assert metrics.volume == 47 * 12 + assert metrics.total_reps == 19 + + +def test_session_without_weight_has_no_e1rm(): + metrics = session_metrics(make_session(1, (0, 11), (0, 8)).approaches) + + assert metrics.e1rm is None + assert metrics.volume == 0 + assert metrics.total_reps == 19 + assert metrics.best_reps == 11 + + +def test_weighted_progress_records_and_change(): + # newest first, like the repository returns + history = [ + make_session(20, (100, 12)), # e1RM 140 + make_session(10, (110, 12), (100, 12)), # e1RM 154 (record) + make_session(1, (80, 10)), # e1RM 106.67 + ] + + progress = summarize(history) + + assert progress.weighted is True + assert progress.max_weight == 110 + assert progress.best_primary.value == pytest.approx(154) + assert progress.best_primary.date == date(2025, 1, 10) + assert progress.best_secondary.value == 110 * 12 + 100 * 12 + assert progress.first_primary == pytest.approx(80 * (1 + 10 / 30)) + assert progress.last_primary == pytest.approx(140) + assert progress.primary_change == pytest.approx(140 - 80 * (1 + 10 / 30)) + assert progress.primary_change_percent == pytest.approx( + (140 - 80 * (1 + 10 / 30)) / (80 * (1 + 10 / 30)) * 100 + ) + + +def test_record_keeps_the_first_date_it_was_reached(): + history = [make_session(20, (100, 12)), make_session(10, (100, 12))] + + assert summarize(history).best_primary.date == date(2025, 1, 10) + + +def test_exercise_without_weight_is_tracked_by_reps(): + history = [ + make_session(20, (0, 8), (0, 7)), # best 8, total 15 + make_session(10, (0, 10), (0, 5)), # best 10, total 15 + make_session(1, (0, 6)), # best 6, total 6 + ] + + progress = summarize(history) + + assert progress.weighted is False + assert progress.max_weight == 0 + assert progress.best_primary.value == 10 + assert progress.best_primary.date == date(2025, 1, 10) + assert progress.best_secondary.value == 15 + assert progress.best_secondary.date == date(2025, 1, 10) + assert (progress.first_primary, progress.last_primary) == (6, 8) + assert progress.primary_change == 2 + + +def test_weighted_exercise_ignores_sessions_without_weight_for_primary_metric(): + history = [ + make_session(20, (0, 12)), # no e1RM + make_session(10, (100, 10)), + ] + + progress = summarize(history) + + assert progress.weighted is True + assert progress.last_primary == pytest.approx(estimate_1rm(100, 10)) + assert progress.primary_change == 0 + + +def test_percent_change_is_undefined_when_the_first_value_is_zero(): + progress = summarize([make_session(1, (0, 0))]) + + assert progress.primary_change_percent is None diff --git a/backend/tests/test_core/test_notes_parsing.py b/backend/tests/test_core/test_notes_parsing.py new file mode 100644 index 0000000..0d2efba --- /dev/null +++ b/backend/tests/test_core/test_notes_parsing.py @@ -0,0 +1,124 @@ +from datetime import date + +import pytest + +from app.core.parsers.apple import AppleNotesParser +from app.core.parsers.obsidian import ObsidianNotesParser +from app.core.utils.date_refactor import parse_training_date + +OBSIDIAN_NOTES = """\ +# 07.01.2025 (solo-2) + +| Упражнение | Вес | Подходы | +| --------------------------------------- | --------------------- | ----------- | +| Разгибание ног сидя | 77-86 | 12-12-12-12 | +| Подтягивания | красная резинка | 9-7-5 | + +# 04.01.2025 (c153-1) + +| Упражнение | Вес | Подходы | +| --- | --- | --- | +| Сгибание ног лежа | 47 | 12-12-11-10 | +""" + +APPLE_NOTES = """\ +**21.08.2024 (с123-69)** + +| | | | +|---|---|---| +|**Упражнение**|**Вес**|**Подходы**| +|Жим ногами|100|12-12-12| + +**22.08.2024 (соло)** + +|Подтягивания||9-7-5| +""" + + +def test_obsidian_parses_every_training_and_trainer(): + parser = ObsidianNotesParser() + trainings = parser.parse(OBSIDIAN_NOTES, map_names=False) + + assert [t.date for t in trainings] == [date(2025, 1, 7), date(2025, 1, 4)] + assert [t.trainer for t in trainings] == ["solo", "c153"] + assert [len(t.exercises) for t in trainings] == [1, 1] + + +def test_malformed_rows_are_reported_not_silently_dropped(): + parser = ObsidianNotesParser() + parser.parse(OBSIDIAN_NOTES, map_names=False) + + assert len(parser.errors) == 1 + assert "красная резинка" in parser.errors[0] + + +def test_errors_are_reset_between_parses(): + parser = ObsidianNotesParser() + parser.parse(OBSIDIAN_NOTES, map_names=False) + parser.parse("# 07.01.2025 (solo-2)\n", map_names=False) + + assert parser.errors == [] + + +def test_last_line_header_keeps_all_trainings(): + parser = ObsidianNotesParser() + text = OBSIDIAN_NOTES + "\n# 01.01.2025 (solo-3)" + trainings = parser.parse(text, map_names=False) + + assert [t.date for t in trainings] == [ + date(2025, 1, 7), + date(2025, 1, 4), + date(2025, 1, 1), + ] + assert trainings[-1].exercises == [] + + +def test_bad_date_skips_whole_training_block(): + parser = ObsidianNotesParser() + text = "# 31.02.2025 (solo-1)\n| Жим | 10 | 12-12 |\n" + OBSIDIAN_NOTES + trainings = parser.parse(text, map_names=False) + + assert [t.date for t in trainings] == [date(2025, 1, 7), date(2025, 1, 4)] + # The bad date itself plus the malformed row inside OBSIDIAN_NOTES; + # the exercise under the bad header is skipped without an extra error + assert len(parser.errors) == 2 + assert "day is out of range" in parser.errors[0] + + +def test_exercise_mapping_is_applied_by_default(): + parser = ObsidianNotesParser() + parser.exercise_mapper = {"Разгибание ног сидя": "Разгибание ног"} + + mapped = parser.parse(OBSIDIAN_NOTES) + unmapped = parser.parse(OBSIDIAN_NOTES, map_names=False) + + assert mapped[0].exercises[0].name == "Разгибание ног" + assert unmapped[0].exercises[0].name == "Разгибание ног сидя" + + +def test_apple_parses_headers_with_and_without_counter(): + parser = AppleNotesParser() + trainings = parser.parse(APPLE_NOTES, map_names=False) + + assert [t.date for t in trainings] == [date(2024, 8, 21), date(2024, 8, 22)] + assert [t.trainer for t in trainings] == ["с123", "соло"] + assert [len(t.exercises) for t in trainings] == [1, 1] + assert trainings[1].exercises[0].approaches[0].weight == 0.0 + + +@pytest.mark.parametrize( + "raw, expected", + [ + ("21.08.2024", date(2024, 8, 21)), + ("21.08.24", date(2024, 8, 21)), + ("2024-08-21", date(2024, 8, 21)), + ("2024.08.21", date(2024, 8, 21)), + ], +) +def test_parse_training_date_formats(raw, expected): + assert parse_training_date(raw) == expected + + +def test_parse_training_date_rejects_garbage(): + with pytest.raises(ValueError): + parse_training_date("yesterday") diff --git a/tests/test_core/test_obsidian_parser.py b/backend/tests/test_core/test_obsidian_parser.py similarity index 57% rename from tests/test_core/test_obsidian_parser.py rename to backend/tests/test_core/test_obsidian_parser.py index b40a4a1..ae60008 100644 --- a/tests/test_core/test_obsidian_parser.py +++ b/backend/tests/test_core/test_obsidian_parser.py @@ -1,7 +1,10 @@ -from obsidian.notes_parser import serialize_exercise -from obsidian.py_models import Approach, Exercise +from app.core.dto.training import ApproachDTO as Approach, ExerciseDTO as Exercise +from app.core.parsers.base import ParseError +from app.core.parsers.obsidian import ObsidianNotesParser import pytest +serialize_exercise = ObsidianNotesParser().serialize_exercise + @pytest.mark.parametrize( "reps, weight, name, expected", @@ -65,8 +68,51 @@ import pytest ], ), ), + ( + # Cyrillic and latin "x" mixed in a single value + "12-12-12", + "10х2-12x2", + "test_exercise", + Exercise( + name="test_exercise", + splitted_weight=True, + approaches=[ + Approach(weight=10, reps=12), + Approach(weight=12, reps=12), + Approach(weight=12, reps=12), + ], + ), + ), + ( + # First approach without weight, the rest per hand + "8-8-7", + "0-12х2-16х2", + "test_exercise", + Exercise( + name="test_exercise", + splitted_weight=True, + approaches=[ + Approach(weight=0, reps=8), + Approach(weight=12, reps=8), + Approach(weight=16, reps=7), + ], + ), + ), ], ) def test_approach_parsing(reps, weight, name, expected): exercise = serialize_exercise(reps, weight, name) assert expected == exercise + + +@pytest.mark.parametrize( + "reps, weight", + [ + ("12-12-", "10х2"), + ("11--11-7", ""), + ("12-12", "красная резинка"), + ], +) +def test_malformed_exercise_raises_parse_error(reps, weight): + with pytest.raises(ParseError): + serialize_exercise(reps, weight, "test_exercise") diff --git a/backend/tests/test_core/test_repository.py b/backend/tests/test_core/test_repository.py new file mode 100644 index 0000000..122fffc --- /dev/null +++ b/backend/tests/test_core/test_repository.py @@ -0,0 +1,150 @@ +"""Repository and migration tests against a real PostgreSQL. + +The `session` / `alembic_config` fixtures (tests/conftest.py) skip these tests +when TEST_DATABASE_URL is not set. +""" + +import asyncio +from datetime import date + +import pytest +from alembic import command +from sqlalchemy import func, select +from sqlalchemy.exc import DBAPIError + +from app.core.database.tables import approaches, exercises +from app.core.database.repository import TrainingRepository +from app.core.dto.training import ApproachDTO, ExerciseDTO, TrainingDTO +from app.core.parsers.apple import AppleNotesParser +from app.core.parsers.obsidian import ObsidianNotesParser + + +def make_training(day: int = 1, trainer: str = "solo") -> TrainingDTO: + return TrainingDTO( + date=date(2025, 1, day), + trainer=trainer, + exercises=[ + ExerciseDTO( + name="Жим ногами", + approaches=[ + ApproachDTO(weight=100, reps=12), + ApproachDTO(weight=110, reps=10), + ], + ), + ExerciseDTO( + name="Жим гантелей лежа", + splitted_weight=True, + approaches=[ApproachDTO(weight=20, reps=12)], + ), + ], + ) + + +async def test_save_and_list_roundtrip(session): + repository = TrainingRepository(session) + + training_id = await repository.save(make_training()) + trainings = await repository.list() + + assert len(trainings) == 1 + saved = trainings[0] + assert saved.id == training_id + assert (saved.date, saved.trainer) == (date(2025, 1, 1), "solo") + assert [e.name for e in saved.exercises] == ["Жим ногами", "Жим гантелей лежа"] + assert saved.exercises[1].splitted_weight is True + assert [(a.weight, a.reps) for a in saved.exercises[0].approaches] == [ + (100, 12), + (110, 10), + ] + + +async def test_list_is_ordered_by_date_desc(session): + repository = TrainingRepository(session) + await repository.save_many([make_training(day=1), make_training(day=3)]) + + assert [t.date.day for t in await repository.list()] == [3, 1] + + +async def test_exercise_names_are_distinct_counted_and_sorted(session): + repository = TrainingRepository(session) + await repository.save_many([make_training(day=1), make_training(day=3)]) + + names = await repository.list_exercise_names() + + assert [(item.name, item.count) for item in names] == [ + ("Жим гантелей лежа", 2), + ("Жим ногами", 2), + ] + + +async def test_exercise_history_is_newest_first(session): + repository = TrainingRepository(session) + await repository.save_many( + [make_training(day=1), make_training(day=3, trainer="c153")] + ) + + history = await repository.exercise_history("Жим ногами") + + assert [item.date.day for item in history] == [3, 1] + assert [item.trainer for item in history] == ["c153", "solo"] + assert [(a.weight, a.reps) for a in history[0].approaches] == [(100, 12), (110, 10)] + assert history[0].splitted_weight is False + + +async def test_exercise_history_keeps_splitted_weight_and_ignores_other_exercises( + session, +): + repository = TrainingRepository(session) + await repository.save(make_training()) + + history = await repository.exercise_history("Жим гантелей лежа") + + assert len(history) == 1 + assert history[0].splitted_weight is True + assert [a.weight for a in history[0].approaches] == [20] + assert await repository.exercise_history("Несуществующее") == [] + + +async def test_delete_cascades_to_exercises_and_approaches(session): + repository = TrainingRepository(session) + keep_id, delete_id = await repository.save_many( + [make_training(day=1), make_training(day=2)] + ) + + assert await repository.delete([delete_id]) == 1 + + assert [t.id for t in await repository.list()] == [keep_id] + assert await session.scalar(select(func.count(exercises.c.id))) == 2 + assert await session.scalar(select(func.count(approaches.c.id))) == 3 + + +async def test_save_many_is_atomic(session): + repository = TrainingRepository(session) + broken = make_training(day=2, trainer="x" * 101) # trainer is VARCHAR(100) + + with pytest.raises(DBAPIError): + await repository.save_many([make_training(day=1), broken]) + await session.rollback() + + assert await repository.count() == 0 + + +async def test_all_notes_can_be_saved(session): + trainings = ObsidianNotesParser().parse_file() + AppleNotesParser().parse_file() + repository = TrainingRepository(session) + + ids = await repository.save_many(trainings) + + assert len(ids) == len(trainings) + assert await repository.count() == len(trainings) + + +async def test_migrations_match_models(alembic_config): + await asyncio.to_thread(command.upgrade, alembic_config, "head") + # check() raises if autogenerate would produce a new migration + await asyncio.to_thread(command.check, alembic_config) + + +async def test_downgrade_and_upgrade(alembic_config): + await asyncio.to_thread(command.downgrade, alembic_config, "base") + await asyncio.to_thread(command.upgrade, alembic_config, "head") diff --git a/compose.override.yaml b/compose.override.yaml index c558717..4826c2a 100644 --- a/compose.override.yaml +++ b/compose.override.yaml @@ -1,15 +1,15 @@ # Development overrides for hot reload -version: '3.8' - services: fastapi-app: environment: - DEBUG=true - command: uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload --reload-dir /app/app --log-level debug + command: sh -c "alembic upgrade head && uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload --reload-dir /app/app --log-level debug" develop: watch: - action: sync - path: ./app + path: ./backend/app target: /app/app - action: rebuild - path: ./pyproject.toml + path: ./backend/requirements.txt + - action: rebuild + path: ./backend/requirements-dev.txt diff --git a/compose.yaml b/compose.yaml index ee6daa9..f51b544 100644 --- a/compose.yaml +++ b/compose.yaml @@ -1,25 +1,41 @@ -version: '3.8' - services: fastapi-app: build: - context: . + context: ./backend dockerfile: Dockerfile ports: - "8000:8000" volumes: - - ./app:/app/app:ro - - ./data:/app/data:ro - - ./tests:/app/tests:ro - - ./migrations:/app/migrations:ro + - ./backend/app:/app/app:ro + - ./backend/data:/app/data:ro + - ./backend/tests:/app/tests:ro + # Writable: `alembic revision --autogenerate` creates files in migrations/versions + - ./backend/migrations:/app/migrations env_file: - .env environment: - - PYTHONPATH=${PYTHONPATH} - command: uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload --reload-dir /app/app + - PYTHONPATH=${PYTHONPATH:-/app} + # Tests wipe their tables, so they use a separate database (created on demand) + - TEST_DATABASE_URL=postgresql+asyncpg://${POSTGRES_DATABASE_USER}:${POSTGRES_DATABASE_PASSWORD}@postgres:5432/${POSTGRES_DATABASE_DB}_test + command: sh -c "alembic upgrade head && uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload --reload-dir /app/app" depends_on: postgres: condition: service_healthy + frontend: + build: + context: ./frontend + ports: + - "8080:80" + volumes: + # Static files are served as they are: edits show up on page reload + - ./frontend/index.html:/usr/share/nginx/html/index.html:ro + - ./frontend/exercises.html:/usr/share/nginx/html/exercises.html:ro + - ./frontend/parse.html:/usr/share/nginx/html/parse.html:ro + - ./frontend/css:/usr/share/nginx/html/css:ro + - ./frontend/js:/usr/share/nginx/html/js:ro + - ./frontend/vendor:/usr/share/nginx/html/vendor:ro + depends_on: + - fastapi-app postgres: image: postgres:15-alpine env_file: diff --git a/frontend/.dockerignore b/frontend/.dockerignore new file mode 100644 index 0000000..fac5ce7 --- /dev/null +++ b/frontend/.dockerignore @@ -0,0 +1,2 @@ +.git +*.md diff --git a/frontend/Dockerfile b/frontend/Dockerfile new file mode 100644 index 0000000..4abba62 --- /dev/null +++ b/frontend/Dockerfile @@ -0,0 +1,7 @@ +FROM nginx:1.27-alpine + +COPY nginx.conf /etc/nginx/conf.d/default.conf +COPY index.html exercises.html parse.html /usr/share/nginx/html/ +COPY css /usr/share/nginx/html/css +COPY js /usr/share/nginx/html/js +COPY vendor /usr/share/nginx/html/vendor diff --git a/frontend/css/main.css b/frontend/css/main.css new file mode 100644 index 0000000..009306c --- /dev/null +++ b/frontend/css/main.css @@ -0,0 +1,74 @@ +/* Custom styles for Fitness Parser */ + +body { + font-family: Arial, sans-serif; + line-height: 1.6; + color: #333; +} + +/* Sidebar navigation */ +.sidebar .nav-link:hover:not(.active) { + background: rgba(255, 255, 255, 0.1); +} + +@media (min-width: 768px) { + .sidebar { + flex: 0 0 15rem; + position: sticky; + top: 0; + height: 100vh; + overflow-y: auto; + } +} + +/* Lets wide tables scroll inside the content instead of stretching the page */ +.content { + min-width: 0; +} + +.card { + border: 1px solid #ddd; + margin-bottom: 1rem; +} + +.card:hover { + box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); +} + +.btn { + font-weight: 500; +} + +/* Text with a tooltip */ +.has-tip { + cursor: help; + border-bottom: 1px dotted currentColor; +} + +/* Trainings table */ +td.date { + font-weight: 600; +} + +/* DataTables right-aligns columns it detects as dates; dates read better on the left. + Same selector as in dataTables.bootstrap5.min.css, this file is loaded after it. */ +table.dataTable th.dt-type-date, +table.dataTable td.dt-type-date { + text-align: left; +} + +.approach { + display: inline-block; + margin: 0 0.35rem 0.15rem 0; + padding: 0.05rem 0.5rem; + border-radius: 0.75rem; + background: #eef2f7; + font-size: 0.875rem; + white-space: nowrap; +} + +/* Footer */ +footer { + margin-top: auto; + border-top: 1px solid #ddd; +} \ No newline at end of file diff --git a/frontend/exercises.html b/frontend/exercises.html new file mode 100644 index 0000000..a6ab423 --- /dev/null +++ b/frontend/exercises.html @@ -0,0 +1,43 @@ + + + + + + Упражнения - Fitness Parser + + + + + + +
+ + + +
+

История упражнения

+
+ +
+ + +
+ +
+
+
+
+ + + + + + diff --git a/frontend/index.html b/frontend/index.html new file mode 100644 index 0000000..5b3f623 --- /dev/null +++ b/frontend/index.html @@ -0,0 +1,34 @@ + + + + + + Тренировки - Fitness Parser + + + + + + +
+ + + +
+

Все упражнения

+
Загрузка…
+
+
+ + + + + + diff --git a/frontend/js/common.js b/frontend/js/common.js new file mode 100644 index 0000000..276653d --- /dev/null +++ b/frontend/js/common.js @@ -0,0 +1,62 @@ +// Shared helpers: API access, DOM building, formatting + +const API = '/api/v1'; + +export async function api(path, options) { + const response = await fetch(API + path, options); + if (!response.ok) { + const error = new Error(`HTTP ${response.status}`); + error.status = response.status; + throw error; + } + return response.json(); +} + +/** h('div', {class: 'x'}, 'text', childNode) -> element; strings become text nodes */ +export function h(tag, attrs = {}, ...children) { + const element = document.createElement(tag); + for (const [name, value] of Object.entries(attrs)) { + if (value !== null && value !== undefined && value !== false) { + element.setAttribute(name, value === true ? '' : value); + } + } + element.append(...children.filter((child) => child !== null && child !== undefined)); + return element; +} + +export function alert(kind, ...children) { + return h('div', { class: `alert alert-${kind}` }, ...children); +} + +/** "2026-10-21" -> "21.10.2026" (no Date: a timezone must not shift the day) */ +export function formatDate(iso) { + const [year, month, day] = iso.split('-'); + return `${day}.${month}.${year}`; +} + +/** Rounded to one decimal without trailing zeros: 22.5 -> "22.5", 20 -> "20" */ +export function num(value) { + return String(Math.round(value * 10) / 10); +} + +/** Same with an explicit sign: "+12", "-3.5", "+0" */ +export function signed(value) { + const rounded = Math.round(value * 10) / 10; + return (rounded > 0 ? '+' : '') + rounded; +} + +/** Approaches as "weight × reps" chips */ +export function approachChips(approaches) { + return approaches.map((approach) => + h('span', { class: 'approach' }, + `${approach.weight ? num(approach.weight) + ' кг' : 'без веса'} × ${approach.reps}`) + ); +} + +export function perArmBadge() { + return h('span', { class: 'badge text-bg-light border', title: 'Вес указан на каждую руку (гантель)' }, 'на руку'); +} + +export function tip(text, hint) { + return h('span', { class: 'has-tip', title: hint }, text); +} diff --git a/frontend/js/exercises.js b/frontend/js/exercises.js new file mode 100644 index 0000000..90dee4d --- /dev/null +++ b/frontend/js/exercises.js @@ -0,0 +1,187 @@ +import { alert, api, approachChips, formatDate, h, num, perArmBadge, signed, tip } from './common.js'; +import { createTable } from './table.js'; + +const HINTS = { + recordE1rm: 'e1RM — расчётный максимум на один повтор по лучшему подходу тренировки (формула Эпли: вес × (1 + повторы / 30)). Рекорд — наибольшее значение за всю историю.', + lastE1rm: 'e1RM лучшего подхода последней тренировки. Ниже — изменение относительно первой тренировки с этим упражнением.', + recordVolume: 'Тоннаж — суммарная работа за тренировку: сумма вес × повторы по всем подходам с весом. Рекорд — тренировка с наибольшим тоннажем.', + maxWeight: 'Самый тяжёлый вес в одном подходе за всю историю, без учёта повторов.', + bestReps: 'Наибольшее число повторов в одном подходе за всю историю.', + lastBestReps: 'Наибольшее число повторов в одном подходе последней тренировки. Ниже — изменение относительно первой тренировки.', + recordTotalReps: 'Наибольшая сумма повторов по всем подходам за одну тренировку.', + e1rm: 'Расчётный максимум на один повтор по лучшему подходу тренировки (формула Эпли: вес × (1 + повторы / 30)). Подходы без веса не учитываются.', + volume: 'Тоннаж: сумма вес × повторы по подходам с весом за тренировку.', +}; + +const input = document.getElementById('exercise-input'); +const container = document.getElementById('exercise'); +const query = (new URLSearchParams(location.search).get('name') || '').trim(); + +let names = []; +try { + names = await api('/exercises/'); +} catch (error) { + container.replaceChildren(alert('danger', `Не удалось загрузить упражнения: ${error.message}`)); +} + +document.getElementById('exercise-names').replaceChildren(...names.map((item) => h('option', { value: item.name }))); +input.value = query; +if (!query) { + input.focus(); +} + +// Open the history right after a suggestion is picked from the list. Typing, pasting and +// deleting have their own inputType, so a half-typed name that equals a shorter exercise +// name doesn't submit early; Enter/button always work. +const knownNames = new Set(names.map((item) => item.name)); +input.addEventListener('input', (event) => { + const picked = !event.inputType || event.inputType === 'insertReplacementText'; + if (picked && knownNames.has(input.value)) { + input.form.submit(); + } +}); + +if (query) { + await showProgress(); +} else if (!names.length && !container.children.length) { + container.replaceChildren(alert('info', + 'В базе пока нет тренировок. Загрузи их из заметок командой:', + h('br'), h('code', {}, 'docker compose exec fastapi-app python -m app.cli import'))); +} + +async function showProgress() { + let progress; + try { + progress = await api(`/exercises/progress/?name=${encodeURIComponent(query)}`); + } catch (error) { + if (error.status !== 404) { + container.replaceChildren(alert('danger', `Не удалось загрузить историю: ${error.message}`)); + return; + } + // Nothing matched exactly: offer the names containing the typed text + const suggestions = names.filter((item) => item.name.toLowerCase().includes(query.toLowerCase())); + container.replaceChildren( + alert('warning', `Упражнение «${query}» не найдено. ${suggestions.length ? 'Возможно, вы искали:' : ''}`), + ...(suggestions.length ? [h('div', { class: 'list-group' }, ...suggestions.map((item) => + h('a', { class: 'list-group-item list-group-item-action d-flex justify-content-between align-items-center', href: `exercises.html?name=${encodeURIComponent(item.name)}` }, + item.name, h('span', { class: 'badge text-bg-secondary rounded-pill' }, `${item.count}`))))] : [])); + return; + } + + input.value = progress.name; + container.replaceChildren(...progressView(progress)); + if (progress.rows.length) { + drawChart(progress); + } +} + +function progressView(progress) { + const { rows, weighted } = progress; + const first = rows[rows.length - 1]; + const last = rows[0]; + + const change = (unit) => h('span', {}, + h('span', { class: progress.primary_change > 0 ? 'text-success' : progress.primary_change < 0 ? 'text-danger' : 'text-muted' }, + `${signed(progress.primary_change)} ${unit}`, + progress.primary_change_percent !== null ? ` (${progress.primary_change_percent >= 0 ? '+' : ''}${progress.primary_change_percent.toFixed(1)}%)` : ''), + ' к первой тренировке'); + + const card = (title, value, note, hint) => h('div', { class: 'col' }, + h('div', { class: 'card h-100 mb-0' }, h('div', { class: 'card-body' }, + h('div', { class: 'text-muted small' }, tip(title, hint)), + h('div', { class: 'fs-4 fw-semibold' }, value), + h('div', { class: 'text-muted small' }, note)))); + + const cards = weighted ? [ + card('Рекорд e1RM', `${num(progress.best_primary.value)} кг`, formatDate(progress.best_primary.date), HINTS.recordE1rm), + card('Последний e1RM', `${num(progress.last_primary)} кг`, rows.length > 1 ? change('кг') : '', HINTS.lastE1rm), + card('Рекорд тоннажа', `${num(progress.best_secondary.value)} кг`, formatDate(progress.best_secondary.date), HINTS.recordVolume), + card('Максимальный вес', `${num(progress.max_weight)} кг`, '', HINTS.maxWeight), + ] : [ + card('Лучший подход', `${num(progress.best_primary.value)} повт.`, formatDate(progress.best_primary.date), HINTS.bestReps), + card('Лучший подход в последний раз', `${num(progress.last_primary)} повт.`, rows.length > 1 ? change('повт.') : '', HINTS.lastBestReps), + card('Рекорд суммы повторов', num(progress.best_secondary.value), formatDate(progress.best_secondary.date), HINTS.recordTotalReps), + ]; + + const columns = [ + { title: 'Дата', className: 'text-nowrap date', sort: (row) => row.date, cell: (row) => formatDate(row.date) }, + { title: 'Тренер', className: 'text-nowrap', sort: (row) => row.trainer || '', cell: (row) => row.trainer || '' }, + { title: 'Подходы (вес × повторения)', cell: (row) => h('span', {}, ...approachChips(row.approaches), row.splitted_weight ? perArmBadge() : null) }, + ...(weighted ? [ + { title: 'Макс. вес', className: 'text-nowrap text-end', sort: (row) => row.metrics.max_weight, cell: (row) => row.metrics.max_weight ? `${num(row.metrics.max_weight)} кг` : '—' }, + { title: tip('e1RM', HINTS.e1rm), className: 'text-nowrap text-end', sort: (row) => row.metrics.e1rm || 0, cell: (row) => row.metrics.e1rm ? `${num(row.metrics.e1rm)} кг` : '—' }, + { title: tip('Тоннаж', HINTS.volume), className: 'text-nowrap text-end', sort: (row) => row.metrics.volume, cell: (row) => row.metrics.volume ? `${num(row.metrics.volume)} кг` : '—' }, + ] : [ + { title: 'Лучший подход', className: 'text-nowrap text-end', sort: (row) => row.metrics.best_reps, cell: (row) => `${row.metrics.best_reps}` }, + { title: 'Всего повторов', className: 'text-nowrap text-end', sort: (row) => row.metrics.total_reps, cell: (row) => `${row.metrics.total_reps}` }, + ]), + ]; + + return [ + h('h2', { class: 'h4' }, progress.name), + h('p', { class: 'text-muted' }, + 'Тренировок: ', h('strong', {}, `${rows.length}`), + ', первая: ', h('strong', {}, formatDate(first.date)), + ', последняя: ', h('strong', {}, formatDate(last.date))), + h('div', { class: 'row row-cols-1 row-cols-sm-2 row-cols-xl-4 g-3 mb-4' }, ...cards), + h('div', { class: 'card mb-2' }, h('div', { class: 'card-body' }, + h('div', { style: 'height: 320px' }, h('canvas', { id: 'progress-chart' })))), + h('p', { class: 'text-muted small mb-4' }, weighted + ? 'e1RM — расчётный максимум на один повтор по формуле Эпли: вес × (1 + повторы / 30), берётся лучший подход тренировки; подходы без веса не учитываются. Тоннаж — сумма вес × повторы по подходам с весом.' + : 'Упражнение выполняется без дополнительного веса, поэтому прогресс считается по повторам.'), + createTable({ id: 'exercise-history-table', columns, rows }), + ]; +} + +/** Two series over time, each on its own y axis. The x axis is linear so gaps between + * trainings are proportional to the real time. */ +function drawChart(progress) { + const series = progress.weighted + ? [['e1RM, кг', (row) => row.metrics.e1rm], ['Тоннаж, кг', (row) => row.metrics.volume || null]] + : [['Лучший подход, повторы', (row) => row.metrics.best_reps], ['Всего повторов за тренировку', (row) => row.metrics.total_reps]]; + const chronological = [...progress.rows].reverse(); + const datasets = series.map(([label, metric]) => ({ + label, + points: chronological + .map((row) => ({ x: Date.parse(row.date), y: metric(row) })) // "YYYY-MM-DD" parses as UTC + .filter((point) => point.y !== null && point.y !== undefined) + .map((point) => ({ x: point.x, y: Math.round(point.y * 10) / 10 })), + })); + + const colors = ['#0d6efd', '#fd7e14']; + const formatTick = (timestamp, options) => + new Date(timestamp).toLocaleDateString('ru-RU', { ...options, timeZone: 'UTC' }); + + const scales = { + x: { type: 'linear', ticks: { maxTicksLimit: 8, callback: (value) => formatTick(value, { month: 'short', year: 'numeric' }) } }, + }; + datasets.forEach((item, index) => { + scales['y' + index] = { + position: index === 0 ? 'left' : 'right', + grid: { drawOnChartArea: index === 0 }, + title: { display: true, text: item.label, color: colors[index] }, + }; + }); + + new Chart(document.getElementById('progress-chart'), { + type: 'line', + data: { + datasets: datasets.map((item, index) => ({ + label: item.label, + data: item.points, + yAxisID: 'y' + index, + borderColor: colors[index], + backgroundColor: colors[index], + borderWidth: 2, + pointRadius: 3, + tension: 0.2, + })), + }, + options: { + maintainAspectRatio: false, + interaction: { mode: 'nearest', axis: 'x', intersect: false }, + scales, + plugins: { tooltip: { callbacks: { title: (items) => formatTick(items[0].parsed.x, {}) } } }, + }, + }); +} diff --git a/frontend/js/parse.js b/frontend/js/parse.js new file mode 100644 index 0000000..37e1a0c --- /dev/null +++ b/frontend/js/parse.js @@ -0,0 +1,23 @@ +import { alert, api } from './common.js'; +import { trainingsView } from './trainings-view.js'; + +const form = document.getElementById('parse-form'); +const result = document.getElementById('result'); + +form.addEventListener('submit', async (event) => { + event.preventDefault(); + result.replaceChildren(alert('info', 'Разбираю…')); + try { + const trainings = await api('/parser/parse/', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + data: document.getElementById('training-data').value, + format: document.getElementById('format').value, + }), + }); + result.replaceChildren(trainings.length ? trainingsView(trainings) : alert('warning', 'Тренировки не найдены')); + } catch (error) { + result.replaceChildren(alert('danger', `Не удалось разобрать заметку: ${error.message}`)); + } +}); diff --git a/frontend/js/table.js b/frontend/js/table.js new file mode 100644 index 0000000..0462fc1 --- /dev/null +++ b/frontend/js/table.js @@ -0,0 +1,33 @@ +// Table with search, sorting and paging by DataTables (no jQuery: DataTables 3.x) + +import { h } from './common.js'; + +/** + * columns: [{ title, cell(row) -> Node | string, sort?(row) -> number | string, className? }] + * A column without `sort` is not sortable. Rows keep the order they were given in until a + * header is clicked. + */ +export function createTable({ id, columns, rows, pageLength = 50 }) { + const head = h('tr', {}, ...columns.map((column) => + h('th', { scope: 'col', class: column.className || '' }, column.title))); + + // data-order: plain numbers and ISO dates, so sorting is numeric/chronological + const body = h('tbody', {}, ...rows.map((row) => + h('tr', {}, ...columns.map((column) => + h('td', { class: column.className || '', 'data-order': column.sort ? column.sort(row) : null }, + column.cell(row)))))); + + const table = h('table', { class: 'table table-sm table-hover align-middle', id }, h('thead', {}, head), body); + const wrapper = h('div', {}, table); + + new DataTable(table, { + pageLength, + lengthMenu: [25, 50, 100, 200], + order: [], // keep the order from the server: newest first + columnDefs: columns.flatMap((column, index) => + column.sort ? [] : [{ targets: index, orderable: false }]), + language: { url: 'vendor/datatables-ru.json' }, + }); + + return wrapper; +} diff --git a/frontend/js/trainings-view.js b/frontend/js/trainings-view.js new file mode 100644 index 0000000..d487c22 --- /dev/null +++ b/frontend/js/trainings-view.js @@ -0,0 +1,39 @@ +// One table for all trainings: a row per exercise + +import { alert, approachChips, formatDate, h, perArmBadge } from './common.js'; +import { createTable } from './table.js'; + +export function trainingsView(trainings) { + if (!trainings.length) { + return alert('info', 'Тренировок нет.'); + } + + // A training without exercises still gets a row, so it doesn't disappear from the list + const rows = trainings.flatMap((training) => + training.exercises?.length + ? training.exercises.map((exercise) => ({ training, exercise })) + : [{ training, exercise: null }]); + + const exerciseCount = rows.filter((row) => row.exercise).length; + + return h('div', {}, + h('p', { class: 'text-muted' }, + 'Тренировок: ', h('strong', {}, `${trainings.length}`), + ', упражнений: ', h('strong', {}, `${exerciseCount}`)), + createTable({ + id: 'trainings-table', + rows, + columns: [ + { title: 'Дата', className: 'text-nowrap date', sort: (row) => row.training.date, cell: (row) => formatDate(row.training.date) }, + { title: 'Тренер', className: 'text-nowrap', sort: (row) => row.training.trainer || '', cell: (row) => row.training.trainer || '' }, + { + title: 'Упражнение', + sort: (row) => row.exercise?.name || '', + cell: (row) => row.exercise + ? h('span', {}, row.exercise.name, ' ', row.exercise.splitted_weight ? perArmBadge() : null) + : h('span', { class: 'text-muted fst-italic' }, 'Упражнения не записаны'), + }, + { title: 'Подходы (вес × повторения)', cell: (row) => h('span', {}, ...(row.exercise ? approachChips(row.exercise.approaches) : [])) }, + ], + })); +} diff --git a/frontend/js/trainings.js b/frontend/js/trainings.js new file mode 100644 index 0000000..c2b30a4 --- /dev/null +++ b/frontend/js/trainings.js @@ -0,0 +1,10 @@ +import { alert, api } from './common.js'; +import { trainingsView } from './trainings-view.js'; + +const container = document.getElementById('trainings'); + +try { + container.replaceChildren(trainingsView(await api('/trainings/'))); +} catch (error) { + container.replaceChildren(alert('danger', `Не удалось загрузить тренировки: ${error.message}`)); +} diff --git a/frontend/nginx.conf b/frontend/nginx.conf new file mode 100644 index 0000000..c2c1872 --- /dev/null +++ b/frontend/nginx.conf @@ -0,0 +1,18 @@ +server { + listen 80; + root /usr/share/nginx/html; + index index.html; + + # The API lives in the backend container; going through the same origin means no CORS + location /api/ { + proxy_pass http://fastapi-app:8000; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + } + + location / { + try_files $uri $uri/ =404; + } +} diff --git a/frontend/parse.html b/frontend/parse.html new file mode 100644 index 0000000..44e78d4 --- /dev/null +++ b/frontend/parse.html @@ -0,0 +1,48 @@ + + + + + + Разбор заметки - Fitness Parser + + + + + + +
+ + + +
+

Разобрать заметку

+
+
+ + +
+
+ + +
+ +
+
+
+
+ + + + + + diff --git a/app/static/css/bootstrap.min.css b/frontend/vendor/bootstrap.min.css similarity index 100% rename from app/static/css/bootstrap.min.css rename to frontend/vendor/bootstrap.min.css diff --git a/frontend/vendor/chart.umd.js b/frontend/vendor/chart.umd.js new file mode 100644 index 0000000..d9fd6ec --- /dev/null +++ b/frontend/vendor/chart.umd.js @@ -0,0 +1,14 @@ +/*! + * Chart.js v4.4.7 + * https://www.chartjs.org + * (c) 2024 Chart.js Contributors + * Released under the MIT License + */ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).Chart=e()}(this,(function(){"use strict";var t=Object.freeze({__proto__:null,get Colors(){return Go},get Decimation(){return Qo},get Filler(){return ma},get Legend(){return ya},get SubTitle(){return ka},get Title(){return Ma},get Tooltip(){return Ba}});function e(){}const i=(()=>{let t=0;return()=>t++})();function s(t){return null==t}function n(t){if(Array.isArray&&Array.isArray(t))return!0;const e=Object.prototype.toString.call(t);return"[object"===e.slice(0,7)&&"Array]"===e.slice(-6)}function o(t){return null!==t&&"[object Object]"===Object.prototype.toString.call(t)}function a(t){return("number"==typeof t||t instanceof Number)&&isFinite(+t)}function r(t,e){return a(t)?t:e}function l(t,e){return void 0===t?e:t}const h=(t,e)=>"string"==typeof t&&t.endsWith("%")?parseFloat(t)/100:+t/e,c=(t,e)=>"string"==typeof t&&t.endsWith("%")?parseFloat(t)/100*e:+t;function d(t,e,i){if(t&&"function"==typeof t.call)return t.apply(i,e)}function u(t,e,i,s){let a,r,l;if(n(t))if(r=t.length,s)for(a=r-1;a>=0;a--)e.call(i,t[a],a);else for(a=0;at,x:t=>t.x,y:t=>t.y};function v(t){const e=t.split("."),i=[];let s="";for(const t of e)s+=t,s.endsWith("\\")?s=s.slice(0,-1)+".":(i.push(s),s="");return i}function M(t,e){const i=y[e]||(y[e]=function(t){const e=v(t);return t=>{for(const i of e){if(""===i)break;t=t&&t[i]}return t}}(e));return i(t)}function w(t){return t.charAt(0).toUpperCase()+t.slice(1)}const k=t=>void 0!==t,S=t=>"function"==typeof t,P=(t,e)=>{if(t.size!==e.size)return!1;for(const i of t)if(!e.has(i))return!1;return!0};function D(t){return"mouseup"===t.type||"click"===t.type||"contextmenu"===t.type}const C=Math.PI,O=2*C,A=O+C,T=Number.POSITIVE_INFINITY,L=C/180,E=C/2,R=C/4,I=2*C/3,z=Math.log10,F=Math.sign;function V(t,e,i){return Math.abs(t-e)t-e)).pop(),e}function N(t){return!isNaN(parseFloat(t))&&isFinite(t)}function H(t,e){const i=Math.round(t);return i-e<=t&&i+e>=t}function j(t,e,i){let s,n,o;for(s=0,n=t.length;sl&&h=Math.min(e,i)-s&&t<=Math.max(e,i)+s}function et(t,e,i){i=i||(i=>t[i]1;)s=o+n>>1,i(s)?o=s:n=s;return{lo:o,hi:n}}const it=(t,e,i,s)=>et(t,i,s?s=>{const n=t[s][e];return nt[s][e]et(t,i,(s=>t[s][e]>=i));function nt(t,e,i){let s=0,n=t.length;for(;ss&&t[n-1]>i;)n--;return s>0||n{const i="_onData"+w(e),s=t[e];Object.defineProperty(t,e,{configurable:!0,enumerable:!1,value(...e){const n=s.apply(this,e);return t._chartjs.listeners.forEach((t=>{"function"==typeof t[i]&&t[i](...e)})),n}})})))}function rt(t,e){const i=t._chartjs;if(!i)return;const s=i.listeners,n=s.indexOf(e);-1!==n&&s.splice(n,1),s.length>0||(ot.forEach((e=>{delete t[e]})),delete t._chartjs)}function lt(t){const e=new Set(t);return e.size===t.length?t:Array.from(e)}const ht="undefined"==typeof window?function(t){return t()}:window.requestAnimationFrame;function ct(t,e){let i=[],s=!1;return function(...n){i=n,s||(s=!0,ht.call(window,(()=>{s=!1,t.apply(e,i)})))}}function dt(t,e){let i;return function(...s){return e?(clearTimeout(i),i=setTimeout(t,e,s)):t.apply(this,s),e}}const ut=t=>"start"===t?"left":"end"===t?"right":"center",ft=(t,e,i)=>"start"===t?e:"end"===t?i:(e+i)/2,gt=(t,e,i,s)=>t===(s?"left":"right")?i:"center"===t?(e+i)/2:e;function pt(t,e,i){const s=e.length;let n=0,o=s;if(t._sorted){const{iScale:a,_parsed:r}=t,l=a.axis,{min:h,max:c,minDefined:d,maxDefined:u}=a.getUserBounds();d&&(n=J(Math.min(it(r,l,h).lo,i?s:it(e,l,a.getPixelForValue(h)).lo),0,s-1)),o=u?J(Math.max(it(r,a.axis,c,!0).hi+1,i?0:it(e,l,a.getPixelForValue(c),!0).hi+1),n,s)-n:s-n}return{start:n,count:o}}function mt(t){const{xScale:e,yScale:i,_scaleRanges:s}=t,n={xmin:e.min,xmax:e.max,ymin:i.min,ymax:i.max};if(!s)return t._scaleRanges=n,!0;const o=s.xmin!==e.min||s.xmax!==e.max||s.ymin!==i.min||s.ymax!==i.max;return Object.assign(s,n),o}class bt{constructor(){this._request=null,this._charts=new Map,this._running=!1,this._lastDate=void 0}_notify(t,e,i,s){const n=e.listeners[s],o=e.duration;n.forEach((s=>s({chart:t,initial:e.initial,numSteps:o,currentStep:Math.min(i-e.start,o)})))}_refresh(){this._request||(this._running=!0,this._request=ht.call(window,(()=>{this._update(),this._request=null,this._running&&this._refresh()})))}_update(t=Date.now()){let e=0;this._charts.forEach(((i,s)=>{if(!i.running||!i.items.length)return;const n=i.items;let o,a=n.length-1,r=!1;for(;a>=0;--a)o=n[a],o._active?(o._total>i.duration&&(i.duration=o._total),o.tick(t),r=!0):(n[a]=n[n.length-1],n.pop());r&&(s.draw(),this._notify(s,i,t,"progress")),n.length||(i.running=!1,this._notify(s,i,t,"complete"),i.initial=!1),e+=n.length})),this._lastDate=t,0===e&&(this._running=!1)}_getAnims(t){const e=this._charts;let i=e.get(t);return i||(i={running:!1,initial:!0,items:[],listeners:{complete:[],progress:[]}},e.set(t,i)),i}listen(t,e,i){this._getAnims(t).listeners[e].push(i)}add(t,e){e&&e.length&&this._getAnims(t).items.push(...e)}has(t){return this._getAnims(t).items.length>0}start(t){const e=this._charts.get(t);e&&(e.running=!0,e.start=Date.now(),e.duration=e.items.reduce(((t,e)=>Math.max(t,e._duration)),0),this._refresh())}running(t){if(!this._running)return!1;const e=this._charts.get(t);return!!(e&&e.running&&e.items.length)}stop(t){const e=this._charts.get(t);if(!e||!e.items.length)return;const i=e.items;let s=i.length-1;for(;s>=0;--s)i[s].cancel();e.items=[],this._notify(t,e,Date.now(),"complete")}remove(t){return this._charts.delete(t)}}var xt=new bt; +/*! + * @kurkle/color v0.3.2 + * https://github.com/kurkle/color#readme + * (c) 2023 Jukka Kurkela + * Released under the MIT License + */function _t(t){return t+.5|0}const yt=(t,e,i)=>Math.max(Math.min(t,i),e);function vt(t){return yt(_t(2.55*t),0,255)}function Mt(t){return yt(_t(255*t),0,255)}function wt(t){return yt(_t(t/2.55)/100,0,1)}function kt(t){return yt(_t(100*t),0,100)}const St={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,A:10,B:11,C:12,D:13,E:14,F:15,a:10,b:11,c:12,d:13,e:14,f:15},Pt=[..."0123456789ABCDEF"],Dt=t=>Pt[15&t],Ct=t=>Pt[(240&t)>>4]+Pt[15&t],Ot=t=>(240&t)>>4==(15&t);function At(t){var e=(t=>Ot(t.r)&&Ot(t.g)&&Ot(t.b)&&Ot(t.a))(t)?Dt:Ct;return t?"#"+e(t.r)+e(t.g)+e(t.b)+((t,e)=>t<255?e(t):"")(t.a,e):void 0}const Tt=/^(hsla?|hwb|hsv)\(\s*([-+.e\d]+)(?:deg)?[\s,]+([-+.e\d]+)%[\s,]+([-+.e\d]+)%(?:[\s,]+([-+.e\d]+)(%)?)?\s*\)$/;function Lt(t,e,i){const s=e*Math.min(i,1-i),n=(e,n=(e+t/30)%12)=>i-s*Math.max(Math.min(n-3,9-n,1),-1);return[n(0),n(8),n(4)]}function Et(t,e,i){const s=(s,n=(s+t/60)%6)=>i-i*e*Math.max(Math.min(n,4-n,1),0);return[s(5),s(3),s(1)]}function Rt(t,e,i){const s=Lt(t,1,.5);let n;for(e+i>1&&(n=1/(e+i),e*=n,i*=n),n=0;n<3;n++)s[n]*=1-e-i,s[n]+=e;return s}function It(t){const e=t.r/255,i=t.g/255,s=t.b/255,n=Math.max(e,i,s),o=Math.min(e,i,s),a=(n+o)/2;let r,l,h;return n!==o&&(h=n-o,l=a>.5?h/(2-n-o):h/(n+o),r=function(t,e,i,s,n){return t===n?(e-i)/s+(e>16&255,o>>8&255,255&o]}return t}(),Ht.transparent=[0,0,0,0]);const e=Ht[t.toLowerCase()];return e&&{r:e[0],g:e[1],b:e[2],a:4===e.length?e[3]:255}}const $t=/^rgba?\(\s*([-+.\d]+)(%)?[\s,]+([-+.e\d]+)(%)?[\s,]+([-+.e\d]+)(%)?(?:[\s,/]+([-+.e\d]+)(%)?)?\s*\)$/;const Yt=t=>t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055,Ut=t=>t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4);function Xt(t,e,i){if(t){let s=It(t);s[e]=Math.max(0,Math.min(s[e]+s[e]*i,0===e?360:1)),s=Ft(s),t.r=s[0],t.g=s[1],t.b=s[2]}}function qt(t,e){return t?Object.assign(e||{},t):t}function Kt(t){var e={r:0,g:0,b:0,a:255};return Array.isArray(t)?t.length>=3&&(e={r:t[0],g:t[1],b:t[2],a:255},t.length>3&&(e.a=Mt(t[3]))):(e=qt(t,{r:0,g:0,b:0,a:1})).a=Mt(e.a),e}function Gt(t){return"r"===t.charAt(0)?function(t){const e=$t.exec(t);let i,s,n,o=255;if(e){if(e[7]!==i){const t=+e[7];o=e[8]?vt(t):yt(255*t,0,255)}return i=+e[1],s=+e[3],n=+e[5],i=255&(e[2]?vt(i):yt(i,0,255)),s=255&(e[4]?vt(s):yt(s,0,255)),n=255&(e[6]?vt(n):yt(n,0,255)),{r:i,g:s,b:n,a:o}}}(t):Bt(t)}class Zt{constructor(t){if(t instanceof Zt)return t;const e=typeof t;let i;var s,n,o;"object"===e?i=Kt(t):"string"===e&&(o=(s=t).length,"#"===s[0]&&(4===o||5===o?n={r:255&17*St[s[1]],g:255&17*St[s[2]],b:255&17*St[s[3]],a:5===o?17*St[s[4]]:255}:7!==o&&9!==o||(n={r:St[s[1]]<<4|St[s[2]],g:St[s[3]]<<4|St[s[4]],b:St[s[5]]<<4|St[s[6]],a:9===o?St[s[7]]<<4|St[s[8]]:255})),i=n||jt(t)||Gt(t)),this._rgb=i,this._valid=!!i}get valid(){return this._valid}get rgb(){var t=qt(this._rgb);return t&&(t.a=wt(t.a)),t}set rgb(t){this._rgb=Kt(t)}rgbString(){return this._valid?(t=this._rgb)&&(t.a<255?`rgba(${t.r}, ${t.g}, ${t.b}, ${wt(t.a)})`:`rgb(${t.r}, ${t.g}, ${t.b})`):void 0;var t}hexString(){return this._valid?At(this._rgb):void 0}hslString(){return this._valid?function(t){if(!t)return;const e=It(t),i=e[0],s=kt(e[1]),n=kt(e[2]);return t.a<255?`hsla(${i}, ${s}%, ${n}%, ${wt(t.a)})`:`hsl(${i}, ${s}%, ${n}%)`}(this._rgb):void 0}mix(t,e){if(t){const i=this.rgb,s=t.rgb;let n;const o=e===n?.5:e,a=2*o-1,r=i.a-s.a,l=((a*r==-1?a:(a+r)/(1+a*r))+1)/2;n=1-l,i.r=255&l*i.r+n*s.r+.5,i.g=255&l*i.g+n*s.g+.5,i.b=255&l*i.b+n*s.b+.5,i.a=o*i.a+(1-o)*s.a,this.rgb=i}return this}interpolate(t,e){return t&&(this._rgb=function(t,e,i){const s=Ut(wt(t.r)),n=Ut(wt(t.g)),o=Ut(wt(t.b));return{r:Mt(Yt(s+i*(Ut(wt(e.r))-s))),g:Mt(Yt(n+i*(Ut(wt(e.g))-n))),b:Mt(Yt(o+i*(Ut(wt(e.b))-o))),a:t.a+i*(e.a-t.a)}}(this._rgb,t._rgb,e)),this}clone(){return new Zt(this.rgb)}alpha(t){return this._rgb.a=Mt(t),this}clearer(t){return this._rgb.a*=1-t,this}greyscale(){const t=this._rgb,e=_t(.3*t.r+.59*t.g+.11*t.b);return t.r=t.g=t.b=e,this}opaquer(t){return this._rgb.a*=1+t,this}negate(){const t=this._rgb;return t.r=255-t.r,t.g=255-t.g,t.b=255-t.b,this}lighten(t){return Xt(this._rgb,2,t),this}darken(t){return Xt(this._rgb,2,-t),this}saturate(t){return Xt(this._rgb,1,t),this}desaturate(t){return Xt(this._rgb,1,-t),this}rotate(t){return function(t,e){var i=It(t);i[0]=Vt(i[0]+e),i=Ft(i),t.r=i[0],t.g=i[1],t.b=i[2]}(this._rgb,t),this}}function Jt(t){if(t&&"object"==typeof t){const e=t.toString();return"[object CanvasPattern]"===e||"[object CanvasGradient]"===e}return!1}function Qt(t){return Jt(t)?t:new Zt(t)}function te(t){return Jt(t)?t:new Zt(t).saturate(.5).darken(.1).hexString()}const ee=["x","y","borderWidth","radius","tension"],ie=["color","borderColor","backgroundColor"];const se=new Map;function ne(t,e,i){return function(t,e){e=e||{};const i=t+JSON.stringify(e);let s=se.get(i);return s||(s=new Intl.NumberFormat(t,e),se.set(i,s)),s}(e,i).format(t)}const oe={values:t=>n(t)?t:""+t,numeric(t,e,i){if(0===t)return"0";const s=this.chart.options.locale;let n,o=t;if(i.length>1){const e=Math.max(Math.abs(i[0].value),Math.abs(i[i.length-1].value));(e<1e-4||e>1e15)&&(n="scientific"),o=function(t,e){let i=e.length>3?e[2].value-e[1].value:e[1].value-e[0].value;Math.abs(i)>=1&&t!==Math.floor(t)&&(i=t-Math.floor(t));return i}(t,i)}const a=z(Math.abs(o)),r=isNaN(a)?1:Math.max(Math.min(-1*Math.floor(a),20),0),l={notation:n,minimumFractionDigits:r,maximumFractionDigits:r};return Object.assign(l,this.options.ticks.format),ne(t,s,l)},logarithmic(t,e,i){if(0===t)return"0";const s=i[e].significand||t/Math.pow(10,Math.floor(z(t)));return[1,2,3,5,10,15].includes(s)||e>.8*i.length?oe.numeric.call(this,t,e,i):""}};var ae={formatters:oe};const re=Object.create(null),le=Object.create(null);function he(t,e){if(!e)return t;const i=e.split(".");for(let e=0,s=i.length;et.chart.platform.getDevicePixelRatio(),this.elements={},this.events=["mousemove","mouseout","click","touchstart","touchmove"],this.font={family:"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",size:12,style:"normal",lineHeight:1.2,weight:null},this.hover={},this.hoverBackgroundColor=(t,e)=>te(e.backgroundColor),this.hoverBorderColor=(t,e)=>te(e.borderColor),this.hoverColor=(t,e)=>te(e.color),this.indexAxis="x",this.interaction={mode:"nearest",intersect:!0,includeInvisible:!1},this.maintainAspectRatio=!0,this.onHover=null,this.onClick=null,this.parsing=!0,this.plugins={},this.responsive=!0,this.scale=void 0,this.scales={},this.showLine=!0,this.drawActiveElementsOnTop=!0,this.describe(t),this.apply(e)}set(t,e){return ce(this,t,e)}get(t){return he(this,t)}describe(t,e){return ce(le,t,e)}override(t,e){return ce(re,t,e)}route(t,e,i,s){const n=he(this,t),a=he(this,i),r="_"+e;Object.defineProperties(n,{[r]:{value:n[e],writable:!0},[e]:{enumerable:!0,get(){const t=this[r],e=a[s];return o(t)?Object.assign({},e,t):l(t,e)},set(t){this[r]=t}}})}apply(t){t.forEach((t=>t(this)))}}var ue=new de({_scriptable:t=>!t.startsWith("on"),_indexable:t=>"events"!==t,hover:{_fallback:"interaction"},interaction:{_scriptable:!1,_indexable:!1}},[function(t){t.set("animation",{delay:void 0,duration:1e3,easing:"easeOutQuart",fn:void 0,from:void 0,loop:void 0,to:void 0,type:void 0}),t.describe("animation",{_fallback:!1,_indexable:!1,_scriptable:t=>"onProgress"!==t&&"onComplete"!==t&&"fn"!==t}),t.set("animations",{colors:{type:"color",properties:ie},numbers:{type:"number",properties:ee}}),t.describe("animations",{_fallback:"animation"}),t.set("transitions",{active:{animation:{duration:400}},resize:{animation:{duration:0}},show:{animations:{colors:{from:"transparent"},visible:{type:"boolean",duration:0}}},hide:{animations:{colors:{to:"transparent"},visible:{type:"boolean",easing:"linear",fn:t=>0|t}}}})},function(t){t.set("layout",{autoPadding:!0,padding:{top:0,right:0,bottom:0,left:0}})},function(t){t.set("scale",{display:!0,offset:!1,reverse:!1,beginAtZero:!1,bounds:"ticks",clip:!0,grace:0,grid:{display:!0,lineWidth:1,drawOnChartArea:!0,drawTicks:!0,tickLength:8,tickWidth:(t,e)=>e.lineWidth,tickColor:(t,e)=>e.color,offset:!1},border:{display:!0,dash:[],dashOffset:0,width:1},title:{display:!1,text:"",padding:{top:4,bottom:4}},ticks:{minRotation:0,maxRotation:50,mirror:!1,textStrokeWidth:0,textStrokeColor:"",padding:3,display:!0,autoSkip:!0,autoSkipPadding:3,labelOffset:0,callback:ae.formatters.values,minor:{},major:{},align:"center",crossAlign:"near",showLabelBackdrop:!1,backdropColor:"rgba(255, 255, 255, 0.75)",backdropPadding:2}}),t.route("scale.ticks","color","","color"),t.route("scale.grid","color","","borderColor"),t.route("scale.border","color","","borderColor"),t.route("scale.title","color","","color"),t.describe("scale",{_fallback:!1,_scriptable:t=>!t.startsWith("before")&&!t.startsWith("after")&&"callback"!==t&&"parser"!==t,_indexable:t=>"borderDash"!==t&&"tickBorderDash"!==t&&"dash"!==t}),t.describe("scales",{_fallback:"scale"}),t.describe("scale.ticks",{_scriptable:t=>"backdropPadding"!==t&&"callback"!==t,_indexable:t=>"backdropPadding"!==t})}]);function fe(){return"undefined"!=typeof window&&"undefined"!=typeof document}function ge(t){let e=t.parentNode;return e&&"[object ShadowRoot]"===e.toString()&&(e=e.host),e}function pe(t,e,i){let s;return"string"==typeof t?(s=parseInt(t,10),-1!==t.indexOf("%")&&(s=s/100*e.parentNode[i])):s=t,s}const me=t=>t.ownerDocument.defaultView.getComputedStyle(t,null);function be(t,e){return me(t).getPropertyValue(e)}const xe=["top","right","bottom","left"];function _e(t,e,i){const s={};i=i?"-"+i:"";for(let n=0;n<4;n++){const o=xe[n];s[o]=parseFloat(t[e+"-"+o+i])||0}return s.width=s.left+s.right,s.height=s.top+s.bottom,s}const ye=(t,e,i)=>(t>0||e>0)&&(!i||!i.shadowRoot);function ve(t,e){if("native"in t)return t;const{canvas:i,currentDevicePixelRatio:s}=e,n=me(i),o="border-box"===n.boxSizing,a=_e(n,"padding"),r=_e(n,"border","width"),{x:l,y:h,box:c}=function(t,e){const i=t.touches,s=i&&i.length?i[0]:t,{offsetX:n,offsetY:o}=s;let a,r,l=!1;if(ye(n,o,t.target))a=n,r=o;else{const t=e.getBoundingClientRect();a=s.clientX-t.left,r=s.clientY-t.top,l=!0}return{x:a,y:r,box:l}}(t,i),d=a.left+(c&&r.left),u=a.top+(c&&r.top);let{width:f,height:g}=e;return o&&(f-=a.width+r.width,g-=a.height+r.height),{x:Math.round((l-d)/f*i.width/s),y:Math.round((h-u)/g*i.height/s)}}const Me=t=>Math.round(10*t)/10;function we(t,e,i,s){const n=me(t),o=_e(n,"margin"),a=pe(n.maxWidth,t,"clientWidth")||T,r=pe(n.maxHeight,t,"clientHeight")||T,l=function(t,e,i){let s,n;if(void 0===e||void 0===i){const o=t&&ge(t);if(o){const t=o.getBoundingClientRect(),a=me(o),r=_e(a,"border","width"),l=_e(a,"padding");e=t.width-l.width-r.width,i=t.height-l.height-r.height,s=pe(a.maxWidth,o,"clientWidth"),n=pe(a.maxHeight,o,"clientHeight")}else e=t.clientWidth,i=t.clientHeight}return{width:e,height:i,maxWidth:s||T,maxHeight:n||T}}(t,e,i);let{width:h,height:c}=l;if("content-box"===n.boxSizing){const t=_e(n,"border","width"),e=_e(n,"padding");h-=e.width+t.width,c-=e.height+t.height}h=Math.max(0,h-o.width),c=Math.max(0,s?h/s:c-o.height),h=Me(Math.min(h,a,l.maxWidth)),c=Me(Math.min(c,r,l.maxHeight)),h&&!c&&(c=Me(h/2));return(void 0!==e||void 0!==i)&&s&&l.height&&c>l.height&&(c=l.height,h=Me(Math.floor(c*s))),{width:h,height:c}}function ke(t,e,i){const s=e||1,n=Math.floor(t.height*s),o=Math.floor(t.width*s);t.height=Math.floor(t.height),t.width=Math.floor(t.width);const a=t.canvas;return a.style&&(i||!a.style.height&&!a.style.width)&&(a.style.height=`${t.height}px`,a.style.width=`${t.width}px`),(t.currentDevicePixelRatio!==s||a.height!==n||a.width!==o)&&(t.currentDevicePixelRatio=s,a.height=n,a.width=o,t.ctx.setTransform(s,0,0,s,0,0),!0)}const Se=function(){let t=!1;try{const e={get passive(){return t=!0,!1}};fe()&&(window.addEventListener("test",null,e),window.removeEventListener("test",null,e))}catch(t){}return t}();function Pe(t,e){const i=be(t,e),s=i&&i.match(/^(\d+)(\.\d+)?px$/);return s?+s[1]:void 0}function De(t){return!t||s(t.size)||s(t.family)?null:(t.style?t.style+" ":"")+(t.weight?t.weight+" ":"")+t.size+"px "+t.family}function Ce(t,e,i,s,n){let o=e[n];return o||(o=e[n]=t.measureText(n).width,i.push(n)),o>s&&(s=o),s}function Oe(t,e,i,s){let o=(s=s||{}).data=s.data||{},a=s.garbageCollect=s.garbageCollect||[];s.font!==e&&(o=s.data={},a=s.garbageCollect=[],s.font=e),t.save(),t.font=e;let r=0;const l=i.length;let h,c,d,u,f;for(h=0;hi.length){for(h=0;h0&&t.stroke()}}function Re(t,e,i){return i=i||.5,!e||t&&t.x>e.left-i&&t.xe.top-i&&t.y0&&""!==r.strokeColor;let c,d;for(t.save(),t.font=a.string,function(t,e){e.translation&&t.translate(e.translation[0],e.translation[1]),s(e.rotation)||t.rotate(e.rotation),e.color&&(t.fillStyle=e.color),e.textAlign&&(t.textAlign=e.textAlign),e.textBaseline&&(t.textBaseline=e.textBaseline)}(t,r),c=0;ct[0])){const o=i||t;void 0===s&&(s=ti("_fallback",t));const a={[Symbol.toStringTag]:"Object",_cacheable:!0,_scopes:t,_rootScopes:o,_fallback:s,_getTarget:n,override:i=>je([i,...t],e,o,s)};return new Proxy(a,{deleteProperty:(e,i)=>(delete e[i],delete e._keys,delete t[0][i],!0),get:(i,s)=>qe(i,s,(()=>function(t,e,i,s){let n;for(const o of e)if(n=ti(Ue(o,t),i),void 0!==n)return Xe(t,n)?Je(i,s,t,n):n}(s,e,t,i))),getOwnPropertyDescriptor:(t,e)=>Reflect.getOwnPropertyDescriptor(t._scopes[0],e),getPrototypeOf:()=>Reflect.getPrototypeOf(t[0]),has:(t,e)=>ei(t).includes(e),ownKeys:t=>ei(t),set(t,e,i){const s=t._storage||(t._storage=n());return t[e]=s[e]=i,delete t._keys,!0}})}function $e(t,e,i,s){const a={_cacheable:!1,_proxy:t,_context:e,_subProxy:i,_stack:new Set,_descriptors:Ye(t,s),setContext:e=>$e(t,e,i,s),override:n=>$e(t.override(n),e,i,s)};return new Proxy(a,{deleteProperty:(e,i)=>(delete e[i],delete t[i],!0),get:(t,e,i)=>qe(t,e,(()=>function(t,e,i){const{_proxy:s,_context:a,_subProxy:r,_descriptors:l}=t;let h=s[e];S(h)&&l.isScriptable(e)&&(h=function(t,e,i,s){const{_proxy:n,_context:o,_subProxy:a,_stack:r}=i;if(r.has(t))throw new Error("Recursion detected: "+Array.from(r).join("->")+"->"+t);r.add(t);let l=e(o,a||s);r.delete(t),Xe(t,l)&&(l=Je(n._scopes,n,t,l));return l}(e,h,t,i));n(h)&&h.length&&(h=function(t,e,i,s){const{_proxy:n,_context:a,_subProxy:r,_descriptors:l}=i;if(void 0!==a.index&&s(t))return e[a.index%e.length];if(o(e[0])){const i=e,s=n._scopes.filter((t=>t!==i));e=[];for(const o of i){const i=Je(s,n,t,o);e.push($e(i,a,r&&r[t],l))}}return e}(e,h,t,l.isIndexable));Xe(e,h)&&(h=$e(h,a,r&&r[e],l));return h}(t,e,i))),getOwnPropertyDescriptor:(e,i)=>e._descriptors.allKeys?Reflect.has(t,i)?{enumerable:!0,configurable:!0}:void 0:Reflect.getOwnPropertyDescriptor(t,i),getPrototypeOf:()=>Reflect.getPrototypeOf(t),has:(e,i)=>Reflect.has(t,i),ownKeys:()=>Reflect.ownKeys(t),set:(e,i,s)=>(t[i]=s,delete e[i],!0)})}function Ye(t,e={scriptable:!0,indexable:!0}){const{_scriptable:i=e.scriptable,_indexable:s=e.indexable,_allKeys:n=e.allKeys}=t;return{allKeys:n,scriptable:i,indexable:s,isScriptable:S(i)?i:()=>i,isIndexable:S(s)?s:()=>s}}const Ue=(t,e)=>t?t+w(e):e,Xe=(t,e)=>o(e)&&"adapters"!==t&&(null===Object.getPrototypeOf(e)||e.constructor===Object);function qe(t,e,i){if(Object.prototype.hasOwnProperty.call(t,e)||"constructor"===e)return t[e];const s=i();return t[e]=s,s}function Ke(t,e,i){return S(t)?t(e,i):t}const Ge=(t,e)=>!0===t?e:"string"==typeof t?M(e,t):void 0;function Ze(t,e,i,s,n){for(const o of e){const e=Ge(i,o);if(e){t.add(e);const o=Ke(e._fallback,i,n);if(void 0!==o&&o!==i&&o!==s)return o}else if(!1===e&&void 0!==s&&i!==s)return null}return!1}function Je(t,e,i,s){const a=e._rootScopes,r=Ke(e._fallback,i,s),l=[...t,...a],h=new Set;h.add(s);let c=Qe(h,l,i,r||i,s);return null!==c&&((void 0===r||r===i||(c=Qe(h,l,r,c,s),null!==c))&&je(Array.from(h),[""],a,r,(()=>function(t,e,i){const s=t._getTarget();e in s||(s[e]={});const a=s[e];if(n(a)&&o(i))return i;return a||{}}(e,i,s))))}function Qe(t,e,i,s,n){for(;i;)i=Ze(t,e,i,s,n);return i}function ti(t,e){for(const i of e){if(!i)continue;const e=i[t];if(void 0!==e)return e}}function ei(t){let e=t._keys;return e||(e=t._keys=function(t){const e=new Set;for(const i of t)for(const t of Object.keys(i).filter((t=>!t.startsWith("_"))))e.add(t);return Array.from(e)}(t._scopes)),e}function ii(t,e,i,s){const{iScale:n}=t,{key:o="r"}=this._parsing,a=new Array(s);let r,l,h,c;for(r=0,l=s;re"x"===t?"y":"x";function ai(t,e,i,s){const n=t.skip?e:t,o=e,a=i.skip?e:i,r=q(o,n),l=q(a,o);let h=r/(r+l),c=l/(r+l);h=isNaN(h)?0:h,c=isNaN(c)?0:c;const d=s*h,u=s*c;return{previous:{x:o.x-d*(a.x-n.x),y:o.y-d*(a.y-n.y)},next:{x:o.x+u*(a.x-n.x),y:o.y+u*(a.y-n.y)}}}function ri(t,e="x"){const i=oi(e),s=t.length,n=Array(s).fill(0),o=Array(s);let a,r,l,h=ni(t,0);for(a=0;a!t.skip))),"monotone"===e.cubicInterpolationMode)ri(t,n);else{let i=s?t[t.length-1]:t[0];for(o=0,a=t.length;o0===t||1===t,di=(t,e,i)=>-Math.pow(2,10*(t-=1))*Math.sin((t-e)*O/i),ui=(t,e,i)=>Math.pow(2,-10*t)*Math.sin((t-e)*O/i)+1,fi={linear:t=>t,easeInQuad:t=>t*t,easeOutQuad:t=>-t*(t-2),easeInOutQuad:t=>(t/=.5)<1?.5*t*t:-.5*(--t*(t-2)-1),easeInCubic:t=>t*t*t,easeOutCubic:t=>(t-=1)*t*t+1,easeInOutCubic:t=>(t/=.5)<1?.5*t*t*t:.5*((t-=2)*t*t+2),easeInQuart:t=>t*t*t*t,easeOutQuart:t=>-((t-=1)*t*t*t-1),easeInOutQuart:t=>(t/=.5)<1?.5*t*t*t*t:-.5*((t-=2)*t*t*t-2),easeInQuint:t=>t*t*t*t*t,easeOutQuint:t=>(t-=1)*t*t*t*t+1,easeInOutQuint:t=>(t/=.5)<1?.5*t*t*t*t*t:.5*((t-=2)*t*t*t*t+2),easeInSine:t=>1-Math.cos(t*E),easeOutSine:t=>Math.sin(t*E),easeInOutSine:t=>-.5*(Math.cos(C*t)-1),easeInExpo:t=>0===t?0:Math.pow(2,10*(t-1)),easeOutExpo:t=>1===t?1:1-Math.pow(2,-10*t),easeInOutExpo:t=>ci(t)?t:t<.5?.5*Math.pow(2,10*(2*t-1)):.5*(2-Math.pow(2,-10*(2*t-1))),easeInCirc:t=>t>=1?t:-(Math.sqrt(1-t*t)-1),easeOutCirc:t=>Math.sqrt(1-(t-=1)*t),easeInOutCirc:t=>(t/=.5)<1?-.5*(Math.sqrt(1-t*t)-1):.5*(Math.sqrt(1-(t-=2)*t)+1),easeInElastic:t=>ci(t)?t:di(t,.075,.3),easeOutElastic:t=>ci(t)?t:ui(t,.075,.3),easeInOutElastic(t){const e=.1125;return ci(t)?t:t<.5?.5*di(2*t,e,.45):.5+.5*ui(2*t-1,e,.45)},easeInBack(t){const e=1.70158;return t*t*((e+1)*t-e)},easeOutBack(t){const e=1.70158;return(t-=1)*t*((e+1)*t+e)+1},easeInOutBack(t){let e=1.70158;return(t/=.5)<1?t*t*((1+(e*=1.525))*t-e)*.5:.5*((t-=2)*t*((1+(e*=1.525))*t+e)+2)},easeInBounce:t=>1-fi.easeOutBounce(1-t),easeOutBounce(t){const e=7.5625,i=2.75;return t<1/i?e*t*t:t<2/i?e*(t-=1.5/i)*t+.75:t<2.5/i?e*(t-=2.25/i)*t+.9375:e*(t-=2.625/i)*t+.984375},easeInOutBounce:t=>t<.5?.5*fi.easeInBounce(2*t):.5*fi.easeOutBounce(2*t-1)+.5};function gi(t,e,i,s){return{x:t.x+i*(e.x-t.x),y:t.y+i*(e.y-t.y)}}function pi(t,e,i,s){return{x:t.x+i*(e.x-t.x),y:"middle"===s?i<.5?t.y:e.y:"after"===s?i<1?t.y:e.y:i>0?e.y:t.y}}function mi(t,e,i,s){const n={x:t.cp2x,y:t.cp2y},o={x:e.cp1x,y:e.cp1y},a=gi(t,n,i),r=gi(n,o,i),l=gi(o,e,i),h=gi(a,r,i),c=gi(r,l,i);return gi(h,c,i)}const bi=/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/,xi=/^(normal|italic|initial|inherit|unset|(oblique( -?[0-9]?[0-9]deg)?))$/;function _i(t,e){const i=(""+t).match(bi);if(!i||"normal"===i[1])return 1.2*e;switch(t=+i[2],i[3]){case"px":return t;case"%":t/=100}return e*t}const yi=t=>+t||0;function vi(t,e){const i={},s=o(e),n=s?Object.keys(e):e,a=o(t)?s?i=>l(t[i],t[e[i]]):e=>t[e]:()=>t;for(const t of n)i[t]=yi(a(t));return i}function Mi(t){return vi(t,{top:"y",right:"x",bottom:"y",left:"x"})}function wi(t){return vi(t,["topLeft","topRight","bottomLeft","bottomRight"])}function ki(t){const e=Mi(t);return e.width=e.left+e.right,e.height=e.top+e.bottom,e}function Si(t,e){t=t||{},e=e||ue.font;let i=l(t.size,e.size);"string"==typeof i&&(i=parseInt(i,10));let s=l(t.style,e.style);s&&!(""+s).match(xi)&&(console.warn('Invalid font style specified: "'+s+'"'),s=void 0);const n={family:l(t.family,e.family),lineHeight:_i(l(t.lineHeight,e.lineHeight),i),size:i,style:s,weight:l(t.weight,e.weight),string:""};return n.string=De(n),n}function Pi(t,e,i,s){let o,a,r,l=!0;for(o=0,a=t.length;oi&&0===t?0:t+e;return{min:a(s,-Math.abs(o)),max:a(n,o)}}function Ci(t,e){return Object.assign(Object.create(t),e)}function Oi(t,e,i){return t?function(t,e){return{x:i=>t+t+e-i,setWidth(t){e=t},textAlign:t=>"center"===t?t:"right"===t?"left":"right",xPlus:(t,e)=>t-e,leftForLtr:(t,e)=>t-e}}(e,i):{x:t=>t,setWidth(t){},textAlign:t=>t,xPlus:(t,e)=>t+e,leftForLtr:(t,e)=>t}}function Ai(t,e){let i,s;"ltr"!==e&&"rtl"!==e||(i=t.canvas.style,s=[i.getPropertyValue("direction"),i.getPropertyPriority("direction")],i.setProperty("direction",e,"important"),t.prevTextDirection=s)}function Ti(t,e){void 0!==e&&(delete t.prevTextDirection,t.canvas.style.setProperty("direction",e[0],e[1]))}function Li(t){return"angle"===t?{between:Z,compare:K,normalize:G}:{between:tt,compare:(t,e)=>t-e,normalize:t=>t}}function Ei({start:t,end:e,count:i,loop:s,style:n}){return{start:t%i,end:e%i,loop:s&&(e-t+1)%i==0,style:n}}function Ri(t,e,i){if(!i)return[t];const{property:s,start:n,end:o}=i,a=e.length,{compare:r,between:l,normalize:h}=Li(s),{start:c,end:d,loop:u,style:f}=function(t,e,i){const{property:s,start:n,end:o}=i,{between:a,normalize:r}=Li(s),l=e.length;let h,c,{start:d,end:u,loop:f}=t;if(f){for(d+=l,u+=l,h=0,c=l;hx||l(n,b,p)&&0!==r(n,b),v=()=>!x||0===r(o,p)||l(o,b,p);for(let t=c,i=c;t<=d;++t)m=e[t%a],m.skip||(p=h(m[s]),p!==b&&(x=l(p,n,o),null===_&&y()&&(_=0===r(p,n)?t:i),null!==_&&v()&&(g.push(Ei({start:_,end:t,loop:u,count:a,style:f})),_=null),i=t,b=p));return null!==_&&g.push(Ei({start:_,end:d,loop:u,count:a,style:f})),g}function Ii(t,e){const i=[],s=t.segments;for(let n=0;nn&&t[o%e].skip;)o--;return o%=e,{start:n,end:o}}(i,n,o,s);if(!0===s)return Fi(t,[{start:a,end:r,loop:o}],i,e);return Fi(t,function(t,e,i,s){const n=t.length,o=[];let a,r=e,l=t[e];for(a=e+1;a<=i;++a){const i=t[a%n];i.skip||i.stop?l.skip||(s=!1,o.push({start:e%n,end:(a-1)%n,loop:s}),e=r=i.stop?a:null):(r=a,l.skip&&(e=a)),l=i}return null!==r&&o.push({start:e%n,end:r%n,loop:s}),o}(i,a,r{t[a]&&t[a](e[i],n)&&(o.push({element:t,datasetIndex:s,index:l}),r=r||t.inRange(e.x,e.y,n))})),s&&!r?[]:o}var Xi={evaluateInteractionItems:Hi,modes:{index(t,e,i,s){const n=ve(e,t),o=i.axis||"x",a=i.includeInvisible||!1,r=i.intersect?ji(t,n,o,s,a):Yi(t,n,o,!1,s,a),l=[];return r.length?(t.getSortedVisibleDatasetMetas().forEach((t=>{const e=r[0].index,i=t.data[e];i&&!i.skip&&l.push({element:i,datasetIndex:t.index,index:e})})),l):[]},dataset(t,e,i,s){const n=ve(e,t),o=i.axis||"xy",a=i.includeInvisible||!1;let r=i.intersect?ji(t,n,o,s,a):Yi(t,n,o,!1,s,a);if(r.length>0){const e=r[0].datasetIndex,i=t.getDatasetMeta(e).data;r=[];for(let t=0;tji(t,ve(e,t),i.axis||"xy",s,i.includeInvisible||!1),nearest(t,e,i,s){const n=ve(e,t),o=i.axis||"xy",a=i.includeInvisible||!1;return Yi(t,n,o,i.intersect,s,a)},x:(t,e,i,s)=>Ui(t,ve(e,t),"x",i.intersect,s),y:(t,e,i,s)=>Ui(t,ve(e,t),"y",i.intersect,s)}};const qi=["left","top","right","bottom"];function Ki(t,e){return t.filter((t=>t.pos===e))}function Gi(t,e){return t.filter((t=>-1===qi.indexOf(t.pos)&&t.box.axis===e))}function Zi(t,e){return t.sort(((t,i)=>{const s=e?i:t,n=e?t:i;return s.weight===n.weight?s.index-n.index:s.weight-n.weight}))}function Ji(t,e){const i=function(t){const e={};for(const i of t){const{stack:t,pos:s,stackWeight:n}=i;if(!t||!qi.includes(s))continue;const o=e[t]||(e[t]={count:0,placed:0,weight:0,size:0});o.count++,o.weight+=n}return e}(t),{vBoxMaxWidth:s,hBoxMaxHeight:n}=e;let o,a,r;for(o=0,a=t.length;o{s[t]=Math.max(e[t],i[t])})),s}return s(t?["left","right"]:["top","bottom"])}function ss(t,e,i,s){const n=[];let o,a,r,l,h,c;for(o=0,a=t.length,h=0;ot.box.fullSize)),!0),s=Zi(Ki(e,"left"),!0),n=Zi(Ki(e,"right")),o=Zi(Ki(e,"top"),!0),a=Zi(Ki(e,"bottom")),r=Gi(e,"x"),l=Gi(e,"y");return{fullSize:i,leftAndTop:s.concat(o),rightAndBottom:n.concat(l).concat(a).concat(r),chartArea:Ki(e,"chartArea"),vertical:s.concat(n).concat(l),horizontal:o.concat(a).concat(r)}}(t.boxes),l=r.vertical,h=r.horizontal;u(t.boxes,(t=>{"function"==typeof t.beforeLayout&&t.beforeLayout()}));const c=l.reduce(((t,e)=>e.box.options&&!1===e.box.options.display?t:t+1),0)||1,d=Object.freeze({outerWidth:e,outerHeight:i,padding:n,availableWidth:o,availableHeight:a,vBoxMaxWidth:o/2/c,hBoxMaxHeight:a/2}),f=Object.assign({},n);ts(f,ki(s));const g=Object.assign({maxPadding:f,w:o,h:a,x:n.left,y:n.top},n),p=Ji(l.concat(h),d);ss(r.fullSize,g,d,p),ss(l,g,d,p),ss(h,g,d,p)&&ss(l,g,d,p),function(t){const e=t.maxPadding;function i(i){const s=Math.max(e[i]-t[i],0);return t[i]+=s,s}t.y+=i("top"),t.x+=i("left"),i("right"),i("bottom")}(g),os(r.leftAndTop,g,d,p),g.x+=g.w,g.y+=g.h,os(r.rightAndBottom,g,d,p),t.chartArea={left:g.left,top:g.top,right:g.left+g.w,bottom:g.top+g.h,height:g.h,width:g.w},u(r.chartArea,(e=>{const i=e.box;Object.assign(i,t.chartArea),i.update(g.w,g.h,{left:0,top:0,right:0,bottom:0})}))}};class rs{acquireContext(t,e){}releaseContext(t){return!1}addEventListener(t,e,i){}removeEventListener(t,e,i){}getDevicePixelRatio(){return 1}getMaximumSize(t,e,i,s){return e=Math.max(0,e||t.width),i=i||t.height,{width:e,height:Math.max(0,s?Math.floor(e/s):i)}}isAttached(t){return!0}updateConfig(t){}}class ls extends rs{acquireContext(t){return t&&t.getContext&&t.getContext("2d")||null}updateConfig(t){t.options.animation=!1}}const hs="$chartjs",cs={touchstart:"mousedown",touchmove:"mousemove",touchend:"mouseup",pointerenter:"mouseenter",pointerdown:"mousedown",pointermove:"mousemove",pointerup:"mouseup",pointerleave:"mouseout",pointerout:"mouseout"},ds=t=>null===t||""===t;const us=!!Se&&{passive:!0};function fs(t,e,i){t&&t.canvas&&t.canvas.removeEventListener(e,i,us)}function gs(t,e){for(const i of t)if(i===e||i.contains(e))return!0}function ps(t,e,i){const s=t.canvas,n=new MutationObserver((t=>{let e=!1;for(const i of t)e=e||gs(i.addedNodes,s),e=e&&!gs(i.removedNodes,s);e&&i()}));return n.observe(document,{childList:!0,subtree:!0}),n}function ms(t,e,i){const s=t.canvas,n=new MutationObserver((t=>{let e=!1;for(const i of t)e=e||gs(i.removedNodes,s),e=e&&!gs(i.addedNodes,s);e&&i()}));return n.observe(document,{childList:!0,subtree:!0}),n}const bs=new Map;let xs=0;function _s(){const t=window.devicePixelRatio;t!==xs&&(xs=t,bs.forEach(((e,i)=>{i.currentDevicePixelRatio!==t&&e()})))}function ys(t,e,i){const s=t.canvas,n=s&&ge(s);if(!n)return;const o=ct(((t,e)=>{const s=n.clientWidth;i(t,e),s{const e=t[0],i=e.contentRect.width,s=e.contentRect.height;0===i&&0===s||o(i,s)}));return a.observe(n),function(t,e){bs.size||window.addEventListener("resize",_s),bs.set(t,e)}(t,o),a}function vs(t,e,i){i&&i.disconnect(),"resize"===e&&function(t){bs.delete(t),bs.size||window.removeEventListener("resize",_s)}(t)}function Ms(t,e,i){const s=t.canvas,n=ct((e=>{null!==t.ctx&&i(function(t,e){const i=cs[t.type]||t.type,{x:s,y:n}=ve(t,e);return{type:i,chart:e,native:t,x:void 0!==s?s:null,y:void 0!==n?n:null}}(e,t))}),t);return function(t,e,i){t&&t.addEventListener(e,i,us)}(s,e,n),n}class ws extends rs{acquireContext(t,e){const i=t&&t.getContext&&t.getContext("2d");return i&&i.canvas===t?(function(t,e){const i=t.style,s=t.getAttribute("height"),n=t.getAttribute("width");if(t[hs]={initial:{height:s,width:n,style:{display:i.display,height:i.height,width:i.width}}},i.display=i.display||"block",i.boxSizing=i.boxSizing||"border-box",ds(n)){const e=Pe(t,"width");void 0!==e&&(t.width=e)}if(ds(s))if(""===t.style.height)t.height=t.width/(e||2);else{const e=Pe(t,"height");void 0!==e&&(t.height=e)}}(t,e),i):null}releaseContext(t){const e=t.canvas;if(!e[hs])return!1;const i=e[hs].initial;["height","width"].forEach((t=>{const n=i[t];s(n)?e.removeAttribute(t):e.setAttribute(t,n)}));const n=i.style||{};return Object.keys(n).forEach((t=>{e.style[t]=n[t]})),e.width=e.width,delete e[hs],!0}addEventListener(t,e,i){this.removeEventListener(t,e);const s=t.$proxies||(t.$proxies={}),n={attach:ps,detach:ms,resize:ys}[e]||Ms;s[e]=n(t,e,i)}removeEventListener(t,e){const i=t.$proxies||(t.$proxies={}),s=i[e];if(!s)return;({attach:vs,detach:vs,resize:vs}[e]||fs)(t,e,s),i[e]=void 0}getDevicePixelRatio(){return window.devicePixelRatio}getMaximumSize(t,e,i,s){return we(t,e,i,s)}isAttached(t){const e=t&&ge(t);return!(!e||!e.isConnected)}}function ks(t){return!fe()||"undefined"!=typeof OffscreenCanvas&&t instanceof OffscreenCanvas?ls:ws}var Ss=Object.freeze({__proto__:null,BasePlatform:rs,BasicPlatform:ls,DomPlatform:ws,_detectPlatform:ks});const Ps="transparent",Ds={boolean:(t,e,i)=>i>.5?e:t,color(t,e,i){const s=Qt(t||Ps),n=s.valid&&Qt(e||Ps);return n&&n.valid?n.mix(s,i).hexString():e},number:(t,e,i)=>t+(e-t)*i};class Cs{constructor(t,e,i,s){const n=e[i];s=Pi([t.to,s,n,t.from]);const o=Pi([t.from,n,s]);this._active=!0,this._fn=t.fn||Ds[t.type||typeof o],this._easing=fi[t.easing]||fi.linear,this._start=Math.floor(Date.now()+(t.delay||0)),this._duration=this._total=Math.floor(t.duration),this._loop=!!t.loop,this._target=e,this._prop=i,this._from=o,this._to=s,this._promises=void 0}active(){return this._active}update(t,e,i){if(this._active){this._notify(!1);const s=this._target[this._prop],n=i-this._start,o=this._duration-n;this._start=i,this._duration=Math.floor(Math.max(o,t.duration)),this._total+=n,this._loop=!!t.loop,this._to=Pi([t.to,e,s,t.from]),this._from=Pi([t.from,s,e])}}cancel(){this._active&&(this.tick(Date.now()),this._active=!1,this._notify(!1))}tick(t){const e=t-this._start,i=this._duration,s=this._prop,n=this._from,o=this._loop,a=this._to;let r;if(this._active=n!==a&&(o||e1?2-r:r,r=this._easing(Math.min(1,Math.max(0,r))),this._target[s]=this._fn(n,a,r))}wait(){const t=this._promises||(this._promises=[]);return new Promise(((e,i)=>{t.push({res:e,rej:i})}))}_notify(t){const e=t?"res":"rej",i=this._promises||[];for(let t=0;t{const a=t[s];if(!o(a))return;const r={};for(const t of e)r[t]=a[t];(n(a.properties)&&a.properties||[s]).forEach((t=>{t!==s&&i.has(t)||i.set(t,r)}))}))}_animateOptions(t,e){const i=e.options,s=function(t,e){if(!e)return;let i=t.options;if(!i)return void(t.options=e);i.$shared&&(t.options=i=Object.assign({},i,{$shared:!1,$animations:{}}));return i}(t,i);if(!s)return[];const n=this._createAnimations(s,i);return i.$shared&&function(t,e){const i=[],s=Object.keys(e);for(let e=0;e{t.options=i}),(()=>{})),n}_createAnimations(t,e){const i=this._properties,s=[],n=t.$animations||(t.$animations={}),o=Object.keys(e),a=Date.now();let r;for(r=o.length-1;r>=0;--r){const l=o[r];if("$"===l.charAt(0))continue;if("options"===l){s.push(...this._animateOptions(t,e));continue}const h=e[l];let c=n[l];const d=i.get(l);if(c){if(d&&c.active()){c.update(d,h,a);continue}c.cancel()}d&&d.duration?(n[l]=c=new Cs(d,t,l,h),s.push(c)):t[l]=h}return s}update(t,e){if(0===this._properties.size)return void Object.assign(t,e);const i=this._createAnimations(t,e);return i.length?(xt.add(this._chart,i),!0):void 0}}function As(t,e){const i=t&&t.options||{},s=i.reverse,n=void 0===i.min?e:0,o=void 0===i.max?e:0;return{start:s?o:n,end:s?n:o}}function Ts(t,e){const i=[],s=t._getSortedDatasetMetas(e);let n,o;for(n=0,o=s.length;n0||!i&&e<0)return n.index}return null}function zs(t,e){const{chart:i,_cachedMeta:s}=t,n=i._stacks||(i._stacks={}),{iScale:o,vScale:a,index:r}=s,l=o.axis,h=a.axis,c=function(t,e,i){return`${t.id}.${e.id}.${i.stack||i.type}`}(o,a,s),d=e.length;let u;for(let t=0;ti[t].axis===e)).shift()}function Vs(t,e){const i=t.controller.index,s=t.vScale&&t.vScale.axis;if(s){e=e||t._parsed;for(const t of e){const e=t._stacks;if(!e||void 0===e[s]||void 0===e[s][i])return;delete e[s][i],void 0!==e[s]._visualValues&&void 0!==e[s]._visualValues[i]&&delete e[s]._visualValues[i]}}}const Bs=t=>"reset"===t||"none"===t,Ws=(t,e)=>e?t:Object.assign({},t);class Ns{static defaults={};static datasetElementType=null;static dataElementType=null;constructor(t,e){this.chart=t,this._ctx=t.ctx,this.index=e,this._cachedDataOpts={},this._cachedMeta=this.getMeta(),this._type=this._cachedMeta.type,this.options=void 0,this._parsing=!1,this._data=void 0,this._objectData=void 0,this._sharedOptions=void 0,this._drawStart=void 0,this._drawCount=void 0,this.enableOptionSharing=!1,this.supportsDecimation=!1,this.$context=void 0,this._syncList=[],this.datasetElementType=new.target.datasetElementType,this.dataElementType=new.target.dataElementType,this.initialize()}initialize(){const t=this._cachedMeta;this.configure(),this.linkScales(),t._stacked=Es(t.vScale,t),this.addElements(),this.options.fill&&!this.chart.isPluginEnabled("filler")&&console.warn("Tried to use the 'fill' option without the 'Filler' plugin enabled. Please import and register the 'Filler' plugin and make sure it is not disabled in the options")}updateIndex(t){this.index!==t&&Vs(this._cachedMeta),this.index=t}linkScales(){const t=this.chart,e=this._cachedMeta,i=this.getDataset(),s=(t,e,i,s)=>"x"===t?e:"r"===t?s:i,n=e.xAxisID=l(i.xAxisID,Fs(t,"x")),o=e.yAxisID=l(i.yAxisID,Fs(t,"y")),a=e.rAxisID=l(i.rAxisID,Fs(t,"r")),r=e.indexAxis,h=e.iAxisID=s(r,n,o,a),c=e.vAxisID=s(r,o,n,a);e.xScale=this.getScaleForId(n),e.yScale=this.getScaleForId(o),e.rScale=this.getScaleForId(a),e.iScale=this.getScaleForId(h),e.vScale=this.getScaleForId(c)}getDataset(){return this.chart.data.datasets[this.index]}getMeta(){return this.chart.getDatasetMeta(this.index)}getScaleForId(t){return this.chart.scales[t]}_getOtherScale(t){const e=this._cachedMeta;return t===e.iScale?e.vScale:e.iScale}reset(){this._update("reset")}_destroy(){const t=this._cachedMeta;this._data&&rt(this._data,this),t._stacked&&Vs(t)}_dataCheck(){const t=this.getDataset(),e=t.data||(t.data=[]),i=this._data;if(o(e)){const t=this._cachedMeta;this._data=function(t,e){const{iScale:i,vScale:s}=e,n="x"===i.axis?"x":"y",o="x"===s.axis?"x":"y",a=Object.keys(t),r=new Array(a.length);let l,h,c;for(l=0,h=a.length;l0&&i._parsed[t-1];if(!1===this._parsing)i._parsed=s,i._sorted=!0,d=s;else{d=n(s[t])?this.parseArrayData(i,s,t,e):o(s[t])?this.parseObjectData(i,s,t,e):this.parsePrimitiveData(i,s,t,e);const a=()=>null===c[l]||f&&c[l]t&&!e.hidden&&e._stacked&&{keys:Ts(i,!0),values:null})(e,i,this.chart),h={min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY},{min:c,max:d}=function(t){const{min:e,max:i,minDefined:s,maxDefined:n}=t.getUserBounds();return{min:s?e:Number.NEGATIVE_INFINITY,max:n?i:Number.POSITIVE_INFINITY}}(r);let u,f;function g(){f=s[u];const e=f[r.axis];return!a(f[t.axis])||c>e||d=0;--u)if(!g()){this.updateRangeFromParsed(h,t,f,l);break}return h}getAllParsedValues(t){const e=this._cachedMeta._parsed,i=[];let s,n,o;for(s=0,n=e.length;s=0&&tthis.getContext(i,s,e)),c);return f.$shared&&(f.$shared=r,n[o]=Object.freeze(Ws(f,r))),f}_resolveAnimations(t,e,i){const s=this.chart,n=this._cachedDataOpts,o=`animation-${e}`,a=n[o];if(a)return a;let r;if(!1!==s.options.animation){const s=this.chart.config,n=s.datasetAnimationScopeKeys(this._type,e),o=s.getOptionScopes(this.getDataset(),n);r=s.createResolver(o,this.getContext(t,i,e))}const l=new Os(s,r&&r.animations);return r&&r._cacheable&&(n[o]=Object.freeze(l)),l}getSharedOptions(t){if(t.$shared)return this._sharedOptions||(this._sharedOptions=Object.assign({},t))}includeOptions(t,e){return!e||Bs(t)||this.chart._animationsDisabled}_getSharedOptions(t,e){const i=this.resolveDataElementOptions(t,e),s=this._sharedOptions,n=this.getSharedOptions(i),o=this.includeOptions(e,n)||n!==s;return this.updateSharedOptions(n,e,i),{sharedOptions:n,includeOptions:o}}updateElement(t,e,i,s){Bs(s)?Object.assign(t,i):this._resolveAnimations(e,s).update(t,i)}updateSharedOptions(t,e,i){t&&!Bs(e)&&this._resolveAnimations(void 0,e).update(t,i)}_setStyle(t,e,i,s){t.active=s;const n=this.getStyle(e,s);this._resolveAnimations(e,i,s).update(t,{options:!s&&this.getSharedOptions(n)||n})}removeHoverStyle(t,e,i){this._setStyle(t,i,"active",!1)}setHoverStyle(t,e,i){this._setStyle(t,i,"active",!0)}_removeDatasetHoverStyle(){const t=this._cachedMeta.dataset;t&&this._setStyle(t,void 0,"active",!1)}_setDatasetHoverStyle(){const t=this._cachedMeta.dataset;t&&this._setStyle(t,void 0,"active",!0)}_resyncElements(t){const e=this._data,i=this._cachedMeta.data;for(const[t,e,i]of this._syncList)this[t](e,i);this._syncList=[];const s=i.length,n=e.length,o=Math.min(n,s);o&&this.parse(0,o),n>s?this._insertElements(s,n-s,t):n{for(t.length+=e,a=t.length-1;a>=o;a--)t[a]=t[a-e]};for(r(n),a=t;a{s[t]=i[t]&&i[t].active()?i[t]._to:this[t]})),s}}function js(t,e){const i=t.options.ticks,n=function(t){const e=t.options.offset,i=t._tickSize(),s=t._length/i+(e?0:1),n=t._maxLength/i;return Math.floor(Math.min(s,n))}(t),o=Math.min(i.maxTicksLimit||n,n),a=i.major.enabled?function(t){const e=[];let i,s;for(i=0,s=t.length;io)return function(t,e,i,s){let n,o=0,a=i[0];for(s=Math.ceil(s),n=0;nn)return e}return Math.max(n,1)}(a,e,o);if(r>0){let t,i;const n=r>1?Math.round((h-l)/(r-1)):null;for($s(e,c,d,s(n)?0:l-n,l),t=0,i=r-1;t"top"===e||"left"===e?t[e]+i:t[e]-i,Us=(t,e)=>Math.min(e||t,t);function Xs(t,e){const i=[],s=t.length/e,n=t.length;let o=0;for(;oa+r)))return h}function Ks(t){return t.drawTicks?t.tickLength:0}function Gs(t,e){if(!t.display)return 0;const i=Si(t.font,e),s=ki(t.padding);return(n(t.text)?t.text.length:1)*i.lineHeight+s.height}function Zs(t,e,i){let s=ut(t);return(i&&"right"!==e||!i&&"right"===e)&&(s=(t=>"left"===t?"right":"right"===t?"left":t)(s)),s}class Js extends Hs{constructor(t){super(),this.id=t.id,this.type=t.type,this.options=void 0,this.ctx=t.ctx,this.chart=t.chart,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.width=void 0,this.height=void 0,this._margins={left:0,right:0,top:0,bottom:0},this.maxWidth=void 0,this.maxHeight=void 0,this.paddingTop=void 0,this.paddingBottom=void 0,this.paddingLeft=void 0,this.paddingRight=void 0,this.axis=void 0,this.labelRotation=void 0,this.min=void 0,this.max=void 0,this._range=void 0,this.ticks=[],this._gridLineItems=null,this._labelItems=null,this._labelSizes=null,this._length=0,this._maxLength=0,this._longestTextCache={},this._startPixel=void 0,this._endPixel=void 0,this._reversePixels=!1,this._userMax=void 0,this._userMin=void 0,this._suggestedMax=void 0,this._suggestedMin=void 0,this._ticksLength=0,this._borderValue=0,this._cache={},this._dataLimitsCached=!1,this.$context=void 0}init(t){this.options=t.setContext(this.getContext()),this.axis=t.axis,this._userMin=this.parse(t.min),this._userMax=this.parse(t.max),this._suggestedMin=this.parse(t.suggestedMin),this._suggestedMax=this.parse(t.suggestedMax)}parse(t,e){return t}getUserBounds(){let{_userMin:t,_userMax:e,_suggestedMin:i,_suggestedMax:s}=this;return t=r(t,Number.POSITIVE_INFINITY),e=r(e,Number.NEGATIVE_INFINITY),i=r(i,Number.POSITIVE_INFINITY),s=r(s,Number.NEGATIVE_INFINITY),{min:r(t,i),max:r(e,s),minDefined:a(t),maxDefined:a(e)}}getMinMax(t){let e,{min:i,max:s,minDefined:n,maxDefined:o}=this.getUserBounds();if(n&&o)return{min:i,max:s};const a=this.getMatchingVisibleMetas();for(let r=0,l=a.length;rs?s:i,s=n&&i>s?i:s,{min:r(i,r(s,i)),max:r(s,r(i,s))}}getPadding(){return{left:this.paddingLeft||0,top:this.paddingTop||0,right:this.paddingRight||0,bottom:this.paddingBottom||0}}getTicks(){return this.ticks}getLabels(){const t=this.chart.data;return this.options.labels||(this.isHorizontal()?t.xLabels:t.yLabels)||t.labels||[]}getLabelItems(t=this.chart.chartArea){return this._labelItems||(this._labelItems=this._computeLabelItems(t))}beforeLayout(){this._cache={},this._dataLimitsCached=!1}beforeUpdate(){d(this.options.beforeUpdate,[this])}update(t,e,i){const{beginAtZero:s,grace:n,ticks:o}=this.options,a=o.sampleSize;this.beforeUpdate(),this.maxWidth=t,this.maxHeight=e,this._margins=i=Object.assign({left:0,right:0,top:0,bottom:0},i),this.ticks=null,this._labelSizes=null,this._gridLineItems=null,this._labelItems=null,this.beforeSetDimensions(),this.setDimensions(),this.afterSetDimensions(),this._maxLength=this.isHorizontal()?this.width+i.left+i.right:this.height+i.top+i.bottom,this._dataLimitsCached||(this.beforeDataLimits(),this.determineDataLimits(),this.afterDataLimits(),this._range=Di(this,n,s),this._dataLimitsCached=!0),this.beforeBuildTicks(),this.ticks=this.buildTicks()||[],this.afterBuildTicks();const r=a=n||i<=1||!this.isHorizontal())return void(this.labelRotation=s);const h=this._getLabelSizes(),c=h.widest.width,d=h.highest.height,u=J(this.chart.width-c,0,this.maxWidth);o=t.offset?this.maxWidth/i:u/(i-1),c+6>o&&(o=u/(i-(t.offset?.5:1)),a=this.maxHeight-Ks(t.grid)-e.padding-Gs(t.title,this.chart.options.font),r=Math.sqrt(c*c+d*d),l=Y(Math.min(Math.asin(J((h.highest.height+6)/o,-1,1)),Math.asin(J(a/r,-1,1))-Math.asin(J(d/r,-1,1)))),l=Math.max(s,Math.min(n,l))),this.labelRotation=l}afterCalculateLabelRotation(){d(this.options.afterCalculateLabelRotation,[this])}afterAutoSkip(){}beforeFit(){d(this.options.beforeFit,[this])}fit(){const t={width:0,height:0},{chart:e,options:{ticks:i,title:s,grid:n}}=this,o=this._isVisible(),a=this.isHorizontal();if(o){const o=Gs(s,e.options.font);if(a?(t.width=this.maxWidth,t.height=Ks(n)+o):(t.height=this.maxHeight,t.width=Ks(n)+o),i.display&&this.ticks.length){const{first:e,last:s,widest:n,highest:o}=this._getLabelSizes(),r=2*i.padding,l=$(this.labelRotation),h=Math.cos(l),c=Math.sin(l);if(a){const e=i.mirror?0:c*n.width+h*o.height;t.height=Math.min(this.maxHeight,t.height+e+r)}else{const e=i.mirror?0:h*n.width+c*o.height;t.width=Math.min(this.maxWidth,t.width+e+r)}this._calculatePadding(e,s,c,h)}}this._handleMargins(),a?(this.width=this._length=e.width-this._margins.left-this._margins.right,this.height=t.height):(this.width=t.width,this.height=this._length=e.height-this._margins.top-this._margins.bottom)}_calculatePadding(t,e,i,s){const{ticks:{align:n,padding:o},position:a}=this.options,r=0!==this.labelRotation,l="top"!==a&&"x"===this.axis;if(this.isHorizontal()){const a=this.getPixelForTick(0)-this.left,h=this.right-this.getPixelForTick(this.ticks.length-1);let c=0,d=0;r?l?(c=s*t.width,d=i*e.height):(c=i*t.height,d=s*e.width):"start"===n?d=e.width:"end"===n?c=t.width:"inner"!==n&&(c=t.width/2,d=e.width/2),this.paddingLeft=Math.max((c-a+o)*this.width/(this.width-a),0),this.paddingRight=Math.max((d-h+o)*this.width/(this.width-h),0)}else{let i=e.height/2,s=t.height/2;"start"===n?(i=0,s=t.height):"end"===n&&(i=e.height,s=0),this.paddingTop=i+o,this.paddingBottom=s+o}}_handleMargins(){this._margins&&(this._margins.left=Math.max(this.paddingLeft,this._margins.left),this._margins.top=Math.max(this.paddingTop,this._margins.top),this._margins.right=Math.max(this.paddingRight,this._margins.right),this._margins.bottom=Math.max(this.paddingBottom,this._margins.bottom))}afterFit(){d(this.options.afterFit,[this])}isHorizontal(){const{axis:t,position:e}=this.options;return"top"===e||"bottom"===e||"x"===t}isFullSize(){return this.options.fullSize}_convertTicksToLabels(t){let e,i;for(this.beforeTickToLabelConversion(),this.generateTickLabels(t),e=0,i=t.length;e{const i=t.gc,s=i.length/2;let n;if(s>e){for(n=0;n({width:r[t]||0,height:l[t]||0});return{first:P(0),last:P(e-1),widest:P(k),highest:P(S),widths:r,heights:l}}getLabelForValue(t){return t}getPixelForValue(t,e){return NaN}getValueForPixel(t){}getPixelForTick(t){const e=this.ticks;return t<0||t>e.length-1?null:this.getPixelForValue(e[t].value)}getPixelForDecimal(t){this._reversePixels&&(t=1-t);const e=this._startPixel+t*this._length;return Q(this._alignToPixels?Ae(this.chart,e,0):e)}getDecimalForPixel(t){const e=(t-this._startPixel)/this._length;return this._reversePixels?1-e:e}getBasePixel(){return this.getPixelForValue(this.getBaseValue())}getBaseValue(){const{min:t,max:e}=this;return t<0&&e<0?e:t>0&&e>0?t:0}getContext(t){const e=this.ticks||[];if(t>=0&&ta*s?a/i:r/s:r*s0}_computeGridLineItems(t){const e=this.axis,i=this.chart,s=this.options,{grid:n,position:a,border:r}=s,h=n.offset,c=this.isHorizontal(),d=this.ticks.length+(h?1:0),u=Ks(n),f=[],g=r.setContext(this.getContext()),p=g.display?g.width:0,m=p/2,b=function(t){return Ae(i,t,p)};let x,_,y,v,M,w,k,S,P,D,C,O;if("top"===a)x=b(this.bottom),w=this.bottom-u,S=x-m,D=b(t.top)+m,O=t.bottom;else if("bottom"===a)x=b(this.top),D=t.top,O=b(t.bottom)-m,w=x+m,S=this.top+u;else if("left"===a)x=b(this.right),M=this.right-u,k=x-m,P=b(t.left)+m,C=t.right;else if("right"===a)x=b(this.left),P=t.left,C=b(t.right)-m,M=x+m,k=this.left+u;else if("x"===e){if("center"===a)x=b((t.top+t.bottom)/2+.5);else if(o(a)){const t=Object.keys(a)[0],e=a[t];x=b(this.chart.scales[t].getPixelForValue(e))}D=t.top,O=t.bottom,w=x+m,S=w+u}else if("y"===e){if("center"===a)x=b((t.left+t.right)/2);else if(o(a)){const t=Object.keys(a)[0],e=a[t];x=b(this.chart.scales[t].getPixelForValue(e))}M=x-m,k=M-u,P=t.left,C=t.right}const A=l(s.ticks.maxTicksLimit,d),T=Math.max(1,Math.ceil(d/A));for(_=0;_0&&(o-=s/2)}d={left:o,top:n,width:s+e.width,height:i+e.height,color:t.backdropColor}}b.push({label:v,font:P,textOffset:O,options:{rotation:m,color:i,strokeColor:o,strokeWidth:h,textAlign:f,textBaseline:A,translation:[M,w],backdrop:d}})}return b}_getXAxisLabelAlignment(){const{position:t,ticks:e}=this.options;if(-$(this.labelRotation))return"top"===t?"left":"right";let i="center";return"start"===e.align?i="left":"end"===e.align?i="right":"inner"===e.align&&(i="inner"),i}_getYAxisLabelAlignment(t){const{position:e,ticks:{crossAlign:i,mirror:s,padding:n}}=this.options,o=t+n,a=this._getLabelSizes().widest.width;let r,l;return"left"===e?s?(l=this.right+n,"near"===i?r="left":"center"===i?(r="center",l+=a/2):(r="right",l+=a)):(l=this.right-o,"near"===i?r="right":"center"===i?(r="center",l-=a/2):(r="left",l=this.left)):"right"===e?s?(l=this.left+n,"near"===i?r="right":"center"===i?(r="center",l-=a/2):(r="left",l-=a)):(l=this.left+o,"near"===i?r="left":"center"===i?(r="center",l+=a/2):(r="right",l=this.right)):r="right",{textAlign:r,x:l}}_computeLabelArea(){if(this.options.ticks.mirror)return;const t=this.chart,e=this.options.position;return"left"===e||"right"===e?{top:0,left:this.left,bottom:t.height,right:this.right}:"top"===e||"bottom"===e?{top:this.top,left:0,bottom:this.bottom,right:t.width}:void 0}drawBackground(){const{ctx:t,options:{backgroundColor:e},left:i,top:s,width:n,height:o}=this;e&&(t.save(),t.fillStyle=e,t.fillRect(i,s,n,o),t.restore())}getLineWidthForValue(t){const e=this.options.grid;if(!this._isVisible()||!e.display)return 0;const i=this.ticks.findIndex((e=>e.value===t));if(i>=0){return e.setContext(this.getContext(i)).lineWidth}return 0}drawGrid(t){const e=this.options.grid,i=this.ctx,s=this._gridLineItems||(this._gridLineItems=this._computeGridLineItems(t));let n,o;const a=(t,e,s)=>{s.width&&s.color&&(i.save(),i.lineWidth=s.width,i.strokeStyle=s.color,i.setLineDash(s.borderDash||[]),i.lineDashOffset=s.borderDashOffset,i.beginPath(),i.moveTo(t.x,t.y),i.lineTo(e.x,e.y),i.stroke(),i.restore())};if(e.display)for(n=0,o=s.length;n{this.drawBackground(),this.drawGrid(t),this.drawTitle()}},{z:s,draw:()=>{this.drawBorder()}},{z:e,draw:t=>{this.drawLabels(t)}}]:[{z:e,draw:t=>{this.draw(t)}}]}getMatchingVisibleMetas(t){const e=this.chart.getSortedVisibleDatasetMetas(),i=this.axis+"AxisID",s=[];let n,o;for(n=0,o=e.length;n{const s=i.split("."),n=s.pop(),o=[t].concat(s).join("."),a=e[i].split("."),r=a.pop(),l=a.join(".");ue.route(o,n,l,r)}))}(e,t.defaultRoutes);t.descriptors&&ue.describe(e,t.descriptors)}(t,o,i),this.override&&ue.override(t.id,t.overrides)),o}get(t){return this.items[t]}unregister(t){const e=this.items,i=t.id,s=this.scope;i in e&&delete e[i],s&&i in ue[s]&&(delete ue[s][i],this.override&&delete re[i])}}class tn{constructor(){this.controllers=new Qs(Ns,"datasets",!0),this.elements=new Qs(Hs,"elements"),this.plugins=new Qs(Object,"plugins"),this.scales=new Qs(Js,"scales"),this._typedRegistries=[this.controllers,this.scales,this.elements]}add(...t){this._each("register",t)}remove(...t){this._each("unregister",t)}addControllers(...t){this._each("register",t,this.controllers)}addElements(...t){this._each("register",t,this.elements)}addPlugins(...t){this._each("register",t,this.plugins)}addScales(...t){this._each("register",t,this.scales)}getController(t){return this._get(t,this.controllers,"controller")}getElement(t){return this._get(t,this.elements,"element")}getPlugin(t){return this._get(t,this.plugins,"plugin")}getScale(t){return this._get(t,this.scales,"scale")}removeControllers(...t){this._each("unregister",t,this.controllers)}removeElements(...t){this._each("unregister",t,this.elements)}removePlugins(...t){this._each("unregister",t,this.plugins)}removeScales(...t){this._each("unregister",t,this.scales)}_each(t,e,i){[...e].forEach((e=>{const s=i||this._getRegistryForType(e);i||s.isForType(e)||s===this.plugins&&e.id?this._exec(t,s,e):u(e,(e=>{const s=i||this._getRegistryForType(e);this._exec(t,s,e)}))}))}_exec(t,e,i){const s=w(t);d(i["before"+s],[],i),e[t](i),d(i["after"+s],[],i)}_getRegistryForType(t){for(let e=0;et.filter((t=>!e.some((e=>t.plugin.id===e.plugin.id))));this._notify(s(e,i),t,"stop"),this._notify(s(i,e),t,"start")}}function nn(t,e){return e||!1!==t?!0===t?{}:t:null}function on(t,{plugin:e,local:i},s,n){const o=t.pluginScopeKeys(e),a=t.getOptionScopes(s,o);return i&&e.defaults&&a.push(e.defaults),t.createResolver(a,n,[""],{scriptable:!1,indexable:!1,allKeys:!0})}function an(t,e){const i=ue.datasets[t]||{};return((e.datasets||{})[t]||{}).indexAxis||e.indexAxis||i.indexAxis||"x"}function rn(t){if("x"===t||"y"===t||"r"===t)return t}function ln(t,...e){if(rn(t))return t;for(const s of e){const e=s.axis||("top"===(i=s.position)||"bottom"===i?"x":"left"===i||"right"===i?"y":void 0)||t.length>1&&rn(t[0].toLowerCase());if(e)return e}var i;throw new Error(`Cannot determine type of '${t}' axis. Please provide 'axis' or 'position' option.`)}function hn(t,e,i){if(i[e+"AxisID"]===t)return{axis:e}}function cn(t,e){const i=re[t.type]||{scales:{}},s=e.scales||{},n=an(t.type,e),a=Object.create(null);return Object.keys(s).forEach((e=>{const r=s[e];if(!o(r))return console.error(`Invalid scale configuration for scale: ${e}`);if(r._proxy)return console.warn(`Ignoring resolver passed as options for scale: ${e}`);const l=ln(e,r,function(t,e){if(e.data&&e.data.datasets){const i=e.data.datasets.filter((e=>e.xAxisID===t||e.yAxisID===t));if(i.length)return hn(t,"x",i[0])||hn(t,"y",i[0])}return{}}(e,t),ue.scales[r.type]),h=function(t,e){return t===e?"_index_":"_value_"}(l,n),c=i.scales||{};a[e]=x(Object.create(null),[{axis:l},r,c[l],c[h]])})),t.data.datasets.forEach((i=>{const n=i.type||t.type,o=i.indexAxis||an(n,e),r=(re[n]||{}).scales||{};Object.keys(r).forEach((t=>{const e=function(t,e){let i=t;return"_index_"===t?i=e:"_value_"===t&&(i="x"===e?"y":"x"),i}(t,o),n=i[e+"AxisID"]||e;a[n]=a[n]||Object.create(null),x(a[n],[{axis:e},s[n],r[t]])}))})),Object.keys(a).forEach((t=>{const e=a[t];x(e,[ue.scales[e.type],ue.scale])})),a}function dn(t){const e=t.options||(t.options={});e.plugins=l(e.plugins,{}),e.scales=cn(t,e)}function un(t){return(t=t||{}).datasets=t.datasets||[],t.labels=t.labels||[],t}const fn=new Map,gn=new Set;function pn(t,e){let i=fn.get(t);return i||(i=e(),fn.set(t,i),gn.add(i)),i}const mn=(t,e,i)=>{const s=M(e,i);void 0!==s&&t.add(s)};class bn{constructor(t){this._config=function(t){return(t=t||{}).data=un(t.data),dn(t),t}(t),this._scopeCache=new Map,this._resolverCache=new Map}get platform(){return this._config.platform}get type(){return this._config.type}set type(t){this._config.type=t}get data(){return this._config.data}set data(t){this._config.data=un(t)}get options(){return this._config.options}set options(t){this._config.options=t}get plugins(){return this._config.plugins}update(){const t=this._config;this.clearCache(),dn(t)}clearCache(){this._scopeCache.clear(),this._resolverCache.clear()}datasetScopeKeys(t){return pn(t,(()=>[[`datasets.${t}`,""]]))}datasetAnimationScopeKeys(t,e){return pn(`${t}.transition.${e}`,(()=>[[`datasets.${t}.transitions.${e}`,`transitions.${e}`],[`datasets.${t}`,""]]))}datasetElementScopeKeys(t,e){return pn(`${t}-${e}`,(()=>[[`datasets.${t}.elements.${e}`,`datasets.${t}`,`elements.${e}`,""]]))}pluginScopeKeys(t){const e=t.id;return pn(`${this.type}-plugin-${e}`,(()=>[[`plugins.${e}`,...t.additionalOptionScopes||[]]]))}_cachedScopes(t,e){const i=this._scopeCache;let s=i.get(t);return s&&!e||(s=new Map,i.set(t,s)),s}getOptionScopes(t,e,i){const{options:s,type:n}=this,o=this._cachedScopes(t,i),a=o.get(e);if(a)return a;const r=new Set;e.forEach((e=>{t&&(r.add(t),e.forEach((e=>mn(r,t,e)))),e.forEach((t=>mn(r,s,t))),e.forEach((t=>mn(r,re[n]||{},t))),e.forEach((t=>mn(r,ue,t))),e.forEach((t=>mn(r,le,t)))}));const l=Array.from(r);return 0===l.length&&l.push(Object.create(null)),gn.has(e)&&o.set(e,l),l}chartOptionScopes(){const{options:t,type:e}=this;return[t,re[e]||{},ue.datasets[e]||{},{type:e},ue,le]}resolveNamedOptions(t,e,i,s=[""]){const o={$shared:!0},{resolver:a,subPrefixes:r}=xn(this._resolverCache,t,s);let l=a;if(function(t,e){const{isScriptable:i,isIndexable:s}=Ye(t);for(const o of e){const e=i(o),a=s(o),r=(a||e)&&t[o];if(e&&(S(r)||_n(r))||a&&n(r))return!0}return!1}(a,e)){o.$shared=!1;l=$e(a,i=S(i)?i():i,this.createResolver(t,i,r))}for(const t of e)o[t]=l[t];return o}createResolver(t,e,i=[""],s){const{resolver:n}=xn(this._resolverCache,t,i);return o(e)?$e(n,e,void 0,s):n}}function xn(t,e,i){let s=t.get(e);s||(s=new Map,t.set(e,s));const n=i.join();let o=s.get(n);if(!o){o={resolver:je(e,i),subPrefixes:i.filter((t=>!t.toLowerCase().includes("hover")))},s.set(n,o)}return o}const _n=t=>o(t)&&Object.getOwnPropertyNames(t).some((e=>S(t[e])));const yn=["top","bottom","left","right","chartArea"];function vn(t,e){return"top"===t||"bottom"===t||-1===yn.indexOf(t)&&"x"===e}function Mn(t,e){return function(i,s){return i[t]===s[t]?i[e]-s[e]:i[t]-s[t]}}function wn(t){const e=t.chart,i=e.options.animation;e.notifyPlugins("afterRender"),d(i&&i.onComplete,[t],e)}function kn(t){const e=t.chart,i=e.options.animation;d(i&&i.onProgress,[t],e)}function Sn(t){return fe()&&"string"==typeof t?t=document.getElementById(t):t&&t.length&&(t=t[0]),t&&t.canvas&&(t=t.canvas),t}const Pn={},Dn=t=>{const e=Sn(t);return Object.values(Pn).filter((t=>t.canvas===e)).pop()};function Cn(t,e,i){const s=Object.keys(t);for(const n of s){const s=+n;if(s>=e){const o=t[n];delete t[n],(i>0||s>e)&&(t[s+i]=o)}}}function On(t,e,i){return t.options.clip?t[i]:e[i]}class An{static defaults=ue;static instances=Pn;static overrides=re;static registry=en;static version="4.4.7";static getChart=Dn;static register(...t){en.add(...t),Tn()}static unregister(...t){en.remove(...t),Tn()}constructor(t,e){const s=this.config=new bn(e),n=Sn(t),o=Dn(n);if(o)throw new Error("Canvas is already in use. Chart with ID '"+o.id+"' must be destroyed before the canvas with ID '"+o.canvas.id+"' can be reused.");const a=s.createResolver(s.chartOptionScopes(),this.getContext());this.platform=new(s.platform||ks(n)),this.platform.updateConfig(s);const r=this.platform.acquireContext(n,a.aspectRatio),l=r&&r.canvas,h=l&&l.height,c=l&&l.width;this.id=i(),this.ctx=r,this.canvas=l,this.width=c,this.height=h,this._options=a,this._aspectRatio=this.aspectRatio,this._layers=[],this._metasets=[],this._stacks=void 0,this.boxes=[],this.currentDevicePixelRatio=void 0,this.chartArea=void 0,this._active=[],this._lastEvent=void 0,this._listeners={},this._responsiveListeners=void 0,this._sortedMetasets=[],this.scales={},this._plugins=new sn,this.$proxies={},this._hiddenIndices={},this.attached=!1,this._animationsDisabled=void 0,this.$context=void 0,this._doResize=dt((t=>this.update(t)),a.resizeDelay||0),this._dataChanges=[],Pn[this.id]=this,r&&l?(xt.listen(this,"complete",wn),xt.listen(this,"progress",kn),this._initialize(),this.attached&&this.update()):console.error("Failed to create chart: can't acquire context from the given item")}get aspectRatio(){const{options:{aspectRatio:t,maintainAspectRatio:e},width:i,height:n,_aspectRatio:o}=this;return s(t)?e&&o?o:n?i/n:null:t}get data(){return this.config.data}set data(t){this.config.data=t}get options(){return this._options}set options(t){this.config.options=t}get registry(){return en}_initialize(){return this.notifyPlugins("beforeInit"),this.options.responsive?this.resize():ke(this,this.options.devicePixelRatio),this.bindEvents(),this.notifyPlugins("afterInit"),this}clear(){return Te(this.canvas,this.ctx),this}stop(){return xt.stop(this),this}resize(t,e){xt.running(this)?this._resizeBeforeDraw={width:t,height:e}:this._resize(t,e)}_resize(t,e){const i=this.options,s=this.canvas,n=i.maintainAspectRatio&&this.aspectRatio,o=this.platform.getMaximumSize(s,t,e,n),a=i.devicePixelRatio||this.platform.getDevicePixelRatio(),r=this.width?"resize":"attach";this.width=o.width,this.height=o.height,this._aspectRatio=this.aspectRatio,ke(this,a,!0)&&(this.notifyPlugins("resize",{size:o}),d(i.onResize,[this,o],this),this.attached&&this._doResize(r)&&this.render())}ensureScalesHaveIDs(){u(this.options.scales||{},((t,e)=>{t.id=e}))}buildOrUpdateScales(){const t=this.options,e=t.scales,i=this.scales,s=Object.keys(i).reduce(((t,e)=>(t[e]=!1,t)),{});let n=[];e&&(n=n.concat(Object.keys(e).map((t=>{const i=e[t],s=ln(t,i),n="r"===s,o="x"===s;return{options:i,dposition:n?"chartArea":o?"bottom":"left",dtype:n?"radialLinear":o?"category":"linear"}})))),u(n,(e=>{const n=e.options,o=n.id,a=ln(o,n),r=l(n.type,e.dtype);void 0!==n.position&&vn(n.position,a)===vn(e.dposition)||(n.position=e.dposition),s[o]=!0;let h=null;if(o in i&&i[o].type===r)h=i[o];else{h=new(en.getScale(r))({id:o,type:r,ctx:this.ctx,chart:this}),i[h.id]=h}h.init(n,t)})),u(s,((t,e)=>{t||delete i[e]})),u(i,(t=>{as.configure(this,t,t.options),as.addBox(this,t)}))}_updateMetasets(){const t=this._metasets,e=this.data.datasets.length,i=t.length;if(t.sort(((t,e)=>t.index-e.index)),i>e){for(let t=e;te.length&&delete this._stacks,t.forEach(((t,i)=>{0===e.filter((e=>e===t._dataset)).length&&this._destroyDatasetMeta(i)}))}buildOrUpdateControllers(){const t=[],e=this.data.datasets;let i,s;for(this._removeUnreferencedMetasets(),i=0,s=e.length;i{this.getDatasetMeta(e).controller.reset()}),this)}reset(){this._resetElements(),this.notifyPlugins("reset")}update(t){const e=this.config;e.update();const i=this._options=e.createResolver(e.chartOptionScopes(),this.getContext()),s=this._animationsDisabled=!i.animation;if(this._updateScales(),this._checkEventBindings(),this._updateHiddenIndices(),this._plugins.invalidate(),!1===this.notifyPlugins("beforeUpdate",{mode:t,cancelable:!0}))return;const n=this.buildOrUpdateControllers();this.notifyPlugins("beforeElementsUpdate");let o=0;for(let t=0,e=this.data.datasets.length;t{t.reset()})),this._updateDatasets(t),this.notifyPlugins("afterUpdate",{mode:t}),this._layers.sort(Mn("z","_idx"));const{_active:a,_lastEvent:r}=this;r?this._eventHandler(r,!0):a.length&&this._updateHoverStyles(a,a,!0),this.render()}_updateScales(){u(this.scales,(t=>{as.removeBox(this,t)})),this.ensureScalesHaveIDs(),this.buildOrUpdateScales()}_checkEventBindings(){const t=this.options,e=new Set(Object.keys(this._listeners)),i=new Set(t.events);P(e,i)&&!!this._responsiveListeners===t.responsive||(this.unbindEvents(),this.bindEvents())}_updateHiddenIndices(){const{_hiddenIndices:t}=this,e=this._getUniformDataChanges()||[];for(const{method:i,start:s,count:n}of e){Cn(t,s,"_removeElements"===i?-n:n)}}_getUniformDataChanges(){const t=this._dataChanges;if(!t||!t.length)return;this._dataChanges=[];const e=this.data.datasets.length,i=e=>new Set(t.filter((t=>t[0]===e)).map(((t,e)=>e+","+t.splice(1).join(",")))),s=i(0);for(let t=1;tt.split(","))).map((t=>({method:t[1],start:+t[2],count:+t[3]})))}_updateLayout(t){if(!1===this.notifyPlugins("beforeLayout",{cancelable:!0}))return;as.update(this,this.width,this.height,t);const e=this.chartArea,i=e.width<=0||e.height<=0;this._layers=[],u(this.boxes,(t=>{i&&"chartArea"===t.position||(t.configure&&t.configure(),this._layers.push(...t._layers()))}),this),this._layers.forEach(((t,e)=>{t._idx=e})),this.notifyPlugins("afterLayout")}_updateDatasets(t){if(!1!==this.notifyPlugins("beforeDatasetsUpdate",{mode:t,cancelable:!0})){for(let t=0,e=this.data.datasets.length;t=0;--e)this._drawDataset(t[e]);this.notifyPlugins("afterDatasetsDraw")}_drawDataset(t){const e=this.ctx,i=t._clip,s=!i.disabled,n=function(t,e){const{xScale:i,yScale:s}=t;return i&&s?{left:On(i,e,"left"),right:On(i,e,"right"),top:On(s,e,"top"),bottom:On(s,e,"bottom")}:e}(t,this.chartArea),o={meta:t,index:t.index,cancelable:!0};!1!==this.notifyPlugins("beforeDatasetDraw",o)&&(s&&Ie(e,{left:!1===i.left?0:n.left-i.left,right:!1===i.right?this.width:n.right+i.right,top:!1===i.top?0:n.top-i.top,bottom:!1===i.bottom?this.height:n.bottom+i.bottom}),t.controller.draw(),s&&ze(e),o.cancelable=!1,this.notifyPlugins("afterDatasetDraw",o))}isPointInArea(t){return Re(t,this.chartArea,this._minPadding)}getElementsAtEventForMode(t,e,i,s){const n=Xi.modes[e];return"function"==typeof n?n(this,t,i,s):[]}getDatasetMeta(t){const e=this.data.datasets[t],i=this._metasets;let s=i.filter((t=>t&&t._dataset===e)).pop();return s||(s={type:null,data:[],dataset:null,controller:null,hidden:null,xAxisID:null,yAxisID:null,order:e&&e.order||0,index:t,_dataset:e,_parsed:[],_sorted:!1},i.push(s)),s}getContext(){return this.$context||(this.$context=Ci(null,{chart:this,type:"chart"}))}getVisibleDatasetCount(){return this.getSortedVisibleDatasetMetas().length}isDatasetVisible(t){const e=this.data.datasets[t];if(!e)return!1;const i=this.getDatasetMeta(t);return"boolean"==typeof i.hidden?!i.hidden:!e.hidden}setDatasetVisibility(t,e){this.getDatasetMeta(t).hidden=!e}toggleDataVisibility(t){this._hiddenIndices[t]=!this._hiddenIndices[t]}getDataVisibility(t){return!this._hiddenIndices[t]}_updateVisibility(t,e,i){const s=i?"show":"hide",n=this.getDatasetMeta(t),o=n.controller._resolveAnimations(void 0,s);k(e)?(n.data[e].hidden=!i,this.update()):(this.setDatasetVisibility(t,i),o.update(n,{visible:i}),this.update((e=>e.datasetIndex===t?s:void 0)))}hide(t,e){this._updateVisibility(t,e,!1)}show(t,e){this._updateVisibility(t,e,!0)}_destroyDatasetMeta(t){const e=this._metasets[t];e&&e.controller&&e.controller._destroy(),delete this._metasets[t]}_stop(){let t,e;for(this.stop(),xt.remove(this),t=0,e=this.data.datasets.length;t{e.addEventListener(this,i,s),t[i]=s},s=(t,e,i)=>{t.offsetX=e,t.offsetY=i,this._eventHandler(t)};u(this.options.events,(t=>i(t,s)))}bindResponsiveEvents(){this._responsiveListeners||(this._responsiveListeners={});const t=this._responsiveListeners,e=this.platform,i=(i,s)=>{e.addEventListener(this,i,s),t[i]=s},s=(i,s)=>{t[i]&&(e.removeEventListener(this,i,s),delete t[i])},n=(t,e)=>{this.canvas&&this.resize(t,e)};let o;const a=()=>{s("attach",a),this.attached=!0,this.resize(),i("resize",n),i("detach",o)};o=()=>{this.attached=!1,s("resize",n),this._stop(),this._resize(0,0),i("attach",a)},e.isAttached(this.canvas)?a():o()}unbindEvents(){u(this._listeners,((t,e)=>{this.platform.removeEventListener(this,e,t)})),this._listeners={},u(this._responsiveListeners,((t,e)=>{this.platform.removeEventListener(this,e,t)})),this._responsiveListeners=void 0}updateHoverStyle(t,e,i){const s=i?"set":"remove";let n,o,a,r;for("dataset"===e&&(n=this.getDatasetMeta(t[0].datasetIndex),n.controller["_"+s+"DatasetHoverStyle"]()),a=0,r=t.length;a{const i=this.getDatasetMeta(t);if(!i)throw new Error("No dataset found at index "+t);return{datasetIndex:t,element:i.data[e],index:e}}));!f(i,e)&&(this._active=i,this._lastEvent=null,this._updateHoverStyles(i,e))}notifyPlugins(t,e,i){return this._plugins.notify(this,t,e,i)}isPluginEnabled(t){return 1===this._plugins._cache.filter((e=>e.plugin.id===t)).length}_updateHoverStyles(t,e,i){const s=this.options.hover,n=(t,e)=>t.filter((t=>!e.some((e=>t.datasetIndex===e.datasetIndex&&t.index===e.index)))),o=n(e,t),a=i?t:n(t,e);o.length&&this.updateHoverStyle(o,s.mode,!1),a.length&&s.mode&&this.updateHoverStyle(a,s.mode,!0)}_eventHandler(t,e){const i={event:t,replay:e,cancelable:!0,inChartArea:this.isPointInArea(t)},s=e=>(e.options.events||this.options.events).includes(t.native.type);if(!1===this.notifyPlugins("beforeEvent",i,s))return;const n=this._handleEvent(t,e,i.inChartArea);return i.cancelable=!1,this.notifyPlugins("afterEvent",i,s),(n||i.changed)&&this.render(),this}_handleEvent(t,e,i){const{_active:s=[],options:n}=this,o=e,a=this._getActiveElements(t,s,i,o),r=D(t),l=function(t,e,i,s){return i&&"mouseout"!==t.type?s?e:t:null}(t,this._lastEvent,i,r);i&&(this._lastEvent=null,d(n.onHover,[t,a,this],this),r&&d(n.onClick,[t,a,this],this));const h=!f(a,s);return(h||e)&&(this._active=a,this._updateHoverStyles(a,s,e)),this._lastEvent=l,h}_getActiveElements(t,e,i,s){if("mouseout"===t.type)return[];if(!i)return e;const n=this.options.hover;return this.getElementsAtEventForMode(t,n.mode,n,s)}}function Tn(){return u(An.instances,(t=>t._plugins.invalidate()))}function Ln(){throw new Error("This method is not implemented: Check that a complete date adapter is provided.")}class En{static override(t){Object.assign(En.prototype,t)}options;constructor(t){this.options=t||{}}init(){}formats(){return Ln()}parse(){return Ln()}format(){return Ln()}add(){return Ln()}diff(){return Ln()}startOf(){return Ln()}endOf(){return Ln()}}var Rn={_date:En};function In(t){const e=t.iScale,i=function(t,e){if(!t._cache.$bar){const i=t.getMatchingVisibleMetas(e);let s=[];for(let e=0,n=i.length;et-e)))}return t._cache.$bar}(e,t.type);let s,n,o,a,r=e._length;const l=()=>{32767!==o&&-32768!==o&&(k(a)&&(r=Math.min(r,Math.abs(o-a)||r)),a=o)};for(s=0,n=i.length;sMath.abs(r)&&(l=r,h=a),e[i.axis]=h,e._custom={barStart:l,barEnd:h,start:n,end:o,min:a,max:r}}(t,e,i,s):e[i.axis]=i.parse(t,s),e}function Fn(t,e,i,s){const n=t.iScale,o=t.vScale,a=n.getLabels(),r=n===o,l=[];let h,c,d,u;for(h=i,c=i+s;ht.x,i="left",s="right"):(e=t.base"spacing"!==t,_indexable:t=>"spacing"!==t&&!t.startsWith("borderDash")&&!t.startsWith("hoverBorderDash")};static overrides={aspectRatio:1,plugins:{legend:{labels:{generateLabels(t){const e=t.data;if(e.labels.length&&e.datasets.length){const{labels:{pointStyle:i,color:s}}=t.legend.options;return e.labels.map(((e,n)=>{const o=t.getDatasetMeta(0).controller.getStyle(n);return{text:e,fillStyle:o.backgroundColor,strokeStyle:o.borderColor,fontColor:s,lineWidth:o.borderWidth,pointStyle:i,hidden:!t.getDataVisibility(n),index:n}}))}return[]}},onClick(t,e,i){i.chart.toggleDataVisibility(e.index),i.chart.update()}}}};constructor(t,e){super(t,e),this.enableOptionSharing=!0,this.innerRadius=void 0,this.outerRadius=void 0,this.offsetX=void 0,this.offsetY=void 0}linkScales(){}parse(t,e){const i=this.getDataset().data,s=this._cachedMeta;if(!1===this._parsing)s._parsed=i;else{let n,a,r=t=>+i[t];if(o(i[t])){const{key:t="value"}=this._parsing;r=e=>+M(i[e],t)}for(n=t,a=t+e;nZ(t,r,l,!0)?1:Math.max(e,e*i,s,s*i),g=(t,e,s)=>Z(t,r,l,!0)?-1:Math.min(e,e*i,s,s*i),p=f(0,h,d),m=f(E,c,u),b=g(C,h,d),x=g(C+E,c,u);s=(p-b)/2,n=(m-x)/2,o=-(p+b)/2,a=-(m+x)/2}return{ratioX:s,ratioY:n,offsetX:o,offsetY:a}}(u,d,r),b=(i.width-o)/f,x=(i.height-o)/g,_=Math.max(Math.min(b,x)/2,0),y=c(this.options.radius,_),v=(y-Math.max(y*r,0))/this._getVisibleDatasetWeightTotal();this.offsetX=p*y,this.offsetY=m*y,s.total=this.calculateTotal(),this.outerRadius=y-v*this._getRingWeightOffset(this.index),this.innerRadius=Math.max(this.outerRadius-v*l,0),this.updateElements(n,0,n.length,t)}_circumference(t,e){const i=this.options,s=this._cachedMeta,n=this._getCircumference();return e&&i.animation.animateRotate||!this.chart.getDataVisibility(t)||null===s._parsed[t]||s.data[t].hidden?0:this.calculateCircumference(s._parsed[t]*n/O)}updateElements(t,e,i,s){const n="reset"===s,o=this.chart,a=o.chartArea,r=o.options.animation,l=(a.left+a.right)/2,h=(a.top+a.bottom)/2,c=n&&r.animateScale,d=c?0:this.innerRadius,u=c?0:this.outerRadius,{sharedOptions:f,includeOptions:g}=this._getSharedOptions(e,s);let p,m=this._getRotation();for(p=0;p0&&!isNaN(t)?O*(Math.abs(t)/e):0}getLabelAndValue(t){const e=this._cachedMeta,i=this.chart,s=i.data.labels||[],n=ne(e._parsed[t],i.options.locale);return{label:s[t]||"",value:n}}getMaxBorderWidth(t){let e=0;const i=this.chart;let s,n,o,a,r;if(!t)for(s=0,n=i.data.datasets.length;s{const o=t.getDatasetMeta(0).controller.getStyle(n);return{text:e,fillStyle:o.backgroundColor,strokeStyle:o.borderColor,fontColor:s,lineWidth:o.borderWidth,pointStyle:i,hidden:!t.getDataVisibility(n),index:n}}))}return[]}},onClick(t,e,i){i.chart.toggleDataVisibility(e.index),i.chart.update()}}},scales:{r:{type:"radialLinear",angleLines:{display:!1},beginAtZero:!0,grid:{circular:!0},pointLabels:{display:!1},startAngle:0}}};constructor(t,e){super(t,e),this.innerRadius=void 0,this.outerRadius=void 0}getLabelAndValue(t){const e=this._cachedMeta,i=this.chart,s=i.data.labels||[],n=ne(e._parsed[t].r,i.options.locale);return{label:s[t]||"",value:n}}parseObjectData(t,e,i,s){return ii.bind(this)(t,e,i,s)}update(t){const e=this._cachedMeta.data;this._updateRadius(),this.updateElements(e,0,e.length,t)}getMinMax(){const t=this._cachedMeta,e={min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY};return t.data.forEach(((t,i)=>{const s=this.getParsed(i).r;!isNaN(s)&&this.chart.getDataVisibility(i)&&(se.max&&(e.max=s))})),e}_updateRadius(){const t=this.chart,e=t.chartArea,i=t.options,s=Math.min(e.right-e.left,e.bottom-e.top),n=Math.max(s/2,0),o=(n-Math.max(i.cutoutPercentage?n/100*i.cutoutPercentage:1,0))/t.getVisibleDatasetCount();this.outerRadius=n-o*this.index,this.innerRadius=this.outerRadius-o}updateElements(t,e,i,s){const n="reset"===s,o=this.chart,a=o.options.animation,r=this._cachedMeta.rScale,l=r.xCenter,h=r.yCenter,c=r.getIndexAngle(0)-.5*C;let d,u=c;const f=360/this.countVisibleElements();for(d=0;d{!isNaN(this.getParsed(i).r)&&this.chart.getDataVisibility(i)&&e++})),e}_computeAngle(t,e,i){return this.chart.getDataVisibility(t)?$(this.resolveDataElementOptions(t,e).angle||i):0}}var Yn=Object.freeze({__proto__:null,BarController:class extends Ns{static id="bar";static defaults={datasetElementType:!1,dataElementType:"bar",categoryPercentage:.8,barPercentage:.9,grouped:!0,animations:{numbers:{type:"number",properties:["x","y","base","width","height"]}}};static overrides={scales:{_index_:{type:"category",offset:!0,grid:{offset:!0}},_value_:{type:"linear",beginAtZero:!0}}};parsePrimitiveData(t,e,i,s){return Fn(t,e,i,s)}parseArrayData(t,e,i,s){return Fn(t,e,i,s)}parseObjectData(t,e,i,s){const{iScale:n,vScale:o}=t,{xAxisKey:a="x",yAxisKey:r="y"}=this._parsing,l="x"===n.axis?a:r,h="x"===o.axis?a:r,c=[];let d,u,f,g;for(d=i,u=i+s;dt.controller.options.grouped)),o=i.options.stacked,a=[],r=this._cachedMeta.controller.getParsed(e),l=r&&r[i.axis],h=t=>{const e=t._parsed.find((t=>t[i.axis]===l)),n=e&&e[t.vScale.axis];if(s(n)||isNaN(n))return!0};for(const i of n)if((void 0===e||!h(i))&&((!1===o||-1===a.indexOf(i.stack)||void 0===o&&void 0===i.stack)&&a.push(i.stack),i.index===t))break;return a.length||a.push(void 0),a}_getStackCount(t){return this._getStacks(void 0,t).length}_getStackIndex(t,e,i){const s=this._getStacks(t,i),n=void 0!==e?s.indexOf(e):-1;return-1===n?s.length-1:n}_getRuler(){const t=this.options,e=this._cachedMeta,i=e.iScale,s=[];let n,o;for(n=0,o=e.data.length;n=i?1:-1)}(u,e,r)*a,f===r&&(b-=u/2);const t=e.getPixelForDecimal(0),s=e.getPixelForDecimal(1),o=Math.min(t,s),h=Math.max(t,s);b=Math.max(Math.min(b,h),o),d=b+u,i&&!c&&(l._stacks[e.axis]._visualValues[n]=e.getValueForPixel(d)-e.getValueForPixel(b))}if(b===e.getPixelForValue(r)){const t=F(u)*e.getLineWidthForValue(r)/2;b+=t,u-=t}return{size:u,base:b,head:d,center:d+u/2}}_calculateBarIndexPixels(t,e){const i=e.scale,n=this.options,o=n.skipNull,a=l(n.maxBarThickness,1/0);let r,h;if(e.grouped){const i=o?this._getStackCount(t):e.stackCount,l="flex"===n.barThickness?function(t,e,i,s){const n=e.pixels,o=n[t];let a=t>0?n[t-1]:null,r=t=0;--i)e=Math.max(e,t[i].size(this.resolveDataElementOptions(i))/2);return e>0&&e}getLabelAndValue(t){const e=this._cachedMeta,i=this.chart.data.labels||[],{xScale:s,yScale:n}=e,o=this.getParsed(t),a=s.getLabelForValue(o.x),r=n.getLabelForValue(o.y),l=o._custom;return{label:i[t]||"",value:"("+a+", "+r+(l?", "+l:"")+")"}}update(t){const e=this._cachedMeta.data;this.updateElements(e,0,e.length,t)}updateElements(t,e,i,s){const n="reset"===s,{iScale:o,vScale:a}=this._cachedMeta,{sharedOptions:r,includeOptions:l}=this._getSharedOptions(e,s),h=o.axis,c=a.axis;for(let d=e;d0&&this.getParsed(e-1);for(let i=0;i<_;++i){const g=t[i],_=b?g:{};if(i=x){_.skip=!0;continue}const v=this.getParsed(i),M=s(v[f]),w=_[u]=a.getPixelForValue(v[u],i),k=_[f]=o||M?r.getBasePixel():r.getPixelForValue(l?this.applyStack(r,v,l):v[f],i);_.skip=isNaN(w)||isNaN(k)||M,_.stop=i>0&&Math.abs(v[u]-y[u])>m,p&&(_.parsed=v,_.raw=h.data[i]),d&&(_.options=c||this.resolveDataElementOptions(i,g.active?"active":n)),b||this.updateElement(g,i,_,n),y=v}}getMaxOverflow(){const t=this._cachedMeta,e=t.dataset,i=e.options&&e.options.borderWidth||0,s=t.data||[];if(!s.length)return i;const n=s[0].size(this.resolveDataElementOptions(0)),o=s[s.length-1].size(this.resolveDataElementOptions(s.length-1));return Math.max(i,n,o)/2}draw(){const t=this._cachedMeta;t.dataset.updateControlPoints(this.chart.chartArea,t.iScale.axis),super.draw()}},PieController:class extends jn{static id="pie";static defaults={cutout:0,rotation:0,circumference:360,radius:"100%"}},PolarAreaController:$n,RadarController:class extends Ns{static id="radar";static defaults={datasetElementType:"line",dataElementType:"point",indexAxis:"r",showLine:!0,elements:{line:{fill:"start"}}};static overrides={aspectRatio:1,scales:{r:{type:"radialLinear"}}};getLabelAndValue(t){const e=this._cachedMeta.vScale,i=this.getParsed(t);return{label:e.getLabels()[t],value:""+e.getLabelForValue(i[e.axis])}}parseObjectData(t,e,i,s){return ii.bind(this)(t,e,i,s)}update(t){const e=this._cachedMeta,i=e.dataset,s=e.data||[],n=e.iScale.getLabels();if(i.points=s,"resize"!==t){const e=this.resolveDatasetElementOptions(t);this.options.showLine||(e.borderWidth=0);const o={_loop:!0,_fullLoop:n.length===s.length,options:e};this.updateElement(i,void 0,o,t)}this.updateElements(s,0,s.length,t)}updateElements(t,e,i,s){const n=this._cachedMeta.rScale,o="reset"===s;for(let a=e;a0&&this.getParsed(e-1);for(let c=e;c0&&Math.abs(i[f]-_[f])>b,m&&(p.parsed=i,p.raw=h.data[c]),u&&(p.options=d||this.resolveDataElementOptions(c,e.active?"active":n)),x||this.updateElement(e,c,p,n),_=i}this.updateSharedOptions(d,n,c)}getMaxOverflow(){const t=this._cachedMeta,e=t.data||[];if(!this.options.showLine){let t=0;for(let i=e.length-1;i>=0;--i)t=Math.max(t,e[i].size(this.resolveDataElementOptions(i))/2);return t>0&&t}const i=t.dataset,s=i.options&&i.options.borderWidth||0;if(!e.length)return s;const n=e[0].size(this.resolveDataElementOptions(0)),o=e[e.length-1].size(this.resolveDataElementOptions(e.length-1));return Math.max(s,n,o)/2}}});function Un(t,e,i,s){const n=vi(t.options.borderRadius,["outerStart","outerEnd","innerStart","innerEnd"]);const o=(i-e)/2,a=Math.min(o,s*e/2),r=t=>{const e=(i-Math.min(o,t))*s/2;return J(t,0,Math.min(o,e))};return{outerStart:r(n.outerStart),outerEnd:r(n.outerEnd),innerStart:J(n.innerStart,0,a),innerEnd:J(n.innerEnd,0,a)}}function Xn(t,e,i,s){return{x:i+t*Math.cos(e),y:s+t*Math.sin(e)}}function qn(t,e,i,s,n,o){const{x:a,y:r,startAngle:l,pixelMargin:h,innerRadius:c}=e,d=Math.max(e.outerRadius+s+i-h,0),u=c>0?c+s+i+h:0;let f=0;const g=n-l;if(s){const t=((c>0?c-s:0)+(d>0?d-s:0))/2;f=(g-(0!==t?g*t/(t+s):g))/2}const p=(g-Math.max(.001,g*d-i/C)/d)/2,m=l+p+f,b=n-p-f,{outerStart:x,outerEnd:_,innerStart:y,innerEnd:v}=Un(e,u,d,b-m),M=d-x,w=d-_,k=m+x/M,S=b-_/w,P=u+y,D=u+v,O=m+y/P,A=b-v/D;if(t.beginPath(),o){const e=(k+S)/2;if(t.arc(a,r,d,k,e),t.arc(a,r,d,e,S),_>0){const e=Xn(w,S,a,r);t.arc(e.x,e.y,_,S,b+E)}const i=Xn(D,b,a,r);if(t.lineTo(i.x,i.y),v>0){const e=Xn(D,A,a,r);t.arc(e.x,e.y,v,b+E,A+Math.PI)}const s=(b-v/u+(m+y/u))/2;if(t.arc(a,r,u,b-v/u,s,!0),t.arc(a,r,u,s,m+y/u,!0),y>0){const e=Xn(P,O,a,r);t.arc(e.x,e.y,y,O+Math.PI,m-E)}const n=Xn(M,m,a,r);if(t.lineTo(n.x,n.y),x>0){const e=Xn(M,k,a,r);t.arc(e.x,e.y,x,m-E,k)}}else{t.moveTo(a,r);const e=Math.cos(k)*d+a,i=Math.sin(k)*d+r;t.lineTo(e,i);const s=Math.cos(S)*d+a,n=Math.sin(S)*d+r;t.lineTo(s,n)}t.closePath()}function Kn(t,e,i,s,n){const{fullCircles:o,startAngle:a,circumference:r,options:l}=e,{borderWidth:h,borderJoinStyle:c,borderDash:d,borderDashOffset:u}=l,f="inner"===l.borderAlign;if(!h)return;t.setLineDash(d||[]),t.lineDashOffset=u,f?(t.lineWidth=2*h,t.lineJoin=c||"round"):(t.lineWidth=h,t.lineJoin=c||"bevel");let g=e.endAngle;if(o){qn(t,e,i,s,g,n);for(let e=0;en?(h=n/l,t.arc(o,a,l,i+h,s-h,!0)):t.arc(o,a,n,i+E,s-E),t.closePath(),t.clip()}(t,e,g),o||(qn(t,e,i,s,g,n),t.stroke())}function Gn(t,e,i=e){t.lineCap=l(i.borderCapStyle,e.borderCapStyle),t.setLineDash(l(i.borderDash,e.borderDash)),t.lineDashOffset=l(i.borderDashOffset,e.borderDashOffset),t.lineJoin=l(i.borderJoinStyle,e.borderJoinStyle),t.lineWidth=l(i.borderWidth,e.borderWidth),t.strokeStyle=l(i.borderColor,e.borderColor)}function Zn(t,e,i){t.lineTo(i.x,i.y)}function Jn(t,e,i={}){const s=t.length,{start:n=0,end:o=s-1}=i,{start:a,end:r}=e,l=Math.max(n,a),h=Math.min(o,r),c=nr&&o>r;return{count:s,start:l,loop:e.loop,ilen:h(a+(h?r-t:t))%o,_=()=>{f!==g&&(t.lineTo(m,g),t.lineTo(m,f),t.lineTo(m,p))};for(l&&(d=n[x(0)],t.moveTo(d.x,d.y)),c=0;c<=r;++c){if(d=n[x(c)],d.skip)continue;const e=d.x,i=d.y,s=0|e;s===u?(ig&&(g=i),m=(b*m+e)/++b):(_(),t.lineTo(e,i),u=s,b=0,f=g=i),p=i}_()}function eo(t){const e=t.options,i=e.borderDash&&e.borderDash.length;return!(t._decimated||t._loop||e.tension||"monotone"===e.cubicInterpolationMode||e.stepped||i)?to:Qn}const io="function"==typeof Path2D;function so(t,e,i,s){io&&!e.options.segment?function(t,e,i,s){let n=e._path;n||(n=e._path=new Path2D,e.path(n,i,s)&&n.closePath()),Gn(t,e.options),t.stroke(n)}(t,e,i,s):function(t,e,i,s){const{segments:n,options:o}=e,a=eo(e);for(const r of n)Gn(t,o,r.style),t.beginPath(),a(t,e,r,{start:i,end:i+s-1})&&t.closePath(),t.stroke()}(t,e,i,s)}class no extends Hs{static id="line";static defaults={borderCapStyle:"butt",borderDash:[],borderDashOffset:0,borderJoinStyle:"miter",borderWidth:3,capBezierPoints:!0,cubicInterpolationMode:"default",fill:!1,spanGaps:!1,stepped:!1,tension:0};static defaultRoutes={backgroundColor:"backgroundColor",borderColor:"borderColor"};static descriptors={_scriptable:!0,_indexable:t=>"borderDash"!==t&&"fill"!==t};constructor(t){super(),this.animated=!0,this.options=void 0,this._chart=void 0,this._loop=void 0,this._fullLoop=void 0,this._path=void 0,this._points=void 0,this._segments=void 0,this._decimated=!1,this._pointsUpdated=!1,this._datasetIndex=void 0,t&&Object.assign(this,t)}updateControlPoints(t,e){const i=this.options;if((i.tension||"monotone"===i.cubicInterpolationMode)&&!i.stepped&&!this._pointsUpdated){const s=i.spanGaps?this._loop:this._fullLoop;hi(this._points,i,t,s,e),this._pointsUpdated=!0}}set points(t){this._points=t,delete this._segments,delete this._path,this._pointsUpdated=!1}get points(){return this._points}get segments(){return this._segments||(this._segments=zi(this,this.options.segment))}first(){const t=this.segments,e=this.points;return t.length&&e[t[0].start]}last(){const t=this.segments,e=this.points,i=t.length;return i&&e[t[i-1].end]}interpolate(t,e){const i=this.options,s=t[e],n=this.points,o=Ii(this,{property:e,start:s,end:s});if(!o.length)return;const a=[],r=function(t){return t.stepped?pi:t.tension||"monotone"===t.cubicInterpolationMode?mi:gi}(i);let l,h;for(l=0,h=o.length;l"borderDash"!==t};circumference;endAngle;fullCircles;innerRadius;outerRadius;pixelMargin;startAngle;constructor(t){super(),this.options=void 0,this.circumference=void 0,this.startAngle=void 0,this.endAngle=void 0,this.innerRadius=void 0,this.outerRadius=void 0,this.pixelMargin=0,this.fullCircles=0,t&&Object.assign(this,t)}inRange(t,e,i){const s=this.getProps(["x","y"],i),{angle:n,distance:o}=X(s,{x:t,y:e}),{startAngle:a,endAngle:r,innerRadius:h,outerRadius:c,circumference:d}=this.getProps(["startAngle","endAngle","innerRadius","outerRadius","circumference"],i),u=(this.options.spacing+this.options.borderWidth)/2,f=l(d,r-a),g=Z(n,a,r)&&a!==r,p=f>=O||g,m=tt(o,h+u,c+u);return p&&m}getCenterPoint(t){const{x:e,y:i,startAngle:s,endAngle:n,innerRadius:o,outerRadius:a}=this.getProps(["x","y","startAngle","endAngle","innerRadius","outerRadius"],t),{offset:r,spacing:l}=this.options,h=(s+n)/2,c=(o+a+l+r)/2;return{x:e+Math.cos(h)*c,y:i+Math.sin(h)*c}}tooltipPosition(t){return this.getCenterPoint(t)}draw(t){const{options:e,circumference:i}=this,s=(e.offset||0)/4,n=(e.spacing||0)/2,o=e.circular;if(this.pixelMargin="inner"===e.borderAlign?.33:0,this.fullCircles=i>O?Math.floor(i/O):0,0===i||this.innerRadius<0||this.outerRadius<0)return;t.save();const a=(this.startAngle+this.endAngle)/2;t.translate(Math.cos(a)*s,Math.sin(a)*s);const r=s*(1-Math.sin(Math.min(C,i||0)));t.fillStyle=e.backgroundColor,t.strokeStyle=e.borderColor,function(t,e,i,s,n){const{fullCircles:o,startAngle:a,circumference:r}=e;let l=e.endAngle;if(o){qn(t,e,i,s,l,n);for(let e=0;e("string"==typeof e?(i=t.push(e)-1,s.unshift({index:i,label:e})):isNaN(e)&&(i=null),i))(t,e,i,s);return n!==t.lastIndexOf(e)?i:n}function po(t){const e=this.getLabels();return t>=0&&ts=e?s:t,a=t=>n=i?n:t;if(t){const t=F(s),e=F(n);t<0&&e<0?a(0):t>0&&e>0&&o(0)}if(s===n){let e=0===n?1:Math.abs(.05*n);a(n+e),t||o(s-e)}this.min=s,this.max=n}getTickLimit(){const t=this.options.ticks;let e,{maxTicksLimit:i,stepSize:s}=t;return s?(e=Math.ceil(this.max/s)-Math.floor(this.min/s)+1,e>1e3&&(console.warn(`scales.${this.id}.ticks.stepSize: ${s} would result generating up to ${e} ticks. Limiting to 1000.`),e=1e3)):(e=this.computeTickLimit(),i=i||11),i&&(e=Math.min(i,e)),e}computeTickLimit(){return Number.POSITIVE_INFINITY}buildTicks(){const t=this.options,e=t.ticks;let i=this.getTickLimit();i=Math.max(2,i);const n=function(t,e){const i=[],{bounds:n,step:o,min:a,max:r,precision:l,count:h,maxTicks:c,maxDigits:d,includeBounds:u}=t,f=o||1,g=c-1,{min:p,max:m}=e,b=!s(a),x=!s(r),_=!s(h),y=(m-p)/(d+1);let v,M,w,k,S=B((m-p)/g/f)*f;if(S<1e-14&&!b&&!x)return[{value:p},{value:m}];k=Math.ceil(m/S)-Math.floor(p/S),k>g&&(S=B(k*S/g/f)*f),s(l)||(v=Math.pow(10,l),S=Math.ceil(S*v)/v),"ticks"===n?(M=Math.floor(p/S)*S,w=Math.ceil(m/S)*S):(M=p,w=m),b&&x&&o&&H((r-a)/o,S/1e3)?(k=Math.round(Math.min((r-a)/S,c)),S=(r-a)/k,M=a,w=r):_?(M=b?a:M,w=x?r:w,k=h-1,S=(w-M)/k):(k=(w-M)/S,k=V(k,Math.round(k),S/1e3)?Math.round(k):Math.ceil(k));const P=Math.max(U(S),U(M));v=Math.pow(10,s(l)?P:l),M=Math.round(M*v)/v,w=Math.round(w*v)/v;let D=0;for(b&&(u&&M!==a?(i.push({value:a}),Mr)break;i.push({value:t})}return x&&u&&w!==r?i.length&&V(i[i.length-1].value,r,mo(r,y,t))?i[i.length-1].value=r:i.push({value:r}):x&&w!==r||i.push({value:w}),i}({maxTicks:i,bounds:t.bounds,min:t.min,max:t.max,precision:e.precision,step:e.stepSize,count:e.count,maxDigits:this._maxDigits(),horizontal:this.isHorizontal(),minRotation:e.minRotation||0,includeBounds:!1!==e.includeBounds},this._range||this);return"ticks"===t.bounds&&j(n,this,"value"),t.reverse?(n.reverse(),this.start=this.max,this.end=this.min):(this.start=this.min,this.end=this.max),n}configure(){const t=this.ticks;let e=this.min,i=this.max;if(super.configure(),this.options.offset&&t.length){const s=(i-e)/Math.max(t.length-1,1)/2;e-=s,i+=s}this._startValue=e,this._endValue=i,this._valueRange=i-e}getLabelForValue(t){return ne(t,this.chart.options.locale,this.options.ticks.format)}}class xo extends bo{static id="linear";static defaults={ticks:{callback:ae.formatters.numeric}};determineDataLimits(){const{min:t,max:e}=this.getMinMax(!0);this.min=a(t)?t:0,this.max=a(e)?e:1,this.handleTickRangeOptions()}computeTickLimit(){const t=this.isHorizontal(),e=t?this.width:this.height,i=$(this.options.ticks.minRotation),s=(t?Math.sin(i):Math.cos(i))||.001,n=this._resolveTickFontOptions(0);return Math.ceil(e/Math.min(40,n.lineHeight/s))}getPixelForValue(t){return null===t?NaN:this.getPixelForDecimal((t-this._startValue)/this._valueRange)}getValueForPixel(t){return this._startValue+this.getDecimalForPixel(t)*this._valueRange}}const _o=t=>Math.floor(z(t)),yo=(t,e)=>Math.pow(10,_o(t)+e);function vo(t){return 1===t/Math.pow(10,_o(t))}function Mo(t,e,i){const s=Math.pow(10,i),n=Math.floor(t/s);return Math.ceil(e/s)-n}function wo(t,{min:e,max:i}){e=r(t.min,e);const s=[],n=_o(e);let o=function(t,e){let i=_o(e-t);for(;Mo(t,e,i)>10;)i++;for(;Mo(t,e,i)<10;)i--;return Math.min(i,_o(t))}(e,i),a=o<0?Math.pow(10,Math.abs(o)):1;const l=Math.pow(10,o),h=n>o?Math.pow(10,n):0,c=Math.round((e-h)*a)/a,d=Math.floor((e-h)/l/10)*l*10;let u=Math.floor((c-d)/Math.pow(10,o)),f=r(t.min,Math.round((h+d+u*Math.pow(10,o))*a)/a);for(;f=10?u=u<15?15:20:u++,u>=20&&(o++,u=2,a=o>=0?1:a),f=Math.round((h+d+u*Math.pow(10,o))*a)/a;const g=r(t.max,f);return s.push({value:g,major:vo(g),significand:u}),s}class ko extends Js{static id="logarithmic";static defaults={ticks:{callback:ae.formatters.logarithmic,major:{enabled:!0}}};constructor(t){super(t),this.start=void 0,this.end=void 0,this._startValue=void 0,this._valueRange=0}parse(t,e){const i=bo.prototype.parse.apply(this,[t,e]);if(0!==i)return a(i)&&i>0?i:null;this._zero=!0}determineDataLimits(){const{min:t,max:e}=this.getMinMax(!0);this.min=a(t)?Math.max(0,t):null,this.max=a(e)?Math.max(0,e):null,this.options.beginAtZero&&(this._zero=!0),this._zero&&this.min!==this._suggestedMin&&!a(this._userMin)&&(this.min=t===yo(this.min,0)?yo(this.min,-1):yo(this.min,0)),this.handleTickRangeOptions()}handleTickRangeOptions(){const{minDefined:t,maxDefined:e}=this.getUserBounds();let i=this.min,s=this.max;const n=e=>i=t?i:e,o=t=>s=e?s:t;i===s&&(i<=0?(n(1),o(10)):(n(yo(i,-1)),o(yo(s,1)))),i<=0&&n(yo(s,-1)),s<=0&&o(yo(i,1)),this.min=i,this.max=s}buildTicks(){const t=this.options,e=wo({min:this._userMin,max:this._userMax},this);return"ticks"===t.bounds&&j(e,this,"value"),t.reverse?(e.reverse(),this.start=this.max,this.end=this.min):(this.start=this.min,this.end=this.max),e}getLabelForValue(t){return void 0===t?"0":ne(t,this.chart.options.locale,this.options.ticks.format)}configure(){const t=this.min;super.configure(),this._startValue=z(t),this._valueRange=z(this.max)-z(t)}getPixelForValue(t){return void 0!==t&&0!==t||(t=this.min),null===t||isNaN(t)?NaN:this.getPixelForDecimal(t===this.min?0:(z(t)-this._startValue)/this._valueRange)}getValueForPixel(t){const e=this.getDecimalForPixel(t);return Math.pow(10,this._startValue+e*this._valueRange)}}function So(t){const e=t.ticks;if(e.display&&t.display){const t=ki(e.backdropPadding);return l(e.font&&e.font.size,ue.font.size)+t.height}return 0}function Po(t,e,i,s,n){return t===s||t===n?{start:e-i/2,end:e+i/2}:tn?{start:e-i,end:e}:{start:e,end:e+i}}function Do(t){const e={l:t.left+t._padding.left,r:t.right-t._padding.right,t:t.top+t._padding.top,b:t.bottom-t._padding.bottom},i=Object.assign({},e),s=[],o=[],a=t._pointLabels.length,r=t.options.pointLabels,l=r.centerPointLabels?C/a:0;for(let u=0;ue.r&&(r=(s.end-e.r)/o,t.r=Math.max(t.r,e.r+r)),n.starte.b&&(l=(n.end-e.b)/a,t.b=Math.max(t.b,e.b+l))}function Oo(t,e,i){const s=t.drawingArea,{extra:n,additionalAngle:o,padding:a,size:r}=i,l=t.getPointPosition(e,s+n+a,o),h=Math.round(Y(G(l.angle+E))),c=function(t,e,i){90===i||270===i?t-=e/2:(i>270||i<90)&&(t-=e);return t}(l.y,r.h,h),d=function(t){if(0===t||180===t)return"center";if(t<180)return"left";return"right"}(h),u=function(t,e,i){"right"===i?t-=e:"center"===i&&(t-=e/2);return t}(l.x,r.w,d);return{visible:!0,x:l.x,y:c,textAlign:d,left:u,top:c,right:u+r.w,bottom:c+r.h}}function Ao(t,e){if(!e)return!0;const{left:i,top:s,right:n,bottom:o}=t;return!(Re({x:i,y:s},e)||Re({x:i,y:o},e)||Re({x:n,y:s},e)||Re({x:n,y:o},e))}function To(t,e,i){const{left:n,top:o,right:a,bottom:r}=i,{backdropColor:l}=e;if(!s(l)){const i=wi(e.borderRadius),s=ki(e.backdropPadding);t.fillStyle=l;const h=n-s.left,c=o-s.top,d=a-n+s.width,u=r-o+s.height;Object.values(i).some((t=>0!==t))?(t.beginPath(),He(t,{x:h,y:c,w:d,h:u,radius:i}),t.fill()):t.fillRect(h,c,d,u)}}function Lo(t,e,i,s){const{ctx:n}=t;if(i)n.arc(t.xCenter,t.yCenter,e,0,O);else{let i=t.getPointPosition(0,e);n.moveTo(i.x,i.y);for(let o=1;ot,padding:5,centerPointLabels:!1}};static defaultRoutes={"angleLines.color":"borderColor","pointLabels.color":"color","ticks.color":"color"};static descriptors={angleLines:{_fallback:"grid"}};constructor(t){super(t),this.xCenter=void 0,this.yCenter=void 0,this.drawingArea=void 0,this._pointLabels=[],this._pointLabelItems=[]}setDimensions(){const t=this._padding=ki(So(this.options)/2),e=this.width=this.maxWidth-t.width,i=this.height=this.maxHeight-t.height;this.xCenter=Math.floor(this.left+e/2+t.left),this.yCenter=Math.floor(this.top+i/2+t.top),this.drawingArea=Math.floor(Math.min(e,i)/2)}determineDataLimits(){const{min:t,max:e}=this.getMinMax(!1);this.min=a(t)&&!isNaN(t)?t:0,this.max=a(e)&&!isNaN(e)?e:0,this.handleTickRangeOptions()}computeTickLimit(){return Math.ceil(this.drawingArea/So(this.options))}generateTickLabels(t){bo.prototype.generateTickLabels.call(this,t),this._pointLabels=this.getLabels().map(((t,e)=>{const i=d(this.options.pointLabels.callback,[t,e],this);return i||0===i?i:""})).filter(((t,e)=>this.chart.getDataVisibility(e)))}fit(){const t=this.options;t.display&&t.pointLabels.display?Do(this):this.setCenterPoint(0,0,0,0)}setCenterPoint(t,e,i,s){this.xCenter+=Math.floor((t-e)/2),this.yCenter+=Math.floor((i-s)/2),this.drawingArea-=Math.min(this.drawingArea/2,Math.max(t,e,i,s))}getIndexAngle(t){return G(t*(O/(this._pointLabels.length||1))+$(this.options.startAngle||0))}getDistanceFromCenterForValue(t){if(s(t))return NaN;const e=this.drawingArea/(this.max-this.min);return this.options.reverse?(this.max-t)*e:(t-this.min)*e}getValueForDistanceFromCenter(t){if(s(t))return NaN;const e=t/(this.drawingArea/(this.max-this.min));return this.options.reverse?this.max-e:this.min+e}getPointLabelContext(t){const e=this._pointLabels||[];if(t>=0&&t=0;n--){const e=t._pointLabelItems[n];if(!e.visible)continue;const o=s.setContext(t.getPointLabelContext(n));To(i,o,e);const a=Si(o.font),{x:r,y:l,textAlign:h}=e;Ne(i,t._pointLabels[n],r,l+a.lineHeight/2,a,{color:o.color,textAlign:h,textBaseline:"middle"})}}(this,o),s.display&&this.ticks.forEach(((t,e)=>{if(0!==e||0===e&&this.min<0){r=this.getDistanceFromCenterForValue(t.value);const i=this.getContext(e),a=s.setContext(i),l=n.setContext(i);!function(t,e,i,s,n){const o=t.ctx,a=e.circular,{color:r,lineWidth:l}=e;!a&&!s||!r||!l||i<0||(o.save(),o.strokeStyle=r,o.lineWidth=l,o.setLineDash(n.dash||[]),o.lineDashOffset=n.dashOffset,o.beginPath(),Lo(t,i,a,s),o.closePath(),o.stroke(),o.restore())}(this,a,r,o,l)}})),i.display){for(t.save(),a=o-1;a>=0;a--){const s=i.setContext(this.getPointLabelContext(a)),{color:n,lineWidth:o}=s;o&&n&&(t.lineWidth=o,t.strokeStyle=n,t.setLineDash(s.borderDash),t.lineDashOffset=s.borderDashOffset,r=this.getDistanceFromCenterForValue(e.reverse?this.min:this.max),l=this.getPointPosition(a,r),t.beginPath(),t.moveTo(this.xCenter,this.yCenter),t.lineTo(l.x,l.y),t.stroke())}t.restore()}}drawBorder(){}drawLabels(){const t=this.ctx,e=this.options,i=e.ticks;if(!i.display)return;const s=this.getIndexAngle(0);let n,o;t.save(),t.translate(this.xCenter,this.yCenter),t.rotate(s),t.textAlign="center",t.textBaseline="middle",this.ticks.forEach(((s,a)=>{if(0===a&&this.min>=0&&!e.reverse)return;const r=i.setContext(this.getContext(a)),l=Si(r.font);if(n=this.getDistanceFromCenterForValue(this.ticks[a].value),r.showLabelBackdrop){t.font=l.string,o=t.measureText(s.label).width,t.fillStyle=r.backdropColor;const e=ki(r.backdropPadding);t.fillRect(-o/2-e.left,-n-l.size/2-e.top,o+e.width,l.size+e.height)}Ne(t,s.label,0,-n,l,{color:r.color,strokeColor:r.textStrokeColor,strokeWidth:r.textStrokeWidth})})),t.restore()}drawTitle(){}}const Ro={millisecond:{common:!0,size:1,steps:1e3},second:{common:!0,size:1e3,steps:60},minute:{common:!0,size:6e4,steps:60},hour:{common:!0,size:36e5,steps:24},day:{common:!0,size:864e5,steps:30},week:{common:!1,size:6048e5,steps:4},month:{common:!0,size:2628e6,steps:12},quarter:{common:!1,size:7884e6,steps:4},year:{common:!0,size:3154e7}},Io=Object.keys(Ro);function zo(t,e){return t-e}function Fo(t,e){if(s(e))return null;const i=t._adapter,{parser:n,round:o,isoWeekday:r}=t._parseOpts;let l=e;return"function"==typeof n&&(l=n(l)),a(l)||(l="string"==typeof n?i.parse(l,n):i.parse(l)),null===l?null:(o&&(l="week"!==o||!N(r)&&!0!==r?i.startOf(l,o):i.startOf(l,"isoWeek",r)),+l)}function Vo(t,e,i,s){const n=Io.length;for(let o=Io.indexOf(t);o=e?i[s]:i[n]]=!0}}else t[e]=!0}function Wo(t,e,i){const s=[],n={},o=e.length;let a,r;for(a=0;a=0&&(e[l].major=!0);return e}(t,s,n,i):s}class No extends Js{static id="time";static defaults={bounds:"data",adapters:{},time:{parser:!1,unit:!1,round:!1,isoWeekday:!1,minUnit:"millisecond",displayFormats:{}},ticks:{source:"auto",callback:!1,major:{enabled:!1}}};constructor(t){super(t),this._cache={data:[],labels:[],all:[]},this._unit="day",this._majorUnit=void 0,this._offsets={},this._normalized=!1,this._parseOpts=void 0}init(t,e={}){const i=t.time||(t.time={}),s=this._adapter=new Rn._date(t.adapters.date);s.init(e),x(i.displayFormats,s.formats()),this._parseOpts={parser:i.parser,round:i.round,isoWeekday:i.isoWeekday},super.init(t),this._normalized=e.normalized}parse(t,e){return void 0===t?null:Fo(this,t)}beforeLayout(){super.beforeLayout(),this._cache={data:[],labels:[],all:[]}}determineDataLimits(){const t=this.options,e=this._adapter,i=t.time.unit||"day";let{min:s,max:n,minDefined:o,maxDefined:r}=this.getUserBounds();function l(t){o||isNaN(t.min)||(s=Math.min(s,t.min)),r||isNaN(t.max)||(n=Math.max(n,t.max))}o&&r||(l(this._getLabelBounds()),"ticks"===t.bounds&&"labels"===t.ticks.source||l(this.getMinMax(!1))),s=a(s)&&!isNaN(s)?s:+e.startOf(Date.now(),i),n=a(n)&&!isNaN(n)?n:+e.endOf(Date.now(),i)+1,this.min=Math.min(s,n-1),this.max=Math.max(s+1,n)}_getLabelBounds(){const t=this.getLabelTimestamps();let e=Number.POSITIVE_INFINITY,i=Number.NEGATIVE_INFINITY;return t.length&&(e=t[0],i=t[t.length-1]),{min:e,max:i}}buildTicks(){const t=this.options,e=t.time,i=t.ticks,s="labels"===i.source?this.getLabelTimestamps():this._generate();"ticks"===t.bounds&&s.length&&(this.min=this._userMin||s[0],this.max=this._userMax||s[s.length-1]);const n=this.min,o=nt(s,n,this.max);return this._unit=e.unit||(i.autoSkip?Vo(e.minUnit,this.min,this.max,this._getLabelCapacity(n)):function(t,e,i,s,n){for(let o=Io.length-1;o>=Io.indexOf(i);o--){const i=Io[o];if(Ro[i].common&&t._adapter.diff(n,s,i)>=e-1)return i}return Io[i?Io.indexOf(i):0]}(this,o.length,e.minUnit,this.min,this.max)),this._majorUnit=i.major.enabled&&"year"!==this._unit?function(t){for(let e=Io.indexOf(t)+1,i=Io.length;e+t.value)))}initOffsets(t=[]){let e,i,s=0,n=0;this.options.offset&&t.length&&(e=this.getDecimalForValue(t[0]),s=1===t.length?1-e:(this.getDecimalForValue(t[1])-e)/2,i=this.getDecimalForValue(t[t.length-1]),n=1===t.length?i:(i-this.getDecimalForValue(t[t.length-2]))/2);const o=t.length<3?.5:.25;s=J(s,0,o),n=J(n,0,o),this._offsets={start:s,end:n,factor:1/(s+1+n)}}_generate(){const t=this._adapter,e=this.min,i=this.max,s=this.options,n=s.time,o=n.unit||Vo(n.minUnit,e,i,this._getLabelCapacity(e)),a=l(s.ticks.stepSize,1),r="week"===o&&n.isoWeekday,h=N(r)||!0===r,c={};let d,u,f=e;if(h&&(f=+t.startOf(f,"isoWeek",r)),f=+t.startOf(f,h?"day":o),t.diff(i,e,o)>1e5*a)throw new Error(e+" and "+i+" are too far apart with stepSize of "+a+" "+o);const g="data"===s.ticks.source&&this.getDataTimestamps();for(d=f,u=0;d+t))}getLabelForValue(t){const e=this._adapter,i=this.options.time;return i.tooltipFormat?e.format(t,i.tooltipFormat):e.format(t,i.displayFormats.datetime)}format(t,e){const i=this.options.time.displayFormats,s=this._unit,n=e||i[s];return this._adapter.format(t,n)}_tickFormatFunction(t,e,i,s){const n=this.options,o=n.ticks.callback;if(o)return d(o,[t,e,i],this);const a=n.time.displayFormats,r=this._unit,l=this._majorUnit,h=r&&a[r],c=l&&a[l],u=i[e],f=l&&c&&u&&u.major;return this._adapter.format(t,s||(f?c:h))}generateTickLabels(t){let e,i,s;for(e=0,i=t.length;e0?a:1}getDataTimestamps(){let t,e,i=this._cache.data||[];if(i.length)return i;const s=this.getMatchingVisibleMetas();if(this._normalized&&s.length)return this._cache.data=s[0].controller.getAllParsedValues(this);for(t=0,e=s.length;t=t[r].pos&&e<=t[l].pos&&({lo:r,hi:l}=it(t,"pos",e)),({pos:s,time:o}=t[r]),({pos:n,time:a}=t[l])):(e>=t[r].time&&e<=t[l].time&&({lo:r,hi:l}=it(t,"time",e)),({time:s,pos:o}=t[r]),({time:n,pos:a}=t[l]));const h=n-s;return h?o+(a-o)*(e-s)/h:o}var jo=Object.freeze({__proto__:null,CategoryScale:class extends Js{static id="category";static defaults={ticks:{callback:po}};constructor(t){super(t),this._startValue=void 0,this._valueRange=0,this._addedLabels=[]}init(t){const e=this._addedLabels;if(e.length){const t=this.getLabels();for(const{index:i,label:s}of e)t[i]===s&&t.splice(i,1);this._addedLabels=[]}super.init(t)}parse(t,e){if(s(t))return null;const i=this.getLabels();return((t,e)=>null===t?null:J(Math.round(t),0,e))(e=isFinite(e)&&i[e]===t?e:go(i,t,l(e,t),this._addedLabels),i.length-1)}determineDataLimits(){const{minDefined:t,maxDefined:e}=this.getUserBounds();let{min:i,max:s}=this.getMinMax(!0);"ticks"===this.options.bounds&&(t||(i=0),e||(s=this.getLabels().length-1)),this.min=i,this.max=s}buildTicks(){const t=this.min,e=this.max,i=this.options.offset,s=[];let n=this.getLabels();n=0===t&&e===n.length-1?n:n.slice(t,e+1),this._valueRange=Math.max(n.length-(i?0:1),1),this._startValue=this.min-(i?.5:0);for(let i=t;i<=e;i++)s.push({value:i});return s}getLabelForValue(t){return po.call(this,t)}configure(){super.configure(),this.isHorizontal()||(this._reversePixels=!this._reversePixels)}getPixelForValue(t){return"number"!=typeof t&&(t=this.parse(t)),null===t?NaN:this.getPixelForDecimal((t-this._startValue)/this._valueRange)}getPixelForTick(t){const e=this.ticks;return t<0||t>e.length-1?null:this.getPixelForValue(e[t].value)}getValueForPixel(t){return Math.round(this._startValue+this.getDecimalForPixel(t)*this._valueRange)}getBasePixel(){return this.bottom}},LinearScale:xo,LogarithmicScale:ko,RadialLinearScale:Eo,TimeScale:No,TimeSeriesScale:class extends No{static id="timeseries";static defaults=No.defaults;constructor(t){super(t),this._table=[],this._minPos=void 0,this._tableRange=void 0}initOffsets(){const t=this._getTimestampsForTable(),e=this._table=this.buildLookupTable(t);this._minPos=Ho(e,this.min),this._tableRange=Ho(e,this.max)-this._minPos,super.initOffsets(t)}buildLookupTable(t){const{min:e,max:i}=this,s=[],n=[];let o,a,r,l,h;for(o=0,a=t.length;o=e&&l<=i&&s.push(l);if(s.length<2)return[{time:e,pos:0},{time:i,pos:1}];for(o=0,a=s.length;ot-e))}_getTimestampsForTable(){let t=this._cache.all||[];if(t.length)return t;const e=this.getDataTimestamps(),i=this.getLabelTimestamps();return t=e.length&&i.length?this.normalize(e.concat(i)):e.length?e:i,t=this._cache.all=t,t}getDecimalForValue(t){return(Ho(this._table,t)-this._minPos)/this._tableRange}getValueForPixel(t){const e=this._offsets,i=this.getDecimalForPixel(t)/e.factor-e.end;return Ho(this._table,i*this._tableRange+this._minPos,!0)}}});const $o=["rgb(54, 162, 235)","rgb(255, 99, 132)","rgb(255, 159, 64)","rgb(255, 205, 86)","rgb(75, 192, 192)","rgb(153, 102, 255)","rgb(201, 203, 207)"],Yo=$o.map((t=>t.replace("rgb(","rgba(").replace(")",", 0.5)")));function Uo(t){return $o[t%$o.length]}function Xo(t){return Yo[t%Yo.length]}function qo(t){let e=0;return(i,s)=>{const n=t.getDatasetMeta(s).controller;n instanceof jn?e=function(t,e){return t.backgroundColor=t.data.map((()=>Uo(e++))),e}(i,e):n instanceof $n?e=function(t,e){return t.backgroundColor=t.data.map((()=>Xo(e++))),e}(i,e):n&&(e=function(t,e){return t.borderColor=Uo(e),t.backgroundColor=Xo(e),++e}(i,e))}}function Ko(t){let e;for(e in t)if(t[e].borderColor||t[e].backgroundColor)return!0;return!1}var Go={id:"colors",defaults:{enabled:!0,forceOverride:!1},beforeLayout(t,e,i){if(!i.enabled)return;const{data:{datasets:s},options:n}=t.config,{elements:o}=n,a=Ko(s)||(r=n)&&(r.borderColor||r.backgroundColor)||o&&Ko(o)||"rgba(0,0,0,0.1)"!==ue.borderColor||"rgba(0,0,0,0.1)"!==ue.backgroundColor;var r;if(!i.forceOverride&&a)return;const l=qo(t);s.forEach(l)}};function Zo(t){if(t._decimated){const e=t._data;delete t._decimated,delete t._data,Object.defineProperty(t,"data",{configurable:!0,enumerable:!0,writable:!0,value:e})}}function Jo(t){t.data.datasets.forEach((t=>{Zo(t)}))}var Qo={id:"decimation",defaults:{algorithm:"min-max",enabled:!1},beforeElementsUpdate:(t,e,i)=>{if(!i.enabled)return void Jo(t);const n=t.width;t.data.datasets.forEach(((e,o)=>{const{_data:a,indexAxis:r}=e,l=t.getDatasetMeta(o),h=a||e.data;if("y"===Pi([r,t.options.indexAxis]))return;if(!l.controller.supportsDecimation)return;const c=t.scales[l.xAxisID];if("linear"!==c.type&&"time"!==c.type)return;if(t.options.parsing)return;let{start:d,count:u}=function(t,e){const i=e.length;let s,n=0;const{iScale:o}=t,{min:a,max:r,minDefined:l,maxDefined:h}=o.getUserBounds();return l&&(n=J(it(e,o.axis,a).lo,0,i-1)),s=h?J(it(e,o.axis,r).hi+1,n,i)-n:i-n,{start:n,count:s}}(l,h);if(u<=(i.threshold||4*n))return void Zo(e);let f;switch(s(a)&&(e._data=h,delete e.data,Object.defineProperty(e,"data",{configurable:!0,enumerable:!0,get:function(){return this._decimated},set:function(t){this._data=t}})),i.algorithm){case"lttb":f=function(t,e,i,s,n){const o=n.samples||s;if(o>=i)return t.slice(e,e+i);const a=[],r=(i-2)/(o-2);let l=0;const h=e+i-1;let c,d,u,f,g,p=e;for(a[l++]=t[p],c=0;cu&&(u=f,d=t[s],g=s);a[l++]=d,p=g}return a[l++]=t[h],a}(h,d,u,n,i);break;case"min-max":f=function(t,e,i,n){let o,a,r,l,h,c,d,u,f,g,p=0,m=0;const b=[],x=e+i-1,_=t[e].x,y=t[x].x-_;for(o=e;og&&(g=l,d=o),p=(m*p+a.x)/++m;else{const i=o-1;if(!s(c)&&!s(d)){const e=Math.min(c,d),s=Math.max(c,d);e!==u&&e!==i&&b.push({...t[e],x:p}),s!==u&&s!==i&&b.push({...t[s],x:p})}o>0&&i!==u&&b.push(t[i]),b.push(a),h=e,m=0,f=g=l,c=d=u=o}}return b}(h,d,u,n);break;default:throw new Error(`Unsupported decimation algorithm '${i.algorithm}'`)}e._decimated=f}))},destroy(t){Jo(t)}};function ta(t,e,i,s){if(s)return;let n=e[t],o=i[t];return"angle"===t&&(n=G(n),o=G(o)),{property:t,start:n,end:o}}function ea(t,e,i){for(;e>t;e--){const t=i[e];if(!isNaN(t.x)&&!isNaN(t.y))break}return e}function ia(t,e,i,s){return t&&e?s(t[i],e[i]):t?t[i]:e?e[i]:0}function sa(t,e){let i=[],s=!1;return n(t)?(s=!0,i=t):i=function(t,e){const{x:i=null,y:s=null}=t||{},n=e.points,o=[];return e.segments.forEach((({start:t,end:e})=>{e=ea(t,e,n);const a=n[t],r=n[e];null!==s?(o.push({x:a.x,y:s}),o.push({x:r.x,y:s})):null!==i&&(o.push({x:i,y:a.y}),o.push({x:i,y:r.y}))})),o}(t,e),i.length?new no({points:i,options:{tension:0},_loop:s,_fullLoop:s}):null}function na(t){return t&&!1!==t.fill}function oa(t,e,i){let s=t[e].fill;const n=[e];let o;if(!i)return s;for(;!1!==s&&-1===n.indexOf(s);){if(!a(s))return s;if(o=t[s],!o)return!1;if(o.visible)return s;n.push(s),s=o.fill}return!1}function aa(t,e,i){const s=function(t){const e=t.options,i=e.fill;let s=l(i&&i.target,i);void 0===s&&(s=!!e.backgroundColor);if(!1===s||null===s)return!1;if(!0===s)return"origin";return s}(t);if(o(s))return!isNaN(s.value)&&s;let n=parseFloat(s);return a(n)&&Math.floor(n)===n?function(t,e,i,s){"-"!==t&&"+"!==t||(i=e+i);if(i===e||i<0||i>=s)return!1;return i}(s[0],e,n,i):["origin","start","end","stack","shape"].indexOf(s)>=0&&s}function ra(t,e,i){const s=[];for(let n=0;n=0;--e){const i=n[e].$filler;i&&(i.line.updateControlPoints(o,i.axis),s&&i.fill&&da(t.ctx,i,o))}},beforeDatasetsDraw(t,e,i){if("beforeDatasetsDraw"!==i.drawTime)return;const s=t.getSortedVisibleDatasetMetas();for(let e=s.length-1;e>=0;--e){const i=s[e].$filler;na(i)&&da(t.ctx,i,t.chartArea)}},beforeDatasetDraw(t,e,i){const s=e.meta.$filler;na(s)&&"beforeDatasetDraw"===i.drawTime&&da(t.ctx,s,t.chartArea)},defaults:{propagate:!0,drawTime:"beforeDatasetDraw"}};const ba=(t,e)=>{let{boxHeight:i=e,boxWidth:s=e}=t;return t.usePointStyle&&(i=Math.min(i,e),s=t.pointStyleWidth||Math.min(s,e)),{boxWidth:s,boxHeight:i,itemHeight:Math.max(e,i)}};class xa extends Hs{constructor(t){super(),this._added=!1,this.legendHitBoxes=[],this._hoveredItem=null,this.doughnutMode=!1,this.chart=t.chart,this.options=t.options,this.ctx=t.ctx,this.legendItems=void 0,this.columnSizes=void 0,this.lineWidths=void 0,this.maxHeight=void 0,this.maxWidth=void 0,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.height=void 0,this.width=void 0,this._margins=void 0,this.position=void 0,this.weight=void 0,this.fullSize=void 0}update(t,e,i){this.maxWidth=t,this.maxHeight=e,this._margins=i,this.setDimensions(),this.buildLabels(),this.fit()}setDimensions(){this.isHorizontal()?(this.width=this.maxWidth,this.left=this._margins.left,this.right=this.width):(this.height=this.maxHeight,this.top=this._margins.top,this.bottom=this.height)}buildLabels(){const t=this.options.labels||{};let e=d(t.generateLabels,[this.chart],this)||[];t.filter&&(e=e.filter((e=>t.filter(e,this.chart.data)))),t.sort&&(e=e.sort(((e,i)=>t.sort(e,i,this.chart.data)))),this.options.reverse&&e.reverse(),this.legendItems=e}fit(){const{options:t,ctx:e}=this;if(!t.display)return void(this.width=this.height=0);const i=t.labels,s=Si(i.font),n=s.size,o=this._computeTitleHeight(),{boxWidth:a,itemHeight:r}=ba(i,n);let l,h;e.font=s.string,this.isHorizontal()?(l=this.maxWidth,h=this._fitRows(o,n,a,r)+10):(h=this.maxHeight,l=this._fitCols(o,s,a,r)+10),this.width=Math.min(l,t.maxWidth||this.maxWidth),this.height=Math.min(h,t.maxHeight||this.maxHeight)}_fitRows(t,e,i,s){const{ctx:n,maxWidth:o,options:{labels:{padding:a}}}=this,r=this.legendHitBoxes=[],l=this.lineWidths=[0],h=s+a;let c=t;n.textAlign="left",n.textBaseline="middle";let d=-1,u=-h;return this.legendItems.forEach(((t,f)=>{const g=i+e/2+n.measureText(t.text).width;(0===f||l[l.length-1]+g+2*a>o)&&(c+=h,l[l.length-(f>0?0:1)]=0,u+=h,d++),r[f]={left:0,top:u,row:d,width:g,height:s},l[l.length-1]+=g+a})),c}_fitCols(t,e,i,s){const{ctx:n,maxHeight:o,options:{labels:{padding:a}}}=this,r=this.legendHitBoxes=[],l=this.columnSizes=[],h=o-t;let c=a,d=0,u=0,f=0,g=0;return this.legendItems.forEach(((t,o)=>{const{itemWidth:p,itemHeight:m}=function(t,e,i,s,n){const o=function(t,e,i,s){let n=t.text;n&&"string"!=typeof n&&(n=n.reduce(((t,e)=>t.length>e.length?t:e)));return e+i.size/2+s.measureText(n).width}(s,t,e,i),a=function(t,e,i){let s=t;"string"!=typeof e.text&&(s=_a(e,i));return s}(n,s,e.lineHeight);return{itemWidth:o,itemHeight:a}}(i,e,n,t,s);o>0&&u+m+2*a>h&&(c+=d+a,l.push({width:d,height:u}),f+=d+a,g++,d=u=0),r[o]={left:f,top:u,col:g,width:p,height:m},d=Math.max(d,p),u+=m+a})),c+=d,l.push({width:d,height:u}),c}adjustHitBoxes(){if(!this.options.display)return;const t=this._computeTitleHeight(),{legendHitBoxes:e,options:{align:i,labels:{padding:s},rtl:n}}=this,o=Oi(n,this.left,this.width);if(this.isHorizontal()){let n=0,a=ft(i,this.left+s,this.right-this.lineWidths[n]);for(const r of e)n!==r.row&&(n=r.row,a=ft(i,this.left+s,this.right-this.lineWidths[n])),r.top+=this.top+t+s,r.left=o.leftForLtr(o.x(a),r.width),a+=r.width+s}else{let n=0,a=ft(i,this.top+t+s,this.bottom-this.columnSizes[n].height);for(const r of e)r.col!==n&&(n=r.col,a=ft(i,this.top+t+s,this.bottom-this.columnSizes[n].height)),r.top=a,r.left+=this.left+s,r.left=o.leftForLtr(o.x(r.left),r.width),a+=r.height+s}}isHorizontal(){return"top"===this.options.position||"bottom"===this.options.position}draw(){if(this.options.display){const t=this.ctx;Ie(t,this),this._draw(),ze(t)}}_draw(){const{options:t,columnSizes:e,lineWidths:i,ctx:s}=this,{align:n,labels:o}=t,a=ue.color,r=Oi(t.rtl,this.left,this.width),h=Si(o.font),{padding:c}=o,d=h.size,u=d/2;let f;this.drawTitle(),s.textAlign=r.textAlign("left"),s.textBaseline="middle",s.lineWidth=.5,s.font=h.string;const{boxWidth:g,boxHeight:p,itemHeight:m}=ba(o,d),b=this.isHorizontal(),x=this._computeTitleHeight();f=b?{x:ft(n,this.left+c,this.right-i[0]),y:this.top+c+x,line:0}:{x:this.left+c,y:ft(n,this.top+x+c,this.bottom-e[0].height),line:0},Ai(this.ctx,t.textDirection);const _=m+c;this.legendItems.forEach(((y,v)=>{s.strokeStyle=y.fontColor,s.fillStyle=y.fontColor;const M=s.measureText(y.text).width,w=r.textAlign(y.textAlign||(y.textAlign=o.textAlign)),k=g+u+M;let S=f.x,P=f.y;r.setWidth(this.width),b?v>0&&S+k+c>this.right&&(P=f.y+=_,f.line++,S=f.x=ft(n,this.left+c,this.right-i[f.line])):v>0&&P+_>this.bottom&&(S=f.x=S+e[f.line].width+c,f.line++,P=f.y=ft(n,this.top+x+c,this.bottom-e[f.line].height));if(function(t,e,i){if(isNaN(g)||g<=0||isNaN(p)||p<0)return;s.save();const n=l(i.lineWidth,1);if(s.fillStyle=l(i.fillStyle,a),s.lineCap=l(i.lineCap,"butt"),s.lineDashOffset=l(i.lineDashOffset,0),s.lineJoin=l(i.lineJoin,"miter"),s.lineWidth=n,s.strokeStyle=l(i.strokeStyle,a),s.setLineDash(l(i.lineDash,[])),o.usePointStyle){const a={radius:p*Math.SQRT2/2,pointStyle:i.pointStyle,rotation:i.rotation,borderWidth:n},l=r.xPlus(t,g/2);Ee(s,a,l,e+u,o.pointStyleWidth&&g)}else{const o=e+Math.max((d-p)/2,0),a=r.leftForLtr(t,g),l=wi(i.borderRadius);s.beginPath(),Object.values(l).some((t=>0!==t))?He(s,{x:a,y:o,w:g,h:p,radius:l}):s.rect(a,o,g,p),s.fill(),0!==n&&s.stroke()}s.restore()}(r.x(S),P,y),S=gt(w,S+g+u,b?S+k:this.right,t.rtl),function(t,e,i){Ne(s,i.text,t,e+m/2,h,{strikethrough:i.hidden,textAlign:r.textAlign(i.textAlign)})}(r.x(S),P,y),b)f.x+=k+c;else if("string"!=typeof y.text){const t=h.lineHeight;f.y+=_a(y,t)+c}else f.y+=_})),Ti(this.ctx,t.textDirection)}drawTitle(){const t=this.options,e=t.title,i=Si(e.font),s=ki(e.padding);if(!e.display)return;const n=Oi(t.rtl,this.left,this.width),o=this.ctx,a=e.position,r=i.size/2,l=s.top+r;let h,c=this.left,d=this.width;if(this.isHorizontal())d=Math.max(...this.lineWidths),h=this.top+l,c=ft(t.align,c,this.right-d);else{const e=this.columnSizes.reduce(((t,e)=>Math.max(t,e.height)),0);h=l+ft(t.align,this.top,this.bottom-e-t.labels.padding-this._computeTitleHeight())}const u=ft(a,c,c+d);o.textAlign=n.textAlign(ut(a)),o.textBaseline="middle",o.strokeStyle=e.color,o.fillStyle=e.color,o.font=i.string,Ne(o,e.text,u,h,i)}_computeTitleHeight(){const t=this.options.title,e=Si(t.font),i=ki(t.padding);return t.display?e.lineHeight+i.height:0}_getLegendItemAt(t,e){let i,s,n;if(tt(t,this.left,this.right)&&tt(e,this.top,this.bottom))for(n=this.legendHitBoxes,i=0;it.chart.options.color,boxWidth:40,padding:10,generateLabels(t){const e=t.data.datasets,{labels:{usePointStyle:i,pointStyle:s,textAlign:n,color:o,useBorderRadius:a,borderRadius:r}}=t.legend.options;return t._getSortedDatasetMetas().map((t=>{const l=t.controller.getStyle(i?0:void 0),h=ki(l.borderWidth);return{text:e[t.index].label,fillStyle:l.backgroundColor,fontColor:o,hidden:!t.visible,lineCap:l.borderCapStyle,lineDash:l.borderDash,lineDashOffset:l.borderDashOffset,lineJoin:l.borderJoinStyle,lineWidth:(h.width+h.height)/4,strokeStyle:l.borderColor,pointStyle:s||l.pointStyle,rotation:l.rotation,textAlign:n||l.textAlign,borderRadius:a&&(r||l.borderRadius),datasetIndex:t.index}}),this)}},title:{color:t=>t.chart.options.color,display:!1,position:"center",text:""}},descriptors:{_scriptable:t=>!t.startsWith("on"),labels:{_scriptable:t=>!["generateLabels","filter","sort"].includes(t)}}};class va extends Hs{constructor(t){super(),this.chart=t.chart,this.options=t.options,this.ctx=t.ctx,this._padding=void 0,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.width=void 0,this.height=void 0,this.position=void 0,this.weight=void 0,this.fullSize=void 0}update(t,e){const i=this.options;if(this.left=0,this.top=0,!i.display)return void(this.width=this.height=this.right=this.bottom=0);this.width=this.right=t,this.height=this.bottom=e;const s=n(i.text)?i.text.length:1;this._padding=ki(i.padding);const o=s*Si(i.font).lineHeight+this._padding.height;this.isHorizontal()?this.height=o:this.width=o}isHorizontal(){const t=this.options.position;return"top"===t||"bottom"===t}_drawArgs(t){const{top:e,left:i,bottom:s,right:n,options:o}=this,a=o.align;let r,l,h,c=0;return this.isHorizontal()?(l=ft(a,i,n),h=e+t,r=n-i):("left"===o.position?(l=i+t,h=ft(a,s,e),c=-.5*C):(l=n-t,h=ft(a,e,s),c=.5*C),r=s-e),{titleX:l,titleY:h,maxWidth:r,rotation:c}}draw(){const t=this.ctx,e=this.options;if(!e.display)return;const i=Si(e.font),s=i.lineHeight/2+this._padding.top,{titleX:n,titleY:o,maxWidth:a,rotation:r}=this._drawArgs(s);Ne(t,e.text,0,0,i,{color:e.color,maxWidth:a,rotation:r,textAlign:ut(e.align),textBaseline:"middle",translation:[n,o]})}}var Ma={id:"title",_element:va,start(t,e,i){!function(t,e){const i=new va({ctx:t.ctx,options:e,chart:t});as.configure(t,i,e),as.addBox(t,i),t.titleBlock=i}(t,i)},stop(t){const e=t.titleBlock;as.removeBox(t,e),delete t.titleBlock},beforeUpdate(t,e,i){const s=t.titleBlock;as.configure(t,s,i),s.options=i},defaults:{align:"center",display:!1,font:{weight:"bold"},fullSize:!0,padding:10,position:"top",text:"",weight:2e3},defaultRoutes:{color:"color"},descriptors:{_scriptable:!0,_indexable:!1}};const wa=new WeakMap;var ka={id:"subtitle",start(t,e,i){const s=new va({ctx:t.ctx,options:i,chart:t});as.configure(t,s,i),as.addBox(t,s),wa.set(t,s)},stop(t){as.removeBox(t,wa.get(t)),wa.delete(t)},beforeUpdate(t,e,i){const s=wa.get(t);as.configure(t,s,i),s.options=i},defaults:{align:"center",display:!1,font:{weight:"normal"},fullSize:!0,padding:0,position:"top",text:"",weight:1500},defaultRoutes:{color:"color"},descriptors:{_scriptable:!0,_indexable:!1}};const Sa={average(t){if(!t.length)return!1;let e,i,s=new Set,n=0,o=0;for(e=0,i=t.length;et+e))/s.size,y:n/o}},nearest(t,e){if(!t.length)return!1;let i,s,n,o=e.x,a=e.y,r=Number.POSITIVE_INFINITY;for(i=0,s=t.length;i-1?t.split("\n"):t}function Ca(t,e){const{element:i,datasetIndex:s,index:n}=e,o=t.getDatasetMeta(s).controller,{label:a,value:r}=o.getLabelAndValue(n);return{chart:t,label:a,parsed:o.getParsed(n),raw:t.data.datasets[s].data[n],formattedValue:r,dataset:o.getDataset(),dataIndex:n,datasetIndex:s,element:i}}function Oa(t,e){const i=t.chart.ctx,{body:s,footer:n,title:o}=t,{boxWidth:a,boxHeight:r}=e,l=Si(e.bodyFont),h=Si(e.titleFont),c=Si(e.footerFont),d=o.length,f=n.length,g=s.length,p=ki(e.padding);let m=p.height,b=0,x=s.reduce(((t,e)=>t+e.before.length+e.lines.length+e.after.length),0);if(x+=t.beforeBody.length+t.afterBody.length,d&&(m+=d*h.lineHeight+(d-1)*e.titleSpacing+e.titleMarginBottom),x){m+=g*(e.displayColors?Math.max(r,l.lineHeight):l.lineHeight)+(x-g)*l.lineHeight+(x-1)*e.bodySpacing}f&&(m+=e.footerMarginTop+f*c.lineHeight+(f-1)*e.footerSpacing);let _=0;const y=function(t){b=Math.max(b,i.measureText(t).width+_)};return i.save(),i.font=h.string,u(t.title,y),i.font=l.string,u(t.beforeBody.concat(t.afterBody),y),_=e.displayColors?a+2+e.boxPadding:0,u(s,(t=>{u(t.before,y),u(t.lines,y),u(t.after,y)})),_=0,i.font=c.string,u(t.footer,y),i.restore(),b+=p.width,{width:b,height:m}}function Aa(t,e,i,s){const{x:n,width:o}=i,{width:a,chartArea:{left:r,right:l}}=t;let h="center";return"center"===s?h=n<=(r+l)/2?"left":"right":n<=o/2?h="left":n>=a-o/2&&(h="right"),function(t,e,i,s){const{x:n,width:o}=s,a=i.caretSize+i.caretPadding;return"left"===t&&n+o+a>e.width||"right"===t&&n-o-a<0||void 0}(h,t,e,i)&&(h="center"),h}function Ta(t,e,i){const s=i.yAlign||e.yAlign||function(t,e){const{y:i,height:s}=e;return it.height-s/2?"bottom":"center"}(t,i);return{xAlign:i.xAlign||e.xAlign||Aa(t,e,i,s),yAlign:s}}function La(t,e,i,s){const{caretSize:n,caretPadding:o,cornerRadius:a}=t,{xAlign:r,yAlign:l}=i,h=n+o,{topLeft:c,topRight:d,bottomLeft:u,bottomRight:f}=wi(a);let g=function(t,e){let{x:i,width:s}=t;return"right"===e?i-=s:"center"===e&&(i-=s/2),i}(e,r);const p=function(t,e,i){let{y:s,height:n}=t;return"top"===e?s+=i:s-="bottom"===e?n+i:n/2,s}(e,l,h);return"center"===l?"left"===r?g+=h:"right"===r&&(g-=h):"left"===r?g-=Math.max(c,u)+n:"right"===r&&(g+=Math.max(d,f)+n),{x:J(g,0,s.width-e.width),y:J(p,0,s.height-e.height)}}function Ea(t,e,i){const s=ki(i.padding);return"center"===e?t.x+t.width/2:"right"===e?t.x+t.width-s.right:t.x+s.left}function Ra(t){return Pa([],Da(t))}function Ia(t,e){const i=e&&e.dataset&&e.dataset.tooltip&&e.dataset.tooltip.callbacks;return i?t.override(i):t}const za={beforeTitle:e,title(t){if(t.length>0){const e=t[0],i=e.chart.data.labels,s=i?i.length:0;if(this&&this.options&&"dataset"===this.options.mode)return e.dataset.label||"";if(e.label)return e.label;if(s>0&&e.dataIndex{const e={before:[],lines:[],after:[]},n=Ia(i,t);Pa(e.before,Da(Fa(n,"beforeLabel",this,t))),Pa(e.lines,Fa(n,"label",this,t)),Pa(e.after,Da(Fa(n,"afterLabel",this,t))),s.push(e)})),s}getAfterBody(t,e){return Ra(Fa(e.callbacks,"afterBody",this,t))}getFooter(t,e){const{callbacks:i}=e,s=Fa(i,"beforeFooter",this,t),n=Fa(i,"footer",this,t),o=Fa(i,"afterFooter",this,t);let a=[];return a=Pa(a,Da(s)),a=Pa(a,Da(n)),a=Pa(a,Da(o)),a}_createItems(t){const e=this._active,i=this.chart.data,s=[],n=[],o=[];let a,r,l=[];for(a=0,r=e.length;at.filter(e,s,n,i)))),t.itemSort&&(l=l.sort(((e,s)=>t.itemSort(e,s,i)))),u(l,(e=>{const i=Ia(t.callbacks,e);s.push(Fa(i,"labelColor",this,e)),n.push(Fa(i,"labelPointStyle",this,e)),o.push(Fa(i,"labelTextColor",this,e))})),this.labelColors=s,this.labelPointStyles=n,this.labelTextColors=o,this.dataPoints=l,l}update(t,e){const i=this.options.setContext(this.getContext()),s=this._active;let n,o=[];if(s.length){const t=Sa[i.position].call(this,s,this._eventPosition);o=this._createItems(i),this.title=this.getTitle(o,i),this.beforeBody=this.getBeforeBody(o,i),this.body=this.getBody(o,i),this.afterBody=this.getAfterBody(o,i),this.footer=this.getFooter(o,i);const e=this._size=Oa(this,i),a=Object.assign({},t,e),r=Ta(this.chart,i,a),l=La(i,a,r,this.chart);this.xAlign=r.xAlign,this.yAlign=r.yAlign,n={opacity:1,x:l.x,y:l.y,width:e.width,height:e.height,caretX:t.x,caretY:t.y}}else 0!==this.opacity&&(n={opacity:0});this._tooltipItems=o,this.$context=void 0,n&&this._resolveAnimations().update(this,n),t&&i.external&&i.external.call(this,{chart:this.chart,tooltip:this,replay:e})}drawCaret(t,e,i,s){const n=this.getCaretPosition(t,i,s);e.lineTo(n.x1,n.y1),e.lineTo(n.x2,n.y2),e.lineTo(n.x3,n.y3)}getCaretPosition(t,e,i){const{xAlign:s,yAlign:n}=this,{caretSize:o,cornerRadius:a}=i,{topLeft:r,topRight:l,bottomLeft:h,bottomRight:c}=wi(a),{x:d,y:u}=t,{width:f,height:g}=e;let p,m,b,x,_,y;return"center"===n?(_=u+g/2,"left"===s?(p=d,m=p-o,x=_+o,y=_-o):(p=d+f,m=p+o,x=_-o,y=_+o),b=p):(m="left"===s?d+Math.max(r,h)+o:"right"===s?d+f-Math.max(l,c)-o:this.caretX,"top"===n?(x=u,_=x-o,p=m-o,b=m+o):(x=u+g,_=x+o,p=m+o,b=m-o),y=x),{x1:p,x2:m,x3:b,y1:x,y2:_,y3:y}}drawTitle(t,e,i){const s=this.title,n=s.length;let o,a,r;if(n){const l=Oi(i.rtl,this.x,this.width);for(t.x=Ea(this,i.titleAlign,i),e.textAlign=l.textAlign(i.titleAlign),e.textBaseline="middle",o=Si(i.titleFont),a=i.titleSpacing,e.fillStyle=i.titleColor,e.font=o.string,r=0;r0!==t))?(t.beginPath(),t.fillStyle=n.multiKeyBackground,He(t,{x:e,y:g,w:h,h:l,radius:r}),t.fill(),t.stroke(),t.fillStyle=a.backgroundColor,t.beginPath(),He(t,{x:i,y:g+1,w:h-2,h:l-2,radius:r}),t.fill()):(t.fillStyle=n.multiKeyBackground,t.fillRect(e,g,h,l),t.strokeRect(e,g,h,l),t.fillStyle=a.backgroundColor,t.fillRect(i,g+1,h-2,l-2))}t.fillStyle=this.labelTextColors[i]}drawBody(t,e,i){const{body:s}=this,{bodySpacing:n,bodyAlign:o,displayColors:a,boxHeight:r,boxWidth:l,boxPadding:h}=i,c=Si(i.bodyFont);let d=c.lineHeight,f=0;const g=Oi(i.rtl,this.x,this.width),p=function(i){e.fillText(i,g.x(t.x+f),t.y+d/2),t.y+=d+n},m=g.textAlign(o);let b,x,_,y,v,M,w;for(e.textAlign=o,e.textBaseline="middle",e.font=c.string,t.x=Ea(this,m,i),e.fillStyle=i.bodyColor,u(this.beforeBody,p),f=a&&"right"!==m?"center"===o?l/2+h:l+2+h:0,y=0,M=s.length;y0&&e.stroke()}_updateAnimationTarget(t){const e=this.chart,i=this.$animations,s=i&&i.x,n=i&&i.y;if(s||n){const i=Sa[t.position].call(this,this._active,this._eventPosition);if(!i)return;const o=this._size=Oa(this,t),a=Object.assign({},i,this._size),r=Ta(e,t,a),l=La(t,a,r,e);s._to===l.x&&n._to===l.y||(this.xAlign=r.xAlign,this.yAlign=r.yAlign,this.width=o.width,this.height=o.height,this.caretX=i.x,this.caretY=i.y,this._resolveAnimations().update(this,l))}}_willRender(){return!!this.opacity}draw(t){const e=this.options.setContext(this.getContext());let i=this.opacity;if(!i)return;this._updateAnimationTarget(e);const s={width:this.width,height:this.height},n={x:this.x,y:this.y};i=Math.abs(i)<.001?0:i;const o=ki(e.padding),a=this.title.length||this.beforeBody.length||this.body.length||this.afterBody.length||this.footer.length;e.enabled&&a&&(t.save(),t.globalAlpha=i,this.drawBackground(n,t,s,e),Ai(t,e.textDirection),n.y+=o.top,this.drawTitle(n,t,e),this.drawBody(n,t,e),this.drawFooter(n,t,e),Ti(t,e.textDirection),t.restore())}getActiveElements(){return this._active||[]}setActiveElements(t,e){const i=this._active,s=t.map((({datasetIndex:t,index:e})=>{const i=this.chart.getDatasetMeta(t);if(!i)throw new Error("Cannot find a dataset at index "+t);return{datasetIndex:t,element:i.data[e],index:e}})),n=!f(i,s),o=this._positionChanged(s,e);(n||o)&&(this._active=s,this._eventPosition=e,this._ignoreReplayEvents=!0,this.update(!0))}handleEvent(t,e,i=!0){if(e&&this._ignoreReplayEvents)return!1;this._ignoreReplayEvents=!1;const s=this.options,n=this._active||[],o=this._getActiveElements(t,n,e,i),a=this._positionChanged(o,t),r=e||!f(o,n)||a;return r&&(this._active=o,(s.enabled||s.external)&&(this._eventPosition={x:t.x,y:t.y},this.update(!0,e))),r}_getActiveElements(t,e,i,s){const n=this.options;if("mouseout"===t.type)return[];if(!s)return e.filter((t=>this.chart.data.datasets[t.datasetIndex]&&void 0!==this.chart.getDatasetMeta(t.datasetIndex).controller.getParsed(t.index)));const o=this.chart.getElementsAtEventForMode(t,n.mode,n,i);return n.reverse&&o.reverse(),o}_positionChanged(t,e){const{caretX:i,caretY:s,options:n}=this,o=Sa[n.position].call(this,t,e);return!1!==o&&(i!==o.x||s!==o.y)}}var Ba={id:"tooltip",_element:Va,positioners:Sa,afterInit(t,e,i){i&&(t.tooltip=new Va({chart:t,options:i}))},beforeUpdate(t,e,i){t.tooltip&&t.tooltip.initialize(i)},reset(t,e,i){t.tooltip&&t.tooltip.initialize(i)},afterDraw(t){const e=t.tooltip;if(e&&e._willRender()){const i={tooltip:e};if(!1===t.notifyPlugins("beforeTooltipDraw",{...i,cancelable:!0}))return;e.draw(t.ctx),t.notifyPlugins("afterTooltipDraw",i)}},afterEvent(t,e){if(t.tooltip){const i=e.replay;t.tooltip.handleEvent(e.event,i,e.inChartArea)&&(e.changed=!0)}},defaults:{enabled:!0,external:null,position:"average",backgroundColor:"rgba(0,0,0,0.8)",titleColor:"#fff",titleFont:{weight:"bold"},titleSpacing:2,titleMarginBottom:6,titleAlign:"left",bodyColor:"#fff",bodySpacing:2,bodyFont:{},bodyAlign:"left",footerColor:"#fff",footerSpacing:2,footerMarginTop:6,footerFont:{weight:"bold"},footerAlign:"left",padding:6,caretPadding:2,caretSize:5,cornerRadius:6,boxHeight:(t,e)=>e.bodyFont.size,boxWidth:(t,e)=>e.bodyFont.size,multiKeyBackground:"#fff",displayColors:!0,boxPadding:0,borderColor:"rgba(0,0,0,0)",borderWidth:0,animation:{duration:400,easing:"easeOutQuart"},animations:{numbers:{type:"number",properties:["x","y","width","height","caretX","caretY"]},opacity:{easing:"linear",duration:200}},callbacks:za},defaultRoutes:{bodyFont:"font",footerFont:"font",titleFont:"font"},descriptors:{_scriptable:t=>"filter"!==t&&"itemSort"!==t&&"external"!==t,_indexable:!1,callbacks:{_scriptable:!1,_indexable:!1},animation:{_fallback:!1},animations:{_fallback:"animation"}},additionalOptionScopes:["interaction"]};return An.register(Yn,jo,fo,t),An.helpers={...Wi},An._adapters=Rn,An.Animation=Cs,An.Animations=Os,An.animator=xt,An.controllers=en.controllers.items,An.DatasetController=Ns,An.Element=Hs,An.elements=fo,An.Interaction=Xi,An.layouts=as,An.platforms=Ss,An.Scale=Js,An.Ticks=ae,Object.assign(An,Yn,jo,fo,t,Ss),An.Chart=An,"undefined"!=typeof window&&(window.Chart=An),An})); +//# sourceMappingURL=chart.umd.js.map diff --git a/frontend/vendor/dataTables.bootstrap5.min.css b/frontend/vendor/dataTables.bootstrap5.min.css new file mode 100644 index 0000000..81bd749 --- /dev/null +++ b/frontend/vendor/dataTables.bootstrap5.min.css @@ -0,0 +1,7 @@ +/*! DataTables Bootstrap 5 integration + * © SpryMedia Ltd - datatables.net/license + */:root{--dt_background-selected: 13, 110, 253;--dt_color-selected: 255, 255, 255;--dt_link_color-selected: 228, 228, 228;--dt-row_background: transparent;--dt-row_background-selected: var(--dt_background-selected);--dt-row-text_color-selected: var(--dt_color-selected);--dt-row-link_color-selected: var(--dt_link_color-selected);--dt-row_background-stripe: 0, 0, 0;--dt-row_background-hover: 0, 0, 0;--dt-column-ordering_background: 0, 0, 0;--dt-header-cell_align-items: center;--dt-header-cell_vertical-align: middle;--dt-html_background: white}:root.dark{--dt-html_background: rgb(33, 37, 41)}table.dataTable tbody td.dt-control{text-align:center;cursor:pointer}table.dataTable tbody td.dt-control:before{display:inline-block;box-sizing:border-box;content:"";border-top:5px solid transparent;border-left:10px solid rgba(0, 0, 0, 0.5);border-bottom:5px solid transparent;border-right:0px solid transparent}table.dataTable tbody tr.dt-hasChild td.dt-control:before{border-top:10px solid rgba(0, 0, 0, 0.5);border-left:5px solid transparent;border-bottom:0px solid transparent;border-right:5px solid transparent}:root.dark table.dataTable td.dt-control:before,:root[data-bs-theme=dark] table.dataTable td.dt-control:before,:root[data-theme=dark] table.dataTable td.dt-control:before{border-left-color:rgba(255, 255, 255, 0.5)}:root.dark table.dataTable tr.dt-hasChild td.dt-control:before,:root[data-bs-theme=dark] table.dataTable tr.dt-hasChild td.dt-control:before,:root[data-theme=dark] table.dataTable tr.dt-hasChild td.dt-control:before{border-top-color:rgba(255, 255, 255, 0.5);border-left-color:transparent}div.dt-scroll{width:100%}div.dt-scroll-body thead tr,div.dt-scroll-body tfoot tr{height:0}div.dt-scroll-body thead tr th,div.dt-scroll-body thead tr td,div.dt-scroll-body tfoot tr th,div.dt-scroll-body tfoot tr td{height:0 !important;padding-top:0px !important;padding-bottom:0px !important;border-top-width:0px !important;border-bottom-width:0px !important}div.dt-scroll-body thead tr th div.dt-scroll-sizing,div.dt-scroll-body thead tr td div.dt-scroll-sizing,div.dt-scroll-body tfoot tr th div.dt-scroll-sizing,div.dt-scroll-body tfoot tr td div.dt-scroll-sizing{height:0 !important;overflow:hidden !important}/*! DataTables Bootstrap 5 integration + * © SpryMedia Ltd - datatables.net/license + */:root{--dt-order-arrow_color: rgb(51, 51, 51);--dt-order-arrow_color-current: rgb(51, 51, 51);--dt-order-arrow-height: 7px;--dt-order-arrow_opacity: 0.125;--dt-order-arrow_opacity-current: 0.65;--dt-order-arrow-width: 8px;--dt-order-arrow-gap: 1px;--dt-order-header_outline-hover: 2px solid rgba(0, 0, 0, 0.05)}:root.dark,:root[data-bs-theme=dark],:root[data-theme=dark]{--dt-order-arrow_color: rgb(229, 233, 238);--dt-order-arrow_color-current: rgb(229, 233, 238);--dt-order-header_outline-hover: 2px solid rgba(255, 255, 255, 0.05)}table.dataTable thead>tr>th:active,table.dataTable thead>tr>td:active{outline:none}table.dataTable thead>tr>th.dt-orderable-asc .dt-column-order:before,table.dataTable thead>tr>th.dt-ordering-asc .dt-column-order:before,table.dataTable thead>tr>td.dt-orderable-asc .dt-column-order:before,table.dataTable thead>tr>td.dt-ordering-asc .dt-column-order:before{bottom:calc(50% + var(--dt-order-arrow-gap));border-bottom:var(--dt-order-arrow-height) solid var(--dt-order-arrow_color);border-left:calc(var(--dt-order-arrow-width)/2) solid transparent;border-right:calc(var(--dt-order-arrow-width)/2) solid transparent}table.dataTable thead>tr>th.dt-orderable-desc .dt-column-order:after,table.dataTable thead>tr>th.dt-ordering-desc .dt-column-order:after,table.dataTable thead>tr>td.dt-orderable-desc .dt-column-order:after,table.dataTable thead>tr>td.dt-ordering-desc .dt-column-order:after{top:calc(50% + 1px);border-top:var(--dt-order-arrow-height) solid var(--dt-order-arrow_color);border-left:calc(var(--dt-order-arrow-width)/2) solid transparent;border-right:calc(var(--dt-order-arrow-width)/2) solid transparent}table.dataTable thead>tr>th.dt-orderable-asc .dt-column-order,table.dataTable thead>tr>th.dt-orderable-desc .dt-column-order,table.dataTable thead>tr>th.dt-ordering-asc .dt-column-order,table.dataTable thead>tr>th.dt-ordering-desc .dt-column-order,table.dataTable thead>tr>td.dt-orderable-asc .dt-column-order,table.dataTable thead>tr>td.dt-orderable-desc .dt-column-order,table.dataTable thead>tr>td.dt-ordering-asc .dt-column-order,table.dataTable thead>tr>td.dt-ordering-desc .dt-column-order{position:relative;width:var(--dt-order-arrow-width);align-self:stretch}table.dataTable thead>tr>th.dt-orderable-asc .dt-column-order:before,table.dataTable thead>tr>th.dt-orderable-asc .dt-column-order:after,table.dataTable thead>tr>th.dt-orderable-desc .dt-column-order:before,table.dataTable thead>tr>th.dt-orderable-desc .dt-column-order:after,table.dataTable thead>tr>th.dt-ordering-asc .dt-column-order:before,table.dataTable thead>tr>th.dt-ordering-asc .dt-column-order:after,table.dataTable thead>tr>th.dt-ordering-desc .dt-column-order:before,table.dataTable thead>tr>th.dt-ordering-desc .dt-column-order:after,table.dataTable thead>tr>td.dt-orderable-asc .dt-column-order:before,table.dataTable thead>tr>td.dt-orderable-asc .dt-column-order:after,table.dataTable thead>tr>td.dt-orderable-desc .dt-column-order:before,table.dataTable thead>tr>td.dt-orderable-desc .dt-column-order:after,table.dataTable thead>tr>td.dt-ordering-asc .dt-column-order:before,table.dataTable thead>tr>td.dt-ordering-asc .dt-column-order:after,table.dataTable thead>tr>td.dt-ordering-desc .dt-column-order:before,table.dataTable thead>tr>td.dt-ordering-desc .dt-column-order:after{position:absolute;display:block;content:" ";height:0;width:0;left:0;color:var(--dt-order-arrow_color);opacity:var(--dt-order-arrow_opacity)}table.dataTable thead>tr>th.dt-orderable-asc,table.dataTable thead>tr>th.dt-orderable-desc,table.dataTable thead>tr>td.dt-orderable-asc,table.dataTable thead>tr>td.dt-orderable-desc{cursor:pointer}table.dataTable thead>tr>th.dt-orderable-asc:hover,table.dataTable thead>tr>th.dt-orderable-desc:hover,table.dataTable thead>tr>td.dt-orderable-asc:hover,table.dataTable thead>tr>td.dt-orderable-desc:hover{outline:var(--dt-order-header_outline-hover);outline-offset:-2px}table.dataTable thead>tr>th.dt-ordering-asc .dt-column-order:before,table.dataTable thead>tr>td.dt-ordering-asc .dt-column-order:before{border-bottom-color:var(--dt-order-arrow_color-current);opacity:var(--dt-order-arrow_opacity-current)}table.dataTable thead>tr>th.dt-ordering-desc .dt-column-order:after,table.dataTable thead>tr>td.dt-ordering-desc .dt-column-order:after{border-top-color:var(--dt-order-arrow_color-current);opacity:var(--dt-order-arrow_opacity-current)}table.dataTable thead>tr>th.dt-orderable-none:not(.dt-ordering-asc,.dt-ordering-desc) .dt-column-order:empty,table.dataTable thead>tr>th.sorting_desc_disabled .dt-column-order:after,table.dataTable thead>tr>th.sorting_asc_disabled .dt-column-order:before,table.dataTable thead>tr>td.dt-orderable-none:not(.dt-ordering-asc,.dt-ordering-desc) .dt-column-order:empty,table.dataTable thead>tr>td.sorting_desc_disabled .dt-column-order:after,table.dataTable thead>tr>td.sorting_asc_disabled .dt-column-order:before{display:none}table.dataTable thead>tr>th:active,table.dataTable thead>tr>td:active{outline:none}table.dataTable thead>tr>th div.dt-column-header,table.dataTable thead>tr>th div.dt-column-footer,table.dataTable thead>tr>td div.dt-column-header,table.dataTable thead>tr>td div.dt-column-footer,table.dataTable tfoot>tr>th div.dt-column-header,table.dataTable tfoot>tr>th div.dt-column-footer,table.dataTable tfoot>tr>td div.dt-column-header,table.dataTable tfoot>tr>td div.dt-column-footer{display:flex;justify-content:space-between;align-items:var(--dt-header-cell_align-items);gap:4px}table.dataTable thead>tr>th div.dt-column-header .dt-column-title,table.dataTable thead>tr>th div.dt-column-footer .dt-column-title,table.dataTable thead>tr>td div.dt-column-header .dt-column-title,table.dataTable thead>tr>td div.dt-column-footer .dt-column-title,table.dataTable tfoot>tr>th div.dt-column-header .dt-column-title,table.dataTable tfoot>tr>th div.dt-column-footer .dt-column-title,table.dataTable tfoot>tr>td div.dt-column-header .dt-column-title,table.dataTable tfoot>tr>td div.dt-column-footer .dt-column-title{flex-grow:1}table.dataTable thead>tr>th div.dt-column-header .dt-column-title:empty,table.dataTable thead>tr>th div.dt-column-footer .dt-column-title:empty,table.dataTable thead>tr>td div.dt-column-header .dt-column-title:empty,table.dataTable thead>tr>td div.dt-column-footer .dt-column-title:empty,table.dataTable tfoot>tr>th div.dt-column-header .dt-column-title:empty,table.dataTable tfoot>tr>th div.dt-column-footer .dt-column-title:empty,table.dataTable tfoot>tr>td div.dt-column-header .dt-column-title:empty,table.dataTable tfoot>tr>td div.dt-column-footer .dt-column-title:empty{display:none}div.dt-scroll-body>table.dataTable>thead>tr>th,div.dt-scroll-body>table.dataTable>thead>tr>td{overflow:hidden}:root.dark table.dataTable thead>tr>th.dt-orderable-asc:hover,:root.dark table.dataTable thead>tr>th.dt-orderable-desc:hover,:root.dark table.dataTable thead>tr>td.dt-orderable-asc:hover,:root.dark table.dataTable thead>tr>td.dt-orderable-desc:hover,:root[data-bs-theme=dark] table.dataTable thead>tr>th.dt-orderable-asc:hover,:root[data-bs-theme=dark] table.dataTable thead>tr>th.dt-orderable-desc:hover,:root[data-bs-theme=dark] table.dataTable thead>tr>td.dt-orderable-asc:hover,:root[data-bs-theme=dark] table.dataTable thead>tr>td.dt-orderable-desc:hover{outline:var(--dt-order-header_outline-hover)}/*! DataTables Bootstrap 5 integration + * © SpryMedia Ltd - datatables.net/license + */:root{--dt-processing-circle_background: var(--dt_background-selected)}div.dt-processing{position:absolute;top:50%;left:50%;width:200px;margin-left:-100px;margin-top:-22px;text-align:center;padding:2px;z-index:10}div.dt-processing>div:last-child{position:relative;width:80px;height:15px;margin:1em auto}div.dt-processing>div:last-child>div{position:absolute;top:0;width:13px;height:13px;border-radius:50%;background:rgb(var(--dt-processing-circle_background));animation-timing-function:cubic-bezier(0, 1, 1, 0)}div.dt-processing>div:last-child>div:nth-child(1){left:8px;animation:datatables-loader-1 .6s infinite}div.dt-processing>div:last-child>div:nth-child(2){left:8px;animation:datatables-loader-2 .6s infinite}div.dt-processing>div:last-child>div:nth-child(3){left:32px;animation:datatables-loader-2 .6s infinite}div.dt-processing>div:last-child>div:nth-child(4){left:56px;animation:datatables-loader-3 .6s infinite}@keyframes datatables-loader-1{0%{transform:scale(0)}100%{transform:scale(1)}}@keyframes datatables-loader-3{0%{transform:scale(1)}100%{transform:scale(0)}}@keyframes datatables-loader-2{0%{transform:translate(0, 0)}100%{transform:translate(24px, 0)}}table.dataTable.nowrap th,table.dataTable.nowrap td{white-space:nowrap}table.dataTable th,table.dataTable td{box-sizing:border-box}table.dataTable th.dt-type-numeric,table.dataTable th.dt-type-date,table.dataTable td.dt-type-numeric,table.dataTable td.dt-type-date{text-align:right}table.dataTable th.dt-type-numeric div.dt-column-header,table.dataTable th.dt-type-numeric div.dt-column-footer,table.dataTable th.dt-type-date div.dt-column-header,table.dataTable th.dt-type-date div.dt-column-footer,table.dataTable td.dt-type-numeric div.dt-column-header,table.dataTable td.dt-type-numeric div.dt-column-footer,table.dataTable td.dt-type-date div.dt-column-header,table.dataTable td.dt-type-date div.dt-column-footer{flex-direction:row-reverse}table.dataTable th.dt-left,table.dataTable td.dt-left{text-align:left}table.dataTable th.dt-left div.dt-column-header,table.dataTable th.dt-left div.dt-column-footer,table.dataTable td.dt-left div.dt-column-header,table.dataTable td.dt-left div.dt-column-footer{flex-direction:row}table.dataTable th.dt-center,table.dataTable td.dt-center{text-align:center}table.dataTable th.dt-right,table.dataTable td.dt-right{text-align:right}table.dataTable th.dt-right div.dt-column-header,table.dataTable th.dt-right div.dt-column-footer,table.dataTable td.dt-right div.dt-column-header,table.dataTable td.dt-right div.dt-column-footer{flex-direction:row-reverse}table.dataTable th.dt-justify,table.dataTable td.dt-justify{text-align:justify}table.dataTable th.dt-justify div.dt-column-header,table.dataTable th.dt-justify div.dt-column-footer,table.dataTable td.dt-justify div.dt-column-header,table.dataTable td.dt-justify div.dt-column-footer{flex-direction:row}table.dataTable th.dt-nowrap,table.dataTable td.dt-nowrap{white-space:nowrap}table.dataTable th.dt-empty,table.dataTable td.dt-empty{text-align:center;vertical-align:top}table.dataTable thead th,table.dataTable thead td,table.dataTable tfoot th,table.dataTable tfoot td{text-align:left;vertical-align:var(--dt-header-cell_vertical-align)}table.dataTable thead th.dt-head-left,table.dataTable thead td.dt-head-left,table.dataTable tfoot th.dt-head-left,table.dataTable tfoot td.dt-head-left{text-align:left}table.dataTable thead th.dt-head-left div.dt-column-header,table.dataTable thead th.dt-head-left div.dt-column-footer,table.dataTable thead td.dt-head-left div.dt-column-header,table.dataTable thead td.dt-head-left div.dt-column-footer,table.dataTable tfoot th.dt-head-left div.dt-column-header,table.dataTable tfoot th.dt-head-left div.dt-column-footer,table.dataTable tfoot td.dt-head-left div.dt-column-header,table.dataTable tfoot td.dt-head-left div.dt-column-footer{flex-direction:row}table.dataTable thead th.dt-head-center,table.dataTable thead td.dt-head-center,table.dataTable tfoot th.dt-head-center,table.dataTable tfoot td.dt-head-center{text-align:center}table.dataTable thead th.dt-head-right,table.dataTable thead td.dt-head-right,table.dataTable tfoot th.dt-head-right,table.dataTable tfoot td.dt-head-right{text-align:right}table.dataTable thead th.dt-head-right div.dt-column-header,table.dataTable thead th.dt-head-right div.dt-column-footer,table.dataTable thead td.dt-head-right div.dt-column-header,table.dataTable thead td.dt-head-right div.dt-column-footer,table.dataTable tfoot th.dt-head-right div.dt-column-header,table.dataTable tfoot th.dt-head-right div.dt-column-footer,table.dataTable tfoot td.dt-head-right div.dt-column-header,table.dataTable tfoot td.dt-head-right div.dt-column-footer{flex-direction:row-reverse}table.dataTable thead th.dt-head-justify,table.dataTable thead td.dt-head-justify,table.dataTable tfoot th.dt-head-justify,table.dataTable tfoot td.dt-head-justify{text-align:justify}table.dataTable thead th.dt-head-justify div.dt-column-header,table.dataTable thead th.dt-head-justify div.dt-column-footer,table.dataTable thead td.dt-head-justify div.dt-column-header,table.dataTable thead td.dt-head-justify div.dt-column-footer,table.dataTable tfoot th.dt-head-justify div.dt-column-header,table.dataTable tfoot th.dt-head-justify div.dt-column-footer,table.dataTable tfoot td.dt-head-justify div.dt-column-header,table.dataTable tfoot td.dt-head-justify div.dt-column-footer{flex-direction:row}table.dataTable thead th.dt-head-nowrap,table.dataTable thead td.dt-head-nowrap,table.dataTable tfoot th.dt-head-nowrap,table.dataTable tfoot td.dt-head-nowrap{white-space:nowrap}table.dataTable tbody th.dt-body-left,table.dataTable tbody td.dt-body-left{text-align:left}table.dataTable tbody th.dt-body-center,table.dataTable tbody td.dt-body-center{text-align:center}table.dataTable tbody th.dt-body-right,table.dataTable tbody td.dt-body-right{text-align:right}table.dataTable tbody th.dt-body-justify,table.dataTable tbody td.dt-body-justify{text-align:justify}table.dataTable tbody th.dt-body-nowrap,table.dataTable tbody td.dt-body-nowrap{white-space:nowrap}:root{--dt_background-selected: 13, 110, 253}:root[data-bs-theme=dark]{--dt-row_background-hover: 255, 255, 255;--dt-row_background-stripe: 255, 255, 255;--dt-column-ordering_background: 255, 255, 255}table.table.dataTable{clear:both;margin-bottom:0;max-width:none;border-spacing:0}table.table.dataTable.table-striped>tbody>tr:nth-of-type(2n+1)>*{box-shadow:none}table.table.dataTable>:not(caption)>*>*{background-color:var(--bs-table-bg)}table.table.dataTable>tbody>tr{background-color:var(--dt-row_background)}table.table.dataTable>tbody>tr.selected>*{box-shadow:inset 0 0 0 9999px rgb(var(--dt-row_background-selected));color:rgb(var(--dt-row-text_color-selected))}table.table.dataTable>tbody>tr.selected a{color:rgb(var(--dt-row-link_color-selected))}table.table.dataTable.table-striped>tbody>tr:nth-of-type(2n+1)>*{box-shadow:inset 0 0 0 9999px rgba(var(--dt-row_background-stripe), 0.05)}table.table.dataTable.table-striped>tbody>tr:nth-of-type(2n+1).selected>*{box-shadow:inset 0 0 0 9999px rgba(var(--dt-row_background-selected), 0.95)}table.table.dataTable.table-hover>tbody>tr:hover>*{box-shadow:inset 0 0 0 9999px rgba(var(--dt-row_background-hover), 0.075)}table.table.dataTable.table-hover>tbody>tr.selected:hover>*{box-shadow:inset 0 0 0 9999px rgba(var(--dt-row_background-selected), 0.975)}div.dt-container div.dt-layout-start>*:not(:last-child){margin-right:1em}div.dt-container div.dt-layout-end>*:not(:first-child){margin-left:1em}div.dt-container div.dt-layout-full{width:100%}div.dt-container div.dt-layout-full>*:only-child{margin-left:auto;margin-right:auto}div.dt-container div.dt-layout-table>div{display:block !important}@media screen and (max-width: 767px){div.dt-container div.dt-layout-start>*:not(:last-child){margin-right:0}div.dt-container div.dt-layout-end>*:not(:first-child){margin-left:0}}div.dt-container{position:relative}div.dt-container div.dt-length label{font-weight:normal;text-align:left;white-space:nowrap}div.dt-container div.dt-length select{width:auto;display:inline-block;margin-right:.5em}div.dt-container div.dt-search{text-align:right}div.dt-container div.dt-search label{font-weight:normal;white-space:nowrap;text-align:left}div.dt-container div.dt-search input{margin-left:.5em;display:inline-block;width:auto}div.dt-container div.dt-paging{margin:0}div.dt-container div.dt-paging ul.pagination{margin:2px 0;flex-wrap:wrap}div.dt-container div.dt-row{position:relative}div.dt-scroll-head table.dataTable{margin-bottom:0 !important}div.dt-scroll-body{border-bottom-color:var(--bs-border-color);border-bottom-width:var(--bs-border-width);border-bottom-style:solid}div.dt-scroll-body>table{border-top:none;margin-top:0 !important;margin-bottom:0 !important}div.dt-scroll-body>table>tbody>tr:first-child{border-top-width:0}div.dt-scroll-body>table>thead>tr{border-width:0 !important}div.dt-scroll-body>table>tbody>tr:last-child>*{border-bottom:none}div.dt-scroll-foot>.dt-scroll-footInner{box-sizing:content-box}div.dt-scroll-foot>.dt-scroll-footInner>table{margin-top:0 !important;border-top:none}div.dt-scroll-foot>.dt-scroll-footInner>table>tfoot>tr:first-child{border-top-width:0 !important}@media screen and (max-width: 767px){div.dt-container div.dt-length,div.dt-container div.dt-search,div.dt-container div.dt-info,div.dt-container div.dt-paging{text-align:center}div.dt-container .row{--bs-gutter-y: 0.5rem}div.dt-container div.dt-paging ul.pagination{justify-content:center !important}}table.dataTable.table-sm>thead>tr th.dt-orderable-asc,table.dataTable.table-sm>thead>tr th.dt-orderable-desc,table.dataTable.table-sm>thead>tr th.dt-ordering-asc,table.dataTable.table-sm>thead>tr th.dt-ordering-desc,table.dataTable.table-sm>thead>tr td.dt-orderable-asc,table.dataTable.table-sm>thead>tr td.dt-orderable-desc,table.dataTable.table-sm>thead>tr td.dt-ordering-asc,table.dataTable.table-sm>thead>tr td.dt-ordering-desc{padding-right:.25rem}table.dataTable.table-sm>thead>tr th.dt-orderable-asc .dt-column-order,table.dataTable.table-sm>thead>tr th.dt-orderable-desc .dt-column-order,table.dataTable.table-sm>thead>tr th.dt-ordering-asc .dt-column-order,table.dataTable.table-sm>thead>tr th.dt-ordering-desc .dt-column-order,table.dataTable.table-sm>thead>tr td.dt-orderable-asc .dt-column-order,table.dataTable.table-sm>thead>tr td.dt-orderable-desc .dt-column-order,table.dataTable.table-sm>thead>tr td.dt-ordering-asc .dt-column-order,table.dataTable.table-sm>thead>tr td.dt-ordering-desc .dt-column-order{right:.25rem}table.dataTable.table-sm>thead>tr th.dt-type-date .dt-column-order,table.dataTable.table-sm>thead>tr th.dt-type-numeric .dt-column-order,table.dataTable.table-sm>thead>tr td.dt-type-date .dt-column-order,table.dataTable.table-sm>thead>tr td.dt-type-numeric .dt-column-order{left:.25rem}table.dataTable.table-sm>thead>tr th.dt-left .dt-column-order,table.dataTable.table-sm>thead>tr th.dt-head-left .dt-column-order,table.dataTable.table-sm>thead>tr td.dt-left .dt-column-order,table.dataTable.table-sm>thead>tr td.dt-head-left .dt-column-order{left:auto;right:.25rem}table.dataTable.table-sm>thead>tr th.dt-right .dt-column-order,table.dataTable.table-sm>thead>tr th.dt-head-right .dt-column-order,table.dataTable.table-sm>thead>tr td.dt-right .dt-column-order,table.dataTable.table-sm>thead>tr td.dt-head-right .dt-column-order{left:.25rem;right:auto}div.dt-scroll-head table.table-bordered{border-bottom-width:0}div.table-responsive>div.dt-container>div.row{margin-left:0;margin-right:0}div.table-responsive>div.dt-container>div.row>div[class^=col-]:first-child{padding-left:0}div.table-responsive>div.dt-container>div.row>div[class^=col-]:last-child{padding-right:0} diff --git a/frontend/vendor/dataTables.bootstrap5.min.js b/frontend/vendor/dataTables.bootstrap5.min.js new file mode 100644 index 0000000..e909e19 --- /dev/null +++ b/frontend/vendor/dataTables.bootstrap5.min.js @@ -0,0 +1,4 @@ +/*! DataTables Bootstrap 5 integration + * © SpryMedia Ltd - datatables.net/license + */ +(e=>{var n;"function"==typeof define&&define.amd?define(["datatables.net"],function(t){return e(window,document,t)}):"object"==typeof exports?(n=function(t){t.DataTable||require("datatables.net")(t)},"undefined"==typeof window?module.exports=function(t){return t=t||window,n(t),e(0,t.document,t.DataTable)}:(n(window),module.exports=e(window,window.document,window.DataTable))):e(window,document,window.DataTable)})(function(t,e,r){return r.util.object.assignDeep(r.defaults,{renderer:"bootstrap"}),r.util.object.assignDeep(r.ext.classes,{container:"dt-container dt-bootstrap5",search:{input:"form-control form-control-sm"},length:{select:"form-select form-select-sm"},processing:{container:"dt-processing card"},layout:{row:"row mt-2 justify-content-between",cell:"d-md-flex justify-content-between align-items-center",tableCell:"col-12",start:"dt-layout-start col-md-auto me-auto",end:"dt-layout-end col-md-auto ms-auto",full:"dt-layout-full col-md"}}),r.ext.renderer.pagingButton.bootstrap=function(t,e,n,o,a){var d=["dt-paging-button","page-item"],o=(o&&d.push("active"),a&&d.push("disabled"),r.Dom.c("li").classAdd(d.join(" "))),a=r.Dom.c("button").classAdd("page-link").attr("role","link").attr("type","button").html(n).appendTo(o);return{display:o.get(0),clicker:a.get(0)}},r.ext.renderer.pagingContainer.bootstrap=function(t,e){return r.Dom.c("ul").classAdd("pagination").append(e).get(0)},r}); \ No newline at end of file diff --git a/frontend/vendor/dataTables.min.js b/frontend/vendor/dataTables.min.js new file mode 100644 index 0000000..2b5d16a --- /dev/null +++ b/frontend/vendor/dataTables.min.js @@ -0,0 +1,4 @@ +/*! DataTables 3.1.4 + * Copyright (c) SpryMedia Ltd - datatables.net/license + */ +(t=>{"function"==typeof define&&define.amd?define([],function(){return t(window,document)}):"object"==typeof exports?"undefined"==typeof window?module.exports=function(e){return e=e||window,t(e,e.document)}:module.exports=t(window,window.document):window.DataTable=t(window,document)})(function(A,T){let _=/['\u00A0,$£€¥%\u2009\u202F\u20BD\u20a9\u20BArfkɃΞ]/gi,j=/<([^>]*>)/g,C=new RegExp("(\\"+["/",".","*","+","?","|","(",")","[","]","{","}","\\","$","^","-"].join("|\\")+")","g");var O=Object.freeze({__proto__:null,isoTimezone:/[T\s]\d{2}.*?(Z|[+-]\d{2}(?::?\d{2})?)$/,reDate:/^\d{2,4}[./-]\d{1,2}[./-]\d{1,2}([T ]{1}\d{1,2}[:.]\d{2}([.:]\d{2})?)?$/,reFormattedNumeric:_,reHtml:j,reNewLines:/[\r\n\u2028]/g,reRegexCharacters:C});let S=Math.pow(2,28),N=function(e,t){var r;return"string"!=typeof e?e:(r=e.normalize?e.normalize("NFD"):e).length!==e.length?(!0===t?e+" ":"")+r.replace(/[\u0300-\u036f]/g,""):r},R=function(e,t=""){if(!e||"string"!=typeof e)return e;if(e.length>S)throw new Error("Exceeded max str len");let r,n=e.replace(j,t);for(;(n=(r=n).replace(/