Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f858618a13 | ||
|
|
e344715f61 | ||
|
|
245ea0a3fa | ||
|
|
2a39de467f | ||
|
|
6416df481e | ||
|
|
ead6c72d16 | ||
|
|
e7efda232c | ||
|
|
937885a12b | ||
|
|
932dd1198a | ||
|
|
0bff2363dc | ||
|
|
9b260b27fd | ||
|
|
a8511368ce |
6
.gitignore
vendored
6
.gitignore
vendored
@@ -85,3 +85,9 @@ secrets.json
|
||||
# Temporary files
|
||||
*.tmp
|
||||
*.bak
|
||||
|
||||
# Just in case
|
||||
.~*
|
||||
report.odt
|
||||
report.csv
|
||||
report.md
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
- Перевод статусов на русский язык
|
||||
- Простой CLI с понятными аргументами
|
||||
- Поддержка настройки диапазона дат по умолчанию через `.env`
|
||||
- Экспорт в ODT с автоматическим заголовком (автор + месяц)
|
||||
- Экспорт в ODT, CSV и Markdown
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "redmine-reporter"
|
||||
version = "1.1.0"
|
||||
version = "1.3.0"
|
||||
description = "Redmine time-entry based issue reporter for internal use"
|
||||
readme = "README.md"
|
||||
authors = [{ name = "Artem Kokos", email = "artem-kokos@mail.ru" }]
|
||||
|
||||
@@ -1 +1 @@
|
||||
__version__ = "1.1.0"
|
||||
__version__ = "1.3.0"
|
||||
|
||||
@@ -5,8 +5,11 @@ from redminelib.resources import Issue
|
||||
|
||||
from .config import Config
|
||||
from .client import fetch_issues_with_spent_time
|
||||
from .report_builder import build_grouped_report
|
||||
from .formatter import format_compact, format_table
|
||||
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]:
|
||||
@@ -43,6 +46,11 @@ def main(argv: Optional[List[str]] = None) -> int:
|
||||
default="",
|
||||
help="Override author name from .env (REDMINE_AUTHOR)"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--no-time",
|
||||
action="store_true",
|
||||
help="Do not include spent time into table"
|
||||
)
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
try:
|
||||
@@ -69,27 +77,48 @@ def main(argv: Optional[List[str]] = None) -> int:
|
||||
|
||||
print(f"✅ Total issues: {len(issue_hours)} [{args.date}]")
|
||||
|
||||
rows = build_grouped_report(issue_hours, fill_time=not args.no_time)
|
||||
|
||||
if args.output:
|
||||
if not args.output.endswith(".odt"):
|
||||
print("❌ Output file must end with .odt", file=sys.stderr)
|
||||
if not (args.output.endswith(".odt") or args.output.endswith(".csv") or args.output.endswith(".md")):
|
||||
print("❌ Output file must end with .odt, .csv or .md", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
try:
|
||||
author = Config.get_author(args.author)
|
||||
doc = format_odt(issue_hours, author=author, from_date=from_date, to_date=to_date)
|
||||
doc.save(args.output)
|
||||
if args.output.endswith(".odt"):
|
||||
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}")
|
||||
except ImportError:
|
||||
print("❌ odfpy is not installed. Install with: pip install odfpy", file=sys.stderr)
|
||||
except ImportError as e:
|
||||
if args.output.endswith(".odt"):
|
||||
print("❌ odfpy is not installed. Install with: pip install odfpy", file=sys.stderr)
|
||||
else:
|
||||
print(f"❌ Import error: {e}", file=sys.stderr)
|
||||
return 1
|
||||
except Exception as e:
|
||||
print(f"❌ ODT export error: {e}", file=sys.stderr)
|
||||
fmt = "ODT" if args.output.endswith(".odt") else ("CSV" if args.output.endswith(".csv") else "Markdown")
|
||||
print(f"❌ {fmt} export error: {e}", file=sys.stderr)
|
||||
return 1
|
||||
else:
|
||||
try:
|
||||
if args.compact:
|
||||
output = format_compact(issue_hours)
|
||||
output = format_compact(rows)
|
||||
else:
|
||||
output = format_table(issue_hours)
|
||||
output = format_table(rows)
|
||||
print(output)
|
||||
except Exception as e:
|
||||
print(f"❌ Formatting error: {e}", file=sys.stderr)
|
||||
|
||||
@@ -1,83 +1,30 @@
|
||||
from typing import List, Tuple
|
||||
from redminelib.resources import Issue
|
||||
from .utils import get_version
|
||||
from typing import List
|
||||
from tabulate import tabulate
|
||||
from .types import ReportRow
|
||||
|
||||
|
||||
STATUS_TRANSLATION = {
|
||||
'Closed': 'Закрыто',
|
||||
'Re-opened': 'В работе',
|
||||
'New': 'В работе',
|
||||
'Resolved': 'Решена',
|
||||
'Pending': 'Ожидание',
|
||||
'Feedback': 'В работе',
|
||||
'In Progress': 'В работе',
|
||||
'Rejected': 'Закрыто',
|
||||
'Confirming': 'Ожидание',
|
||||
}
|
||||
|
||||
|
||||
def hours_to_human(hours: float) -> str:
|
||||
if hours <= 0:
|
||||
return "0ч"
|
||||
|
||||
total_minutes = round(hours * 60)
|
||||
h = total_minutes // 60
|
||||
m = total_minutes % 60
|
||||
parts = []
|
||||
|
||||
if h:
|
||||
parts.append(f"{h}ч")
|
||||
if m:
|
||||
parts.append(f"{m}м")
|
||||
|
||||
return " ".join(parts) if parts else "0ч"
|
||||
|
||||
|
||||
def format_compact(issue_hours: List[Tuple[Issue, float]]) -> str:
|
||||
def format_compact(rows: List[ReportRow]) -> str:
|
||||
lines = []
|
||||
prev_project = None
|
||||
prev_version = None
|
||||
|
||||
for issue, hours in issue_hours:
|
||||
project = str(issue.project)
|
||||
version = get_version(issue)
|
||||
status = str(issue.status)
|
||||
|
||||
display_project = project if project != prev_project else ""
|
||||
display_version = version if (project != prev_project or version != prev_version) else ""
|
||||
lines.append(f"{display_project} | {display_version} | {issue.id}. {issue.subject} | {status} | {hours_to_human(hours)}")
|
||||
|
||||
prev_project = project
|
||||
prev_version = version
|
||||
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(issue_hours: List[Tuple[Issue, float]]) -> str:
|
||||
from tabulate import tabulate
|
||||
def format_table(rows: List[ReportRow]) -> str:
|
||||
table_rows = [['Проект', 'Версия', 'Задача', 'Статус', 'Затрачено']]
|
||||
|
||||
rows = [['Проект', 'Версия', 'Задача', 'Статус', 'Затрачено']]
|
||||
prev_project = None
|
||||
prev_version = None
|
||||
|
||||
for issue, hours in issue_hours:
|
||||
project = str(issue.project)
|
||||
version = get_version(issue)
|
||||
status_en = str(issue.status)
|
||||
status_ru = STATUS_TRANSLATION.get(status_en, status_en)
|
||||
|
||||
display_project = project if project != prev_project else ""
|
||||
display_version = version if (project != prev_project or version != prev_version) else ""
|
||||
|
||||
rows.append([
|
||||
display_project,
|
||||
display_version,
|
||||
f"{issue.id}. {issue.subject}",
|
||||
status_ru,
|
||||
hours_to_human(hours)
|
||||
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']
|
||||
])
|
||||
|
||||
prev_project = project
|
||||
prev_version = version
|
||||
|
||||
return tabulate(rows, headers="firstrow", tablefmt="fancy_grid")
|
||||
return tabulate(table_rows, headers="firstrow", tablefmt="fancy_grid")
|
||||
|
||||
22
redmine_reporter/formatter_csv.py
Normal file
22
redmine_reporter/formatter_csv.py
Normal file
@@ -0,0 +1,22 @@
|
||||
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()
|
||||
19
redmine_reporter/formatter_md.py
Normal file
19
redmine_reporter/formatter_md.py
Normal file
@@ -0,0 +1,19 @@
|
||||
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,19 +1,18 @@
|
||||
import os
|
||||
from typing import List, Tuple
|
||||
from redminelib.resources import Issue
|
||||
from typing import List
|
||||
from odf.opendocument import load
|
||||
from odf.text import P
|
||||
from odf.table import Table, TableColumn, TableRow, TableCell
|
||||
|
||||
from .formatter import get_version, hours_to_human, STATUS_TRANSLATION
|
||||
from odf.style import Style, TableColumnProperties, TableCellProperties
|
||||
from .types import ReportRow
|
||||
from .utils import get_month_name_from_range
|
||||
|
||||
|
||||
def format_odt(
|
||||
issue_hours: List[Tuple[Issue, float]],
|
||||
rows: List[ReportRow],
|
||||
author: str = "",
|
||||
from_date: str = "",
|
||||
to_date: str = ""
|
||||
to_date: str = "",
|
||||
) -> "OpenDocument":
|
||||
template_path = "template.odt"
|
||||
if not os.path.exists(template_path):
|
||||
@@ -25,61 +24,67 @@ def format_odt(
|
||||
# Заголовок
|
||||
month_name = get_month_name_from_range(from_date, to_date)
|
||||
header_text = f"{author}. Отчет за месяц {month_name}."
|
||||
header_paragraph = P(stylename=para_style_name, text=header_text)
|
||||
doc.text.addElement(header_paragraph)
|
||||
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)
|
||||
|
||||
# Группировка: project - version - [(issue, hours, status_ru)]
|
||||
projects = {}
|
||||
for issue, hours in issue_hours:
|
||||
project = str(issue.project)
|
||||
version = get_version(issue)
|
||||
status_en = str(issue.status)
|
||||
status_ru = STATUS_TRANSLATION.get(status_en, status_en)
|
||||
|
||||
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((issue, hours, status_ru))
|
||||
|
||||
# Создаём таблицу
|
||||
table = Table(name="Report")
|
||||
for _ in range(5):
|
||||
table.addElement(TableColumn())
|
||||
|
||||
# Заголовки
|
||||
header_row = TableRow()
|
||||
headers = ["Наименование Проекта", "Номер версии*", "Задача", "Статус Готовность*", "Затрачено за отчетный период"]
|
||||
for text in headers:
|
||||
cell = TableCell()
|
||||
p = P(stylename=para_style_name, text=text)
|
||||
cell.addElement(p)
|
||||
header_row.addElement(cell)
|
||||
table.addElement(header_row)
|
||||
projects[project][version].append(r)
|
||||
|
||||
# Данные с двухуровневой группировкой и объединением ячеек
|
||||
for project, versions in projects.items():
|
||||
total_project_rows = sum(len(rows) for rows in versions.values())
|
||||
total_project_rows = sum(len(rows_for_version) for rows_for_version in versions.values())
|
||||
first_version_in_project = True
|
||||
|
||||
for version, rows in versions.items():
|
||||
row_span_version = len(rows)
|
||||
for version, rows_for_version in versions.items():
|
||||
row_span_version = len(rows_for_version)
|
||||
first_row_in_version = True
|
||||
|
||||
for issue, hours, status_ru in rows:
|
||||
for r in rows_for_version:
|
||||
row = TableRow()
|
||||
|
||||
# Ячейка "Проект" - только в первой строке всего проекта
|
||||
if first_version_in_project and first_row_in_version:
|
||||
cell_project = TableCell()
|
||||
cell_project = TableCell(stylename=cell_style_name)
|
||||
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)
|
||||
row.addElement(cell_project)
|
||||
|
||||
# Ячейка "Версия" - только в первой строке каждой версии
|
||||
if first_row_in_version:
|
||||
cell_version = TableCell()
|
||||
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)
|
||||
@@ -90,24 +95,37 @@ def format_odt(
|
||||
pass
|
||||
|
||||
# Остальные колонки
|
||||
task_cell = TableCell()
|
||||
p = P(stylename=para_style_name, text=f"{issue.id}. {issue.subject}")
|
||||
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()
|
||||
p = P(stylename=para_style_name, text=status_ru)
|
||||
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()
|
||||
p = P(stylename=para_style_name, text=hours_to_human(hours))
|
||||
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
|
||||
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
|
||||
|
||||
62
redmine_reporter/report_builder.py
Normal file
62
redmine_reporter/report_builder.py
Normal file
@@ -0,0 +1,62 @@
|
||||
from typing import List, Tuple, cast
|
||||
from redminelib.resources import Issue
|
||||
from .types import ReportRow
|
||||
from .utils import get_version, hours_to_human
|
||||
|
||||
|
||||
STATUS_TRANSLATION = {
|
||||
'Closed': 'Закрыто',
|
||||
'Re-opened': 'В работе',
|
||||
'New': 'В работе',
|
||||
'Resolved': 'Решена',
|
||||
'Pending': 'Ожидание',
|
||||
'Feedback': 'В работе',
|
||||
'In Progress': 'В работе',
|
||||
'Rejected': 'Закрыто',
|
||||
'Confirming': 'Ожидание',
|
||||
}
|
||||
|
||||
|
||||
def build_grouped_report(
|
||||
issue_hours: List[Tuple[Issue, float]],
|
||||
fill_time: bool = True,
|
||||
) -> List[ReportRow]:
|
||||
"""
|
||||
Преобразует список задач с затраченным временем в плоский список строк отчёта,
|
||||
с учётом группировки по проекту и версии (пустые ячейки для повторяющихся значений).
|
||||
"""
|
||||
|
||||
rows: List[ReportRow] = []
|
||||
prev_project: str = ""
|
||||
prev_version: str = ""
|
||||
|
||||
for issue, hours in issue_hours:
|
||||
project = str(issue.project)
|
||||
version = get_version(issue)
|
||||
status_en = str(issue.status)
|
||||
status_ru = STATUS_TRANSLATION.get(status_en, status_en)
|
||||
time_text = hours_to_human(hours) if fill_time else ""
|
||||
|
||||
display_project = project if project != prev_project else ""
|
||||
display_version = version if (project != prev_project or version != prev_version) else ""
|
||||
|
||||
rows.append(
|
||||
cast(
|
||||
ReportRow,
|
||||
{
|
||||
"project": project,
|
||||
"version": version,
|
||||
"display_project": display_project,
|
||||
"display_version": display_version,
|
||||
"issue_id": issue.id,
|
||||
"subject": issue.subject,
|
||||
"status_ru": status_ru,
|
||||
"time_text": time_text,
|
||||
},
|
||||
)
|
||||
)
|
||||
|
||||
prev_project = project
|
||||
prev_version = version
|
||||
|
||||
return rows
|
||||
14
redmine_reporter/types.py
Normal file
14
redmine_reporter/types.py
Normal file
@@ -0,0 +1,14 @@
|
||||
from typing import TypedDict
|
||||
|
||||
|
||||
class ReportRow(TypedDict):
|
||||
"""Строка итогового отчёта."""
|
||||
|
||||
project: str
|
||||
version: str
|
||||
display_project: str
|
||||
display_version: str
|
||||
issue_id: int
|
||||
subject: str
|
||||
status_ru: str
|
||||
time_text: str
|
||||
@@ -2,22 +2,40 @@ from datetime import datetime
|
||||
|
||||
|
||||
def get_month_name_from_range(from_date: str, to_date: str) -> str:
|
||||
"""Определяет название месяца по диапазону дат.
|
||||
- Если from == to - возвращает месяц этой даты.
|
||||
- Если диапазон охватывает несколько месяцев - возвращает месяц из to_date.
|
||||
"""
|
||||
"""Определяет название месяца по диапазону дат"""
|
||||
|
||||
try:
|
||||
end = datetime.strptime(to_date, "%Y-%m-%d")
|
||||
except ValueError:
|
||||
return "Январь" # fallback, хотя лучше бы не срабатывало
|
||||
return "Январь"
|
||||
|
||||
months = [
|
||||
"", "Январь", "Февраль", "Март", "Апрель", "Май", "Июнь",
|
||||
"Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь"
|
||||
]
|
||||
|
||||
return months[end.month]
|
||||
|
||||
|
||||
def get_version(issue) -> str:
|
||||
"""Возвращает версию задачи или '<N/A>', если не задана."""
|
||||
return str(getattr(issue, 'fixed_version', '<N/A>'))
|
||||
|
||||
|
||||
def hours_to_human(hours: float) -> str:
|
||||
"""Преобразует часы в человекочитаемый формат: '2ч 30м'."""
|
||||
|
||||
if hours <= 0:
|
||||
return "0ч"
|
||||
|
||||
total_minutes = round(hours * 60)
|
||||
h = total_minutes // 60
|
||||
m = total_minutes % 60
|
||||
parts = []
|
||||
|
||||
if h:
|
||||
parts.append(f"{h}ч")
|
||||
if m:
|
||||
parts.append(f"{m}м")
|
||||
|
||||
return " ".join(parts) if parts else "0ч"
|
||||
|
||||
Reference in New Issue
Block a user