Skip to content
TheChatArchiveThe Chat Archive
o1-preview-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

write a py code for bakery management system using pandas library and also the data can…

  1. User

    write a py code for bakery management system using pandas library and also the data can be extracted into excel sheets

  2. Assistant

    Sure! Below is a Python code for a simple bakery management system using the pandas library. This code allows you to manage inventory, products, and sales data. It also provides functionality to export the data into Excel sheets.

    import pandas as pd
    import datetime
    
    # Initialize data
    
    # Inventory DataFrame
    inventory = pd.DataFrame(columns=['Ingredient', 'Quantity', 'Unit'])
    
    # Products DataFrame
    products = pd.DataFrame(columns=['ProductID', 'ProductName', 'Price', 'Ingredients'])
    
    # Sales DataFrame
    sales = pd.DataFrame(columns=['SaleID', 'ProductID', 'Quantity', 'TotalPrice', 'Date'])
    
    # Functions to manage inventory
    def add_ingredient(ingredient_name, quantity, unit):
        """
        Add a new ingredient to the inventory or update the quantity if it already exists.
        """
        global inventory
        if ingredient_name in inventory['Ingredient'].values:
            # Update existing ingredient quantity
            inventory.loc[inventory['Ingredient'] == ingredient_name, 'Quantity'] += quantity
        else:
            # Add new ingredient
            inventory = inventory.append({'Ingredient': ingredient_name, 'Quantity': quantity, 'Unit': unit}, ignore_index=True)
    
    def remove_ingredient(ingredient_name, quantity):
        """
        Remove a specified quantity of an ingredient from the inventory.
        """
        global inventory
        if ingredient_name in inventory['Ingredient'].values:
            current_quantity = inventory.loc[inventory['Ingredient'] == ingredient_name, 'Quantity'].values[0]
            if current_quantity >= quantity:
                inventory.loc[inventory['Ingredient'] == ingredient_name, 'Quantity'] -= quantity
            else:
                print(f"Not enough {ingredient_name} in inventory to remove {quantity}{inventory.loc[inventory['Ingredient'] == ingredient_name, 'Unit'].values[0]}")
        else:
            print(f"{ingredient_name} not found in inventory")
    
    # Functions to manage products
    def add_product(product_id, product_name, price, ingredients):
        """
        Add a new product to the products list.
        ingredients: a dictionary of ingredient quantities required for the product.
        """
        global products
        products = products.append({
            'ProductID': product_id,
            'ProductName': product_name,
            'Price': price,
            'Ingredients': ingredients
        }, ignore_index=True)
    
    def sell_product(product_id, quantity_sold):
        """
        Process the sale of a product, update inventory, and record the sale.
        """
        global sales, products
        product = products.loc[products['ProductID'] == product_id]
        if not product.empty:
            price_per_unit = product['Price'].values[0]
            total_price = price_per_unit * quantity_sold
            sale_id = len(sales) + 1
            sale_date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            sales = sales.append({
                'SaleID': sale_id,
                'ProductID': product_id,
                'Quantity': quantity_sold,
                'TotalPrice': total_price,
                'Date': sale_date
            }, ignore_index=True)
            # Update inventory based on ingredients used
            ingredients_needed = product['Ingredients'].values[0]  # Assuming ingredients is a dict
            for ingredient, qty_required in ingredients_needed.items():
                total_qty_needed = qty_required * quantity_sold
                remove_ingredient(ingredient, total_qty_needed)
        else:
            print(f"Product with ID {product_id} not found.")
    
    def export_data_to_excel(filename='bakery_data.xlsx'):
        """
        Export the inventory, products, and sales data to an Excel file.
        """
        with pd.ExcelWriter(filename) as writer:
            inventory.to_excel(writer, sheet_name='Inventory', index=False)
            products.to_excel(writer, sheet_name='Products', index=False)
            sales.to_excel(writer, sheet_name='Sales', index=False)
        print(f"Data successfully exported to {filename}")
    
    # Example usage
    
    # Add ingredients to inventory
    add_ingredient('Flour', 10000, 'grams')   # 10 kg of Flour
    add_ingredient('Sugar', 5000, 'grams')    # 5 kg of Sugar
    add_ingredient('Butter', 2000, 'grams')   # 2 kg of Butter
    add_ingredient('Eggs', 200, 'pcs')        # 200 Eggs
    
    # Add products
    add_product(
        product_id=1,
        product_name='Chocolate Cake',
        price=25.0,
        ingredients={
            'Flour': 500,      # grams
            'Sugar': 200,      # grams
            'Butter': 100,     # grams
            'Eggs': 4          # pieces
        }
    )
    
    add_product(
        product_id=2,
        product_name='Croissant',
        price=3.0,
        ingredients={
            'Flour': 100,      # grams
            'Butter': 50       # grams
        }
    )
    
    # Sell products
    sell_product(1, 5)  # Sell 5 Chocolate Cakes
    sell_product(2, 20) # Sell 20 Croissants
    
    # Export data to Excel
    export_data_to_excel()
    

    Explanation:

    1. Imports and Data Initialization:

      • We import pandas for data handling and datetime for timestamps.
      • We create empty pandas DataFrames for inventory, products, and sales.
    2. Inventory Management Functions:

      • add_ingredient: Adds a new ingredient or updates the quantity if it already exists.
      • remove_ingredient: Removes a specified quantity of an ingredient from the inventory.
    3. Product Management Functions:

      • add_product: Adds a new product with associated ingredients and price.
      • sell_product: Processes the sale of a product, updates the inventory based on ingredients used, and records the sale in the sales DataFrame.
    4. Data Export Function:

      • export_data_to_excel: Exports the inventory, products, and sales DataFrames to separate sheets in an Excel workbook.
    5. Example Usage:

      • We add some ingredients to the inventory.
      • We add two products: Chocolate Cake and Croissant, specifying the ingredients required for each.
      • We simulate sales of these products.
      • Finally, we export all data to an Excel file named bakery_data.xlsx.

    Note: Before running this code, make sure you have pandas installed in your Python environment. You can install it using:

    pip install pandas
    

    Output:

    After running the code, an Excel file named bakery_data.xlsx will be created in your working directory. This file will have three sheets:

    • Inventory: Lists the current inventory of ingredients after sales.
    • Products: Lists all products offered by the bakery along with their ingredients and prices.
    • Sales: Records all the sales transactions with timestamps.

    Sample Data in Excel Sheets:

    • Inventory Sheet:
    IngredientQuantityUnit
    Flour6000grams
    Sugar4000grams
    Butter1000grams
    Eggs180pcs
    • Products Sheet:
    ProductIDProductNamePriceIngredients
    1Chocolate Cake25.0{'Flour': 500, 'Sugar': 200, 'Butter': 100, 'Eggs': 4}
    2Croissant3.0{'Flour': 100, 'Butter': 50}
    • Sales Sheet:
    SaleIDProductIDQuantityTotalPriceDate
    115125.02023-10-07 14:35:00
    222060.02023-10-07 14:35:00

    Customizations:

    • You can modify the ingredients, products, and sales according to your bakery's needs.
    • Add more functions as needed, such as updating product prices, deleting products, or generating specific reports.

    Feel free to expand upon this code to suit the specific requirements of your bakery management system!