"""cf import-xlsx — импорт данных из Excel.""" import typer from rich.markup import escape from rich.table import Table from infrastructure.cli.i18n import t from infrastructure.cli.services import console, save_model from infrastructure.repositories import ExcelRepository, ExcelRepositoryError, ExcelRowError app = typer.Typer() _repo = ExcelRepository() def _counts(model) -> dict[str, int]: return { "accounts": len(model.accounts), "transactions": len(model.transactions), "recurring": len(model.recurring), "assets": len(model.assets), "liabilities": len(model.liabilities), } def _print_warnings(warnings: list[str]) -> None: for warning in warnings: console.print(f"[yellow]{t('cmd.import.warn', warning=escape(warning))}[/yellow]") def _print_errors(errors: list[ExcelRowError]) -> None: table = Table(title=t("cmd.import.errors.title", count=len(errors))) table.add_column(t("cmd.import.errors.col.sheet")) table.add_column(t("cmd.import.errors.col.row"), justify="right") table.add_column(t("cmd.import.errors.col.field")) table.add_column(t("cmd.import.errors.col.message")) for error in errors: table.add_row( escape(error.sheet), str(error.row), escape(error.field) or "—", escape(error.message), ) console.print(table) console.print(f"[red]{t('cmd.import.errors.hint', first=escape(str(errors[0])))}[/red]") @app.command(name="import-xlsx") def import_xlsx( path: str = typer.Argument(..., help=t("cmd.import.arg.path")), dry_run: bool = typer.Option(False, "--dry-run", help=t("cmd.import.opt.dry_run")), ) -> None: """Импорт данных из Excel""" try: report = _repo.load_report(path) except ExcelRepositoryError as e: console.print(f"[red]{t('cmd.import.err', error=escape(str(e)))}[/red]") raise typer.Exit(1) _print_warnings(report.warnings) if report.errors: _print_errors(report.errors) raise typer.Exit(1) counts = _counts(report.model) if dry_run: console.print(t("cmd.import.dry_run.title")) console.print(t("cmd.import.dry_run.ok", **counts)) console.print(t("cmd.import.dry_run.base_currency", currency=report.model.base_currency)) console.print(f"[yellow]{t('cmd.import.dry_run.not_saved')}[/yellow]") return save_model(report.model) console.print(t("cmd.import.ok", **counts)) console.print(t("cmd.import.base_currency", currency=report.model.base_currency))