abc-formatter #10
@@ -1,3 +1,4 @@
|
|||||||
|
import os
|
||||||
import sys
|
import sys
|
||||||
import argparse
|
import argparse
|
||||||
from typing import List, Optional
|
from typing import List, Optional
|
||||||
@@ -6,10 +7,7 @@ from redminelib.resources import Issue
|
|||||||
from .config import Config
|
from .config import Config
|
||||||
from .client import fetch_issues_with_spent_time
|
from .client import fetch_issues_with_spent_time
|
||||||
from .report_builder import build_grouped_report
|
from .report_builder import build_grouped_report
|
||||||
from .formatter import format_compact, format_table
|
from .formatters.factory import get_formatter_by_extension, get_console_formatter
|
||||||
from .formatter_odt import format_odt
|
|
||||||
from .formatter_csv import format_csv
|
|
||||||
from .formatter_md import format_md
|
|
||||||
|
|
||||||
|
|
||||||
def parse_date_range(date_arg: str) -> tuple[str, str]:
|
def parse_date_range(date_arg: str) -> tuple[str, str]:
|
||||||
@@ -80,45 +78,44 @@ def main(argv: Optional[List[str]] = None) -> int:
|
|||||||
rows = build_grouped_report(issue_hours, fill_time=not args.no_time)
|
rows = build_grouped_report(issue_hours, fill_time=not args.no_time)
|
||||||
|
|
||||||
if args.output:
|
if args.output:
|
||||||
if not (args.output.endswith(".odt") or args.output.endswith(".csv") or args.output.endswith(".md")):
|
output_ext = os.path.splitext(args.output)[1].lower()
|
||||||
print("❌ Output file must end with .odt, .csv or .md", file=sys.stderr)
|
|
||||||
|
formatter = get_formatter_by_extension(output_ext,
|
||||||
|
author=Config.get_author(args.author),
|
||||||
|
from_date=from_date,
|
||||||
|
to_date=to_date
|
||||||
|
)
|
||||||
|
|
||||||
|
if not formatter:
|
||||||
|
print(f"❌ Неизвестный формат файла: {output_ext}", file=sys.stderr)
|
||||||
return 1
|
return 1
|
||||||
|
|
||||||
try:
|
try:
|
||||||
if args.output.endswith(".odt"):
|
formatter.save(rows, args.output)
|
||||||
doc = format_odt(
|
|
||||||
rows,
|
|
||||||
author=Config.get_author(args.author),
|
|
||||||
from_date=from_date,
|
|
||||||
to_date=to_date,
|
|
||||||
)
|
|
||||||
doc.save(args.output)
|
|
||||||
elif args.output.endswith(".csv"):
|
|
||||||
content = format_csv(rows)
|
|
||||||
with open(args.output, "w", encoding="utf-8", newline="") as f:
|
|
||||||
f.write(content)
|
|
||||||
elif args.output.endswith(".md"):
|
|
||||||
content = format_md(rows)
|
|
||||||
with open(args.output, "w", encoding="utf-8") as f:
|
|
||||||
f.write(content)
|
|
||||||
|
|
||||||
print(f"✅ Report saved to {args.output}")
|
print(f"✅ Report saved to {args.output}")
|
||||||
except ImportError as e:
|
except ImportError as e:
|
||||||
if args.output.endswith(".odt"):
|
if output_ext == ".odt":
|
||||||
print("❌ odfpy is not installed. Install with: pip install odfpy", file=sys.stderr)
|
print("❌ odfpy is not installed. Install with: pip install odfpy", file=sys.stderr)
|
||||||
else:
|
else:
|
||||||
print(f"❌ Import error: {e}", file=sys.stderr)
|
print(f"❌ Import error: {e}", file=sys.stderr)
|
||||||
return 1
|
return 1
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
fmt = "ODT" if args.output.endswith(".odt") else ("CSV" if args.output.endswith(".csv") else "Markdown")
|
fmt = "ODT" if output_ext == ".odt" else ("CSV" if output_ext == ".csv" else "Markdown")
|
||||||
print(f"❌ {fmt} export error: {e}", file=sys.stderr)
|
print(f"❌ {fmt} export error: {e}", file=sys.stderr)
|
||||||
return 1
|
return 1
|
||||||
|
|
||||||
else:
|
else:
|
||||||
|
if args.compact:
|
||||||
|
formatter = get_console_formatter("compact")
|
||||||
|
else:
|
||||||
|
formatter = get_console_formatter("table")
|
||||||
|
|
||||||
|
if not formatter:
|
||||||
|
print("❌ Неизвестный тип консольного форматтера.", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
|
||||||
try:
|
try:
|
||||||
if args.compact:
|
output = formatter.format(rows)
|
||||||
output = format_compact(rows)
|
|
||||||
else:
|
|
||||||
output = format_table(rows)
|
|
||||||
print(output)
|
print(output)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"❌ Formatting error: {e}", file=sys.stderr)
|
print(f"❌ Formatting error: {e}", file=sys.stderr)
|
||||||
|
|||||||
@@ -1,30 +0,0 @@
|
|||||||
from typing import List
|
|
||||||
from tabulate import tabulate
|
|
||||||
from .types import ReportRow
|
|
||||||
|
|
||||||
|
|
||||||
def format_compact(rows: List[ReportRow]) -> str:
|
|
||||||
lines = []
|
|
||||||
|
|
||||||
for r in rows:
|
|
||||||
lines.append(
|
|
||||||
f"{r['display_project']} | {r['display_version']} | "
|
|
||||||
f"{r['issue_id']}. {r['subject']} | {r['status_ru']} | {r['time_text']}"
|
|
||||||
)
|
|
||||||
|
|
||||||
return "\n".join(lines)
|
|
||||||
|
|
||||||
|
|
||||||
def format_table(rows: List[ReportRow]) -> str:
|
|
||||||
table_rows = [['Проект', 'Версия', 'Задача', 'Статус', 'Затрачено']]
|
|
||||||
|
|
||||||
for r in rows:
|
|
||||||
table_rows.append([
|
|
||||||
r['display_project'],
|
|
||||||
r['display_version'],
|
|
||||||
f"{r['issue_id']}. {r['subject']}",
|
|
||||||
r['status_ru'],
|
|
||||||
r['time_text']
|
|
||||||
])
|
|
||||||
|
|
||||||
return tabulate(table_rows, headers="firstrow", tablefmt="fancy_grid")
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
import csv
|
|
||||||
import io
|
|
||||||
from typing import List
|
|
||||||
from .types import ReportRow
|
|
||||||
|
|
||||||
|
|
||||||
def format_csv(rows: List[ReportRow]) -> str:
|
|
||||||
output = io.StringIO()
|
|
||||||
writer = csv.writer(output, dialect="excel")
|
|
||||||
writer.writerow(["Project", "Version", "Issue ID", "Subject", "Status", "Spent Time"])
|
|
||||||
|
|
||||||
for r in rows:
|
|
||||||
writer.writerow([
|
|
||||||
r["project"],
|
|
||||||
r["version"],
|
|
||||||
r["issue_id"],
|
|
||||||
r["subject"],
|
|
||||||
r["status_ru"],
|
|
||||||
r["time_text"]
|
|
||||||
])
|
|
||||||
|
|
||||||
return output.getvalue()
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
from typing import List
|
|
||||||
from .types import ReportRow
|
|
||||||
|
|
||||||
|
|
||||||
def format_md(rows: List[ReportRow]) -> str:
|
|
||||||
lines = [
|
|
||||||
"| Проект | Версия | Задача | Статус | Затрачено |",
|
|
||||||
"|--------|--------|--------|--------|-----------|"
|
|
||||||
]
|
|
||||||
|
|
||||||
for r in rows:
|
|
||||||
task_cell = f"{r['issue_id']}. {r['subject']}"
|
|
||||||
|
|
||||||
lines.append(
|
|
||||||
f"| {r['display_project']} | {r['display_version']} "
|
|
||||||
f"| {task_cell} | {r['status_ru']} | {r['time_text']} |"
|
|
||||||
)
|
|
||||||
|
|
||||||
return "\n".join(lines)
|
|
||||||
@@ -1,131 +0,0 @@
|
|||||||
import os
|
|
||||||
from typing import List
|
|
||||||
from odf.opendocument import load
|
|
||||||
from odf.text import P
|
|
||||||
from odf.table import Table, TableColumn, TableRow, TableCell
|
|
||||||
from odf.style import Style, TableColumnProperties, TableCellProperties
|
|
||||||
from .types import ReportRow
|
|
||||||
from .utils import get_month_name_from_range
|
|
||||||
|
|
||||||
|
|
||||||
def format_odt(
|
|
||||||
rows: List[ReportRow],
|
|
||||||
author: str = "",
|
|
||||||
from_date: str = "",
|
|
||||||
to_date: str = "",
|
|
||||||
) -> "OpenDocument":
|
|
||||||
template_path = "template.odt"
|
|
||||||
if not os.path.exists(template_path):
|
|
||||||
raise FileNotFoundError("Шаблон template.odt не найден...")
|
|
||||||
|
|
||||||
doc = load(template_path)
|
|
||||||
para_style_name = "Standard"
|
|
||||||
|
|
||||||
# Заголовок
|
|
||||||
month_name = get_month_name_from_range(from_date, to_date)
|
|
||||||
header_text = f"{author}. Отчет за месяц {month_name}."
|
|
||||||
doc.text.addElement(P(stylename=para_style_name, text=header_text))
|
|
||||||
doc.text.addElement(P(stylename=para_style_name, text=""))
|
|
||||||
|
|
||||||
# Стиль ячеек
|
|
||||||
cell_style_name = "TableCellStyle"
|
|
||||||
cell_style = Style(name=cell_style_name, family="table-cell")
|
|
||||||
cell_props = TableCellProperties(padding="0.04in", border="0.05pt solid #000000")
|
|
||||||
cell_style.addElement(cell_props)
|
|
||||||
doc.automaticstyles.addElement(cell_style)
|
|
||||||
|
|
||||||
# Таблица
|
|
||||||
table = Table(name="Report")
|
|
||||||
column_widths = ["1.56in", "1.63in", "3.93in", "1.56in", "1.43in"]
|
|
||||||
for width in column_widths:
|
|
||||||
col_style = Style(name=f"col_{width}", family="table-column")
|
|
||||||
col_props = TableColumnProperties(columnwidth=width)
|
|
||||||
col_style.addElement(col_props)
|
|
||||||
doc.automaticstyles.addElement(col_style)
|
|
||||||
table.addElement(TableColumn(stylename=col_style))
|
|
||||||
|
|
||||||
# Заголовки
|
|
||||||
header_row = TableRow()
|
|
||||||
for text in ["Наименование Проекта", "Номер версии*", "Задача", "Статус Готовность*", "Затрачено за отчетный период"]:
|
|
||||||
cell = TableCell(stylename=cell_style_name)
|
|
||||||
cell.addElement(P(stylename=para_style_name, text=text))
|
|
||||||
header_row.addElement(cell)
|
|
||||||
table.addElement(header_row)
|
|
||||||
|
|
||||||
projects = {}
|
|
||||||
for r in rows:
|
|
||||||
project = r["project"]
|
|
||||||
version = r["version"]
|
|
||||||
if project not in projects:
|
|
||||||
projects[project] = {}
|
|
||||||
if version not in projects[project]:
|
|
||||||
projects[project][version] = []
|
|
||||||
projects[project][version].append(r)
|
|
||||||
|
|
||||||
# Данные с двухуровневой группировкой и объединением ячеек
|
|
||||||
for project, versions in projects.items():
|
|
||||||
total_project_rows = sum(len(rows_for_version) for rows_for_version in versions.values())
|
|
||||||
first_version_in_project = True
|
|
||||||
|
|
||||||
for version, rows_for_version in versions.items():
|
|
||||||
row_span_version = len(rows_for_version)
|
|
||||||
first_row_in_version = True
|
|
||||||
|
|
||||||
for r in rows_for_version:
|
|
||||||
row = TableRow()
|
|
||||||
|
|
||||||
# Ячейка "Проект" - только в первой строке всего проекта
|
|
||||||
if first_version_in_project and first_row_in_version:
|
|
||||||
cell_project = TableCell(stylename=cell_style_name)
|
|
||||||
cell_project.setAttribute("numberrowsspanned", str(total_project_rows))
|
|
||||||
p = P(stylename=para_style_name, text=project) # Полное название проекта
|
|
||||||
cell_project.addElement(p)
|
|
||||||
row.addElement(cell_project)
|
|
||||||
|
|
||||||
# Ячейка "Версия" - только в первой строке каждой версии
|
|
||||||
if first_row_in_version:
|
|
||||||
cell_version = TableCell(stylename=cell_style_name)
|
|
||||||
cell_version.setAttribute("numberrowsspanned", str(row_span_version))
|
|
||||||
p = P(stylename=para_style_name, text=version)
|
|
||||||
cell_version.addElement(p)
|
|
||||||
row.addElement(cell_version)
|
|
||||||
first_row_in_version = False
|
|
||||||
else:
|
|
||||||
# Пропускаем - уже объединена
|
|
||||||
pass
|
|
||||||
|
|
||||||
# Остальные колонки
|
|
||||||
task_cell = TableCell(stylename=cell_style_name)
|
|
||||||
task_text = f"{r['issue_id']}. {r['subject']}"
|
|
||||||
p = P(stylename=para_style_name, text=task_text)
|
|
||||||
task_cell.addElement(p)
|
|
||||||
row.addElement(task_cell)
|
|
||||||
|
|
||||||
status_cell = TableCell(stylename=cell_style_name)
|
|
||||||
p = P(stylename=para_style_name, text=r["status_ru"])
|
|
||||||
status_cell.addElement(p)
|
|
||||||
row.addElement(status_cell)
|
|
||||||
|
|
||||||
time_cell = TableCell(stylename=cell_style_name)
|
|
||||||
p = P(stylename=para_style_name, text=r["time_text"])
|
|
||||||
time_cell.addElement(p)
|
|
||||||
row.addElement(time_cell)
|
|
||||||
|
|
||||||
table.addElement(row)
|
|
||||||
first_version_in_project = False
|
|
||||||
|
|
||||||
doc.text.addElement(table)
|
|
||||||
doc.text.addElement(P(stylename=para_style_name, text=""))
|
|
||||||
|
|
||||||
# Справка
|
|
||||||
for line in [
|
|
||||||
"«Наименование Проекта» - Имя собственное устройства или программного обеспечения.",
|
|
||||||
"«Номер версии» - Версия в проекте. Опциональное поле.",
|
|
||||||
"«Задача» - Номер по Redmine и формулировка.",
|
|
||||||
"«Статус» - Актуальное состояние задачи на момент отчета. Статусы: закрыто, в работе, ожидание, решена.",
|
|
||||||
"«Готовность» – Опциональное поле в процентах.",
|
|
||||||
"«Затрачено за отчетный период» - в днях или часах."
|
|
||||||
]:
|
|
||||||
doc.text.addElement(P(stylename=para_style_name, text=line))
|
|
||||||
|
|
||||||
return doc
|
|
||||||
27
redmine_reporter/formatters/base.py
Normal file
27
redmine_reporter/formatters/base.py
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
from abc import ABC, abstractmethod
|
||||||
|
from typing import List
|
||||||
|
from ..types import ReportRow
|
||||||
|
|
||||||
|
|
||||||
|
class Formatter(ABC):
|
||||||
|
"""
|
||||||
|
Абстрактный базовый класс для всех форматтеров.
|
||||||
|
Определяет общий интерфейс для форматирования отчета.
|
||||||
|
"""
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def format(self, rows: List[ReportRow]) -> str:
|
||||||
|
"""
|
||||||
|
Форматирует список строк отчета в нужный формат.
|
||||||
|
Возвращает строковое представление отчета.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def save(self, rows: List[ReportRow], output_path: str) -> None:
|
||||||
|
"""
|
||||||
|
Сохраняет отформатированный отчет в файл по указанному пути.
|
||||||
|
Для форматтеров, которые не поддерживают сохранение (например, консольные),
|
||||||
|
можно вызывать `format` и записывать результат вручную.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
42
redmine_reporter/formatters/console.py
Normal file
42
redmine_reporter/formatters/console.py
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
from typing import List
|
||||||
|
from tabulate import tabulate
|
||||||
|
from .base import Formatter
|
||||||
|
from ..types import ReportRow
|
||||||
|
|
||||||
|
|
||||||
|
class TableFormatter(Formatter):
|
||||||
|
"""Форматтер для вывода красивой таблицы в консоль."""
|
||||||
|
|
||||||
|
def format(self, rows: List[ReportRow]) -> str:
|
||||||
|
table_rows = [['Проект', 'Версия', 'Задача', 'Статус', 'Затрачено']]
|
||||||
|
for r in rows:
|
||||||
|
table_rows.append([
|
||||||
|
r['display_project'],
|
||||||
|
r['display_version'],
|
||||||
|
f"{r['issue_id']}. {r['subject']}",
|
||||||
|
r['status_ru'],
|
||||||
|
r['time_text']
|
||||||
|
])
|
||||||
|
return tabulate(table_rows, headers="firstrow", tablefmt="fancy_grid")
|
||||||
|
|
||||||
|
def save(self, rows: List[ReportRow], output_path: str) -> None:
|
||||||
|
# Консольные форматтеры не умеют сохранять в файл напрямую.
|
||||||
|
# Это делается в CLI.
|
||||||
|
raise NotImplementedError("TableFormatter не поддерживает сохранение в файл.")
|
||||||
|
|
||||||
|
class CompactFormatter(Formatter):
|
||||||
|
"""Форматтер для компактного вывода в консоль."""
|
||||||
|
|
||||||
|
def format(self, rows: List[ReportRow]) -> str:
|
||||||
|
lines = []
|
||||||
|
for r in rows:
|
||||||
|
lines.append(
|
||||||
|
f"{r['display_project']} | {r['display_version']} | "
|
||||||
|
f"{r['issue_id']}. {r['subject']} | {r['status_ru']} | {r['time_text']}"
|
||||||
|
)
|
||||||
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
def save(self, rows: List[ReportRow], output_path: str) -> None:
|
||||||
|
# Консольные форматтеры не умеют сохранять в файл напрямую.
|
||||||
|
# Это делается в CLI.
|
||||||
|
raise NotImplementedError("CompactFormatter не поддерживает сохранение в файл.")
|
||||||
29
redmine_reporter/formatters/csv.py
Normal file
29
redmine_reporter/formatters/csv.py
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
import csv
|
||||||
|
import io
|
||||||
|
from typing import List
|
||||||
|
from .base import Formatter
|
||||||
|
from ..types import ReportRow
|
||||||
|
|
||||||
|
|
||||||
|
class CSVFormatter(Formatter):
|
||||||
|
"""Форматтер для экспорта в CSV."""
|
||||||
|
|
||||||
|
def format(self, rows: List[ReportRow]) -> str:
|
||||||
|
output = io.StringIO()
|
||||||
|
writer = csv.writer(output, dialect="excel")
|
||||||
|
writer.writerow(["Project", "Version", "Issue ID", "Subject", "Status", "Spent Time"])
|
||||||
|
for r in rows:
|
||||||
|
writer.writerow([
|
||||||
|
r["project"],
|
||||||
|
r["version"],
|
||||||
|
r["issue_id"],
|
||||||
|
r["subject"],
|
||||||
|
r["status_ru"],
|
||||||
|
r["time_text"]
|
||||||
|
])
|
||||||
|
return output.getvalue()
|
||||||
|
|
||||||
|
def save(self, rows: List[ReportRow], output_path: str) -> None:
|
||||||
|
content = self.format(rows)
|
||||||
|
with open(output_path, "w", encoding="utf-8", newline="") as f:
|
||||||
|
f.write(content)
|
||||||
42
redmine_reporter/formatters/factory.py
Normal file
42
redmine_reporter/formatters/factory.py
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
from typing import Dict, Type, Optional
|
||||||
|
from .base import Formatter
|
||||||
|
from .console import TableFormatter, CompactFormatter
|
||||||
|
from .csv import CSVFormatter
|
||||||
|
from .markdown import MarkdownFormatter
|
||||||
|
from .odt import ODTFormatter
|
||||||
|
|
||||||
|
|
||||||
|
# Словарь для сопоставления расширений файлов с классами форматтеров
|
||||||
|
FORMATTER_MAP: Dict[str, Type[Formatter]] = {
|
||||||
|
".odt": ODTFormatter,
|
||||||
|
".csv": CSVFormatter,
|
||||||
|
".md": MarkdownFormatter,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# Словарь для сопоставления типа вывода (консоль) с классами форматтеров
|
||||||
|
CONSOLE_FORMATTER_MAP: Dict[str, Type[Formatter]] = {
|
||||||
|
"table": TableFormatter,
|
||||||
|
"compact": CompactFormatter,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def get_formatter_by_extension(extension: str, **kwargs) -> Optional[Formatter]:
|
||||||
|
"""
|
||||||
|
Возвращает экземпляр форматтера по расширению файла.
|
||||||
|
Ключевые аргументы (**kwargs) передаются в конструктор форматтера.
|
||||||
|
"""
|
||||||
|
formatter_class = FORMATTER_MAP.get(extension.lower())
|
||||||
|
if formatter_class:
|
||||||
|
return formatter_class(**kwargs)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def get_console_formatter(formatter_type: str) -> Optional[Formatter]:
|
||||||
|
"""
|
||||||
|
Возвращает экземпляр консольного форматтера по его типу.
|
||||||
|
"""
|
||||||
|
formatter_class = CONSOLE_FORMATTER_MAP.get(formatter_type.lower())
|
||||||
|
if formatter_class:
|
||||||
|
return formatter_class()
|
||||||
|
return None
|
||||||
25
redmine_reporter/formatters/markdown.py
Normal file
25
redmine_reporter/formatters/markdown.py
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
from typing import List
|
||||||
|
from .base import Formatter
|
||||||
|
from ..types import ReportRow
|
||||||
|
|
||||||
|
|
||||||
|
class MarkdownFormatter(Formatter):
|
||||||
|
"""Форматтер для экспорта в Markdown."""
|
||||||
|
|
||||||
|
def format(self, rows: List[ReportRow]) -> str:
|
||||||
|
lines = [
|
||||||
|
"| Проект | Версия | Задача | Статус | Затрачено |",
|
||||||
|
"|--------|--------|--------|--------|-----------|"
|
||||||
|
]
|
||||||
|
for r in rows:
|
||||||
|
task_cell = f"{r['issue_id']}. {r['subject']}"
|
||||||
|
lines.append(
|
||||||
|
f"| {r['display_project']} | {r['display_version']} "
|
||||||
|
f"| {task_cell} | {r['status_ru']} | {r['time_text']} |"
|
||||||
|
)
|
||||||
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
def save(self, rows: List[ReportRow], output_path: str) -> None:
|
||||||
|
content = self.format(rows)
|
||||||
|
with open(output_path, "w", encoding="utf-8") as f:
|
||||||
|
f.write(content)
|
||||||
151
redmine_reporter/formatters/odt.py
Normal file
151
redmine_reporter/formatters/odt.py
Normal file
@@ -0,0 +1,151 @@
|
|||||||
|
import os
|
||||||
|
from typing import List
|
||||||
|
from odf.opendocument import load
|
||||||
|
from odf.text import P
|
||||||
|
from odf.table import Table, TableColumn, TableRow, TableCell
|
||||||
|
from odf.style import Style, TableColumnProperties, TableCellProperties
|
||||||
|
from .base import Formatter
|
||||||
|
from ..types import ReportRow
|
||||||
|
from ..utils import get_month_name_from_range
|
||||||
|
|
||||||
|
|
||||||
|
class ODTFormatter(Formatter):
|
||||||
|
"""Форматтер для экспорта в ODT."""
|
||||||
|
|
||||||
|
def __init__(self, author: str = "", from_date: str = "", to_date: str = ""):
|
||||||
|
"""
|
||||||
|
Инициализирует форматтер с параметрами для шапки отчета.
|
||||||
|
"""
|
||||||
|
self.author = author
|
||||||
|
self.from_date = from_date
|
||||||
|
self.to_date = to_date
|
||||||
|
|
||||||
|
def format(self, rows: List[ReportRow]) -> "OpenDocument":
|
||||||
|
"""
|
||||||
|
Форматирует данные в объект OpenDocument.
|
||||||
|
"""
|
||||||
|
template_path = "template.odt"
|
||||||
|
if not os.path.exists(template_path):
|
||||||
|
raise FileNotFoundError("Шаблон template.odt не найден...")
|
||||||
|
|
||||||
|
doc = load(template_path)
|
||||||
|
para_style_name = "Standard"
|
||||||
|
|
||||||
|
# Заголовок
|
||||||
|
month_name = get_month_name_from_range(self.from_date, self.to_date)
|
||||||
|
header_text = f"{self.author}. Отчет за месяц {month_name}."
|
||||||
|
doc.text.addElement(P(stylename=para_style_name, text=header_text))
|
||||||
|
doc.text.addElement(P(stylename=para_style_name, text=""))
|
||||||
|
|
||||||
|
# Стиль ячеек
|
||||||
|
cell_style_name = "TableCellStyle"
|
||||||
|
cell_style = Style(name=cell_style_name, family="table-cell")
|
||||||
|
cell_props = TableCellProperties(padding="0.04in", border="0.05pt solid #000000")
|
||||||
|
cell_style.addElement(cell_props)
|
||||||
|
doc.automaticstyles.addElement(cell_style)
|
||||||
|
|
||||||
|
# Таблица
|
||||||
|
table = Table(name="Report")
|
||||||
|
column_widths = ["1.56in", "1.63in", "3.93in", "1.56in", "1.43in"]
|
||||||
|
for width in column_widths:
|
||||||
|
col_style = Style(name=f"col_{width}", family="table-column")
|
||||||
|
col_props = TableColumnProperties(columnwidth=width)
|
||||||
|
col_style.addElement(col_props)
|
||||||
|
doc.automaticstyles.addElement(col_style)
|
||||||
|
table.addElement(TableColumn(stylename=col_style))
|
||||||
|
|
||||||
|
# Заголовки
|
||||||
|
header_row = TableRow()
|
||||||
|
for text in ["Наименование Проекта", "Номер версии*", "Задача", "Статус Готовность*", "Затрачено за отчетный период"]:
|
||||||
|
cell = TableCell(stylename=cell_style_name)
|
||||||
|
cell.addElement(P(stylename=para_style_name, text=text))
|
||||||
|
header_row.addElement(cell)
|
||||||
|
table.addElement(header_row)
|
||||||
|
|
||||||
|
projects = {}
|
||||||
|
for r in rows:
|
||||||
|
project = r["project"]
|
||||||
|
version = r["version"]
|
||||||
|
|
||||||
|
if project not in projects:
|
||||||
|
projects[project] = {}
|
||||||
|
|
||||||
|
if version not in projects[project]:
|
||||||
|
projects[project][version] = []
|
||||||
|
|
||||||
|
projects[project][version].append(r)
|
||||||
|
|
||||||
|
# Данные с двухуровневой группировкой и объединением ячеек
|
||||||
|
for project, versions in projects.items():
|
||||||
|
total_project_rows = sum(len(rows_for_version) for rows_for_version in versions.values())
|
||||||
|
first_version_in_project = True
|
||||||
|
|
||||||
|
for version, rows_for_version in versions.items():
|
||||||
|
row_span_version = len(rows_for_version)
|
||||||
|
first_row_in_version = True
|
||||||
|
|
||||||
|
for r in rows_for_version:
|
||||||
|
row = TableRow()
|
||||||
|
|
||||||
|
# Ячейка "Проект" - только в первой строке всего проекта
|
||||||
|
if first_version_in_project and first_row_in_version:
|
||||||
|
cell_project = TableCell(stylename=cell_style_name)
|
||||||
|
cell_project.setAttribute("numberrowsspanned", str(total_project_rows))
|
||||||
|
p = P(stylename=para_style_name, text=project) # Полное название проекта
|
||||||
|
cell_project.addElement(p)
|
||||||
|
row.addElement(cell_project)
|
||||||
|
|
||||||
|
# Ячейка "Версия" - только в первой строке каждой версии
|
||||||
|
if first_row_in_version:
|
||||||
|
cell_version = TableCell(stylename=cell_style_name)
|
||||||
|
cell_version.setAttribute("numberrowsspanned", str(row_span_version))
|
||||||
|
p = P(stylename=para_style_name, text=version)
|
||||||
|
cell_version.addElement(p)
|
||||||
|
row.addElement(cell_version)
|
||||||
|
first_row_in_version = False
|
||||||
|
else:
|
||||||
|
# Пропускаем - уже объединена
|
||||||
|
pass
|
||||||
|
|
||||||
|
# Остальные колонки
|
||||||
|
task_cell = TableCell(stylename=cell_style_name)
|
||||||
|
task_text = f"{r['issue_id']}. {r['subject']}"
|
||||||
|
p = P(stylename=para_style_name, text=task_text)
|
||||||
|
task_cell.addElement(p)
|
||||||
|
row.addElement(task_cell)
|
||||||
|
|
||||||
|
status_cell = TableCell(stylename=cell_style_name)
|
||||||
|
p = P(stylename=para_style_name, text=r["status_ru"])
|
||||||
|
status_cell.addElement(p)
|
||||||
|
row.addElement(status_cell)
|
||||||
|
|
||||||
|
time_cell = TableCell(stylename=cell_style_name)
|
||||||
|
p = P(stylename=para_style_name, text=r["time_text"])
|
||||||
|
time_cell.addElement(p)
|
||||||
|
row.addElement(time_cell)
|
||||||
|
|
||||||
|
table.addElement(row)
|
||||||
|
first_version_in_project = False
|
||||||
|
|
||||||
|
doc.text.addElement(table)
|
||||||
|
doc.text.addElement(P(stylename=para_style_name, text=""))
|
||||||
|
|
||||||
|
# Справка
|
||||||
|
for line in [
|
||||||
|
"«Наименование Проекта» - Имя собственное устройства или программного обеспечения.",
|
||||||
|
"«Номер версии» - Версия в проекте. Опциональное поле.",
|
||||||
|
"«Задача» - Номер по Redmine и формулировка.",
|
||||||
|
"«Статус» - Актуальное состояние задачи на момент отчета. Статусы: закрыто, в работе, ожидание, решена.",
|
||||||
|
"«Готовность» – Опциональное поле в процентах.",
|
||||||
|
"«Затрачено за отчетный период» - в днях или часах."
|
||||||
|
]:
|
||||||
|
doc.text.addElement(P(stylename=para_style_name, text=line))
|
||||||
|
|
||||||
|
return doc
|
||||||
|
|
||||||
|
def save(self, rows: List[ReportRow], output_path: str) -> None:
|
||||||
|
"""
|
||||||
|
Сохраняет сформированный документ в файл.
|
||||||
|
"""
|
||||||
|
doc = self.format(rows)
|
||||||
|
doc.save(output_path)
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
import pytest
|
|
||||||
from redmine_reporter.cli import parse_date_range
|
|
||||||
|
|
||||||
|
|
||||||
def test_parse_date_range_valid():
|
|
||||||
assert parse_date_range("2025-01-01--2025-12-31") == ("2025-01-01", "2025-12-31")
|
|
||||||
|
|
||||||
|
|
||||||
def test_parse_date_range_with_spaces():
|
|
||||||
assert parse_date_range("2025-01-01 -- 2025-12-31") == ("2025-01-01", "2025-12-31")
|
|
||||||
|
|
||||||
|
|
||||||
def test_parse_date_range_invalid_no_separator():
|
|
||||||
with pytest.raises(ValueError, match="must be in format"):
|
|
||||||
parse_date_range("2025-01-01")
|
|
||||||
|
|
||||||
|
|
||||||
def test_parse_date_range_invalid_parts():
|
|
||||||
with pytest.raises(ValueError, match="Invalid date range format"):
|
|
||||||
parse_date_range("2025-01-01--")
|
|
||||||
@@ -1,73 +0,0 @@
|
|||||||
import tempfile
|
|
||||||
from types import SimpleNamespace
|
|
||||||
from redmine_reporter.formatter_odt import format_odt
|
|
||||||
|
|
||||||
|
|
||||||
def make_mock_issue(id_, project, subject, status, fixed_version=None):
|
|
||||||
"""Создаёт лёгкий mock-объект, имитирующий Issue из redminelib."""
|
|
||||||
|
|
||||||
issue = SimpleNamespace()
|
|
||||||
issue.id = id_
|
|
||||||
issue.project = project
|
|
||||||
issue.subject = subject
|
|
||||||
issue.status = status
|
|
||||||
|
|
||||||
if fixed_version is not None:
|
|
||||||
issue.fixed_version = fixed_version
|
|
||||||
return issue
|
|
||||||
|
|
||||||
|
|
||||||
def test_format_odt_basic():
|
|
||||||
issues = [
|
|
||||||
(make_mock_issue(101, "Камеры", "Поддержка нового датчика", "In Progress", "v2.5.0"), 2.5),
|
|
||||||
(make_mock_issue(102, "Камеры", "Исправить утечку памяти", "Resolved", "v2.5.0"), 4.0),
|
|
||||||
(make_mock_issue(103, "ПО", "Обновить документацию", "Pending", None), 12.0),
|
|
||||||
]
|
|
||||||
|
|
||||||
doc = format_odt(issues)
|
|
||||||
|
|
||||||
# Сохраняем и проверяем содержимое
|
|
||||||
with tempfile.NamedTemporaryFile(suffix=".odt") as tmp:
|
|
||||||
doc.save(tmp.name)
|
|
||||||
|
|
||||||
# Проверяем, что файл - это ZIP (ODT основан на ZIP)
|
|
||||||
with open(tmp.name, "rb") as f:
|
|
||||||
assert f.read(2) == b"PK"
|
|
||||||
|
|
||||||
# Извлекаем content.xml
|
|
||||||
import zipfile
|
|
||||||
with zipfile.ZipFile(tmp.name) as zf:
|
|
||||||
content_xml = zf.read("content.xml").decode("utf-8")
|
|
||||||
|
|
||||||
# Проверяем заголовки
|
|
||||||
assert "Проект" in content_xml
|
|
||||||
assert "Версия" in content_xml
|
|
||||||
assert "Задача" in content_xml
|
|
||||||
assert "Статус" in content_xml
|
|
||||||
assert "Затрачено" in content_xml
|
|
||||||
|
|
||||||
# Проверяем данные задач
|
|
||||||
assert "101. Поддержка нового датчика" in content_xml
|
|
||||||
assert "102. Исправить утечку памяти" in content_xml
|
|
||||||
assert "103. Обновить документацию" in content_xml
|
|
||||||
|
|
||||||
# Проверяем проекты и версии
|
|
||||||
assert "Камеры" in content_xml
|
|
||||||
assert "ПО" in content_xml
|
|
||||||
assert "v2.5.0" in content_xml
|
|
||||||
assert "<N/A>" in content_xml or "<N/A>" in content_xml # зависит от экранирования
|
|
||||||
|
|
||||||
# Проверяем перевод статусов
|
|
||||||
assert "В работе" in content_xml # In Progress
|
|
||||||
assert "Решена" in content_xml # Resolved
|
|
||||||
assert "Ожидание" in content_xml # Pending
|
|
||||||
|
|
||||||
# Проверяем формат времени
|
|
||||||
assert "2ч 30м" in content_xml
|
|
||||||
assert "4ч" in content_xml
|
|
||||||
assert "12ч" in content_xml
|
|
||||||
|
|
||||||
# Проверяем группировку: "Камеры" должен встречаться только один раз явно
|
|
||||||
# (вторая строка — пустая ячейка)
|
|
||||||
cam_occurrences = content_xml.count(">Камеры<")
|
|
||||||
assert cam_occurrences == 1
|
|
||||||
175
tests/test_formatters.py
Normal file
175
tests/test_formatters.py
Normal file
@@ -0,0 +1,175 @@
|
|||||||
|
import pytest
|
||||||
|
import os
|
||||||
|
from typing import List
|
||||||
|
from redmine_reporter.types import ReportRow
|
||||||
|
from redmine_reporter.formatters.console import TableFormatter, CompactFormatter
|
||||||
|
from redmine_reporter.formatters.csv import CSVFormatter
|
||||||
|
from redmine_reporter.formatters.markdown import MarkdownFormatter
|
||||||
|
from redmine_reporter.formatters.odt import ODTFormatter
|
||||||
|
from odf.opendocument import OpenDocument
|
||||||
|
|
||||||
|
|
||||||
|
def make_fake_report_rows() -> List[ReportRow]:
|
||||||
|
"""
|
||||||
|
Генерирует фейковый отчёт с полным покрытием логики группировки:
|
||||||
|
- Проект A: версия v1.0 (2 задачи), версия v2.0 (1 задача)
|
||||||
|
- Проект B: версия <N/A> (1 задача)
|
||||||
|
- Проект C: версия v1.0 (1 задача), версия v1.1 (2 задачи)
|
||||||
|
"""
|
||||||
|
|
||||||
|
return [
|
||||||
|
# Проект A, v1.0
|
||||||
|
{
|
||||||
|
"project": "Проект A",
|
||||||
|
"version": "v1.0",
|
||||||
|
"display_project": "Проект A",
|
||||||
|
"display_version": "v1.0",
|
||||||
|
"issue_id": 101,
|
||||||
|
"subject": "Реализовать фичу X",
|
||||||
|
"status_ru": "В работе",
|
||||||
|
"time_text": "4ч 30м"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"project": "Проект A",
|
||||||
|
"version": "v1.0",
|
||||||
|
"display_project": "",
|
||||||
|
"display_version": "",
|
||||||
|
"issue_id": 102,
|
||||||
|
"subject": "Исправить баг Y",
|
||||||
|
"status_ru": "Решена",
|
||||||
|
"time_text": "2ч"
|
||||||
|
},
|
||||||
|
# Проект A, v2.0
|
||||||
|
{
|
||||||
|
"project": "Проект A",
|
||||||
|
"version": "v2.0",
|
||||||
|
"display_project": "",
|
||||||
|
"display_version": "v2.0",
|
||||||
|
"issue_id": 103,
|
||||||
|
"subject": "Документация Z",
|
||||||
|
"status_ru": "Ожидание",
|
||||||
|
"time_text": "1ч"
|
||||||
|
},
|
||||||
|
# Проект B, без версии
|
||||||
|
{
|
||||||
|
"project": "Проект B",
|
||||||
|
"version": "<N/A>",
|
||||||
|
"display_project": "Проект B",
|
||||||
|
"display_version": "<N/A>",
|
||||||
|
"issue_id": 201,
|
||||||
|
"subject": "Обновить README",
|
||||||
|
"status_ru": "Закрыто",
|
||||||
|
"time_text": "0ч"
|
||||||
|
},
|
||||||
|
# Проект C, v1.0
|
||||||
|
{
|
||||||
|
"project": "Проект C",
|
||||||
|
"version": "v1.0",
|
||||||
|
"display_project": "Проект C",
|
||||||
|
"display_version": "v1.0",
|
||||||
|
"issue_id": 301,
|
||||||
|
"subject": "Настроить CI",
|
||||||
|
"status_ru": "В работе",
|
||||||
|
"time_text": "3ч 15м"
|
||||||
|
},
|
||||||
|
# Проект C, v1.1
|
||||||
|
{
|
||||||
|
"project": "Проект C",
|
||||||
|
"version": "v1.1",
|
||||||
|
"display_project": "",
|
||||||
|
"display_version": "v1.1",
|
||||||
|
"issue_id": 302,
|
||||||
|
"subject": "Добавить тесты",
|
||||||
|
"status_ru": "В работе",
|
||||||
|
"time_text": "5ч"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"project": "Проект C",
|
||||||
|
"version": "v1.1",
|
||||||
|
"display_project": "",
|
||||||
|
"display_version": "",
|
||||||
|
"issue_id": 303,
|
||||||
|
"subject": "Рефакторинг",
|
||||||
|
"status_ru": "Решена",
|
||||||
|
"time_text": "6ч 45м"
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def fake_rows():
|
||||||
|
return make_fake_report_rows()
|
||||||
|
|
||||||
|
|
||||||
|
def _get_formatter_output_text(result):
|
||||||
|
"""Преобразует результат форматтера в строку для проверки содержимого."""
|
||||||
|
|
||||||
|
if isinstance(result, OpenDocument):
|
||||||
|
return ""
|
||||||
|
elif isinstance(result, str):
|
||||||
|
return result
|
||||||
|
else:
|
||||||
|
raise TypeError(f"Unexpected formatter output type: {type(result)}")
|
||||||
|
|
||||||
|
|
||||||
|
FORMATTER_FACTORIES = [
|
||||||
|
("table", lambda: TableFormatter()),
|
||||||
|
("compact", lambda: CompactFormatter()),
|
||||||
|
("csv", lambda: CSVFormatter()),
|
||||||
|
("markdown", lambda: MarkdownFormatter()),
|
||||||
|
("odt", lambda: ODTFormatter(author="Тест Автор", from_date="2026-01-01", to_date="2026-01-31")),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("name, formatter_factory", FORMATTER_FACTORIES)
|
||||||
|
def test_formatter_does_not_crash(fake_rows, name, formatter_factory):
|
||||||
|
"""Проверяем, что форматтер не падает на валидных данных."""
|
||||||
|
|
||||||
|
formatter = formatter_factory()
|
||||||
|
result = formatter.format(fake_rows)
|
||||||
|
|
||||||
|
if name == "odt":
|
||||||
|
assert isinstance(result, OpenDocument)
|
||||||
|
else:
|
||||||
|
assert isinstance(result, str)
|
||||||
|
assert len(result.strip()) > 0
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("name, formatter_factory", FORMATTER_FACTORIES)
|
||||||
|
def test_formatter_contains_key_content(fake_rows, name, formatter_factory):
|
||||||
|
"""Проверяем, что вывод содержит ключевые элементы."""
|
||||||
|
|
||||||
|
formatter = formatter_factory()
|
||||||
|
result = formatter.format(fake_rows)
|
||||||
|
|
||||||
|
output_text = _get_formatter_output_text(result)
|
||||||
|
if not output_text:
|
||||||
|
return # Пропускаем ODT
|
||||||
|
|
||||||
|
# Общие элементы
|
||||||
|
assert "Проект A" in output_text
|
||||||
|
assert "Проект B" in output_text
|
||||||
|
assert "В работе" in output_text
|
||||||
|
assert "<N/A>" in output_text
|
||||||
|
assert "6ч 45м" in output_text
|
||||||
|
|
||||||
|
# Специфика по форматам
|
||||||
|
if name == "csv":
|
||||||
|
# В CSV ID и subject — отдельные колонки
|
||||||
|
assert "101" in output_text
|
||||||
|
assert "Реализовать фичу X" in output_text
|
||||||
|
else:
|
||||||
|
# В остальных — вместе
|
||||||
|
assert "101. Реализовать фичу X" in output_text
|
||||||
|
|
||||||
|
|
||||||
|
def test_odt_save_creates_valid_file(fake_rows, tmp_path):
|
||||||
|
"""Проверяем, что ODT можно сохранить и он открывается как ZIP."""
|
||||||
|
|
||||||
|
output_file = tmp_path / "report.odt"
|
||||||
|
formatter = ODTFormatter(author="Тест", from_date="2026-01-01", to_date="2026-01-31")
|
||||||
|
formatter.save(fake_rows, str(output_file))
|
||||||
|
|
||||||
|
assert output_file.exists()
|
||||||
|
with open(output_file, "rb") as f:
|
||||||
|
assert f.read(2) == b"PK" # сигнатура ZIP
|
||||||
Reference in New Issue
Block a user