-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgui.py
More file actions
401 lines (330 loc) · 15 KB
/
Copy pathgui.py
File metadata and controls
401 lines (330 loc) · 15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
"""Interface gráfica para o NF-e Batch Processor.
Uso: python gui.py
"""
import os
import sys
import time
import threading
import xml.etree.ElementTree as ET
from decimal import Decimal
from pathlib import Path
import tkinter as tk
from tkinter import ttk, filedialog, scrolledtext, messagebox
sys.path.insert(0, str(Path(__file__).parent / "src"))
from nfe_processor import fake_generator, reader, parser, validators, report
from nfe_processor.models import ResultadoValidacao
# ─── Paleta ──────────────────────────────────────────────────────────────────
DARK = "#1F3864"
BLUE = "#2E75B6"
BLUE_H = "#1A5C9A"
LIGHT = "#EBF2FA"
BG = "#F4F6F9"
WHITE = "#FFFFFF"
GREEN = "#27AE60"
GREEN_H = "#1E8449"
RED_BG = "#FDEDEC"
TEXT = "#2C3E50"
GRAY = "#BDC3C7"
GRAY_D = "#7F8C8D"
BORDER = "#D5D8DC"
# ─── Redirecionador de stdout para o widget de log ───────────────────────────
class _LogRedirector:
def __init__(self, widget: scrolledtext.ScrolledText, after_fn):
self._widget = widget
self._after = after_fn
self._buffer = []
def write(self, text: str):
self._buffer.append(text)
self._after(0, self._flush)
def _flush(self):
if not self._buffer:
return
chunk = "".join(self._buffer)
self._buffer.clear()
self._widget.configure(state="normal")
self._widget.insert(tk.END, chunk)
self._widget.see(tk.END)
self._widget.configure(state="disabled")
def flush(self):
pass
# ─── Componentes de UI ───────────────────────────────────────────────────────
def _btn(parent, text, command, color=BLUE, hover=BLUE_H, width=22, **kw):
b = tk.Button(
parent, text=text, command=command,
bg=color, fg=WHITE, activebackground=hover, activeforeground=WHITE,
font=("Segoe UI", 9, "bold"), relief="flat", cursor="hand2",
padx=14, pady=7, width=width, bd=0, **kw
)
b.bind("<Enter>", lambda _: b.configure(bg=hover))
b.bind("<Leave>", lambda _: b.configure(bg=color))
return b
def _label(parent, text, size=9, bold=False, color=TEXT, **kw):
return tk.Label(
parent, text=text, bg=BG,
font=("Segoe UI", size, "bold" if bold else "normal"),
fg=color, **kw
)
def _entry(parent, textvariable, width=50):
e = ttk.Entry(parent, textvariable=textvariable, width=width, font=("Segoe UI", 9))
return e
def _card(parent, title: str, **kw):
frame = tk.LabelFrame(
parent, text=f" {title} ",
bg=BG, fg=DARK, font=("Segoe UI", 9, "bold"),
relief="solid", bd=1, padx=14, pady=10, **kw
)
return frame
# ─── Aplicação principal ─────────────────────────────────────────────────────
class App(tk.Tk):
def __init__(self):
super().__init__()
self.title("NF-e Batch Processor")
self.geometry("720x620")
self.minsize(600, 520)
self.configure(bg=BG)
self.resizable(True, True)
self._ultimo_relatorio: Path | None = None
self._processando = False
self._input_var = tk.StringVar()
self._output_var = tk.StringVar(value=str(Path.home() / "nfe-output"))
self._qty_var = tk.IntVar(value=40)
self._status_var = tk.StringVar(value="Pronto")
self._build()
# ── Construção da UI ──────────────────────────────────────────────────────
def _build(self):
self._build_header()
main = tk.Frame(self, bg=BG, padx=16, pady=10)
main.pack(fill="both", expand=True)
self._build_fake_section(main)
self._build_process_section(main)
self._build_log_section(main)
self._build_footer(main)
def _build_header(self):
header = tk.Frame(self, bg=DARK, pady=14)
header.pack(fill="x")
tk.Label(
header, text="NF-e Batch Processor",
bg=DARK, fg=WHITE, font=("Segoe UI", 14, "bold")
).pack(side="left", padx=20)
tk.Label(
header, text="Processamento e validação em lote",
bg=DARK, fg=GRAY, font=("Segoe UI", 9)
).pack(side="left", padx=4, pady=4)
def _build_fake_section(self, parent):
card = _card(parent, "1 — Gerar XMLs de Demonstração")
card.pack(fill="x", pady=(0, 10))
row = tk.Frame(card, bg=BG)
row.pack(fill="x")
_label(row, "Quantidade de notas:").pack(side="left")
sb = tk.Spinbox(
row, from_=5, to=500, textvariable=self._qty_var,
width=6, font=("Segoe UI", 9), relief="solid", bd=1
)
sb.pack(side="left", padx=(6, 20))
self._btn_fake = _btn(
row, "📁 Escolher pasta e gerar",
self._gerar_fake, width=26
)
self._btn_fake.pack(side="left")
_label(
card,
"Gera XMLs sintéticos (com ~15% de defeitos propositais). "
"A pasta de entrada é preenchida automaticamente.",
color=GRAY_D, size=8
).pack(anchor="w", pady=(6, 0))
def _build_process_section(self, parent):
card = _card(parent, "2 — Processar Lote")
card.pack(fill="x", pady=(0, 10))
# Pasta de entrada
row1 = tk.Frame(card, bg=BG)
row1.pack(fill="x", pady=(0, 6))
_label(row1, "Pasta de entrada:", width=18, anchor="w").pack(side="left")
_entry(row1, self._input_var, width=44).pack(side="left", padx=(0, 6))
tk.Button(
row1, text="Procurar…", command=self._browse_input,
font=("Segoe UI", 8), relief="solid", bd=1, padx=8, pady=4,
bg=WHITE, fg=TEXT, cursor="hand2"
).pack(side="left")
# Pasta de saída
row2 = tk.Frame(card, bg=BG)
row2.pack(fill="x", pady=(0, 10))
_label(row2, "Pasta de saída:", width=18, anchor="w").pack(side="left")
_entry(row2, self._output_var, width=44).pack(side="left", padx=(0, 6))
tk.Button(
row2, text="Procurar…", command=self._browse_output,
font=("Segoe UI", 8), relief="solid", bd=1, padx=8, pady=4,
bg=WHITE, fg=TEXT, cursor="hand2"
).pack(side="left")
# Botão processar
btn_row = tk.Frame(card, bg=BG)
btn_row.pack(fill="x")
self._btn_processar = _btn(
btn_row, "▶ Processar Lote",
self._processar, color=GREEN, hover=GREEN_H, width=22
)
self._btn_processar.pack(side="right")
def _build_log_section(self, parent):
card = _card(parent, "Resultado")
card.pack(fill="both", expand=True, pady=(0, 10))
self._log = scrolledtext.ScrolledText(
card, state="disabled", height=10,
font=("Consolas", 9), bg="#1E1E1E", fg="#D4D4D4",
insertbackground=WHITE, relief="flat", bd=0,
wrap="word",
)
self._log.pack(fill="both", expand=True)
# Tags de cor no log
self._log.tag_configure("ok", foreground="#4EC9B0")
self._log.tag_configure("erro", foreground="#F14C4C")
self._log.tag_configure("info", foreground="#9CDCFE")
self._log.tag_configure("path", foreground="#CE9178")
def _build_footer(self, parent):
footer = tk.Frame(parent, bg=BG)
footer.pack(fill="x")
self._btn_abrir = _btn(
footer, "📊 Abrir Relatório Excel",
self._abrir_relatorio, color=DARK, hover="#2C4070", width=24
)
self._btn_abrir.pack(side="left")
self._btn_abrir.configure(state="disabled")
tk.Button(
footer, text="Limpar log",
command=self._log_clear,
font=("Segoe UI", 8), relief="flat", bg=BG, fg=GRAY_D,
cursor="hand2", bd=0
).pack(side="left", padx=10)
tk.Label(
footer, textvariable=self._status_var,
bg=BG, fg=GRAY_D, font=("Segoe UI", 8)
).pack(side="right")
# ── Ações ─────────────────────────────────────────────────────────────────
def _gerar_fake(self):
pasta = filedialog.askdirectory(title="Escolha a pasta para os XMLs gerados")
if not pasta:
return
n = self._qty_var.get()
self._log_clear()
self._log_write(f"Gerando {n} XMLs sintéticos em:\n{pasta}\n\n", "info")
self._status("Gerando XMLs…")
self._btn_fake.configure(state="disabled")
def run():
old_stdout = sys.stdout
sys.stdout = _LogRedirector(self._log, self.after)
try:
fake_generator.gerar_lote(Path(pasta), n)
self._input_var.set(pasta)
self.after(0, lambda: self._status("✔ XMLs gerados — pasta de entrada preenchida"))
except Exception as e:
self.after(0, lambda: messagebox.showerror("Erro", str(e)))
finally:
sys.stdout = old_stdout
self.after(0, lambda: self._btn_fake.configure(state="normal"))
threading.Thread(target=run, daemon=True).start()
def _processar(self):
input_dir = Path(self._input_var.get().strip())
output_dir = Path(self._output_var.get().strip())
if not self._input_var.get().strip():
messagebox.showwarning("Atenção", "Informe a pasta de entrada.")
return
if not input_dir.exists():
messagebox.showerror("Erro", f"Pasta não encontrada:\n{input_dir}")
return
self._log_clear()
self._status("Processando…")
self._btn_processar.configure(state="disabled")
self._btn_abrir.configure(state="disabled")
def run():
old_stdout = sys.stdout
sys.stdout = _LogRedirector(self._log, self.after)
try:
inicio = time.perf_counter()
resultados: list[ResultadoValidacao] = []
chaves_vistas: set[str] = set()
xmls = list(reader.ler_pasta(input_dir))
if not xmls:
print("Nenhum XML encontrado na pasta selecionada.")
return
print(f"Processando {len(xmls)} arquivo(s)…\n")
for caminho in xmls:
try:
nota = parser.parse_xml(caminho)
erros = validators.validar_nota(nota, chaves_vistas)
chaves_vistas.add(nota.chave)
resultado = ResultadoValidacao(
arquivo=caminho.name, chave=nota.chave,
ok=len(erros) == 0, erros=erros, nota=nota,
)
except ET.ParseError as e:
resultado = ResultadoValidacao(
arquivo=caminho.name, chave=None, ok=False,
erros=[f"XML malformado: {e}"],
)
except Exception as e:
resultado = ResultadoValidacao(
arquivo=caminho.name, chave=None, ok=False,
erros=[f"Erro ao ler: {e}"],
)
resultados.append(resultado)
duracao = time.perf_counter() - inicio
ok = [r for r in resultados if r.ok]
erros = [r for r in resultados if not r.ok]
soma = sum(r.nota.valor_total for r in ok if r.nota)
caminho_xlsx = report.gerar_relatorio(resultados, output_dir)
self._ultimo_relatorio = caminho_xlsx
# Resumo colorido no log
self.after(0, lambda: self._log_write(
f"✔ {len(resultados)} arquivo(s) processados em {duracao:.1f}s\n", "ok"
))
self.after(0, lambda: self._log_write(
f" {len(ok)} nota(s) válida(s) — R$ {soma:,.2f}\n", "ok"
))
if erros:
self.after(0, lambda: self._log_write(
f" {len(erros)} nota(s) com problema:\n", "erro"
))
for r in erros:
for e in r.erros:
msg = f" ✖ [{r.arquivo}] {e}\n"
self.after(0, lambda m=msg: self._log_write(m, "erro"))
self.after(0, lambda: self._log_write(f"\n→ {caminho_xlsx}\n", "path"))
self.after(0, lambda: self._status(
f"✔ Concluído — {len(ok)} OK / {len(erros)} erro(s)"
))
self.after(0, lambda: self._btn_abrir.configure(state="normal"))
except Exception as e:
self.after(0, lambda: messagebox.showerror("Erro inesperado", str(e)))
self.after(0, lambda: self._status("Erro durante processamento"))
finally:
sys.stdout = old_stdout
self.after(0, lambda: self._btn_processar.configure(state="normal"))
threading.Thread(target=run, daemon=True).start()
def _abrir_relatorio(self):
if self._ultimo_relatorio and self._ultimo_relatorio.exists():
os.startfile(str(self._ultimo_relatorio))
def _browse_input(self):
pasta = filedialog.askdirectory(title="Selecione a pasta com os XMLs de NF-e")
if pasta:
self._input_var.set(pasta)
def _browse_output(self):
pasta = filedialog.askdirectory(title="Selecione a pasta de saída para o relatório")
if pasta:
self._output_var.set(pasta)
# ── Utilitários de log ────────────────────────────────────────────────────
def _log_write(self, text: str, tag: str = ""):
self._log.configure(state="normal")
if tag:
self._log.insert(tk.END, text, tag)
else:
self._log.insert(tk.END, text)
self._log.see(tk.END)
self._log.configure(state="disabled")
def _log_clear(self):
self._log.configure(state="normal")
self._log.delete("1.0", tk.END)
self._log.configure(state="disabled")
def _status(self, msg: str):
self._status_var.set(msg)
# ─── Entry point ─────────────────────────────────────────────────────────────
if __name__ == "__main__":
app = App()
app.mainloop()