Счёт и реестр счетов
Считает суммы по позициям, формирует счёт в HTML или Markdown и ведёт CSV-реестр.
Что делает скрипт
Исходные данные берутся из JSON: реквизиты, позиции, налог и срок оплаты. Скрипт проверяет числа, считает итог и создаёт новый файл счёта, а по флагу register дописывает строку в реестр. Перезапись готового счёта требует явного подтверждения.
- Проверяйте реквизиты и ставку налога перед отправкой счёта.
Быстрый старт
python invoice.py --data invoice.json --output invoice.html
Скачайте файл, откройте терминал в папке со скриптом и выполните команду.
В Linux и macOS интерпретатор может называться python3, в Windows - python или py.
Другие варианты
python invoice.py --init --output invoice.example.jsonpython invoice.py --data invoice.json --output invoice.htmlpython invoice.py --data invoice.json --output invoice.md --register invoices.csv
Что понадобится
winget install Python.Python.3.12
brew install python
sudo apt install python3
invoice.py
#!/usr/bin/env python3
"""Счёт из JSON с расчётом итога и CSV-реестром."""
from __future__ import annotations
import argparse
import csv
import html
import json
from datetime import date
from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
from pathlib import Path
SAMPLE = {
"number": "2026-001",
"date": "2026-11-09",
"due": "2026-11-23",
"currency": "USD",
"tax_rate": 0,
"from": {"name": "Demo Studio", "address": "1 Example Street, Demo"},
"to": {"name": "Example Client", "address": "2 Example Avenue, Demo"},
"items": [
{"description": "Консультация", "quantity": 2, "price": 100},
{"description": "Подготовка документа", "quantity": 1, "price": 250},
],
}
def money(value: Decimal) -> str:
return f"{value.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP):,.2f}"
def to_decimal(value, label: str) -> Decimal:
try:
number = Decimal(str(value))
except (InvalidOperation, ValueError):
raise SystemExit(f"Не число в поле {label}: {value}")
if number < 0:
raise SystemExit(f"Отрицательное значение в поле {label}")
return number
def load_invoice(path: Path) -> dict:
try:
data = json.loads(path.read_text(encoding="utf-8"))
except json.JSONDecodeError as error:
raise SystemExit(f"Ошибка JSON: {error}")
if not isinstance(data, dict):
raise SystemExit("Корень JSON должен быть объектом")
for field in ("number", "date", "to", "items"):
if field not in data:
raise SystemExit(f"В JSON нет поля {field}")
if not isinstance(data["items"], list) or not data["items"]:
raise SystemExit("Поле items должно быть непустым списком")
return data
def calculate(data: dict) -> tuple[list[dict], Decimal, Decimal, Decimal]:
rows = []
subtotal = Decimal("0")
for index, item in enumerate(data["items"], start=1):
if not isinstance(item, dict) or not item.get("description"):
raise SystemExit(f"Позиция {index} без description")
quantity = to_decimal(item.get("quantity", 1), f"items[{index}].quantity")
price = to_decimal(item.get("price", 0), f"items[{index}].price")
amount = quantity * price
subtotal += amount
rows.append({"description": str(item["description"]), "quantity": quantity, "price": price, "amount": amount})
tax_rate = to_decimal(data.get("tax_rate", 0), "tax_rate")
tax = subtotal * tax_rate / Decimal("100")
total = subtotal + tax
return rows, subtotal, tax, total
def render_html(data: dict, rows: list[dict], subtotal: Decimal, tax: Decimal, total: Decimal) -> str:
esc = html.escape
client = data.get("to", {})
seller = data.get("from", {})
currency = esc(str(data.get("currency", "")))
body = []
for row in rows:
body.append(
"<tr>"
f"<td>{esc(row['description'])}</td>"
f"<td class='num'>{row['quantity']}</td>"
f"<td class='num'>{money(row['price'])}</td>"
f"<td class='num'>{money(row['amount'])}</td>"
"</tr>"
)
tax_row = ""
if tax > 0:
tax_row = f"<tr><td colspan='3'>Налог {esc(str(data.get('tax_rate', 0)))}%</td><td class='num'>{money(tax)}</td></tr>"
due_text = f" · Оплатить до: {esc(str(data['due']))}" if data.get("due") else ""
return f"""<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<title>Счёт {esc(str(data['number']))}</title>
<style>
body {{ font-family: system-ui, sans-serif; color: #111827; max-width: 820px; margin: 40px auto; padding: 0 20px; }}
h1 {{ margin-bottom: 4px; }}
.muted {{ color: #6b7280; }}
table {{ width: 100%; border-collapse: collapse; margin-top: 24px; }}
th, td {{ border-bottom: 1px solid #e5e7eb; padding: 10px 8px; text-align: left; }}
th {{ background: #f9fafb; }}
.num {{ text-align: right; white-space: nowrap; }}
.total {{ font-size: 20px; font-weight: 700; }}
.parties {{ display: flex; gap: 40px; margin-top: 24px; }}
</style>
</head>
<body>
<h1>Счёт {esc(str(data['number']))}</h1>
<div class="muted">Дата: {esc(str(data['date']))}{due_text}</div>
<div class="parties">
<div><strong>Исполнитель</strong><br>{esc(str(seller.get("name", "")))}<br>{esc(str(seller.get("address", "")))}</div>
<div><strong>Заказчик</strong><br>{esc(str(client.get("name", "")))}<br>{esc(str(client.get("address", "")))}</div>
</div>
<table>
<thead><tr><th>Описание</th><th class="num">Кол-во</th><th class="num">Цена</th><th class="num">Сумма</th></tr></thead>
<tbody>{''.join(body)}</tbody>
<tfoot>
<tr><td colspan="3">Подытог</td><td class="num">{money(subtotal)} {currency}</td></tr>
{tax_row}
<tr><td colspan="3" class="total">Итого</td><td class="num total">{money(total)} {currency}</td></tr>
</tfoot>
</table>
</body>
</html>
"""
def render_markdown(data: dict, rows: list[dict], subtotal: Decimal, tax: Decimal, total: Decimal) -> str:
currency = str(data.get("currency", ""))
lines = [
f"# Счёт {data['number']}",
"",
f"Дата: {data['date']}",
]
if data.get("due"):
lines.append(f"Оплатить до: {data['due']}")
lines.extend([
"",
f"Исполнитель: {data.get('from', {}).get('name', '')}",
f"Заказчик: {data.get('to', {}).get('name', '')}",
"",
"| Описание | Кол-во | Цена | Сумма |",
"|---|---:|---:|---:|",
])
for row in rows:
description = str(row["description"]).replace("|", "\\|")
lines.append(
f"| {description} | {row['quantity']} | {money(row['price'])} | {money(row['amount'])} |"
)
lines.extend([
"",
f"Подытог: {money(subtotal)} {currency}",
])
if tax > 0:
lines.append(f"Налог {data.get('tax_rate', 0)}%: {money(tax)} {currency}")
lines.append(f"**Итого: {money(total)} {currency}**")
return "\n".join(lines) + "\n"
def append_register(path: Path, data: dict, total: Decimal) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
is_new = not path.exists()
with path.open("a", encoding="utf-8", newline="") as handle:
writer = csv.writer(handle)
if is_new:
writer.writerow(["number", "date", "due", "client", "total", "currency"])
writer.writerow([
data.get("number", ""),
data.get("date", ""),
data.get("due", ""),
data.get("to", {}).get("name", ""),
money(total),
data.get("currency", ""),
])
print(f"Реестр обновлён: {path}")
def main() -> int:
parser = argparse.ArgumentParser(description="Счёт из JSON")
parser.add_argument("--data", type=Path)
parser.add_argument("--output", type=Path, default=Path("invoice.html"))
parser.add_argument("--register", type=Path)
parser.add_argument("--init", action="store_true")
parser.add_argument("--force", action="store_true")
args = parser.parse_args()
if args.init:
if not args.output:
parser.error("Для --init укажите --output")
output = args.output.expanduser()
if output.exists() and not args.force:
parser.error(f"Файл уже существует: {output}")
output.parent.mkdir(parents=True, exist_ok=True)
output.write_text(json.dumps(SAMPLE, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print(f"Пример счёта сохранён: {output}")
return 0
if not args.data:
parser.error("Укажите --data или --init")
data_path = args.data.expanduser()
if not data_path.is_file():
parser.error(f"Файл не найден: {data_path}")
data = load_invoice(data_path)
for field in ("date", "due"):
if data.get(field):
try:
date.fromisoformat(str(data[field]))
except ValueError:
parser.error(f"Поле {field} должно быть в формате YYYY-MM-DD")
output = args.output.expanduser()
suffix = output.suffix.lower()
if suffix not in {".html", ".md"}:
parser.error("Поддерживаются расширения .html и .md")
if output.exists() and not args.force:
parser.error(f"Файл уже существует: {output}. Добавьте --force.")
rows, subtotal, tax, total = calculate(data)
text = render_html(data, rows, subtotal, tax, total) if suffix == ".html" else render_markdown(data, rows, subtotal, tax, total)
output.parent.mkdir(parents=True, exist_ok=True)
output.write_text(text, encoding="utf-8")
print(f"Счёт сохранён: {output}")
if args.register:
append_register(args.register.expanduser(), data, total)
return 0
if __name__ == "__main__":
raise SystemExit(main())
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.