Untitled

 avatar
unknown
python
2 months ago
9.2 kB
3
Indexable
import tkinter as tk
from tkinter import ttk, messagebox
from PIL import Image, ImageTk
import sqlite3
import os
from datetime import datetime

# configure la base de données
def setup_database():
    conn = sqlite3.connect("db.sqlite")
    cursor = conn.cursor()
    
    # crée les tables si elles n'existent pas
    cursor.execute("""
    CREATE TABLE IF NOT EXISTS articles (
        id INTEGER PRIMARY KEY,
        categorie TEXT,
        nom TEXT,
        couleur TEXT,
        tailles TEXT,
        prix REAL,
        quantite INTEGER,
        image_path TEXT
    )
    """)
    
    cursor.execute("""
    CREATE TABLE IF NOT EXISTS commandes (
        id INTEGER PRIMARY KEY,
        nom_client TEXT,
        prenom_client TEXT,
        adresse TEXT,
        telephone TEXT,
        article_id INTEGER,
        quantite INTEGER,
        FOREIGN KEY (article_id) REFERENCES articles (id)
    )
    """)
    
    # si la table des articles est vide, ajoute des articles par défaut
    cursor.execute("SELECT COUNT(*) FROM articles")
    if cursor.fetchone()[0] == 0:
        articles = [
            ("Pulls", "Pull en laine", "blanc cassé", "S,M,L,XL", 49.99, 20, "images/pull_laine.png"),
            ("Pulls", "Pull col V", "Beige", "M,L", 39.99, 15, "images/pull_col_v.png"),
            ("Pantalons", "Jean slim", "bleu ciel", "S,M,L", 59.99, 10, "images/jean_slim.png"),
            ("Pantalons", "Pantalon cargo", "Kaki", "M,L,XL", 69.99, 8, "images/pantalon_cargo.png"),
            ("Tee shirts", "T-shirt uni", "Blanc", "S,M,L,XL", 19.99, 30, "images/tshirt_uni.png"),
            ("Tee shirts", "T-shirt imprimé", "Noir, or", "M,L", 24.99, 25, "images/tshirt_imprime.png")
        ]
        cursor.executemany("""
        INSERT INTO articles (categorie, nom, couleur, tailles, prix, quantite, image_path)
        VALUES (?, ?, ?, ?, ?, ?, ?)
        """, articles)
        conn.commit()
    
    conn.close()

# récupère les articles d'une catégorie
def get_articles_by_category(categorie):
    conn = sqlite3.connect("db.sqlite")
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM articles WHERE categorie = ?", (categorie,))
    articles = cursor.fetchall()
    conn.close()
    return articles

# classe principale de l'application
class BoutiqueApp:
    def __init__(self, root):
        self.root = root
        self.root.title("Flo et Ismaïl")
        
        # crée les onglets pour chaque catégorie
        self.tab_control = ttk.Notebook(root)
        self.tabs = {}
        
        for category in ["Pulls", "Pantalons", "Tee shirts"]:
            tab = ttk.Frame(self.tab_control)
            self.tab_control.add(tab, text=category)
            self.tabs[category] = tab
        
        self.tab_control.pack(expand=1, fill="both")
        
        # affiche les articles pour chaque catégorie
        for category in self.tabs:
            self.display_articles(category, self.tabs[category])
        
        self.create_order_form()
    
    # affiche les articles d'une catégorie
    def display_articles(self, category, frame):
        articles = get_articles_by_category(category)
        for idx, article in enumerate(articles):
            try:
                # charge l'image de l'article
                image = Image.open(article[7])
                image = image.resize((100, 100), Image.LANCZOS)
                photo = ImageTk.PhotoImage(image)
            except Exception as e:
                print(f"{article[2]}: {e}")
                photo = None
            
            if photo:
                image_label = tk.Label(frame, image=photo)
                image_label.image = photo
                image_label.grid(row=idx, column=0, padx=10, pady=5)
            
            # affiche les infos de l'article
            article_label = tk.Label(frame, text=f"{article[2]} - {article[3]} - {article[4]} - {article[5]}€ - Stock: {article[6]}")
            article_label.grid(row=idx, column=1, padx=10, pady=5, sticky="w")
            
            # bouton pour commander
            order_button = tk.Button(frame, text="Commander", command=lambda a=article: self.open_order_form(a))
            order_button.grid(row=idx, column=2, padx=10, pady=5)
    
    # crée le formulaire de commande
    def create_order_form(self):
        self.order_form = tk.Toplevel(self.root)
        self.order_form.title("Commander")
        self.order_form.geometry("400x300")
        self.order_form.withdraw()
        
        # champs pour la commande
        tk.Label(self.order_form, text="Nom:").grid(row=0, column=0, padx=10, pady=5)
        self.nom_entry = tk.Entry(self.order_form)
        self.nom_entry.grid(row=0, column=1, padx=10, pady=5)
        
        tk.Label(self.order_form, text="Prénom:").grid(row=1, column=0, padx=10, pady=5)
        self.prenom_entry = tk.Entry(self.order_form)
        self.prenom_entry.grid(row=1, column=1, padx=10, pady=5)
        
        tk.Label(self.order_form, text="Adresse:").grid(row=2, column=0, padx=10, pady=5)
        self.adresse_entry = tk.Entry(self.order_form)
        self.adresse_entry.grid(row=2, column=1, padx=10, pady=5)
        
        tk.Label(self.order_form, text="Numéro:").grid(row=3, column=0, padx=10, pady=5)
        self.telephone_entry = tk.Entry(self.order_form)
        self.telephone_entry.grid(row=3, column=1, padx=10, pady=5)
        
        tk.Label(self.order_form, text="Quantité:").grid(row=4, column=0, padx=10, pady=5)
        self.quantite_spinbox = tk.Spinbox(self.order_form, from_=1, to=10, width=5)
        self.quantite_spinbox.grid(row=4, column=1, padx=10, pady=5)
        
        self.selected_article = None
        self.confirm_button = tk.Button(self.order_form, text="Confirmer", command=self.submit_order)
        self.confirm_button.grid(row=5, column=0, columnspan=2, pady=20)
    
    # ouvre le formulaire avec l'article sélectionné
    def open_order_form(self, article):
        self.selected_article = article
        self.order_form.deiconify()
    
    # soumet la commande après vérification
    def submit_order(self):
        nom = self.nom_entry.get()
        prenom = self.prenom_entry.get()
        adresse = self.adresse_entry.get()
        telephone = self.telephone_entry.get()
        quantite = int(self.quantite_spinbox.get())
        
        # vérifie les champs
        if not all([nom, prenom, adresse, telephone]):
            messagebox.showerror("Erreur", "Tous les champs doivent être remplis.")
            return
        
        # vérifie le stock
        if self.selected_article[6] < quantite:
            messagebox.showerror("Erreur", "Stock insuffisant.")
            return
        
        # met à jour les données
        self.update_stock_and_orders(nom, prenom, adresse, telephone, quantite)
    
    # met à jour le stock et enregistre la commande
    def update_stock_and_orders(self, nom, prenom, adresse, telephone, quantite):
        conn = sqlite3.connect("db.sqlite")
        cursor = conn.cursor()
        
        cursor.execute("""
        INSERT INTO commandes (nom_client, prenom_client, adresse, telephone, article_id, quantite)
        VALUES (?, ?, ?, ?, ?, ?)
        """, (nom, prenom, adresse, telephone, self.selected_article[0], quantite))
        
        cursor.execute("""
        UPDATE articles SET quantite = quantite - ? WHERE id = ?
        """, (quantite, self.selected_article[0]))
        
        conn.commit()
        conn.close()

        # Génère la facture après la commande
        self.generate_invoice(nom, prenom, adresse, telephone, quantite)
        
        messagebox.showinfo("Merci", "Commande validée !")
        self.order_form.withdraw()

    # Génère une facture et l'enregistre dans un fichier texte
    def generate_invoice(self, nom, prenom, adresse, telephone, quantite):
        article_nom = self.selected_article[2]
        article_prix = self.selected_article[5]
        total = article_prix * quantite

        # Crée un fichier facture
        facture_dir = "factures"
        if not os.path.exists(facture_dir):
            os.makedirs(facture_dir)

        # Nom de la facture (basé sur l'ID de la commande et la date)
        facture_filename = f"factures/facture_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"
        
        with open(facture_filename, "w") as f:
            f.write("Facture de commande\n")
            f.write(f"Date: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n")
            f.write(f"Nom du client: {nom} {prenom}\n")
            f.write(f"Adresse: {adresse}\n")
            f.write(f"Téléphone: {telephone}\n\n")
            f.write(f"Article: {article_nom}\n")
            f.write(f"Quantité: {quantite}\n")
            f.write(f"Prix unitaire: {article_prix}€\n")
            f.write(f"Total: {total}€\n")
        
        messagebox.showinfo("Facture", f"Merci de votre commande, votre facture est disponible dans : {facture_filename}")

if __name__ == "__main__":
    setup_database()  # initialise la base de données
    root = tk.Tk()
    app = BoutiqueApp(root)  # lance l'application
    root.mainloop()
Leave a Comment