#!/usr/bin/env python3 """ resumo_nfe.py — Lê uma pasta de XMLs de NF-e (modelo 55, layout 4.00), extrai emitente, destinatário, valores e impostos e gera: * resumo_nfe.xlsx — planilha com abas "Notas", "Por emitente" e "Erros" * resumo_nfe.csv — mesma tabela de notas, separador ";" (padrão Excel BR) * relatorio_email.html / relatorio_email.txt — relatório pronto para colar no e-mail Uso: python resumo_nfe.py exemplos/xmls -o saida Somente biblioteca padrão + openpyxl. Não acessa SEFAZ nem a internet. Projeto demonstrativo de João Cesar dos Santos Pereira. """ from __future__ import annotations import argparse import csv import html import sys import xml.etree.ElementTree as ET from collections import defaultdict from dataclasses import dataclass, asdict, fields from datetime import datetime from pathlib import Path NS = {"n": "http://www.portalfiscal.inf.br/nfe"} @dataclass class Nota: arquivo: str chave: str numero: str serie: str data_emissao: str emitente_cnpj: str emitente_nome: str emitente_uf: str destinatario_doc: str destinatario_nome: str destinatario_uf: str qtd_itens: int valor_produtos: float valor_icms: float valor_ipi: float valor_pis: float valor_cofins: float valor_total: float status: str def _txt(node, path: str, default: str = "") -> str: if node is None: return default el = node.find(path, NS) return el.text.strip() if el is not None and el.text else default def _num(node, path: str) -> float: try: return float(_txt(node, path, "0").replace(",", ".")) except ValueError: return 0.0 def fmt_doc(doc: str) -> str: d = "".join(c for c in doc if c.isdigit()) if len(d) == 14: return f"{d[:2]}.{d[2:5]}.{d[5:8]}/{d[8:12]}-{d[12:]}" if len(d) == 11: return f"{d[:3]}.{d[3:6]}.{d[6:9]}-{d[9:]}" return doc def brl(v: float) -> str: s = f"{v:,.2f}" return "R$ " + s.replace(",", "X").replace(".", ",").replace("X", ".") def ler_nfe(caminho: Path) -> Nota: raiz = ET.parse(caminho).getroot() inf = raiz.find(".//n:infNFe", NS) if inf is None: raise ValueError("tag não encontrada (não parece uma NF-e)") ide, emit, dest = inf.find("n:ide", NS), inf.find("n:emit", NS), inf.find("n:dest", NS) tot = inf.find("n:total/n:ICMSTot", NS) if tot is None: raise ValueError("totais ausentes") data = _txt(ide, "n:dhEmi") or _txt(ide, "n:dEmi") try: data = datetime.fromisoformat(data).strftime("%d/%m/%Y %H:%M") except ValueError: pass cstat = _txt(raiz, ".//n:protNFe/n:infProt/n:cStat") status = {"100": "Autorizada", "101": "Cancelada", "110": "Denegada"}.get(cstat, "Sem protocolo" if not cstat else f"cStat {cstat}") return Nota( arquivo=caminho.name, chave=inf.get("Id", "").removeprefix("NFe"), numero=_txt(ide, "n:nNF"), serie=_txt(ide, "n:serie"), data_emissao=data, emitente_cnpj=fmt_doc(_txt(emit, "n:CNPJ") or _txt(emit, "n:CPF")), emitente_nome=_txt(emit, "n:xNome"), emitente_uf=_txt(emit, "n:enderEmit/n:UF"), destinatario_doc=fmt_doc(_txt(dest, "n:CNPJ") or _txt(dest, "n:CPF")), destinatario_nome=_txt(dest, "n:xNome"), destinatario_uf=_txt(dest, "n:enderDest/n:UF"), qtd_itens=len(inf.findall("n:det", NS)), valor_produtos=_num(tot, "n:vProd"), valor_icms=_num(tot, "n:vICMS"), valor_ipi=_num(tot, "n:vIPI"), valor_pis=_num(tot, "n:vPIS"), valor_cofins=_num(tot, "n:vCOFINS"), valor_total=_num(tot, "n:vNF"), status=status, ) CABECALHOS = { "arquivo": "Arquivo", "chave": "Chave de acesso", "numero": "Número", "serie": "Série", "data_emissao": "Emissão", "emitente_cnpj": "CNPJ emitente", "emitente_nome": "Emitente", "emitente_uf": "UF emit.", "destinatario_doc": "CNPJ/CPF destinatário", "destinatario_nome": "Destinatário", "destinatario_uf": "UF dest.", "qtd_itens": "Itens", "valor_produtos": "Valor produtos", "valor_icms": "ICMS", "valor_ipi": "IPI", "valor_pis": "PIS", "valor_cofins": "COFINS", "valor_total": "Valor total", "status": "Status", } MONETARIOS = {"valor_produtos", "valor_icms", "valor_ipi", "valor_pis", "valor_cofins", "valor_total"} def gerar_csv(notas: list[Nota], destino: Path) -> None: with destino.open("w", newline="", encoding="utf-8-sig") as f: w = csv.writer(f, delimiter=";") w.writerow(CABECALHOS.values()) for n in notas: w.writerow([f"{v:.2f}".replace(".", ",") if isinstance(v, float) else v for v in asdict(n).values()]) def agrupar(notas: list[Nota]) -> list[dict]: g: dict[str, dict] = defaultdict(lambda: {"notas": 0, "total": 0.0, "icms": 0.0, "ipi": 0.0, "pis": 0.0, "cofins": 0.0}) for n in notas: k = f"{n.emitente_nome} ({n.emitente_cnpj})" g[k]["notas"] += 1 g[k]["total"] += n.valor_total g[k]["icms"] += n.valor_icms g[k]["ipi"] += n.valor_ipi g[k]["pis"] += n.valor_pis g[k]["cofins"] += n.valor_cofins return sorted(({"emitente": k, **v} for k, v in g.items()), key=lambda x: -x["total"]) def gerar_xlsx(notas: list[Nota], erros: list[tuple[str, str]], destino: Path) -> None: from openpyxl import Workbook from openpyxl.styles import Alignment, Font, PatternFill from openpyxl.utils import get_column_letter azul = PatternFill("solid", fgColor="0F4C81") branco = Font(bold=True, color="FFFFFF") moeda = 'R$ #,##0.00' wb = Workbook() ws = wb.active ws.title = "Notas" chaves = [f.name for f in fields(Nota)] ws.append([CABECALHOS[c] for c in chaves]) for n in notas: ws.append([getattr(n, c) for c in chaves]) linha_total = ws.max_row + 1 ws.cell(linha_total, 1, "TOTAL").font = Font(bold=True) for i, c in enumerate(chaves, start=1): if c in MONETARIOS: L = get_column_letter(i) ws.cell(linha_total, i, f"=SUM({L}2:{L}{linha_total-1})").font = Font(bold=True) for r in range(2, linha_total + 1): ws.cell(r, i).number_format = moeda for cell in ws[1]: cell.fill, cell.font = azul, branco cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True) for i, c in enumerate(chaves, start=1): largura = max(len(str(ws.cell(r, i).value or "")) for r in range(1, ws.max_row + 1)) ws.column_dimensions[get_column_letter(i)].width = min(max(10, largura + 2), 48) ws.freeze_panes = "A2" ws.auto_filter.ref = f"A1:{get_column_letter(len(chaves))}{linha_total-1}" ws2 = wb.create_sheet("Por emitente") ws2.append(["Emitente", "Notas", "Valor total", "ICMS", "IPI", "PIS", "COFINS"]) for g in agrupar(notas): ws2.append([g["emitente"], g["notas"]] + [round(g[k], 2) for k in ("total", "icms", "ipi", "pis", "cofins")]) for cell in ws2[1]: cell.fill, cell.font = azul, branco for row in ws2.iter_rows(min_row=2, min_col=3): for cell in row: cell.number_format = moeda ws2.column_dimensions["A"].width = 52 for L in "BCDEFG": ws2.column_dimensions[L].width = 16 ws3 = wb.create_sheet("Erros") ws3.append(["Arquivo", "Motivo"]) for cell in ws3[1]: cell.fill, cell.font = azul, branco for e in erros: ws3.append(list(e)) ws3.column_dimensions["A"].width = 30 ws3.column_dimensions["B"].width = 70 wb.save(destino) def gerar_relatorio(notas: list[Nota], erros: list[tuple[str, str]], pasta: Path, destino_dir: Path) -> None: total = sum(n.valor_total for n in notas) imp = {k: sum(getattr(n, f"valor_{k}") for n in notas) for k in ("icms", "ipi", "pis", "cofins")} grupos = agrupar(notas) hoje = datetime.now().strftime("%d/%m/%Y %H:%M") txt = [ "Assunto: Resumo de NF-e processadas", "", "Olá,", "", f"Segue o resumo das notas fiscais eletrônicas da pasta \"{pasta.name}\" (gerado em {hoje}).", "", f" • Notas processadas: {len(notas)}", f" • Arquivos com erro: {len(erros)}", f" • Valor total das notas: {brl(total)}", f" • ICMS: {brl(imp['icms'])} | IPI: {brl(imp['ipi'])} | PIS: {brl(imp['pis'])} | COFINS: {brl(imp['cofins'])}", "", "Por emitente:", ] txt += [f" - {g['emitente']}: {g['notas']} nota(s), {brl(g['total'])}" for g in grupos] if erros: txt += ["", "Arquivos não processados:"] + [f" - {a}: {m}" for a, m in erros] txt += ["", "A planilha completa (resumo_nfe.xlsx) segue em anexo.", "", "Atenciosamente,"] (destino_dir / "relatorio_email.txt").write_text("\n".join(txt) + "\n", encoding="utf-8") linhas = "".join( f"{html.escape(n.numero)}{html.escape(n.data_emissao)}{html.escape(n.emitente_nome)}" f"{html.escape(n.destinatario_nome)}{brl(n.valor_icms)}" f"{brl(n.valor_total)}" for n in notas) cards = "".join( f"
{r}
" f"
{v}
" for r, v in [("Notas", len(notas)), ("Valor total", brl(total)), ("ICMS", brl(imp["icms"])), ("Erros", len(erros))]) erros_html = ("

Arquivos não processados

") if erros else "" doc = f"""Resumo de NF-e

Resumo de NF-e processadas

Pasta: {html.escape(pasta.name)} · gerado em {hoje}

{cards}

Notas

{linhas}
NºEmissãoEmitenteDestinatárioICMSTotal
TOTAL{brl(imp['icms'])}{brl(total)}
{erros_html}

IPI {brl(imp['ipi'])} · PIS {brl(imp['pis'])} · COFINS {brl(imp['cofins'])} — planilha completa em anexo (resumo_nfe.xlsx).

""" (destino_dir / "relatorio_email.html").write_text(doc, encoding="utf-8") def main(argv=None) -> int: ap = argparse.ArgumentParser(description="Gera planilha e relatório a partir de XMLs de NF-e.") ap.add_argument("pasta", type=Path, help="pasta com os arquivos .xml") ap.add_argument("-o", "--saida", type=Path, default=Path("saida"), help="pasta de saída (padrão: ./saida)") ap.add_argument("--sem-xlsx", action="store_true", help="não gerar a planilha XLSX (somente CSV)") a = ap.parse_args(argv) if not a.pasta.is_dir(): print(f"Pasta não encontrada: {a.pasta}", file=sys.stderr) return 2 a.saida.mkdir(parents=True, exist_ok=True) notas, erros = [], [] for xml in sorted(a.pasta.glob("*.xml")): try: notas.append(ler_nfe(xml)) except ET.ParseError as e: erros.append((xml.name, f"XML malformado ({e})")) except ValueError as e: erros.append((xml.name, str(e))) notas.sort(key=lambda n: (n.emitente_nome, n.numero)) gerar_csv(notas, a.saida / "resumo_nfe.csv") if not a.sem_xlsx: gerar_xlsx(notas, erros, a.saida / "resumo_nfe.xlsx") gerar_relatorio(notas, erros, a.pasta, a.saida) total = sum(n.valor_total for n in notas) print(f"✔ {len(notas)} NF-e processadas | {len(erros)} com erro | total {brl(total)}") print(f" Arquivos gerados em: {a.saida.resolve()}") for e in erros: print(f" ✘ {e[0]}: {e[1]}") return 0 if __name__ == "__main__": raise SystemExit(main())