-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerateur_factures_kdp.py
More file actions
439 lines (368 loc) · 19.9 KB
/
Copy pathgenerateur_factures_kdp.py
File metadata and controls
439 lines (368 loc) · 19.9 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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
import tkinter as tk
from tkinter import ttk, filedialog, scrolledtext, messagebox
import json
import os
import subprocess
import platform
from datetime import datetime, timedelta
import threading
# Assuming kdp_invoice_generator is available
from kdp_invoice_generator import generer_facture_logic
# Placeholder for generer_facture_logic for testing purposes
# def generer_facture_logic(filepath, year, month, output_format):
# # Simulate some work
# print(f"Generating invoice for {month}/{year} from {filepath} in {output_format} format.")
# if "error" in filepath:
# return False, "Simulated error during generation.", []
#
# # Simulate success and return dummy file paths
# dummy_files = []
# if output_format == "docx" or output_format == "both":
# dummy_files.append(f"facture_{year}_{month}.docx")
# if output_format == "pdf" or output_format == "both":
# dummy_files.append(f"facture_{year}_{month}.pdf")
#
# return True, f"Facture(s) générée(s) pour {month}/{year}.", dummy_files
CONFIG_PATH = "config.json"
# --- Description/version ---
INFOS_VERSION = """\
Générateur de factures Word et PDF automatisé pour les revenus Amazon KDP
Auteur: Sébastien Baudry – assisté de Claude 4 Sonnet, Gemini Pro 2.5, ChatGPT 4o
Version: 3.3 – génération par lots + corrections de bugs
"""
def charger_config():
if os.path.exists(CONFIG_PATH):
with open(CONFIG_PATH, 'r', encoding='utf-8') as f:
return json.load(f)
# Provide a default structure if config.json doesn't exist
return {
"informations_personnelles": {
"nom": "",
"adresse": "",
"siret": "",
"tva_intra": "",
"code_ape": "",
"iban": "",
"bic": ""
},
"facturation": {
"lieu": "",
"autoliquidation": "Facture en auto-liquidation (Art. 283-2 du CGI)",
"message": "En tant qu’auteur, mes prestations sont exonérées de TVA (Art. 293B du CGI).",
"format_nom_sortie": "Facture KDP {annee}-{mois}"
}
}
def sauvegarder_config(config):
with open(CONFIG_PATH, 'w', encoding='utf-8') as f:
json.dump(config, f, indent=2, ensure_ascii=False)
class InvoiceApp(tk.Tk):
def __init__(self):
super().__init__()
self.title("Générateur de Factures KDP")
self.geometry("900x700")
self.config_data = charger_config()
self.config_widgets = {}
self.is_generating = False # Flag to prevent multiple generations
self.notebook = ttk.Notebook(self)
self.notebook.pack(fill=tk.BOTH, expand=True)
self.setup_generation_tab()
self.setup_config_tab()
self.setup_version_tab() # Ajout de l'onglet version
# Define a style for invalid entries (ttk widgets)
self.style = ttk.Style()
self.style.configure('Error.TEntry', fieldbackground='#FFE0E0', foreground='black') # Light red background
self.style.configure('Error.TCombobox', fieldbackground='#FFE0E0', foreground='black')
# --- Onglet Génération ---
def setup_generation_tab(self):
gen_frame = ttk.Frame(self.notebook)
self.notebook.add(gen_frame, text="Génération")
file_frame = ttk.LabelFrame(gen_frame, text="Fichier de rapport KDP", padding=10)
file_frame.pack(fill=tk.X, padx=10, pady=5)
self.filepath_var = tk.StringVar()
ttk.Entry(file_frame, textvariable=self.filepath_var, state="readonly").pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(0, 10))
ttk.Button(file_frame, text="Parcourir...", command=self.browse_file).pack(side=tk.LEFT)
period_frame = ttk.LabelFrame(gen_frame, text="Période des revenus", padding=10)
period_frame.pack(fill=tk.X, padx=10, pady=5)
# Configure grid
period_frame.grid_columnconfigure(0, weight=1)
period_frame.grid_columnconfigure(1, weight=1)
period_frame.grid_columnconfigure(2, weight=1)
period_frame.grid_columnconfigure(3, weight=1)
# Headers
ttk.Label(period_frame, text="Début", font=('TkDefaultFont', 10, 'bold')).grid(row=0, column=0, columnspan=2, sticky='w', padx=5, pady=(0,5))
ttk.Label(period_frame, text="Fin", font=('TkDefaultFont', 10, 'bold')).grid(row=0, column=2, columnspan=2, sticky='w', padx=5, pady=(0,5))
# Année labels
ttk.Label(period_frame, text="Année :").grid(row=1, column=0, sticky='w', padx=5)
ttk.Label(period_frame, text="Année :").grid(row=1, column=2, sticky='w', padx=5)
# Année entries
self.start_year_var = tk.StringVar(value=str(self.get_default_period()[0]))
ttk.Combobox(period_frame, textvariable=self.start_year_var, values=[str(y) for y in range(2007, 2037)], state="readonly", width=10).grid(row=1, column=1, padx=5, sticky='w')
self.end_year_var = tk.StringVar(value=str(self.get_default_period()[0]))
ttk.Combobox(period_frame, textvariable=self.end_year_var, values=[str(y) for y in range(2007, 2037)], state="readonly", width=10).grid(row=1, column=3, padx=5, sticky='w')
# Mois labels
ttk.Label(period_frame, text="Mois :").grid(row=2, column=0, sticky='w', padx=5)
ttk.Label(period_frame, text="Mois :").grid(row=2, column=2, sticky='w', padx=5)
# Mois comboboxes
self.start_month_var = tk.StringVar(value=str(self.get_default_period()[1]))
ttk.Combobox(period_frame, textvariable=self.start_month_var, values=[str(i) for i in range(1, 13)], state="readonly", width=5).grid(row=2, column=1, padx=5, sticky='w')
self.end_month_var = tk.StringVar(value=str(self.get_default_period()[1]))
ttk.Combobox(period_frame, textvariable=self.end_month_var, values=[str(i) for i in range(1, 13)], state="readonly", width=5).grid(row=2, column=3, padx=5, sticky='w')
format_frame = ttk.LabelFrame(gen_frame, text="Format de sortie", padding=10)
format_frame.pack(fill=tk.X, padx=10, pady=5)
self.format_var = tk.StringVar(value="pdf")
for fmt in [("DOCX", "docx"), ("PDF", "pdf"), ("Les deux", "both")]:
ttk.Radiobutton(format_frame, text=fmt[0], variable=self.format_var, value=fmt[1]).pack(side=tk.LEFT, padx=10)
self.generate_button = ttk.Button(gen_frame, text="Générer la facture", command=self.start_generation)
self.generate_button.pack(pady=15, fill=tk.X, padx=10)
log_frame = ttk.LabelFrame(gen_frame, text="Journal", padding=10)
log_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)
self.log_text = scrolledtext.ScrolledText(log_frame, height=10, state='disabled', wrap=tk.WORD)
self.log_text.pack(fill=tk.BOTH, expand=True)
self.log_text.tag_config('ERROR', foreground='red')
self.log_text.tag_config('SUCCESS', foreground='green')
self.log_text.tag_config('WARNING', foreground='orange')
def browse_file(self):
filepath = filedialog.askopenfilename(title="Sélectionnez le fichier KDP", filetypes=[("Excel", "*.xlsx"), ("CSV", "*.csv")])
if filepath:
self.filepath_var.set(filepath)
def get_default_period(self):
today = datetime.now()
# Calculate month - 2
two_months_ago = today.replace(day=1) - timedelta(days=1) # last month
two_months_ago = two_months_ago.replace(day=1) - timedelta(days=1) # month before that
return two_months_ago.year, two_months_ago.month
def start_generation(self):
if self.is_generating:
return # Already generating, ignore
self.is_generating = True
self.generate_button.config(state='disabled') # Disable immediately
filepath = self.filepath_var.get()
start_year = self.start_year_var.get()
start_month = self.start_month_var.get()
end_year = self.end_year_var.get()
end_month = self.end_month_var.get()
if not filepath:
self.log("Veuillez sélectionner un fichier.", "ERROR")
self.is_generating = False
self.generate_button.config(state='normal')
return
if not (start_year.isdigit() and start_month.isdigit() and end_year.isdigit() and end_month.isdigit()):
self.log("Années et mois invalides.", "ERROR")
self.is_generating = False
self.generate_button.config(state='normal')
return
start_year, start_month, end_year, end_month = int(start_year), int(start_month), int(end_year), int(end_month)
# Generate list of periods
periods = self.generate_periods(start_year, start_month, end_year, end_month)
if not periods:
self.log("Période de fin antérieure à la période de début.", "ERROR")
self.is_generating = False
self.generate_button.config(state='normal')
return
self.clear_log()
self.log(f"Lancement de la génération pour {len(periods)} période(s)...")
threading.Thread(target=self.run_batch_generation, args=(filepath, periods)).start()
def generate_periods(self, start_year, start_month, end_year, end_month):
periods = []
current_year = start_year
current_month = start_month
max_periods = 100 # Prevent infinite loops or too many
while ((current_year < end_year) or (current_year == end_year and current_month <= end_month)) and len(periods) < max_periods:
periods.append((current_year, current_month))
current_month += 1
if current_month > 12:
current_month = 1
current_year += 1
if len(periods) >= max_periods:
return [] # Too many periods, likely error
return periods
def run_batch_generation(self, filepath, periods):
try:
self.log(f"Démarrage génération batch pour {len(periods)} période(s)")
total_files = []
for year, month in periods:
self.log(f"Traitement {month}/{year}...")
try:
success, message, fichiers = generer_facture_logic(filepath, year, month, self.format_var.get())
if success:
self.log(f"✅ {message}")
total_files.extend(fichiers)
else:
if "Aucune donnée trouvée" in message or "Aucun fichier généré." in message:
self.log(f"⚠️ Aucune donnée pour {month}/{year}: {message}", "WARNING")
else:
self.log(f"❌ Erreur pour {month}/{year}: {message}", "ERROR")
except Exception as e:
self.log(f"❌ Erreur pour {month}/{year}: {e}", "ERROR")
if total_files:
self.log("-" * 50)
self.log(f"Terminé ! {len(total_files)} fichier(s) généré(s) au total.")
max_open = 5
for f in total_files[:max_open]:
try:
if platform.system() == 'Windows':
os.startfile(f)
elif platform.system() == 'Darwin':
subprocess.run(['open', f])
else:
subprocess.run(['xdg-open', f])
except Exception as e:
self.log(f"Impossible d'ouvrir {f} : {e}", "ERROR")
if len(total_files) > max_open:
self.log(f"⚠️ {len(total_files) - max_open} fichier(s) supplémentaire(s) non ouvert(s) (limite à {max_open}).", "WARNING")
else:
self.log("Aucun fichier généré.", "ERROR")
finally:
self.is_generating = False
self.generate_button.config(state='normal')
def run_generation_logic(self, filepath, year, month):
try:
success, message, fichiers = generer_facture_logic(filepath, year, month, self.format_var.get())
except Exception as e:
self.log(f"Erreur : {e}", "ERROR")
self.generate_button.config(state='normal')
return
if success:
self.log(message, "SUCCESS")
for f in fichiers:
self.log(f"Ouverture : {f}")
try:
if platform.system() == 'Windows':
os.startfile(f)
elif platform.system() == 'Darwin':
subprocess.run(['open', f])
else:
subprocess.run(['xdg-open', f])
except Exception as e:
self.log(f"Impossible d’ouvrir {f} : {e}", "ERROR")
else:
self.log(message, "ERROR")
def log(self, message, level=None):
self.log_text.config(state='normal')
self.log_text.insert(tk.END, message + "\n", level)
self.log_text.config(state='disabled')
self.log_text.see(tk.END)
# Also write to log file
try:
with open("generation_log.txt", "a", encoding="utf-8") as f:
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
f.write(f"[{timestamp}] {message}\n")
except Exception as e:
# If can't write to file, ignore
pass
def clear_log(self):
self.log_text.config(state='normal')
self.log_text.delete(1.0, tk.END)
self.log_text.config(state='disabled')
# Also write separator to log file
try:
with open("generation_log.txt", "a", encoding="utf-8") as f:
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
f.write(f"\n[{timestamp}] === Nouvelle session ===\n")
except Exception as e:
pass
# --- Onglet Paramétrage ---
def setup_config_tab(self):
config_frame = ttk.Frame(self.notebook)
self.notebook.add(config_frame, text="Paramétrage")
canvas = tk.Canvas(config_frame)
scrollbar = ttk.Scrollbar(config_frame, orient="vertical", command=canvas.yview)
scrollable = ttk.Frame(canvas)
scrollable.bind("<Configure>", lambda e: canvas.configure(scrollregion=canvas.bbox("all")))
canvas.create_window((0, 0), window=scrollable, anchor="nw")
canvas.configure(yscrollcommand=scrollbar.set)
canvas.pack(side="left", fill="both", expand=True)
scrollbar.pack(side="right", fill="y")
def _on_mousewheel(event):
if platform.system() == 'Windows':
canvas.yview_scroll(-1 * int(event.delta / 120), "units")
elif platform.system() == 'Darwin':
canvas.yview_scroll(-1 * int(event.delta), "units")
else:
canvas.yview_scroll(-1 if event.num == 4 else 1, "units")
scrollable.bind("<Enter>", lambda e: canvas.bind_all("<MouseWheel>", _on_mousewheel))
scrollable.bind("<Leave>", lambda e: canvas.unbind_all("<MouseWheel>"))
scrollable.bind("<Enter>", lambda e: canvas.bind_all("<Button-4>", _on_mousewheel))
scrollable.bind("<Enter>", lambda e: canvas.bind_all("<Button-5>", _on_mousewheel))
scrollable.bind("<Leave>", lambda e: canvas.unbind_all("<Button-4>"))
scrollable.bind("<Leave>", lambda e: canvas.unbind_all("<Button-5>"))
multiligne_keys = ["adresse", "autoliquidation", "message", "format", "texte"]
for section, fields in self.config_data.items():
frame = ttk.LabelFrame(scrollable, text=section.capitalize(), padding=10)
frame.pack(fill=tk.X, expand=True, padx=10, pady=5)
self.config_widgets[section] = {}
for key, value in fields.items():
row = ttk.Frame(frame)
row.pack(fill=tk.X, expand=True, pady=3)
ttk.Label(row, text=key + " :", width=25, anchor="w").pack(side=tk.LEFT)
if any(k in key.lower() for k in multiligne_keys) or "\n" in str(value):
widget = tk.Text(row, height=3, wrap=tk.WORD)
widget.insert("1.0", str(value))
widget.pack(side=tk.LEFT, fill=tk.X, expand=True)
else:
widget = ttk.Entry(row)
widget.insert(0, str(value))
widget.pack(side=tk.LEFT, fill=tk.X, expand=True)
self.config_widgets[section][key] = widget
ttk.Button(scrollable, text="💾 Enregistrer les paramètres", command=self.save_config).pack(pady=15)
# Modified highlight_invalid function
def highlight_invalid(self, widget):
if isinstance(widget, tk.Text):
widget.configure(highlightbackground="red", highlightcolor="red", highlightthickness=2)
elif isinstance(widget, ttk.Entry) or isinstance(widget, ttk.Combobox): # Assuming Combobox might also be used
widget.configure(style='Error.TEntry') # Apply the custom style for ttk widgets
# Add more conditions for other ttk widgets if necessary
# else:
# print(f"Cannot highlight unknown widget type: {type(widget)}")
def save_config(self):
erreurs = []
champs_valides = {}
# Modified reset_border function
def reset_border(w):
if isinstance(w, tk.Text):
w.configure(highlightthickness=0)
elif isinstance(w, ttk.Entry) or isinstance(w, ttk.Combobox):
# Reset to default style
w.configure(style='TEntry') # Default ttk Entry style
# Add more conditions for other ttk widgets if necessary
for section, fields in self.config_widgets.items():
champs_valides[section] = {}
for key, widget in fields.items():
reset_border(widget) # Reset border before validation
value = widget.get("1.0", tk.END).strip() if isinstance(widget, tk.Text) else widget.get().strip()
if not value:
erreurs.append(f"[{section}] Le champ '{key}' est vide.")
self.highlight_invalid(widget)
continue
k = key.lower()
if k == "siret" and not value.replace(" ", "").isdigit():
erreurs.append(f"[{section}] Le SIRET doit être numérique.")
self.highlight_invalid(widget)
elif k == "tva_intra" and not (len(value) >= 4 and value[:2].isalpha() and value[2:].replace(" ", "").isalnum()):
erreurs.append(f"[{section}] TVA intra invalide. Format attendu: FRxx... (minimum 4 caractères, 2 lettres suivies de chiffres/lettres).")
self.highlight_invalid(widget)
elif k == "iban" and not (len(value) >= 4 and value[:2].isalpha() and value[2:].replace(" ", "").isalnum()): # IBANs can contain letters after country code
erreurs.append(f"[{section}] IBAN invalide. Format attendu: FRxx... (minimum 4 caractères, 2 lettres suivies de chiffres/lettres).")
self.highlight_invalid(widget)
elif k == "bic" and not (len(value.strip()) in [8, 11] and value.isalnum()):
erreurs.append(f"[{section}] BIC invalide.")
self.highlight_invalid(widget)
else:
champs_valides[section][key] = value
if erreurs:
messagebox.showerror("Erreurs de validation", "\n".join(erreurs))
return
self.config_data = champs_valides
sauvegarder_config(self.config_data)
messagebox.showinfo("Succès", "Configuration enregistrée.")
# --- Onglet Version ---
def setup_version_tab(self):
version_frame = ttk.Frame(self.notebook)
self.notebook.add(version_frame, text="Version")
txt = tk.Text(version_frame, wrap=tk.WORD, height=15, bg=self.cget('bg'), relief=tk.FLAT)
txt.insert("1.0", INFOS_VERSION)
txt.config(state='disabled')
txt.pack(fill=tk.BOTH, expand=True, padx=20, pady=20)
if __name__ == "__main__":
app = InvoiceApp()
app.mainloop()