Skip to content

Instantly share code, notes, and snippets.

@ridheshcybe
Last active December 18, 2025 15:02
Show Gist options
  • Select an option

  • Save ridheshcybe/bfb6bd0114c176522e64c5cf20fc62cc to your computer and use it in GitHub Desktop.

Select an option

Save ridheshcybe/bfb6bd0114c176522e64c5cf20fc62cc to your computer and use it in GitHub Desktop.
School project
"""CAFE HYBRID MANAGEMENT SYSTEM - CBSE Class 12 | SQLite + File Handling"""
import sqlite3, csv, os
from datetime import datetime
import getpass
def get_db():
os.makedirs('data', exist_ok=True)
conn = sqlite3.connect('data/cafe_hybrid.db')
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA foreign_keys = ON")
return conn
def setup_database():
try:
conn = get_db()
cursor = conn.cursor()
schemas = {
'menu': [('item_id', 'INTEGER PRIMARY KEY'), ('name', 'TEXT'), ('category', 'TEXT'), ('price', 'REAL'),
('available_online', 'BOOLEAN DEFAULT 1'), ('available_offline', 'BOOLEAN DEFAULT 1'),
('online_exclusive', 'BOOLEAN DEFAULT 0'), ('offline_only', 'BOOLEAN DEFAULT 0')],
'orders': [('order_id', 'INTEGER PRIMARY KEY AUTOINCREMENT'), ('order_type', 'TEXT CHECK(order_type IN ("online", "offline"))'),
('customer_name', 'TEXT'), ('customer_contact', 'TEXT'), ('items', 'TEXT'), ('total_amount', 'REAL'),
('order_date', 'TIMESTAMP DEFAULT CURRENT_TIMESTAMP'),
('status', 'TEXT CHECK(status IN ("pending", "confirmed", "preparing", "ready", "completed", "cancelled"))'),
('payment_mode', 'TEXT CHECK(payment_mode IN ("cash", "card", "upi", "online"))'), ('discount_amount', 'REAL DEFAULT 0.00')],
'inventory': [('item_id', 'INTEGER PRIMARY KEY'), ('current_stock', 'INTEGER DEFAULT 0'),
('min_stock', 'INTEGER DEFAULT 10'), ('last_restock', 'TEXT')],
'staff': [('staff_id', 'TEXT PRIMARY KEY'), ('name', 'TEXT'), ('password', 'TEXT'), ('role', 'TEXT')],
'coupons': [('coupon_code', 'TEXT PRIMARY KEY'), ('discount_percent', 'INTEGER'), ('max_discount', 'REAL'),
('min_order', 'REAL'), ('valid_till', 'TEXT'), ('usage_count', 'INTEGER DEFAULT 0')]
}
for table, cols in schemas.items():
cursor.execute(f"CREATE TABLE IF NOT EXISTS {table} ({', '.join([f'{c} {t}' for c, t in cols])})")
cursor.execute("SELECT COUNT(*) as count FROM menu")
if cursor.fetchone()['count'] == 0:
cursor.executemany("INSERT INTO menu VALUES (?, ?, ?, ?, ?, ?, ?, ?)", [
(1, 'Cappuccino', 'Coffee', 120, 1, 1, 0, 0), (2, 'Cold Brew', 'Coffee', 150, 1, 1, 0, 0),
(3, 'Latte', 'Coffee', 130, 1, 1, 0, 0), (4, 'Sandwich', 'Snacks', 180, 1, 1, 0, 0),
(5, 'French Fries', 'Snacks', 120, 1, 1, 0, 0), (6, 'Chocolate Cake', 'Dessert', 200, 1, 1, 0, 0),
(7, 'Online Special Pizza', 'Special', 300, 1, 0, 1, 0), (8, 'Chef Special Pasta', 'Special', 250, 0, 1, 0, 1),
(9, 'Iced Tea', 'Beverages', 100, 1, 1, 0, 0), (10, 'Lemonade', 'Beverages', 90, 1, 1, 0, 0)])
cursor.executemany("INSERT INTO inventory VALUES (?, ?, ?, ?)", [(i, 50, 10, '2023-01-01') for i in range(1, 11)])
cursor.executemany("INSERT INTO staff VALUES (?, ?, ?, ?)", [('STAFF001', 'Admin User', 'admin123', 'Manager'), ('STAFF002', 'Cashier 1', 'cash123', 'Cashier')])
cursor.executemany("INSERT INTO coupons VALUES (?, ?, ?, ?, ?, 0)", [('WELCOME10', 10, 50, 200, '2024-12-31'), ('CAFE20', 20, 100, 500, '2024-12-31')])
print("✅ Sample data inserted!")
conn.commit()
conn.close()
return True
except sqlite3.Error as e:
print(f"❌ Database error: {e}")
return False
def save_invoice(order_id, customer, items, total, discount, payment):
filename = f"invoice_{order_id}.txt"
try:
with open(filename, 'w') as f:
sep, line = "="*60, "-"*60
f.write(f"{sep}\n{'CAFÉ FUSION':^60}\n{'HYBRID MANAGEMENT SYSTEM':^60}\n{sep}\n")
f.write(f"Order ID: {order_id}\nDate: {datetime.now().strftime('%d/%m/%Y %H:%M:%S')}\n")
f.write(f"Customer: {customer}\nPayment: {payment}\n{line}\n")
f.write(f"{'Item':<30} {'Qty':<10} {'Price':<10} {'Total':<10}\n{line}\n")
for item in items:
f.write(f"{item['name'][:29]:<30} {item['qty']:<10} ₹{item['price']:<9} ₹{item['price']*item['qty']:<9}\n")
f.write(f"{line}\n")
if discount > 0: f.write(f"Discount: ₹{discount:.2f}\n")
f.write(f"TOTAL: ₹{total:.2f}\n{sep}\n{'Thank you! Visit again!':^60}\n{sep}\n")
print(f"📄 Invoice saved: {filename}")
return filename
except Exception as e:
print(f"❌ Error: {e}")
return None
def items_to_str(items):
return ";".join([f"{i['id']}:{i['name']}:{i['price']}:{i['qty']}" for i in items])
def str_to_items(s):
if not s: return []
return [{'id': int(p[0]), 'name': p[1], 'price': float(p[2]), 'qty': int(p[3])}
for p in [e.split(":") for e in s.split(";")] if len(p) == 4]
def auth_staff(staff_id, password):
conn = get_db()
if not conn: return False
cursor = conn.cursor()
cursor.execute("SELECT * FROM staff WHERE staff_id = ? AND password = ?", (staff_id, password))
result = cursor.fetchone()
conn.close()
return result is not None
def display_menu(mode="all"):
conn = get_db()
if not conn: return []
cursor = conn.cursor()
query = {"online": "SELECT * FROM menu WHERE available_online = 1 ORDER BY category, item_id",
"offline": "SELECT * FROM menu WHERE available_offline = 1 ORDER BY category, item_id"}.get(mode, "SELECT * FROM menu ORDER BY category, item_id")
cursor.execute(query)
items = cursor.fetchall()
conn.close()
print(f"\n{'='*70}\n{'MENU':^70}\n{'='*70}")
cat = ""
for item in items:
if item[2] != cat:
cat = item[2]
print(f"\n{cat.upper():^70}\n{'-'*70}")
tags = " [ONLINE ONLY]" if item[6] else " [OFFLINE ONLY]" if item[7] else ""
print(f"{item[0]:3}. {item[1]:30} ₹{item[3]:7.2f}{tags}")
print("="*70)
return items
def create_bill():
print(f"\n{'='*50}\nCREATE OFFLINE BILL\n{'='*50}")
items = display_menu("offline")
if not items: return print("No items available!")
cart = []
while True:
try:
item_id = int(input("\nItem ID (0 to finish): "))
if item_id == 0: break
selected = next((i for i in items if i[0] == item_id), None)
if not selected: print("❌ Invalid ID!"); continue
qty = int(input("Quantity: "))
if qty <= 0: print("❌ Invalid quantity!"); continue
cart.append({'id': selected[0], 'name': selected[1], 'price': float(selected[3]), 'qty': qty})
print(f"✅ Added {selected[1]} x{qty}")
except ValueError: print("❌ Invalid input!")
if not cart: return print("Cart empty!")
subtotal = sum(i['price'] * i['qty'] for i in cart)
discount = 0
if input(f"\nApply discount? (Total: ₹{subtotal:.2f}) (y/n): ").lower() == 'y':
try:
discount = float(input("Discount amount: ₹"))
if discount > subtotal: print("❌ Invalid!"); discount = 0
except ValueError: print("❌ Invalid!")
total = subtotal - discount
print("\n💳 PAYMENT: 1.Cash 2.Card 3.UPI")
pm = ['cash', 'card', 'upi'][int(input("Select: "))-1] if input("Select: ") in ['1','2','3'] else 'cash'
customer = input("\nCustomer name (Enter for 'Walk-in'): ").strip() or "Walk-in Customer"
conn = get_db()
if not conn: return
cursor = conn.cursor()
cursor.execute("INSERT INTO orders (order_type, customer_name, items, total_amount, status, payment_mode, discount_amount) VALUES (?, ?, ?, ?, ?, ?, ?)",
('offline', customer, items_to_str(cart), total, 'completed', pm, discount))
order_id = cursor.lastrowid
for item in cart:
cursor.execute("UPDATE inventory SET current_stock = current_stock - ? WHERE item_id = ?", (item['qty'], item['id']))
conn.commit()
conn.close()
save_invoice(order_id, customer, cart, total, discount, pm)
print(f"\n{'='*50}\n✅ BILL CREATED!\n{'='*50}\nOrder ID: {order_id}\nCustomer: {customer}\nTotal: ₹{total:.2f}\nPayment: {pm}\n{'='*50}")
def place_order():
print(f"\n{'='*50}\nPLACE ONLINE ORDER\n{'='*50}")
name = input("\n👤 Your name: ").strip()
phone = input("Phone: ").strip()
if not name or not phone: return print("❌ Name and phone required!")
items = display_menu("online")
if not items: return print("No items available!")
cart = []
while True:
try:
item_id = int(input("\nItem ID (0 to finish): "))
if item_id == 0: break
selected = next((i for i in items if i[0] == item_id), None)
if not selected: print("❌ Invalid!"); continue
qty = int(input("Quantity: "))
if qty <= 0: print("❌ Invalid!"); continue
cart.append({'id': selected[0], 'name': selected[1], 'price': float(selected[3]), 'qty': qty})
print(f"✅ Added {selected[1]} x{qty}")
except ValueError: print("❌ Invalid!")
if not cart: return print("Cart empty!")
subtotal = sum(i['price'] * i['qty'] for i in cart)
discount = 0
coupon = input("\n💳 Coupon code (Enter to skip): ").strip().upper()
if coupon:
conn = get_db()
if conn:
cursor = conn.cursor()
cursor.execute("SELECT discount_percent, max_discount, min_order FROM coupons WHERE coupon_code = ? AND valid_till >= date('now')", (coupon,))
c = cursor.fetchone()
conn.close()
if c and subtotal >= c[2]:
discount = min((subtotal * c[0]) / 100, c[1])
print(f"✅ Discount: ₹{discount:.2f}")
else: print("❌ Invalid coupon!")
total = subtotal - discount
print(f"\n{'-'*50}\nORDER SUMMARY\n{'-'*50}")
for i in cart: print(f"{i['name']:30} x{i['qty']:3} ₹{i['price']*i['qty']:8.2f}")
print(f"{'-'*50}")
if discount > 0: print(f"Discount: ₹{discount:.2f}")
print(f"TOTAL: ₹{total:.2f}\n{'-'*50}")
if input("\nConfirm? (y/n): ").lower() != 'y': return print("Cancelled!")
conn = get_db()
if not conn: return
cursor = conn.cursor()
cursor.execute("INSERT INTO orders (order_type, customer_name, customer_contact, items, total_amount, status, discount_amount, payment_mode) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
('online', name, phone, items_to_str(cart), total, 'pending', discount, 'online'))
order_id = cursor.lastrowid
conn.commit()
conn.close()
save_online_backup({'order_id': order_id, 'customer': name, 'phone': phone, 'items': cart, 'total': total, 'discount': discount, 'timestamp': str(datetime.now()), 'status': 'pending'})
print(f"\n{'='*50}\n✅ ORDER PLACED!\n{'='*50}\nOrder ID: {order_id}\nCustomer: {name}\nPhone: {phone}\nTotal: ₹{total:.2f}\nStatus: Pending\n{'='*50}\n📱 Track using Order ID\n{'='*50}")
def track_order():
print(f"\n{'='*50}\nTRACK ORDER\n{'='*50}")
try: order_id = int(input("Order ID: "))
except ValueError: return print("❌ Invalid ID!")
conn = get_db()
if not conn: return
cursor = conn.cursor()
cursor.execute("SELECT order_id, customer_name, order_date, total_amount, status, items FROM orders WHERE order_id = ? AND order_type = 'online'", (order_id,))
order = cursor.fetchone()
conn.close()
if not order: return print("❌ Not found!")
items = str_to_items(order[5])
print(f"\n{'='*50}\nORDER STATUS\n{'='*50}\nID: {order[0]}\nCustomer: {order[1]}\nTime: {order[2]}\nTotal: ₹{order[3]:.2f}")
if items:
print("\nItems:")
for i in items: print(f" - {i['name']} x{i['qty']}")
status_emoji = {'pending': '⏳', 'confirmed': '✅', 'preparing': '👨‍🍳', 'ready': '📦', 'completed': '🎉', 'cancelled': '❌'}.get(order[4], '📝')
print(f"\nStatus: {status_emoji} {order[4].upper()}\n{'='*50}")
def process_orders():
print(f"\n{'='*50}\nPROCESS ONLINE ORDERS\n{'='*50}")
conn = get_db()
if not conn: return
cursor = conn.cursor()
cursor.execute("SELECT order_id, customer_name, customer_contact, items, total_amount FROM orders WHERE order_type = 'online' AND status = 'pending' ORDER BY order_date")
orders = cursor.fetchall()
if not orders: print("No pending orders!"); conn.close(); return
print(f"\nFound {len(orders)} pending order(s):\n{'-'*50}")
for o in orders:
items = str_to_items(o[3])
print(f"\n📦 Order #{o[0]}\n Customer: {o[1]} ({o[2]})\n Total: ₹{o[4]}\n Items:")
for i in items: print(f" - {i['name']} x{i['qty']}")
action = input(f"\nProcess #{o[0]}? (c=confirm, s=skip, x=cancel): ").lower()
if action == 'c':
cursor.execute("UPDATE orders SET status = 'confirmed' WHERE order_id = ?", (o[0],))
print(f"✅ Order #{o[0]} confirmed!")
elif action == 'x':
cursor.execute("UPDATE orders SET status = 'cancelled' WHERE order_id = ?", (o[0],))
print(f"❌ Order #{o[0]} cancelled!")
else: print(f"⏸️ Skipped")
conn.commit()
conn.close()
print("\n✅ Processing complete!")
def view_orders():
conn = get_db()
if not conn: return
cursor = conn.cursor()
today = datetime.now().strftime('%Y-%m-%d')
cursor.execute("SELECT order_id, order_type, customer_name, total_amount, payment_mode, status, order_date FROM orders WHERE DATE(order_date) = ? ORDER BY order_date DESC", (today,))
orders = cursor.fetchall()
conn.close()
if not orders: return print("No orders today!")
sep = "="*80
line = "-"*80
print(f"\n{sep}\n{'TODAY ORDERS':^80}\n{sep}\n{'ID':<6} {'Type':<8} {'Customer':<20} {'Amount':<10} {'Payment':<8} {'Status':<12} {'Time':<10}\n{line}")
total = 0
for o in orders:
print(f"{o[0]:<6} {o[1]:<8} {o[2][:18]:<20} ₹{o[3]:<8.2f} {o[4]:<8} {o[5]:<12} {o[6][:5]:<10}")
total += float(o[3])
print(f"{line}\nTotal Orders: {len(orders)}\nTotal Revenue: ₹{total:.2f}\n{sep}")
def check_inventory():
conn = get_db()
if not conn: return
cursor = conn.cursor()
cursor.execute("SELECT m.item_id, m.name, i.current_stock, i.min_stock, CASE WHEN i.current_stock <= i.min_stock THEN 'LOW' WHEN i.current_stock = 0 THEN 'OUT' ELSE 'OK' END FROM menu m JOIN inventory i ON m.item_id = i.item_id ORDER BY current_stock")
inv = cursor.fetchall()
conn.close()
print(f"\n{'='*70}\n{'INVENTORY STATUS':^70}\n{'='*70}\n{'ID':<4} {'Item':<30} {'Current':<10} {'Min':<10} {'Status':<15}\n{'-'*70}")
low = []
for i in inv:
print(f"{i[0]:<4} {i[1][:29]:<30} {i[2]:<10} {i[3]:<10} {i[4]:<15}")
if i[4] in ['LOW', 'OUT']: low.append(i[1])
print("="*70)
if low: print("\n⚠️ ATTENTION:"); [print(f" - {i}") for i in low]
else: print("\n✅ All items stocked!")
def update_stock():
print(f"\n{'='*50}\nUPDATE STOCK\n{'='*50}")
check_inventory()
try:
item_id = int(input("\nItem ID: "))
new_stock = int(input("New stock: "))
conn = get_db()
if not conn: return
cursor = conn.cursor()
cursor.execute("SELECT name FROM menu WHERE item_id = ?", (item_id,))
item = cursor.fetchone()
if not item: print("❌ Not found!"); conn.close(); return
cursor.execute("UPDATE inventory SET current_stock = ?, last_restock = date('now') WHERE item_id = ?", (new_stock, item_id))
conn.commit()
conn.close()
print(f"✅ Stock updated for {item[0]}")
except ValueError: print("❌ Invalid input!")
def export_csv():
conn = get_db()
if not conn: return
cursor = conn.cursor()
today = datetime.now().strftime('%Y-%m-%d')
cursor.execute("SELECT order_id, order_type, customer_name, total_amount, payment_mode, order_date FROM orders WHERE DATE(order_date) = ? ORDER BY order_date", (today,))
orders = cursor.fetchall()
conn.close()
if not orders: return print("No orders today!")
filename = f"daily_report_{today}.csv"
try:
with open(filename, 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(['Order ID', 'Type', 'Customer', 'Amount', 'Payment', 'Time'])
total = 0
for o in orders:
writer.writerow([o[0], o[1], o[2], o[3], o[4], o[5]])
total += float(o[3])
writer.writerow([])
writer.writerow(['Total Orders:', len(orders), '', '', '', ''])
writer.writerow(['Total Revenue:', f'₹{total:.2f}', '', '', '', ''])
print(f"📊 Report exported: {filename}\n📈 Orders: {len(orders)}\n💰 Revenue: ₹{total:.2f}")
except Exception as e:
print(f"❌ Error: {e}")
def save_online_backup(order_data):
try:
with open("online_orders_backup.txt", 'a') as f:
f.write(f"{'='*50}\nOrder ID: {order_data['order_id']}\nCustomer: {order_data['customer']}\nPhone: {order_data['phone']}\nTotal: ₹{order_data['total']:.2f}\nTime: {order_data['timestamp']}\nStatus: {order_data['status']}\nItems:\n")
for i in order_data['items']:
f.write(f" - {i['name']} x{i['qty']} @ ₹{i['price']}\n")
f.write(f"{'='*50}\n\n")
print(f"💾 Backed up to online_orders_backup.txt")
except Exception as e:
print(f"❌ Error: {e}")
def daily_report():
conn = get_db()
if not conn: return
cursor = conn.cursor()
today = datetime.now().strftime('%Y-%m-%d')
cursor.execute("SELECT COUNT(*) as total, SUM(total_amount) as revenue, AVG(total_amount) as avg, SUM(CASE WHEN order_type = 'online' THEN 1 ELSE 0 END) as online, SUM(CASE WHEN order_type = 'offline' THEN 1 ELSE 0 END) as offline FROM orders WHERE DATE(order_date) = ?", (today,))
s = cursor.fetchone()
conn.close()
if not s or s[0] == 0: return print("No orders today!")
print(f"\n{'='*50}\nDAILY SUMMARY\n{'='*50}\nDate: {today}\nTotal Orders: {s[0]}\nOnline: {s[3]}\nOffline: {s[4]}\nRevenue: ₹{s[1] or 0:.2f}\nAvg Order: ₹{s[2] or 0:.2f}\n{'='*50}")
export_csv()
def offline_mode():
print(f"\n{'='*70}\n{'OFFLINE COUNTER MODE':^70}\n{'='*70}")
print("\n🔐 STAFF LOGIN")
staff_id = input("Staff ID: ")
password = getpass.getpass("Password: ")
if not auth_staff(staff_id, password): return print("❌ Auth failed!")
print(f"\n✅ Welcome, {staff_id}!")
while True:
print(f"\n{'-'*50}\nOFFLINE MENU\n{'-'*50}\n1. 🧾 New Bill\n2. 📋 Today's Orders\n3. 📦 Inventory\n4. 🔄 Update Stock\n5. 📊 Daily Report\n6. 📱 Process Online Orders\n7. 🏠 Back")
choice = input("\nChoice (1-7): ")
if choice == '1': create_bill()
elif choice == '2': view_orders()
elif choice == '3': check_inventory()
elif choice == '4': update_stock()
elif choice == '5': daily_report()
elif choice == '6': process_orders()
elif choice == '7': break
else: print("❌ Invalid!")
def online_mode():
print(f"\n{'='*70}\n{'ONLINE ORDERING PORTAL':^70}\n{'='*70}")
while True:
print("\n1. 🆕 New Order\n2. 🔍 Track Order\n3. 📋 View Menu\n4. 🏠 Back")
choice = input("\nChoice (1-4): ")
if choice == '1': place_order()
elif choice == '2': track_order()
elif choice == '3': display_menu("online"); input("\nPress Enter...")
elif choice == '4': break
else: print("❌ Invalid!")
def main_menu():
while True:
print(f"\n{'='*70}\n{'CAFÉ FUSION - HYBRID SYSTEM':^70}\n{'='*70}\n\n1. 🔒 STAFF MODE (Offline Counter)\n2. 🛒 CUSTOMER MODE (Online Ordering)\n3. 📊 SYSTEM REPORTS\n4. ❌ EXIT\n{'='*70}")
choice = input("\nSelect (1-4): ")
if choice == '1': offline_mode()
elif choice == '2': online_mode()
elif choice == '3':
while True:
print(f"\n{'='*50}\nREPORTS\n{'='*50}\n1. 📈 Today's Orders\n2. 📦 Inventory\n3. 💰 Revenue\n4. 🏠 Back")
c = input("\nChoice (1-4): ")
if c == '1': view_orders()
elif c == '2': check_inventory()
elif c == '3': daily_report()
elif c == '4': break
else: print("❌ Invalid!")
elif choice == '4':
print(f"\n{'='*70}\nThank you for using Café Fusion!\nCBSE Class 12 Computer Science Project\n{'='*70}")
break
else: print("❌ Invalid!")
def main():
print(f"\n{'='*80}\n{'WELCOME TO CAFÉ FUSION':^80}\n{'Hybrid Management System v1.0':^80}\n{'='*80}\nCBSE Class 12 | Python + SQLite + File Handling\n{'='*80}")
print("\n🔧 Initializing...")
if not setup_database(): return print("❌ Setup failed!")
print("✅ System ready!")
main_menu()
if __name__ == "__main__":
try: main()
except KeyboardInterrupt: print("\n⚠️ Interrupted!")
except sqlite3.Error as e: print(f"\n❌ SQLite Error: {e}")
except Exception as e: print(f"\n❌ Error: {e}")
finally: print("\nThank you for using Café Fusion! Goodbye! 👋")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment