|
| 1 | +import sqlite3 |
| 2 | +import datetime |
| 3 | + |
| 4 | + |
| 5 | +class Inventory: |
| 6 | + def __init__(self): |
| 7 | + """Initialize database and create tables if they don't exist.""" |
| 8 | + self.conn = sqlite3.connect("inventory.db") |
| 9 | + self.cursor = self.conn.cursor() |
| 10 | + |
| 11 | + # Create inventory table |
| 12 | + self.cursor.execute(""" |
| 13 | + CREATE TABLE IF NOT EXISTS inventory ( |
| 14 | + id INTEGER PRIMARY KEY AUTOINCREMENT, |
| 15 | + name TEXT UNIQUE, |
| 16 | + price INTEGER, |
| 17 | + quantity INTEGER |
| 18 | + ) |
| 19 | + """) |
| 20 | + |
| 21 | + # Create history table with total_price for tracking sales revenue |
| 22 | + self.cursor.execute(""" |
| 23 | + CREATE TABLE IF NOT EXISTS history ( |
| 24 | + id INTEGER PRIMARY KEY AUTOINCREMENT, |
| 25 | + action TEXT, |
| 26 | + item_id INTEGER, |
| 27 | + item_name TEXT, |
| 28 | + quantity INTEGER, |
| 29 | + price INTEGER, |
| 30 | + total_price INTEGER, |
| 31 | + timestamp TEXT, |
| 32 | + FOREIGN KEY (item_id) REFERENCES inventory(id) ON DELETE CASCADE |
| 33 | + ) |
| 34 | + """) |
| 35 | + self.conn.commit() |
| 36 | + |
| 37 | + def log_history(self, action, item_name, quantity=None, price=None): |
| 38 | + """Log actions in the history table.""" |
| 39 | + self.cursor.execute( |
| 40 | + "SELECT id FROM inventory WHERE name=?", (item_name,)) |
| 41 | + item = self.cursor.fetchone() |
| 42 | + item_id = item[0] if item else None |
| 43 | + |
| 44 | + timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") |
| 45 | + |
| 46 | + # Calculate total price for sales transactions |
| 47 | + total_price = price * quantity if action == "Sold" and price and quantity else None |
| 48 | + |
| 49 | + self.cursor.execute(""" |
| 50 | + INSERT INTO history (action, item_id, item_name, quantity, price, total_price, timestamp) |
| 51 | + VALUES (?, ?, ?, ?, ?, ?, ?) |
| 52 | + """, (action, item_id, item_name, quantity, price, total_price, timestamp)) |
| 53 | + self.conn.commit() |
| 54 | + |
| 55 | + def add(self, **kwargs): |
| 56 | + """Add an item to inventory and log the action.""" |
| 57 | + try: |
| 58 | + self.cursor.execute( |
| 59 | + "INSERT INTO inventory (name, price, quantity) VALUES (:name, :price, :quantity)", kwargs) |
| 60 | + self.conn.commit() |
| 61 | + self.log_history( |
| 62 | + "Added", kwargs['name'], kwargs['quantity'], kwargs['price']) |
| 63 | + print(f"{kwargs['name']} added to inventory.") |
| 64 | + except sqlite3.IntegrityError: |
| 65 | + print(f"Error: {kwargs['name']} already exists.") |
| 66 | + |
| 67 | + def edit(self, item_name): |
| 68 | + """Edit item price or quantity and log the action.""" |
| 69 | + self.cursor.execute( |
| 70 | + "SELECT * FROM inventory WHERE name=?", (item_name,)) |
| 71 | + item = self.cursor.fetchone() |
| 72 | + |
| 73 | + if not item: |
| 74 | + return print(f"{item_name} not found.") |
| 75 | + |
| 76 | + updates = {} |
| 77 | + |
| 78 | + new_price = input(f"New price for {item_name} (Enter to skip): ") |
| 79 | + new_quantity = input(f"New quantity for {item_name} (Enter to skip): ") |
| 80 | + |
| 81 | + if new_price: |
| 82 | + updates["price"] = int(new_price) |
| 83 | + if new_quantity: |
| 84 | + updates["quantity"] = int(new_quantity) |
| 85 | + |
| 86 | + if updates: |
| 87 | + set_clause = ", ".join(f"{col}=?" for col in updates.keys()) |
| 88 | + self.cursor.execute( |
| 89 | + f"UPDATE inventory SET {set_clause} WHERE name=?", (*updates.values(), item_name)) |
| 90 | + self.conn.commit() |
| 91 | + |
| 92 | + # Log changes in history |
| 93 | + if "price" in updates: |
| 94 | + self.log_history("Price Edited", item_name, |
| 95 | + price=updates["price"]) |
| 96 | + if "quantity" in updates: |
| 97 | + self.log_history("Quantity Edited", item_name, |
| 98 | + quantity=updates["quantity"]) |
| 99 | + |
| 100 | + print(f"{item_name} updated.") |
| 101 | + else: |
| 102 | + print("No changes made.") |
| 103 | + |
| 104 | + def remove(self, item_name): |
| 105 | + """Remove an item from inventory and log the action.""" |
| 106 | + self.cursor.execute( |
| 107 | + "SELECT id FROM inventory WHERE name=?", (item_name,)) |
| 108 | + item = self.cursor.fetchone() |
| 109 | + |
| 110 | + if not item: |
| 111 | + return print(f"Error: {item_name} not found in inventory.") |
| 112 | + |
| 113 | + # Remove the item |
| 114 | + self.cursor.execute("DELETE FROM inventory WHERE name=?", (item_name,)) |
| 115 | + self.conn.commit() |
| 116 | + |
| 117 | + # Log removal action |
| 118 | + self.log_history("Removed", item_name) |
| 119 | + print(f"{item_name} removed successfully.") |
| 120 | + |
| 121 | + def sell(self, item_name, quantity): |
| 122 | + """Sell an item, update inventory, and log the action.""" |
| 123 | + self.cursor.execute( |
| 124 | + "SELECT * FROM inventory WHERE name=?", (item_name,)) |
| 125 | + if not (item := self.cursor.fetchone()): |
| 126 | + return print(f"{item_name} not found.") |
| 127 | + |
| 128 | + if item[3] < quantity: |
| 129 | + return print(f"Not enough stock. Available: {item[3]}") |
| 130 | + |
| 131 | + new_qty = item[3] - quantity |
| 132 | + if new_qty: |
| 133 | + self.cursor.execute( |
| 134 | + "UPDATE inventory SET quantity=? WHERE name=?", (new_qty, item_name)) |
| 135 | + else: |
| 136 | + self.remove(item_name) |
| 137 | + |
| 138 | + self.conn.commit() |
| 139 | + total_price = item[2] * quantity # price * quantity |
| 140 | + self.log_history("Sold", item_name, quantity, item[2]) |
| 141 | + print(f"Sold {quantity} {item_name}(s) for ${total_price}") |
| 142 | + input() |
| 143 | + |
| 144 | + def view_history(self): |
| 145 | + """Display history of transactions with total price for sales.""" |
| 146 | + self.cursor.execute("SELECT * FROM history ORDER BY timestamp DESC") |
| 147 | + history = self.cursor.fetchall() |
| 148 | + if not history: |
| 149 | + return print("No history available.") |
| 150 | + |
| 151 | + print("\nTransaction History:\n" + "-" * 70) |
| 152 | + print( |
| 153 | + f"{'No.':<5} {'Action':<10} {'Item':<15} {'Qty':<8} {'Price':<8} {'Total':<10} {'Timestamp':<20}") |
| 154 | + for i, (id, action, item_id, name, qty, price, total_price, timestamp) in enumerate(history, 1): |
| 155 | + print( |
| 156 | + f"{i:<5} {action:<10} {name:<15} {qty if qty else '-':<8} {price if price else '-':<8} {total_price if total_price else '-':<10} {timestamp:<20}") |
| 157 | + print("-" * 70) |
| 158 | + |
| 159 | + def display(self): |
| 160 | + """Display inventory in a well-formatted table.""" |
| 161 | + self.cursor.execute("SELECT * FROM inventory") |
| 162 | + items = self.cursor.fetchall() |
| 163 | + |
| 164 | + if not items: |
| 165 | + return print("Inventory is empty.") |
| 166 | + |
| 167 | + print("\nInventory List:\n" + "-" * 50) |
| 168 | + print(f"{'No.':<5} {'Name':<20} {'Price':<10} {'Quantity':<10}") |
| 169 | + print("-" * 50) |
| 170 | + |
| 171 | + for i, (id, name, price, qty) in enumerate(items, 1): |
| 172 | + print(f"{i:<5} {name:<20} {price:<10} {qty:<10}") |
| 173 | + |
| 174 | + print("-" * 50) |
| 175 | + |
| 176 | + def __del__(self): |
| 177 | + """Close database connection.""" |
| 178 | + self.conn.close() |
| 179 | + print("Inventory closed.") |
0 commit comments