Compare commits
22 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5f51d40fef | ||
|
|
22f1733a5d | ||
|
|
17b0e99aa3 | ||
|
|
8992bb922e | ||
|
|
608afe08e3 | ||
|
|
e1862462af | ||
|
|
863ad50cc3 | ||
|
|
5e1c366a60 | ||
|
|
0968560090 | ||
|
|
25425901b1 | ||
|
|
b0e353c565 | ||
|
|
b926dd0d49 | ||
|
|
80faccb1f9 | ||
|
|
9b78d66769 | ||
|
|
485be063d2 | ||
|
|
47152f8f04 | ||
|
|
67350bfcd6 | ||
|
|
0fa4e271a7 | ||
|
|
b1a565bc9e | ||
|
|
c962a93f30 | ||
|
|
676f7ede30 | ||
|
|
5dd234e7b3 |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -85,6 +85,7 @@ secrets.json
|
|||||||
# Temporary files
|
# Temporary files
|
||||||
*.tmp
|
*.tmp
|
||||||
*.bak
|
*.bak
|
||||||
|
docs/superpowers
|
||||||
|
|
||||||
# Just in case
|
# Just in case
|
||||||
.~*
|
.~*
|
||||||
|
|||||||
216
README.md
216
README.md
@@ -12,11 +12,17 @@ CLI-инструмент для генерации отчётов по зада
|
|||||||
- Авторизация через Redmine API token или логин/пароль.
|
- Авторизация через Redmine API token или логин/пароль.
|
||||||
- Группировка задач по проекту и версии.
|
- Группировка задач по проекту и версии.
|
||||||
- Перевод статусов задач на русский язык.
|
- Перевод статусов задач на русский язык.
|
||||||
|
- Разбивка по типам активности (`--by-activity`).
|
||||||
- Вывод в консоль (таблица / компактный вид).
|
- Вывод в консоль (таблица / компактный вид).
|
||||||
- Экспорт в ODT, CSV, Markdown, HTML, JSON и Excel (.xlsx).
|
- Экспорт в ODT, CSV, Markdown, HTML, JSON и Excel (.xlsx).
|
||||||
- Excel-отчёт с merge-ячейками по проекту/версии, итогами, автошириной, автофильтром и закреплённой шапкой.
|
- Excel-отчёт с merge-ячейками по проекту/версии, итогами, автошириной, автофильтром и закреплённой шапкой.
|
||||||
- Сводка по времени (`--summary`).
|
- Сводка по времени (`--summary`).
|
||||||
- Понятные сообщения об ошибках Redmine API (401/403/5xx, таймаут, сеть).
|
- YAML-конфиг (`~/.config/redmine-reporter/config.yml`): шаблон имени файла, путь по умолчанию, период, email, настройки содержимого отчёта (`report.no_time`).
|
||||||
|
- Умное разрешение `--output`: bare-формат (`xlsx`) → путь по шаблону, без расширения → автодописывание.
|
||||||
|
- `--commit`: автосохранение отчёта в файл + фиксация периода в YAML-конфиге для следующего запуска.
|
||||||
|
- `--send`: отправка отчёта по email через SMTP сразу после генерации.
|
||||||
|
- HTML-версия тела письма при `--send`, если включено в YAML-конфиге (`email.html: true`).
|
||||||
|
- Понятные сообщения об ошибках Redmine API, SMTP и файловой системы.
|
||||||
- Загрузка альтернативного `.env` через `--config`.
|
- Загрузка альтернативного `.env` через `--config`.
|
||||||
|
|
||||||
## Установка
|
## Установка
|
||||||
@@ -38,28 +44,82 @@ pip install -e ".[dev]"
|
|||||||
|
|
||||||
## Настройка
|
## Настройка
|
||||||
|
|
||||||
Создайте файл `.env` в корне проекта. Он не должен попадать в git.
|
Источники конфигурации (от высшего приоритета к низшему):
|
||||||
|
|
||||||
Рекомендуемый вариант авторизации:
|
```
|
||||||
|
CLI-флаги > переменные окружения > .env > YAML-конфиг > кодовые дефолты
|
||||||
|
```
|
||||||
|
|
||||||
|
### YAML-конфиг (основной способ)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Сгенерировать YAML из текущего .env
|
||||||
|
redmine-reporter --init-config
|
||||||
|
|
||||||
|
# Редактировать под себя
|
||||||
|
vim ~/.config/redmine-reporter/config.yml
|
||||||
|
```
|
||||||
|
|
||||||
|
Структура:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
redmine:
|
||||||
|
url: https://red.eltex.loc
|
||||||
|
api_key: ${REDMINE_API_KEY}
|
||||||
|
author: "Кокос А.А."
|
||||||
|
verify_ssl: true
|
||||||
|
|
||||||
|
period:
|
||||||
|
precision: date # date | datetime
|
||||||
|
default_from: "2026-06-01"
|
||||||
|
# default_to можно не указывать — конец периода будет сегодня
|
||||||
|
default_to: "2026-06-30"
|
||||||
|
dynamic: false
|
||||||
|
# last_used заполняется --commit (см. docs/CONFIG.md)
|
||||||
|
|
||||||
|
output:
|
||||||
|
dir: ~/reports
|
||||||
|
filename: "{author}_{from}_{to}.{ext}"
|
||||||
|
default_format: xlsx
|
||||||
|
|
||||||
|
report:
|
||||||
|
no_time: false
|
||||||
|
|
||||||
|
email:
|
||||||
|
html: false
|
||||||
|
smtp:
|
||||||
|
host: smtp.example.com
|
||||||
|
port: 587
|
||||||
|
user: bot@example.com
|
||||||
|
password: ${SMTP_PASSWORD}
|
||||||
|
tls: true
|
||||||
|
from: bot@example.com
|
||||||
|
to:
|
||||||
|
- boss@example.com
|
||||||
|
cc: []
|
||||||
|
bcc: []
|
||||||
|
subject: "Отчёт {author} за {period}"
|
||||||
|
body_text: "Во вложении отчёт."
|
||||||
|
attach: true
|
||||||
|
```
|
||||||
|
|
||||||
|
Шаблон `output.filename` поддерживает `{author}`, `{from}`, `{to}`, `{date}` (DD_MM_YYYY), `{ext}`.
|
||||||
|
|
||||||
|
Шаблоны `email.subject` и `email.body_text` поддерживают `{author}`, `{period}` (строка диапазона, например `2026-06-01--2026-06-30`).
|
||||||
|
|
||||||
|
Подробнее: [docs/CONFIG.md](docs/CONFIG.md).
|
||||||
|
|
||||||
|
### `.env` (legacy)
|
||||||
|
|
||||||
```ini
|
```ini
|
||||||
REDMINE_URL=https://red.eltex.loc/
|
REDMINE_URL=https://red.eltex.loc/
|
||||||
REDMINE_API_KEY=ваш_api_token
|
REDMINE_API_KEY=ваш_api_token
|
||||||
REDMINE_AUTHOR=Иванов Иван Иванович
|
REDMINE_AUTHOR=Иванов Иван Иванович
|
||||||
|
|
||||||
DEFAULT_FROM_DATE=2026-01-01
|
DEFAULT_FROM_DATE=2026-01-01
|
||||||
|
# DEFAULT_TO_DATE можно не задавать — тогда конец периода будет сегодня
|
||||||
DEFAULT_TO_DATE=2026-01-31
|
DEFAULT_TO_DATE=2026-01-31
|
||||||
```
|
```
|
||||||
|
|
||||||
Резервный вариант:
|
|
||||||
|
|
||||||
```ini
|
|
||||||
REDMINE_URL=https://red.eltex.loc/
|
|
||||||
REDMINE_USER=ваш.логин
|
|
||||||
REDMINE_PASSWORD=ваш_пароль
|
|
||||||
REDMINE_AUTHOR=Иванов Иван Иванович
|
|
||||||
```
|
|
||||||
|
|
||||||
Переменные окружения:
|
Переменные окружения:
|
||||||
|
|
||||||
| Переменная | Обязательность | Описание |
|
| Переменная | Обязательность | Описание |
|
||||||
@@ -68,9 +128,9 @@ REDMINE_AUTHOR=Иванов Иван Иванович
|
|||||||
| `REDMINE_API_KEY` | Да, если нет логина и пароля | Redmine API token. |
|
| `REDMINE_API_KEY` | Да, если нет логина и пароля | Redmine API token. |
|
||||||
| `REDMINE_USER` | Да, если нет токена | Логин Redmine. |
|
| `REDMINE_USER` | Да, если нет токена | Логин Redmine. |
|
||||||
| `REDMINE_PASSWORD` | Да, если нет токена | Пароль Redmine. |
|
| `REDMINE_PASSWORD` | Да, если нет токена | Пароль Redmine. |
|
||||||
| `REDMINE_AUTHOR` | Нет | Имя автора для ODT-отчёта. |
|
| `REDMINE_AUTHOR` | Нет | Имя автора для отчёта. |
|
||||||
| `DEFAULT_FROM_DATE` | Нет | Начальная дата периода по умолчанию (`YYYY-MM-DD`). |
|
| `DEFAULT_FROM_DATE` | Нет | Начальная дата периода по умолчанию (`YYYY-MM-DD`). |
|
||||||
| `DEFAULT_TO_DATE` | Нет | Конечная дата периода по умолчанию (`YYYY-MM-DD`). |
|
| `DEFAULT_TO_DATE` | Нет | Конечная дата периода по умолчанию (`YYYY-MM-DD`). Если не задана, а `DEFAULT_FROM_DATE` задана — используется сегодняшняя дата. |
|
||||||
| `REDMINE_VERIFY` | Нет | TLS-проверка: `true` / `false` / путь к CA bundle. |
|
| `REDMINE_VERIFY` | Нет | TLS-проверка: `true` / `false` / путь к CA bundle. |
|
||||||
|
|
||||||
## Использование
|
## Использование
|
||||||
@@ -79,19 +139,21 @@ REDMINE_AUTHOR=Иванов Иван Иванович
|
|||||||
source .venv/bin/activate
|
source .venv/bin/activate
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Основные сценарии
|
||||||
|
|
||||||
Отчёт за период по умолчанию:
|
Отчёт за период по умолчанию:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
redmine-reporter
|
redmine-reporter
|
||||||
```
|
```
|
||||||
|
|
||||||
Отчёт за произвольный период:
|
Произвольный период:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
redmine-reporter --date 2026-02-01--2026-02-28
|
redmine-reporter --date 2026-02-01--2026-02-28
|
||||||
```
|
```
|
||||||
|
|
||||||
Отчёт по другому пользователю:
|
Другой пользователь:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
redmine-reporter --user-id 42
|
redmine-reporter --user-id 42
|
||||||
@@ -99,51 +161,101 @@ redmine-reporter --user-login ivanov
|
|||||||
redmine-reporter --user-name "Иванов И.И."
|
redmine-reporter --user-name "Иванов И.И."
|
||||||
```
|
```
|
||||||
|
|
||||||
`--user-name` требует точного совпадения; если найдено несколько пользователей, CLI сообщает об ошибке и просит использовать `--user-id`.
|
Переопределить URL / API-ключ:
|
||||||
|
|
||||||
Переопределить URL/API-ключ из `.env`:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
redmine-reporter --url https://red.example.com --api-key ваш_токен
|
redmine-reporter --url https://red.example.com --api-key ваш_токен
|
||||||
```
|
```
|
||||||
|
|
||||||
Альтернативный конфигурационный файл:
|
Альтернативный `.env`:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
redmine-reporter --config /path/to/.env
|
redmine-reporter --config /path/to/.env
|
||||||
```
|
```
|
||||||
|
|
||||||
Компактный вывод:
|
Компактный / отладочный вывод:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
redmine-reporter --compact
|
redmine-reporter --compact
|
||||||
```
|
|
||||||
|
|
||||||
Отладочный вывод:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
redmine-reporter --debug
|
redmine-reporter --debug
|
||||||
```
|
```
|
||||||
|
|
||||||
Экспорт:
|
### Экспорт в файл
|
||||||
|
|
||||||
|
Явный путь:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
redmine-reporter --output report.odt
|
|
||||||
redmine-reporter --output report.csv
|
|
||||||
redmine-reporter --output report.md
|
|
||||||
redmine-reporter --output report.html
|
|
||||||
redmine-reporter --output report.json
|
|
||||||
redmine-reporter --output report.xlsx
|
redmine-reporter --output report.xlsx
|
||||||
|
redmine-reporter --output /path/to/report.odt
|
||||||
```
|
```
|
||||||
|
|
||||||
Отчёт без затраченного времени (работает для всех форматов):
|
Только формат (путь и имя берутся из YAML-шаблона):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
redmine-reporter --output xlsx # → output.dir/отчёт_01_07_2026.xlsx
|
||||||
|
redmine-reporter --output odt # → output.dir/отчёт_01_07_2026.odt
|
||||||
|
```
|
||||||
|
|
||||||
|
Путь без расширения (дописывается `default_format` из конфига):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
redmine-reporter --output /tmp/report # → /tmp/report.xlsx (если default_format: xlsx)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Отправка по email (`--send`)
|
||||||
|
|
||||||
|
Отправить отчёт на email, указанный в YAML-конфиге (секция `email`):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Сохранить по шаблону и отправить
|
||||||
|
redmine-reporter --date 2026-06-01--2026-06-30 --send
|
||||||
|
|
||||||
|
# С явным путём
|
||||||
|
redmine-reporter --date 2026-06-01--2026-06-30 --output ~/report.xlsx --send
|
||||||
|
|
||||||
|
# Вместе с фиксацией периода
|
||||||
|
redmine-reporter --date 2026-06-01--2026-06-30 --send --commit
|
||||||
|
```
|
||||||
|
|
||||||
|
Если в секции `email` установить `html: true`, письмо будет отправлено в двух версиях: plain-text и HTML (таблица отчёта прямо в теле письма). Файл отчёта всё равно прикрепляется, если `attach: true`.
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
email:
|
||||||
|
html: true
|
||||||
|
```
|
||||||
|
|
||||||
|
Если секция `email` не настроена — ошибка с пояснением. При ошибке SMTP файл отчёта остаётся на диске, данные не теряются. Поддерживаются `to`, `cc`, `bcc`, TLS, отключение вложения (`attach: false`).
|
||||||
|
|
||||||
|
### Фиксация периода (`--commit`)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Сгенерировать, сохранить в файл по шаблону, запомнить период
|
||||||
|
redmine-reporter --commit
|
||||||
|
|
||||||
|
# С явным путём
|
||||||
|
redmine-reporter --commit --output report.xlsx
|
||||||
|
|
||||||
|
# Следующий запуск (без --date) возьмёт следующий период автоматически
|
||||||
|
redmine-reporter
|
||||||
|
|
||||||
|
# При precision=datetime запоминает момент времени
|
||||||
|
# (предотвращает дублирование записей внутри дня)
|
||||||
|
redmine-reporter --commit
|
||||||
|
```
|
||||||
|
|
||||||
|
### Сводка и опции
|
||||||
|
|
||||||
|
Без времени / с разбивкой по активностям:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
redmine-reporter --no-time
|
redmine-reporter --no-time
|
||||||
redmine-reporter --no-time --output report.xlsx
|
redmine-reporter --by-activity
|
||||||
|
redmine-reporter --by-activity --summary
|
||||||
```
|
```
|
||||||
|
|
||||||
Сводка по времени:
|
`--no-time` можно задать в YAML-конфиге (`report.no_time: true`), чтобы автоматические режимы (`--commit`, `--send`) не включали затраченное время без явного флага. При ручном `--output` YAML-значение не применяется — только CLI-флаг `--no-time`.
|
||||||
|
|
||||||
|
Сводка:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
redmine-reporter --summary
|
redmine-reporter --summary
|
||||||
@@ -160,6 +272,33 @@ redmine-reporter --summary
|
|||||||
| **JSON** | Массив объектов: `project`, `version`, `issue_id`, `subject`, `status`, `time`. |
|
| **JSON** | Массив объектов: `project`, `version`, `issue_id`, `subject`, `status`, `time`. |
|
||||||
| **Excel (.xlsx)** | Merge cells, колонки `Hours`/`Spent Time`, итоги, автоширина, автофильтр, freeze panes. |
|
| **Excel (.xlsx)** | Merge cells, колонки `Hours`/`Spent Time`, итоги, автоширина, автофильтр, freeze panes. |
|
||||||
|
|
||||||
|
## Полный список флагов
|
||||||
|
|
||||||
|
```
|
||||||
|
--date DATE Диапазон дат: YYYY-MM-DD--YYYY-MM-DD
|
||||||
|
--compact Компактный текстовый вывод вместо таблицы
|
||||||
|
--output PATH/FMT Путь к файлу (.odt/.csv/.md/.html/.json/.xlsx)
|
||||||
|
или bare-формат (xlsx/odt/...) — путь из конфига
|
||||||
|
--author NAME Переопределить имя автора
|
||||||
|
--no-time Не включать затраченное время в таблицу
|
||||||
|
--url URL Переопределить Redmine URL
|
||||||
|
--api-key KEY Переопределить Redmine API key
|
||||||
|
--config PATH Путь к альтернативному .env-файлу
|
||||||
|
--verbose Подробный вывод
|
||||||
|
--debug Отладочный вывод
|
||||||
|
--version Показать версию и выйти
|
||||||
|
--summary Вывести сводку по времени в stderr
|
||||||
|
--user-id ID Redmine ID пользователя для отчёта
|
||||||
|
--user-login LOGIN Логин пользователя Redmine
|
||||||
|
--user-name NAME Полное имя пользователя Redmine
|
||||||
|
--by-activity Разбить время по типам активности
|
||||||
|
--init-config Сгенерировать YAML-конфиг и выйти
|
||||||
|
--force Перезаписать существующий конфиг (с --init-config)
|
||||||
|
--config-path PATH Путь к YAML-конфигу (по умолчанию ~/.config/redmine-reporter/config.yml)
|
||||||
|
--commit Сохранить отчёт в файл и зафиксировать период в конфиге
|
||||||
|
--send Отправить отчёт по email после сохранения
|
||||||
|
```
|
||||||
|
|
||||||
## Разработка
|
## Разработка
|
||||||
|
|
||||||
Проверки перед коммитом:
|
Проверки перед коммитом:
|
||||||
@@ -167,13 +306,14 @@ redmine-reporter --summary
|
|||||||
```bash
|
```bash
|
||||||
pytest
|
pytest
|
||||||
ruff check redmine_reporter tests
|
ruff check redmine_reporter tests
|
||||||
black --check redmine_reporter tests
|
ruff format --check redmine_reporter tests
|
||||||
isort --check-only redmine_reporter tests
|
|
||||||
mypy redmine_reporter
|
mypy redmine_reporter
|
||||||
```
|
```
|
||||||
|
|
||||||
## Безопасность
|
## Безопасность
|
||||||
|
|
||||||
- Не коммитьте `.env`, API token, пароль или логин.
|
- Не коммитьте `.env`, API token, пароль или логин.
|
||||||
|
- YAML-конфиг имеет права `0600`, директория — `0700`.
|
||||||
|
- Рекомендуется хранить секреты через `${VAR}`, а не plaintext.
|
||||||
- Используйте аккаунт с минимальными правами, достаточными для чтения time entries и задач.
|
- Используйте аккаунт с минимальными правами, достаточными для чтения time entries и задач.
|
||||||
- Инструмент работает только в режиме чтения и не изменяет данные в Redmine.
|
- Инструмент работает только в режиме чтения и не изменяет данные в Redmine.
|
||||||
|
|||||||
433
docs/CONFIG.md
Normal file
433
docs/CONFIG.md
Normal file
@@ -0,0 +1,433 @@
|
|||||||
|
# Настройка redmine-reporter
|
||||||
|
|
||||||
|
## Источники конфигурации
|
||||||
|
|
||||||
|
Приоритет, от высшего к низшему:
|
||||||
|
|
||||||
|
```
|
||||||
|
CLI-флаги > переменные окружения > .env > YAML > кодовые дефолты
|
||||||
|
```
|
||||||
|
|
||||||
|
Если значение не задано на верхнем уровне, берётся уровень ниже. `.env` и YAML
|
||||||
|
работают одновременно — можно оставить оба, можно удалить `.env` после миграции.
|
||||||
|
|
||||||
|
## YAML-конфиг
|
||||||
|
|
||||||
|
Основной файл: `~/.config/redmine-reporter/config.yml`.
|
||||||
|
|
||||||
|
Создаётся с правами `0600` (владелец: чтение/запись, остальные: доступ запрещён).
|
||||||
|
Директория `~/.config/redmine-reporter/` — с правами `0700`.
|
||||||
|
|
||||||
|
Если права файла шире `0600`, при запуске выводится предупреждение.
|
||||||
|
|
||||||
|
### Структура
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
redmine:
|
||||||
|
url: https://red.eltex.loc
|
||||||
|
api_key: ${REDMINE_API_KEY}
|
||||||
|
author: "Кокос А.А."
|
||||||
|
verify_ssl: true
|
||||||
|
|
||||||
|
period:
|
||||||
|
precision: date
|
||||||
|
default_from: "2026-06-01"
|
||||||
|
# default_to можно не указывать — тогда конец периода будет сегодня
|
||||||
|
default_to: "2026-06-30"
|
||||||
|
dynamic: false
|
||||||
|
last_used:
|
||||||
|
from: "2026-06-30T09:00:00"
|
||||||
|
to: "2026-06-30T12:00:00"
|
||||||
|
|
||||||
|
output:
|
||||||
|
dir: ~/reports
|
||||||
|
filename: "{author}_{from}_{to}.{ext}"
|
||||||
|
default_format: xlsx
|
||||||
|
|
||||||
|
report:
|
||||||
|
no_time: false
|
||||||
|
|
||||||
|
email:
|
||||||
|
html: false
|
||||||
|
smtp:
|
||||||
|
host: smtp.example.com
|
||||||
|
port: 587
|
||||||
|
user: bot@example.com
|
||||||
|
password: ${SMTP_PASSWORD}
|
||||||
|
tls: true
|
||||||
|
from: bot@example.com
|
||||||
|
to:
|
||||||
|
- boss@example.com
|
||||||
|
cc: []
|
||||||
|
bcc: []
|
||||||
|
subject: "Отчёт {author} за {period}"
|
||||||
|
body_text: "Во вложении отчёт."
|
||||||
|
attach: true
|
||||||
|
```
|
||||||
|
|
||||||
|
### `period.precision` — точность периода
|
||||||
|
|
||||||
|
Определяет, как вычисляется следующий период после фиксации:
|
||||||
|
|
||||||
|
- `date` (по умолчанию) — период с точностью до дня. Следующий запуск (после `--commit`) начинается со следующего дня.
|
||||||
|
- `datetime` — период с точностью до секунды. При повторном запуске time entries с `created_on` и `updated_on` ранее `last_used.to` исключаются (AND-логика: запись исключается только если **оба** поля раньше cutoff). Это предотвращает дублирование при отправке отчёта внутри рабочего дня.
|
||||||
|
|
||||||
|
`last_used.from` / `last_used.to` записываются автоматически при `--commit`. Вручную редактировать не требуется.
|
||||||
|
|
||||||
|
### `period.default_to` — необязательное окончание периода
|
||||||
|
|
||||||
|
Если `period.default_to` не задан, а `period.default_from` задан, инструмент
|
||||||
|
использует сегодняшнюю дату в качестве конца периода.
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
period:
|
||||||
|
default_from: "2026-07-01"
|
||||||
|
# default_to отсутствует → конец периода = сегодня
|
||||||
|
```
|
||||||
|
|
||||||
|
Это предотвращает устаревание периода, когда отчёт генерируется автоматически
|
||||||
|
(`--send`, `--commit`) без явного `--date`.
|
||||||
|
|
||||||
|
Аналогично работает `DEFAULT_TO_DATE`: если переменная не задана, а
|
||||||
|
`DEFAULT_FROM_DATE` задана, конец периода = сегодня.
|
||||||
|
|
||||||
|
### `--commit` — автофиксация периода
|
||||||
|
|
||||||
|
Флаг `--commit` сохраняет использованный период в YAML-конфиг, чтобы следующий запуск автоматически начинался с нового периода.
|
||||||
|
|
||||||
|
**Что делает:**
|
||||||
|
|
||||||
|
1. Генерирует отчёт как обычно.
|
||||||
|
2. Сохраняет отчёт в файл:
|
||||||
|
- Если указан `--output` — по явному пути.
|
||||||
|
- Если `--output` не указан — по шаблону из `output.dir` / `output.filename`.
|
||||||
|
3. Записывает `period.last_used.from` / `period.last_used.to` в YAML-конфиг.
|
||||||
|
4. При `period.precision: datetime` сохраняет текущий момент времени (ISO с секундами).
|
||||||
|
5. При `period.precision: date` сохраняет даты периода.
|
||||||
|
|
||||||
|
**Поведение `period.dynamic`:**
|
||||||
|
|
||||||
|
- `dynamic: true` — следующий запуск (без `--date`) вычисляет период от `last_used`:
|
||||||
|
- Полный календарный месяц → следующий полный месяц.
|
||||||
|
- Произвольный диапазон → та же длительность, начиная со дня после `last_used.to`.
|
||||||
|
- `dynamic: false` — `--commit` перезаписывает `default_from`/`default_to` на использованный период.
|
||||||
|
|
||||||
|
**Примеры:**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Июнь 2026 → следующий запуск (без --date) → июль 2026
|
||||||
|
redmine-reporter --date 2026-06-01--2026-06-30 --commit
|
||||||
|
|
||||||
|
# Произвольный диапазон: 15-20 июня → следующий запуск → 21-26 июня
|
||||||
|
redmine-reporter --date 2026-06-15--2026-06-20 --commit
|
||||||
|
|
||||||
|
# С datetime-точностью: повторный запуск не дублирует записи
|
||||||
|
redmine-reporter --commit
|
||||||
|
```
|
||||||
|
|
||||||
|
### `email` — настройка отправки по почте
|
||||||
|
|
||||||
|
Секция `email` используется флагом `--send`. Если секция не настроена или `smtp.host`
|
||||||
|
пуст, `--send` завершится с ошибкой «Email не настроен».
|
||||||
|
|
||||||
|
**Все поля:**
|
||||||
|
|
||||||
|
| Поле | Тип | По умолчанию | Описание |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `smtp.host` | строка | `""` | Адрес SMTP-сервера |
|
||||||
|
| `smtp.port` | число | `587` | Порт SMTP |
|
||||||
|
| `smtp.user` | строка | `""` | Логин для аутентификации |
|
||||||
|
| `smtp.password` | строка | `""` | Пароль (рекомендуется `${SMTP_PASSWORD}`) |
|
||||||
|
| `smtp.tls` | bool | `true` | Использовать STARTTLS |
|
||||||
|
| `from` | строка | `""` | Адрес отправителя |
|
||||||
|
| `to` | список | `[]` | Основные получатели |
|
||||||
|
| `cc` | список | `[]` | Копия |
|
||||||
|
| `bcc` | список | `[]` | Скрытая копия (не отображается в заголовках письма) |
|
||||||
|
| `subject` | строка | `"Отчёт {author} за {period}"` | Тема письма |
|
||||||
|
| `body_text` | строка | `"Во вложении отчёт."` | Текст письма (plain text) |
|
||||||
|
| `attach` | bool | `true` | Прикреплять файл отчёта. Если `false` — только текст |
|
||||||
|
| `html` | bool | `false` | Добавить HTML-версию тела письма (`multipart/alternative`) |
|
||||||
|
|
||||||
|
**Подстановки в `subject` и `body_text`:**
|
||||||
|
|
||||||
|
| Плейсхолдер | Описание | Пример |
|
||||||
|
|---|---|---|
|
||||||
|
| `{author}` | Имя автора из конфига или `--author` | `Кокос А.А.` |
|
||||||
|
| `{period}` | Строка диапазона дат | `2026-06-01--2026-06-30` |
|
||||||
|
|
||||||
|
**MIME-тип вложения** определяется по расширению файла:
|
||||||
|
|
||||||
|
| Расширение | MIME-тип |
|
||||||
|
|---|---|
|
||||||
|
| `.xlsx` | `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet` |
|
||||||
|
| `.odt` | `application/vnd.oasis.opendocument.text` |
|
||||||
|
| `.csv` | `text/csv` |
|
||||||
|
| `.html` | `text/html` |
|
||||||
|
| `.json` | `application/json` |
|
||||||
|
| `.md` | `text/markdown` |
|
||||||
|
|
||||||
|
Неизвестное расширение → `application/octet-stream`.
|
||||||
|
|
||||||
|
**Пример конфигурации:**
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
email:
|
||||||
|
html: false
|
||||||
|
smtp:
|
||||||
|
host: smtp.example.com
|
||||||
|
port: 587
|
||||||
|
user: bot@example.com
|
||||||
|
password: ${SMTP_PASSWORD}
|
||||||
|
tls: true
|
||||||
|
from: bot@example.com
|
||||||
|
to:
|
||||||
|
- boss@example.com
|
||||||
|
- team-lead@example.com
|
||||||
|
cc:
|
||||||
|
- manager@example.com
|
||||||
|
bcc: []
|
||||||
|
subject: "Отчёт {author} за {period}"
|
||||||
|
body_text: "Во вложении отчёт за период {period}."
|
||||||
|
attach: true
|
||||||
|
```
|
||||||
|
|
||||||
|
### `--send` — отправка отчёта по email
|
||||||
|
|
||||||
|
Флаг `--send` отправляет сгенерированный отчёт через SMTP сразу после сохранения
|
||||||
|
в файл. Требует настроенную секцию `email` в YAML-конфиге.
|
||||||
|
|
||||||
|
**Что делает:**
|
||||||
|
|
||||||
|
1. Генерирует отчёт как обычно.
|
||||||
|
2. Сохраняет отчёт в файл:
|
||||||
|
- Если указан `--output` — по явному пути.
|
||||||
|
- Если `--output` не указан — по шаблону из `output.dir` / `output.filename`.
|
||||||
|
3. Формирует MIME-письмо:
|
||||||
|
- Тема, plain-text тело и вложение (если `attach: true`).
|
||||||
|
- При `email.html: true` — дополнительно HTML-версия тела (`multipart/alternative`), сгенерированная из таблицы отчёта.
|
||||||
|
4. Отправляет через SMTP с TLS (таймаут 30 секунд).
|
||||||
|
|
||||||
|
**Файл отчёта сохраняется до попытки отправки** — при ошибке SMTP файл остаётся
|
||||||
|
на диске, данные не теряются.
|
||||||
|
|
||||||
|
**Ошибки SMTP:**
|
||||||
|
|
||||||
|
- Нет соединения → `"Не удалось подключиться к SMTP-серверу host:port"`
|
||||||
|
- Неверный логин/пароль → `"Ошибка аутентификации SMTP. Проверьте логин и пароль."`
|
||||||
|
- Таймаут → `"Таймаут соединения с SMTP-сервером."`
|
||||||
|
- Другая ошибка → `"Ошибка отправки письма: <детали>"`
|
||||||
|
|
||||||
|
Все ошибки выводятся в stderr, код возврата 1.
|
||||||
|
|
||||||
|
**Примеры:**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Отправить отчёт за июнь (сохранится по шаблону output.filename)
|
||||||
|
redmine-reporter --date 2026-06-01--2026-06-30 --send
|
||||||
|
|
||||||
|
# С явным путём
|
||||||
|
redmine-reporter --date 2026-06-01--2026-06-30 --output ~/report.xlsx --send
|
||||||
|
|
||||||
|
# Отправить и зафиксировать период
|
||||||
|
redmine-reporter --date 2026-06-01--2026-06-30 --send --commit
|
||||||
|
```
|
||||||
|
|
||||||
|
**Совместимость с другими флагами:**
|
||||||
|
|
||||||
|
| Комбинация | Поведение |
|
||||||
|
|---|---|
|
||||||
|
| `--send` | Сохранить по шаблону → отправить |
|
||||||
|
| `--send --output X` | Сохранить в X → отправить |
|
||||||
|
| `--send --commit` | Сохранить → отправить → зафиксировать период |
|
||||||
|
| `--send` с `email.html: true` | Письмо с plain-text + HTML-таблицей |
|
||||||
|
| `--send` без `email` в конфиге | Ошибка, exit 1 |
|
||||||
|
| `--send` при ошибке SMTP | Файл сохранён, ошибка в stderr, exit 1 |
|
||||||
|
|
||||||
|
### `output` — путь и имя файла по умолчанию
|
||||||
|
|
||||||
|
Секция управляет тем, куда и с каким именем сохраняется отчёт, когда `--output` не содержит полного пути.
|
||||||
|
|
||||||
|
**Правила разрешения `--output`:**
|
||||||
|
|
||||||
|
| Аргумент `--output` | Поведение |
|
||||||
|
|---|---|
|
||||||
|
| `/полный/путь/report.xlsx` | Используется как есть, конфиг игнорируется |
|
||||||
|
| `xlsx` (bare format: `xlsx`, `odt`, `csv`, `md`, `html`, `json`) | Путь = `output.dir` + `output.filename`, расширение = bare format |
|
||||||
|
| `/tmp/report` (путь без расширения) | Дописывается `.default_format` → `/tmp/report.xlsx` |
|
||||||
|
|
||||||
|
**Шаблон имени файла:**
|
||||||
|
|
||||||
|
`output.filename` поддерживает подстановки:
|
||||||
|
|
||||||
|
| Плейсхолдер | Описание | Пример |
|
||||||
|
|---|---|---|
|
||||||
|
| `{author}` | Имя автора (пробелы → `_`) | `Кокос_А.А.` |
|
||||||
|
| `{from}` | Начало периода, `YYYY-MM-DD` | `2026-06-01` |
|
||||||
|
| `{to}` | Конец периода, `YYYY-MM-DD` | `2026-06-30` |
|
||||||
|
| `{date}` | Конец периода, `DD_MM_YYYY` | `30_06_2026` |
|
||||||
|
| `{ext}` | Расширение файла без точки | `xlsx` |
|
||||||
|
|
||||||
|
Неизвестные плейсхолдеры остаются в имени как есть.
|
||||||
|
|
||||||
|
Примеры:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# По умолчанию
|
||||||
|
filename: "{author}_{from}_{to}.{ext}" # → Кокос_А.А._2026-06-01_2026-06-30.xlsx
|
||||||
|
|
||||||
|
# Русский формат даты
|
||||||
|
filename: "отчёт_{date}.{ext}" # → отчёт_30_06_2026.xlsx
|
||||||
|
|
||||||
|
# Без автора, только диапазон
|
||||||
|
filename: "report_{from}--{to}.{ext}" # → report_2026-06-01--2026-06-30.xlsx
|
||||||
|
```
|
||||||
|
|
||||||
|
### Подстановка переменных окружения
|
||||||
|
|
||||||
|
В любом строковом значении YAML можно использовать `${VAR}` — при загрузке
|
||||||
|
оно заменяется на значение переменной окружения:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
redmine:
|
||||||
|
api_key: ${REDMINE_API_KEY}
|
||||||
|
|
||||||
|
email:
|
||||||
|
smtp:
|
||||||
|
password: ${SMTP_PASSWORD}
|
||||||
|
```
|
||||||
|
|
||||||
|
Это безопаснее, чем хранить секреты plaintext в YAML. Однако plaintext-секреты
|
||||||
|
**не запрещены** — если вписать `api_key: "abc123"` напрямую, система примет.
|
||||||
|
Права `0600` — основная защита.
|
||||||
|
|
||||||
|
### `report` — настройки содержимого отчёта
|
||||||
|
|
||||||
|
Секция управляет тем, что попадает в сгенерированный отчёт.
|
||||||
|
|
||||||
|
| Поле | Тип | По умолчанию | Описание |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `no_time` | bool | `false` | Не включать затраченное время в файл отчёта |
|
||||||
|
|
||||||
|
`report.no_time` применяется только в автоматических режимах (`--commit`, `--send`).
|
||||||
|
При ручном `--output` YAML-настройка игнорируется — там работает только CLI-флаг `--no-time`.
|
||||||
|
CLI-флаг `--no-time` всегда имеет приоритет над YAML.
|
||||||
|
|
||||||
|
**Примеры:**
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
report:
|
||||||
|
no_time: true
|
||||||
|
```
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Автоматический режим: время не выводится
|
||||||
|
redmine-reporter --commit
|
||||||
|
|
||||||
|
# Ручной режим: report.no_time игнорируется, время выводится
|
||||||
|
redmine-reporter --output report.odt
|
||||||
|
|
||||||
|
# Ручной режим с явным флагом: время не выводится
|
||||||
|
redmine-reporter --output report.odt --no-time
|
||||||
|
```
|
||||||
|
|
||||||
|
## Разрешение выходного пути
|
||||||
|
|
||||||
|
Функция `resolve_output_path()` определяет итоговый путь к файлу:
|
||||||
|
|
||||||
|
1. `--output` не указан → консольный вывод.
|
||||||
|
2. `--output xlsx` (bare format) → путь формируется как `output.dir / output.filename` с подстановкой `{ext}` = bare format и дат из периода.
|
||||||
|
3. `--output /path/report` (без расширения) → дописывается `.output.default_format`.
|
||||||
|
4. `--output /path/report.csv` (с расширением) → используется как есть.
|
||||||
|
5. `--output /path/report.xyz` (неизвестное расширение) → используется как есть, форматтер выбирается по расширению.
|
||||||
|
|
||||||
|
## Миграция с `.env` на YAML
|
||||||
|
|
||||||
|
### Быстрый старт
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. Генерируем YAML из текущего .env
|
||||||
|
redmine-reporter --init-config
|
||||||
|
|
||||||
|
# 2. Проверяем, что создалось
|
||||||
|
cat ~/.config/redmine-reporter/config.yml
|
||||||
|
|
||||||
|
# 3. Редактируем под себя (шаблон имени, период, etc.)
|
||||||
|
vim ~/.config/redmine-reporter/config.yml
|
||||||
|
```
|
||||||
|
|
||||||
|
### Что делает `--init-config`
|
||||||
|
|
||||||
|
- Читает текущие значения из `.env` и переменных окружения.
|
||||||
|
- Формирует YAML со всеми секциями (`redmine`, `period`, `output`, `email`).
|
||||||
|
- Секреты (`REDMINE_API_KEY`, `SMTP_PASSWORD`) записывает как `${VAR}`, если
|
||||||
|
переменная существует, иначе — пустая строка.
|
||||||
|
- Создаёт файл с правами `0600`, директорию — с `0700`.
|
||||||
|
|
||||||
|
### Флаги миграции
|
||||||
|
|
||||||
|
| Флаг | Назначение |
|
||||||
|
|---|---|
|
||||||
|
| `--init-config` | Создать YAML и выйти |
|
||||||
|
| `--init-config --force` | Перезаписать существующий YAML |
|
||||||
|
| `--config-path PATH` | Сохранить YAML по указанному пути (по умолчанию `~/.config/redmine-reporter/config.yml`) |
|
||||||
|
|
||||||
|
Если `DEFAULT_TO_DATE` не задана, а `DEFAULT_FROM_DATE` задана, сгенерированный
|
||||||
|
YAML будет содержать пустое `default_to`, и при запуске инструмент использует
|
||||||
|
сегодняшнюю дату.
|
||||||
|
|
||||||
|
### Проверка после миграции
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Запустить без .env в текущей директории
|
||||||
|
cd /tmp
|
||||||
|
redmine-reporter --date 2026-06-01--2026-06-30
|
||||||
|
```
|
||||||
|
|
||||||
|
Если отработал — YAML-конфиг читается корректно. Если `REDMINE_URL is required` —
|
||||||
|
проверь права:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ls -la ~/.config/redmine-reporter/
|
||||||
|
# config.yml должно быть -rw------- (600)
|
||||||
|
# директория должна быть drwx------ (700)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Сосуществование `.env` и YAML
|
||||||
|
|
||||||
|
Можно оставить оба источника. `.env` имеет **более высокий приоритет**, чем YAML:
|
||||||
|
|
||||||
|
```
|
||||||
|
.env значения переопределяют YAML, если заданы
|
||||||
|
YAML работает как базовый слой для всего, что не в .env
|
||||||
|
```
|
||||||
|
|
||||||
|
Это safe — если с YAML что-то пойдёт не так, просто положи `.env` обратно.
|
||||||
|
|
||||||
|
### Откат
|
||||||
|
|
||||||
|
```bash
|
||||||
|
rm ~/.config/redmine-reporter/config.yml
|
||||||
|
```
|
||||||
|
|
||||||
|
## `.env` (legacy)
|
||||||
|
|
||||||
|
Для обратной совместимости `.env` продолжает работать без изменений.
|
||||||
|
|
||||||
|
```ini
|
||||||
|
REDMINE_URL=https://red.eltex.loc
|
||||||
|
REDMINE_API_KEY=your-api-key
|
||||||
|
REDMINE_AUTHOR=Кокос А.А.
|
||||||
|
DEFAULT_FROM_DATE=2026-06-01
|
||||||
|
DEFAULT_TO_DATE=2026-06-30
|
||||||
|
```
|
||||||
|
|
||||||
|
Если ни `.env`, ни YAML не заданы — используются кодовые дефолты (текущий месяц
|
||||||
|
как период, стандартный путь сертификатов, пустой автор).
|
||||||
|
|
||||||
|
## Безопасность
|
||||||
|
|
||||||
|
- YAML-конфиг: права `0600`, директория `0700`.
|
||||||
|
- Права шире `0600` → warning в stderr при каждом запуске.
|
||||||
|
- Секреты рекомендуется хранить через `${VAR}`, а не plaintext.
|
||||||
|
- `.env` **не рекомендуется** для постоянных настроек — оставьте его только
|
||||||
|
для CI/CD или временных переопределений.
|
||||||
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|||||||
|
|
||||||
[project]
|
[project]
|
||||||
name = "redmine-reporter"
|
name = "redmine-reporter"
|
||||||
version = "1.8.0"
|
version = "1.10.1"
|
||||||
description = "Redmine time-entry based issue reporter for internal use"
|
description = "Redmine time-entry based issue reporter for internal use"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
authors = [{ name = "Artem Kokos", email = "artem-kokos@mail.ru" }]
|
authors = [{ name = "Artem Kokos", email = "artem-kokos@mail.ru" }]
|
||||||
@@ -24,13 +24,12 @@ dependencies = [
|
|||||||
"python-dotenv>=1.0.0",
|
"python-dotenv>=1.0.0",
|
||||||
"odfpy>=1.4.0",
|
"odfpy>=1.4.0",
|
||||||
"openpyxl>=3.1.0",
|
"openpyxl>=3.1.0",
|
||||||
|
"pyyaml>=6.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
[project.optional-dependencies]
|
[project.optional-dependencies]
|
||||||
dev = [
|
dev = [
|
||||||
"pytest>=7.0",
|
"pytest>=7.0",
|
||||||
"black>=23.0",
|
|
||||||
"isort>=5.12",
|
|
||||||
"mypy>=1.0",
|
"mypy>=1.0",
|
||||||
"ruff>=0.1.0",
|
"ruff>=0.1.0",
|
||||||
]
|
]
|
||||||
@@ -45,17 +44,9 @@ include = ["redmine_reporter*"]
|
|||||||
[tool.setuptools.package-data]
|
[tool.setuptools.package-data]
|
||||||
"redmine_reporter" = ["templates/template.odt"]
|
"redmine_reporter" = ["templates/template.odt"]
|
||||||
|
|
||||||
[tool.black]
|
|
||||||
line-length = 100
|
|
||||||
target-version = ['py39']
|
|
||||||
|
|
||||||
[tool.isort]
|
|
||||||
profile = "black"
|
|
||||||
multi_line_output = 3
|
|
||||||
|
|
||||||
[tool.mypy]
|
[tool.mypy]
|
||||||
warn_unused_configs = true
|
warn_unused_configs = true
|
||||||
|
|
||||||
[[tool.mypy.overrides]]
|
[[tool.mypy.overrides]]
|
||||||
module = ["odf.*", "redminelib.*", "tabulate", "openpyxl.*"]
|
module = ["odf.*", "redminelib.*", "tabulate", "openpyxl.*", "yaml", "requests", "urllib3.*"]
|
||||||
ignore_missing_imports = true
|
ignore_missing_imports = true
|
||||||
|
|||||||
@@ -1 +1 @@
|
|||||||
__version__ = "1.8.0"
|
__version__ = "1.10.1"
|
||||||
|
|||||||
@@ -3,14 +3,19 @@ import logging
|
|||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
import sys
|
import sys
|
||||||
from datetime import datetime
|
from datetime import datetime, timezone
|
||||||
|
from pathlib import Path
|
||||||
from typing import List, Optional
|
from typing import List, Optional
|
||||||
|
|
||||||
|
import yaml
|
||||||
|
|
||||||
from . import __version__
|
from . import __version__
|
||||||
from .client import RedmineAPIError, fetch_issues_with_spent_time
|
from .client import RedmineAPIError, fetch_issues_with_spent_time
|
||||||
from .config import Config
|
from .config import Config
|
||||||
from .formatters.factory import get_console_formatter, get_formatter_by_extension
|
from .formatters.factory import get_console_formatter, get_formatter_by_extension
|
||||||
|
from .mailer import send_report
|
||||||
from .report_builder import build_grouped_report, calculate_summary
|
from .report_builder import build_grouped_report, calculate_summary
|
||||||
|
from .yaml_config import ensure_config_dir, resolve_output_path, save_period_to_config
|
||||||
|
|
||||||
|
|
||||||
def parse_date_range(date_arg: str) -> tuple[str, str]:
|
def parse_date_range(date_arg: str) -> tuple[str, str]:
|
||||||
@@ -20,7 +25,9 @@ def parse_date_range(date_arg: str) -> tuple[str, str]:
|
|||||||
|
|
||||||
from_date, to_date = parts[0].strip(), parts[1].strip()
|
from_date, to_date = parts[0].strip(), parts[1].strip()
|
||||||
date_pattern = r"\d{4}-\d{2}-\d{2}"
|
date_pattern = r"\d{4}-\d{2}-\d{2}"
|
||||||
if not re.fullmatch(date_pattern, from_date) or not re.fullmatch(date_pattern, to_date):
|
if not re.fullmatch(date_pattern, from_date) or not re.fullmatch(
|
||||||
|
date_pattern, to_date
|
||||||
|
):
|
||||||
raise ValueError("Date range must be in format YYYY-MM-DD--YYYY-MM-DD")
|
raise ValueError("Date range must be in format YYYY-MM-DD--YYYY-MM-DD")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -35,6 +42,189 @@ def parse_date_range(date_arg: str) -> tuple[str, str]:
|
|||||||
return start.isoformat(), end.isoformat()
|
return start.isoformat(), end.isoformat()
|
||||||
|
|
||||||
|
|
||||||
|
def _run_init_config(config_path: str, force: bool) -> int:
|
||||||
|
"""Создаёт YAML-конфиг из текущих настроек окружения."""
|
||||||
|
path = Path(config_path)
|
||||||
|
|
||||||
|
if path.exists() and not force:
|
||||||
|
print(
|
||||||
|
f"⚠️ {path} already exists.\n Use --init-config --force to overwrite.",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
return 1
|
||||||
|
|
||||||
|
# Собираем значения из окружения
|
||||||
|
data = {
|
||||||
|
"redmine": {
|
||||||
|
"url": os.getenv("REDMINE_URL", "").strip().rstrip("/"),
|
||||||
|
"api_key": ("${REDMINE_API_KEY}" if os.getenv("REDMINE_API_KEY") else ""),
|
||||||
|
"author": os.getenv("REDMINE_AUTHOR", "").strip(),
|
||||||
|
"verify_ssl": True,
|
||||||
|
},
|
||||||
|
"period": {
|
||||||
|
"precision": "date",
|
||||||
|
"default_from": os.getenv("DEFAULT_FROM_DATE", "").strip(),
|
||||||
|
"default_to": os.getenv("DEFAULT_TO_DATE", "").strip(),
|
||||||
|
"dynamic": False,
|
||||||
|
},
|
||||||
|
"output": {
|
||||||
|
"dir": "",
|
||||||
|
"filename": "{author}_{from}_{to}.{ext}",
|
||||||
|
"default_format": "xlsx",
|
||||||
|
},
|
||||||
|
"report": {
|
||||||
|
"no_time": False,
|
||||||
|
},
|
||||||
|
"email": {
|
||||||
|
"html": False,
|
||||||
|
"smtp": {
|
||||||
|
"host": "",
|
||||||
|
"port": 587,
|
||||||
|
"user": "",
|
||||||
|
"password": ("${SMTP_PASSWORD}" if os.getenv("SMTP_PASSWORD") else ""),
|
||||||
|
"tls": True,
|
||||||
|
},
|
||||||
|
"from": "",
|
||||||
|
"to": [],
|
||||||
|
"cc": [],
|
||||||
|
"bcc": [],
|
||||||
|
"subject": "Отчёт {author} за {period}",
|
||||||
|
"body_text": "Во вложении отчёт.",
|
||||||
|
"attach": True,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
ensure_config_dir(path.parent)
|
||||||
|
with open(path, "w", encoding="utf-8") as fh:
|
||||||
|
yaml.dump(
|
||||||
|
data, fh, allow_unicode=True, default_flow_style=False, sort_keys=False
|
||||||
|
)
|
||||||
|
path.chmod(0o600)
|
||||||
|
|
||||||
|
sections_found = [s for s in data if data[s]]
|
||||||
|
print(f"✅ Config written to {path}")
|
||||||
|
print(f" Sections: {', '.join(sections_found)}")
|
||||||
|
print(" Secrets stored as ${VAR} references where detected.")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def _compute_dedup_cutoff() -> Optional[datetime]:
|
||||||
|
"""Compute deduplication cutoff from config.
|
||||||
|
|
||||||
|
If period.precision == 'datetime' and period.last_used.to is set,
|
||||||
|
return the datetime to filter out entries already accounted for.
|
||||||
|
Otherwise return None.
|
||||||
|
"""
|
||||||
|
if Config.get_period_precision() != "datetime":
|
||||||
|
return None
|
||||||
|
|
||||||
|
last_to = Config.get_last_used_to()
|
||||||
|
if not last_to:
|
||||||
|
return None
|
||||||
|
|
||||||
|
try:
|
||||||
|
dt = datetime.fromisoformat(last_to.replace("Z", "+00:00"))
|
||||||
|
if dt.tzinfo is None:
|
||||||
|
dt = dt.replace(tzinfo=timezone.utc)
|
||||||
|
return dt
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_no_time(cli_flag: bool, is_auto_mode: bool) -> bool:
|
||||||
|
"""Возвращает финальное значение no_time.
|
||||||
|
|
||||||
|
Приоритет:
|
||||||
|
1. CLI-флаг --no-time (всегда побеждает).
|
||||||
|
2. YAML report.no_time (только в автоматических режимах --commit/--send).
|
||||||
|
3. Иначе False.
|
||||||
|
"""
|
||||||
|
if cli_flag:
|
||||||
|
return True
|
||||||
|
if is_auto_mode:
|
||||||
|
return Config.get_report_no_time()
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _save_and_maybe_send(
|
||||||
|
rows,
|
||||||
|
output_arg: str,
|
||||||
|
author: str,
|
||||||
|
from_date: str,
|
||||||
|
to_date: str,
|
||||||
|
no_time: bool,
|
||||||
|
do_send: bool,
|
||||||
|
) -> int:
|
||||||
|
"""Сохраняет отчёт в файл и опционально отправляет по email.
|
||||||
|
|
||||||
|
Returns 0 on success, 1 on error.
|
||||||
|
"""
|
||||||
|
output_ext = os.path.splitext(output_arg)[1].lower()
|
||||||
|
|
||||||
|
if not output_ext:
|
||||||
|
print(
|
||||||
|
"❌ Файл без расширения. Укажите расширение: .odt, .csv, .md, .html, .json или .xlsx",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
return 1
|
||||||
|
|
||||||
|
formatter = get_formatter_by_extension(
|
||||||
|
output_ext,
|
||||||
|
author=author,
|
||||||
|
from_date=from_date,
|
||||||
|
to_date=to_date,
|
||||||
|
no_time=no_time,
|
||||||
|
)
|
||||||
|
|
||||||
|
if not formatter:
|
||||||
|
if output_ext == ".odt":
|
||||||
|
print(
|
||||||
|
"❌ odfpy is not installed. Install with: pip install odfpy",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
known_exts = ", ".join([".odt", ".csv", ".md", ".html", ".json", ".xlsx"])
|
||||||
|
print(
|
||||||
|
f"❌ Неизвестный формат файла: {output_ext!r}. "
|
||||||
|
f"Поддерживаются: {known_exts}",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
return 1
|
||||||
|
|
||||||
|
try:
|
||||||
|
formatter.save(rows, output_arg)
|
||||||
|
print(f"✅ Report saved to {output_arg}")
|
||||||
|
except Exception as e:
|
||||||
|
fmt = output_ext.lstrip(".").upper()
|
||||||
|
print(f"❌ {fmt} export error: {e}", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
|
||||||
|
if do_send:
|
||||||
|
email_config = Config.get_email_config()
|
||||||
|
if email_config is None:
|
||||||
|
print(
|
||||||
|
"❌ Email не настроен. Добавьте секцию 'email' в конфиг "
|
||||||
|
"(~/.config/redmine-reporter/config.yml).",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
return 1
|
||||||
|
|
||||||
|
try:
|
||||||
|
send_report(
|
||||||
|
email_config,
|
||||||
|
output_arg,
|
||||||
|
author,
|
||||||
|
f"{from_date}--{to_date}",
|
||||||
|
rows=rows,
|
||||||
|
)
|
||||||
|
print(f"📧 Report sent to {', '.join(email_config.to)}")
|
||||||
|
except RedmineAPIError as e:
|
||||||
|
print(f"❌ {e.message}", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
def main(argv: Optional[List[str]] = None) -> int:
|
def main(argv: Optional[List[str]] = None) -> int:
|
||||||
parser = argparse.ArgumentParser(
|
parser = argparse.ArgumentParser(
|
||||||
prog="redmine-reporter",
|
prog="redmine-reporter",
|
||||||
@@ -42,7 +232,7 @@ def main(argv: Optional[List[str]] = None) -> int:
|
|||||||
)
|
)
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"--date",
|
"--date",
|
||||||
default=Config.get_default_date_range(),
|
default=None,
|
||||||
help="Date range in format YYYY-MM-DD--YYYY-MM-DD (default: current month or from .env)",
|
help="Date range in format YYYY-MM-DD--YYYY-MM-DD (default: current month or from .env)",
|
||||||
)
|
)
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
@@ -61,7 +251,9 @@ def main(argv: Optional[List[str]] = None) -> int:
|
|||||||
"--no-time", action="store_true", help="Do not include spent time into table"
|
"--no-time", action="store_true", help="Do not include spent time into table"
|
||||||
)
|
)
|
||||||
parser.add_argument("--url", help="Override Redmine URL from .env (REDMINE_URL)")
|
parser.add_argument("--url", help="Override Redmine URL from .env (REDMINE_URL)")
|
||||||
parser.add_argument("--api-key", help="Override Redmine API key from .env (REDMINE_API_KEY)")
|
parser.add_argument(
|
||||||
|
"--api-key", help="Override Redmine API key from .env (REDMINE_API_KEY)"
|
||||||
|
)
|
||||||
parser.add_argument("--config", help="Path to .env config file")
|
parser.add_argument("--config", help="Path to .env config file")
|
||||||
parser.add_argument("--verbose", action="store_true", help="Enable verbose output")
|
parser.add_argument("--verbose", action="store_true", help="Enable verbose output")
|
||||||
parser.add_argument("--debug", action="store_true", help="Enable debug output")
|
parser.add_argument("--debug", action="store_true", help="Enable debug output")
|
||||||
@@ -93,8 +285,56 @@ def main(argv: Optional[List[str]] = None) -> int:
|
|||||||
action="store_true",
|
action="store_true",
|
||||||
help="Break down spent time by activity type",
|
help="Break down spent time by activity type",
|
||||||
)
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--init-config",
|
||||||
|
action="store_true",
|
||||||
|
help="Generate YAML config from current environment and exit",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--force",
|
||||||
|
action="store_true",
|
||||||
|
help="Allow overwriting existing config with --init-config",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--config-path",
|
||||||
|
default=str(Path.home() / ".config" / "redmine-reporter" / "config.yml"),
|
||||||
|
help="Path for --init-config output (default: ~/.config/redmine-reporter/config.yml)",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--commit",
|
||||||
|
action="store_true",
|
||||||
|
help="Save used period as last_used in YAML config and auto-commit to file",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--send",
|
||||||
|
action="store_true",
|
||||||
|
help="Send generated report via email after saving (requires email section in config)",
|
||||||
|
)
|
||||||
args = parser.parse_args(argv)
|
args = parser.parse_args(argv)
|
||||||
|
|
||||||
|
# --init-config: обработка до всего остального
|
||||||
|
if args.init_config:
|
||||||
|
# Проверка на взаимоисключающие флаги
|
||||||
|
report_flags = [
|
||||||
|
args.date is not None,
|
||||||
|
args.output,
|
||||||
|
args.compact,
|
||||||
|
args.summary,
|
||||||
|
args.user_id,
|
||||||
|
args.user_login,
|
||||||
|
args.user_name,
|
||||||
|
args.no_time,
|
||||||
|
args.by_activity,
|
||||||
|
args.send,
|
||||||
|
]
|
||||||
|
if any(report_flags):
|
||||||
|
print(
|
||||||
|
"❌ --init-config cannot be used with report-generating flags.",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
return 1
|
||||||
|
return _run_init_config(args.config_path, args.force)
|
||||||
|
|
||||||
# Валидация взаимоисключающих флагов пользователя
|
# Валидация взаимоисключающих флагов пользователя
|
||||||
user_args = [args.user_id, args.user_login, args.user_name]
|
user_args = [args.user_id, args.user_login, args.user_name]
|
||||||
if sum(bool(a) for a in user_args) > 1:
|
if sum(bool(a) for a in user_args) > 1:
|
||||||
@@ -110,6 +350,10 @@ def main(argv: Optional[List[str]] = None) -> int:
|
|||||||
Config.set_redmine_url(args.url)
|
Config.set_redmine_url(args.url)
|
||||||
Config.set_redmine_api_key(args.api_key)
|
Config.set_redmine_api_key(args.api_key)
|
||||||
|
|
||||||
|
# Автозагрузка YAML-конфига
|
||||||
|
yaml_path = args.config_path
|
||||||
|
Config.load_yaml(yaml_path)
|
||||||
|
|
||||||
# Настройка уровня логирования
|
# Настройка уровня логирования
|
||||||
if args.debug:
|
if args.debug:
|
||||||
logging.basicConfig(level=logging.DEBUG, format="%(levelname)s: %(message)s")
|
logging.basicConfig(level=logging.DEBUG, format="%(levelname)s: %(message)s")
|
||||||
@@ -124,8 +368,10 @@ def main(argv: Optional[List[str]] = None) -> int:
|
|||||||
print(f"❌ Configuration error: {e}", file=sys.stderr)
|
print(f"❌ Configuration error: {e}", file=sys.stderr)
|
||||||
return 1
|
return 1
|
||||||
|
|
||||||
|
# Если --date не указан, используем дефолтный диапазон
|
||||||
|
date_arg = args.date if args.date is not None else Config.get_default_date_range()
|
||||||
try:
|
try:
|
||||||
from_date, to_date = parse_date_range(args.date)
|
from_date, to_date = parse_date_range(date_arg)
|
||||||
except ValueError as e:
|
except ValueError as e:
|
||||||
print(f"❌ Date error: {e}", file=sys.stderr)
|
print(f"❌ Date error: {e}", file=sys.stderr)
|
||||||
return 1
|
return 1
|
||||||
@@ -136,6 +382,7 @@ def main(argv: Optional[List[str]] = None) -> int:
|
|||||||
to_date,
|
to_date,
|
||||||
user_id=args.user_id or args.user_login or args.user_name,
|
user_id=args.user_id or args.user_login or args.user_name,
|
||||||
by_activity=args.by_activity,
|
by_activity=args.by_activity,
|
||||||
|
dedup_before=_compute_dedup_cutoff(),
|
||||||
)
|
)
|
||||||
except RedmineAPIError as e:
|
except RedmineAPIError as e:
|
||||||
print(f"❌ {e.message}", file=sys.stderr)
|
print(f"❌ {e.message}", file=sys.stderr)
|
||||||
@@ -154,11 +401,14 @@ def main(argv: Optional[List[str]] = None) -> int:
|
|||||||
print("ℹ️ No time entries found in the given period.", file=sys.stderr)
|
print("ℹ️ No time entries found in the given period.", file=sys.stderr)
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
print(f"✅ Total issues: {len(issue_hours)} [{args.date}]", file=sys.stderr)
|
print(f"✅ Total issues: {len(issue_hours)} [{date_arg}]", file=sys.stderr)
|
||||||
|
|
||||||
|
is_auto_mode = args.commit or args.send
|
||||||
|
no_time = _resolve_no_time(args.no_time, is_auto_mode)
|
||||||
|
|
||||||
rows = build_grouped_report(
|
rows = build_grouped_report(
|
||||||
issue_hours,
|
issue_hours,
|
||||||
fill_time=not args.no_time,
|
fill_time=not no_time,
|
||||||
by_activity=args.by_activity,
|
by_activity=args.by_activity,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -176,47 +426,79 @@ def main(argv: Optional[List[str]] = None) -> int:
|
|||||||
activity = key.split(":", 1)[1]
|
activity = key.split(":", 1)[1]
|
||||||
print(f" [{activity}]: {value}h", file=sys.stderr)
|
print(f" [{activity}]: {value}h", file=sys.stderr)
|
||||||
|
|
||||||
|
if args.output or args.commit:
|
||||||
if args.output:
|
if args.output:
|
||||||
output_ext = os.path.splitext(args.output)[1].lower()
|
output_arg = resolve_output_path(
|
||||||
|
args.output,
|
||||||
if not output_ext:
|
output_dir=Config.get_output_dir(),
|
||||||
print(
|
filename_template=Config.get_output_filename(),
|
||||||
"❌ Файл без расширения. Укажите расширение: .odt, .csv, .md, .html, .json или .xlsx",
|
default_format=Config.get_output_default_format(),
|
||||||
file=sys.stderr,
|
|
||||||
)
|
|
||||||
return 1
|
|
||||||
|
|
||||||
formatter = get_formatter_by_extension(
|
|
||||||
output_ext,
|
|
||||||
author=Config.get_author(args.author),
|
author=Config.get_author(args.author),
|
||||||
from_date=from_date,
|
from_date=from_date,
|
||||||
to_date=to_date,
|
to_date=to_date,
|
||||||
no_time=args.no_time,
|
|
||||||
)
|
|
||||||
|
|
||||||
if not formatter:
|
|
||||||
if output_ext == ".odt":
|
|
||||||
print(
|
|
||||||
"❌ odfpy is not installed. Install with: pip install odfpy",
|
|
||||||
file=sys.stderr,
|
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
known_exts = ", ".join([".odt", ".csv", ".md", ".html", ".json", ".xlsx"])
|
# --commit без --output: используем default_format
|
||||||
|
default_format = Config.get_output_default_format()
|
||||||
|
output_arg = resolve_output_path(
|
||||||
|
default_format,
|
||||||
|
output_dir=Config.get_output_dir(),
|
||||||
|
filename_template=Config.get_output_filename(),
|
||||||
|
default_format=default_format,
|
||||||
|
author=Config.get_author(args.author),
|
||||||
|
from_date=from_date,
|
||||||
|
to_date=to_date,
|
||||||
|
)
|
||||||
|
|
||||||
|
if output_arg is None:
|
||||||
print(
|
print(
|
||||||
f"❌ Неизвестный формат файла: {output_ext!r}. "
|
"❌ Не удалось определить путь для сохранения отчёта.", file=sys.stderr
|
||||||
f"Поддерживаются: {known_exts}",
|
|
||||||
file=sys.stderr,
|
|
||||||
)
|
)
|
||||||
return 1
|
return 1
|
||||||
|
|
||||||
try:
|
ret = _save_and_maybe_send(
|
||||||
formatter.save(rows, args.output)
|
rows,
|
||||||
print(f"✅ Report saved to {args.output}")
|
output_arg,
|
||||||
except Exception as e:
|
author=Config.get_author(args.author),
|
||||||
fmt = output_ext.lstrip(".").upper()
|
from_date=from_date,
|
||||||
print(f"❌ {fmt} export error: {e}", file=sys.stderr)
|
to_date=to_date,
|
||||||
|
no_time=no_time,
|
||||||
|
do_send=args.send,
|
||||||
|
)
|
||||||
|
if ret != 0:
|
||||||
|
return ret
|
||||||
|
|
||||||
|
elif args.send:
|
||||||
|
# --send без --output и --commit: сохраняем по шаблону и отправляем
|
||||||
|
default_format = Config.get_output_default_format()
|
||||||
|
output_arg = resolve_output_path(
|
||||||
|
default_format,
|
||||||
|
output_dir=Config.get_output_dir(),
|
||||||
|
filename_template=Config.get_output_filename(),
|
||||||
|
default_format=default_format,
|
||||||
|
author=Config.get_author(args.author),
|
||||||
|
from_date=from_date,
|
||||||
|
to_date=to_date,
|
||||||
|
)
|
||||||
|
|
||||||
|
if output_arg is None:
|
||||||
|
print(
|
||||||
|
"❌ Не удалось определить путь для сохранения отчёта.", file=sys.stderr
|
||||||
|
)
|
||||||
return 1
|
return 1
|
||||||
|
|
||||||
|
ret = _save_and_maybe_send(
|
||||||
|
rows,
|
||||||
|
output_arg,
|
||||||
|
author=Config.get_author(args.author),
|
||||||
|
from_date=from_date,
|
||||||
|
to_date=to_date,
|
||||||
|
no_time=no_time,
|
||||||
|
do_send=True,
|
||||||
|
)
|
||||||
|
if ret != 0:
|
||||||
|
return ret
|
||||||
|
|
||||||
else:
|
else:
|
||||||
if args.compact:
|
if args.compact:
|
||||||
formatter = get_console_formatter("compact")
|
formatter = get_console_formatter("compact")
|
||||||
@@ -234,6 +516,35 @@ def main(argv: Optional[List[str]] = None) -> int:
|
|||||||
print(f"❌ Formatting error: {e}", file=sys.stderr)
|
print(f"❌ Formatting error: {e}", file=sys.stderr)
|
||||||
return 1
|
return 1
|
||||||
|
|
||||||
|
if args.commit:
|
||||||
|
precision = Config.get_period_precision()
|
||||||
|
dynamic = Config._app.period_dynamic if Config._app else False
|
||||||
|
|
||||||
|
if precision == "datetime":
|
||||||
|
from datetime import datetime as dt_mod
|
||||||
|
|
||||||
|
now = dt_mod.now().isoformat(timespec="seconds")
|
||||||
|
from_str = now
|
||||||
|
to_str = now
|
||||||
|
else:
|
||||||
|
from_str = from_date
|
||||||
|
to_str = to_date
|
||||||
|
|
||||||
|
try:
|
||||||
|
save_period_to_config(
|
||||||
|
args.config_path, from_str, to_str, precision, dynamic
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
print(
|
||||||
|
f"❌ Не удалось сохранить период в конфиг: {e}",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
return 1
|
||||||
|
print(
|
||||||
|
f"📌 Period committed [{from_str} -- {to_str}] → {args.config_path}",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
from datetime import datetime
|
||||||
from typing import Any, Dict, List, Optional, Tuple, Union
|
from typing import Any, Dict, List, Optional, Tuple, Union
|
||||||
|
|
||||||
import requests
|
import requests
|
||||||
@@ -144,13 +145,34 @@ def _get_activity_name(entry, activities: Dict[int, str]) -> str:
|
|||||||
return str(activity)
|
return str(activity)
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_datetime(value: Any) -> Optional[datetime]:
|
||||||
|
"""Parse a datetime from Redmine API response.
|
||||||
|
|
||||||
|
Accepts datetime objects, ISO strings (with or without timezone),
|
||||||
|
or None. Returns a timezone-aware datetime or None.
|
||||||
|
"""
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
if isinstance(value, datetime):
|
||||||
|
return value
|
||||||
|
if isinstance(value, str):
|
||||||
|
try:
|
||||||
|
dt = datetime.fromisoformat(value.replace("Z", "+00:00"))
|
||||||
|
return dt
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
return None
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
def _fetch_issues_chunked(redmine: Redmine, issue_ids: List[int]) -> List[Issue]:
|
def _fetch_issues_chunked(redmine: Redmine, issue_ids: List[int]) -> List[Issue]:
|
||||||
"""Загружает задачи чанками, чтобы не превышать лимит длины URL (#21)."""
|
"""Загружает задачи чанками, чтобы не превышать лимит длины URL (#21)."""
|
||||||
all_issues: List[Issue] = []
|
all_issues: List[Issue] = []
|
||||||
for i in range(0, len(issue_ids), ISSUE_ID_CHUNK_SIZE):
|
for i in range(0, len(issue_ids), ISSUE_ID_CHUNK_SIZE):
|
||||||
chunk = issue_ids[i : i + ISSUE_ID_CHUNK_SIZE]
|
chunk = issue_ids[i : i + ISSUE_ID_CHUNK_SIZE]
|
||||||
issue_list_str = ",".join(str(x) for x in chunk)
|
issue_list_str = ",".join(str(x) for x in chunk)
|
||||||
issues = redmine.issue.filter(issue_id=issue_list_str, status_id="*", sort="project:asc")
|
issues = redmine.issue.filter(
|
||||||
|
issue_id=issue_list_str, status_id="*", sort="project:asc"
|
||||||
|
)
|
||||||
all_issues.extend(issues)
|
all_issues.extend(issues)
|
||||||
return all_issues
|
return all_issues
|
||||||
|
|
||||||
@@ -220,12 +242,15 @@ def fetch_issues_with_spent_time(
|
|||||||
to_date: str,
|
to_date: str,
|
||||||
user_id: Optional[Union[int, str]] = None,
|
user_id: Optional[Union[int, str]] = None,
|
||||||
by_activity: bool = False,
|
by_activity: bool = False,
|
||||||
|
dedup_before: Optional[datetime] = None,
|
||||||
) -> Optional[List[Tuple[Issue, float, Optional[Dict[str, float]]]]]:
|
) -> Optional[List[Tuple[Issue, float, Optional[Dict[str, float]]]]]:
|
||||||
"""
|
"""
|
||||||
Fetch unique issues linked to time entries of the given user in date range,
|
Fetch unique issues linked to time entries of the given user in date range,
|
||||||
along with total spent hours per issue.
|
along with total spent hours per issue.
|
||||||
If user_id is None, uses current user.
|
If user_id is None, uses current user.
|
||||||
If by_activity is True, returns per-activity breakdown as third tuple element.
|
If by_activity is True, returns per-activity breakdown as third tuple element.
|
||||||
|
If dedup_before is set, filters out time entries whose created_on AND updated_on
|
||||||
|
are both before dedup_before (AND logic: both must be < cutoff to exclude).
|
||||||
Returns list of (issue, total_hours, activities) tuples.
|
Returns list of (issue, total_hours, activities) tuples.
|
||||||
Raises RedmineAPIError on API/auth/network failures.
|
Raises RedmineAPIError on API/auth/network failures.
|
||||||
"""
|
"""
|
||||||
@@ -238,14 +263,36 @@ def fetch_issues_with_spent_time(
|
|||||||
else _get_current_user_id(redmine)
|
else _get_current_user_id(redmine)
|
||||||
)
|
)
|
||||||
activities_lookup = _load_time_entry_activities(redmine) if by_activity else {}
|
activities_lookup = _load_time_entry_activities(redmine) if by_activity else {}
|
||||||
time_entries = redmine.time_entry.filter(
|
time_entries = list(
|
||||||
|
redmine.time_entry.filter(
|
||||||
user_id=target_user_id, from_date=from_date, to_date=to_date
|
user_id=target_user_id, from_date=from_date, to_date=to_date
|
||||||
)
|
)
|
||||||
|
)
|
||||||
except RedmineAPIError:
|
except RedmineAPIError:
|
||||||
raise
|
raise
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
raise RedmineAPIError(_format_redmine_error(exc), original=exc) from exc
|
raise RedmineAPIError(_format_redmine_error(exc), original=exc) from exc
|
||||||
|
|
||||||
|
# Дедупликация: отсекаем записи, которые были учтены в предыдущем отчёте.
|
||||||
|
# Запись исключается, если BOTH created_on AND updated_on < dedup_before.
|
||||||
|
# Записи без метаданных (created_on/updated_on == None) не фильтруются.
|
||||||
|
if dedup_before is not None:
|
||||||
|
filtered: list = []
|
||||||
|
for entry in time_entries:
|
||||||
|
created = _parse_datetime(getattr(entry, "created_on", None))
|
||||||
|
updated = _parse_datetime(getattr(entry, "updated_on", None))
|
||||||
|
|
||||||
|
if created is None and updated is None:
|
||||||
|
filtered.append(entry)
|
||||||
|
elif created is not None and updated is not None:
|
||||||
|
if created >= dedup_before and updated >= dedup_before:
|
||||||
|
filtered.append(entry)
|
||||||
|
elif created is not None and created >= dedup_before:
|
||||||
|
filtered.append(entry)
|
||||||
|
elif updated is not None and updated >= dedup_before:
|
||||||
|
filtered.append(entry)
|
||||||
|
time_entries = filtered
|
||||||
|
|
||||||
# Агрегируем часы по issue.id (и активности, если требуется)
|
# Агрегируем часы по issue.id (и активности, если требуется)
|
||||||
spent_time: Dict[int, float] = {}
|
spent_time: Dict[int, float] = {}
|
||||||
spent_by_activity: Dict[int, Dict[str, float]] = {}
|
spent_by_activity: Dict[int, Dict[str, float]] = {}
|
||||||
@@ -278,7 +325,9 @@ def fetch_issues_with_spent_time(
|
|||||||
result = []
|
result = []
|
||||||
for issue in issues:
|
for issue in issues:
|
||||||
iid = issue.id
|
iid = issue.id
|
||||||
total_hours = spent_time.get(iid, 0.0)
|
if iid not in spent_time:
|
||||||
|
continue
|
||||||
|
total_hours = spent_time[iid]
|
||||||
activity_breakdown = spent_by_activity.get(iid) if by_activity else None
|
activity_breakdown = spent_by_activity.get(iid) if by_activity else None
|
||||||
result.append((issue, total_hours, activity_breakdown))
|
result.append((issue, total_hours, activity_breakdown))
|
||||||
|
|
||||||
|
|||||||
@@ -1,19 +1,249 @@
|
|||||||
|
import logging
|
||||||
import os
|
import os
|
||||||
|
from dataclasses import dataclass, field
|
||||||
from datetime import date, timedelta
|
from datetime import date, timedelta
|
||||||
|
from pathlib import Path
|
||||||
from typing import Union
|
from typing import Union
|
||||||
|
|
||||||
|
import yaml
|
||||||
from dotenv import load_dotenv
|
from dotenv import load_dotenv
|
||||||
|
|
||||||
|
from .yaml_config import check_file_permissions, resolve_env_vars
|
||||||
|
|
||||||
load_dotenv(override=False)
|
load_dotenv(override=False)
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
DEFAULT_REDMINE_VERIFY = "/etc/ssl/certs/ca-certificates.crt"
|
DEFAULT_REDMINE_VERIFY = "/etc/ssl/certs/ca-certificates.crt"
|
||||||
FALSE_VALUES = {"0", "false", "no", "off"}
|
FALSE_VALUES = {"0", "false", "no", "off"}
|
||||||
TRUE_VALUES = {"1", "true", "yes", "on"}
|
TRUE_VALUES = {"1", "true", "yes", "on"}
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class SmtpConfig:
|
||||||
|
host: str = ""
|
||||||
|
port: int = 587
|
||||||
|
user: str = ""
|
||||||
|
password: str = ""
|
||||||
|
tls: bool = True
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class EmailConfig:
|
||||||
|
smtp: SmtpConfig = field(default_factory=SmtpConfig)
|
||||||
|
from_: str = ""
|
||||||
|
to: list = field(default_factory=list)
|
||||||
|
cc: list = field(default_factory=list)
|
||||||
|
bcc: list = field(default_factory=list)
|
||||||
|
subject: str = "Отчёт {author} за {period}"
|
||||||
|
body_text: str = "Во вложении отчёт."
|
||||||
|
attach: bool = True
|
||||||
|
html: bool = False
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class PeriodLastUsed:
|
||||||
|
from_: str = ""
|
||||||
|
to: str = ""
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class AppConfig:
|
||||||
|
redmine_url: str = ""
|
||||||
|
redmine_api_key: str = ""
|
||||||
|
redmine_author: str = ""
|
||||||
|
redmine_verify: Union[bool, str] = DEFAULT_REDMINE_VERIFY
|
||||||
|
period_precision: str = "date"
|
||||||
|
period_default_from: str = ""
|
||||||
|
period_default_to: str = ""
|
||||||
|
period_dynamic: bool = False
|
||||||
|
period_last_used_from: str = ""
|
||||||
|
period_last_used_to: str = ""
|
||||||
|
output_dir: str = ""
|
||||||
|
output_filename: str = "{author}_{from}_{to}.{ext}"
|
||||||
|
output_default_format: str = "xlsx"
|
||||||
|
report_no_time: bool = False
|
||||||
|
email: EmailConfig = field(default_factory=EmailConfig)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_yaml(cls, path: Union[str, Path]) -> "AppConfig":
|
||||||
|
"""Загружает настройки из YAML-файла.
|
||||||
|
|
||||||
|
Если файл не существует — возвращает конфиг со значениями по умолчанию.
|
||||||
|
Неизвестные ключи верхнего уровня логируются с warning.
|
||||||
|
"""
|
||||||
|
path = Path(path)
|
||||||
|
if not path.exists():
|
||||||
|
return cls()
|
||||||
|
|
||||||
|
# Проверяем права файла
|
||||||
|
for warning in check_file_permissions(path):
|
||||||
|
logger.warning(warning)
|
||||||
|
|
||||||
|
with open(path, "r", encoding="utf-8") as fh:
|
||||||
|
raw = yaml.safe_load(fh) or {}
|
||||||
|
|
||||||
|
# Предупреждаем о неизвестных ключах верхнего уровня
|
||||||
|
known_keys = {
|
||||||
|
"redmine",
|
||||||
|
"period",
|
||||||
|
"output",
|
||||||
|
"report",
|
||||||
|
"email",
|
||||||
|
}
|
||||||
|
for key in raw:
|
||||||
|
if key not in known_keys:
|
||||||
|
logger.warning("Unknown top-level key in config: %s", key)
|
||||||
|
|
||||||
|
return cls(
|
||||||
|
redmine_url=cls._resolve_str(raw, "redmine", "url"),
|
||||||
|
redmine_api_key=cls._resolve_str(raw, "redmine", "api_key"),
|
||||||
|
redmine_author=cls._resolve_str(raw, "redmine", "author"),
|
||||||
|
redmine_verify=cls._resolve_verify(raw),
|
||||||
|
period_precision=cls._resolve_str(raw, "period", "precision") or "date",
|
||||||
|
period_default_from=cls._resolve_str(raw, "period", "default_from"),
|
||||||
|
period_default_to=cls._resolve_str(raw, "period", "default_to"),
|
||||||
|
period_dynamic=cls._resolve_bool(raw, "period", "dynamic"),
|
||||||
|
period_last_used_from=cls._resolve_str(raw, "period", "last_used", "from"),
|
||||||
|
period_last_used_to=cls._resolve_str(raw, "period", "last_used", "to"),
|
||||||
|
output_dir=cls._resolve_str(raw, "output", "dir"),
|
||||||
|
output_filename=cls._resolve_str(raw, "output", "filename")
|
||||||
|
or "{author}_{from}_{to}.{ext}",
|
||||||
|
output_default_format=cls._resolve_str(raw, "output", "default_format")
|
||||||
|
or "xlsx",
|
||||||
|
report_no_time=cls._resolve_bool(raw, "report", "no_time"),
|
||||||
|
email=cls._resolve_email(raw),
|
||||||
|
)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_env(cls) -> "AppConfig":
|
||||||
|
"""Загружает настройки из переменных окружения."""
|
||||||
|
return cls(
|
||||||
|
redmine_url=os.getenv("REDMINE_URL", "").strip().rstrip("/"),
|
||||||
|
redmine_api_key=os.getenv("REDMINE_API_KEY", "").strip(),
|
||||||
|
redmine_author=os.getenv("REDMINE_AUTHOR", "").strip(),
|
||||||
|
period_default_from=os.getenv("DEFAULT_FROM_DATE", "").strip(),
|
||||||
|
period_default_to=os.getenv("DEFAULT_TO_DATE", "").strip(),
|
||||||
|
)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _resolve_str(raw: dict, section: str, *keys: str) -> str:
|
||||||
|
value = raw.get(section)
|
||||||
|
for key in keys:
|
||||||
|
if isinstance(value, dict):
|
||||||
|
value = value.get(key)
|
||||||
|
else:
|
||||||
|
value = None
|
||||||
|
break
|
||||||
|
if isinstance(value, str):
|
||||||
|
return resolve_env_vars(value)
|
||||||
|
if value is None:
|
||||||
|
return ""
|
||||||
|
return str(value)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _resolve_bool(raw: dict, section: str, key: str) -> bool:
|
||||||
|
value = raw.get(section, {}).get(key)
|
||||||
|
if isinstance(value, bool):
|
||||||
|
return value
|
||||||
|
if isinstance(value, str):
|
||||||
|
normalized = value.lower()
|
||||||
|
if normalized in TRUE_VALUES:
|
||||||
|
return True
|
||||||
|
if normalized in FALSE_VALUES:
|
||||||
|
return False
|
||||||
|
return False
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _resolve_verify(cls, raw: dict) -> Union[bool, str]:
|
||||||
|
value = raw.get("redmine", {}).get("verify_ssl")
|
||||||
|
if value is None:
|
||||||
|
return DEFAULT_REDMINE_VERIFY
|
||||||
|
if isinstance(value, bool):
|
||||||
|
return DEFAULT_REDMINE_VERIFY if value else False
|
||||||
|
if isinstance(value, str):
|
||||||
|
normalized = value.lower()
|
||||||
|
if normalized in FALSE_VALUES:
|
||||||
|
return False
|
||||||
|
if normalized in TRUE_VALUES:
|
||||||
|
return DEFAULT_REDMINE_VERIFY
|
||||||
|
return resolve_env_vars(value)
|
||||||
|
return DEFAULT_REDMINE_VERIFY
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _resolve_email(cls, raw: dict) -> EmailConfig:
|
||||||
|
email_raw = raw.get("email", {}) or {}
|
||||||
|
smtp_raw = email_raw.get("smtp", {}) or {}
|
||||||
|
|
||||||
|
return EmailConfig(
|
||||||
|
smtp=SmtpConfig(
|
||||||
|
host=cls._safe_str(smtp_raw.get("host")),
|
||||||
|
port=cls._safe_int(smtp_raw.get("port"), 587),
|
||||||
|
user=cls._safe_str(smtp_raw.get("user")),
|
||||||
|
password=resolve_env_vars(cls._safe_str(smtp_raw.get("password"))),
|
||||||
|
tls=cls._safe_bool(smtp_raw.get("tls"), True),
|
||||||
|
),
|
||||||
|
from_=cls._safe_str(email_raw.get("from")),
|
||||||
|
to=cls._safe_list(email_raw.get("to")),
|
||||||
|
cc=cls._safe_list(email_raw.get("cc")),
|
||||||
|
bcc=cls._safe_list(email_raw.get("bcc")),
|
||||||
|
subject=resolve_env_vars(
|
||||||
|
cls._safe_str(email_raw.get("subject")) or "Отчёт {author} за {period}"
|
||||||
|
),
|
||||||
|
body_text=resolve_env_vars(
|
||||||
|
cls._safe_str(email_raw.get("body_text")) or "Во вложении отчёт."
|
||||||
|
),
|
||||||
|
attach=cls._safe_bool(email_raw.get("attach"), True),
|
||||||
|
html=cls._safe_bool(email_raw.get("html"), False),
|
||||||
|
)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _safe_str(value) -> str:
|
||||||
|
if value is None:
|
||||||
|
return ""
|
||||||
|
if isinstance(value, str):
|
||||||
|
return value
|
||||||
|
return str(value)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _safe_int(value, default: int = 0) -> int:
|
||||||
|
if value is None:
|
||||||
|
return default
|
||||||
|
try:
|
||||||
|
return int(value)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return default
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _safe_bool(value, default: bool = False) -> bool:
|
||||||
|
if isinstance(value, bool):
|
||||||
|
return value
|
||||||
|
if isinstance(value, str):
|
||||||
|
normalized = value.lower()
|
||||||
|
if normalized in TRUE_VALUES:
|
||||||
|
return True
|
||||||
|
if normalized in FALSE_VALUES:
|
||||||
|
return False
|
||||||
|
return default
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _safe_list(value) -> list:
|
||||||
|
if value is None:
|
||||||
|
return []
|
||||||
|
if isinstance(value, list):
|
||||||
|
return [str(v) for v in value]
|
||||||
|
return [str(value)]
|
||||||
|
|
||||||
|
|
||||||
class Config:
|
class Config:
|
||||||
_cli_url: str | None = None
|
_cli_url: str | None = None
|
||||||
_cli_api_key: str | None = None
|
_cli_api_key: str | None = None
|
||||||
|
_app: AppConfig | None = None
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def load_yaml(cls, path: str) -> None:
|
||||||
|
"""Загружает YAML-конфиг. Не бросает исключений при отсутствии файла."""
|
||||||
|
cls._app = AppConfig.from_yaml(path)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def load_config(cls, path: str) -> None:
|
def load_config(cls, path: str) -> None:
|
||||||
@@ -32,13 +262,23 @@ class Config:
|
|||||||
def get_redmine_url(cls) -> str:
|
def get_redmine_url(cls) -> str:
|
||||||
if cls._cli_url is not None:
|
if cls._cli_url is not None:
|
||||||
return cls._cli_url
|
return cls._cli_url
|
||||||
return os.getenv("REDMINE_URL", "").strip().rstrip("/")
|
env = os.getenv("REDMINE_URL", "").strip().rstrip("/")
|
||||||
|
if env:
|
||||||
|
return env
|
||||||
|
if cls._app:
|
||||||
|
return cls._app.redmine_url.strip().rstrip("/")
|
||||||
|
return ""
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def get_redmine_api_key(cls) -> str:
|
def get_redmine_api_key(cls) -> str:
|
||||||
if cls._cli_api_key is not None:
|
if cls._cli_api_key is not None:
|
||||||
return cls._cli_api_key
|
return cls._cli_api_key
|
||||||
return os.getenv("REDMINE_API_KEY", "").strip()
|
env = os.getenv("REDMINE_API_KEY", "").strip()
|
||||||
|
if env:
|
||||||
|
return env
|
||||||
|
if cls._app:
|
||||||
|
return cls._app.redmine_api_key
|
||||||
|
return ""
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def get_redmine_user(cls) -> str:
|
def get_redmine_user(cls) -> str:
|
||||||
@@ -51,40 +291,110 @@ class Config:
|
|||||||
@classmethod
|
@classmethod
|
||||||
def get_redmine_verify(cls) -> Union[bool, str]:
|
def get_redmine_verify(cls) -> Union[bool, str]:
|
||||||
value = os.getenv("REDMINE_VERIFY", "").strip()
|
value = os.getenv("REDMINE_VERIFY", "").strip()
|
||||||
if not value:
|
if value:
|
||||||
return DEFAULT_REDMINE_VERIFY
|
|
||||||
|
|
||||||
normalized = value.lower()
|
normalized = value.lower()
|
||||||
if normalized in FALSE_VALUES:
|
if normalized in FALSE_VALUES:
|
||||||
return False
|
return False
|
||||||
if normalized in TRUE_VALUES:
|
if normalized in TRUE_VALUES:
|
||||||
return True
|
return True
|
||||||
return value
|
return value
|
||||||
|
if cls._app:
|
||||||
|
return cls._app.redmine_verify
|
||||||
|
return DEFAULT_REDMINE_VERIFY
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def get_author(cls, cli_author: str = "") -> str:
|
def get_author(cls, cli_author: str = "") -> str:
|
||||||
"""Возвращает автора: из CLI если задан, иначе из .env, иначе — заглушку."""
|
|
||||||
if cli_author:
|
if cli_author:
|
||||||
return cli_author
|
return cli_author
|
||||||
return os.getenv("REDMINE_AUTHOR", "").strip()
|
env = os.getenv("REDMINE_AUTHOR", "").strip()
|
||||||
|
if env:
|
||||||
|
return env
|
||||||
|
if cls._app:
|
||||||
|
return cls._app.redmine_author
|
||||||
|
return ""
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def get_period_precision(cls) -> str:
|
||||||
|
if cls._app:
|
||||||
|
return cls._app.period_precision or "date"
|
||||||
|
return "date"
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def get_last_used_from(cls) -> str:
|
||||||
|
if cls._app:
|
||||||
|
return cls._app.period_last_used_from
|
||||||
|
return ""
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def get_last_used_to(cls) -> str:
|
||||||
|
if cls._app:
|
||||||
|
return cls._app.period_last_used_to
|
||||||
|
return ""
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def get_output_dir(cls) -> str:
|
||||||
|
if cls._app:
|
||||||
|
return cls._app.output_dir
|
||||||
|
return ""
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def get_output_filename(cls) -> str:
|
||||||
|
if cls._app:
|
||||||
|
return cls._app.output_filename or "{author}_{from}_{to}.{ext}"
|
||||||
|
return "{author}_{from}_{to}.{ext}"
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def get_output_default_format(cls) -> str:
|
||||||
|
if cls._app:
|
||||||
|
return cls._app.output_default_format or "xlsx"
|
||||||
|
return "xlsx"
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def get_report_no_time(cls) -> bool:
|
||||||
|
"""Возвращает report.no_time из YAML-конфига (по умолчанию False)."""
|
||||||
|
if cls._app:
|
||||||
|
return cls._app.report_no_time
|
||||||
|
return False
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def get_email_config(cls) -> "EmailConfig | None":
|
||||||
|
"""Возвращает EmailConfig из YAML-конфига или None, если не настроен."""
|
||||||
|
if cls._app is None:
|
||||||
|
return None
|
||||||
|
email = cls._app.email
|
||||||
|
if not email.smtp.host:
|
||||||
|
return None
|
||||||
|
return email
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def get_default_date_range(cls) -> str:
|
def get_default_date_range(cls) -> str:
|
||||||
default_from_date = os.getenv("DEFAULT_FROM_DATE", "").strip()
|
from_env = os.getenv("DEFAULT_FROM_DATE", "").strip()
|
||||||
default_to_date = os.getenv("DEFAULT_TO_DATE", "").strip()
|
to_env = os.getenv("DEFAULT_TO_DATE", "").strip()
|
||||||
if default_from_date and default_to_date:
|
|
||||||
return f"{default_from_date}--{default_to_date}"
|
|
||||||
|
|
||||||
# fallback: текущий месяц
|
|
||||||
today = date.today()
|
today = date.today()
|
||||||
|
today_str = today.isoformat()
|
||||||
|
|
||||||
|
if from_env:
|
||||||
|
return f"{from_env}--{to_env or today_str}"
|
||||||
|
|
||||||
|
if (
|
||||||
|
cls._app
|
||||||
|
and cls._app.period_dynamic
|
||||||
|
and cls._app.period_last_used_from
|
||||||
|
and cls._app.period_last_used_to
|
||||||
|
):
|
||||||
|
nf, nt = compute_next_period(
|
||||||
|
cls._app.period_last_used_from,
|
||||||
|
cls._app.period_last_used_to,
|
||||||
|
cls._app.period_precision or "date",
|
||||||
|
)
|
||||||
|
return f"{nf}--{nt}"
|
||||||
|
|
||||||
|
if cls._app and cls._app.period_default_from:
|
||||||
|
default_to = cls._app.period_default_to or today_str
|
||||||
|
return f"{cls._app.period_default_from}--{default_to}"
|
||||||
|
|
||||||
start = today.replace(day=1)
|
start = today.replace(day=1)
|
||||||
# последний день месяца: берём первое число следующего месяца и вычитаем день
|
return f"{start.isoformat()}--{today_str}"
|
||||||
if today.month == 12:
|
|
||||||
next_month = today.replace(year=today.year + 1, month=1, day=1)
|
|
||||||
else:
|
|
||||||
next_month = today.replace(month=today.month + 1, day=1)
|
|
||||||
end = next_month - timedelta(days=1)
|
|
||||||
return f"{start.isoformat()}--{end.isoformat()}"
|
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def validate(cls) -> None:
|
def validate(cls) -> None:
|
||||||
@@ -96,3 +406,52 @@ class Config:
|
|||||||
raise ValueError(
|
raise ValueError(
|
||||||
"REDMINE_API_KEY is required, or set both REDMINE_USER and REDMINE_PASSWORD"
|
"REDMINE_API_KEY is required, or set both REDMINE_USER and REDMINE_PASSWORD"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def compute_next_period(
|
||||||
|
last_from: str, last_to: str, precision: str
|
||||||
|
) -> tuple[str, str]:
|
||||||
|
"""Compute the next report period based on the last committed period.
|
||||||
|
|
||||||
|
- For a full calendar month → next full calendar month.
|
||||||
|
- For an arbitrary range → same duration, starting the day after last_to.
|
||||||
|
- For datetime precision → same duration, starting 1 second after last_to.
|
||||||
|
"""
|
||||||
|
from datetime import datetime as dt_mod
|
||||||
|
|
||||||
|
if precision == "datetime":
|
||||||
|
fmt = "%Y-%m-%dT%H:%M:%S"
|
||||||
|
from_dt = dt_mod.fromisoformat(last_from.replace("Z", "+00:00"))
|
||||||
|
to_dt = dt_mod.fromisoformat(last_to.replace("Z", "+00:00"))
|
||||||
|
duration = to_dt - from_dt
|
||||||
|
next_from_dt = to_dt + timedelta(seconds=1)
|
||||||
|
next_to_dt = next_from_dt + duration
|
||||||
|
return next_from_dt.strftime(fmt), next_to_dt.strftime(fmt)
|
||||||
|
|
||||||
|
from_parts = last_from.split("-")
|
||||||
|
to_parts = last_to.split("-")
|
||||||
|
from_d = date(int(from_parts[0]), int(from_parts[1]), int(from_parts[2]))
|
||||||
|
to_d = date(int(to_parts[0]), int(to_parts[1]), int(to_parts[2]))
|
||||||
|
|
||||||
|
first_of_month = from_d.replace(day=1)
|
||||||
|
if from_d == first_of_month:
|
||||||
|
if to_d.month == 12:
|
||||||
|
last_of_month = date(to_d.year, 12, 31)
|
||||||
|
else:
|
||||||
|
next_first = date(to_d.year, to_d.month + 1, 1)
|
||||||
|
last_of_month = next_first - timedelta(days=1)
|
||||||
|
if to_d == last_of_month:
|
||||||
|
if to_d.month == 12:
|
||||||
|
nstart = date(to_d.year + 1, 1, 1)
|
||||||
|
else:
|
||||||
|
nstart = date(to_d.year, to_d.month + 1, 1)
|
||||||
|
if nstart.month == 12:
|
||||||
|
nend = date(nstart.year, 12, 31)
|
||||||
|
else:
|
||||||
|
nend = date(nstart.year, nstart.month + 1, 1) - timedelta(days=1)
|
||||||
|
return nstart.isoformat(), nend.isoformat()
|
||||||
|
|
||||||
|
duration = to_d - from_d
|
||||||
|
next_from = to_d + timedelta(days=1)
|
||||||
|
next_to = next_from + duration
|
||||||
|
return next_from.isoformat(), next_to.isoformat()
|
||||||
|
|||||||
@@ -15,7 +15,9 @@ from .base import Formatter
|
|||||||
class ODTFormatter(Formatter):
|
class ODTFormatter(Formatter):
|
||||||
"""Форматтер для экспорта в ODT."""
|
"""Форматтер для экспорта в ODT."""
|
||||||
|
|
||||||
def __init__(self, author: str = "", from_date: str = "", to_date: str = "", **_kwargs):
|
def __init__(
|
||||||
|
self, author: str = "", from_date: str = "", to_date: str = "", **_kwargs
|
||||||
|
):
|
||||||
"""
|
"""
|
||||||
Инициализирует форматтер с параметрами для шапки отчета.
|
Инициализирует форматтер с параметрами для шапки отчета.
|
||||||
"""
|
"""
|
||||||
@@ -28,9 +30,20 @@ class ODTFormatter(Formatter):
|
|||||||
Форматирует данные в объект OpenDocument.
|
Форматирует данные в объект OpenDocument.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
with resources.files("redmine_reporter").joinpath("templates/template.odt").open("rb") as f:
|
with (
|
||||||
|
resources.files("redmine_reporter")
|
||||||
|
.joinpath("templates/template.odt")
|
||||||
|
.open("rb") as f
|
||||||
|
):
|
||||||
doc = load(f)
|
doc = load(f)
|
||||||
|
|
||||||
|
# Удаляем все текстовые параграфы из шаблона, оставляя только
|
||||||
|
# структурные элементы (forms, sequence-decls). Это защищает от
|
||||||
|
# артефактов редактирования шаблона в LibreOffice (#42).
|
||||||
|
for child in list(doc.text.childNodes):
|
||||||
|
if child.tagName == "text:p":
|
||||||
|
doc.text.removeChild(child)
|
||||||
|
|
||||||
para_style_name = "Standard"
|
para_style_name = "Standard"
|
||||||
|
|
||||||
# Заголовок
|
# Заголовок
|
||||||
@@ -45,7 +58,9 @@ class ODTFormatter(Formatter):
|
|||||||
# Стиль ячеек
|
# Стиль ячеек
|
||||||
cell_style_name = "TableCellStyle"
|
cell_style_name = "TableCellStyle"
|
||||||
cell_style = Style(name=cell_style_name, family="table-cell")
|
cell_style = Style(name=cell_style_name, family="table-cell")
|
||||||
cell_props = TableCellProperties(padding="0.04in", border="0.05pt solid #000000")
|
cell_props = TableCellProperties(
|
||||||
|
padding="0.04in", border="0.05pt solid #000000"
|
||||||
|
)
|
||||||
cell_style.addElement(cell_props)
|
cell_style.addElement(cell_props)
|
||||||
doc.automaticstyles.addElement(cell_style)
|
doc.automaticstyles.addElement(cell_style)
|
||||||
|
|
||||||
@@ -93,7 +108,9 @@ class ODTFormatter(Formatter):
|
|||||||
# в остальных — covered-cell для валидности ODF (#13)
|
# в остальных — covered-cell для валидности ODF (#13)
|
||||||
if first_version_in_project and first_row_in_version:
|
if first_version_in_project and first_row_in_version:
|
||||||
cell_project = TableCell(stylename=cell_style_name)
|
cell_project = TableCell(stylename=cell_style_name)
|
||||||
cell_project.setAttribute("numberrowsspanned", str(total_project_rows))
|
cell_project.setAttribute(
|
||||||
|
"numberrowsspanned", str(total_project_rows)
|
||||||
|
)
|
||||||
p = P(stylename=para_style_name, text=project)
|
p = P(stylename=para_style_name, text=project)
|
||||||
cell_project.addElement(p)
|
cell_project.addElement(p)
|
||||||
row.addElement(cell_project)
|
row.addElement(cell_project)
|
||||||
@@ -104,7 +121,9 @@ class ODTFormatter(Formatter):
|
|||||||
# в остальных — covered-cell для валидности ODF (#13)
|
# в остальных — covered-cell для валидности ODF (#13)
|
||||||
if first_row_in_version:
|
if first_row_in_version:
|
||||||
cell_version = TableCell(stylename=cell_style_name)
|
cell_version = TableCell(stylename=cell_style_name)
|
||||||
cell_version.setAttribute("numberrowsspanned", str(row_span_version))
|
cell_version.setAttribute(
|
||||||
|
"numberrowsspanned", str(row_span_version)
|
||||||
|
)
|
||||||
p = P(stylename=para_style_name, text=version)
|
p = P(stylename=para_style_name, text=version)
|
||||||
cell_version.addElement(p)
|
cell_version.addElement(p)
|
||||||
row.addElement(cell_version)
|
row.addElement(cell_version)
|
||||||
|
|||||||
@@ -19,8 +19,12 @@ class XLSXFormatter(Formatter):
|
|||||||
и числовой столбец с часами для удобного суммирования.
|
и числовой столбец с часами для удобного суммирования.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
_HEADER_FILL = PatternFill(start_color="D9E1F2", end_color="D9E1F2", fill_type="solid")
|
_HEADER_FILL = PatternFill(
|
||||||
_TOTAL_FILL = PatternFill(start_color="FFF2CC", end_color="FFF2CC", fill_type="solid")
|
start_color="D9E1F2", end_color="D9E1F2", fill_type="solid"
|
||||||
|
)
|
||||||
|
_TOTAL_FILL = PatternFill(
|
||||||
|
start_color="FFF2CC", end_color="FFF2CC", fill_type="solid"
|
||||||
|
)
|
||||||
_BORDER = Border(
|
_BORDER = Border(
|
||||||
left=Side(style="thin"),
|
left=Side(style="thin"),
|
||||||
right=Side(style="thin"),
|
right=Side(style="thin"),
|
||||||
@@ -40,7 +44,15 @@ class XLSXFormatter(Formatter):
|
|||||||
else:
|
else:
|
||||||
ws.title = "Report"
|
ws.title = "Report"
|
||||||
|
|
||||||
headers = ["Project", "Version", "Issue ID", "Subject", "Status", "Hours", "Spent Time"]
|
headers = [
|
||||||
|
"Project",
|
||||||
|
"Version",
|
||||||
|
"Issue ID",
|
||||||
|
"Subject",
|
||||||
|
"Status",
|
||||||
|
"Hours",
|
||||||
|
"Spent Time",
|
||||||
|
]
|
||||||
ws.append(headers)
|
ws.append(headers)
|
||||||
self._style_header_row(ws, headers)
|
self._style_header_row(ws, headers)
|
||||||
|
|
||||||
@@ -89,7 +101,10 @@ class XLSXFormatter(Formatter):
|
|||||||
)
|
)
|
||||||
self._style_total_row(ws, current_row, bold=False)
|
self._style_total_row(ws, current_row, bold=False)
|
||||||
ws.merge_cells(
|
ws.merge_cells(
|
||||||
start_row=current_row, start_column=2, end_row=current_row, end_column=5
|
start_row=current_row,
|
||||||
|
start_column=2,
|
||||||
|
end_row=current_row,
|
||||||
|
end_column=5,
|
||||||
)
|
)
|
||||||
current_row += 1
|
current_row += 1
|
||||||
|
|
||||||
@@ -99,7 +114,8 @@ class XLSXFormatter(Formatter):
|
|||||||
|
|
||||||
if not self.no_time:
|
if not self.no_time:
|
||||||
project_hours = sum(
|
project_hours = sum(
|
||||||
sum(r.get("hours", 0.0) for r in task_rows) for task_rows in versions.values()
|
sum(r.get("hours", 0.0) for r in task_rows)
|
||||||
|
for task_rows in versions.values()
|
||||||
)
|
)
|
||||||
ws.append(
|
ws.append(
|
||||||
[
|
[
|
||||||
@@ -114,7 +130,10 @@ class XLSXFormatter(Formatter):
|
|||||||
)
|
)
|
||||||
self._style_total_row(ws, current_row, bold=True)
|
self._style_total_row(ws, current_row, bold=True)
|
||||||
ws.merge_cells(
|
ws.merge_cells(
|
||||||
start_row=current_row, start_column=1, end_row=current_row, end_column=5
|
start_row=current_row,
|
||||||
|
start_column=1,
|
||||||
|
end_row=current_row,
|
||||||
|
end_column=5,
|
||||||
)
|
)
|
||||||
current_row += 1
|
current_row += 1
|
||||||
project_totals[project] = project_hours
|
project_totals[project] = project_hours
|
||||||
@@ -137,7 +156,9 @@ class XLSXFormatter(Formatter):
|
|||||||
]
|
]
|
||||||
)
|
)
|
||||||
self._style_total_row(ws, current_row, bold=True)
|
self._style_total_row(ws, current_row, bold=True)
|
||||||
ws.merge_cells(start_row=current_row, start_column=1, end_row=current_row, end_column=5)
|
ws.merge_cells(
|
||||||
|
start_row=current_row, start_column=1, end_row=current_row, end_column=5
|
||||||
|
)
|
||||||
|
|
||||||
for start, end in project_ranges:
|
for start, end in project_ranges:
|
||||||
ws.merge_cells(start_row=start, start_column=1, end_row=end, end_column=1)
|
ws.merge_cells(start_row=start, start_column=1, end_row=end, end_column=1)
|
||||||
@@ -167,7 +188,9 @@ class XLSXFormatter(Formatter):
|
|||||||
cell.font = Font(bold=True)
|
cell.font = Font(bold=True)
|
||||||
cell.fill = self._HEADER_FILL
|
cell.fill = self._HEADER_FILL
|
||||||
cell.border = self._BORDER
|
cell.border = self._BORDER
|
||||||
cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
cell.alignment = Alignment(
|
||||||
|
horizontal="center", vertical="center", wrap_text=True
|
||||||
|
)
|
||||||
|
|
||||||
def _style_data_row(self, ws: Worksheet, row: int) -> None:
|
def _style_data_row(self, ws: Worksheet, row: int) -> None:
|
||||||
for col_idx in range(1, 8):
|
for col_idx in range(1, 8):
|
||||||
@@ -190,7 +213,15 @@ class XLSXFormatter(Formatter):
|
|||||||
|
|
||||||
def _apply_column_widths(self, ws: Worksheet) -> None:
|
def _apply_column_widths(self, ws: Worksheet) -> None:
|
||||||
# Минимальные ширины по умолчанию
|
# Минимальные ширины по умолчанию
|
||||||
widths: Dict[int, float] = {1: 18.0, 2: 16.0, 3: 12.0, 4: 45.0, 5: 14.0, 6: 10.0, 7: 14.0}
|
widths: Dict[int, float] = {
|
||||||
|
1: 18.0,
|
||||||
|
2: 16.0,
|
||||||
|
3: 12.0,
|
||||||
|
4: 45.0,
|
||||||
|
5: 14.0,
|
||||||
|
6: 10.0,
|
||||||
|
7: 14.0,
|
||||||
|
}
|
||||||
|
|
||||||
for row in ws.iter_rows(min_row=2, max_row=ws.max_row):
|
for row in ws.iter_rows(min_row=2, max_row=ws.max_row):
|
||||||
for col_idx, cell in enumerate(row, start=1):
|
for col_idx, cell in enumerate(row, start=1):
|
||||||
|
|||||||
143
redmine_reporter/mailer.py
Normal file
143
redmine_reporter/mailer.py
Normal file
@@ -0,0 +1,143 @@
|
|||||||
|
"""Отправка сгенерированного отчёта по email через SMTP."""
|
||||||
|
|
||||||
|
import email.charset as _charset
|
||||||
|
import os
|
||||||
|
import smtplib
|
||||||
|
from email.mime.application import MIMEApplication
|
||||||
|
from email.mime.multipart import MIMEMultipart
|
||||||
|
from email.mime.text import MIMEText
|
||||||
|
from typing import Dict, List
|
||||||
|
|
||||||
|
from .client import RedmineAPIError
|
||||||
|
from .config import EmailConfig
|
||||||
|
from .types import ReportRow
|
||||||
|
|
||||||
|
# Use 8bit transfer encoding for UTF-8 so non-ASCII text (e.g. Russian)
|
||||||
|
# appears literally in MIME output instead of base64.
|
||||||
|
_charset.add_charset("utf-8", _charset.SHORTEST, None, "utf-8")
|
||||||
|
|
||||||
|
SMTP_TIMEOUT = 30
|
||||||
|
|
||||||
|
MIME_TYPES: Dict[str, str] = {
|
||||||
|
".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||||
|
".odt": "application/vnd.oasis.opendocument.text",
|
||||||
|
".csv": "text/csv",
|
||||||
|
".html": "text/html",
|
||||||
|
".json": "application/json",
|
||||||
|
".md": "text/markdown",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_mime_type(file_path: str) -> str:
|
||||||
|
"""Определяет MIME-тип по расширению файла."""
|
||||||
|
ext = os.path.splitext(file_path)[1].lower()
|
||||||
|
return MIME_TYPES.get(ext, "application/octet-stream")
|
||||||
|
|
||||||
|
|
||||||
|
def _build_html_body(rows: List[ReportRow]) -> str:
|
||||||
|
"""Генерирует HTML-версию тела письма через HTMLFormatter."""
|
||||||
|
from .formatters.html import HTMLFormatter
|
||||||
|
|
||||||
|
formatter = HTMLFormatter()
|
||||||
|
return formatter.format(rows)
|
||||||
|
|
||||||
|
|
||||||
|
def build_message(
|
||||||
|
email_config: EmailConfig,
|
||||||
|
file_path: str,
|
||||||
|
author: str,
|
||||||
|
period: str,
|
||||||
|
rows: List[ReportRow],
|
||||||
|
) -> MIMEMultipart:
|
||||||
|
"""Формирует MIME-письмо с подстановками, телами и вложением."""
|
||||||
|
subject = email_config.subject.replace("{author}", author).replace(
|
||||||
|
"{period}", period
|
||||||
|
)
|
||||||
|
body = email_config.body_text.replace("{author}", author).replace(
|
||||||
|
"{period}", period
|
||||||
|
)
|
||||||
|
|
||||||
|
msg = MIMEMultipart()
|
||||||
|
msg["Subject"] = subject
|
||||||
|
msg["From"] = email_config.from_
|
||||||
|
msg["To"] = ", ".join(email_config.to)
|
||||||
|
if email_config.cc:
|
||||||
|
msg["Cc"] = ", ".join(email_config.cc)
|
||||||
|
|
||||||
|
# Тела письма: plain-text всегда, HTML по флагу
|
||||||
|
body_container = MIMEMultipart("alternative")
|
||||||
|
body_container.attach(MIMEText(body, "plain", "utf-8"))
|
||||||
|
|
||||||
|
if email_config.html:
|
||||||
|
html_body = _build_html_body(rows)
|
||||||
|
body_container.attach(MIMEText(html_body, "html", "utf-8"))
|
||||||
|
|
||||||
|
msg.attach(body_container)
|
||||||
|
|
||||||
|
if email_config.attach:
|
||||||
|
try:
|
||||||
|
with open(file_path, "rb") as fh:
|
||||||
|
attachment = MIMEApplication(fh.read())
|
||||||
|
except OSError:
|
||||||
|
raise RedmineAPIError(
|
||||||
|
f"Не удалось прочитать файл отчёта: {file_path}"
|
||||||
|
) from None
|
||||||
|
attachment.add_header(
|
||||||
|
"Content-Disposition",
|
||||||
|
"attachment",
|
||||||
|
filename=os.path.basename(file_path),
|
||||||
|
)
|
||||||
|
mime_type = _resolve_mime_type(file_path)
|
||||||
|
attachment.set_type(mime_type)
|
||||||
|
msg.attach(attachment)
|
||||||
|
|
||||||
|
return msg
|
||||||
|
|
||||||
|
|
||||||
|
def send_report(
|
||||||
|
email_config: EmailConfig,
|
||||||
|
file_path: str,
|
||||||
|
author: str,
|
||||||
|
period: str,
|
||||||
|
rows: List[ReportRow],
|
||||||
|
) -> None:
|
||||||
|
"""Отправляет сгенерированный отчёт по email через SMTP.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
email_config: Настройки SMTP и письма.
|
||||||
|
file_path: Путь к файлу отчёта для вложения.
|
||||||
|
author: Имя автора (для подстановки в тему/тело).
|
||||||
|
period: Строка периода (для подстановки в тему/тело).
|
||||||
|
rows: Строки отчёта (для HTML-версии тела письма).
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
RedmineAPIError: При любой ошибке соединения или отправки.
|
||||||
|
"""
|
||||||
|
smtp_cfg = email_config.smtp
|
||||||
|
msg = build_message(email_config, file_path, author, period, rows)
|
||||||
|
all_recipients = (
|
||||||
|
list(email_config.to) + list(email_config.cc) + list(email_config.bcc)
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
with smtplib.SMTP(smtp_cfg.host, smtp_cfg.port, timeout=SMTP_TIMEOUT) as server:
|
||||||
|
if smtp_cfg.tls:
|
||||||
|
server.starttls()
|
||||||
|
if smtp_cfg.user:
|
||||||
|
server.login(smtp_cfg.user, smtp_cfg.password)
|
||||||
|
|
||||||
|
server.send_message(
|
||||||
|
msg, from_addr=email_config.from_, to_addrs=all_recipients
|
||||||
|
)
|
||||||
|
except smtplib.SMTPAuthenticationError:
|
||||||
|
raise RedmineAPIError(
|
||||||
|
"Ошибка аутентификации SMTP. Проверьте логин и пароль."
|
||||||
|
) from None
|
||||||
|
except TimeoutError:
|
||||||
|
raise RedmineAPIError("Таймаут соединения с SMTP-сервером.") from None
|
||||||
|
except smtplib.SMTPException as exc:
|
||||||
|
raise RedmineAPIError(f"Ошибка отправки письма: {exc}") from exc
|
||||||
|
except OSError as exc:
|
||||||
|
raise RedmineAPIError(
|
||||||
|
f"Не удалось подключиться к SMTP-серверу {smtp_cfg.host}:{smtp_cfg.port}"
|
||||||
|
) from exc
|
||||||
@@ -45,7 +45,9 @@ def build_grouped_report(
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
# Защитная сортировка -- гарантирует корректную группировку независимо от порядка на входе
|
# Защитная сортировка -- гарантирует корректную группировку независимо от порядка на входе
|
||||||
issue_hours = sorted(issue_hours, key=lambda x: (str(x[0].project), get_version(x[0]), x[0].id))
|
issue_hours = sorted(
|
||||||
|
issue_hours, key=lambda x: (str(x[0].project), get_version(x[0]), x[0].id)
|
||||||
|
)
|
||||||
|
|
||||||
rows: List[ReportRow] = []
|
rows: List[ReportRow] = []
|
||||||
prev_project: str = ""
|
prev_project: str = ""
|
||||||
@@ -67,7 +69,9 @@ def build_grouped_report(
|
|||||||
time_text = ""
|
time_text = ""
|
||||||
|
|
||||||
display_project = project if project != prev_project else ""
|
display_project = project if project != prev_project else ""
|
||||||
display_version = version if (project != prev_project or version != prev_version) else ""
|
display_version = (
|
||||||
|
version if (project != prev_project or version != prev_version) else ""
|
||||||
|
)
|
||||||
|
|
||||||
rows.append(
|
rows.append(
|
||||||
cast(
|
cast(
|
||||||
@@ -122,7 +126,9 @@ def calculate_summary(
|
|||||||
**{f"version:{k}": round(v, 2) for k, v in by_project_version.items()},
|
**{f"version:{k}": round(v, 2) for k, v in by_project_version.items()},
|
||||||
}
|
}
|
||||||
if by_activity:
|
if by_activity:
|
||||||
result.update({f"activity:{k}": round(v, 2) for k, v in by_activity_name.items()})
|
result.update(
|
||||||
|
{f"activity:{k}": round(v, 2) for k, v in by_activity_name.items()}
|
||||||
|
)
|
||||||
|
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
|||||||
190
redmine_reporter/yaml_config.py
Normal file
190
redmine_reporter/yaml_config.py
Normal file
@@ -0,0 +1,190 @@
|
|||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
_ENV_VAR_RE = re.compile(r"\$\{([^}]+)\}")
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_env_vars(value: str) -> str:
|
||||||
|
"""Replace ${VAR} patterns with environment variable values.
|
||||||
|
|
||||||
|
Non-recursive: if ${A} expands to a literal ${B}, ${B} is NOT resolved.
|
||||||
|
Unknown variables are replaced with empty string and a warning is logged.
|
||||||
|
"""
|
||||||
|
if not isinstance(value, str):
|
||||||
|
return value
|
||||||
|
|
||||||
|
def _replacer(match: re.Match) -> str:
|
||||||
|
var_name = match.group(1)
|
||||||
|
env_value = os.environ.get(var_name)
|
||||||
|
if env_value is None:
|
||||||
|
logger.warning(
|
||||||
|
"Environment variable %s is not set, using empty string", var_name
|
||||||
|
)
|
||||||
|
return ""
|
||||||
|
return env_value
|
||||||
|
|
||||||
|
return _ENV_VAR_RE.sub(_replacer, value)
|
||||||
|
|
||||||
|
|
||||||
|
def ensure_config_dir(path: Path | None = None) -> Path:
|
||||||
|
"""Create ~/.config/redmine-reporter/ with 0o700 permissions.
|
||||||
|
|
||||||
|
Returns the path to the config directory.
|
||||||
|
No-op if the directory already exists.
|
||||||
|
"""
|
||||||
|
if path is None:
|
||||||
|
path = Path.home() / ".config" / "redmine-reporter"
|
||||||
|
path.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||||
|
return path
|
||||||
|
|
||||||
|
|
||||||
|
def check_file_permissions(path: Path) -> list[str]:
|
||||||
|
"""Check that a config file has safe permissions (0o600 or stricter).
|
||||||
|
|
||||||
|
Returns a list of warning messages. Empty list means no issues.
|
||||||
|
"""
|
||||||
|
warnings: list[str] = []
|
||||||
|
if not path.exists():
|
||||||
|
return warnings
|
||||||
|
|
||||||
|
mode = path.stat().st_mode & 0o777
|
||||||
|
if mode > 0o600:
|
||||||
|
warnings.append(
|
||||||
|
f"Config file permissions are too open ({mode:04o}). "
|
||||||
|
f"Expected 0600. Fix with: chmod 600 {path}"
|
||||||
|
)
|
||||||
|
return warnings
|
||||||
|
|
||||||
|
|
||||||
|
def expand_filename_template(
|
||||||
|
template: str,
|
||||||
|
*,
|
||||||
|
author: str = "",
|
||||||
|
from_date: str = "",
|
||||||
|
to_date: str = "",
|
||||||
|
ext: str = "",
|
||||||
|
) -> str:
|
||||||
|
"""Expand placeholders in a filename template.
|
||||||
|
|
||||||
|
Supported placeholders:
|
||||||
|
{author} — author name
|
||||||
|
{from} — start date (YYYY-MM-DD)
|
||||||
|
{to} — end date (YYYY-MM-DD)
|
||||||
|
{date} — end date formatted as DD_MM_YYYY
|
||||||
|
{ext} — file extension without dot
|
||||||
|
|
||||||
|
Unknown placeholders are left as-is.
|
||||||
|
"""
|
||||||
|
date_dd_mm_yyyy = ""
|
||||||
|
if to_date:
|
||||||
|
try:
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
dt = datetime.strptime(to_date, "%Y-%m-%d")
|
||||||
|
date_dd_mm_yyyy = dt.strftime("%d_%m_%Y")
|
||||||
|
except ValueError:
|
||||||
|
date_dd_mm_yyyy = to_date
|
||||||
|
|
||||||
|
replacements = {
|
||||||
|
"author": author.replace(" ", "_"),
|
||||||
|
"from": from_date,
|
||||||
|
"to": to_date,
|
||||||
|
"date": date_dd_mm_yyyy,
|
||||||
|
"ext": ext,
|
||||||
|
}
|
||||||
|
|
||||||
|
result = template
|
||||||
|
for key, value in replacements.items():
|
||||||
|
result = result.replace("{" + key + "}", value)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
KNOWN_FORMAT_NAMES = {"xlsx", "odt", "csv", "md", "html", "json"}
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_output_path(
|
||||||
|
output_arg: str | None,
|
||||||
|
*,
|
||||||
|
output_dir: str = "",
|
||||||
|
filename_template: str = "{author}_{from}_{to}.{ext}",
|
||||||
|
default_format: str = "xlsx",
|
||||||
|
author: str = "",
|
||||||
|
from_date: str = "",
|
||||||
|
to_date: str = "",
|
||||||
|
) -> str | None:
|
||||||
|
"""Resolve the final output path from --output argument and config settings.
|
||||||
|
|
||||||
|
Returns None if output_arg is None (meaning no file output, use console).
|
||||||
|
|
||||||
|
Resolution rules:
|
||||||
|
- None → None (console output)
|
||||||
|
- Bare format name (xlsx, odt, csv, md, html, json) → use template path
|
||||||
|
- Path without extension → append .{default_format}
|
||||||
|
- Path with known extension → use as-is
|
||||||
|
- Path with unknown extension → use as-is
|
||||||
|
"""
|
||||||
|
if output_arg is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
arg = output_arg.strip()
|
||||||
|
|
||||||
|
import os
|
||||||
|
|
||||||
|
if arg.lower() in KNOWN_FORMAT_NAMES:
|
||||||
|
ext = arg.lower()
|
||||||
|
resolved_dir = os.path.expanduser(output_dir) if output_dir else "."
|
||||||
|
filename = expand_filename_template(
|
||||||
|
filename_template,
|
||||||
|
author=author,
|
||||||
|
from_date=from_date,
|
||||||
|
to_date=to_date,
|
||||||
|
ext=ext,
|
||||||
|
)
|
||||||
|
return os.path.join(resolved_dir, filename)
|
||||||
|
|
||||||
|
_, ext = os.path.splitext(arg)
|
||||||
|
if not ext:
|
||||||
|
arg = f"{arg}.{default_format}"
|
||||||
|
|
||||||
|
return arg
|
||||||
|
|
||||||
|
|
||||||
|
def save_period_to_config(
|
||||||
|
config_path: str,
|
||||||
|
from_str: str,
|
||||||
|
to_str: str,
|
||||||
|
precision: str,
|
||||||
|
dynamic: bool,
|
||||||
|
) -> None:
|
||||||
|
"""Save committed period to YAML config file.
|
||||||
|
|
||||||
|
Writes period.last_used.from / period.last_used.to.
|
||||||
|
When dynamic=False, also overwrites period.default_from / period.default_to.
|
||||||
|
|
||||||
|
Preserves all other sections unchanged. Creates config file if missing.
|
||||||
|
"""
|
||||||
|
import yaml
|
||||||
|
|
||||||
|
path = Path(config_path)
|
||||||
|
raw: dict = {}
|
||||||
|
if path.exists():
|
||||||
|
with open(path, "r", encoding="utf-8") as fh:
|
||||||
|
raw = yaml.safe_load(fh) or {}
|
||||||
|
|
||||||
|
period = raw.setdefault("period", {})
|
||||||
|
period["last_used"] = {"from": from_str, "to": to_str}
|
||||||
|
|
||||||
|
if not dynamic:
|
||||||
|
period["default_from"] = from_str.split("T")[0] if "T" in from_str else from_str
|
||||||
|
period["default_to"] = to_str.split("T")[0] if "T" in to_str else to_str
|
||||||
|
|
||||||
|
ensure_config_dir(path.parent)
|
||||||
|
with open(path, "w", encoding="utf-8") as fh:
|
||||||
|
yaml.dump(
|
||||||
|
raw, fh, allow_unicode=True, default_flow_style=False, sort_keys=False
|
||||||
|
)
|
||||||
|
path.chmod(0o600)
|
||||||
1102
tests/test_cli.py
1102
tests/test_cli.py
File diff suppressed because it is too large
Load Diff
@@ -157,7 +157,9 @@ def test_fetch_uses_username_password_when_no_api_key(mock_redmine_class):
|
|||||||
assert "key" not in kwargs
|
assert "key" not in kwargs
|
||||||
|
|
||||||
|
|
||||||
@mock.patch.dict(os.environ, {**PASSWORD_ENV, "REDMINE_VERIFY": "/tmp/redmine-ca.pem"}, clear=True)
|
@mock.patch.dict(
|
||||||
|
os.environ, {**PASSWORD_ENV, "REDMINE_VERIFY": "/tmp/redmine-ca.pem"}, clear=True
|
||||||
|
)
|
||||||
@mock.patch("redmine_reporter.client.Redmine")
|
@mock.patch("redmine_reporter.client.Redmine")
|
||||||
def test_fetch_uses_custom_verify_path(mock_redmine_class):
|
def test_fetch_uses_custom_verify_path(mock_redmine_class):
|
||||||
mock_redmine = mock_redmine_class.return_value
|
mock_redmine = mock_redmine_class.return_value
|
||||||
@@ -390,7 +392,9 @@ def test_fetch_mounts_retry_adapter(mock_redmine_class):
|
|||||||
assert "http://" in prefixes
|
assert "http://" in prefixes
|
||||||
|
|
||||||
# Проверяем retry-конфигурацию адаптера
|
# Проверяем retry-конфигурацию адаптера
|
||||||
https_adapter = next(call.args[1] for call in mount_calls if call.args[0] == "https://")
|
https_adapter = next(
|
||||||
|
call.args[1] for call in mount_calls if call.args[0] == "https://"
|
||||||
|
)
|
||||||
max_retries = https_adapter.max_retries
|
max_retries = https_adapter.max_retries
|
||||||
assert max_retries.total == 3
|
assert max_retries.total == 3
|
||||||
assert 429 in max_retries.status_forcelist
|
assert 429 in max_retries.status_forcelist
|
||||||
@@ -422,7 +426,9 @@ def test_fetch_chunks_large_issue_count(mock_redmine_class):
|
|||||||
ids_str = kwargs.get("issue_id", "")
|
ids_str = kwargs.get("issue_id", "")
|
||||||
call_chunks.append(ids_str)
|
call_chunks.append(ids_str)
|
||||||
ids = [int(x) for x in ids_str.split(",")]
|
ids = [int(x) for x in ids_str.split(",")]
|
||||||
return [mock.MagicMock(id=i, project="P", subject="T", status="New") for i in ids]
|
return [
|
||||||
|
mock.MagicMock(id=i, project="P", subject="T", status="New") for i in ids
|
||||||
|
]
|
||||||
|
|
||||||
mock_redmine.issue.filter.side_effect = issue_filter_side_effect
|
mock_redmine.issue.filter.side_effect = issue_filter_side_effect
|
||||||
|
|
||||||
@@ -435,3 +441,253 @@ def test_fetch_chunks_large_issue_count(mock_redmine_class):
|
|||||||
assert len(call_chunks[2].split(",")) == 50
|
assert len(call_chunks[2].split(",")) == 50
|
||||||
assert result is not None
|
assert result is not None
|
||||||
assert len(result) == 250
|
assert len(result) == 250
|
||||||
|
|
||||||
|
|
||||||
|
# -- #47: Дедупликация time entries по datetime --
|
||||||
|
|
||||||
|
|
||||||
|
@mock.patch.dict(os.environ, PASSWORD_ENV, clear=True)
|
||||||
|
@mock.patch("redmine_reporter.client.Redmine")
|
||||||
|
def test_dedup_filters_entries_created_before_cutoff(mock_redmine_class):
|
||||||
|
"""Записи с created_on/updated_on раньше dedup_before исключаются."""
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
mock_redmine = mock_redmine_class.return_value
|
||||||
|
_configure_current_user(mock_redmine, user_id=123)
|
||||||
|
|
||||||
|
dedup_cutoff = datetime(2026, 7, 1, 12, 0, 0, tzinfo=timezone.utc)
|
||||||
|
|
||||||
|
e1 = mock.MagicMock()
|
||||||
|
e1.issue.id = 1
|
||||||
|
e1.hours = 2.0
|
||||||
|
e1.created_on = datetime(2026, 7, 1, 10, 0, 0, tzinfo=timezone.utc)
|
||||||
|
e1.updated_on = datetime(2026, 7, 1, 10, 0, 0, tzinfo=timezone.utc)
|
||||||
|
|
||||||
|
e2 = mock.MagicMock()
|
||||||
|
e2.issue.id = 2
|
||||||
|
e2.hours = 1.0
|
||||||
|
e2.created_on = datetime(2026, 7, 1, 14, 0, 0, tzinfo=timezone.utc)
|
||||||
|
e2.updated_on = datetime(2026, 7, 1, 14, 0, 0, tzinfo=timezone.utc)
|
||||||
|
|
||||||
|
mock_redmine.time_entry.filter.return_value = [e1, e2]
|
||||||
|
|
||||||
|
mock_issue1 = mock.MagicMock()
|
||||||
|
mock_issue1.id = 1
|
||||||
|
mock_issue1.project = "P"
|
||||||
|
mock_issue2 = mock.MagicMock()
|
||||||
|
mock_issue2.id = 2
|
||||||
|
mock_issue2.project = "P"
|
||||||
|
mock_redmine.issue.filter.return_value = [mock_issue1, mock_issue2]
|
||||||
|
|
||||||
|
result = fetch_issues_with_spent_time(
|
||||||
|
"2026-07-01", "2026-07-01", dedup_before=dedup_cutoff
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result is not None
|
||||||
|
assert len(result) == 1
|
||||||
|
assert result[0][0].id == 2
|
||||||
|
|
||||||
|
|
||||||
|
@mock.patch.dict(os.environ, PASSWORD_ENV, clear=True)
|
||||||
|
@mock.patch("redmine_reporter.client.Redmine")
|
||||||
|
def test_dedup_filters_entries_with_old_created_even_if_updated_recently(
|
||||||
|
mock_redmine_class,
|
||||||
|
):
|
||||||
|
"""Записи с created_on < cutoff исключаются даже при updated_on >= cutoff (AND-логика)."""
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
mock_redmine = mock_redmine_class.return_value
|
||||||
|
_configure_current_user(mock_redmine, user_id=123)
|
||||||
|
|
||||||
|
dedup_cutoff = datetime(2026, 7, 1, 12, 0, 0, tzinfo=timezone.utc)
|
||||||
|
|
||||||
|
e1 = mock.MagicMock()
|
||||||
|
e1.issue.id = 1
|
||||||
|
e1.hours = 2.0
|
||||||
|
e1.created_on = datetime(2026, 7, 1, 10, 0, 0, tzinfo=timezone.utc)
|
||||||
|
e1.updated_on = datetime(2026, 7, 1, 15, 0, 0, tzinfo=timezone.utc)
|
||||||
|
|
||||||
|
mock_redmine.time_entry.filter.return_value = [e1]
|
||||||
|
mock_redmine.issue.filter.return_value = []
|
||||||
|
|
||||||
|
result = fetch_issues_with_spent_time(
|
||||||
|
"2026-07-01", "2026-07-01", dedup_before=dedup_cutoff
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result is None
|
||||||
|
|
||||||
|
|
||||||
|
@mock.patch.dict(os.environ, PASSWORD_ENV, clear=True)
|
||||||
|
@mock.patch("redmine_reporter.client.Redmine")
|
||||||
|
def test_dedup_keeps_entries_created_after_cutoff(mock_redmine_class):
|
||||||
|
"""Записи с created_on/updated_on >= dedup_before сохраняются."""
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
mock_redmine = mock_redmine_class.return_value
|
||||||
|
_configure_current_user(mock_redmine, user_id=123)
|
||||||
|
|
||||||
|
dedup_cutoff = datetime(2026, 7, 1, 12, 0, 0, tzinfo=timezone.utc)
|
||||||
|
|
||||||
|
e1 = mock.MagicMock()
|
||||||
|
e1.issue.id = 1
|
||||||
|
e1.hours = 2.0
|
||||||
|
e1.created_on = datetime(2026, 7, 1, 12, 0, 0, tzinfo=timezone.utc)
|
||||||
|
e1.updated_on = datetime(2026, 7, 1, 12, 0, 0, tzinfo=timezone.utc)
|
||||||
|
|
||||||
|
mock_redmine.time_entry.filter.return_value = [e1]
|
||||||
|
|
||||||
|
mock_issue1 = mock.MagicMock()
|
||||||
|
mock_issue1.id = 1
|
||||||
|
mock_issue1.project = "P"
|
||||||
|
mock_issue1.subject = "T"
|
||||||
|
mock_issue1.status = "New"
|
||||||
|
mock_redmine.issue.filter.return_value = [mock_issue1]
|
||||||
|
|
||||||
|
result = fetch_issues_with_spent_time(
|
||||||
|
"2026-07-01", "2026-07-01", dedup_before=dedup_cutoff
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result is not None
|
||||||
|
assert len(result) == 1
|
||||||
|
|
||||||
|
|
||||||
|
@mock.patch.dict(os.environ, PASSWORD_ENV, clear=True)
|
||||||
|
@mock.patch("redmine_reporter.client.Redmine")
|
||||||
|
def test_dedup_entries_without_created_on_are_kept(mock_redmine_class):
|
||||||
|
"""Записи без created_on/updated_on не фильтруются (сохраняются)."""
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
mock_redmine = mock_redmine_class.return_value
|
||||||
|
_configure_current_user(mock_redmine, user_id=123)
|
||||||
|
|
||||||
|
dedup_cutoff = datetime(2026, 7, 1, 12, 0, 0, tzinfo=timezone.utc)
|
||||||
|
|
||||||
|
e1 = mock.MagicMock()
|
||||||
|
e1.issue.id = 1
|
||||||
|
e1.hours = 2.0
|
||||||
|
e1.created_on = None
|
||||||
|
e1.updated_on = None
|
||||||
|
|
||||||
|
mock_redmine.time_entry.filter.return_value = [e1]
|
||||||
|
|
||||||
|
mock_issue1 = mock.MagicMock()
|
||||||
|
mock_issue1.id = 1
|
||||||
|
mock_issue1.project = "P"
|
||||||
|
mock_issue1.subject = "T"
|
||||||
|
mock_issue1.status = "New"
|
||||||
|
mock_redmine.issue.filter.return_value = [mock_issue1]
|
||||||
|
|
||||||
|
result = fetch_issues_with_spent_time(
|
||||||
|
"2026-07-01", "2026-07-01", dedup_before=dedup_cutoff
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result is not None
|
||||||
|
assert len(result) == 1
|
||||||
|
|
||||||
|
|
||||||
|
@mock.patch.dict(os.environ, PASSWORD_ENV, clear=True)
|
||||||
|
@mock.patch("redmine_reporter.client.Redmine")
|
||||||
|
def test_dedup_handles_string_created_on(mock_redmine_class):
|
||||||
|
"""created_on может быть строкой ISO — парсим корректно."""
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
mock_redmine = mock_redmine_class.return_value
|
||||||
|
_configure_current_user(mock_redmine, user_id=123)
|
||||||
|
|
||||||
|
dedup_cutoff = datetime(2026, 7, 1, 12, 0, 0, tzinfo=timezone.utc)
|
||||||
|
|
||||||
|
e1 = mock.MagicMock()
|
||||||
|
e1.issue.id = 1
|
||||||
|
e1.hours = 2.0
|
||||||
|
e1.created_on = "2026-07-01T10:00:00Z"
|
||||||
|
e1.updated_on = "2026-07-01T10:00:00Z"
|
||||||
|
|
||||||
|
mock_redmine.time_entry.filter.return_value = [e1]
|
||||||
|
mock_redmine.issue.filter.return_value = []
|
||||||
|
|
||||||
|
result = fetch_issues_with_spent_time(
|
||||||
|
"2026-07-01", "2026-07-01", dedup_before=dedup_cutoff
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result is None
|
||||||
|
|
||||||
|
|
||||||
|
@mock.patch.dict(os.environ, PASSWORD_ENV, clear=True)
|
||||||
|
@mock.patch("redmine_reporter.client.Redmine")
|
||||||
|
def test_no_dedup_when_cutoff_is_none(mock_redmine_class):
|
||||||
|
"""Без dedup_before фильтрация не применяется."""
|
||||||
|
mock_redmine = mock_redmine_class.return_value
|
||||||
|
_configure_current_user(mock_redmine, user_id=123)
|
||||||
|
|
||||||
|
e1 = mock.MagicMock()
|
||||||
|
e1.issue.id = 1
|
||||||
|
e1.hours = 2.0
|
||||||
|
e1.created_on = None
|
||||||
|
e1.updated_on = None
|
||||||
|
|
||||||
|
mock_redmine.time_entry.filter.return_value = [e1]
|
||||||
|
|
||||||
|
mock_issue1 = mock.MagicMock()
|
||||||
|
mock_issue1.id = 1
|
||||||
|
mock_issue1.project = "P"
|
||||||
|
mock_issue1.subject = "T"
|
||||||
|
mock_issue1.status = "New"
|
||||||
|
mock_redmine.issue.filter.return_value = [mock_issue1]
|
||||||
|
|
||||||
|
result = fetch_issues_with_spent_time("2026-07-01", "2026-07-01", dedup_before=None)
|
||||||
|
|
||||||
|
assert result is not None
|
||||||
|
assert len(result) == 1
|
||||||
|
|
||||||
|
|
||||||
|
@mock.patch.dict(os.environ, PASSWORD_ENV, clear=True)
|
||||||
|
@mock.patch("redmine_reporter.client.Redmine")
|
||||||
|
def test_dedup_mixed_entries_correct_filtering(mock_redmine_class):
|
||||||
|
"""Смешанные записи: старые исключаются, новые сохраняются, аки идут."""
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
mock_redmine = mock_redmine_class.return_value
|
||||||
|
_configure_current_user(mock_redmine, user_id=123)
|
||||||
|
|
||||||
|
dedup_cutoff = datetime(2026, 7, 1, 12, 0, 0, tzinfo=timezone.utc)
|
||||||
|
|
||||||
|
e_old = mock.MagicMock()
|
||||||
|
e_old.issue.id = 10
|
||||||
|
e_old.hours = 1.0
|
||||||
|
e_old.created_on = datetime(2026, 7, 1, 9, 0, 0, tzinfo=timezone.utc)
|
||||||
|
e_old.updated_on = datetime(2026, 7, 1, 9, 0, 0, tzinfo=timezone.utc)
|
||||||
|
|
||||||
|
e_new = mock.MagicMock()
|
||||||
|
e_new.issue.id = 20
|
||||||
|
e_new.hours = 3.0
|
||||||
|
e_new.created_on = datetime(2026, 7, 1, 14, 0, 0, tzinfo=timezone.utc)
|
||||||
|
e_new.updated_on = datetime(2026, 7, 1, 14, 0, 0, tzinfo=timezone.utc)
|
||||||
|
|
||||||
|
e_akiy = mock.MagicMock()
|
||||||
|
e_akiy.issue.id = 30
|
||||||
|
e_akiy.hours = 5.0
|
||||||
|
e_akiy.created_on = None
|
||||||
|
e_akiy.updated_on = None
|
||||||
|
|
||||||
|
mock_redmine.time_entry.filter.return_value = [e_old, e_new, e_akiy]
|
||||||
|
|
||||||
|
mock_issue_new = mock.MagicMock()
|
||||||
|
mock_issue_new.id = 20
|
||||||
|
mock_issue_new.project = "P"
|
||||||
|
mock_issue_new.subject = "T"
|
||||||
|
mock_issue_new.status = "New"
|
||||||
|
mock_issue_akiy = mock.MagicMock()
|
||||||
|
mock_issue_akiy.id = 30
|
||||||
|
mock_issue_akiy.project = "P"
|
||||||
|
mock_issue_akiy.subject = "T2"
|
||||||
|
mock_issue_akiy.status = "New"
|
||||||
|
mock_redmine.issue.filter.return_value = [mock_issue_new, mock_issue_akiy]
|
||||||
|
|
||||||
|
result = fetch_issues_with_spent_time(
|
||||||
|
"2026-07-01", "2026-07-01", dedup_before=dedup_cutoff
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result is not None
|
||||||
|
assert len(result) == 2
|
||||||
|
ids = {r[0].id for r in result}
|
||||||
|
assert ids == {20, 30}
|
||||||
|
|||||||
@@ -1,9 +1,16 @@
|
|||||||
import os
|
import os
|
||||||
|
import tempfile
|
||||||
|
from pathlib import Path
|
||||||
from unittest import mock
|
from unittest import mock
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from redmine_reporter.config import DEFAULT_REDMINE_VERIFY, Config
|
from redmine_reporter.config import (
|
||||||
|
DEFAULT_REDMINE_VERIFY,
|
||||||
|
AppConfig,
|
||||||
|
Config,
|
||||||
|
EmailConfig,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@mock.patch.dict(
|
@mock.patch.dict(
|
||||||
@@ -72,21 +79,29 @@ def test_get_default_date_range_from_env():
|
|||||||
assert Config.get_default_date_range() == "2026-01-01--2026-01-31"
|
assert Config.get_default_date_range() == "2026-01-01--2026-01-31"
|
||||||
|
|
||||||
|
|
||||||
|
@mock.patch.dict(
|
||||||
|
os.environ,
|
||||||
|
{"DEFAULT_FROM_DATE": "2026-01-01"},
|
||||||
|
clear=True,
|
||||||
|
)
|
||||||
|
def test_get_default_date_range_from_env_without_to():
|
||||||
|
"""Если DEFAULT_TO_DATE не задан, конец периода — сегодня."""
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
|
today = date.today().isoformat()
|
||||||
|
assert Config.get_default_date_range() == f"2026-01-01--{today}"
|
||||||
|
|
||||||
|
|
||||||
@mock.patch.dict(os.environ, {}, clear=True)
|
@mock.patch.dict(os.environ, {}, clear=True)
|
||||||
def test_get_default_date_range_fallback():
|
def test_get_default_date_range_fallback():
|
||||||
"""Если даты не заданы -- используется текущий месяц."""
|
"""Если даты не заданы -- используется текущий месяц с начала до сегодня."""
|
||||||
from datetime import date, timedelta
|
from datetime import date
|
||||||
|
|
||||||
today = date.today()
|
today = date.today()
|
||||||
start = today.replace(day=1)
|
start = today.replace(day=1)
|
||||||
if today.month == 12:
|
|
||||||
next_month = today.replace(year=today.year + 1, month=1, day=1)
|
|
||||||
else:
|
|
||||||
next_month = today.replace(month=today.month + 1, day=1)
|
|
||||||
end = next_month - timedelta(days=1)
|
|
||||||
|
|
||||||
result = Config.get_default_date_range()
|
result = Config.get_default_date_range()
|
||||||
assert result == f"{start.isoformat()}--{end.isoformat()}"
|
assert result == f"{start.isoformat()}--{today.isoformat()}"
|
||||||
|
|
||||||
|
|
||||||
@mock.patch.dict(os.environ, {}, clear=True)
|
@mock.patch.dict(os.environ, {}, clear=True)
|
||||||
@@ -133,3 +148,585 @@ def test_env_var_takes_priority_over_dotenv(mock_load):
|
|||||||
def test_get_redmine_password_strips_whitespace():
|
def test_get_redmine_password_strips_whitespace():
|
||||||
"""Пароль обрезается от whitespace, как и все остальные геттеры."""
|
"""Пароль обрезается от whitespace, как и все остальные геттеры."""
|
||||||
assert Config.get_redmine_password() == "secret123"
|
assert Config.get_redmine_password() == "secret123"
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# AppConfig tests — YAML config loading
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
FULL_YAML = """\
|
||||||
|
redmine:
|
||||||
|
url: https://redmine.example.com/
|
||||||
|
api_key: ${MISSING_API_KEY_FOR_TEST}
|
||||||
|
author: "Тестовый Автор"
|
||||||
|
verify_ssl: false
|
||||||
|
|
||||||
|
period:
|
||||||
|
precision: datetime
|
||||||
|
default_from: "2026-06-01"
|
||||||
|
default_to: "2026-06-30"
|
||||||
|
dynamic: true
|
||||||
|
last_used:
|
||||||
|
from: "2026-06-30T09:00:00"
|
||||||
|
to: "2026-06-30T12:00:00"
|
||||||
|
|
||||||
|
output:
|
||||||
|
dir: ~/reports
|
||||||
|
filename: "{author}_{from}_{to}.{ext}"
|
||||||
|
default_format: xlsx
|
||||||
|
|
||||||
|
email:
|
||||||
|
smtp:
|
||||||
|
host: smtp.example.com
|
||||||
|
port: 587
|
||||||
|
user: bot@example.com
|
||||||
|
password: ${MISSING_SMTP_PASSWORD_FOR_TEST}
|
||||||
|
tls: true
|
||||||
|
from: bot@example.com
|
||||||
|
to:
|
||||||
|
- boss@example.com
|
||||||
|
cc: []
|
||||||
|
bcc: []
|
||||||
|
subject: "Отчёт {author} за {period}"
|
||||||
|
body_text: "Во вложении отчёт."
|
||||||
|
attach: true
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class TestAppConfigFromYaml:
|
||||||
|
"""Tests for AppConfig.from_yaml()."""
|
||||||
|
|
||||||
|
def test_loads_all_sections_from_valid_yaml(self):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
yaml_path = Path(tmp) / "config.yml"
|
||||||
|
yaml_path.write_text(FULL_YAML)
|
||||||
|
|
||||||
|
cfg = AppConfig.from_yaml(yaml_path)
|
||||||
|
|
||||||
|
assert cfg.redmine_url == "https://redmine.example.com/"
|
||||||
|
assert cfg.redmine_api_key == "" # ${MISSING_API_KEY_FOR_TEST} not set
|
||||||
|
assert cfg.redmine_author == "Тестовый Автор"
|
||||||
|
assert cfg.redmine_verify is False
|
||||||
|
assert cfg.period_precision == "datetime"
|
||||||
|
assert cfg.period_default_from == "2026-06-01"
|
||||||
|
assert cfg.period_default_to == "2026-06-30"
|
||||||
|
assert cfg.period_dynamic is True
|
||||||
|
assert cfg.period_last_used_from == "2026-06-30T09:00:00"
|
||||||
|
assert cfg.period_last_used_to == "2026-06-30T12:00:00"
|
||||||
|
assert cfg.output_dir == "~/reports"
|
||||||
|
assert cfg.output_filename == "{author}_{from}_{to}.{ext}"
|
||||||
|
assert cfg.output_default_format == "xlsx"
|
||||||
|
assert cfg.email.smtp.host == "smtp.example.com"
|
||||||
|
assert cfg.email.smtp.port == 587
|
||||||
|
assert cfg.email.smtp.user == "bot@example.com"
|
||||||
|
assert cfg.email.smtp.password == ""
|
||||||
|
assert cfg.email.smtp.tls is True
|
||||||
|
assert cfg.email.from_ == "bot@example.com"
|
||||||
|
assert cfg.email.to == ["boss@example.com"]
|
||||||
|
assert cfg.email.subject == "Отчёт {author} за {period}"
|
||||||
|
|
||||||
|
def test_partial_yaml_uses_defaults_for_missing(self):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
yaml_path = Path(tmp) / "config.yml"
|
||||||
|
yaml_path.write_text("redmine:\n url: https://x.com/\n")
|
||||||
|
|
||||||
|
cfg = AppConfig.from_yaml(yaml_path)
|
||||||
|
|
||||||
|
assert cfg.redmine_url == "https://x.com/"
|
||||||
|
# defaults for everything else
|
||||||
|
assert cfg.redmine_author == ""
|
||||||
|
assert cfg.period_precision == "date"
|
||||||
|
assert cfg.output_dir == ""
|
||||||
|
assert cfg.email.to == []
|
||||||
|
|
||||||
|
def test_empty_file_returns_all_defaults(self):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
yaml_path = Path(tmp) / "config.yml"
|
||||||
|
yaml_path.write_text("")
|
||||||
|
|
||||||
|
cfg = AppConfig.from_yaml(yaml_path)
|
||||||
|
|
||||||
|
assert cfg.redmine_url == ""
|
||||||
|
assert cfg.redmine_api_key == ""
|
||||||
|
assert cfg.period_precision == "date"
|
||||||
|
|
||||||
|
def test_file_not_found_returns_all_defaults(self):
|
||||||
|
cfg = AppConfig.from_yaml("/nonexistent/path/config.yml")
|
||||||
|
assert cfg.redmine_url == ""
|
||||||
|
|
||||||
|
@mock.patch.dict(os.environ, {"REDMINE_API_KEY": "secret-token"}, clear=True)
|
||||||
|
def test_env_var_resolved_in_yaml(self):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
yaml_path = Path(tmp) / "config.yml"
|
||||||
|
yaml_path.write_text("redmine:\n api_key: ${REDMINE_API_KEY}\n")
|
||||||
|
|
||||||
|
cfg = AppConfig.from_yaml(yaml_path)
|
||||||
|
|
||||||
|
assert cfg.redmine_api_key == "secret-token"
|
||||||
|
|
||||||
|
def test_verify_ssl_true_returns_default_ca_path(self):
|
||||||
|
"""verify_ssl: true → DEFAULT_REDMINE_VERIFY (путь), не Python True."""
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
yaml_path = Path(tmp) / "config.yml"
|
||||||
|
yaml_path.write_text("redmine:\n verify_ssl: true\n")
|
||||||
|
|
||||||
|
cfg = AppConfig.from_yaml(yaml_path)
|
||||||
|
|
||||||
|
assert cfg.redmine_verify == DEFAULT_REDMINE_VERIFY
|
||||||
|
assert cfg.redmine_verify is not True # не бул!
|
||||||
|
|
||||||
|
def test_verify_ssl_false_returns_false(self):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
yaml_path = Path(tmp) / "config.yml"
|
||||||
|
yaml_path.write_text("redmine:\n verify_ssl: false\n")
|
||||||
|
|
||||||
|
cfg = AppConfig.from_yaml(yaml_path)
|
||||||
|
|
||||||
|
assert cfg.redmine_verify is False
|
||||||
|
|
||||||
|
def test_missing_env_var_logs_warning(self, caplog):
|
||||||
|
import logging
|
||||||
|
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
yaml_path = Path(tmp) / "config.yml"
|
||||||
|
yaml_path.write_text("redmine:\n api_key: ${MISSING_KEY}\n")
|
||||||
|
|
||||||
|
with caplog.at_level(logging.WARNING):
|
||||||
|
cfg = AppConfig.from_yaml(yaml_path)
|
||||||
|
|
||||||
|
assert cfg.redmine_api_key == ""
|
||||||
|
assert "MISSING_KEY" in caplog.text
|
||||||
|
|
||||||
|
def test_unknown_top_level_key_logs_warning(self, caplog):
|
||||||
|
import logging
|
||||||
|
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
yaml_path = Path(tmp) / "config.yml"
|
||||||
|
yaml_path.write_text("unknown_section:\n foo: bar\n")
|
||||||
|
|
||||||
|
with caplog.at_level(logging.WARNING):
|
||||||
|
AppConfig.from_yaml(yaml_path)
|
||||||
|
|
||||||
|
assert "unknown_section" in caplog.text
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Config priority chain tests — YAML fallback
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
class TestConfigYamlFallback:
|
||||||
|
"""Tests that Config.get_*() falls back to YAML when env/CLI not set."""
|
||||||
|
|
||||||
|
@mock.patch.dict(os.environ, {}, clear=True)
|
||||||
|
def test_url_from_yaml_when_no_env_or_cli(self):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
yaml_path = Path(tmp) / "config.yml"
|
||||||
|
yaml_path.write_text("redmine:\n url: https://yaml-redmine.example.com/\n")
|
||||||
|
|
||||||
|
Config._cli_url = None
|
||||||
|
Config._app = AppConfig.from_yaml(yaml_path)
|
||||||
|
|
||||||
|
assert Config.get_redmine_url() == "https://yaml-redmine.example.com"
|
||||||
|
|
||||||
|
@mock.patch.dict(os.environ, {}, clear=True)
|
||||||
|
def test_cli_beats_yaml(self):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
yaml_path = Path(tmp) / "config.yml"
|
||||||
|
yaml_path.write_text("redmine:\n url: https://yaml-redmine.example.com/\n")
|
||||||
|
|
||||||
|
Config._app = AppConfig.from_yaml(yaml_path)
|
||||||
|
Config.set_redmine_url("https://cli-override.example.com")
|
||||||
|
|
||||||
|
assert Config.get_redmine_url() == "https://cli-override.example.com"
|
||||||
|
|
||||||
|
@mock.patch.dict(
|
||||||
|
os.environ, {"REDMINE_URL": "https://env-redmine.example.com/"}, clear=True
|
||||||
|
)
|
||||||
|
def test_env_beats_yaml(self):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
yaml_path = Path(tmp) / "config.yml"
|
||||||
|
yaml_path.write_text("redmine:\n url: https://yaml-redmine.example.com/\n")
|
||||||
|
|
||||||
|
Config._cli_url = None
|
||||||
|
Config._app = AppConfig.from_yaml(yaml_path)
|
||||||
|
|
||||||
|
assert Config.get_redmine_url() == "https://env-redmine.example.com"
|
||||||
|
|
||||||
|
@mock.patch.dict(os.environ, {}, clear=True)
|
||||||
|
def test_date_range_from_yaml(self):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
yaml_path = Path(tmp) / "config.yml"
|
||||||
|
yaml_path.write_text(
|
||||||
|
"period:\n default_from: '2026-03-01'\n default_to: '2026-03-15'\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
Config._app = AppConfig.from_yaml(yaml_path)
|
||||||
|
|
||||||
|
assert Config.get_default_date_range() == "2026-03-01--2026-03-15"
|
||||||
|
|
||||||
|
@mock.patch.dict(os.environ, {}, clear=True)
|
||||||
|
def test_author_from_yaml(self):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
yaml_path = Path(tmp) / "config.yml"
|
||||||
|
yaml_path.write_text("redmine:\n author: 'Автор Из Ямла'\n")
|
||||||
|
|
||||||
|
Config._app = AppConfig.from_yaml(yaml_path)
|
||||||
|
|
||||||
|
assert Config.get_author("") == "Автор Из Ямла"
|
||||||
|
|
||||||
|
@mock.patch.dict(os.environ, {}, clear=True)
|
||||||
|
def test_validate_passes_with_yaml_url_and_api_key(self):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
yaml_path = Path(tmp) / "config.yml"
|
||||||
|
yaml_path.write_text(
|
||||||
|
"redmine:\n url: https://yaml.example.com/\n api_key: yaml-token\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
Config._cli_url = None
|
||||||
|
Config._cli_api_key = None
|
||||||
|
Config._app = AppConfig.from_yaml(yaml_path)
|
||||||
|
|
||||||
|
# Не должно быть исключения
|
||||||
|
Config.validate()
|
||||||
|
|
||||||
|
@mock.patch.dict(os.environ, {}, clear=True)
|
||||||
|
def test_default_date_range_env_beats_yaml(self):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
yaml_path = Path(tmp) / "config.yml"
|
||||||
|
yaml_path.write_text(
|
||||||
|
"period:\n default_from: '2026-03-01'\n default_to: '2026-03-15'\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
Config._app = AppConfig.from_yaml(yaml_path)
|
||||||
|
|
||||||
|
with mock.patch.dict(
|
||||||
|
os.environ,
|
||||||
|
{"DEFAULT_FROM_DATE": "2026-07-01", "DEFAULT_TO_DATE": "2026-07-15"},
|
||||||
|
clear=True,
|
||||||
|
):
|
||||||
|
assert Config.get_default_date_range() == "2026-07-01--2026-07-15"
|
||||||
|
|
||||||
|
|
||||||
|
class TestConfigPeriodPrecision:
|
||||||
|
"""Tests for period.precision and period.last_used."""
|
||||||
|
|
||||||
|
@mock.patch.dict(os.environ, {}, clear=True)
|
||||||
|
def test_get_period_precision_defaults_to_date(self):
|
||||||
|
"""Без YAML-конфига precision == 'date'."""
|
||||||
|
Config._app = None
|
||||||
|
assert Config.get_period_precision() == "date"
|
||||||
|
|
||||||
|
@mock.patch.dict(os.environ, {}, clear=True)
|
||||||
|
def test_get_period_precision_from_yaml(self):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
yaml_path = Path(tmp) / "config.yml"
|
||||||
|
yaml_path.write_text("period:\n precision: datetime\n")
|
||||||
|
|
||||||
|
Config._app = AppConfig.from_yaml(yaml_path)
|
||||||
|
assert Config.get_period_precision() == "datetime"
|
||||||
|
|
||||||
|
@mock.patch.dict(os.environ, {}, clear=True)
|
||||||
|
def test_get_last_used_from_yaml(self):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
yaml_path = Path(tmp) / "config.yml"
|
||||||
|
yaml_path.write_text(
|
||||||
|
"period:\n last_used:\n from: '2026-06-30T09:00:00'\n to: '2026-06-30T12:00:00'\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
Config._app = AppConfig.from_yaml(yaml_path)
|
||||||
|
assert Config.get_last_used_from() == "2026-06-30T09:00:00"
|
||||||
|
assert Config.get_last_used_to() == "2026-06-30T12:00:00"
|
||||||
|
|
||||||
|
@mock.patch.dict(os.environ, {}, clear=True)
|
||||||
|
def test_get_last_used_returns_empty_when_not_set(self):
|
||||||
|
Config._app = AppConfig()
|
||||||
|
assert Config.get_last_used_from() == ""
|
||||||
|
assert Config.get_last_used_to() == ""
|
||||||
|
|
||||||
|
@mock.patch.dict(os.environ, {}, clear=True)
|
||||||
|
def test_yaml_loads_last_used_field(self):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
yaml_path = Path(tmp) / "config.yml"
|
||||||
|
yaml_path.write_text(
|
||||||
|
"period:\n last_used:\n from: '2026-07-01T08:00:00'\n to: '2026-07-01T18:00:00'\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
cfg = AppConfig.from_yaml(yaml_path)
|
||||||
|
assert cfg.period_last_used_from == "2026-07-01T08:00:00"
|
||||||
|
assert cfg.period_last_used_to == "2026-07-01T18:00:00"
|
||||||
|
|
||||||
|
@mock.patch.dict(os.environ, {}, clear=True)
|
||||||
|
def test_yaml_without_last_used_has_empty_fields(self):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
yaml_path = Path(tmp) / "config.yml"
|
||||||
|
yaml_path.write_text("period:\n precision: date\n")
|
||||||
|
|
||||||
|
cfg = AppConfig.from_yaml(yaml_path)
|
||||||
|
assert cfg.period_last_used_from == ""
|
||||||
|
assert cfg.period_last_used_to == ""
|
||||||
|
|
||||||
|
|
||||||
|
class TestComputeNextPeriod:
|
||||||
|
"""Tests for compute_next_period()."""
|
||||||
|
|
||||||
|
def test_full_month_goes_to_next_full_month(self):
|
||||||
|
from redmine_reporter.config import compute_next_period
|
||||||
|
|
||||||
|
nf, nt = compute_next_period("2026-06-01", "2026-06-30", "date")
|
||||||
|
assert nf == "2026-07-01"
|
||||||
|
assert nt == "2026-07-31"
|
||||||
|
|
||||||
|
def test_december_to_next_year_january(self):
|
||||||
|
from redmine_reporter.config import compute_next_period
|
||||||
|
|
||||||
|
nf, nt = compute_next_period("2025-12-01", "2025-12-31", "date")
|
||||||
|
assert nf == "2026-01-01"
|
||||||
|
assert nt == "2026-01-31"
|
||||||
|
|
||||||
|
def test_february_2026_non_leap_to_march(self):
|
||||||
|
from redmine_reporter.config import compute_next_period
|
||||||
|
|
||||||
|
nf, nt = compute_next_period("2026-02-01", "2026-02-28", "date")
|
||||||
|
assert nf == "2026-03-01"
|
||||||
|
assert nt == "2026-03-31"
|
||||||
|
|
||||||
|
def test_arbitrary_range_same_length_from_to_plus_one(self):
|
||||||
|
from redmine_reporter.config import compute_next_period
|
||||||
|
|
||||||
|
nf, nt = compute_next_period("2026-06-15", "2026-06-20", "date")
|
||||||
|
assert nf == "2026-06-21"
|
||||||
|
assert nt == "2026-06-26"
|
||||||
|
|
||||||
|
def test_single_day_range_moves_one_day(self):
|
||||||
|
from redmine_reporter.config import compute_next_period
|
||||||
|
|
||||||
|
nf, nt = compute_next_period("2026-06-15", "2026-06-15", "date")
|
||||||
|
assert nf == "2026-06-16"
|
||||||
|
assert nt == "2026-06-16"
|
||||||
|
|
||||||
|
def test_cross_month_range(self):
|
||||||
|
from redmine_reporter.config import compute_next_period
|
||||||
|
|
||||||
|
nf, nt = compute_next_period("2026-06-25", "2026-07-05", "date")
|
||||||
|
assert nf == "2026-07-06"
|
||||||
|
assert nt == "2026-07-16"
|
||||||
|
|
||||||
|
def test_datetime_precision_moves_by_seconds(self):
|
||||||
|
from redmine_reporter.config import compute_next_period
|
||||||
|
|
||||||
|
nf, nt = compute_next_period(
|
||||||
|
"2026-06-30T09:00:00", "2026-06-30T12:00:00", "datetime"
|
||||||
|
)
|
||||||
|
assert nf == "2026-06-30T12:00:01"
|
||||||
|
assert nt == "2026-06-30T15:00:01"
|
||||||
|
|
||||||
|
|
||||||
|
class TestDefaultDateRangeWithLastUsed:
|
||||||
|
"""Tests that get_default_date_range() uses last_used when dynamic=True."""
|
||||||
|
|
||||||
|
@mock.patch.dict(os.environ, {}, clear=True)
|
||||||
|
def test_uses_last_used_when_dynamic_true(self):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
yaml_path = Path(tmp) / "config.yml"
|
||||||
|
yaml_path.write_text(
|
||||||
|
"period:\n"
|
||||||
|
" precision: date\n"
|
||||||
|
" dynamic: true\n"
|
||||||
|
" last_used:\n"
|
||||||
|
" from: '2026-05-01'\n"
|
||||||
|
" to: '2026-05-31'\n"
|
||||||
|
)
|
||||||
|
Config._app = AppConfig.from_yaml(yaml_path)
|
||||||
|
result = Config.get_default_date_range()
|
||||||
|
assert result == "2026-06-01--2026-06-30"
|
||||||
|
|
||||||
|
@mock.patch.dict(os.environ, {}, clear=True)
|
||||||
|
def test_ignores_last_used_when_dynamic_false(self):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
yaml_path = Path(tmp) / "config.yml"
|
||||||
|
yaml_path.write_text(
|
||||||
|
"period:\n"
|
||||||
|
" precision: date\n"
|
||||||
|
" dynamic: false\n"
|
||||||
|
" default_from: '2026-03-01'\n"
|
||||||
|
" default_to: '2026-03-15'\n"
|
||||||
|
" last_used:\n"
|
||||||
|
" from: '2026-06-01'\n"
|
||||||
|
" to: '2026-06-30'\n"
|
||||||
|
)
|
||||||
|
Config._app = AppConfig.from_yaml(yaml_path)
|
||||||
|
result = Config.get_default_date_range()
|
||||||
|
assert result == "2026-03-01--2026-03-15"
|
||||||
|
|
||||||
|
@mock.patch.dict(os.environ, {}, clear=True)
|
||||||
|
def test_falls_back_when_no_last_used_even_with_dynamic(self):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
yaml_path = Path(tmp) / "config.yml"
|
||||||
|
yaml_path.write_text(
|
||||||
|
"period:\n"
|
||||||
|
" precision: date\n"
|
||||||
|
" dynamic: true\n"
|
||||||
|
" default_from: '2026-04-01'\n"
|
||||||
|
" default_to: '2026-04-15'\n"
|
||||||
|
)
|
||||||
|
Config._app = AppConfig.from_yaml(yaml_path)
|
||||||
|
result = Config.get_default_date_range()
|
||||||
|
assert result == "2026-04-01--2026-04-15"
|
||||||
|
|
||||||
|
@mock.patch.dict(os.environ, {}, clear=True)
|
||||||
|
def test_falls_back_to_today_when_default_to_missing(self):
|
||||||
|
"""Если default_from задан, а default_to нет — конец периода сегодня."""
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
yaml_path = Path(tmp) / "config.yml"
|
||||||
|
yaml_path.write_text(
|
||||||
|
"period:\n"
|
||||||
|
" precision: date\n"
|
||||||
|
" dynamic: false\n"
|
||||||
|
" default_from: '2026-04-01'\n"
|
||||||
|
)
|
||||||
|
Config._app = AppConfig.from_yaml(yaml_path)
|
||||||
|
today = date.today().isoformat()
|
||||||
|
result = Config.get_default_date_range()
|
||||||
|
assert result == f"2026-04-01--{today}"
|
||||||
|
|
||||||
|
|
||||||
|
class TestGetEmailConfig:
|
||||||
|
"""Tests for Config.get_email_config()."""
|
||||||
|
|
||||||
|
@mock.patch.dict(os.environ, {}, clear=True)
|
||||||
|
def test_get_email_config_from_yaml(self):
|
||||||
|
"""get_email_config() возвращает EmailConfig из YAML."""
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
yaml_path = Path(tmp) / "config.yml"
|
||||||
|
yaml_path.write_text(
|
||||||
|
"email:\n"
|
||||||
|
" smtp:\n"
|
||||||
|
" host: smtp.example.com\n"
|
||||||
|
" port: 587\n"
|
||||||
|
" user: bot@example.com\n"
|
||||||
|
" password: secret\n"
|
||||||
|
" tls: true\n"
|
||||||
|
" from: bot@example.com\n"
|
||||||
|
" to:\n"
|
||||||
|
" - boss@example.com\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
Config._app = AppConfig.from_yaml(yaml_path)
|
||||||
|
cfg = Config.get_email_config()
|
||||||
|
|
||||||
|
assert cfg is not None
|
||||||
|
assert cfg.smtp.host == "smtp.example.com"
|
||||||
|
assert cfg.smtp.port == 587
|
||||||
|
assert cfg.smtp.user == "bot@example.com"
|
||||||
|
assert cfg.smtp.password == "secret"
|
||||||
|
assert cfg.smtp.tls is True
|
||||||
|
assert cfg.from_ == "bot@example.com"
|
||||||
|
assert cfg.to == ["boss@example.com"]
|
||||||
|
|
||||||
|
@mock.patch.dict(os.environ, {}, clear=True)
|
||||||
|
def test_get_email_config_returns_none_when_no_yaml(self):
|
||||||
|
"""Без YAML-конфига get_email_config() возвращает None."""
|
||||||
|
Config._app = None
|
||||||
|
assert Config.get_email_config() is None
|
||||||
|
|
||||||
|
@mock.patch.dict(os.environ, {}, clear=True)
|
||||||
|
def test_get_email_config_returns_none_when_no_host(self):
|
||||||
|
"""С YAML но без smtp.host — возвращает None."""
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
yaml_path = Path(tmp) / "config.yml"
|
||||||
|
yaml_path.write_text("email:\n smtp:\n host: ''\n")
|
||||||
|
|
||||||
|
Config._app = AppConfig.from_yaml(yaml_path)
|
||||||
|
assert Config.get_email_config() is None
|
||||||
|
|
||||||
|
|
||||||
|
class TestEmailConfigHtml:
|
||||||
|
"""Tests for EmailConfig.html field."""
|
||||||
|
|
||||||
|
def test_email_config_html_from_yaml(self):
|
||||||
|
"""email.html: true загружается из YAML."""
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
yaml_path = Path(tmp) / "config.yml"
|
||||||
|
yaml_path.write_text(
|
||||||
|
"email:\n html: true\n smtp:\n host: smtp.example.com\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
cfg = AppConfig.from_yaml(yaml_path)
|
||||||
|
assert cfg.email.html is True
|
||||||
|
|
||||||
|
def test_email_config_html_defaults_to_false(self):
|
||||||
|
"""email.html по умолчанию False."""
|
||||||
|
assert EmailConfig().html is False
|
||||||
|
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
yaml_path = Path(tmp) / "config.yml"
|
||||||
|
yaml_path.write_text("email:\n smtp:\n host: smtp.example.com\n")
|
||||||
|
|
||||||
|
cfg = AppConfig.from_yaml(yaml_path)
|
||||||
|
assert cfg.email.html is False
|
||||||
|
|
||||||
|
def test_email_config_html_false_from_yaml(self):
|
||||||
|
"""email.html: false явно загружается из YAML."""
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
yaml_path = Path(tmp) / "config.yml"
|
||||||
|
yaml_path.write_text(
|
||||||
|
"email:\n html: false\n smtp:\n host: smtp.example.com\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
cfg = AppConfig.from_yaml(yaml_path)
|
||||||
|
assert cfg.email.html is False
|
||||||
|
|
||||||
|
def test_email_config_html_invalid_string_defaults_to_false(self):
|
||||||
|
"""email.html со строкой 'invalid' приводится к False."""
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
yaml_path = Path(tmp) / "config.yml"
|
||||||
|
yaml_path.write_text(
|
||||||
|
"email:\n html: 'invalid'\n smtp:\n host: smtp.example.com\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
cfg = AppConfig.from_yaml(yaml_path)
|
||||||
|
assert cfg.email.html is False
|
||||||
|
|
||||||
|
|
||||||
|
class TestReportNoTime:
|
||||||
|
"""Tests for Config.get_report_no_time()."""
|
||||||
|
|
||||||
|
@mock.patch.dict(os.environ, {}, clear=True)
|
||||||
|
def test_get_report_no_time_from_yaml(self):
|
||||||
|
"""report.no_time: true загружается из YAML."""
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
yaml_path = Path(tmp) / "config.yml"
|
||||||
|
yaml_path.write_text("report:\n no_time: true\n")
|
||||||
|
|
||||||
|
Config._app = AppConfig.from_yaml(yaml_path)
|
||||||
|
assert Config.get_report_no_time() is True
|
||||||
|
|
||||||
|
@mock.patch.dict(os.environ, {}, clear=True)
|
||||||
|
def test_get_report_no_time_defaults_to_false(self):
|
||||||
|
"""Без YAML-конфига report.no_time по умолчанию False."""
|
||||||
|
Config._app = None
|
||||||
|
assert Config.get_report_no_time() is False
|
||||||
|
|
||||||
|
@mock.patch.dict(os.environ, {}, clear=True)
|
||||||
|
def test_get_report_no_time_from_yaml_false(self):
|
||||||
|
"""report.no_time: false явно загружается из YAML."""
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
yaml_path = Path(tmp) / "config.yml"
|
||||||
|
yaml_path.write_text("report:\n no_time: false\n")
|
||||||
|
|
||||||
|
Config._app = AppConfig.from_yaml(yaml_path)
|
||||||
|
assert Config.get_report_no_time() is False
|
||||||
|
|
||||||
|
@mock.patch.dict(os.environ, {}, clear=True)
|
||||||
|
def test_get_report_no_time_invalid_type_defaults_to_false(self):
|
||||||
|
"""report.no_time со строковым значением приводится к False."""
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
yaml_path = Path(tmp) / "config.yml"
|
||||||
|
yaml_path.write_text("report:\n no_time: 'invalid'\n")
|
||||||
|
|
||||||
|
Config._app = AppConfig.from_yaml(yaml_path)
|
||||||
|
assert Config.get_report_no_time() is False
|
||||||
|
|||||||
@@ -134,7 +134,9 @@ def odt_formatter():
|
|||||||
)
|
)
|
||||||
),
|
),
|
||||||
):
|
):
|
||||||
yield ODTFormatter(author="Тест Автор", from_date="2026-01-01", to_date="2026-01-31")
|
yield ODTFormatter(
|
||||||
|
author="Тест Автор", from_date="2026-01-01", to_date="2026-01-31"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
# -- Тесты упаковки formatters как полноценного пакета --
|
# -- Тесты упаковки formatters как полноценного пакета --
|
||||||
@@ -171,7 +173,11 @@ def _simulate_missing_odfpy():
|
|||||||
|
|
||||||
saved = {}
|
saved = {}
|
||||||
for key in list(sys.modules.keys()):
|
for key in list(sys.modules.keys()):
|
||||||
if key == "odf" or key.startswith("odf.") or key == "redmine_reporter.formatters.odt":
|
if (
|
||||||
|
key == "odf"
|
||||||
|
or key.startswith("odf.")
|
||||||
|
or key == "redmine_reporter.formatters.odt"
|
||||||
|
):
|
||||||
saved[key] = sys.modules.pop(key)
|
saved[key] = sys.modules.pop(key)
|
||||||
return saved
|
return saved
|
||||||
|
|
||||||
@@ -474,7 +480,9 @@ def test_odt_empty_author_no_garbage_in_header(fake_rows):
|
|||||||
)
|
)
|
||||||
),
|
),
|
||||||
):
|
):
|
||||||
formatter = ODTFormatter(author="", from_date="2026-01-01", to_date="2026-01-31")
|
formatter = ODTFormatter(
|
||||||
|
author="", from_date="2026-01-01", to_date="2026-01-31"
|
||||||
|
)
|
||||||
doc = formatter.format(fake_rows)
|
doc = formatter.format(fake_rows)
|
||||||
|
|
||||||
from odf.text import P
|
from odf.text import P
|
||||||
@@ -501,7 +509,9 @@ def test_odt_formatter_save_creates_valid_file(fake_rows, tmp_path):
|
|||||||
)
|
)
|
||||||
),
|
),
|
||||||
):
|
):
|
||||||
formatter = ODTFormatter(author="Тест", from_date="2026-01-01", to_date="2026-01-31")
|
formatter = ODTFormatter(
|
||||||
|
author="Тест", from_date="2026-01-01", to_date="2026-01-31"
|
||||||
|
)
|
||||||
output_file = tmp_path / "report.odt"
|
output_file = tmp_path / "report.odt"
|
||||||
formatter.save(fake_rows, str(output_file))
|
formatter.save(fake_rows, str(output_file))
|
||||||
|
|
||||||
@@ -537,7 +547,9 @@ def test_odt_has_covered_cells_for_spans(fake_rows):
|
|||||||
)
|
)
|
||||||
),
|
),
|
||||||
):
|
):
|
||||||
formatter = ODTFormatter(author="Тест", from_date="2026-01-01", to_date="2026-01-31")
|
formatter = ODTFormatter(
|
||||||
|
author="Тест", from_date="2026-01-01", to_date="2026-01-31"
|
||||||
|
)
|
||||||
doc = formatter.format(fake_rows)
|
doc = formatter.format(fake_rows)
|
||||||
|
|
||||||
from odf.table import CoveredTableCell
|
from odf.table import CoveredTableCell
|
||||||
|
|||||||
303
tests/test_mailer.py
Normal file
303
tests/test_mailer.py
Normal file
@@ -0,0 +1,303 @@
|
|||||||
|
import smtplib
|
||||||
|
from unittest import mock
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from redmine_reporter.client import RedmineAPIError
|
||||||
|
from redmine_reporter.config import EmailConfig, SmtpConfig
|
||||||
|
from redmine_reporter.mailer import build_message, send_report
|
||||||
|
|
||||||
|
|
||||||
|
def _make_email_config(**overrides) -> EmailConfig:
|
||||||
|
"""Создаёт EmailConfig с минимальными валидными настройками."""
|
||||||
|
smtp = SmtpConfig(
|
||||||
|
host=overrides.pop("smtp_host", "smtp.example.com"),
|
||||||
|
port=overrides.pop("smtp_port", 587),
|
||||||
|
user=overrides.pop("smtp_user", "bot@example.com"),
|
||||||
|
password=overrides.pop("smtp_password", "secret"),
|
||||||
|
tls=overrides.pop("smtp_tls", True),
|
||||||
|
)
|
||||||
|
return EmailConfig(
|
||||||
|
smtp=smtp,
|
||||||
|
from_=overrides.pop("from_", "bot@example.com"),
|
||||||
|
to=overrides.pop("to", ["boss@example.com"]),
|
||||||
|
cc=overrides.pop("cc", []),
|
||||||
|
bcc=overrides.pop("bcc", []),
|
||||||
|
subject=overrides.pop("subject", "Отчёт {author} за {period}"),
|
||||||
|
body_text=overrides.pop("body_text", "Во вложении отчёт."),
|
||||||
|
attach=overrides.pop("attach", True),
|
||||||
|
**overrides,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class TestBuildMessage:
|
||||||
|
"""Тесты формирования MIME-письма."""
|
||||||
|
|
||||||
|
def test_subject_substitution(self):
|
||||||
|
"""{author} и {period} подставляются в тему."""
|
||||||
|
cfg = _make_email_config(subject="Отчёт {author} за {period}", attach=False)
|
||||||
|
msg = build_message(
|
||||||
|
cfg, "/tmp/report.xlsx", "Кокос А.Н.", "2026-06-01--2026-06-30", []
|
||||||
|
)
|
||||||
|
assert msg["Subject"] == "Отчёт Кокос А.Н. за 2026-06-01--2026-06-30"
|
||||||
|
|
||||||
|
def test_body_substitution(self):
|
||||||
|
"""{author} и {period} подставляются в тело."""
|
||||||
|
cfg = _make_email_config(
|
||||||
|
body_text="Автор: {author}, период: {period}", attach=False
|
||||||
|
)
|
||||||
|
msg = build_message(cfg, "/tmp/report.xlsx", "Иванов", "Q1", [])
|
||||||
|
plain_parts = [p for p in msg.walk() if p.get_content_type() == "text/plain"]
|
||||||
|
assert len(plain_parts) == 1
|
||||||
|
assert "Автор: Иванов, период: Q1" in plain_parts[0].as_string()
|
||||||
|
|
||||||
|
def test_from_header(self):
|
||||||
|
cfg = _make_email_config(from_="sender@example.com", attach=False)
|
||||||
|
msg = build_message(cfg, "/tmp/r.xlsx", "A", "P", [])
|
||||||
|
assert msg["From"] == "sender@example.com"
|
||||||
|
|
||||||
|
def test_to_header(self):
|
||||||
|
cfg = _make_email_config(to=["a@x.com", "b@x.com"], attach=False)
|
||||||
|
msg = build_message(cfg, "/tmp/r.xlsx", "A", "P", [])
|
||||||
|
assert msg["To"] == "a@x.com, b@x.com"
|
||||||
|
|
||||||
|
def test_cc_header(self):
|
||||||
|
cfg = _make_email_config(cc=["cc@x.com"], attach=False)
|
||||||
|
msg = build_message(cfg, "/tmp/r.xlsx", "A", "P", [])
|
||||||
|
assert msg["Cc"] == "cc@x.com"
|
||||||
|
|
||||||
|
def test_bcc_not_in_headers(self):
|
||||||
|
"""BCC не должен появляться в заголовках письма."""
|
||||||
|
cfg = _make_email_config(bcc=["hidden@x.com"], attach=False)
|
||||||
|
msg = build_message(cfg, "/tmp/r.xlsx", "A", "P", [])
|
||||||
|
assert "Bcc" not in msg
|
||||||
|
|
||||||
|
def test_attachment_present_when_attach_true(self, tmp_path):
|
||||||
|
report = tmp_path / "report.xlsx"
|
||||||
|
report.write_text("fake xlsx content")
|
||||||
|
cfg = _make_email_config(attach=True)
|
||||||
|
msg = build_message(cfg, str(report), "A", "P", [])
|
||||||
|
assert len(msg.get_payload()) == 2
|
||||||
|
|
||||||
|
def test_no_attachment_when_attach_false(self, tmp_path):
|
||||||
|
report = tmp_path / "report.xlsx"
|
||||||
|
report.write_text("fake xlsx content")
|
||||||
|
cfg = _make_email_config(attach=False)
|
||||||
|
msg = build_message(cfg, str(report), "A", "P", [])
|
||||||
|
assert len(msg.get_payload()) == 1
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"ext,expected_mime",
|
||||||
|
[
|
||||||
|
(
|
||||||
|
".xlsx",
|
||||||
|
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||||
|
),
|
||||||
|
(".odt", "application/vnd.oasis.opendocument.text"),
|
||||||
|
(".csv", "text/csv"),
|
||||||
|
(".html", "text/html"),
|
||||||
|
(".json", "application/json"),
|
||||||
|
(".md", "text/markdown"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_mime_type_by_extension(self, ext, expected_mime, tmp_path):
|
||||||
|
report = tmp_path / f"report{ext}"
|
||||||
|
report.write_text("content")
|
||||||
|
cfg = _make_email_config()
|
||||||
|
msg = build_message(cfg, str(report), "A", "P", [])
|
||||||
|
attachment_part = msg.get_payload()[1]
|
||||||
|
assert attachment_part.get_content_type() == expected_mime
|
||||||
|
|
||||||
|
def test_missing_attachment_file_raises_error(self, tmp_path):
|
||||||
|
"""Если файл вложения не существует — RedmineAPIError."""
|
||||||
|
cfg = _make_email_config()
|
||||||
|
missing = str(tmp_path / "nonexistent.xlsx")
|
||||||
|
with pytest.raises(RedmineAPIError, match="Не удалось прочитать файл"):
|
||||||
|
build_message(cfg, missing, "A", "P", [])
|
||||||
|
|
||||||
|
def test_html_part_present_when_html_true(self, tmp_path):
|
||||||
|
"""При email.html: true письмо содержит multipart/alternative с HTML."""
|
||||||
|
report = tmp_path / "report.xlsx"
|
||||||
|
report.write_text("fake content")
|
||||||
|
cfg = _make_email_config(html=True)
|
||||||
|
rows = [
|
||||||
|
{
|
||||||
|
"project": "Project",
|
||||||
|
"version": "1.0",
|
||||||
|
"issue_id": 1,
|
||||||
|
"subject": "Task",
|
||||||
|
"status_ru": "В работе",
|
||||||
|
"time_text": "2ч",
|
||||||
|
"hours": 2.0,
|
||||||
|
}
|
||||||
|
]
|
||||||
|
msg = build_message(cfg, str(report), "A", "P", rows)
|
||||||
|
|
||||||
|
alternatives = [
|
||||||
|
p for p in msg.walk() if p.get_content_type() == "multipart/alternative"
|
||||||
|
]
|
||||||
|
assert len(alternatives) == 1
|
||||||
|
|
||||||
|
html_parts = [p for p in msg.walk() if p.get_content_type() == "text/html"]
|
||||||
|
assert len(html_parts) == 1
|
||||||
|
|
||||||
|
plain_parts = [p for p in msg.walk() if p.get_content_type() == "text/plain"]
|
||||||
|
assert len(plain_parts) == 1
|
||||||
|
|
||||||
|
def test_no_html_part_when_html_false(self, tmp_path):
|
||||||
|
"""При email.html: false письмо содержит только plain-text."""
|
||||||
|
report = tmp_path / "report.xlsx"
|
||||||
|
report.write_text("fake content")
|
||||||
|
cfg = _make_email_config(html=False)
|
||||||
|
msg = build_message(cfg, str(report), "A", "P", [])
|
||||||
|
|
||||||
|
html_parts = [p for p in msg.walk() if p.get_content_type() == "text/html"]
|
||||||
|
assert len(html_parts) == 0
|
||||||
|
|
||||||
|
plain_parts = [p for p in msg.walk() if p.get_content_type() == "text/plain"]
|
||||||
|
assert len(plain_parts) == 1
|
||||||
|
|
||||||
|
def test_html_part_contains_report_data(self, tmp_path):
|
||||||
|
"""HTML-часть содержит данные отчёта."""
|
||||||
|
report = tmp_path / "report.xlsx"
|
||||||
|
report.write_text("fake content")
|
||||||
|
cfg = _make_email_config(html=True)
|
||||||
|
rows = [
|
||||||
|
{
|
||||||
|
"project": "Project X",
|
||||||
|
"version": "2.0",
|
||||||
|
"issue_id": 42,
|
||||||
|
"subject": "Important task",
|
||||||
|
"status_ru": "В работе",
|
||||||
|
"time_text": "3ч 30м",
|
||||||
|
"hours": 3.5,
|
||||||
|
}
|
||||||
|
]
|
||||||
|
msg = build_message(cfg, str(report), "A", "P", rows)
|
||||||
|
|
||||||
|
html_part = [p for p in msg.walk() if p.get_content_type() == "text/html"][0]
|
||||||
|
payload = html_part.get_payload(decode=True).decode("utf-8")
|
||||||
|
assert "Project X" in payload
|
||||||
|
assert "Important task" in payload
|
||||||
|
|
||||||
|
def test_plain_text_before_html_in_alternative(self, tmp_path):
|
||||||
|
"""В multipart/alternative plain-text идёт перед HTML."""
|
||||||
|
report = tmp_path / "report.xlsx"
|
||||||
|
report.write_text("fake content")
|
||||||
|
cfg = _make_email_config(html=True)
|
||||||
|
rows = [
|
||||||
|
{
|
||||||
|
"project": "P",
|
||||||
|
"version": "V",
|
||||||
|
"issue_id": 1,
|
||||||
|
"subject": "S",
|
||||||
|
"status_ru": "В работе",
|
||||||
|
"time_text": "1ч",
|
||||||
|
"hours": 1.0,
|
||||||
|
}
|
||||||
|
]
|
||||||
|
msg = build_message(cfg, str(report), "A", "P", rows)
|
||||||
|
|
||||||
|
alternative = [
|
||||||
|
p for p in msg.walk() if p.get_content_type() == "multipart/alternative"
|
||||||
|
][0]
|
||||||
|
payloads = alternative.get_payload()
|
||||||
|
assert payloads[0].get_content_type() == "text/plain"
|
||||||
|
assert payloads[1].get_content_type() == "text/html"
|
||||||
|
|
||||||
|
|
||||||
|
class TestSendReport:
|
||||||
|
"""Тесты отправки письма."""
|
||||||
|
|
||||||
|
def test_send_success(self, tmp_path):
|
||||||
|
report = tmp_path / "report.xlsx"
|
||||||
|
report.write_text("fake content")
|
||||||
|
cfg = _make_email_config()
|
||||||
|
|
||||||
|
with mock.patch("smtplib.SMTP") as mock_smtp_class:
|
||||||
|
mock_smtp = mock.MagicMock()
|
||||||
|
mock_smtp_class.return_value.__enter__.return_value = mock_smtp
|
||||||
|
|
||||||
|
send_report(cfg, str(report), "Кокос А.Н.", "2026-06-01--2026-06-30", [])
|
||||||
|
|
||||||
|
mock_smtp_class.assert_called_once_with("smtp.example.com", 587, timeout=30)
|
||||||
|
mock_smtp.starttls.assert_called_once()
|
||||||
|
mock_smtp.login.assert_called_once_with("bot@example.com", "secret")
|
||||||
|
mock_smtp.send_message.assert_called_once()
|
||||||
|
|
||||||
|
def test_send_no_tls(self, tmp_path):
|
||||||
|
report = tmp_path / "report.xlsx"
|
||||||
|
report.write_text("fake content")
|
||||||
|
cfg = _make_email_config(smtp_tls=False)
|
||||||
|
|
||||||
|
with mock.patch("smtplib.SMTP") as mock_smtp_class:
|
||||||
|
mock_smtp = mock.MagicMock()
|
||||||
|
mock_smtp_class.return_value.__enter__.return_value = mock_smtp
|
||||||
|
|
||||||
|
send_report(cfg, str(report), "A", "P", [])
|
||||||
|
|
||||||
|
mock_smtp.starttls.assert_not_called()
|
||||||
|
|
||||||
|
def test_send_connection_error(self, tmp_path):
|
||||||
|
report = tmp_path / "report.xlsx"
|
||||||
|
report.write_text("fake content")
|
||||||
|
cfg = _make_email_config()
|
||||||
|
|
||||||
|
with mock.patch("smtplib.SMTP", side_effect=OSError("Connection refused")):
|
||||||
|
with pytest.raises(RedmineAPIError, match="Не удалось подключиться к SMTP"):
|
||||||
|
send_report(cfg, str(report), "A", "P", [])
|
||||||
|
|
||||||
|
def test_send_auth_error(self, tmp_path):
|
||||||
|
report = tmp_path / "report.xlsx"
|
||||||
|
report.write_text("fake content")
|
||||||
|
cfg = _make_email_config()
|
||||||
|
|
||||||
|
with mock.patch("smtplib.SMTP") as mock_smtp_class:
|
||||||
|
mock_smtp = mock.MagicMock()
|
||||||
|
mock_smtp_class.return_value.__enter__.return_value = mock_smtp
|
||||||
|
mock_smtp.login.side_effect = smtplib.SMTPAuthenticationError(
|
||||||
|
535, b"Bad auth"
|
||||||
|
)
|
||||||
|
|
||||||
|
with pytest.raises(RedmineAPIError, match="Ошибка аутентификации SMTP"):
|
||||||
|
send_report(cfg, str(report), "A", "P", [])
|
||||||
|
|
||||||
|
def test_send_timeout_error(self, tmp_path):
|
||||||
|
report = tmp_path / "report.xlsx"
|
||||||
|
report.write_text("fake content")
|
||||||
|
cfg = _make_email_config()
|
||||||
|
|
||||||
|
with mock.patch("smtplib.SMTP", side_effect=TimeoutError()):
|
||||||
|
with pytest.raises(RedmineAPIError, match="Таймаут соединения с SMTP"):
|
||||||
|
send_report(cfg, str(report), "A", "P", [])
|
||||||
|
|
||||||
|
def test_send_generic_smtp_error(self, tmp_path):
|
||||||
|
report = tmp_path / "report.xlsx"
|
||||||
|
report.write_text("fake content")
|
||||||
|
cfg = _make_email_config()
|
||||||
|
|
||||||
|
with mock.patch("smtplib.SMTP") as mock_smtp_class:
|
||||||
|
mock_smtp = mock.MagicMock()
|
||||||
|
mock_smtp_class.return_value.__enter__.return_value = mock_smtp
|
||||||
|
mock_smtp.send_message.side_effect = smtplib.SMTPException(
|
||||||
|
"Something went wrong"
|
||||||
|
)
|
||||||
|
|
||||||
|
with pytest.raises(RedmineAPIError, match="Ошибка отправки письма"):
|
||||||
|
send_report(cfg, str(report), "A", "P", [])
|
||||||
|
|
||||||
|
def test_send_includes_cc_and_bcc(self, tmp_path):
|
||||||
|
report = tmp_path / "report.xlsx"
|
||||||
|
report.write_text("fake content")
|
||||||
|
cfg = _make_email_config(to=["a@x.com"], cc=["cc@x.com"], bcc=["bcc@x.com"])
|
||||||
|
|
||||||
|
with mock.patch("smtplib.SMTP") as mock_smtp_class:
|
||||||
|
mock_smtp = mock.MagicMock()
|
||||||
|
mock_smtp_class.return_value.__enter__.return_value = mock_smtp
|
||||||
|
|
||||||
|
send_report(cfg, str(report), "A", "P", [])
|
||||||
|
|
||||||
|
call_args = mock_smtp.send_message.call_args
|
||||||
|
msg = call_args.args[0]
|
||||||
|
assert msg["To"] == "a@x.com"
|
||||||
|
assert msg["Cc"] == "cc@x.com"
|
||||||
330
tests/test_yaml_config.py
Normal file
330
tests/test_yaml_config.py
Normal file
@@ -0,0 +1,330 @@
|
|||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import tempfile
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest import mock
|
||||||
|
|
||||||
|
from redmine_reporter.yaml_config import (
|
||||||
|
check_file_permissions,
|
||||||
|
ensure_config_dir,
|
||||||
|
expand_filename_template,
|
||||||
|
resolve_env_vars,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class TestResolveEnvVars:
|
||||||
|
"""Tests for ${VAR} resolution."""
|
||||||
|
|
||||||
|
@mock.patch.dict(os.environ, {"MY_VAR": "hello"}, clear=True)
|
||||||
|
def test_replaces_var_with_env_value(self):
|
||||||
|
assert resolve_env_vars("prefix_${MY_VAR}_suffix") == "prefix_hello_suffix"
|
||||||
|
|
||||||
|
@mock.patch.dict(os.environ, {}, clear=True)
|
||||||
|
def test_missing_var_returns_empty_and_warns(self, caplog):
|
||||||
|
with caplog.at_level(logging.WARNING):
|
||||||
|
result = resolve_env_vars("${MISSING_VAR}")
|
||||||
|
assert result == ""
|
||||||
|
assert "MISSING_VAR" in caplog.text
|
||||||
|
|
||||||
|
def test_no_braces_returns_unchanged(self):
|
||||||
|
assert resolve_env_vars("plain text no vars") == "plain text no vars"
|
||||||
|
|
||||||
|
@mock.patch.dict(os.environ, {"A": "${B}", "B": "final"}, clear=True)
|
||||||
|
def test_non_recursive_no_double_resolution(self):
|
||||||
|
# A → literal "${B}", B → "final". Non-recursive means we get "${B}", not "final".
|
||||||
|
result = resolve_env_vars("${A}")
|
||||||
|
assert result == "${B}"
|
||||||
|
|
||||||
|
|
||||||
|
class TestEnsureConfigDir:
|
||||||
|
"""Tests for config directory creation."""
|
||||||
|
|
||||||
|
def test_creates_dir_with_0700(self):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
config_dir = Path(tmp) / "test_config"
|
||||||
|
result = ensure_config_dir(config_dir)
|
||||||
|
assert result == config_dir
|
||||||
|
assert result.exists()
|
||||||
|
assert result.is_dir()
|
||||||
|
mode = result.stat().st_mode & 0o777
|
||||||
|
assert mode == 0o700
|
||||||
|
|
||||||
|
def test_noop_if_dir_exists(self):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
config_dir = Path(tmp) / "existing"
|
||||||
|
config_dir.mkdir(mode=0o700)
|
||||||
|
mtime_before = config_dir.stat().st_mtime
|
||||||
|
result = ensure_config_dir(config_dir)
|
||||||
|
assert result == config_dir
|
||||||
|
assert config_dir.stat().st_mtime == mtime_before
|
||||||
|
|
||||||
|
|
||||||
|
class TestCheckFilePermissions:
|
||||||
|
"""Tests for config file permission checks."""
|
||||||
|
|
||||||
|
def test_warns_on_permissive_file(self):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
f = Path(tmp) / "open.yml"
|
||||||
|
f.write_text("key: value")
|
||||||
|
f.chmod(0o644)
|
||||||
|
warnings = check_file_permissions(f)
|
||||||
|
assert len(warnings) >= 1
|
||||||
|
assert "0644" in warnings[0] or "permissions" in warnings[0].lower()
|
||||||
|
|
||||||
|
def test_silent_on_0600(self):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
f = Path(tmp) / "secure.yml"
|
||||||
|
f.write_text("key: value")
|
||||||
|
f.chmod(0o600)
|
||||||
|
warnings = check_file_permissions(f)
|
||||||
|
assert warnings == []
|
||||||
|
|
||||||
|
|
||||||
|
class TestExpandFilenameTemplate:
|
||||||
|
"""Tests for filename template expansion."""
|
||||||
|
|
||||||
|
def test_expands_all_placeholders(self):
|
||||||
|
result = expand_filename_template(
|
||||||
|
"report_{author}_{from}_{to}.{ext}",
|
||||||
|
author="Кокос А.А.",
|
||||||
|
from_date="2026-06-01",
|
||||||
|
to_date="2026-06-30",
|
||||||
|
ext="xlsx",
|
||||||
|
)
|
||||||
|
assert result == "report_Кокос_А.А._2026-06-01_2026-06-30.xlsx"
|
||||||
|
|
||||||
|
def test_date_placeholder_dd_mm_yyyy(self):
|
||||||
|
result = expand_filename_template(
|
||||||
|
"отчёт_{date}.{ext}",
|
||||||
|
author="Кокос А.А.",
|
||||||
|
from_date="2026-03-01",
|
||||||
|
to_date="2026-03-31",
|
||||||
|
ext="odt",
|
||||||
|
)
|
||||||
|
assert result == "отчёт_31_03_2026.odt"
|
||||||
|
|
||||||
|
def test_no_placeholders_returns_unchanged(self):
|
||||||
|
result = expand_filename_template(
|
||||||
|
"report.odt",
|
||||||
|
author="Кокос А.А.",
|
||||||
|
from_date="2026-01-01",
|
||||||
|
to_date="2026-01-31",
|
||||||
|
ext="odt",
|
||||||
|
)
|
||||||
|
assert result == "report.odt"
|
||||||
|
|
||||||
|
def test_unknown_placeholder_left_as_is(self):
|
||||||
|
result = expand_filename_template(
|
||||||
|
"{author}_{unknown}.{ext}",
|
||||||
|
author="Кокос А.А.",
|
||||||
|
from_date="2026-01-01",
|
||||||
|
to_date="2026-01-31",
|
||||||
|
ext="xlsx",
|
||||||
|
)
|
||||||
|
assert result == "Кокос_А.А._{unknown}.xlsx"
|
||||||
|
|
||||||
|
|
||||||
|
class TestResolveOutputPath:
|
||||||
|
"""Tests for resolve_output_path()."""
|
||||||
|
|
||||||
|
def test_none_returns_none(self):
|
||||||
|
from redmine_reporter.yaml_config import resolve_output_path
|
||||||
|
|
||||||
|
assert resolve_output_path(None) is None
|
||||||
|
|
||||||
|
def test_explicit_path_with_known_extension_is_unchanged(self):
|
||||||
|
from redmine_reporter.yaml_config import resolve_output_path
|
||||||
|
|
||||||
|
result = resolve_output_path("/tmp/report.xlsx")
|
||||||
|
assert result == "/tmp/report.xlsx"
|
||||||
|
|
||||||
|
def test_explicit_path_with_unknown_extension_is_unchanged(self):
|
||||||
|
from redmine_reporter.yaml_config import resolve_output_path
|
||||||
|
|
||||||
|
result = resolve_output_path("report.odt")
|
||||||
|
assert result == "report.odt"
|
||||||
|
|
||||||
|
def test_no_extension_appends_default_format(self):
|
||||||
|
from redmine_reporter.yaml_config import resolve_output_path
|
||||||
|
|
||||||
|
result = resolve_output_path("report", default_format="xlsx")
|
||||||
|
assert result == "report.xlsx"
|
||||||
|
|
||||||
|
def test_no_extension_appends_custom_default_format(self):
|
||||||
|
from redmine_reporter.yaml_config import resolve_output_path
|
||||||
|
|
||||||
|
result = resolve_output_path("file", default_format="csv")
|
||||||
|
assert result == "file.csv"
|
||||||
|
|
||||||
|
def test_bare_format_name_resolves_to_template_path(self):
|
||||||
|
from redmine_reporter.yaml_config import resolve_output_path
|
||||||
|
|
||||||
|
result = resolve_output_path(
|
||||||
|
"xlsx",
|
||||||
|
output_dir="/tmp/reports",
|
||||||
|
filename_template="{date}.{ext}",
|
||||||
|
author="Кокос А.А.",
|
||||||
|
from_date="2026-06-01",
|
||||||
|
to_date="2026-06-30",
|
||||||
|
default_format="xlsx",
|
||||||
|
)
|
||||||
|
assert result == "/tmp/reports/30_06_2026.xlsx"
|
||||||
|
|
||||||
|
def test_bare_format_name_odt_resolves_to_template_path(self):
|
||||||
|
from redmine_reporter.yaml_config import resolve_output_path
|
||||||
|
|
||||||
|
result = resolve_output_path(
|
||||||
|
"odt",
|
||||||
|
output_dir="~/reports",
|
||||||
|
filename_template="{author}_{from}_{to}.{ext}",
|
||||||
|
author="Кокос А.А.",
|
||||||
|
from_date="2026-06-01",
|
||||||
|
to_date="2026-06-30",
|
||||||
|
default_format="xlsx",
|
||||||
|
)
|
||||||
|
assert result.startswith("/") and result.endswith(
|
||||||
|
"/reports/Кокос_А.А._2026-06-01_2026-06-30.odt"
|
||||||
|
)
|
||||||
|
assert "~" not in result
|
||||||
|
|
||||||
|
def test_bare_format_name_with_empty_output_dir_uses_cwd(self):
|
||||||
|
from redmine_reporter.yaml_config import resolve_output_path
|
||||||
|
|
||||||
|
result = resolve_output_path(
|
||||||
|
"csv",
|
||||||
|
output_dir="",
|
||||||
|
filename_template="report.{ext}",
|
||||||
|
author="A",
|
||||||
|
from_date="2026-01-01",
|
||||||
|
to_date="2026-01-31",
|
||||||
|
)
|
||||||
|
assert not result.startswith("/")
|
||||||
|
assert "report.csv" in result
|
||||||
|
|
||||||
|
def test_unknown_bare_format_is_treated_as_path(self):
|
||||||
|
from redmine_reporter.yaml_config import resolve_output_path
|
||||||
|
|
||||||
|
result = resolve_output_path("unknown_format")
|
||||||
|
assert result == "unknown_format.xlsx"
|
||||||
|
|
||||||
|
|
||||||
|
class TestSavePeriodToConfig:
|
||||||
|
"""Tests for save_period_to_config()."""
|
||||||
|
|
||||||
|
def test_creates_last_used_in_empty_config(self, tmp_path):
|
||||||
|
import yaml
|
||||||
|
|
||||||
|
from redmine_reporter.yaml_config import save_period_to_config
|
||||||
|
|
||||||
|
config_path = tmp_path / "config.yml"
|
||||||
|
save_period_to_config(
|
||||||
|
str(config_path), "2026-06-01", "2026-06-30", "date", True
|
||||||
|
)
|
||||||
|
|
||||||
|
with open(config_path) as fh:
|
||||||
|
data = yaml.safe_load(fh)
|
||||||
|
|
||||||
|
assert data["period"]["last_used"]["from"] == "2026-06-01"
|
||||||
|
assert data["period"]["last_used"]["to"] == "2026-06-30"
|
||||||
|
assert "default_from" not in data["period"]
|
||||||
|
|
||||||
|
def test_overwrites_existing_last_used(self, tmp_path):
|
||||||
|
import yaml
|
||||||
|
|
||||||
|
from redmine_reporter.yaml_config import save_period_to_config
|
||||||
|
|
||||||
|
config_path = tmp_path / "config.yml"
|
||||||
|
config_path.write_text(
|
||||||
|
"period:\n last_used:\n from: '2026-05-01'\n to: '2026-05-31'\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
save_period_to_config(
|
||||||
|
str(config_path), "2026-06-01", "2026-06-30", "date", True
|
||||||
|
)
|
||||||
|
|
||||||
|
with open(config_path) as fh:
|
||||||
|
data = yaml.safe_load(fh)
|
||||||
|
|
||||||
|
assert data["period"]["last_used"]["from"] == "2026-06-01"
|
||||||
|
assert data["period"]["last_used"]["to"] == "2026-06-30"
|
||||||
|
|
||||||
|
def test_dynamic_false_overwrites_defaults(self, tmp_path):
|
||||||
|
import yaml
|
||||||
|
|
||||||
|
from redmine_reporter.yaml_config import save_period_to_config
|
||||||
|
|
||||||
|
config_path = tmp_path / "config.yml"
|
||||||
|
config_path.write_text(
|
||||||
|
"period:\n default_from: '2026-01-01'\n default_to: '2026-01-31'\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
save_period_to_config(
|
||||||
|
str(config_path), "2026-06-01", "2026-06-30", "date", False
|
||||||
|
)
|
||||||
|
|
||||||
|
with open(config_path) as fh:
|
||||||
|
data = yaml.safe_load(fh)
|
||||||
|
|
||||||
|
assert data["period"]["default_from"] == "2026-06-01"
|
||||||
|
assert data["period"]["default_to"] == "2026-06-30"
|
||||||
|
assert data["period"]["last_used"]["from"] == "2026-06-01"
|
||||||
|
assert data["period"]["last_used"]["to"] == "2026-06-30"
|
||||||
|
|
||||||
|
def test_datetime_precision_stores_timestamps(self, tmp_path):
|
||||||
|
import yaml
|
||||||
|
|
||||||
|
from redmine_reporter.yaml_config import save_period_to_config
|
||||||
|
|
||||||
|
config_path = tmp_path / "config.yml"
|
||||||
|
|
||||||
|
save_period_to_config(
|
||||||
|
str(config_path),
|
||||||
|
"2026-06-30T09:00:00",
|
||||||
|
"2026-06-30T12:00:00",
|
||||||
|
"datetime",
|
||||||
|
True,
|
||||||
|
)
|
||||||
|
|
||||||
|
with open(config_path) as fh:
|
||||||
|
data = yaml.safe_load(fh)
|
||||||
|
|
||||||
|
assert data["period"]["last_used"]["from"] == "2026-06-30T09:00:00"
|
||||||
|
assert data["period"]["last_used"]["to"] == "2026-06-30T12:00:00"
|
||||||
|
|
||||||
|
def test_preserves_existing_sections(self, tmp_path):
|
||||||
|
import yaml
|
||||||
|
|
||||||
|
from redmine_reporter.yaml_config import save_period_to_config
|
||||||
|
|
||||||
|
config_path = tmp_path / "config.yml"
|
||||||
|
config_path.write_text(
|
||||||
|
"redmine:\n"
|
||||||
|
" url: https://example.com\n"
|
||||||
|
" author: Test\n"
|
||||||
|
"output:\n"
|
||||||
|
" dir: /tmp\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
save_period_to_config(
|
||||||
|
str(config_path), "2026-06-01", "2026-06-30", "date", True
|
||||||
|
)
|
||||||
|
|
||||||
|
with open(config_path) as fh:
|
||||||
|
data = yaml.safe_load(fh)
|
||||||
|
|
||||||
|
assert data["redmine"]["url"] == "https://example.com"
|
||||||
|
assert data["redmine"]["author"] == "Test"
|
||||||
|
assert data["output"]["dir"] == "/tmp"
|
||||||
|
assert data["period"]["last_used"]["from"] == "2026-06-01"
|
||||||
|
|
||||||
|
def test_sets_permissions_0600(self, tmp_path):
|
||||||
|
from redmine_reporter.yaml_config import save_period_to_config
|
||||||
|
|
||||||
|
config_path = tmp_path / "config.yml"
|
||||||
|
|
||||||
|
save_period_to_config(
|
||||||
|
str(config_path), "2026-06-01", "2026-06-30", "date", True
|
||||||
|
)
|
||||||
|
|
||||||
|
mode = config_path.stat().st_mode & 0o777
|
||||||
|
assert mode == 0o600
|
||||||
Reference in New Issue
Block a user