import psycopg2
import datetime
import os
# Database connection
def get_connection():
try:
connection = psycopg2.connect(
host="localhost",
database="turbo_mart",
user="postgres",
password="Heyiknow777",
port="5432"
)
return connection
except Exception as e:
print(f"Error connecting to database: {str(e)}")
return None
# Create tables if they don't exist
def create_tables():
conn = get_connection()
if conn:
try:
cursor = conn.cursor()
# Users table
cursor.execute("""
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
username VARCHAR(50) UNIQUE NOT NULL,
password VARCHAR(50) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
# Products table
cursor.execute("""
CREATE TABLE IF NOT EXISTS products (
id SERIAL PRIMARY KEY,
name VARCHAR(100) NOT NULL,
price DECIMAL(10, 2) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
# Transactions table
cursor.execute("""
CREATE TABLE IF NOT EXISTS transactions (
id SERIAL PRIMARY KEY,
total_amount DECIMAL(10, 2) NOT NULL,
tax_amount DECIMAL(10, 2) NOT NULL,
amount_paid DECIMAL(10, 2) NOT NULL,
change_given DECIMAL(10, 2) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
# Transaction items table
cursor.execute("""
CREATE TABLE IF NOT EXISTS transaction_items (
id SERIAL PRIMARY KEY,
transaction_id INTEGER REFERENCES transactions(id),
product_id INTEGER REFERENCES products(id),
quantity INTEGER NOT NULL,
price DECIMAL(10, 2) NOT NULL,
total DECIMAL(10, 2) NOT NULL
)
""")
# Insert default admin user if not exists
cursor.execute("""
INSERT INTO users (username, password)
SELECT 'admin', 'admin'
WHERE NOT EXISTS (SELECT 1 FROM users WHERE username = 'admin')
""")
conn.commit()
print("Tables created successfully")
except Exception as e:
print(f"Error creating tables: {str(e)}")
finally:
cursor.close()
conn.close()
# Clear screen function
def clear_screen():
os.system('cls' if os.name == 'nt' else 'clear')
# Login function
def login():
clear_screen()
print("=== Turbo-Mart POS System ===")
print("Please login to continue")
print("=" * 30)
username = input("Username: ")
password = input("Password: ")
conn = get_connection()
if conn:
try:
cursor = conn.cursor()
cursor.execute("SELECT * FROM users WHERE username = %s AND password = %s", (username, password))
user = cursor.fetchone()
if user:
print("Login successful!")
input("Press Enter to continue...")
return True
else:
print("Invalid username or password")
input("Press Enter to try again...")
return False
except Exception as e:
print(f"Error during login: {str(e)}")
input("Press Enter to try again...")
return False
finally:
cursor.close()
conn.close()
return False
# Product management functions
def view_products():
clear_screen()
print("=== Product Management ===")
print("1. View All Products")
print("2. Add New Product")
print("3. Update Product")
print("4. Delete Product")
print("5. Back to Main Menu")
choice = input("Enter your choice (1-5): ")
if choice == "1":
show_all_products()
elif choice == "2":
add_product()
elif choice == "3":
update_product()
elif choice == "4":
delete_product()
elif choice == "5":
return
else:
print("Invalid choice. Please try again.")
input("Press Enter to continue...")
view_products()
def show_all_products():
clear_screen()
print("=== All Products ===")
conn = get_connection()
if conn:
try:
cursor = conn.cursor()
cursor.execute("SELECT id, name, price, created_at FROM products ORDER BY name")
products = cursor.fetchall()
if not products:
print("No products found.")
else:
print(f"{'ID':<5} {'Name':<30} {'Price':<10} {'Created At'}")
print("-" * 60)
for product in products:
print(f"{product[0]:<5} {product[1]:<30} ${product[2]:<9.2f} {product[3].strftime('%Y-%m-%d')}")
input("\nPress Enter to continue...")
except Exception as e:
print(f"Error loading products: {str(e)}")
input("Press Enter to continue...")
finally:
cursor.close()
conn.close()
view_products()
def add_product():
clear_screen()
print("=== Add New Product ===")
name = input("Product Name: ").strip()
if not name:
print("Product name is required")
input("Press Enter to continue...")
add_product()
return
try:
price = float(input("Price: "))
if price <= 0:
print("Price must be greater than 0")
input("Press Enter to continue...")
add_product()
return
except ValueError:
print("Price must be a valid number")
input("Press Enter to continue...")
add_product()
return
conn = get_connection()
if conn:
try:
cursor = conn.cursor()
cursor.execute("INSERT INTO products (name, price) VALUES (%s, %s)", (name, price))
conn.commit()
print("Product added successfully!")
input("Press Enter to continue...")
except Exception as e:
print(f"Error adding product: {str(e)}")
input("Press Enter to continue...")
finally:
cursor.close()
conn.close()
view_products()
def update_product():
clear_screen()
print("=== Update Product ===")
# First show all products
conn = get_connection()
if conn:
try:
cursor = conn.cursor()
cursor.execute("SELECT id, name, price FROM products ORDER BY name")
products = cursor.fetchall()
if not products:
print("No products found.")
input("Press Enter to continue...")
view_products()
return
print(f"{'ID':<5} {'Name':<30} {'Price'}")
print("-" * 45)
for product in products:
print(f"{product[0]:<5} {product[1]:<30} ${product[2]:.2f}")
try:
product_id = int(input("\nEnter product ID to update: "))
except ValueError:
print("Invalid product ID")
input("Press Enter to continue...")
update_product()
return
# Get the product details
cursor.execute("SELECT id, name, price FROM products WHERE id = %s", (product_id,))
product = cursor.fetchone()
if not product:
print("Product not found!")
input("Press Enter to continue...")
update_product()
return
print(f"\nCurrent details: {product[1]} - ${product[2]:.2f}")
print("Leave field blank to keep current value")
new_name = input(f"New name ({product[1]}): ").strip()
if not new_name:
new_name = product[1]
price_input = input(f"New price (${product[2]}): ").strip()
if not price_input:
new_price = product[2]
else:
try:
new_price = float(price_input)
if new_price <= 0:
print("Price must be greater than 0")
input("Press Enter to continue...")
update_product()
return
except ValueError:
print("Price must be a valid number")
input("Press Enter to continue...")
update_product()
return
cursor.execute("UPDATE products SET name = %s, price = %s WHERE id = %s",
(new_name, new_price, product_id))
conn.commit()
print("Product updated successfully!")
input("Press Enter to continue...")
except Exception as e:
print(f"Error updating product: {str(e)}")
input("Press Enter to continue...")
finally:
cursor.close()
conn.close()
view_products()
def delete_product():
clear_screen()
print("=== Delete Product ===")
# First show all products
conn = get_connection()
if conn:
try:
cursor = conn.cursor()
cursor.execute("SELECT id, name, price FROM products ORDER BY name")
products = cursor.fetchall()
if not products:
print("No products found.")
input("Press Enter to continue...")
view_products()
return
print(f"{'ID':<5} {'Name':<30} {'Price'}")
print("-" * 45)
for product in products:
print(f"{product[0]:<5} {product[1]:<30} ${product[2]:.2f}")
try:
product_id = int(input("\nEnter product ID to delete: "))
except ValueError:
print("Invalid product ID")
input("Press Enter to continue...")
delete_product()
return
# Get the product name for confirmation
cursor.execute("SELECT name FROM products WHERE id = %s", (product_id,))
product = cursor.fetchone()
if not product:
print("Product not found!")
input("Press Enter to continue...")
delete_product()
return
confirm = input(f"Are you sure you want to delete '{product[0]}'? (y/n): ").lower()
if confirm == 'y':
cursor.execute("DELETE FROM products WHERE id = %s", (product_id,))
conn.commit()
print("Product deleted successfully!")
else:
print("Deletion cancelled.")
input("Press Enter to continue...")
except Exception as e:
print(f"Error deleting product: {str(e)}")
input("Press Enter to continue...")
finally:
cursor.close()
conn.close()
view_products()
# Transaction functions
def new_transaction():
clear_screen()
print("=== New Transaction ===")
cart = []
while True:
clear_screen()
print("=== New Transaction ===")
print("1. Add Product to Cart")
print("2. View Cart")
print("3. Remove Item from Cart")
print("4. Complete Transaction")
print("5. Cancel Transaction")
choice = input("Enter your choice (1-5): ")
if choice == "1":
add_to_cart(cart)
elif choice == "2":
view_cart(cart)
elif choice == "3":
remove_from_cart(cart)
elif choice == "4":
complete_transaction(cart)
break
elif choice == "5":
print("Transaction cancelled.")
input("Press Enter to continue...")
break
else:
print("Invalid choice. Please try again.")
input("Press Enter to continue...")
def add_to_cart(cart):
clear_screen()
print("=== Add Product to Cart ===")
# Show all products
conn = get_connection()
if conn:
try:
cursor = conn.cursor()
cursor.execute("SELECT id, name, price FROM products ORDER BY name")
products = cursor.fetchall()
if not products:
print("No products found.")
input("Press Enter to continue...")
return
print(f"{'ID':<5} {'Name':<30} {'Price'}")
print("-" * 45)
for product in products:
print(f"{product[0]:<5} {product[1]:<30} ${product[2]:.2f}")
try:
product_id = int(input("\nEnter product ID to add to cart: "))
except ValueError:
print("Invalid product ID")
input("Press Enter to continue...")
return
# Get the product details
cursor.execute("SELECT id, name, price FROM products WHERE id = %s", (product_id,))
product = cursor.fetchone()
if not product:
print("Product not found!")
input("Press Enter to continue...")
return
try:
quantity = int(input(f"Enter quantity for '{product[1]}': "))
if quantity <= 0:
print("Quantity must be greater than 0")
input("Press Enter to continue...")
return
except ValueError:
print("Quantity must be a valid number")
input("Press Enter to continue...")
return
# Check if product already in cart
found = False
for item in cart:
if item['id'] == product_id:
item['quantity'] += quantity
item['total'] = item['price'] * item['quantity']
found = True
break
# Add new item to cart if not found
if not found:
cart.append({
'id': product_id,
'name': product[1],
'price': product[2],
'quantity': quantity,
'total': product[2] * quantity
})
print("Product added to cart successfully!")
input("Press Enter to continue...")
except Exception as e:
print(f"Error adding to cart: {str(e)}")
input("Press Enter to continue...")
finally:
cursor.close()
conn.close()
def view_cart(cart):
clear_screen()
print("=== Shopping Cart ===")
if not cart:
print("Cart is empty.")
input("Press Enter to continue...")
return
print(f"{'ID':<5} {'Name':<30} {'Price':<10} {'Qty':<5} {'Total'}")
print("-" * 65)
subtotal = 0
for item in cart:
print(f"{item['id']:<5} {item['name']:<30} ${item['price']:<9.2f} {item['quantity']:<5} ${item['total']:.2f}")
subtotal += item['total']
tax = subtotal * 0.08
total = subtotal + tax
print("-" * 65)
print(f"{'Subtotal:':<45} ${subtotal:.2f}")
print(f"{'Tax (8%):':<45} ${tax:.2f}")
print(f"{'Total:':<45} ${total:.2f}")
print("-" * 65)
input("Press Enter to continue...")
def remove_from_cart(cart):
clear_screen()
print("=== Remove Item from Cart ===")
if not cart:
print("Cart is empty.")
input("Press Enter to continue...")
return
print(f"{'#':<3} {'Name':<30} {'Qty':<5} {'Total'}")
print("-" * 50)
for i, item in enumerate(cart, 1):
print(f"{i:<3} {item['name']:<30} {item['quantity']:<5} ${item['total']:.2f}")
try:
item_num = int(input("\nEnter item number to remove: "))
if 1 <= item_num <= len(cart):
removed_item = cart.pop(item_num - 1)
print(f"Removed '{removed_item['name']}' from cart.")
else:
print("Invalid item number.")
except ValueError:
print("Invalid input.")
input("Press Enter to continue...")
def complete_transaction(cart):
if not cart:
print("Cart is empty. Cannot complete transaction.")
input("Press Enter to continue...")
return
clear_screen()
print("=== Complete Transaction ===")
# Calculate totals
subtotal = sum(item['total'] for item in cart)
tax = subtotal * 0.08
total = subtotal + tax
print("Cart Summary:")
print("-" * 40)
for item in cart:
print(f"{item['name']} x {item['quantity']} - ${item['total']:.2f}")
print("-" * 40)
print(f"Subtotal: ${subtotal:.2f}")
print(f"Tax (8%): ${tax:.2f}")
print(f"Total: ${total:.2f}")
print("-" * 40)
try:
amount_paid = float(input("Enter amount paid: "))
if amount_paid < total:
print("Amount paid is less than total. Transaction cancelled.")
input("Press Enter to continue...")
return
change = amount_paid - total
conn = get_connection()
if conn:
try:
cursor = conn.cursor()
# Insert transaction
cursor.execute(
"INSERT INTO transactions (total_amount, tax_amount, amount_paid, change_given) VALUES (%s, %s, %s, %s) RETURNING id",
(total, tax, amount_paid, change)
)
transaction_id = cursor.fetchone()[0]
# Insert transaction items
for item in cart:
cursor.execute(
"INSERT INTO transaction_items (transaction_id, product_id, quantity, price, total) VALUES (%s, %s, %s, %s, %s)",
(transaction_id, item['id'], item['quantity'], item['price'], item['total'])
)
conn.commit()
# Display receipt
print("\n=== RECEIPT ===")
print(f"Transaction #: {transaction_id}")
print(f"Date: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print("-" * 40)
for item in cart:
print(f"{item['name']} x {item['quantity']} @ ${item['price']:.2f} = ${item['total']:.2f}")
print("-" * 40)
print(f"Subtotal: ${subtotal:.2f}")
print(f"Tax (8%): ${tax:.2f}")
print(f"Total: ${total:.2f}")
print(f"Amount Paid: ${amount_paid:.2f}")
print(f"Change: ${change:.2f}")
print("-" * 40)
print("Thank you for shopping at Turbo-Mart!")
print("\nTransaction completed successfully!")
input("Press Enter to continue...")
except Exception as e:
print(f"Error completing transaction: {str(e)}")
input("Press Enter to continue...")
finally:
cursor.close()
conn.close()
except ValueError:
print("Invalid amount entered. Transaction cancelled.")
input("Press Enter to continue...")
# View transactions
def view_transactions():
clear_screen()
print("=== View Transactions ===")
conn = get_connection()
if conn:
try:
cursor = conn.cursor()
cursor.execute("""
SELECT id, created_at, total_amount, tax_amount, amount_paid, change_given
FROM transactions
ORDER BY created_at DESC
LIMIT 20
""")
transactions = cursor.fetchall()
if not transactions:
print("No transactions found.")
else:
print(f"{'ID':<5} {'Date':<20} {'Total':<10} {'Tax':<10} {'Paid':<10} {'Change'}")
print("-" * 70)
for transaction in transactions:
print(f"{transaction[0]:<5} {transaction[1].strftime('%Y-%m-%d %H:%M'):<20} ${transaction[2]:<9.2f} ${transaction[3]:<9.2f} ${transaction[4]:<9.2f} ${transaction[5]:.2f}")
input("\nPress Enter to continue...")
except Exception as e:
print(f"Error loading transactions: {str(e)}")
input("Press Enter to continue...")
finally:
cursor.close()
conn.close()
# Main menu
def main_menu():
while True:
clear_screen()
print("=== Turbo-Mart POS System ===")
print("1. Product Management")
print("2. New Transaction")
print("3. View Transactions")
print("4. Exit")
choice = input("Enter your choice (1-4): ")
if choice == "1":
view_products()
elif choice == "2":
new_transaction()
elif choice == "3":
view_transactions()
elif choice == "4":
print("Thank you for using Turbo-Mart POS System!")
break
else:
print("Invalid choice. Please try again.")
input("Press Enter to continue...")
# Main function
def main():
create_tables()
# Login loop
while True:
if login():
main_menu()
break
else:
retry = input("Would you like to try again? (y/n): ").lower()
if retry != 'y':
print("Goodbye!")
break
if __name__ == "__main__":
main()