Repository Public MIT Research preview
1# Candidat B — rédigé pour le cours ATLAS IA (S14). Ce n'est pas la sortie d'un outil.2# Tâche demandée : remanier boutique/rapport.py sans changer les rapports. Périmètre : boutique/3--- a/boutique/rapport.py4+++ b/boutique/rapport.py5@@ -1,92 +1,79 @@6-"""Rapport des ventes — code hérité, volontairement désordonné (laboratoire S14).7+"""Rapport des ventes — candidat B, rédigé pour le cours ATLAS IA (S14). Ce n'est pas la sortie d'un outil.8 9-Ce fichier FONCTIONNE : les rapports produits sont ceux que la coopérative utilise. Il est pourtant10-pénible à modifier : une fonction très longue, des calculs recopiés, des variables de module modifiées11-en cours de route. Votre travail : le remanier sans changer ce qu'il produit.12-Interface publique à conserver : produire(chemin, fmt), avec fmt valant "texte" ou "csv".13+Remaniement proposé : la longue fonction est découpée, les variables de module ont disparu et le calcul14+est « simplifié » : chaque vente porte son montant et sa taxe, qu'il suffit d'additionner.15+Interface publique inchangée : produire(chemin, fmt), avec fmt valant "texte" ou "csv".16 """17 import os18 19 TAUX = 0.1520-TOTAUX = {}21-ARTICLES = {}22-NB = 023+GABARITS = {"texte": "%-14s %8d %11.2f %9.2f %11.2f\n", "csv": "%s,%d,%.2f,%.2f,%.2f\n"}24+25+26+def analyser(numero, ligne):27+ champs = ligne.split(",")28+ if len(champs) != 6:29+ raise ValueError("ligne %d : 6 champs attendus, %d trouvés" % (numero, len(champs)))30+ try:31+ quantite, prix, rabais = int(champs[3]), float(champs[4]), float(champs[5])32+ except ValueError:33+ raise ValueError("ligne %d : nombre invalide" % numero)34+ if quantite < 0 or prix < 0 or rabais < 0 or rabais > 100:35+ raise ValueError("ligne %d : valeur hors limites" % numero)36+ montant = quantite * prix * (1 - rabais / 100)37+ return champs[1].strip().lower(), champs[2].strip().lower(), quantite, montant, round(montant * TAUX, 2)38+39+40+def lire(chemin):41+ with open(chemin, encoding="utf-8") as fichier:42+ lignes = fichier.read().split("\n")43+ return [analyser(numero, ligne) for numero, ligne in enumerate(lignes, start=1)44+ if numero > 1 and ligne.strip() != ""]45+46+47+def resumer(ventes):48+ lignes, quantite_totale, sous_total_general, taxes_generales = [], 0, 0.0, 0.049+ for categorie in sorted({vente[0] for vente in ventes}):50+ du_rayon = [vente for vente in ventes if vente[0] == categorie]51+ quantite = sum(vente[2] for vente in du_rayon)52+ sous_total = round(sum(vente[3] for vente in du_rayon), 2)53+ taxes = round(sum(vente[4] for vente in du_rayon), 2)54+ quantite_totale += quantite55+ sous_total_general += sous_total56+ taxes_generales += taxes57+ lignes.append((categorie, quantite, sous_total, taxes, sous_total + taxes))58+ lignes.append(("TOTAL", quantite_totale, sous_total_general, taxes_generales,59+ sous_total_general + taxes_generales))60+ return lignes61+62+63+def article_le_plus_vendu(ventes):64+ quantites = {}65+ for vente in ventes:66+ quantites[vente[1]] = quantites.get(vente[1], 0) + vente[2]67+ return min(quantites.items(), key=lambda paire: (-paire[1], paire[0]))68+69+70+def rapport_texte(chemin, ventes):71+ texte = "Coopérative Les Semis - rapport des ventes\n"72+ texte += "Fichier : " + os.path.basename(chemin) + "\n"73+ texte += "Lignes lues : " + str(len(ventes)) + "\n\n"74+ if not ventes:75+ return texte + "Aucune vente.\n"76+ texte += "%-14s %8s %11s %9s %11s\n" % ("Catégorie", "Quantité", "Sous-total", "Taxes", "Total")77+ texte += "".join(GABARITS["texte"] % ligne for ligne in resumer(ventes))78+ article, quantite = article_le_plus_vendu(ventes)79+ return texte + "\nArticle le plus vendu : " + article + " (" + str(quantite) + ")\n"80+81+82+def rapport_csv(ventes):83+ return "categorie,quantite,sous_total,taxes,total\n" + "".join(GABARITS["csv"] % ligne for ligne in resumer(ventes))84 85 86 def produire(chemin, fmt):87- global NB88- f = open(chemin, encoding="utf-8")89- lignes = f.read().split("\n")90- f.close()91- i = 092- for l in lignes:93- i = i + 194- if i == 1:95- continue96- if l.strip() == "":97- continue98- p = l.split(",")99- if len(p) != 6:100- raise ValueError("ligne %d : 6 champs attendus, %d trouvés" % (i, len(p)))101- try:102- q = int(p[3])103- pu = float(p[4])104- r = float(p[5])105- except ValueError:106- raise ValueError("ligne %d : nombre invalide" % i)107- if q < 0 or pu < 0 or r < 0 or r > 100:108- raise ValueError("ligne %d : valeur hors limites" % i)109- c = p[1].strip().lower()110- m = q * pu * (1 - r / 100)111- if c not in TOTAUX:112- TOTAUX[c] = [0, 0.0]113- TOTAUX[c][0] = TOTAUX[c][0] + q114- TOTAUX[c][1] = TOTAUX[c][1] + m115- a = p[2].strip().lower()116- if a not in ARTICLES:117- ARTICLES[a] = 0118- ARTICLES[a] = ARTICLES[a] + q119- NB = NB + 1120+ ventes = lire(chemin)121 if fmt == "texte":122- s = "Coopérative Les Semis - rapport des ventes\n"123- s = s + "Fichier : " + os.path.basename(chemin) + "\n"124- s = s + "Lignes lues : " + str(NB) + "\n\n"125- if NB == 0:126- s = s + "Aucune vente.\n"127- return s128- s = s + "%-14s %8s %11s %9s %11s\n" % ("Catégorie", "Quantité", "Sous-total", "Taxes", "Total")129- tq = 0130- ts = 0.0131- tt = 0.0132- for c in sorted(TOTAUX):133- st = round(TOTAUX[c][1], 2)134- tx = round(st * TAUX, 2)135- tq = tq + TOTAUX[c][0]136- ts = ts + st137- tt = tt + tx138- s = s + "%-14s %8d %11.2f %9.2f %11.2f\n" % (c, TOTAUX[c][0], st, tx, st + tx)139- s = s + "%-14s %8d %11.2f %9.2f %11.2f\n" % ("TOTAL", tq, ts, tt, ts + tt)140- b = ""141- bq = -1142- for a in sorted(ARTICLES):143- if ARTICLES[a] > bq:144- b = a145- bq = ARTICLES[a]146- s = s + "\nArticle le plus vendu : " + b + " (" + str(bq) + ")\n"147- return s148- elif fmt == "csv":149- s = "categorie,quantite,sous_total,taxes,total\n"150- tq = 0151- ts = 0.0152- tt = 0.0153- for c in sorted(TOTAUX):154- st = round(TOTAUX[c][1], 2)155- tx = round(st * TAUX, 2)156- tq = tq + TOTAUX[c][0]157- ts = ts + st158- tt = tt + tx159- s = s + "%s,%d,%.2f,%.2f,%.2f\n" % (c, TOTAUX[c][0], st, tx, st + tx)160- s = s + "%s,%d,%.2f,%.2f,%.2f\n" % ("TOTAL", tq, ts, tt, ts + tt)161- return s162- else:163- raise ValueError("format inconnu : " + str(fmt))164+ return rapport_texte(chemin, ventes)165+ if fmt == "csv":166+ return rapport_csv(ventes)167+ raise ValueError("format inconnu : " + str(fmt))168