Spaces:
Sleeping

File size: 32,115 Bytes
cf08437
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8641d62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf08437
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8641d62
 
cf08437
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8641d62
 
cf08437
8641d62
 
cf08437
8641d62
 
cf08437
 
8641d62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf08437
8641d62
 
 
 
 
cf08437
8641d62
 
 
 
 
 
 
 
cf08437
 
 
8641d62
 
 
 
cf08437
8641d62
 
cf08437
8641d62
 
 
 
 
 
 
 
 
 
cf08437
8641d62
 
cf08437
8641d62
 
 
 
cf08437
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8641d62
cf08437
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8641d62
 
 
 
 
 
 
cf08437
 
 
 
 
8641d62
cf08437
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8641d62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf08437
 
 
 
 
 
8641d62
cf08437
 
8641d62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf08437
 
 
 
 
 
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
from flask import Flask, request, jsonify, send_file, render_template_string
import pdfplumber
import re
import io
import zipfile
from fpdf import FPDF
from datetime import datetime
import os

app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 50 * 1024 * 1024

def extraire_client(texte):
    t = str(texte).upper()
    t = re.sub(r'\b(VIR(EMENT)?|PRLV|SEPA|RECU|CARTE|CB|RETRAIT|AVOIR|REMISE|CHEQUE|CHQ|PAIEMENT|REGLEMENT|ABONNEMENT|DOC|TXT|PID|FRAIS)\b', ' ', t)
    t = re.sub(r'\d', ' ', t)
    m = re.search(r'([A-Z][A-Z\s\-]{3,})', t)
    return m.group(1).strip()[:40] if m else "Client inconnu"

def parse_montant(s):
    s = str(s).replace('\u00a0','').replace(' ','').replace(',','.')
    s = re.sub(r'[^\d.\-+]', '', s)
    try: return float(s)
    except: return None

def parse_qonto(texte):
    LIGNE = re.compile(r'"(\d{2}/\d{2})\s+(.+?)\s+([\-\+]\s*[\d\s]+\.?\d*)\s+EUR"')
    MONT  = re.compile(r'([+\-])\s*([\d\s]+\.?\d*)')
    res   = []
    annee = str(datetime.now().year)
    for line in texte.splitlines():
        m = LIGNE.match(line.strip())
        if not m: continue
        mm = MONT.match(m.group(3).strip())
        if not mm: continue
        sign = 1 if mm.group(1)=='+' else -1
        val  = float(mm.group(2).replace(' ','')) * sign
        res.append({"date": m.group(1)+"/"+annee, "client": extraire_client(m.group(2).strip()), "montant": val})
    return res

def parse_csv(texte):
    lignes = [l for l in texte.strip().splitlines() if l.strip()]
    if not lignes: return []
    sep = ";" if texte[:500].count(";") >= texte[:500].count(",") else ","
    mots = ["date","libelle","libellé","montant","amount","credit","debit","description","label","motif","operation","solde"]
    debut = 0
    for i,l in enumerate(lignes):
        cols = [c.strip().strip('"').lower() for c in l.split(sep)]
        if any(any(k in c for k in mots) for c in cols):
            debut = i; break
    headers = [c.strip().strip('"').lower() for c in lignes[debut].split(sep)]
    mc = next((c for c in headers if any(k in c for k in ["montant","amount","crédit","credit","débit","debit"])), None)
    if not mc: return []
    lc = next((c for c in headers if any(k in c for k in ["libelle","libellé","description","label","motif","operation"])), None)
    dc = next((c for c in headers if "date" in c or "jour" in c), None)
    res = []
    for ligne in lignes[debut+1:]:
        cells = [c.strip().strip('"') for c in ligne.split(sep)]
        if len(cells) < len(headers): continue
        row = dict(zip(headers, cells))
        val = parse_montant(row.get(mc, ""))
        if val is None: continue
        res.append({
            "date": row.get(dc, datetime.now().strftime("%d/%m/%Y")) if dc else datetime.now().strftime("%d/%m/%Y"),
            "client": extraire_client(row.get(lc, "")) if lc else "Client inconnu",
            "montant": val
        })
    return res

def parse_qonto_pdf(texte):
    """Parser specifique pour le format PDF Qonto :
    JJ/MM NOM CLIENT
    description optionnelle
    + ou - montant EUR
    """
    lignes = texte.strip().splitlines()
    annee = str(datetime.now().year)
    DATE_RE = re.compile(r'^(\d{2}/\d{2})\s+(.+)$')
    MONT_RE = re.compile(r'^([+\-])\s*([\d\s]+\.?\d*)\s*EUR$')
    res = []
    i = 0
    while i < len(lignes):
        ligne = lignes[i].strip()
        dm = DATE_RE.match(ligne)
        if dm:
            date = dm.group(1) + "/" + annee
            client = dm.group(2).strip()
            for j in range(i+1, min(i+4, len(lignes))):
                l = lignes[j].strip()
                mm = MONT_RE.match(l)
                if mm:
                    sign = 1 if mm.group(1) == "+" else -1
                    val = float(mm.group(2).replace(" ", "")) * sign
                    res.append({"date": date, "client": client, "montant": val})
                    i = j
                    break
        i += 1
    return res

def parse_texte_brut(texte):
    DATE_RE    = re.compile(r'\b(\d{1,2}[/\-\.]\d{1,2}(?:[/\-\.]\d{2,4})?)\b')
    MONTANT_RE = re.compile(r'([+\-]?\s?\d{1,3}(?:[\s\u00a0]\d{3})*(?:[,\.]\d{1,2})?)\s*(?:EUR|€)?')
    res = []
    for ligne in texte.strip().splitlines():
        ligne = ligne.strip()
        if not ligne: continue
        dm = DATE_RE.search(ligne)
        if not dm: continue
        ms = MONTANT_RE.findall(ligne)
        if not ms: continue
        m = parse_montant(ms[-1].replace(' ','').replace('\u00a0',''))
        if m is None: continue
        lib = MONTANT_RE.sub('', ligne[dm.end():]).strip(' €-+')
        res.append({"date": dm.group(1), "client": extraire_client(lib or ligne), "montant": m})
    return res

def parse_auto(texte):
    r = parse_qonto_pdf(texte)
    if r: return r
    r = parse_qonto(texte)
    if r: return r
    r = parse_csv(texte)
    if r: return r
    return parse_texte_brut(texte)

def lire_pdf(data):
    try:
        texte = []
        with pdfplumber.open(io.BytesIO(data)) as pdf:
            for page in pdf.pages:
                t = page.extract_text()
                if t: texte.append(t)
        return parse_auto("\n".join(texte))
    except:
        return []

def lire_csv(data):
    for enc in ["utf-8","latin-1","cp1252"]:
        try:
            return parse_auto(data.decode(enc))
        except: continue
    return []

def generer_facture(row, numero, company, tva_rate):
    pdf = FPDF()
    pdf.add_page()

    # ── Bande header ──
    pdf.set_fill_color(13,13,13)
    pdf.rect(0,0,210,45,'F')
    pdf.set_font("Helvetica","B",20)
    pdf.set_text_color(200,241,53)
    pdf.set_y(10)
    pdf.cell(0,11,"FACTURE",ln=1,align="C")
    pdf.set_font("Helvetica","",8)
    pdf.set_text_color(170,170,170)
    num = "N FACT-"+datetime.now().strftime("%Y%m")+"-"+str(numero).zfill(4)
    pdf.cell(0,5,num+"   |   Date : "+str(row.get("date","")),ln=1,align="C")
    pdf.ln(12)

    # ── Emetteur / Destinataire ──
    pdf.set_text_color(80,80,80)
    pdf.set_font("Helvetica","B",7)
    pdf.set_x(14)
    pdf.cell(88,4,"EMETTEUR",ln=0)
    pdf.cell(88,4,"DESTINATAIRE",ln=1)
    pdf.ln(2)

    name    = str(company.get("name",""))[:45]
    addr    = str(company.get("address","")).replace("\n"," - ")[:60]
    siret   = "SIRET : "+str(company.get("siret",""))
    client  = str(row.get("client",""))[:45]

    pdf.set_font("Helvetica","B",9)
    pdf.set_text_color(20,20,20)
    pdf.set_x(14); pdf.cell(88,5,name,ln=0); pdf.cell(88,5,client,ln=1)

    pdf.set_font("Helvetica","",8)
    pdf.set_text_color(100,100,100)
    pdf.set_x(14); pdf.cell(88,5,addr,ln=1)
    pdf.set_x(14); pdf.cell(88,5,siret,ln=1)
    pdf.ln(5)

    # ── Separateur ──
    pdf.set_draw_color(200,241,53); pdf.set_line_width(0.6)
    pdf.line(14,pdf.get_y(),196,pdf.get_y()); pdf.ln(5)

    # ── En-tete tableau ──
    pdf.set_fill_color(13,13,13)
    pdf.set_text_color(200,241,53)
    pdf.set_font("Helvetica","B",8)
    pdf.set_x(14)
    pdf.cell(104,8,"DESCRIPTION",0,fill=True)
    pdf.cell(28,8,"HT",0,align="R",fill=True)
    pdf.cell(22,8,"TVA",0,align="R",fill=True)
    pdf.cell(28,8,"TTC",0,align="R",fill=True)
    pdf.ln(8)

    # ── Ligne prestation ──
    tva  = tva_rate/100
    mht  = round(row["montant"]/(1+tva),2) if tva>0 else round(row["montant"],2)
    mtva = round(row["montant"]-mht,2)
    mttc = round(row["montant"],2)

    pdf.set_fill_color(248,248,244)
    pdf.set_text_color(20,20,20)
    pdf.set_font("Helvetica","",9)
    pdf.set_x(14)
    pdf.cell(104,9,"Prestation de services",0,fill=True)
    pdf.cell(28,9,str(mht)+" EUR",0,align="R",fill=True)
    pdf.cell(22,9,str(tva_rate)+"%",0,align="R",fill=True)
    pdf.cell(28,9,str(mttc)+" EUR",0,align="R",fill=True)
    pdf.ln(11)

    # ── Totaux ──
    pdf.set_draw_color(220,215,205); pdf.set_line_width(0.3)
    pdf.line(14,pdf.get_y(),196,pdf.get_y()); pdf.ln(4)

    pdf.set_x(130); pdf.set_font("Helvetica","",8); pdf.set_text_color(130,125,115)
    pdf.cell(36,5,"Sous-total HT",ln=0); pdf.cell(36,5,str(mht)+" EUR",align="R",ln=1)
    pdf.set_x(130); pdf.cell(36,5,"TVA "+str(tva_rate)+"%",ln=0); pdf.cell(36,5,str(mtva)+" EUR",align="R",ln=1)
    pdf.ln(2)

    pdf.set_fill_color(200,241,53); pdf.set_x(120)
    pdf.set_font("Helvetica","B",10); pdf.set_text_color(13,13,13)
    pdf.cell(76,12,"  TOTAL TTC    "+str(mttc)+" EUR",align="R",fill=True,ln=1)
    pdf.ln(18)

    # ── Pied ──
    pdf.set_font("Helvetica","I",7); pdf.set_text_color(160,155,145); pdf.set_x(14)
    pdf.cell(0,4,"Facture payable sous 30 jours - Merci pour votre confiance.",ln=1)
    if tva_rate==0:
        pdf.set_x(14); pdf.cell(0,4,"TVA non applicable, art. 293 B du CGI",ln=1)
    return bytes(pdf.output())


HTML_PAGE = (
    "<!DOCTYPE html>"
    "<html lang='fr'>"
    "<head>"
    "<meta charset='UTF-8'>"
    "<meta name='viewport' content='width=device-width,initial-scale=1,maximum-scale=1'>"
    "<title>FactureAuto</title>"
    "<link href='https://fonts.googleapis.com/css2?family=Syne:wght@700;800&family=DM+Sans:wght@300;400;500;600&display=swap' rel='stylesheet'>"
    "<style>"
    "*{box-sizing:border-box;margin:0;padding:0;-webkit-tap-highlight-color:transparent;}"
    ":root{--bg:#0a0a0a;--card:#141414;--card2:#1a1a1a;--border:#252525;--a:#c8f135;--a2:#35f1c8;--t:#efefef;--m:#666;}"
    "body{font-family:'DM Sans',sans-serif;background:var(--bg);color:var(--t);min-height:100vh;padding:0 0 80px;}"
    ".hdr{padding:40px 20px 0;text-align:center;}"
    ".hdr-tag{font-size:10px;letter-spacing:4px;text-transform:uppercase;color:var(--m);margin-bottom:8px;}"
    ".hdr-title{font-family:'Syne',sans-serif;font-size:42px;font-weight:800;line-height:1;background:linear-gradient(135deg,var(--t) 0%,var(--a) 100%);-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text;}"
    ".hdr-sub{font-size:13px;color:var(--m);margin-top:8px;font-weight:300;line-height:1.5;}"
    ".hdr-line{height:1px;background:linear-gradient(90deg,transparent,var(--a),transparent);margin:28px 0;}"
    ".card{background:var(--card);border:1px solid var(--border);border-radius:20px;padding:20px;margin:0 16px 16px;}"
    ".card-title{font-size:11px;letter-spacing:3px;text-transform:uppercase;color:var(--m);margin-bottom:16px;font-weight:500;}"
    "input[type=text],input[type=password],textarea,select{width:100%;background:var(--card2);border:1px solid var(--border);border-radius:12px;color:var(--t);font-family:'DM Sans',sans-serif;font-size:15px;padding:14px 16px;outline:none;transition:border-color .2s;-webkit-appearance:none;}"
    "input:focus,textarea:focus,select:focus{border-color:var(--a);}"
    "textarea{resize:none;height:80px;}"
    "label{display:block;font-size:12px;color:var(--m);margin-bottom:6px;font-weight:500;}"
    ".row{display:grid;grid-template-columns:1fr 1fr;gap:12px;}"
    ".upload-zone{border:2px dashed var(--border);border-radius:16px;padding:32px 20px;text-align:center;transition:all .2s;cursor:pointer;position:relative;background:var(--card2);}"
    ".upload-zone.drag{border-color:var(--a);background:rgba(200,241,53,.04);}"
    ".upload-zone input{position:absolute;inset:0;opacity:0;width:100%;height:100%;cursor:pointer;font-size:16px;}"
    ".upload-icon{font-size:36px;margin-bottom:10px;}"
    ".upload-title{font-size:15px;font-weight:600;color:var(--t);margin-bottom:4px;}"
    ".upload-sub{font-size:12px;color:var(--m);}"
    ".file-list{margin-top:12px;}"
    ".file-item{display:flex;align-items:center;gap:10px;background:var(--card2);border:1px solid var(--border);border-radius:10px;padding:10px 14px;margin-bottom:8px;}"
    ".file-icon{font-size:20px;}"
    ".file-name{flex:1;font-size:13px;font-weight:500;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}"
    ".file-size{font-size:11px;color:var(--m);}"
    ".file-remove{background:none;border:none;color:var(--m);font-size:18px;cursor:pointer;padding:0 4px;}"
    ".progress{display:none;margin-top:16px;}"
    ".progress-bar{height:4px;background:var(--border);border-radius:99px;overflow:hidden;}"
    ".progress-fill{height:100%;background:linear-gradient(90deg,var(--a),var(--a2));border-radius:99px;width:0%;transition:width .3s;}"
    ".progress-text{font-size:12px;color:var(--m);margin-top:8px;text-align:center;}"
    ".tx-list{display:none;}"
    ".tx-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:14px;}"
    ".stats{display:grid;grid-template-columns:1fr 1fr 1fr;gap:8px;margin-bottom:16px;}"
    ".stat{background:var(--card2);border:1px solid var(--border);border-radius:12px;padding:12px;text-align:center;}"
    ".stat-n{font-family:'Syne',sans-serif;font-size:18px;font-weight:700;color:var(--a);}"
    ".stat-l{font-size:10px;color:var(--m);text-transform:uppercase;letter-spacing:1px;margin-top:2px;}"
    ".tx-item{display:flex;align-items:center;gap:12px;padding:14px;background:var(--card2);border:1px solid var(--border);border-radius:12px;margin-bottom:8px;transition:border-color .15s;cursor:pointer;}"
    ".tx-item.selected{border-color:var(--a);background:rgba(200,241,53,.04);}"
    ".tx-check{width:22px;height:22px;border-radius:6px;border:2px solid var(--border);flex-shrink:0;display:flex;align-items:center;justify-content:center;transition:all .15s;}"
    ".tx-item.selected .tx-check{background:var(--a);border-color:var(--a);}"
    ".tx-check-inner{display:none;color:#0a0a0a;font-size:13px;font-weight:900;}"
    ".tx-item.selected .tx-check-inner{display:block;}"
    ".tx-info{flex:1;min-width:0;}"
    ".tx-client{font-size:14px;font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}"
    ".tx-date{font-size:11px;color:var(--m);margin-top:2px;}"
    ".tx-amount{font-size:15px;font-weight:700;color:var(--a);white-space:nowrap;}"
    ".btn{display:block;width:100%;padding:16px;border-radius:14px;font-family:'DM Sans',sans-serif;font-size:16px;font-weight:700;border:none;cursor:pointer;transition:all .2s;letter-spacing:.3px;text-align:center;text-decoration:none;}"
    ".btn-primary{background:var(--a);color:#0a0a0a;}"
    ".btn-primary:active{background:#b5d92e;}"
    ".btn-primary:disabled{background:var(--border);color:var(--m);cursor:not-allowed;}"
    ".btn-dl{background:var(--a2);color:#0a0a0a;margin-top:12px;display:none;}"
    ".sel-all{display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;}"
    ".sel-all-btn{font-size:12px;color:var(--a);background:none;border:none;cursor:pointer;font-family:'DM Sans',sans-serif;font-weight:600;}"
    ".sel-count{font-size:12px;color:var(--m);}"
    ".alert{padding:14px 16px;border-radius:12px;font-size:13px;margin-bottom:12px;line-height:1.5;}"
    ".alert-err{background:rgba(255,80,80,.1);border:1px solid rgba(255,80,80,.3);color:#ff8080;}"
    ".alert-ok{background:rgba(200,241,53,.08);border:1px solid rgba(200,241,53,.2);color:var(--a);}"
    "@keyframes spin{to{transform:rotate(360deg)}}"
    ".spinner{width:18px;height:18px;border:2px solid rgba(10,10,10,.3);border-top-color:#0a0a0a;border-radius:50%;animation:spin .7s linear infinite;display:inline-block;vertical-align:middle;margin-right:8px;}"
    "</style>"
    "</head>"
    "<body>"
    "<div class='hdr'>"
    "<div class='hdr-tag'>Facturation automatique</div>"
    "<div class='hdr-title'>FactureAuto</div>"
    "<div class='hdr-sub'>Chargez vos relevés bancaires<br>et generez vos factures en un tap</div>"
    "<div class='hdr-line'></div>"
    "</div>"
    "<div class='card'>"
    "<div class='card-title'>Votre societe</div>"
    "<div style='margin-bottom:12px'><label>Nom de la societe</label><input type='text' id='company_name' value='Ma Societe SARL'></div>"
    "<div style='margin-bottom:12px'><label>Adresse</label><textarea id='company_address'>12 rue des Entrepreneurs\n75001 Paris</textarea></div>"
    "<div class='row'><div><label>SIRET</label><input type='text' id='company_siret' value='123 456 789 00012'></div>"
    "<div><label>TVA</label><select id='tva_rate'><option value='0'>0%</option><option value='5'>5%</option><option value='10'>10%</option><option value='20' selected>20%</option></select></div></div>"
    "</div>"
    "<div class='card'>"
    "<div class='card-title'>Releves bancaires</div>"
    "<div class='upload-zone' id='uploadZone'>"
    "<input type='file' id='fileInput' accept='.pdf,.csv' multiple>"
    "<div class='upload-icon'>📂</div>"
    "<div class='upload-title'>Appuyez pour choisir vos fichiers</div>"
    "<div class='upload-sub'>PDF ou CSV - Plusieurs fichiers acceptes</div>"
    "</div>"
    "<div class='file-list' id='fileList'></div>"
    "<div class='progress' id='progress'>"
    "<div class='progress-bar'><div class='progress-fill' id='progressFill'></div></div>"
    "<div class='progress-text' id='progressText'>Analyse en cours...</div>"
    "</div>"
    "<div id='alertZone' style='margin-top:12px'></div>"
    "<button class='btn btn-primary' id='analyzeBtn' style='margin-top:16px;display:none' onclick='analyser()'>Analyser les releves</button>"
    "</div>"
    "<div class='card tx-list' id='txCard'>"
    "<div class='card-title'>Encaissements detectes</div>"
    "<div class='stats' id='statsZone'></div>"
    "<div class='sel-all'>"
    "<button class='sel-all-btn' onclick='toutSelectionner()'>Tout selectionner / deselectionner</button>"
    "<span class='sel-count' id='selCount'>0 selectionne(s)</span>"
    "</div>"
    "<div id='txList'></div>"
    "<div style='margin-bottom:12px;margin-top:16px'>"+"<div style='font-size:11px;letter-spacing:3px;text-transform:uppercase;color:var(--m);margin-bottom:10px;font-weight:500'>MODE DE FACTURATION</div>"+"<div style='display:grid;grid-template-columns:1fr 1fr;gap:8px'>"+"<button id='modeIndiv' onclick='setMode(\"individuel\")' style='padding:12px;border-radius:10px;border:2px solid var(--a);background:var(--a);color:#0a0a0a;font-family:DM Sans,sans-serif;font-size:13px;font-weight:700;cursor:pointer'>Une facture<br><span style=\"font-weight:400;font-size:11px\">par transaction</span></button>"+"<button id='modeGroupe' onclick='setMode(\"groupe\")' style='padding:12px;border-radius:10px;border:2px solid var(--border);background:var(--card2);color:var(--m);font-family:DM Sans,sans-serif;font-size:13px;font-weight:700;cursor:pointer'>Une facture<br><span style=\"font-weight:400;font-size:11px\">par tiers (groupee)</span></button>"+"</div></div>"+"<button class='btn btn-primary' id='genBtn' onclick='generer()' style='margin-top:12px'>Generer les factures</button>"
    "<a class='btn btn-dl' id='dlBtn'>Telecharger le ZIP</a>"
    "</div>"
    "<script>"
    "var selectedFiles=[];var transactions=[];var selected=new Set();"
    "var zone=document.getElementById('uploadZone');"
    "zone.addEventListener('dragover',function(e){e.preventDefault();zone.classList.add('drag');});"
    "zone.addEventListener('dragleave',function(){zone.classList.remove('drag');});"
    "zone.addEventListener('drop',function(e){e.preventDefault();zone.classList.remove('drag');addFiles(e.dataTransfer.files);});"
    "document.getElementById('fileInput').addEventListener('change',function(){addFiles(this.files);this.value='';});"
    "function addFiles(files){"
    "for(var i=0;i<files.length;i++){var f=files[i];var exists=selectedFiles.some(function(x){return x.name===f.name&&x.size===f.size;});if(!exists)selectedFiles.push(f);}"
    "renderFiles();}"
    "function renderFiles(){"
    "var list=document.getElementById('fileList');list.innerHTML='';"
    "selectedFiles.forEach(function(f,i){"
    "var size=f.size>1024*1024?(f.size/1024/1024).toFixed(1)+'MB':Math.round(f.size/1024)+'KB';"
    "var div=document.createElement('div');div.className='file-item';"
    "div.innerHTML='<span class=\"file-icon\">'+(f.name.endsWith('.pdf')?'📄':'📊')+'</span><span class=\"file-name\">'+f.name+'</span><span class=\"file-size\">'+size+'</span><button class=\"file-remove\" onclick=\"removeFile('+i+')\">x</button>';"
    "list.appendChild(div);});"
    "document.getElementById('analyzeBtn').style.display=selectedFiles.length?'block':'none';}"
    "function removeFile(i){selectedFiles.splice(i,1);renderFiles();}"
    "function showAlert(msg,type){document.getElementById('alertZone').innerHTML='<div class=\"alert alert-'+(type||'err')+'\">'+msg+'</div>';}"
    "function analyser(){"
    "if(!selectedFiles.length)return;"
    "var btn=document.getElementById('analyzeBtn');"
    "btn.disabled=true;btn.innerHTML='<span class=\"spinner\"></span>Analyse en cours...';"
    "document.getElementById('progress').style.display='block';"
    "document.getElementById('progressFill').style.width='30%';"
    "document.getElementById('alertZone').innerHTML='';"
    "var form=new FormData();"
    "selectedFiles.forEach(function(f){form.append('files',f);});"
    "form.append('company_name',document.getElementById('company_name').value);"
    "form.append('company_address',document.getElementById('company_address').value);"
    "form.append('company_siret',document.getElementById('company_siret').value);"
    "form.append('tva_rate',document.getElementById('tva_rate').value);"
    "fetch('/analyser',{method:'POST',body:form})"
    ".then(function(r){return r.json();})"
    ".then(function(data){"
    "document.getElementById('progressFill').style.width='100%';"
    "if(data.error){showAlert(data.error);btn.disabled=false;btn.innerHTML='Analyser les releves';return;}"
    "transactions=data.transactions;renderTransactions();"
    "btn.disabled=false;btn.innerHTML='Analyser les releves';"
    "document.getElementById('progress').style.display='none';})"
    ".catch(function(e){showAlert('Erreur: '+e.message);btn.disabled=false;btn.innerHTML='Analyser les releves';document.getElementById('progress').style.display='none';});}"
    "function renderTransactions(){"
    "if(!transactions.length){showAlert('Aucun encaissement trouve.');return;}"
    "selected=new Set(transactions.map(function(_,i){return i;}));"
    "var total=transactions.reduce(function(s,t){return s+t.montant;},0);"
    "document.getElementById('statsZone').innerHTML="
    "'<div class=\"stat\"><div class=\"stat-n\">'+transactions.length+'</div><div class=\"stat-l\">Encaissements</div></div>'"
    "+'<div class=\"stat\"><div class=\"stat-n\">'+Math.round(total).toLocaleString('fr')+'</div><div class=\"stat-l\">Total EUR</div></div>'"
    "+'<div class=\"stat\"><div class=\"stat-n\">'+Math.round(total/1.2).toLocaleString('fr')+'</div><div class=\"stat-l\">Total HT</div></div>';"
    "var list=document.getElementById('txList');list.innerHTML='';"
    "transactions.forEach(function(tx,i){"
    "var div=document.createElement('div');div.className='tx-item selected';div.id='tx-'+i;div.onclick=function(){toggleTx(i);};"
    "div.innerHTML='<div class=\"tx-check\"><span class=\"tx-check-inner\">✓</span></div><div class=\"tx-info\"><div class=\"tx-client\">'+tx.client+'</div><div class=\"tx-date\">'+tx.date+'</div></div><div class=\"tx-amount\">'+tx.montant.toFixed(2)+' EUR</div>';"
    "list.appendChild(div);});"
    "document.getElementById('txCard').style.display='block';"
    "document.getElementById('dlBtn').style.display='none';"
    "updateSelCount();"
    "document.getElementById('txCard').scrollIntoView({behavior:'smooth'});}"
    "function toggleTx(i){if(selected.has(i))selected.delete(i);else selected.add(i);var el=document.getElementById('tx-'+i);if(selected.has(i))el.classList.add('selected');else el.classList.remove('selected');updateSelCount();}"
    "function toutSelectionner(){if(selected.size===transactions.length){selected.clear();transactions.forEach(function(_,i){document.getElementById('tx-'+i).classList.remove('selected');});}else{transactions.forEach(function(_,i){selected.add(i);document.getElementById('tx-'+i).classList.add('selected');});}updateSelCount();}"
    "function updateSelCount(){document.getElementById('selCount').textContent=selected.size+' selectionne(s)';setMode(currentMode);document.getElementById('genBtn').disabled=selected.size===0;}"
    "var currentMode='individuel';"
    "function setMode(m){currentMode=m;"
    "document.getElementById('modeIndiv').style.cssText='padding:12px;border-radius:10px;border:2px solid '+(m==='individuel'?'var(--a)':'var(--border)')+';background:'+(m==='individuel'?'var(--a)':'var(--card2)')+';color:'+(m==='individuel'?'#0a0a0a':'var(--m)')+';font-family:DM Sans,sans-serif;font-size:13px;font-weight:700;cursor:pointer;width:100%';"
    "document.getElementById('modeGroupe').style.cssText='padding:12px;border-radius:10px;border:2px solid '+(m==='groupe'?'var(--a)':'var(--border)')+';background:'+(m==='groupe'?'var(--a)':'var(--card2)')+';color:'+(m==='groupe'?'#0a0a0a':'var(--m)')+';font-family:DM Sans,sans-serif;font-size:13px;font-weight:700;cursor:pointer;width:100%';"
    "var nb=m==='groupe'?new Set(Array.from(selected).map(function(i){return transactions[i].client;})).size:selected.size;"
    "document.getElementById('genBtn').textContent='Generer '+nb+(m==='groupe'?' facture(s) groupee(s)':' facture(s)');}"
    "function generer(){"
    "if(!selected.size)return;"
    "var btn=document.getElementById('genBtn');"
    "btn.disabled=true;btn.innerHTML='<span class=\"spinner\"></span>Generation...';"
    "var sel=Array.from(selected).map(function(i){return transactions[i];});"
    "fetch('/generer',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({transactions:sel,mode:currentMode,company:{name:document.getElementById('company_name').value,address:document.getElementById('company_address').value,siret:document.getElementById('company_siret').value},tva_rate:parseInt(document.getElementById('tva_rate').value)})})"
    ".then(function(r){return r.blob();})"
    ".then(function(blob){"
    "var url=URL.createObjectURL(blob);"
    "var dl=document.getElementById('dlBtn');"
    "dl.href=url;dl.download='factures_'+new Date().toISOString().slice(0,10)+'.zip';"
    "dl.style.display='block';dl.textContent='Telecharger '+selected.size+' facture(s) ZIP';"
    "btn.disabled=false;btn.innerHTML='Generer '+selected.size+' facture(s)';"
    "dl.scrollIntoView({behavior:'smooth'});})"
    ".catch(function(e){showAlert('Erreur: '+e.message);btn.disabled=false;btn.innerHTML='Generer les factures';});}"
    "</script>"
    "</body></html>"
)


@app.route('/')
def index():
    return HTML_PAGE

@app.route('/analyser', methods=['POST'])
def analyser():
    try:
        files = request.files.getlist('files')
        if not files:
            return jsonify({'error': 'Aucun fichier recu'})
        all_transactions = []
        for f in files:
            data = f.read()
            nom  = f.filename.lower()
            txs = lire_pdf(data) if nom.endswith('.pdf') else lire_csv(data)
            for tx in txs:
                if tx['montant'] > 0:
                    all_transactions.append(tx)
        if not all_transactions:
            return jsonify({'error': 'Aucun encaissement trouve dans ces fichiers.'})
        return jsonify({'transactions': all_transactions})
    except Exception as e:
        return jsonify({'error': str(e)})

def generer_facture_groupee(client, txs, numero, company, tva_rate):
    total = sum(t["montant"] for t in txs)
    pdf = FPDF()
    pdf.add_page()
    pdf.set_fill_color(13,13,13)
    pdf.rect(0,0,210,45,"F")
    pdf.set_font("Helvetica","B",20)
    pdf.set_text_color(200,241,53)
    pdf.set_y(10)
    pdf.cell(0,11,"FACTURE",ln=1,align="C")
    pdf.set_font("Helvetica","",8)
    pdf.set_text_color(170,170,170)
    num = "N FACT-"+datetime.now().strftime("%Y%m")+"-"+str(numero).zfill(4)
    d1 = txs[0].get("date","")
    d2 = txs[-1].get("date","")
    periode = d1 if d1==d2 else d1+" au "+d2
    pdf.cell(0,5,num+"   |   "+periode,ln=1,align="C")
    pdf.ln(12)
    pdf.set_text_color(80,80,80); pdf.set_font("Helvetica","B",7)
    pdf.set_x(14); pdf.cell(88,4,"EMETTEUR",ln=0); pdf.cell(88,4,"DESTINATAIRE",ln=1)
    pdf.ln(2)
    pdf.set_font("Helvetica","B",9); pdf.set_text_color(20,20,20)
    pdf.set_x(14); pdf.cell(88,5,str(company.get("name",""))[:45],ln=0); pdf.cell(88,5,str(client)[:45],ln=1)
    pdf.set_font("Helvetica","",8); pdf.set_text_color(100,100,100)
    pdf.set_x(14); pdf.cell(0,5,str(company.get("address","")).replace("\n"," - ")[:60],ln=1)
    pdf.set_x(14); pdf.cell(0,5,"SIRET : "+str(company.get("siret","")),ln=1)
    pdf.ln(5)
    pdf.set_draw_color(200,241,53); pdf.set_line_width(0.6)
    pdf.line(14,pdf.get_y(),196,pdf.get_y()); pdf.ln(5)
    pdf.set_fill_color(13,13,13); pdf.set_text_color(200,241,53); pdf.set_font("Helvetica","B",8)
    pdf.set_x(14)
    pdf.cell(70,8,"DESCRIPTION",0,fill=True)
    pdf.cell(30,8,"DATE",0,align="C",fill=True)
    pdf.cell(28,8,"HT",0,align="R",fill=True)
    pdf.cell(22,8,"TVA",0,align="R",fill=True)
    pdf.cell(28,8,"TTC",0,align="R",fill=True)
    pdf.ln(8)
    tva = tva_rate/100
    for tx in txs:
        mht = round(tx["montant"]/(1+tva),2) if tva>0 else round(tx["montant"],2)
        mttc = round(tx["montant"],2)
        pdf.set_fill_color(248,248,244); pdf.set_text_color(20,20,20); pdf.set_font("Helvetica","",8)
        pdf.set_x(14)
        pdf.cell(70,8,"Prestation de services",0,fill=True)
        pdf.cell(30,8,str(tx.get("date","")),0,align="C",fill=True)
        pdf.cell(28,8,str(mht)+" EUR",0,align="R",fill=True)
        pdf.cell(22,8,str(tva_rate)+"%",0,align="R",fill=True)
        pdf.cell(28,8,str(mttc)+" EUR",0,align="R",fill=True)
        pdf.ln(8)
        if pdf.get_y() > 260:
            pdf.add_page()
    pdf.set_draw_color(220,215,205); pdf.set_line_width(0.3)
    pdf.line(14,pdf.get_y(),196,pdf.get_y()); pdf.ln(4)
    total_ht = round(total/(1+tva),2) if tva>0 else round(total,2)
    total_tva = round(total-total_ht,2)
    total_ttc = round(total,2)
    pdf.set_x(130); pdf.set_font("Helvetica","",8); pdf.set_text_color(130,125,115)
    pdf.cell(36,5,"Sous-total HT",ln=0); pdf.cell(36,5,str(total_ht)+" EUR",align="R",ln=1)
    pdf.set_x(130); pdf.cell(36,5,"TVA "+str(tva_rate)+"%",ln=0); pdf.cell(36,5,str(total_tva)+" EUR",align="R",ln=1)
    pdf.ln(2)
    pdf.set_fill_color(200,241,53); pdf.set_x(120)
    pdf.set_font("Helvetica","B",10); pdf.set_text_color(13,13,13)
    pdf.cell(76,12,"  TOTAL TTC    "+str(total_ttc)+" EUR",align="R",fill=True,ln=1)
    pdf.ln(16)
    pdf.set_font("Helvetica","I",7); pdf.set_text_color(160,155,145); pdf.set_x(14)
    pdf.cell(0,4,"Facture payable sous 30 jours - Merci pour votre confiance.",ln=1)
    return bytes(pdf.output())

@app.route('/generer', methods=['POST'])
def generer():
    data     = request.get_json()
    txs      = data['transactions']
    company  = data['company']
    tva_rate = data.get('tva_rate', 20)
    mode     = data.get('mode', 'individuel')
    zip_buf  = io.BytesIO()
    with zipfile.ZipFile(zip_buf, 'w', zipfile.ZIP_DEFLATED) as zf:
        if mode == 'groupe':
            groupes = {}
            for tx in txs:
                c = tx['client']
                if c not in groupes: groupes[c] = []
                groupes[c].append(tx)
            for i, (client, group_txs) in enumerate(groupes.items(), 1):
                pdf_bytes = generer_facture_groupee(client, group_txs, i, company, tva_rate)
                client_safe = re.sub(r'[^A-Za-z0-9_-]', '_', str(client)[:20])
                fname = "FACT_GROUPE_"+client_safe+"_"+datetime.now().strftime('%Y%m%d')+".pdf"
                zf.writestr(fname, pdf_bytes)
        else:
            for i, tx in enumerate(txs, 1):
                pdf_bytes = generer_facture(tx, i, company, tva_rate)
                client_safe = re.sub(r'[^A-Za-z0-9_-]', '_', str(tx['client'])[:20])
                fname = "FACT_"+client_safe+"_"+datetime.now().strftime('%Y%m%d')+"_"+str(i).zfill(4)+".pdf"
                zf.writestr(fname, pdf_bytes)
    zip_buf.seek(0)
    return send_file(zip_buf, mimetype='application/zip', as_attachment=True, download_name='factures.zip')

if __name__ == '__main__':
    port = int(os.environ.get('PORT', 7860))
    app.run(host='0.0.0.0', port=port, debug=False)