97 lines
5.1 KiB
Python
97 lines
5.1 KiB
Python
"""Dossier de révision PDF. Ne prétend pas être un formulaire gouvernemental officiel."""
|
||
from __future__ import annotations
|
||
from io import BytesIO
|
||
from pathlib import Path
|
||
from urllib.parse import urlsplit
|
||
from xml.sax.saxutils import escape
|
||
|
||
from reportlab.lib import colors
|
||
from reportlab.lib.enums import TA_CENTER, TA_RIGHT
|
||
from reportlab.lib.pagesizes import A4
|
||
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
|
||
from reportlab.lib.units import mm
|
||
from reportlab.pdfbase import pdfmetrics
|
||
from reportlab.pdfbase.ttfonts import TTFont
|
||
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, KeepTogether
|
||
|
||
from .tax import SOURCES, monnaie
|
||
|
||
FONT_DIR = Path("/usr/share/fonts/truetype/dejavu")
|
||
if (FONT_DIR / "DejaVuSans.ttf").exists():
|
||
pdfmetrics.registerFont(TTFont("Fisc", str(FONT_DIR / "DejaVuSans.ttf")))
|
||
pdfmetrics.registerFont(TTFont("FiscBold", str(FONT_DIR / "DejaVuSans-Bold.ttf")))
|
||
REG, BOLD = "Fisc", "FiscBold"
|
||
else:
|
||
REG, BOLD = "Helvetica", "Helvetica-Bold"
|
||
|
||
|
||
def argent_fr(value) -> str:
|
||
"""Affichage français des montants, sans conversion flottante."""
|
||
entier, cents = monnaie(value).split(".")
|
||
sign = "-" if entier.startswith("-") else ""
|
||
chiffres = entier.lstrip("-")
|
||
groupes = []
|
||
while chiffres:
|
||
groupes.insert(0, chiffres[-3:])
|
||
chiffres = chiffres[:-3]
|
||
return sign + " ".join(groupes) + "," + cents + " $"
|
||
|
||
|
||
def exporter_pdf(dossier: dict, resultat: dict) -> bytes:
|
||
mem = BytesIO()
|
||
doc = SimpleDocTemplate(mem, pagesize=A4, rightMargin=18 * mm, leftMargin=18 * mm,
|
||
topMargin=19 * mm, bottomMargin=20 * mm)
|
||
styles = getSampleStyleSheet()
|
||
styles.add(ParagraphStyle(name="TitreFisc", fontName=BOLD, fontSize=21, leading=28, textColor=colors.HexColor("#123F4C"), spaceAfter=6))
|
||
styles.add(ParagraphStyle(name="SousFisc", fontName=BOLD, fontSize=11, leading=15, textColor=colors.HexColor("#123F4C"), spaceBefore=15, spaceAfter=7))
|
||
styles.add(ParagraphStyle(name="TexteFisc", fontName=REG, fontSize=8.4, leading=13, spaceAfter=6))
|
||
styles.add(ParagraphStyle(name="AlerteFisc", fontName=BOLD, fontSize=9, leading=14, textColor=colors.HexColor("#9B2F20"), spaceAfter=9))
|
||
styles.add(ParagraphStyle(name="UrlFisc", fontName=REG, fontSize=7.3, leading=11, wordWrap="CJK", spaceAfter=5))
|
||
story = [Paragraph("FISCALIBRE", styles["TitreFisc"]),
|
||
Paragraph("DOCUMENT DE TRAVAIL — NON TRANSMISSIBLE AUX AUTORITÉS FISCALES", styles["AlerteFisc"]),
|
||
Paragraph("Ce document ne remplace aucun formulaire gouvernemental officiel, n’est pas compatible IMPÔTNET et doit rester dans le dossier interne de révision.", styles["TexteFisc"]),
|
||
Paragraph(f"Millésime : 2025 · Profil : {escape(dossier['profil'])} · Référence : {escape(dossier['id'])}", styles["TexteFisc"])]
|
||
ident = dossier["data"]["identite"]
|
||
nom = ident.get("raison_sociale") or ((ident.get("prenom", "") + " " + ident.get("nom", "")).strip())
|
||
story.append(Paragraph(f"Dossier : {escape(nom or 'Non renseigné')}", styles["TexteFisc"]))
|
||
story.append(Paragraph("Résumé de calcul (incomplet)", styles["SousFisc"]))
|
||
|
||
def table(rows):
|
||
lignes = [[Paragraph(escape(str(a)), styles["TexteFisc"]), Paragraph(escape(str(b)), styles["TexteFisc"])] for a, b in rows]
|
||
t = Table(lignes, colWidths=[112 * mm, 55 * mm], hAlign="LEFT", repeatRows=0)
|
||
t.setStyle(TableStyle([
|
||
("VALIGN", (0, 0), (-1, -1), "TOP"),
|
||
("ROWBACKGROUNDS", (0, 0), (-1, -1), [colors.white, colors.HexColor("#F0F4F5")]),
|
||
("LEFTPADDING", (0, 0), (-1, -1), 8),
|
||
("RIGHTPADDING", (0, 0), (-1, -1), 8),
|
||
("BOTTOMPADDING", (0, 0), (-1, -1), 5),
|
||
("TOPPADDING", (0, 0), (-1, -1), 5),
|
||
]))
|
||
return t
|
||
|
||
story.append(table([(k, argent_fr(v)) for k, v in resultat["resume"].items()]))
|
||
for titre, lignes in resultat["lignes"].items():
|
||
story.append(Paragraph(escape(titre), styles["SousFisc"]))
|
||
story.append(table([(k, argent_fr(v)) for k, v in lignes.items()]))
|
||
story.append(Paragraph("Contrôles non réalisés et limites", styles["SousFisc"]))
|
||
for alerte in resultat["alertes"]:
|
||
story.append(Paragraph("• " + escape(alerte), styles["TexteFisc"]))
|
||
story.append(Paragraph("Références gouvernementales", styles["SousFisc"]))
|
||
for source in resultat["sources"]:
|
||
url = SOURCES[source]
|
||
domaine = urlsplit(url).hostname or "source officielle"
|
||
etiquette = source.replace("_", " ").capitalize()
|
||
story.append(Paragraph(f'<link href="{escape(url)}" color="#0b6558">{escape(etiquette)} — {escape(domaine)}</link>', styles["UrlFisc"]))
|
||
|
||
def footer(canvas, document):
|
||
canvas.saveState()
|
||
width, _ = A4
|
||
canvas.setFont(BOLD, 7)
|
||
canvas.setFillColor(colors.HexColor("#9B2F20"))
|
||
canvas.drawString(18*mm, 12*mm, "FISCALIBRE V0.1 — BROUILLON NON TRANSMISSIBLE")
|
||
canvas.setFont(REG, 7)
|
||
canvas.drawRightString(width-18*mm, 12*mm, f"Page {document.page}")
|
||
canvas.restoreState()
|
||
|
||
doc.build(story, onFirstPage=footer, onLaterPages=footer)
|
||
return mem.getvalue()
|