Repository Public MIT Research preview
1"""Rapport des ventes — code hérité, volontairement désordonné (laboratoire S14).23Ce fichier FONCTIONNE : les rapports produits sont ceux que la coopérative utilise. Il est pourtant4pénible à modifier : une fonction très longue, des calculs recopiés, des variables de module modifiées5en cours de route. Votre travail : le remanier sans changer ce qu'il produit.6Interface publique à conserver : produire(chemin, fmt), avec fmt valant "texte" ou "csv".7"""8import os910TAUX = 0.1511TOTAUX = {}12ARTICLES = {}13NB = 0141516def produire(chemin, fmt):17 global NB18 f = open(chemin, encoding="utf-8")19 lignes = f.read().split("\n")20 f.close()21 i = 022 for l in lignes:23 i = i + 124 if i == 1:25 continue26 if l.strip() == "":27 continue28 p = l.split(",")29 if len(p) != 6:30 raise ValueError("ligne %d : 6 champs attendus, %d trouvés" % (i, len(p)))31 try:32 q = int(p[3])33 pu = float(p[4])34 r = float(p[5])35 except ValueError:36 raise ValueError("ligne %d : nombre invalide" % i)37 if q < 0 or pu < 0 or r < 0 or r > 100:38 raise ValueError("ligne %d : valeur hors limites" % i)39 c = p[1].strip().lower()40 m = q * pu * (1 - r / 100)41 if c not in TOTAUX:42 TOTAUX[c] = [0, 0.0]43 TOTAUX[c][0] = TOTAUX[c][0] + q44 TOTAUX[c][1] = TOTAUX[c][1] + m45 a = p[2].strip().lower()46 if a not in ARTICLES:47 ARTICLES[a] = 048 ARTICLES[a] = ARTICLES[a] + q49 NB = NB + 150 if fmt == "texte":51 s = "Coopérative Les Semis - rapport des ventes\n"52 s = s + "Fichier : " + os.path.basename(chemin) + "\n"53 s = s + "Lignes lues : " + str(NB) + "\n\n"54 if NB == 0:55 s = s + "Aucune vente.\n"56 return s57 s = s + "%-14s %8s %11s %9s %11s\n" % ("Catégorie", "Quantité", "Sous-total", "Taxes", "Total")58 tq = 059 ts = 0.060 tt = 0.061 for c in sorted(TOTAUX):62 st = round(TOTAUX[c][1], 2)63 tx = round(st * TAUX, 2)64 tq = tq + TOTAUX[c][0]65 ts = ts + st66 tt = tt + tx67 s = s + "%-14s %8d %11.2f %9.2f %11.2f\n" % (c, TOTAUX[c][0], st, tx, st + tx)68 s = s + "%-14s %8d %11.2f %9.2f %11.2f\n" % ("TOTAL", tq, ts, tt, ts + tt)69 b = ""70 bq = -171 for a in sorted(ARTICLES):72 if ARTICLES[a] > bq:73 b = a74 bq = ARTICLES[a]75 s = s + "\nArticle le plus vendu : " + b + " (" + str(bq) + ")\n"76 return s77 elif fmt == "csv":78 s = "categorie,quantite,sous_total,taxes,total\n"79 tq = 080 ts = 0.081 tt = 0.082 for c in sorted(TOTAUX):83 st = round(TOTAUX[c][1], 2)84 tx = round(st * TAUX, 2)85 tq = tq + TOTAUX[c][0]86 ts = ts + st87 tt = tt + tx88 s = s + "%s,%d,%.2f,%.2f,%.2f\n" % (c, TOTAUX[c][0], st, tx, st + tx)89 s = s + "%s,%d,%.2f,%.2f,%.2f\n" % ("TOTAL", tq, ts, tt, ts + tt)90 return s91 else:92 raise ValueError("format inconnu : " + str(fmt))93