rework the recipe management, i want to change add recipe to create recipe, choosing…
- User
rework the recipe management, i want to change add recipe to create recipe, choosing create i will have to inter the name then choose the ingredients of the recipe form the ingredients in the database then add size variations, in the ingredients there will be all of the size variations, 1kg 2kg 2ltr 1ltr 200ml etc, when choosing a variation the script should choose the right quantity per recipe considering the recipe is 100L or 100kg per batch depends on if the final product is liquid or solid, here's my script:
main.py
import sys import os import logging import sqlite3 from PyQt5.QtWidgets import ( QApplication, QWidget, QTabWidget, QVBoxLayout, QPushButton, QLabel, QLineEdit, QMessageBox, QHBoxLayout, QListWidget, QFormLayout, QComboBox, QFileDialog, QDateEdit, QTableWidget, QTableWidgetItem, QInputDialog ) from PyQt5.QtCore import Qt, QDate
Import your database helpers and unit conversion functions
from database_helpers import ( add_ingredient, get_all_ingredients, get_ingredient_id, get_recipe_id, add_recipe, get_all_recipes, add_ingredient_to_recipe, get_recipe_ingredients, delete_ingredient_from_recipe, add_size_variation, get_size_variations, delete_size_variation, add_production_data, get_production_data, get_connection, initialize_database, get_ingredient_name_by_id, update_ingredient ) from unit_conversion import convert_unit import openpyxl from datetime import datetime
Configure logging
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))
Set up logging to file and console
logging.basicConfig( filename=os.path.join(get_base_path(), 'application.log'), level=logging.DEBUG, # Set to DEBUG to capture all levels of logs format='%(asctime)s - %(levelname)s - %(message)s', filemode='a' ) console_handler = logging.StreamHandler() console_handler.setLevel(logging.DEBUG) console_formatter = logging.Formatter('%(levelname)s - %(message)s') console_handler.setFormatter(console_formatter) logging.getLogger().addHandler(console_handler)
class IngredientsTab(QWidget): def init(self): super().init() self.layout = QVBoxLayout() try: self.init_ui() self.layout.addStretch() self.setLayout(self.layout) logging.info("Initialized IngredientsTab UI successfully.") except Exception as e: logging.error(f"Error initializing IngredientsTab: {e}") QMessageBox.critical(self, "Error", f"Failed to initialize IngredientsTab: {e}")
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) # Import Button import_btn = QPushButton("Import Ingredients from Excel") self.layout.addWidget(import_btn) import_btn.clicked.connect(self.import_ingredients_from_excel) # 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): try: 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}") logging.debug("Ingredients list refreshed.") except Exception as e: logging.error(f"Error refreshing ingredients list: {e}") QMessageBox.critical(self, "Error", f"Failed to refresh ingredients list: {e}") 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: conn = get_connection() c = conn.cursor() try: 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 c.execute('INSERT INTO Ingredients (sap_code, name, default_uom, balance) VALUES (?, ?, ?, ?)', (sap_code, name, uom, balance)) logging.info(f"Added new ingredient: {name} (SAP Code: {sap_code})") except sqlite3.IntegrityError: # Update existing ingredient if sap_code or name already exists c.execute('UPDATE Ingredients SET default_uom = ?, balance = ? WHERE sap_code = ? OR name = ?', (uom, balance, sap_code, name)) logging.info(f"Updated existing ingredient: {name} (SAP Code: {sap_code})") conn.commit() except Exception as e_inner: conn.rollback() logging.error(f"Error during import transaction: {e_inner}") QMessageBox.critical(self, "Error", f"Failed to import ingredients: {e_inner}") finally: conn.close() QMessageBox.information(self, "Success", "Ingredients imported successfully.") self.refresh_ingredients() else: QMessageBox.warning(self, "Warning", "No data found in the selected file.") logging.warning("No data found in the selected Excel file.") except Exception as e: logging.error(f"Error importing ingredients from Excel: {e}") QMessageBox.critical(self, "Error", f"Failed to import ingredients: {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: logging.error(f"Missing header '{header}' in the Excel sheet.") 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: try: balance_float = float(balance) ingredients_data.append({ 'sap_code': str(sap_code).strip(), 'name': str(name).strip(), 'balance': balance_float, 'uom': str(uom).strip() }) logging.debug(f"Read ingredient from Excel: {name} (SAP Code: {sap_code})") except ValueError: logging.warning(f"Invalid balance value at row {row}. Skipping this row.") continue return ingredients_data except Exception as e: logging.error(f"Error reading ingredients from Excel: {e}") QMessageBox.critical(self, "Error", f"Failed to read ingredients from Excel: {e}") return None def add_ingredient(self): dialog = IngredientDialog() if dialog.exec_(): sap_code, name, uom, balance = dialog.get_data() try: add_ingredient(sap_code, name, uom, balance) self.refresh_ingredients() logging.info(f"Added ingredient: {name} (SAP Code: {sap_code})") except sqlite3.IntegrityError as e: logging.error(f"IntegrityError when adding ingredient: {e}") QMessageBox.critical(self, "Error", "Ingredient SAP code and name must be unique.") except Exception as e: logging.error(f"Error adding ingredient: {e}") QMessageBox.critical(self, "Error", f"Failed to add ingredient: {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.") logging.warning("No ingredient selected for editing.") return text = selected_item.text() parts = text.split(' - ') if len(parts) < 2: QMessageBox.warning(self, "Warning", "Invalid item format.") logging.warning("Invalid ingredient item format when editing.") return sap_code = parts[0].strip() name_part = parts[1] name = name_part.split(' (')[0].strip() try: 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.") logging.warning(f"Ingredient not found in database: {name} (SAP Code: {sap_code})") 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 try: update_ingredient(ingredient_id, new_sap_code, new_name, new_uom, new_balance) QMessageBox.information(self, "Success", "Ingredient updated successfully.") self.refresh_ingredients() logging.info(f"Updated ingredient: {new_name} (SAP Code: {new_sap_code})") except sqlite3.IntegrityError as e: logging.error(f"IntegrityError when updating ingredient: {e}") QMessageBox.critical(self, "Error", "Ingredient SAP code and name must be unique.") except Exception as e: logging.error(f"Error updating ingredient: {e}") QMessageBox.critical(self, "Error", f"Failed to update ingredient: {e}") except Exception as e: logging.error(f"Error editing ingredient: {e}") QMessageBox.critical(self, "Error", f"Failed to edit ingredient: {e}") def delete_ingredient(self): selected_item = self.ingredients_list.currentItem() if not selected_item: QMessageBox.warning(self, "Warning", "Please select an ingredient to delete.") logging.warning("No ingredient selected for deletion.") return text = selected_item.text() parts = text.split(' - ') if len(parts) < 2: QMessageBox.warning(self, "Warning", "Invalid item format.") logging.warning("Invalid ingredient item format when deleting.") return sap_code = parts[0].strip() name_part = parts[1] name = name_part.split(' (')[0].strip() ingredient_id = get_ingredient_id(name) if not ingredient_id: QMessageBox.warning(self, "Warning", "Selected ingredient not found.") logging.warning(f"Ingredient not found in database: {name} (SAP Code: {sap_code})") 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() logging.info(f"Deleted ingredient: {name} (SAP Code: {sap_code})") except Exception as e: logging.error(f"Error deleting ingredient: {e}") QMessageBox.critical(self, "Error", f"Failed to delete ingredient: {e}") - Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.