File size: 15,936 Bytes
8845c50
 
 
3ea04f7
8845c50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4403c66
 
 
 
 
 
 
 
 
 
 
 
 
 
8845c50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ea04f7
8845c50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4403c66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f97338f
 
 
4403c66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f97338f
4403c66
 
 
 
 
 
 
 
 
 
 
 
072146d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8845c50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ea04f7
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
"""
Écriture des fichiers CSV au format EBP Gestion Commerciale.
Format de référence : CAMENGO import ebp 2026.csv

Colonnes articles :
  Nom de dessin ; Référence ; Collection ; Prix d'achat HT par ml ;
  Prix conseillé HT par ml ; Remise ; Unité ; Fournisseur ;
  Code fournisseur ; Code famille

Règles : sep=";", encoding="utf-8-sig", décimales en virgule française,
         pas de symbole €/%, fin de ligne \\r\\n.
Produit 3 fichiers numérotés dans l'ordre d'import EBP.
"""
from __future__ import annotations

import csv
import os
from pathlib import Path


# ── Colonnes EBP (format de référence CAMENGO) ───────────────────────────────

COLS_ARTICLES = [
    "Nom de dessin",
    "Référence",
    "Collection",
    "Prix d'achat HT par ml",
    "Prix conseillé HT par ml",
    "Remise",
    "Unité",
    "Fournisseur",
    "Code fournisseur",
    "Code famille",
]

COLS_FAMILLES = [
    "Code famille", "Libellé", "Code TVA",
    "Coefficient de marge", "Compte comptable vente", "Compte comptable achat",
]

COLS_FOURNISSEUR = [
    "Code fournisseur", "Nom", "Adresse", "Code postal", "Ville", "Pays",
    "Téléphone", "Email", "Famille fournisseur", "Conditions de règlement",
]

# ── Colonnes article EBP (écran « Articles » — capture utilisateur) ──────────
# Mapping FIXE, aligné exactement sur l'écran EBP fourni. Ordre verrouillé.
COLS_ARTICLES_EBP = [
    "Code article",
    "Libellé",
    "PV HT public conseillé",
    "PV TTC",
    "Code unité",
    "Prix d'achat",
    "Montant de TVA",
    "Code fournisseur",
    "Code sous-famille article",
]


# ── Helpers ──────────────────────────────────────────────────────────────────

def _fmt_decimal(value) -> str:
    """Float ou string → virgule française, sans symbole monétaire ou %."""
    if value is None or value == "":
        return ""
    try:
        f = float(str(value).replace(",", ".").replace("€", "").replace("%", "").strip())
        return f"{f:.2f}".replace(".", ",")
    except (ValueError, TypeError):
        return ""


def _fmt_remise(value) -> str:
    """Remise : entier ou float, sans symbole %."""
    if value is None or value == "":
        return ""
    try:
        f = float(str(value).replace("%", "").replace(",", ".").strip())
        return str(int(f)) if f == int(f) else f"{f:.2f}".replace(".", ",")
    except (ValueError, TypeError):
        return ""


def _truncate(text: str, max_len: int = 80) -> str:
    text = str(text or "").strip()
    return text[:max_len] if len(text) > max_len else text


def _write_csv(rows: list[dict], columns: list[str], path: str) -> None:
    with open(path, "w", newline="", encoding="utf-8-sig") as f:
        w = csv.DictWriter(f, fieldnames=columns, delimiter=";",
                           extrasaction="ignore", lineterminator="\r\n")
        w.writeheader()
        for row in rows:
            w.writerow(row)


# ── Calcul prix ──────────────────────────────────────────────────────────────

def prix_achat_from_conseille(prix_conseille_ht: float, remise: float) -> float:
    """Prix achat HT = prix_conseillé_HT × (1 - remise/100). Arrondi 2 décimales."""
    if prix_conseille_ht <= 0:
        return 0.0
    return round(prix_conseille_ht * (1 - remise / 100), 2)


def prix_ht_from_ttc(prix_ttc: float, taux_tva: float = 20.0) -> float:
    """PV HT = prix_TTC / (1 + taux_TVA/100). Utilisé si le catalogue affiche des prix TTC."""
    if prix_ttc <= 0:
        return 0.0
    return round(prix_ttc / (1 + taux_tva / 100), 2)


# ── Export principal ──────────────────────────────────────────────────────────

def export_ebp(
    articles: list[dict],
    output_dir: str,
    fournisseur_nom: str,
    fournisseur_code: str,
    remise: float = 45.0,
    unite_defaut: str = "ml",
    code_famille: str = "FFR00001",
    code_tva: str = "TVA20",
    prix_sont_ttc: bool = False,
    taux_tva: float = 20.0,
    collection_famille_map: dict | None = None,
) -> dict[str, str]:
    """
    Génère les 3 fichiers EBP dans output_dir.
    Retourne un dict {nom_fichier: chemin_absolu}.

    Chaque article doit avoir :
      - nom_dessin       : str
      - reference        : str
      - collection       : str  (→ Collection, sert aussi à déduire la famille)
      - prix_conseille   : float (prix conseillé HT, ou TTC si prix_sont_ttc=True)
      - remise_specifique: float|None (si différente de la remise globale)
      - unite            : str|None

    collection_famille_map : dict optionnel {nom_collection: code_famille_ebp}
      Si fourni, le code famille de chaque article est résolu depuis sa collection.
      Exemple : {"CHOREGRAPHIE": "TIS-DEC", "PIUMA": "TIS-VEL"}
    """
    os.makedirs(output_dir, exist_ok=True)

    # ── 1. Familles ───────────────────────────────────────────────────────────
    # Les collections deviennent des familles (on les regroupe par code famille)
    # Le code famille est unique par fournisseur (ex: FFR00001)
    familles_rows = [{
        "Code famille":             code_famille,
        "Libellé":                  fournisseur_nom,
        "Code TVA":                 code_tva,
        "Coefficient de marge":     "",
        "Compte comptable vente":   "",
        "Compte comptable achat":   "",
    }]
    path_familles = os.path.join(output_dir, "1_familles_articles.csv")
    _write_csv(familles_rows, COLS_FAMILLES, path_familles)

    # ── 2. Fournisseur ────────────────────────────────────────────────────────
    fournisseur_row = [{
        "Code fournisseur":     fournisseur_code,
        "Nom":                  fournisseur_nom,
        "Adresse":              "",
        "Code postal":          "",
        "Ville":                "",
        "Pays":                 "",
        "Téléphone":            "",
        "Email":                "",
        "Famille fournisseur":  "",
        "Conditions de règlement": "",
    }]
    path_fournisseur = os.path.join(output_dir, "2_fournisseur.csv")
    _write_csv(fournisseur_row, COLS_FOURNISSEUR, path_fournisseur)

    # ── 3. Articles ───────────────────────────────────────────────────────────
    articles_rows = []
    for a in articles:
        nom       = _truncate(a.get("nom_dessin") or a.get("libelle") or "", 80)
        ref       = str(a.get("reference") or a.get("code") or "").strip()
        collection = _truncate(a.get("collection") or a.get("famille_suggeree") or "", 80)
        unite_art  = str(a.get("unite") or unite_defaut).strip()
        remise_art = float(a.get("remise_specifique") or remise)

        # Prix conseillé HT
        prix_brut_val = float(a.get("prix_conseille") or a.get("prix_ttc") or 0)
        if prix_sont_ttc and prix_brut_val > 0:
            prix_conseille_ht = prix_ht_from_ttc(prix_brut_val, taux_tva)
        else:
            prix_conseille_ht = prix_brut_val

        # Prix achat HT calculé depuis le conseillé et la remise
        prix_achat_ht = prix_achat_from_conseille(prix_conseille_ht, remise_art)

        # Code famille : résolu depuis le mapping collection si disponible
        famille_art = code_famille
        if collection_famille_map and collection:
            famille_art = collection_famille_map.get(collection, code_famille)

        articles_rows.append({
            "Nom de dessin":            nom,
            "Référence":                ref,
            "Collection":               collection,
            "Prix d'achat HT par ml":   _fmt_decimal(prix_achat_ht) if prix_achat_ht else "",
            "Prix conseillé HT par ml": _fmt_decimal(prix_conseille_ht) if prix_conseille_ht else "",
            "Remise":                   _fmt_remise(remise_art),
            "Unité":                    unite_art,
            "Fournisseur":              fournisseur_nom,
            "Code fournisseur":         fournisseur_code,
            "Code famille":             famille_art,
        })

    path_articles = os.path.join(output_dir, "3_articles.csv")
    _write_csv(articles_rows, COLS_ARTICLES, path_articles)

    return {
        "1_familles_articles.csv": path_familles,
        "2_fournisseur.csv":       path_fournisseur,
        "3_articles.csv":          path_articles,
    }


def _prix_ttc_from_ht(prix_ht: float, taux_tva: float) -> float:
    if prix_ht <= 0:
        return 0.0
    return round(prix_ht * (1 + taux_tva / 100), 2)


def _safe_filename(name: str) -> str:
    return "".join(c if c.isalnum() or c in "-_" else "_" for c in str(name)).strip("_") or "DIVERS"


def _build_article_ebp_row(
    a: dict,
    fournisseur_code: str,
    remise: float,
    code_tva: str,
    taux_tva: float,
    prix_sont_ttc: bool,
) -> dict:
    """Construit une ligne au format écran « Articles » EBP."""
    ref        = str(a.get("reference") or a.get("code") or "").strip()
    libelle    = _truncate(a.get("nom_dessin") or a.get("libelle") or "", 80)
    # Unité prise telle quelle dans la source, jamais imposée ni uniformisée.
    # Chaque référence garde sa propre unité ; vide si la source n'en donne pas.
    unite_art  = str(a.get("unite") or "").strip()
    remise_art = float(a.get("remise_specifique") or remise)
    famille    = str(a.get("code_sous_famille") or "").strip()

    prix_brut_val = float(a.get("prix_conseille") or a.get("prix_ttc") or 0)
    if prix_sont_ttc and prix_brut_val > 0:
        prix_ht = prix_ht_from_ttc(prix_brut_val, taux_tva)
    else:
        prix_ht = prix_brut_val

    prix_ttc   = _prix_ttc_from_ht(prix_ht, taux_tva)
    prix_achat = prix_achat_from_conseille(prix_ht, remise_art)

    return {
        "Code article":             ref,
        "Libellé":                  libelle,
        "PV HT public conseillé":   _fmt_decimal(prix_ht) if prix_ht else "",
        "PV TTC":                   _fmt_decimal(prix_ttc) if prix_ttc else "",
        "Code unité":               unite_art,
        "Prix d'achat":             _fmt_decimal(prix_achat) if prix_achat else "",
        "Montant de TVA":           code_tva,
        "Code fournisseur":         fournisseur_code,
        "Code sous-famille article": famille,
    }


def export_articles_par_famille(
    articles: list[dict],
    output_dir: str,
    fournisseur_code: str,
    remise: float = 45.0,
    code_tva: str = "TVA20",
    taux_tva: float = 20.0,
    prix_sont_ttc: bool = False,
) -> dict[str, str]:
    """
    Export EBP « écran Articles » : 1 fichier CSV par famille (code_sous_famille).

    Chaque article doit avoir été annoté au préalable par
    core.subfamily.analyse_sous_familles (clé `code_sous_famille`).

    Nommage : articles_<FAMILLE>.csv. Retourne {nom_fichier: chemin_absolu}.
    """
    os.makedirs(output_dir, exist_ok=True)

    from collections import defaultdict
    groupes: dict[str, list[dict]] = defaultdict(list)
    for a in articles:
        famille = str(a.get("code_sous_famille") or "DIVERS").strip() or "DIVERS"
        groupes[famille].append(a)

    produits: dict[str, str] = {}
    for famille in sorted(groupes):
        rows = [
            _build_article_ebp_row(
                a, fournisseur_code, remise,
                code_tva, taux_tva, prix_sont_ttc,
            )
            for a in groupes[famille]
        ]
        fname = f"articles_{_safe_filename(famille)}.csv"
        path = os.path.join(output_dir, fname)
        _write_csv(rows, COLS_ARTICLES_EBP, path)
        produits[fname] = path

    return produits


COL_TAUX_MARGE = "Taux de marge"
COLS_ARTICLES_EBP_MARGE = COLS_ARTICLES_EBP + [COL_TAUX_MARGE]


def build_ebp_row_marge(
    a: dict,
    fournisseur_code: str,
    taux_tva: float = 20.0,
    code_tva: str = "TVA20",
) -> dict:
    """
    Ligne EBP « écran Articles » + colonne « Taux de marge ».

    Utilise le prix d'achat (a['prix_achat']) ET le prix de vente
    (a['prix_conseille']), tous deux HT, sans remise. Unité telle quelle.
    Taux de marge = (PV − PA) / PV × 100.
    """
    ref     = str(a.get("reference") or a.get("code") or "").strip()
    libelle = _truncate(a.get("nom_dessin") or a.get("libelle") or "", 80)
    unite   = str(a.get("unite") or "").strip()
    famille = str(a.get("code_sous_famille") or "").strip()

    pv = float(a.get("prix_conseille") or 0)   # prix de vente HT
    pa = float(a.get("prix_achat") or 0)       # prix d'achat HT

    pv_ttc = round(pv * (1 + taux_tva / 100), 2) if pv else 0.0
    marge  = round((pv - pa) / pv * 100, 2) if pv else None

    return {
        "Code article":              ref,
        "Libellé":                   libelle,
        "PV HT public conseillé":    _fmt_decimal(pv) if pv else "",
        "PV TTC":                    _fmt_decimal(pv_ttc) if pv_ttc else "",
        "Code unité":                unite,
        "Prix d'achat":              _fmt_decimal(pa) if pa else "",
        "Montant de TVA":            code_tva,
        "Code fournisseur":          fournisseur_code,
        "Code sous-famille article": famille,
        COL_TAUX_MARGE:              _fmt_decimal(marge) if marge is not None else "",
    }


def export_articles_par_zone(
    articles: list[dict],
    output_dir: str,
    fournisseur_code: str,
    taux_tva: float = 20.0,
    code_tva: str = "TVA20",
) -> dict[str, str]:
    """
    Export EBP « écran Articles » + Taux de marge, 1 fichier CSV par ZONE
    (regroupement sur `code_sous_famille`, qui porte le libellé de la zone).

    Nommage : zone_NN_<label>.csv. Retourne {nom_fichier: chemin}.
    """
    os.makedirs(output_dir, exist_ok=True)

    from collections import defaultdict
    groupes: dict[str, list[dict]] = defaultdict(list)
    for a in articles:
        zone = str(a.get("code_sous_famille") or "ZONE").strip() or "ZONE"
        groupes[zone].append(a)

    produced: dict[str, str] = {}
    for i, zone in enumerate(sorted(groupes), 1):
        rows = [
            build_ebp_row_marge(a, fournisseur_code, taux_tva, code_tva)
            for a in groupes[zone]
        ]
        fname = f"zone_{i:02d}_{_safe_filename(zone)}.csv"
        path = os.path.join(output_dir, fname)
        _write_csv(rows, COLS_ARTICLES_EBP_MARGE, path)
        produced[fname] = path
    return produced


def _make_famille_code(libelle: str) -> str:
    cleaned = "".join(c for c in libelle.upper() if c.isalpha() or c.isspace())
    words = cleaned.split()
    if not words:
        return "DIV"
    if len(words) == 1:
        return words[0][:6]
    return "".join(w[0] for w in words[:6])


# ── Compatibilité ancienne API (app.py) ───────────────────────────────────────

def to_csv(articles: list[dict], output_path: str, brand: str = "") -> str:
    """Ancienne signature conservée pour compatibilité."""
    out_dir = os.path.dirname(output_path) or "."
    files = export_ebp(
        articles,
        output_dir=out_dir,
        fournisseur_nom=brand,
        fournisseur_code=brand[:8].upper().replace(" ", "") or "FOUR001",
    )
    import shutil
    shutil.copy(files["3_articles.csv"], output_path)
    return output_path