refactor(reports): модульное разделение excel_exporter на styles, calculators и билдеры отчетов
This commit is contained in:
@@ -0,0 +1,80 @@
|
||||
"""
|
||||
===============================================================================
|
||||
FILE: services/reports/styles.py
|
||||
ROLE: Стили, палитры цветов, форматирование дат и защита от блокировок Excel.
|
||||
===============================================================================
|
||||
"""
|
||||
|
||||
import os
|
||||
import time
|
||||
from datetime import datetime
|
||||
from xlsxwriter.exceptions import FileCreateError
|
||||
from config import REPORTS_DIR
|
||||
|
||||
MONTHS_RU_GENITIVE = {
|
||||
1: "января", 2: "февраля", 3: "марта", 4: "апреля",
|
||||
5: "мая", 6: "июня", 7: "июля", 8: "августа",
|
||||
9: "сентября", 10: "октября", 11: "ноября", 12: "декабря"
|
||||
}
|
||||
|
||||
MONTHS_RU_NOMINATIVE = {
|
||||
1: "январь", 2: "февраль", 3: "март", 4: "апрель",
|
||||
5: "май", 6: "июнь", 7: "июль", 8: "август",
|
||||
9: "сентябрь", 10: "октябрь", 11: "ноябрь", 12: "декабрь"
|
||||
}
|
||||
|
||||
|
||||
def format_date_ru(date_str):
|
||||
date_clean = str(date_str).replace('_', '.')
|
||||
try:
|
||||
dt = datetime.strptime(date_clean, "%d.%m.%Y")
|
||||
return f"{dt.day} {MONTHS_RU_GENITIVE[dt.month]} {dt.year}"
|
||||
except Exception:
|
||||
return date_str
|
||||
|
||||
|
||||
def get_dated_reports_dir(date_str):
|
||||
date_clean = str(date_str).replace('_', '.')
|
||||
try:
|
||||
dt = datetime.strptime(date_clean, "%d.%m.%Y")
|
||||
year_str = str(dt.year)
|
||||
month_name = MONTHS_RU_NOMINATIVE[dt.month]
|
||||
except Exception:
|
||||
now = datetime.now()
|
||||
year_str = str(now.year)
|
||||
month_name = MONTHS_RU_NOMINATIVE[now.month]
|
||||
|
||||
target_dir = os.path.join(REPORTS_DIR, year_str, month_name)
|
||||
os.makedirs(target_dir, exist_ok=True)
|
||||
return target_dir
|
||||
|
||||
|
||||
def safe_close_workbook(wb, output_path, target_dir, filename):
|
||||
try:
|
||||
wb.close()
|
||||
return output_path
|
||||
except (FileCreateError, OSError, PermissionError):
|
||||
alt_filename = filename.replace(".xlsx", f"_{int(time.time())}.xlsx")
|
||||
alt_path = os.path.join(target_dir, alt_filename)
|
||||
try:
|
||||
wb.filename = alt_path
|
||||
wb._store_workbook()
|
||||
return alt_path
|
||||
except Exception:
|
||||
return output_path
|
||||
|
||||
|
||||
def create_xlsx_format(workbook, font_name="Calibri", font_size=11, bg_color=None, bold=False, align="left", wrap=False):
|
||||
fmt_dict = {
|
||||
'font_name': font_name,
|
||||
'font_size': font_size,
|
||||
'bold': bold,
|
||||
'align': align,
|
||||
'valign': 'vcenter',
|
||||
'border': 1,
|
||||
'border_color': '#D3D3D3',
|
||||
'text_wrap': wrap
|
||||
}
|
||||
if bg_color:
|
||||
fmt_dict['bg_color'] = bg_color
|
||||
return workbook.add_format(fmt_dict)
|
||||
Reference in New Issue
Block a user