cfdi-kit 1.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cfdi_kit/__init__.py +42 -0
- cfdi_kit/catalogs.py +134 -0
- cfdi_kit/cli.py +232 -0
- cfdi_kit/export.py +259 -0
- cfdi_kit/loader.py +125 -0
- cfdi_kit/models.py +200 -0
- cfdi_kit/parser.py +331 -0
- cfdi_kit/py.typed +0 -0
- cfdi_kit/report.css +53 -0
- cfdi_kit/report.py +387 -0
- cfdi_kit/risk.py +207 -0
- cfdi_kit/summary.py +245 -0
- cfdi_kit/validate.py +203 -0
- cfdi_kit-1.1.0.dist-info/METADATA +204 -0
- cfdi_kit-1.1.0.dist-info/RECORD +18 -0
- cfdi_kit-1.1.0.dist-info/WHEEL +4 -0
- cfdi_kit-1.1.0.dist-info/entry_points.txt +2 -0
- cfdi_kit-1.1.0.dist-info/licenses/LICENSE +21 -0
cfdi_kit/__init__.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Parse SAT CFDI invoices into typed models, dataframes and reports."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import version
|
|
4
|
+
|
|
5
|
+
from cfdi_kit.export import concepts_frame, invoices_frame, payments_frame, to_csv, to_excel
|
|
6
|
+
from cfdi_kit.loader import LoadResult, load
|
|
7
|
+
from cfdi_kit.models import Cfdi, InvoiceType
|
|
8
|
+
from cfdi_kit.parser import CfdiParseError, parse_bytes, parse_file
|
|
9
|
+
from cfdi_kit.risk import Listing, ListingStatus, Match, Snapshot, find_matches, load_snapshot
|
|
10
|
+
from cfdi_kit.summary import Basis, Summary, summarize, summary_frame
|
|
11
|
+
from cfdi_kit.validate import Issue, Severity, validate
|
|
12
|
+
|
|
13
|
+
__version__ = version("cfdi-kit")
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"Basis",
|
|
17
|
+
"Cfdi",
|
|
18
|
+
"CfdiParseError",
|
|
19
|
+
"InvoiceType",
|
|
20
|
+
"Issue",
|
|
21
|
+
"Listing",
|
|
22
|
+
"ListingStatus",
|
|
23
|
+
"LoadResult",
|
|
24
|
+
"Match",
|
|
25
|
+
"Severity",
|
|
26
|
+
"Snapshot",
|
|
27
|
+
"Summary",
|
|
28
|
+
"__version__",
|
|
29
|
+
"concepts_frame",
|
|
30
|
+
"find_matches",
|
|
31
|
+
"invoices_frame",
|
|
32
|
+
"load",
|
|
33
|
+
"load_snapshot",
|
|
34
|
+
"parse_bytes",
|
|
35
|
+
"parse_file",
|
|
36
|
+
"payments_frame",
|
|
37
|
+
"summarize",
|
|
38
|
+
"summary_frame",
|
|
39
|
+
"to_csv",
|
|
40
|
+
"to_excel",
|
|
41
|
+
"validate",
|
|
42
|
+
]
|
cfdi_kit/catalogs.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"""Labels for the SAT catalogs that appear in reports (Anexo 20). Labels keep the SAT's Spanish."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from enum import StrEnum
|
|
6
|
+
from types import MappingProxyType
|
|
7
|
+
from typing import TYPE_CHECKING
|
|
8
|
+
|
|
9
|
+
if TYPE_CHECKING:
|
|
10
|
+
from collections.abc import Mapping
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class Catalog(StrEnum):
|
|
14
|
+
INVOICE_TYPE = "c_TipoDeComprobante"
|
|
15
|
+
PAYMENT_FORM = "c_FormaPago"
|
|
16
|
+
PAYMENT_METHOD = "c_MetodoPago"
|
|
17
|
+
CFDI_USE = "c_UsoCFDI"
|
|
18
|
+
TAX_REGIME = "c_RegimenFiscal"
|
|
19
|
+
TAX = "c_Impuesto"
|
|
20
|
+
RELATION_TYPE = "c_TipoRelacion"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
_CATALOGS: Mapping[Catalog, Mapping[str, str]] = MappingProxyType(
|
|
24
|
+
{
|
|
25
|
+
Catalog.INVOICE_TYPE: {
|
|
26
|
+
"I": "Ingreso",
|
|
27
|
+
"E": "Egreso",
|
|
28
|
+
"T": "Traslado",
|
|
29
|
+
"N": "Nómina",
|
|
30
|
+
"P": "Pago",
|
|
31
|
+
},
|
|
32
|
+
Catalog.PAYMENT_FORM: {
|
|
33
|
+
"01": "Efectivo",
|
|
34
|
+
"02": "Cheque nominativo",
|
|
35
|
+
"03": "Transferencia electrónica de fondos",
|
|
36
|
+
"04": "Tarjeta de crédito",
|
|
37
|
+
"05": "Monedero electrónico",
|
|
38
|
+
"06": "Dinero electrónico",
|
|
39
|
+
"08": "Vales de despensa",
|
|
40
|
+
"12": "Dación en pago",
|
|
41
|
+
"13": "Pago por subrogación",
|
|
42
|
+
"14": "Pago por consignación",
|
|
43
|
+
"15": "Condonación",
|
|
44
|
+
"17": "Compensación",
|
|
45
|
+
"23": "Novación",
|
|
46
|
+
"24": "Confusión",
|
|
47
|
+
"25": "Remisión de deuda",
|
|
48
|
+
"26": "Prescripción o caducidad",
|
|
49
|
+
"27": "A satisfacción del acreedor",
|
|
50
|
+
"28": "Tarjeta de débito",
|
|
51
|
+
"29": "Tarjeta de servicios",
|
|
52
|
+
"30": "Aplicación de anticipos",
|
|
53
|
+
"31": "Intermediario pagos",
|
|
54
|
+
"99": "Por definir",
|
|
55
|
+
},
|
|
56
|
+
Catalog.PAYMENT_METHOD: {
|
|
57
|
+
"PUE": "Pago en una sola exhibición",
|
|
58
|
+
"PPD": "Pago en parcialidades o diferido",
|
|
59
|
+
},
|
|
60
|
+
Catalog.CFDI_USE: {
|
|
61
|
+
"G01": "Adquisición de mercancías",
|
|
62
|
+
"G02": "Devoluciones, descuentos o bonificaciones",
|
|
63
|
+
"G03": "Gastos en general",
|
|
64
|
+
"I01": "Construcciones",
|
|
65
|
+
"I02": "Mobiliario y equipo de oficina por inversiones",
|
|
66
|
+
"I03": "Equipo de transporte",
|
|
67
|
+
"I04": "Equipo de cómputo y accesorios",
|
|
68
|
+
"I05": "Dados, troqueles, moldes, matrices y herramental",
|
|
69
|
+
"I06": "Comunicaciones telefónicas",
|
|
70
|
+
"I07": "Comunicaciones satelitales",
|
|
71
|
+
"I08": "Otra maquinaria y equipo",
|
|
72
|
+
"D01": "Honorarios médicos, dentales y gastos hospitalarios",
|
|
73
|
+
"D02": "Gastos médicos por incapacidad o discapacidad",
|
|
74
|
+
"D03": "Gastos funerales",
|
|
75
|
+
"D04": "Donativos",
|
|
76
|
+
"D05": "Intereses reales pagados por créditos hipotecarios (casa habitación)",
|
|
77
|
+
"D06": "Aportaciones voluntarias al SAR",
|
|
78
|
+
"D07": "Primas por seguros de gastos médicos",
|
|
79
|
+
"D08": "Gastos de transportación escolar obligatoria",
|
|
80
|
+
"D09": "Depósitos en cuentas para el ahorro, primas de pensiones",
|
|
81
|
+
"D10": "Pagos por servicios educativos (colegiaturas)",
|
|
82
|
+
"S01": "Sin efectos fiscales",
|
|
83
|
+
"CP01": "Pagos",
|
|
84
|
+
"CN01": "Nómina",
|
|
85
|
+
"P01": "Por definir",
|
|
86
|
+
},
|
|
87
|
+
Catalog.TAX_REGIME: {
|
|
88
|
+
"601": "General de Ley Personas Morales",
|
|
89
|
+
"603": "Personas Morales con Fines no Lucrativos",
|
|
90
|
+
"605": "Sueldos y Salarios e Ingresos Asimilados a Salarios",
|
|
91
|
+
"606": "Arrendamiento",
|
|
92
|
+
"607": "Régimen de Enajenación o Adquisición de Bienes",
|
|
93
|
+
"608": "Demás ingresos",
|
|
94
|
+
"610": "Residentes en el Extranjero sin Establecimiento Permanente en México",
|
|
95
|
+
"611": "Ingresos por Dividendos (socios y accionistas)",
|
|
96
|
+
"612": "Personas Físicas con Actividades Empresariales y Profesionales",
|
|
97
|
+
"614": "Ingresos por intereses",
|
|
98
|
+
"615": "Régimen de los ingresos por obtención de premios",
|
|
99
|
+
"616": "Sin obligaciones fiscales",
|
|
100
|
+
"620": "Sociedades Cooperativas de Producción que optan por diferir sus ingresos",
|
|
101
|
+
"621": "Incorporación Fiscal",
|
|
102
|
+
"622": "Actividades Agrícolas, Ganaderas, Silvícolas y Pesqueras",
|
|
103
|
+
"623": "Opcional para Grupos de Sociedades",
|
|
104
|
+
"624": "Coordinados",
|
|
105
|
+
"625": "Actividades Empresariales con ingresos a través de Plataformas Tecnológicas",
|
|
106
|
+
"626": "Régimen Simplificado de Confianza",
|
|
107
|
+
},
|
|
108
|
+
Catalog.TAX: {
|
|
109
|
+
"001": "ISR",
|
|
110
|
+
"002": "IVA",
|
|
111
|
+
"003": "IEPS",
|
|
112
|
+
},
|
|
113
|
+
Catalog.RELATION_TYPE: {
|
|
114
|
+
"01": "Nota de crédito de los documentos relacionados",
|
|
115
|
+
"02": "Nota de débito de los documentos relacionados",
|
|
116
|
+
"03": "Devolución de mercancía sobre facturas o traslados previos",
|
|
117
|
+
"04": "Sustitución de los CFDI previos",
|
|
118
|
+
"05": "Traslados de mercancías facturados previamente",
|
|
119
|
+
"06": "Factura generada por los traslados previos",
|
|
120
|
+
"07": "CFDI por aplicación de anticipo",
|
|
121
|
+
},
|
|
122
|
+
}
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def label(catalog: Catalog, code: str | None) -> str | None:
|
|
127
|
+
"""Return the SAT description for `code`, the code itself if unknown, or None if missing."""
|
|
128
|
+
if code is None:
|
|
129
|
+
return None
|
|
130
|
+
return _CATALOGS[catalog].get(code, code)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def codes(catalog: Catalog) -> Mapping[str, str]:
|
|
134
|
+
return MappingProxyType(dict(_CATALOGS[catalog]))
|
cfdi_kit/cli.py
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
"""`cfdi-kit` command line."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import sys
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import TYPE_CHECKING
|
|
9
|
+
|
|
10
|
+
from cfdi_kit import __version__
|
|
11
|
+
from cfdi_kit.export import to_csv, to_excel
|
|
12
|
+
from cfdi_kit.loader import LoadResult, load
|
|
13
|
+
from cfdi_kit.report import build_report
|
|
14
|
+
from cfdi_kit.risk import Match, Snapshot, SnapshotError, find_matches, load_snapshot
|
|
15
|
+
from cfdi_kit.summary import Basis, Summary, summarize, summary_frame
|
|
16
|
+
from cfdi_kit.validate import Severity, validate
|
|
17
|
+
|
|
18
|
+
if TYPE_CHECKING:
|
|
19
|
+
from collections.abc import Callable, Sequence
|
|
20
|
+
|
|
21
|
+
import pandas as pd
|
|
22
|
+
|
|
23
|
+
EXIT_OK = 0
|
|
24
|
+
EXIT_FAILURE = 1
|
|
25
|
+
RISK_LIST_HELP = "local copy of the SAT's Listado_completo_69-B.csv (see the README to download it)"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
29
|
+
parser = _parser()
|
|
30
|
+
args = parser.parse_args(argv)
|
|
31
|
+
handler: Callable[[argparse.Namespace], int] = args.handler
|
|
32
|
+
return handler(args)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _parser() -> argparse.ArgumentParser:
|
|
36
|
+
parser = argparse.ArgumentParser(
|
|
37
|
+
prog="cfdi-kit",
|
|
38
|
+
description="Read SAT CFDI invoices locally: export, summarize and validate them.",
|
|
39
|
+
)
|
|
40
|
+
parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
|
|
41
|
+
commands = parser.add_subparsers(required=True, metavar="COMMAND")
|
|
42
|
+
|
|
43
|
+
parse = commands.add_parser("parse", help="export invoices to Excel or CSV")
|
|
44
|
+
_add_inputs(parse)
|
|
45
|
+
parse.add_argument("-o", "--output", type=Path, required=True, help="output .xlsx or .csv")
|
|
46
|
+
parse.add_argument("--rfc", help="your RFC, to label each invoice as issued or received")
|
|
47
|
+
parse.set_defaults(handler=_parse)
|
|
48
|
+
|
|
49
|
+
summary = commands.add_parser("summary", help="monthly income, expenses and VAT for an RFC")
|
|
50
|
+
_add_inputs(summary)
|
|
51
|
+
summary.add_argument("--rfc", required=True, help="the RFC to summarize")
|
|
52
|
+
summary.add_argument(
|
|
53
|
+
"--basis",
|
|
54
|
+
choices=[b.value for b in Basis],
|
|
55
|
+
default=Basis.ACCRUAL.value,
|
|
56
|
+
help="accrual: by issue date (default); cash: PPD invoices on their payment date",
|
|
57
|
+
)
|
|
58
|
+
summary.add_argument("-o", "--output", type=Path, help="also write the table to .xlsx or .csv")
|
|
59
|
+
summary.set_defaults(handler=_summary)
|
|
60
|
+
|
|
61
|
+
check = commands.add_parser("validate", help="check totals, taxes, RFCs and duplicates")
|
|
62
|
+
_add_inputs(check)
|
|
63
|
+
check.set_defaults(handler=_validate)
|
|
64
|
+
|
|
65
|
+
report = commands.add_parser("report", help="write a self-contained HTML report for an RFC")
|
|
66
|
+
_add_inputs(report)
|
|
67
|
+
report.add_argument("--rfc", required=True, help="the RFC to report on")
|
|
68
|
+
report.add_argument("--basis", choices=[b.value for b in Basis], default=Basis.ACCRUAL.value)
|
|
69
|
+
report.add_argument("-o", "--output", type=Path, default=Path("cfdi-report.html"))
|
|
70
|
+
report.add_argument("--risk-list", type=Path, metavar="CSV", help=RISK_LIST_HELP)
|
|
71
|
+
report.set_defaults(handler=_report)
|
|
72
|
+
|
|
73
|
+
risk = commands.add_parser("risk", help="flag suppliers that appear on the SAT 69-B list")
|
|
74
|
+
_add_inputs(risk)
|
|
75
|
+
risk.add_argument("--list", type=Path, required=True, metavar="CSV", help=RISK_LIST_HELP)
|
|
76
|
+
risk.add_argument("--rfc", help="your RFC: only invoices you received are checked")
|
|
77
|
+
risk.set_defaults(handler=_risk)
|
|
78
|
+
return parser
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _add_inputs(parser: argparse.ArgumentParser) -> None:
|
|
82
|
+
parser.add_argument("paths", nargs="+", type=Path, help="XML files, folders or ZIP archives")
|
|
83
|
+
parser.add_argument("--keep-duplicates", action="store_true", help="do not skip repeated UUIDs")
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def load_inputs(args: argparse.Namespace) -> LoadResult:
|
|
87
|
+
result = load(args.paths, deduplicate=not args.keep_duplicates)
|
|
88
|
+
for error in result.errors:
|
|
89
|
+
print(f"skipped {error.source}: {error.message}", file=sys.stderr)
|
|
90
|
+
if result.duplicates:
|
|
91
|
+
print(f"skipped {len(result.duplicates)} duplicate UUID(s)", file=sys.stderr)
|
|
92
|
+
print(f"loaded {len(result.cfdis)} CFDI(s)", file=sys.stderr)
|
|
93
|
+
return result
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _parse(args: argparse.Namespace) -> int:
|
|
97
|
+
result = load_inputs(args)
|
|
98
|
+
if not result.cfdis:
|
|
99
|
+
return EXIT_FAILURE
|
|
100
|
+
output: Path = args.output
|
|
101
|
+
if output.suffix.lower() == ".csv":
|
|
102
|
+
to_csv(result.cfdis, output, args.rfc)
|
|
103
|
+
elif output.suffix.lower() == ".xlsx":
|
|
104
|
+
to_excel(result.cfdis, output, args.rfc)
|
|
105
|
+
else:
|
|
106
|
+
print("output must end in .xlsx or .csv", file=sys.stderr)
|
|
107
|
+
return EXIT_FAILURE
|
|
108
|
+
print(f"wrote {output}", file=sys.stderr)
|
|
109
|
+
return EXIT_OK
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _summary(args: argparse.Namespace) -> int:
|
|
113
|
+
result = load_inputs(args)
|
|
114
|
+
summary = summarize(result.cfdis, args.rfc, Basis(args.basis))
|
|
115
|
+
if not summary.months:
|
|
116
|
+
print(f"no invoices issued to or by {summary.rfc}", file=sys.stderr)
|
|
117
|
+
return EXIT_FAILURE
|
|
118
|
+
frame = summary_frame(summary)
|
|
119
|
+
print(render_summary(summary, frame))
|
|
120
|
+
output: Path | None = args.output
|
|
121
|
+
if output is not None:
|
|
122
|
+
if output.suffix.lower() == ".xlsx":
|
|
123
|
+
frame.to_excel(output, index=False, sheet_name="summary")
|
|
124
|
+
else:
|
|
125
|
+
frame.to_csv(output, index=False)
|
|
126
|
+
print(f"wrote {output}", file=sys.stderr)
|
|
127
|
+
return EXIT_OK
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
TERMINAL_COLUMNS = {
|
|
131
|
+
"month": "Month",
|
|
132
|
+
"income": "Income",
|
|
133
|
+
"iva_charged": "VAT charged",
|
|
134
|
+
"iva_withheld_by_clients": "VAT withheld",
|
|
135
|
+
"expenses": "Expenses",
|
|
136
|
+
"iva_creditable": "VAT creditable",
|
|
137
|
+
"net_iva": "Net VAT",
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def render_summary(summary: Summary, frame: pd.DataFrame) -> str:
|
|
142
|
+
header = f"{summary.rfc} · {summary.basis.value} basis · MXN"
|
|
143
|
+
rows = [list(TERMINAL_COLUMNS.values())]
|
|
144
|
+
for record in frame.to_dict("records"):
|
|
145
|
+
rows.append(
|
|
146
|
+
[
|
|
147
|
+
str(value) if column == "month" else f"{float(value):,.2f}"
|
|
148
|
+
for column, value in ((c, record[c]) for c in TERMINAL_COLUMNS)
|
|
149
|
+
]
|
|
150
|
+
)
|
|
151
|
+
widths = [max(len(row[i]) for row in rows) for i in range(len(rows[0]))]
|
|
152
|
+
lines = [header, ""]
|
|
153
|
+
for index, row in enumerate(rows):
|
|
154
|
+
lines.append(" ".join(cell.rjust(width) for cell, width in zip(row, widths, strict=True)))
|
|
155
|
+
if index == 0:
|
|
156
|
+
lines.append(" ".join("-" * width for width in widths))
|
|
157
|
+
if summary.unmatched_payments:
|
|
158
|
+
lines.append("")
|
|
159
|
+
lines.append(
|
|
160
|
+
f"note: {len(summary.unmatched_payments)} payment(s) settle invoices that were not "
|
|
161
|
+
"loaded and have no tax breakdown; their full amount was counted as net."
|
|
162
|
+
)
|
|
163
|
+
return "\n".join(lines)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _validate(args: argparse.Namespace) -> int:
|
|
167
|
+
result = load_inputs(args)
|
|
168
|
+
issues = validate(result.cfdis)
|
|
169
|
+
for issue in issues:
|
|
170
|
+
print(f"{issue.severity.value:7} {issue.code:28} {issue.source} {issue.message}")
|
|
171
|
+
errors = sum(1 for i in issues if i.severity is Severity.ERROR)
|
|
172
|
+
warnings = len(issues) - errors
|
|
173
|
+
print(f"{errors} error(s), {warnings} warning(s)", file=sys.stderr)
|
|
174
|
+
return EXIT_FAILURE if errors or result.errors else EXIT_OK
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _read_snapshot(path: Path) -> Snapshot | None:
|
|
178
|
+
try:
|
|
179
|
+
return load_snapshot(path)
|
|
180
|
+
except (OSError, SnapshotError) as error:
|
|
181
|
+
print(f"cannot read {path}: {error}", file=sys.stderr)
|
|
182
|
+
return None
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _risk(args: argparse.Namespace) -> int:
|
|
186
|
+
snapshot = _read_snapshot(args.list)
|
|
187
|
+
if snapshot is None:
|
|
188
|
+
return EXIT_FAILURE
|
|
189
|
+
result = load_inputs(args)
|
|
190
|
+
matches = find_matches(result.cfdis, snapshot, args.rfc)
|
|
191
|
+
for match in matches:
|
|
192
|
+
print(render_match(match))
|
|
193
|
+
alerts = sum(1 for match in matches if match.status.is_alert)
|
|
194
|
+
dated = f"dated {snapshot.as_of.isoformat()}" if snapshot.as_of else "of unknown date"
|
|
195
|
+
print(
|
|
196
|
+
f"{len(matches)} match(es) against the 69-B list {dated}, {alerts} presumed or definitive",
|
|
197
|
+
file=sys.stderr,
|
|
198
|
+
)
|
|
199
|
+
print(
|
|
200
|
+
"a match is a coincidence with a public list, not an accusation; ask your accountant",
|
|
201
|
+
file=sys.stderr,
|
|
202
|
+
)
|
|
203
|
+
return EXIT_FAILURE if alerts or result.errors else EXIT_OK
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def render_match(match: Match) -> str:
|
|
207
|
+
issued = match.issued_at.date().isoformat()
|
|
208
|
+
return (
|
|
209
|
+
f"{match.status.value:19} {match.issuer_rfc:13} {issued} {match.uuid or '-':36} "
|
|
210
|
+
f"{match.total:>12,.2f} {match.currency} {match.issuer_name or ''}"
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _report(args: argparse.Namespace) -> int:
|
|
215
|
+
snapshot = None
|
|
216
|
+
if args.risk_list is not None:
|
|
217
|
+
snapshot = _read_snapshot(args.risk_list)
|
|
218
|
+
if snapshot is None:
|
|
219
|
+
return EXIT_FAILURE
|
|
220
|
+
result = load_inputs(args)
|
|
221
|
+
if not result.cfdis:
|
|
222
|
+
return EXIT_FAILURE
|
|
223
|
+
output: Path = args.output
|
|
224
|
+
output.write_text(
|
|
225
|
+
build_report(result.cfdis, args.rfc, Basis(args.basis), risk=snapshot), encoding="utf-8"
|
|
226
|
+
)
|
|
227
|
+
print(f"wrote {output}", file=sys.stderr)
|
|
228
|
+
return EXIT_OK
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
if __name__ == "__main__":
|
|
232
|
+
raise SystemExit(main())
|
cfdi_kit/export.py
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
"""Flatten CFDIs into pandas tables and write them as CSV or Excel."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from datetime import datetime
|
|
6
|
+
from enum import StrEnum
|
|
7
|
+
from typing import TYPE_CHECKING
|
|
8
|
+
|
|
9
|
+
import pandas as pd
|
|
10
|
+
|
|
11
|
+
from cfdi_kit.catalogs import Catalog, label
|
|
12
|
+
from cfdi_kit.models import TaxCode, TaxKind, sum_taxes
|
|
13
|
+
|
|
14
|
+
if TYPE_CHECKING:
|
|
15
|
+
from collections.abc import Iterable, Sequence
|
|
16
|
+
from decimal import Decimal
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
from openpyxl.worksheet.worksheet import Worksheet
|
|
20
|
+
|
|
21
|
+
from cfdi_kit.models import Cfdi, Concept, Payment, PaymentDocument
|
|
22
|
+
|
|
23
|
+
Row = dict[str, str | float | int | datetime | None]
|
|
24
|
+
|
|
25
|
+
FORMULA_PREFIXES = ("=", "+", "-", "@", "\t", "\r", "\n", "\uff1d", "\uff0b", "\uff0d", "\uff20")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class Direction(StrEnum):
|
|
29
|
+
ISSUED = "issued"
|
|
30
|
+
RECEIVED = "received"
|
|
31
|
+
OTHER = "other"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def direction(cfdi: Cfdi, rfc: str) -> Direction:
|
|
35
|
+
"""Whether `rfc` issued or received the invoice."""
|
|
36
|
+
rfc = rfc.strip().upper()
|
|
37
|
+
if cfdi.issuer.rfc == rfc:
|
|
38
|
+
return Direction.ISSUED
|
|
39
|
+
if cfdi.receiver.rfc == rfc:
|
|
40
|
+
return Direction.RECEIVED
|
|
41
|
+
return Direction.OTHER
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def invoices_frame(cfdis: Iterable[Cfdi], rfc: str | None = None) -> pd.DataFrame:
|
|
45
|
+
"""One row per CFDI."""
|
|
46
|
+
return _frame([_invoice_row(c, rfc) for c in cfdis], INVOICE_COLUMNS)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def concepts_frame(cfdis: Iterable[Cfdi]) -> pd.DataFrame:
|
|
50
|
+
"""One row per line item (`Concepto`)."""
|
|
51
|
+
rows = [_concept_row(c, concept) for c in cfdis for concept in c.concepts]
|
|
52
|
+
return _frame(rows, CONCEPT_COLUMNS)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def payments_frame(cfdis: Iterable[Cfdi]) -> pd.DataFrame:
|
|
56
|
+
"""One row per invoice settled in a payment complement."""
|
|
57
|
+
rows = [
|
|
58
|
+
_payment_row(c, payment, document)
|
|
59
|
+
for c in cfdis
|
|
60
|
+
for payment in c.payments
|
|
61
|
+
for document in payment.documents
|
|
62
|
+
]
|
|
63
|
+
return _frame(rows, PAYMENT_COLUMNS)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def to_csv(cfdis: Sequence[Cfdi], path: str | Path, rfc: str | None = None) -> None:
|
|
67
|
+
"""Write one row per invoice; text a spreadsheet would run is prefixed with an apostrophe."""
|
|
68
|
+
invoices_frame(cfdis, rfc).map(_escape_formula).to_csv(path, index=False)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def to_excel(cfdis: Sequence[Cfdi], path: str | Path, rfc: str | None = None) -> None:
|
|
72
|
+
"""Write `invoices`, `line_items` and `payments` sheets."""
|
|
73
|
+
sheets = {
|
|
74
|
+
"invoices": invoices_frame(cfdis, rfc),
|
|
75
|
+
"line_items": concepts_frame(cfdis),
|
|
76
|
+
"payments": payments_frame(cfdis),
|
|
77
|
+
}
|
|
78
|
+
with pd.ExcelWriter(path, engine="openpyxl") as writer:
|
|
79
|
+
for name, frame in sheets.items():
|
|
80
|
+
frame.to_excel(writer, sheet_name=name, index=False)
|
|
81
|
+
sheet = writer.sheets[name]
|
|
82
|
+
_store_as_text(sheet)
|
|
83
|
+
sheet.freeze_panes = "A2"
|
|
84
|
+
sheet.auto_filter.ref = sheet.dimensions
|
|
85
|
+
for column, header in zip(sheet.columns, frame.columns, strict=True):
|
|
86
|
+
width = max([len(str(header)), *(len(str(c.value or "")) for c in column[1:200])])
|
|
87
|
+
sheet.column_dimensions[column[0].column_letter].width = min(width + 2, 60)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
INVOICE_COLUMNS = (
|
|
91
|
+
"uuid",
|
|
92
|
+
"direction",
|
|
93
|
+
"version",
|
|
94
|
+
"type",
|
|
95
|
+
"type_label",
|
|
96
|
+
"issued_at",
|
|
97
|
+
"stamped_at",
|
|
98
|
+
"series",
|
|
99
|
+
"folio",
|
|
100
|
+
"issuer_rfc",
|
|
101
|
+
"issuer_name",
|
|
102
|
+
"issuer_tax_regime",
|
|
103
|
+
"receiver_rfc",
|
|
104
|
+
"receiver_name",
|
|
105
|
+
"cfdi_use",
|
|
106
|
+
"payment_method",
|
|
107
|
+
"payment_form",
|
|
108
|
+
"payment_form_label",
|
|
109
|
+
"currency",
|
|
110
|
+
"exchange_rate",
|
|
111
|
+
"subtotal",
|
|
112
|
+
"discount",
|
|
113
|
+
"iva_transferred",
|
|
114
|
+
"ieps_transferred",
|
|
115
|
+
"iva_withheld",
|
|
116
|
+
"isr_withheld",
|
|
117
|
+
"total",
|
|
118
|
+
"total_mxn",
|
|
119
|
+
"related_uuids",
|
|
120
|
+
"source",
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
CONCEPT_COLUMNS = (
|
|
124
|
+
"uuid",
|
|
125
|
+
"issued_at",
|
|
126
|
+
"type",
|
|
127
|
+
"issuer_rfc",
|
|
128
|
+
"receiver_rfc",
|
|
129
|
+
"product_key",
|
|
130
|
+
"description",
|
|
131
|
+
"quantity",
|
|
132
|
+
"unit_key",
|
|
133
|
+
"unit_value",
|
|
134
|
+
"amount",
|
|
135
|
+
"discount",
|
|
136
|
+
"iva_transferred",
|
|
137
|
+
"iva_withheld",
|
|
138
|
+
"isr_withheld",
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
PAYMENT_COLUMNS = (
|
|
142
|
+
"payment_uuid",
|
|
143
|
+
"paid_at",
|
|
144
|
+
"issuer_rfc",
|
|
145
|
+
"receiver_rfc",
|
|
146
|
+
"payment_form",
|
|
147
|
+
"currency",
|
|
148
|
+
"exchange_rate",
|
|
149
|
+
"payment_amount",
|
|
150
|
+
"document_uuid",
|
|
151
|
+
"document_currency",
|
|
152
|
+
"installment",
|
|
153
|
+
"previous_balance",
|
|
154
|
+
"amount_paid",
|
|
155
|
+
"remaining_balance",
|
|
156
|
+
"iva_paid",
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _escape_formula(value: object) -> object:
|
|
161
|
+
if isinstance(value, str) and value.startswith(FORMULA_PREFIXES):
|
|
162
|
+
return f"'{value}"
|
|
163
|
+
return value
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _store_as_text(sheet: Worksheet) -> None:
|
|
167
|
+
"""Invoice text comes from third parties: never let openpyxl type it as formula or error."""
|
|
168
|
+
for row in sheet.iter_rows():
|
|
169
|
+
for cell in row:
|
|
170
|
+
if cell.data_type in {"f", "e"}:
|
|
171
|
+
cell.data_type = "s"
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _frame(rows: list[Row], columns: tuple[str, ...]) -> pd.DataFrame:
|
|
175
|
+
frame = pd.DataFrame(rows, columns=list(columns))
|
|
176
|
+
for column in columns:
|
|
177
|
+
if column.endswith("_at"):
|
|
178
|
+
frame[column] = pd.to_datetime(frame[column])
|
|
179
|
+
return frame
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def _money(value: Decimal | None) -> float | None:
|
|
183
|
+
return None if value is None else float(value)
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _invoice_row(cfdi: Cfdi, rfc: str | None) -> Row:
|
|
187
|
+
return {
|
|
188
|
+
"uuid": cfdi.uuid,
|
|
189
|
+
"direction": direction(cfdi, rfc).value if rfc else None,
|
|
190
|
+
"version": cfdi.version,
|
|
191
|
+
"type": cfdi.invoice_type.value,
|
|
192
|
+
"type_label": label(Catalog.INVOICE_TYPE, cfdi.invoice_type.value),
|
|
193
|
+
"issued_at": cfdi.issued_at,
|
|
194
|
+
"stamped_at": cfdi.stamp.stamped_at if cfdi.stamp else None,
|
|
195
|
+
"series": cfdi.series,
|
|
196
|
+
"folio": cfdi.folio,
|
|
197
|
+
"issuer_rfc": cfdi.issuer.rfc,
|
|
198
|
+
"issuer_name": cfdi.issuer.name,
|
|
199
|
+
"issuer_tax_regime": cfdi.issuer.tax_regime,
|
|
200
|
+
"receiver_rfc": cfdi.receiver.rfc,
|
|
201
|
+
"receiver_name": cfdi.receiver.name,
|
|
202
|
+
"cfdi_use": cfdi.receiver.cfdi_use,
|
|
203
|
+
"payment_method": cfdi.payment_method,
|
|
204
|
+
"payment_form": cfdi.payment_form,
|
|
205
|
+
"payment_form_label": label(Catalog.PAYMENT_FORM, cfdi.payment_form),
|
|
206
|
+
"currency": cfdi.currency,
|
|
207
|
+
"exchange_rate": _money(cfdi.exchange_rate),
|
|
208
|
+
"subtotal": _money(cfdi.subtotal),
|
|
209
|
+
"discount": _money(cfdi.discount),
|
|
210
|
+
"iva_transferred": _money(cfdi.iva_transferred),
|
|
211
|
+
"ieps_transferred": _money(cfdi.ieps_transferred),
|
|
212
|
+
"iva_withheld": _money(cfdi.iva_withheld),
|
|
213
|
+
"isr_withheld": _money(cfdi.isr_withheld),
|
|
214
|
+
"total": _money(cfdi.total),
|
|
215
|
+
"total_mxn": _money(cfdi.total * cfdi.rate_to_mxn),
|
|
216
|
+
"related_uuids": " ".join(u for r in cfdi.relations for u in r.uuids) or None,
|
|
217
|
+
"source": cfdi.source,
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _concept_row(cfdi: Cfdi, concept: Concept) -> Row:
|
|
222
|
+
return {
|
|
223
|
+
"uuid": cfdi.uuid,
|
|
224
|
+
"issued_at": cfdi.issued_at,
|
|
225
|
+
"type": cfdi.invoice_type.value,
|
|
226
|
+
"issuer_rfc": cfdi.issuer.rfc,
|
|
227
|
+
"receiver_rfc": cfdi.receiver.rfc,
|
|
228
|
+
"product_key": concept.product_key,
|
|
229
|
+
"description": concept.description,
|
|
230
|
+
"quantity": _money(concept.quantity),
|
|
231
|
+
"unit_key": concept.unit_key,
|
|
232
|
+
"unit_value": _money(concept.unit_value),
|
|
233
|
+
"amount": _money(concept.amount),
|
|
234
|
+
"discount": _money(concept.discount),
|
|
235
|
+
"iva_transferred": _money(sum_taxes(concept.taxes, TaxKind.TRANSFERRED, TaxCode.IVA)),
|
|
236
|
+
"iva_withheld": _money(sum_taxes(concept.taxes, TaxKind.WITHHELD, TaxCode.IVA)),
|
|
237
|
+
"isr_withheld": _money(sum_taxes(concept.taxes, TaxKind.WITHHELD, TaxCode.ISR)),
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _payment_row(cfdi: Cfdi, payment: Payment, document: PaymentDocument) -> Row:
|
|
242
|
+
iva_paid = sum_taxes(document.taxes, TaxKind.TRANSFERRED, TaxCode.IVA)
|
|
243
|
+
return {
|
|
244
|
+
"payment_uuid": cfdi.uuid,
|
|
245
|
+
"paid_at": payment.paid_at,
|
|
246
|
+
"issuer_rfc": cfdi.issuer.rfc,
|
|
247
|
+
"receiver_rfc": cfdi.receiver.rfc,
|
|
248
|
+
"payment_form": payment.payment_form,
|
|
249
|
+
"currency": payment.currency,
|
|
250
|
+
"exchange_rate": _money(payment.exchange_rate),
|
|
251
|
+
"payment_amount": _money(payment.amount),
|
|
252
|
+
"document_uuid": document.uuid,
|
|
253
|
+
"document_currency": document.currency,
|
|
254
|
+
"installment": document.installment,
|
|
255
|
+
"previous_balance": _money(document.previous_balance),
|
|
256
|
+
"amount_paid": _money(document.amount_paid),
|
|
257
|
+
"remaining_balance": _money(document.remaining_balance),
|
|
258
|
+
"iva_paid": _money(iva_paid) if document.taxes else None,
|
|
259
|
+
}
|