- ExcelRepository: canonical columns with ru/en aliases, date/number normalization (Excel dates, DD.MM.YYYY, '1 234,56', currency symbols, parentheses), account name->UUID resolution, per-row errors with sheet!row, warnings for formulas without cached values, duplicate names and default exchange rates - ExcelTemplate: skeleton generator (number/date formats, dropdowns for currency, frequency en/ru and account, 'Инструкция' sheet); ship data/model_template.xlsx - CLI: cf template-xlsx [--force]; cf import-xlsx --dry-run with rich error table, import writes nothing when the file has errors - RecurringCashflow.account (empty = all accounts) + name/UUID matching in forecast; cf config recurring-add --account, account column in info/recurring-list - Forecast: runs are idempotent, 'Итог: Баланс' sums all accounts of the last month - README: 'Сборка модели в Excel' section - ruff check . clean (9 pre-existing import/line-length findings fixed) - MetaAgent: T9 archived, req-T9 approved, manifest/checkpoints/state synced 118 tests pass
223 lines
9.4 KiB
Python
223 lines
9.4 KiB
Python
"""Генератор пустого Excel-шаблона для ручного заполнения модели.
|
|
|
|
``write_template(path)`` создаёт .xlsx только с заголовками листов, форматами
|
|
чисел и выпадающими списками, плюс лист «Инструкция» на русском. Шаблон
|
|
импортируется без ошибок и даёт пустую ``FinancialModel``.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
from pathlib import Path
|
|
|
|
from openpyxl import Workbook
|
|
from openpyxl.styles import Font
|
|
from openpyxl.utils import get_column_letter
|
|
from openpyxl.worksheet.datavalidation import DataValidation
|
|
|
|
from domain.currency import CURRENCY_DECIMALS
|
|
from infrastructure.repositories.excel_repository import (
|
|
CANONICAL_COLUMNS,
|
|
CELL_NUMBER_FORMATS,
|
|
COLUMN_WIDTHS,
|
|
FIELD_KINDS,
|
|
ExcelRepositoryError,
|
|
)
|
|
|
|
_TEMPLATE_ROWS = 500
|
|
_VALIDATION_ROWS = 1000
|
|
_ACCOUNT_RANGE = "=Accounts!$B$2:$B$500"
|
|
_INSTRUCTION_SHEET = "Инструкция"
|
|
|
|
_FREQUENCIES_EN = ("daily", "weekly", "monthly", "yearly")
|
|
_FREQUENCIES_RU = ("ежедневно", "еженедельно", "ежемесячно", "ежегодно")
|
|
|
|
# Подсказка по типу значения: (обязательно, формат / допустимые значения).
|
|
_KIND_HELP: dict[str, tuple[str, str]] = {
|
|
"id": ("нет", "UUID или пусто — id создаётся автоматически"),
|
|
"text": ("—", "текст"),
|
|
"currency": ("—", "код валюты: " + ", ".join(CURRENCY_DECIMALS)),
|
|
"decimal": ("—", "число, напр. 1 234,56"),
|
|
"date": ("—", "2026-01-31, 31.01.2026, 31/01/2026, 2026/01/31, 31-01-2026"),
|
|
"frequency": (
|
|
"—",
|
|
"daily / weekly / monthly / yearly "
|
|
"(ежедневно / еженедельно / ежемесячно / ежегодно)",
|
|
),
|
|
"account": ("да", "имя счёта из листа Accounts"),
|
|
"account_optional": ("нет", "имя счёта из Accounts; пусто = все счета"),
|
|
}
|
|
|
|
_REQUIRED: dict[tuple[str, str], bool] = {
|
|
("Accounts", "name"): True,
|
|
("Transactions", "date"): True,
|
|
("Transactions", "account"): True,
|
|
("Transactions", "amount"): True,
|
|
("Recurring", "start_date"): True,
|
|
("Recurring", "frequency"): True,
|
|
("Recurring", "amount"): True,
|
|
("Assets", "name"): True,
|
|
("Liabilities", "name"): True,
|
|
("ExchangeRates", "from_currency"): True,
|
|
("ExchangeRates", "to_currency"): True,
|
|
("ExchangeRates", "rate"): True,
|
|
}
|
|
|
|
|
|
def _column_index(sheet_name: str, field_name: str) -> int:
|
|
return CANONICAL_COLUMNS[sheet_name].index(field_name) + 1
|
|
|
|
|
|
def _list_validation(values: tuple[str, ...], *, prompt: str) -> DataValidation:
|
|
return DataValidation(
|
|
type="list",
|
|
formula1='"' + ",".join(values) + '"',
|
|
allow_blank=True,
|
|
showDropDown=False,
|
|
promptTitle="Допустимые значения",
|
|
prompt=prompt,
|
|
)
|
|
|
|
|
|
def _account_validation() -> DataValidation:
|
|
return DataValidation(
|
|
type="list",
|
|
formula1=_ACCOUNT_RANGE,
|
|
allow_blank=True,
|
|
showDropDown=False,
|
|
promptTitle="Счёт",
|
|
prompt="Имя счёта из листа Accounts",
|
|
)
|
|
|
|
|
|
def _write_columns_sheet(wb: Workbook, sheet_name: str) -> None:
|
|
headers = list(CANONICAL_COLUMNS[sheet_name])
|
|
ws = wb.create_sheet(title=sheet_name)
|
|
ws.append(headers)
|
|
for cell in ws[1]:
|
|
cell.font = Font(bold=True)
|
|
|
|
for column_index, field_name in enumerate(headers, start=1):
|
|
letter = get_column_letter(column_index)
|
|
ws.column_dimensions[letter].width = COLUMN_WIDTHS.get(field_name, 18)
|
|
number_format = CELL_NUMBER_FORMATS.get((sheet_name, field_name))
|
|
if number_format:
|
|
for row_number in range(2, _TEMPLATE_ROWS + 1):
|
|
ws.cell(row=row_number, column=column_index).number_format = number_format
|
|
|
|
ws.freeze_panes = "A2"
|
|
ws.auto_filter.ref = f"A1:{get_column_letter(len(headers))}{_TEMPLATE_ROWS}"
|
|
|
|
|
|
def _add_validations(wb: Workbook) -> None:
|
|
currency = _list_validation(tuple(CURRENCY_DECIMALS), prompt="Код валюты, напр. RUB")
|
|
accounts_ws = wb["Accounts"]
|
|
account_currency_col = get_column_letter(_column_index("Accounts", "currency"))
|
|
accounts_ws.add_data_validation(currency)
|
|
currency.add(f"{account_currency_col}2:{account_currency_col}{_VALIDATION_ROWS}")
|
|
|
|
transactions = wb["Transactions"]
|
|
tx_account_col = get_column_letter(_column_index("Transactions", "account"))
|
|
tx_account_validation = _account_validation()
|
|
transactions.add_data_validation(tx_account_validation)
|
|
tx_account_validation.add(f"{tx_account_col}2:{tx_account_col}{_VALIDATION_ROWS}")
|
|
|
|
recurring = wb["Recurring"]
|
|
rec_account_col = get_column_letter(_column_index("Recurring", "account"))
|
|
rec_frequency_col = get_column_letter(_column_index("Recurring", "frequency"))
|
|
rec_account_validation = _account_validation()
|
|
recurring.add_data_validation(rec_account_validation)
|
|
rec_account_validation.add(f"{rec_account_col}2:{rec_account_col}{_VALIDATION_ROWS}")
|
|
|
|
frequency = _list_validation(
|
|
_FREQUENCIES_EN + _FREQUENCIES_RU,
|
|
prompt="daily / weekly / monthly / yearly или ежедневно / еженедельно / ежемесячно / ежегодно",
|
|
)
|
|
recurring.add_data_validation(frequency)
|
|
frequency.add(f"{rec_frequency_col}2:{rec_frequency_col}{_VALIDATION_ROWS}")
|
|
|
|
|
|
def _instruction_rows() -> list[tuple[str, str, str, str]]:
|
|
rows: list[tuple[str, str, str, str]] = []
|
|
|
|
def line(text: str) -> None:
|
|
rows.append((text, "", "", ""))
|
|
|
|
line("Порядок работы")
|
|
line("1. Заполните листы Accounts, Transactions, Recurring, Assets, Liabilities, ExchangeRates.")
|
|
line("2. Сохраните файл в Excel — формулы должны быть пересчитаны и сохранены.")
|
|
line("3. Импортируйте модель командой: cf import-xlsx путь/к/файлу.xlsx")
|
|
line("")
|
|
|
|
line("Правила заполнения")
|
|
line("• id можно оставить пустым — идентификатор создаётся автоматически.")
|
|
line("• счёт указывается по имени из листа Accounts (регистр и лишние пробелы не важны).")
|
|
line("• пустой счёт в Recurring = платёж относится ко всем счетам.")
|
|
line("• сумма со знаком: положительная = доход, отрицательная = расход.")
|
|
line("• даты: 2026-01-31, 31.01.2026, 31/01/2026, 2026/01/31, 31-01-2026 (время отбрасывается).")
|
|
line("• числа: 1 234,56 или 1234.56; символы валют и пробелы игнорируются; (100) = -100.")
|
|
line("• валюта: " + ", ".join(CURRENCY_DECIMALS) + ".")
|
|
line(
|
|
"• периодичность: " + ", ".join(_FREQUENCIES_EN) + " (можно по-русски: "
|
|
+ ", ".join(_FREQUENCIES_RU) + ")."
|
|
)
|
|
line("")
|
|
|
|
rows.append(("Лист", "Столбец", "Обязательно", "Формат / допустимые значения"))
|
|
for sheet_name, fields in FIELD_KINDS.items():
|
|
for field_name, kind in fields.items():
|
|
required = "да" if _REQUIRED.get((sheet_name, field_name)) else _KIND_HELP[kind][0]
|
|
rows.append((sheet_name, field_name, required, _KIND_HELP[kind][1]))
|
|
return rows
|
|
|
|
|
|
def _write_instruction_sheet(wb: Workbook) -> None:
|
|
ws = wb.create_sheet(title=_INSTRUCTION_SHEET)
|
|
ws.column_dimensions["A"].width = 74
|
|
ws.column_dimensions["B"].width = 22
|
|
ws.column_dimensions["C"].width = 14
|
|
ws.column_dimensions["D"].width = 64
|
|
|
|
title = ws.cell(row=1, column=1, value="Инструкция: заполнение Excel-шаблона")
|
|
title.font = Font(bold=True, size=14)
|
|
|
|
for offset, values in enumerate(_instruction_rows(), start=2):
|
|
for column, value in enumerate(values, start=1):
|
|
ws.cell(row=offset, column=column, value=value or None)
|
|
if values[0] and not values[1] and not values[2] and not values[3]:
|
|
ws.cell(row=offset, column=1).font = Font(bold=True)
|
|
|
|
ws.freeze_panes = "A2"
|
|
|
|
|
|
def write_template(path: str | Path, *, force: bool = False) -> Path:
|
|
"""Создать пустой шаблон .xlsx. Существующий файл — ошибка, если не ``force``."""
|
|
target = Path(path)
|
|
if target.exists() and not force:
|
|
raise ExcelRepositoryError(
|
|
f"Файл уже существует: {target} — используйте force=True, чтобы перезаписать"
|
|
)
|
|
target.parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
wb = Workbook()
|
|
wb.remove(wb.active)
|
|
|
|
wb.create_sheet(title="ModelInfo")
|
|
info_ws = wb["ModelInfo"]
|
|
info_ws.append(["Property", "Value"])
|
|
for cell in info_ws[1]:
|
|
cell.font = Font(bold=True)
|
|
info_ws.column_dimensions["A"].width = COLUMN_WIDTHS["Property"]
|
|
info_ws.column_dimensions["B"].width = COLUMN_WIDTHS["Value"]
|
|
info_ws.freeze_panes = "A2"
|
|
|
|
for sheet_name in CANONICAL_COLUMNS:
|
|
_write_columns_sheet(wb, sheet_name)
|
|
|
|
_add_validations(wb)
|
|
_write_instruction_sheet(wb)
|
|
|
|
wb.save(target)
|
|
return target
|
|
|
|
|
|
__all__ = ["write_template"]
|