100 lines
3.1 KiB
Python
100 lines
3.1 KiB
Python
#!/usr/bin/env python3
|
|
"""S-13: чеки из Paperless → CSV для импорта в Firefly.
|
|
|
|
Ищет документы, вытаскивает сумму, пишет CSV в формате Firefly III.
|
|
"""
|
|
import csv
|
|
import json
|
|
import os
|
|
import re
|
|
import subprocess
|
|
import urllib.parse
|
|
import urllib.request
|
|
from datetime import datetime
|
|
|
|
PAPERLESS = "http://192.168.1.105:8000"
|
|
TOKEN = open("/root/.paperless-token", encoding="utf-8").read().strip()
|
|
OUT_DIR = "/mnt/media/finance"
|
|
STATE = "/var/lib/hub-finance/processed.json"
|
|
|
|
AMOUNT_RE = re.compile(
|
|
r"(?:итого|к\s*оплате|всего|сумма)[^\d]{0,20}([\d\s]{1,12}[.,]\d{2})",
|
|
re.IGNORECASE)
|
|
FALLBACK_RE = re.compile(r"(\d{1,6}[.,]\d{2})\s*(?:руб|₽)?", re.IGNORECASE)
|
|
|
|
|
|
def api(path):
|
|
req = urllib.request.Request(PAPERLESS + path,
|
|
headers={"Authorization": "Token " + TOKEN,
|
|
"Accept": "application/json"})
|
|
with urllib.request.urlopen(req, timeout=25) as r:
|
|
return json.loads(r.read() or b"{}")
|
|
|
|
|
|
def text_of(doc_id):
|
|
"""Достаёт текст документа (OCR/content)."""
|
|
req = urllib.request.Request(f"{PAPERLESS}/api/documents/{doc_id}/",
|
|
headers={"Authorization": "Token " + TOKEN,
|
|
"Accept": "application/json"})
|
|
with urllib.request.urlopen(req, timeout=25) as r:
|
|
d = json.loads(r.read() or b"{}")
|
|
return d.get("content") or ""
|
|
|
|
|
|
def extract_amount(text):
|
|
m = AMOUNT_RE.search(text)
|
|
if not m:
|
|
m = FALLBACK_RE.search(text)
|
|
if not m:
|
|
return None
|
|
raw = re.sub(r"\s", "", m.group(1)).replace(",", ".")
|
|
try:
|
|
return round(float(raw), 2)
|
|
except Exception:
|
|
return None
|
|
|
|
|
|
def main():
|
|
os.makedirs(OUT_DIR, exist_ok=True)
|
|
os.makedirs(os.path.dirname(STATE), exist_ok=True)
|
|
try:
|
|
processed = set(json.load(open(STATE, encoding="utf-8")))
|
|
except Exception:
|
|
processed = set()
|
|
|
|
docs = api("/api/documents/?page_size=50&ordering=-created")
|
|
rows = []
|
|
for d in docs.get("results", []):
|
|
did = str(d.get("id"))
|
|
if did in processed:
|
|
continue
|
|
text = text_of(did)
|
|
amount = extract_amount(text)
|
|
if not amount:
|
|
continue
|
|
title = (d.get("title") or "чек")[:60]
|
|
date = (d.get("created") or datetime.now().isoformat())[:10]
|
|
rows.append([date, title, amount])
|
|
processed.add(did)
|
|
|
|
if not rows:
|
|
print("новых чеков с суммой не найдено")
|
|
return
|
|
|
|
out = os.path.join(OUT_DIR, f"receipts-{datetime.now():%Y%m}.csv")
|
|
new_file = not os.path.exists(out)
|
|
with open(out, "a", newline="", encoding="utf-8") as f:
|
|
w = csv.writer(f)
|
|
if new_file:
|
|
w.writerow(["date", "description", "amount", "currency_code"])
|
|
for r in rows:
|
|
w.writerow(r + ["RUB"])
|
|
json.dump(sorted(processed), open(STATE, "w", encoding="utf-8"))
|
|
print(f"добавлено чеков: {len(rows)} → {out}")
|
|
for r in rows[:5]:
|
|
print(" ", r)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|