i'll share with u the main.py script, i have 3 more scripts, i want to adjust the ingredients reading and adding method to be loaded once from excel, and stored then in the database, i have 3 other scripts, database_helpers, database_setup and unit_conversion, the excel file will have 4 columns, A sap code, 2 material description, 3 balance, 4 UoM. here's the code:
main.py
import sys
import os
import logging
import sqlite3 # Make sure to import sqlite3
from PyQt5.QtWidgets import (
QApplication, QWidget, QTabWidget, QVBoxLayout, QPushButton,
QLabel, QLineEdit, QMessageBox, QHBoxLayout, QListWidget, QFormLayout,
QComboBox, QSpinBox, QFileDialog, QDateEdit, QTableWidget, QTableWidgetItem,
QInputDialog
)
from PyQt5.QtCore import Qt, QDate
Import your database helpers and unit conversion functions
def get_base_path():
if getattr(sys, 'frozen', False):
# Running as a PyInstaller bundle
return sys._MEIPASS
else:
# Running as a script
return os.path.dirname(os.path.abspath(file))
def init_ui(self):
# Title
title = QLabel("Ingredients Management")
title.setAlignment(Qt.AlignCenter)
title.setStyleSheet("font-size: 18px; font-weight: bold;")
self.layout.addWidget(title)
# Ingredients List
self.ingredients_list = QListWidget()
self.refresh_ingredients()
self.layout.addWidget(self.ingredients_list)
# Buttons
buttons_layout = QHBoxLayout()
add_btn = QPushButton("Add Ingredient")
edit_btn = QPushButton("Edit Ingredient")
delete_btn = QPushButton("Delete Ingredient")
buttons_layout.addWidget(add_btn)
buttons_layout.addWidget(edit_btn)
buttons_layout.addWidget(delete_btn)
self.layout.addLayout(buttons_layout)
# Connect buttons
add_btn.clicked.connect(self.add_ingredient)
edit_btn.clicked.connect(self.edit_ingredient)
delete_btn.clicked.connect(self.delete_ingredient)
def refresh_ingredients(self):
self.ingredients_list.clear()
ingredients = get_all_ingredients()
for ing in ingredients:
self.ingredients_list.addItem(f"{ing[1]} ({ing[2]})")
def add_ingredient(self):
dialog = IngredientDialog()
if dialog.exec_():
name, uom = dialog.get_data()
try:
add_ingredient(name, uom)
self.refresh_ingredients()
except Exception as e:
QMessageBox.critical(self, "Error", str(e))
def edit_ingredient(self):
selected_item = self.ingredients_list.currentItem()
if not selected_item:
QMessageBox.warning(self, "Warning", "Please select an ingredient to edit.")
return
text = selected_item.text()
name = text.split(' (')[0]
ingredient_id = get_ingredient_id(name)
if not ingredient_id:
QMessageBox.warning(self, "Warning", "Selected ingredient not found.")
return
# Fetch current UoM
ingredients = get_all_ingredients()
current_uom = None
for ing in ingredients:
if ing[0] == ingredient_id:
current_uom = ing[2]
break
if not current_uom:
QMessageBox.warning(self, "Warning", "Unit of Measurement not found.")
return
# Open dialog with current data
dialog = IngredientDialog(name, current_uom)
if dialog.exec_():
new_name, new_uom = dialog.get_data()
# Update the ingredient in the database
conn = get_connection()
c = conn.cursor()
try:
c.execute('UPDATE Ingredients SET name = ?, default_uom = ? WHERE ingredient_id = ?',
(new_name, new_uom, ingredient_id))
conn.commit()
QMessageBox.information(self, "Success", "Ingredient updated successfully.")
self.refresh_ingredients()
except sqlite3.IntegrityError:
QMessageBox.critical(self, "Error", "Ingredient name must be unique.")
finally:
conn.close()
def delete_ingredient(self):
selected_item = self.ingredients_list.currentItem()
if not selected_item:
QMessageBox.warning(self, "Warning", "Please select an ingredient to delete.")
return
text = selected_item.text()
name = text.split(' (')[0]
ingredient_id = get_ingredient_id(name)
if not ingredient_id:
QMessageBox.warning(self, "Warning", "Selected ingredient not found.")
return
confirm = QMessageBox.question(self, "Confirm Deletion",
f"Are you sure you want to delete ingredient '{name}'?",
QMessageBox.Yes | QMessageBox.No)
if confirm == QMessageBox.Yes:
try:
# Delete ingredient from recipes if needed
conn = get_connection()
c = conn.cursor()
c.execute('DELETE FROM RecipeIngredients WHERE ingredient_id = ?', (ingredient_id,))
# Now delete the ingredient itself
c.execute('DELETE FROM Ingredients WHERE ingredient_id = ?', (ingredient_id,))
conn.commit()
conn.close()
QMessageBox.information(self, "Success", "Ingredient deleted successfully.")
self.refresh_ingredients()
except Exception as e:
QMessageBox.critical(self, "Error", str(e))
Assistant
class IngredientDialog(QMessageBox):
def init(self, name="", uom=""):
super().init()
self.setWindowTitle("Ingredient Details")
self.setWindowModality(Qt.ApplicationModal)
self.name_input = QLineEdit()
self.name_input.setText(name)
self.uom_input = QLineEdit()
self.uom_input.setText(uom)
form_layout = QFormLayout()
form_layout.addRow("Name:", self.name_input)
form_layout.addRow("Unit of Measurement:", self.uom_input)
# Buttons
self.addButton(QPushButton("OK"), QMessageBox.AcceptRole)
self.addButton(QPushButton("Cancel"), QMessageBox.RejectRole)
self.layout().addLayout(form_layout, 0, 0)
def accept(self):
name = self.name_input.text().strip()
uom = self.uom_input.text().strip()
if not name or not uom:
QMessageBox.warning(self, "Input Error", "Please provide both name and unit of measurement.")
return
super().accept()
def get_data(self):
return self.name_input.text().strip(), self.uom_input.text().strip()
def main():
app = QApplication(sys.argv)
app.setStyle("Fusion") # Optional: Set a style
# Initialize the database
initialize_database()
window = GUIApp()
window.show()
sys.exit(app.exec_())
if name == "main":
main()
To adjust your main.py script to load ingredients from an Excel file and store them in the database, you'll need to modify several parts of your code. Here's a step-by-step guide to help you implement this functionality:
Modify the Database Schema to Include SAP Code and Balance
First, you'll need to modify your database schema to include the sap_code and balance fields in the Ingredients table. Assuming your database initialization code is in database_setup.py or within the initialize_database() function, you can update it as follows:
# In database_helpers.py or database_setup.py
def initialize_database():
conn = get_connection()
c = conn.cursor()
c.execute('''
CREATE TABLE IF NOT EXISTS Ingredients (
ingredient_id INTEGER PRIMARY KEY AUTOINCREMENT,
sap_code TEXT UNIQUE,
name TEXT UNIQUE,
default_uom TEXT,
balance REAL
)
''')
# ... rest of your initialization code ...
conn.commit()
conn.close()
This modification adds sap_code (as a unique identifier) and balance (as a real number) to your Ingredients table.
Update Database Helper Functions
Modify your add_ingredient function in database_helpers.py to accept the sap_code and balance parameters:
Define the import_ingredients_from_excel method in your IngredientsTab class. This method will open a file dialog, read the Excel file, and update the database accordingly:
class IngredientsTab(QWidget):
# ... existing code ...
def import_ingredients_from_excel(self):
options = QFileDialog.Options()
file_path, _ = QFileDialog.getOpenFileName(self, "Select Ingredients Excel File", "", "Excel Files (*.xlsx);;All Files (*)", options=options)
if file_path:
try:
ingredients_data = self.read_ingredients_from_excel(file_path)
if ingredients_data:
# Insert or update ingredients in the database
for ing in ingredients_data:
sap_code = ing['sap_code']
name = ing['name']
balance = ing['balance']
uom = ing['uom']
try:
# Try to add new ingredient
add_ingredient(sap_code, name, uom, balance)
except sqlite3.IntegrityError:
# Update existing ingredient if sap_code or name already exists
conn = get_connection()
c = conn.cursor()
c.execute('UPDATE Ingredients SET default_uom = ?, balance = ? WHERE sap_code = ? OR name = ?', (uom, balance, sap_code, name))
conn.commit()
conn.close()
QMessageBox.information(self, "Success", "Ingredients imported successfully.")
self.refresh_ingredients()
else:
QMessageBox.warning(self, "Warning", "No data found in the selected file.")
except Exception as e:
QMessageBox.critical(self, "Error", str(e))
def read_ingredients_from_excel(self, file_path):
"""Read the ingredients from the specified Excel file."""
try:
wb = openpyxl.load_workbook(file_path, data_only=True)
sheet = wb.active # Assuming the first sheet contains the data
ingredients_data = []
# Map headers to columns
headers = {}
for col in range(1, sheet.max_column + 1):
header = sheet.cell(row=1, column=col).value
if header:
headers[header.strip().lower()] = col
required_headers = ['sap code', 'material description', 'balance', 'uom']
for header in required_headers:
if header not in headers:
QMessageBox.critical(self, "Error", f"Missing header '{header}' in the Excel sheet.")
return None
# Read data rows
for row in range(2, sheet.max_row + 1):
sap_code = sheet.cell(row=row, column=headers['sap code']).value
name = sheet.cell(row=row, column=headers['material description']).value
balance = sheet.cell(row=row, column=headers['balance']).value
uom = sheet.cell(row=row, column=headers['uom']).value
if sap_code and name and balance is not None and uom:
ingredients_data.append({
'sap_code': str(sap_code).strip(),
'name': str(name).strip(),
'balance': float(balance),
'uom': str(uom).strip()
})
return ingredients_data
except Exception as e:
logging.error(f"Error importing ingredients: {str(e)}")
QMessageBox.critical(self, "Error", f"Failed to import ingredients: {str(e)}")
return None
Update the Ingredient Display Functionality
Modify the refresh_ingredients method in IngredientsTab to display the sap_code and balance alongside the ingredient name:
def refresh_ingredients(self):
self.ingredients_list.clear()
ingredients = get_all_ingredients()
for ing in ingredients:
sap_code = ing[1]
name = ing[2]
uom = ing[3]
balance = ing[4]
self.ingredients_list.addItem(f"{sap_code} - {name} ({uom}), Balance: {balance}")
Adjust the Ingredient Editing Dialog
Update the IngredientDialog class to include fields for sap_code and balance so that users can edit these values:
class IngredientDialog(QMessageBox):
def __init__(self, sap_code="", name="", uom="", balance=0):
super().__init__()
self.setWindowTitle("Ingredient Details")
self.setWindowModality(Qt.ApplicationModal)
self.sap_code_input = QLineEdit()
self.sap_code_input.setText(sap_code)
self.name_input = QLineEdit()
self.name_input.setText(name)
self.uom_input = QLineEdit()
self.uom_input.setText(uom)
self.balance_input = QLineEdit()
self.balance_input.setText(str(balance))
form_layout = QFormLayout()
form_layout.addRow("SAP Code:", self.sap_code_input)
form_layout.addRow("Name:", self.name_input)
form_layout.addRow("Unit of Measurement:", self.uom_input)
form_layout.addRow("Balance:", self.balance_input)
# Buttons
self.addButton(QPushButton("OK"), QMessageBox.AcceptRole)
self.addButton(QPushButton("Cancel"), QMessageBox.RejectRole)
self.layout().addLayout(form_layout, 0, 0)
def accept(self):
sap_code = self.sap_code_input.text().strip()
name = self.name_input.text().strip()
uom = self.uom_input.text().strip()
balance_text = self.balance_input.text().strip()
if not sap_code or not name or not uom or not balance_text:
QMessageBox.warning(self, "Input Error", "Please provide all fields.")
return
try:
balance = float(balance_text)
except ValueError:
QMessageBox.warning(self, "Input Error", "Balance must be a number.")
return
super().accept()
def get_data(self):
return (
self.sap_code_input.text().strip(),
self.name_input.text().strip(),
self.uom_input.text().strip(),
float(self.balance_input.text().strip())
)
Update the Ingredient Editing Functionality
Modify the edit_ingredient method in IngredientsTab to handle the additional fields:
def edit_ingredient(self):
selected_item = self.ingredients_list.currentItem()
if not selected_item:
QMessageBox.warning(self, "Warning", "Please select an ingredient to edit.")
return
text = selected_item.text()
parts = text.split(' - ')
sap_code = parts[0]
name_part = parts[1]
name = name_part.split(' (')[0]
conn = get_connection()
c = conn.cursor()
c.execute('SELECT ingredient_id, default_uom, balance FROM Ingredients WHERE sap_code = ? OR name = ?', (sap_code, name))
row = c.fetchone()
conn.close()
if not row:
QMessageBox.warning(self, "Warning", "Selected ingredient not found.")
return
ingredient_id = row[0]
uom = row[1]
balance = row[2]
# Open dialog with current data
dialog = IngredientDialog(sap_code, name, uom, balance)
if dialog.exec_():
new_sap_code, new_name, new_uom, new_balance = dialog.get_data()
# Update the ingredient in the database
conn = get_connection()
c = conn.cursor()
try:
c.execute('UPDATE Ingredients SET sap_code = ?, name = ?, default_uom = ?, balance = ? WHERE ingredient_id = ?',
(new_sap_code, new_name, new_uom, new_balance, ingredient_id))
conn.commit()
QMessageBox.information(self, "Success", "Ingredient updated successfully.")
self.refresh_ingredients()
except sqlite3.IntegrityError:
QMessageBox.critical(self, "Error", "Ingredient SAP code and name must be unique.")
finally:
conn.close()
Ensure Consistent Data Handling
Make sure that any other parts of your code that interact with the Ingredients table are updated to handle the new sap_code and balance fields. For example, when calculating consumption or displaying ingredient details, include the balance and ensure the correct matching of ingredients using sap_code or name.
Testing
After implementing the changes, test your application thoroughly:
Import an Excel file with ingredients and verify that they're added to the database.
Edit ingredients and check that updates are saved correctly.
Ensure that duplicate SAP codes or names are handled appropriately.
Test the consumption calculations to make sure they work with the updated ingredient data.
Note on the Excel File Format:
Your Excel file should have the following columns with headers exactly as specified (case-insensitive):
SAP Code — Unique code for the ingredient.
Material Description — Name of the ingredient.
Balance — Quantity of the ingredient available.
UoM — Unit of Measurement for the balance.
Example Excel Format:
SAP Code
Material Description
Balance
UoM
123456
Sugar
1000
kg
234567
Flour
500
kg
345678
Milk
200
L
With these changes, your application will be able to read ingredients from an Excel file and store them in the database, including the SAP code, name, balance, and unit of measurement. This will streamline the process of initializing your ingredients and ensure that your application has the necessary data to perform consumption calculations and other functionalities.
Additional Tips:
Error Handling: Ensure that your code gracefully handles any errors that may occur during the import process, such as missing fields or invalid data types.
Data Validation: Implement validation checks when reading from the Excel file to ensure that the data conforms to expected formats.
User Feedback: Provide informative messages to the user during the import process to indicate success or highlight any issues that need attention.
Database Transactions: Consider using database transactions to ensure that your data remains consistent in case of any import failures halfway through.
By following these steps, you'll adjust your application to meet your requirement of loading ingredients from an Excel file and storing them in the database. This will enhance the usability of your application and make managing ingredients more efficient.