build a complete billing app in python
- User
build a complete billing app in python
- Assistant
build a complete billing app in python
Certainly! Building a complete billing application in Python is a great project that can help you understand many aspects of software development, including database management, user interfaces, data processing, and reporting. Below, I'll guide you through the process of creating a basic billing application using Python. We'll use a command-line interface for simplicity and sqlite3 for the database. You can later expand this to have a graphical user interface (GUI) or a web interface using frameworks like Tkinter, Flask, or Django.
Overview:
Prerequisites:
Modules to be used:
sqlite3 for database operations (built-in with Python).datetime for handling date and time.reportlab or fpdf for generating PDF invoices (not covered in this basic implementation).We'll use sqlite3 to create a simple database called billing.db. It will have the following tables:
Products Table:
| Field | Type | Description |
|---|---|---|
| id | INTEGER | Primary Key (auto-increment) |
| name | TEXT | Name of the product |
| price | REAL | Price per unit |
Customers Table:
| Field | Type | Description |
|---|---|---|
| id | INTEGER | Primary Key (auto-increment) |
| name | TEXT | Customer's name |
| TEXT | Customer's email address | |
| phone | TEXT | Customer's phone number |
Transactions Table:
| Field | Type | Description |
|---|---|---|
| id | INTEGER | Primary Key (auto-increment) |
| product_id | INTEGER | Foreign Key referencing Products(id) |
| customer_id | INTEGER | Foreign Key referencing Customers(id) |
| quantity | INTEGER | Quantity of the product sold |
| total_price | REAL | Total price for the transaction |
| date | TEXT | Date and time of the transaction |
The billing application will have the following features:
Product Management:
Customer Management:
Billing Transactions:
Reporting:
Below is the full source code for the billing application. I've added comments to explain each part of the code.
Explanation:
Database Functions:
connect_db() establishes a connection to the SQLite database.create_tables() creates the products, customers, and transactions tables if they don't already exist.Product Functions:
add_product() prompts the user to enter product details and inserts them into the database.list_products() retrieves and displays all products from the database.Customer Functions:
add_customer() prompts the user to enter customer details and inserts them into the database.list_customers() retrieves and displays all customers from the database.Transaction Functions:
create_transaction() handles the process of creating a new transaction, including selecting a product, customer, and quantity.generate_invoice() generates and displays an invoice for a given transaction.list_transactions() retrieves and displays all transactions from the database.Main Program Loop:
main() function displays a menu and calls the appropriate functions based on the user's choice.Save the code above to a file named billing_app.py. To run the application, open a terminal or command prompt, navigate to the directory containing the script, and execute:
python billing_app.py
Follow the on-screen instructions to interact with the application.
This basic application can be extended in many ways to create a more robust billing system:
reportlab or fpdf to generate professional PDF invoices.Building a billing application is an excellent way to practice full-stack development with Python. The key is to start small, as we've done here, and gradually add features, ensuring that your code remains clean and maintainable.
Remember to follow good programming practices:
Need Further Assistance?
Feel free to ask if you have questions about specific features, need help with extending the application, or encounter any issues while implementing the code.
Happy coding!
Not yet included in a published release.
# billing_app.py
import sqlite3
from datetime import datetime
# Database setup and utility functions
def connect_db():
return sqlite3.connect('billing.db')
def create_tables():
conn = connect_db()
cursor = conn.cursor()
# Create products table
cursor.execute('''
CREATE TABLE IF NOT EXISTS products (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
price REAL NOT NULL
)
''')
# Create customers table
cursor.execute('''
CREATE TABLE IF NOT EXISTS customers (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT,
phone TEXT
)
''')
# Create transactions table
cursor.execute('''
CREATE TABLE IF NOT EXISTS transactions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
product_id INTEGER NOT NULL,
customer_id INTEGER NOT NULL,
quantity INTEGER NOT NULL,
total_price REAL NOT NULL,
date TEXT NOT NULL,
FOREIGN KEY(product_id) REFERENCES products(id),
FOREIGN KEY(customer_id) REFERENCES customers(id)
)
''')
conn.commit()
conn.close()
# Product functions
def add_product():
name = input("Enter product name: ").strip()
try:
price = float(input("Enter product price: "))
except ValueError:
print("Invalid price entered.")
return
conn = connect_db()
cursor = conn.cursor()
cursor.execute('INSERT INTO products (name, price) VALUES (?, ?)', (name, price))
conn.commit()
conn.close()
print(f"Product '{name}' added successfully.")
def list_products():
conn = connect_db()
cursor = conn.cursor()
cursor.execute('SELECT * FROM products')
products = cursor.fetchall()
conn.close()
if products:
print("\nAvailable Products:")
print("ID\tName\t\tPrice")
print("--\t----\t\t-----")
for p in products:
print(f"{p[0]}\t{p[1]:15}\t${p[2]:.2f}")
else:
print("No products found.")
# Customer functions
def add_customer():
name = input("Enter customer name: ").strip()
email = input("Enter customer email: ").strip()
phone = input("Enter customer phone: ").strip()
conn = connect_db()
cursor = conn.cursor()
cursor.execute('INSERT INTO customers (name, email, phone) VALUES (?, ?, ?)', (name, email, phone))
conn.commit()
conn.close()
print(f"Customer '{name}' added successfully.")
def list_customers():
conn = connect_db()
cursor = conn.cursor()
cursor.execute('SELECT * FROM customers')
customers = cursor.fetchall()
conn.close()
if customers:
print("\nCustomers:")
print("ID\tName\t\tEmail\t\t\tPhone")
print("--\t----\t\t-----\t\t\t-----")
for c in customers:
print(f"{c[0]}\t{c[1]:15}\t{c[2]:20}\t{c[3]}")
else:
print("No customers found.")
# Transaction functions
def create_transaction():
list_products()
try:
product_id = int(input("Enter product ID: "))
except ValueError:
print("Invalid product ID.")
return
list_customers()
try:
customer_id = int(input("Enter customer ID: "))
except ValueError:
print("Invalid customer ID.")
return
try:
quantity = int(input("Enter quantity: "))
except ValueError:
print("Invalid quantity.")
return
conn = connect_db()
cursor = conn.cursor()
# Get product price
cursor.execute('SELECT price FROM products WHERE id=?', (product_id,))
product = cursor.fetchone()
if not product:
print("Product not found.")
conn.close()
return
price = product[0]
total_price = price * quantity
date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
cursor.execute('''
INSERT INTO transactions (product_id, customer_id, quantity, total_price, date)
VALUES (?, ?, ?, ?, ?)
''', (product_id, customer_id, quantity, total_price, date))
conn.commit()
transaction_id = cursor.lastrowid
conn.close()
print(f"Transaction created with ID: {transaction_id}")
generate_invoice(transaction_id)
def generate_invoice(transaction_id):
conn = connect_db()
cursor = conn.cursor()
cursor.execute('''
SELECT t.id, t.date, c.name, c.email, c.phone, p.name, t.quantity, p.price, t.total_price
FROM transactions t
JOIN customers c ON t.customer_id = c.id
JOIN products p ON t.product_id = p.id
WHERE t.id=?
''', (transaction_id,))
transaction = cursor.fetchone()
conn.close()
if transaction:
invoice = f'''
==============================
INVOICE
==============================
Invoice ID: {transaction[0]}
Date: {transaction[1]}
Customer Information:
Name: {transaction[2]}
Email: {transaction[3]}
Phone: {transaction[4]}
Product Information:
Product Name: {transaction[5]}
Quantity: {transaction[6]}
Price per Unit: ${transaction[7]:.2f}
--------------------------------
Total Price: ${transaction[8]:.2f}
--------------------------------
Thank you for your business!
'''
print(invoice)
else:
print("Transaction not found.")
def list_transactions():
conn = connect_db()
cursor = conn.cursor()
cursor.execute('''
SELECT t.id, t.date, c.name, p.name, t.quantity, t.total_price
FROM transactions t
JOIN customers c ON t.customer_id = c.id
JOIN products p ON t.product_id = p.id
ORDER BY t.date DESC
''')
transactions = cursor.fetchall()
conn.close()
if transactions:
print("\nTransactions:")
print("ID\tDate\t\t\tCustomer\tProduct\t\tQuantity\tTotal Price")
print("--\t----\t\t\t--------\t-------\t\t--------\t-----------")
for t in transactions:
print(f"{t[0]}\t{t[1]}\t{t[2]:10}\t{t[3]:15}\t{t[4]}\t\t${t[5]:.2f}")
else:
print("No transactions found.")
# Main Program Loop
def main():
create_tables()
while True:
print("\n======== Billing App Menu ========")
print("1. Add Product")
print("2. List Products")
print("3. Add Customer")
print("4. List Customers")
print("5. Create Transaction")
print("6. List Transactions")
print("7. Exit")
print("==================================")
choice = input("Enter your choice (1-7): ").strip()
if choice == '1':
add_product()
elif choice == '2':
list_products()
elif choice == '3':
add_customer()
elif choice == '4':
list_customers()
elif choice == '5':
create_transaction()
elif choice == '6':
list_transactions()
elif choice == '7':
print("Exiting the application.")
break
else:
print("Invalid choice. Please enter a number between 1 and 7.")
if __name__ == '__main__':
main()