The provided Python code defines a basic inventory management system....

May 18, 2025 at 11:44 AM

from datetime import datetime import write def add_product(products, filename, product_name): print(f"\n=== Add New Product: {product_name} ===") # Use the provided product name if any(p['name'].lower() == product_name.lower() for p in products): print(f"Product '{product_name}' already exists in inventory.") return False brand = input("Enter brand name: ").strip() if not brand: print("Brand name required and cannot be empty.") return False country = input("Enter country of origin: ").strip() if not country: print("Country is required and cannot be empty.") return False try: quantity = int(input("Enter initial quantity: ")) if quantity < 0: print("Quantity must be a non-negative number.") return False cost_price = float(input("Enter cost price: ")) if cost_price < 0: print("Cost price must be a non-negative number.") return False except ValueError: print("Invalid input. Please enter valid numbers for quantity and cost price.") return False new_product = { 'name': product_name, 'brand': brand, 'quantity': quantity, 'cost_price': cost_price, 'country': country } products.append(new_product) write_to_file(filename, products) print(f"Product '{product_name}' successfully added to stock.") return True def write_to_file(filename, products): try: with open(filename, 'w') as file: for product in products: line = f"{product['name']},{product['brand']},{product['quantity']},{product['cost_price']},{product['country']}\n" file.write(line) print(f"{filename} has been successfully updated.") except PermissionError: print(f"Error: Permission denied when writing to {filename}.") except Exception as e: print(f"Error writing to file: {e}") def process_transaction(products, filename): if not products: print("No products available for transactions at the moment.") return customer_name = input("Enter customer name: ").strip() if not customer_name: print("Customer name is required and cannot be left blank.") return transaction = [] while True: write.display_products(products) product_name = input("Enter product name (or 'done' to finish): ").strip() if product_name.lower() == 'done': break product = next((p for p in products if p['name'].lower() == product_name.lower()), None) if not product: print(f"Sorry, the product '{product_name}' is not in stock.") add_choice = input("Do you want to add this product to the Stock? (yes/no): ").strip().lower() if add_choice == 'yes': if add_product(products, filename, product_name): # Refresh product reference after adding product = next((p for p in products if p['name'].lower() == product_name.lower()), None) else: continue else: continue try: qty = int(input(f"Enter quantity to purchase for {product['name']}: ")) if qty <= 0: print("Please enter a valid positive quantity.") continue free_items = qty // 3 # Buy 3 get 1 free total_items = qty + free_items if total_items > product['quantity']: print(f"We currently have insufficient stock for {product['name']}. Available: {product['quantity']}, Requested: {total_items}.") continue try: selling_price = product['cost_price'] * 2 except KeyError as e: print(f"Error: Missing key {e} in product data.") continue transaction.append({ 'product': product, 'qty_purchased': qty, 'free_items': free_items, 'VAT': 0.13 * (qty * selling_price), 'total_cost': qty * selling_price + 0.13 * (qty * selling_price) }) except ValueError: print("Invalid input. Please provide a numeric value for quantity.") continue if not transaction: print("No items were purchased during this transaction.") return for item in transaction: product = item['product'] product['quantity'] -= (item['qty_purchased'] + item['free_items']) timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") invoice_filename = f"invoice_{timestamp}.txt" total_amount = sum(item['total_cost'] for item in transaction) try: with open(invoice_filename, 'w') as file: file.write("=== Sales Invoice ===\n") file.write(f"Customer: {customer_name}\n") file.write(f"Date: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n") file.write("-" * 40 + "\n") file.write(f"{'Product':<20} {'Brand':<15} {'Qty':<10} {'Free':<10} {'VAT': <8} {'Cost':<15}\n") file.write("-" * 40 + "\n") for item in transaction: product = item['product'] file.write(f"{product['name']:<20} {product['brand']:<15} {item['qty_purchased']:<10} {item['free_items']:<10} {item['VAT']:<8} {item['total_cost']:<15.2f}\n") file.write("-" * 40 + "\n") file.write(f"Total Amount: {total_amount:.2f}\n") print(f"Invoice successfully created: {invoice_filename}") except Exception as e: print(f"Error generating invoice: {e}") write_to_file(filename, products) def restock_products(products, filename): if not products: print("No products are available for restocking.") return supplier_name = input("Enter supplier name: ").strip() if not supplier_name: print("Supplier name is mandatory and cannot be empty.") return write.display_products(products) product_name = input("Enter product name to restock: ").strip() product = next((p for p in products if p['name'].lower() == product_name.lower()), None) if not product: print(f"The product '{product_name}' could not be located in the inventory.") return try: qty = int(input(f"Enter quantity to restock for {product['name']}: ")) if qty <= 0: print("Please enter a valid positive number for the quantity.") return cost_price = float(input(f"Enter new cost price for {product['name']} (current: {product['cost_price']}): ")) if cost_price < 0: print("Cost price must be a non-negative value.") return except ValueError: print("Invalid input. Please enter valid numbers.") return product['quantity'] += qty product['cost_price'] = cost_price timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") invoice_filename = f"restock_{timestamp}.txt" total_amount = qty * cost_price try: with open(invoice_filename, 'w') as file: file.write("=== Restock Invoice ===\n") file.write(f"Supplier: {supplier_name}\n") file.write(f"Date: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n") file.write("-" * 40 + "\n") file.write(f"{'Product':<20} {'Brand':<15} {'Qty':<10} {'Cost':<15}\n") file.write("-" * 40 + "\n") file.write(f"{product['name']:<20} {product['brand']:<15} {qty:<10} {total_amount:<15.2f}\n") file.write("-" * 40 + "\n") file.write(f"Total Amount: {total_amount:.2f}\n") print(f"Restock invoice successfully created: {invoice_filename}") except Exception as e: print(f"Error generating restock invoice: {e}") write_to_file(filename, products)

The provided Python code defines a basic inventory management system. Here's what each part of the code does:


add_product(products, filename, product_name)

This function adds a new product to the inventory.

  1. Checks if the product already exists: Searches the products list for a product with a matching name (case-insensitive).
  2. Prompts for information: If the product doesn't already exist, the user is prompted to enter details like brand, country of origin, initial quantity, and cost price. Validation ensures inputs are non-empty and numeric values are valid.
  3. Adds the product to the inventory: The new product, structured as a dictionary, is appended to the products list.
  4. Writes the updated inventory to file: The write_to_file function is called to save the updated products list to the specified file.

write_to_file(filename, products)

This function writes the current state of the inventory (products list) to a file in CSV format.

  • Each product is saved as a line with its properties (name, brand, quantity, cost_price, and country).
  • Includes error handling for issues such as permission errors or other unexpected exceptions during file writing.

process_transaction(products, filename)

This function handles customer transactions (purchasing products).

  1. Validates inventory and customer input: Ensures the product list is not empty and prompts for the customer's name.
  2. Handles product selection and purchase: For each product the customer wants to buy:
    • Finds the product in the inventory (or prompts to add it if it doesn't exist).
    • Validates quantities (checks stock availability) and calculates the free items (based on a "Buy 3, Get 1 Free" promotion).
    • Calculates the selling price, VAT (13%), and total cost.
    • Records the transaction if everything is valid.
  3. Deducts purchased quantities from stock: Updates the products list.
  4. Generates an invoice: Creates a text file with the transaction details, including the purchased products, their quantities, VAT, and the total price.
  5. Updates inventory file: Writes the updated inventory back to the file.

restock_products(products, filename)

This function restocks an existing product in the inventory.

  1. Validates existing products: Ensures the inventory is not empty and the supplied product exists.
  2. Prompts for supplier information: The user enters the supplier name, restock quantity, and updated cost price. Validation is performed for numerical inputs and non-negative values.
  3. Updates the selected product: Adds the restocked quantity to the product and updates its cost price.
  4. Generates a restock invoice: Saves the restock details to a file (including supplier name, product details, and total cost).
  5. Updates inventory file: Saves the modified inventory list to the file.

Supporting Functionalities:

  1. Error Handling: The code handles errors like invalid inputs, missing keys in product data, file access permissions, or unexpected exceptions during file I/O.
  2. Integration with write Module: The code references the write module to access functions like display_products, which lists the inventory items for user interaction.

Key Observed Behaviors:

  • Buy 3, Get 1 Free Promotion: Ensures customers receive a free product for every 3 purchased, but only if there is sufficient stock (total calculated items, purchased plus free, must not exceed inventory quantity).
  • Invoice and Restock File Generation: The application creates transaction logs in a timestamped file for reference or bookkeeping.
  • Real-Time Inventory Update: Modifies the shared products list to reflect transactions or restocking immediately.

The code provides a basic framework for managing a stock inventory system with functionalities for adding products, processing transactions (with a promotion), and restocking items.

Generate your own explanations
Download our vscode extension
Read other generated explanations

Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node