Computer Science Project - Copy
Computer Science Project - Copy
~~~
INDEX
1. Synopsis 2
5. Output 23-34
6. Conclusion 35
7. Bibliography 36
~1~
SYNOPSIS
Billing capabilities enable the generation of detailed bills for customer purchases, accurately
calculating totals while updating inventory levels. A search function facilitates quick
retrieval of medications by name or category, enhancing operational efficiency. The
application
incorporates robust error handling and logging mechanisms to track runtime issues,
making maintenance and debugging manageable. By automating routine pharmacy
processes and
providing timely insights into stock and sales, the system significantly reduces human error
and enhances customer satisfaction.
Developed using Python and MySQL, this solution offers an efficient and scalable
database for managing daily pharmacy operations. It aims to improve operational
efficiency, enhance inventory management, and streamline the billing process, providing
a valuable tool for
pharmacies to manage their resources effectively. The application lays a strong
foundation for future improvements, such as implementing user authentication,
graphical interfaces, and advanced reporting features, all aimed at adapting to evolving
healthcare needs and elevating pharmacy management standards. Overall, the Pharmacy
Management System serves as an essential resource for pharmacies, ensuring accurate
~2~
transactions and effective resource management.
SOFTWARES USED
1. Python:
Description
Python is a high-level programming language known for its simplicity and readability. It is widely
used for various applications, including web development, data analysis, artificial intelligence,
and automation.
In the Pharmacy Management System, Python serves as the primary programming language to
implement the application's logic, including user interactions, data processing, and database
management. The entire application is built using Python, allowing for easy maintenance and
scalability
2. MySQL:
Description
In the Pharmacy Management System, MySQL is used to store and manage medication data,
including details such as name, quantity, rate, category, manufacturing date, and expiry date.
The application performs various SQL operations, such as inserting, updating, deleting, and
retrieving medication records.
~3~
3. MySQL Connector for Python:
Description
The MySQL Connector for Python is a library that allows Python applications to connect to
MySQL databases. It provides a Pythonic interface for executing SQL queries and managing
database connections.
In the Pharmacy Management System, the MySQL Connector is used to establish connections to
the MySQL database, execute SQL queries, and manage transactions. It facilitates all database
operations, including adding, viewing, updating, and deleting medication records.
Description
A Command Line Interface (CLI) is a text-based interface used to interact with software and
operating systems. Users input commands through a console or terminal to perform specific
tasks.
In the Pharmacy Management System, the CLI is used to present a menu of options to the user,
allowing them to perform various operations such as adding medications, viewing stock, and
generating bills. User input is collected through the command line, and feedback is provided in
text format.
5. Datetime:
Description
~4~
The datetime module in Python provides classes for manipulating dates and times. It allows for
easy handling of date and time operations.
In the Pharmacy Management System, the datetime module is used to handle and validate
manufacturing and expiry dates of medications. It ensures that dates are correctly formatted
and allows for comparisons between dates.
6. File I/O
Description
File Input/Output (I/O) refers to the operations of reading from and writing to files on a storage
medium. It is essential for data persistence and management.
In the Pharmacy Management System, file I/O is used to export medication reports to text files
and JSON files. This allows for easy data backup and sharing, ensuring that medication records
can be preserved outside the database.
7. Error Handling
Description
Error handling refers to the process of responding to and managing errors that occur during the
execution of a program. It is essential for maintaining the stability and reliability of an
application.
~5~
MODULUS USED
1. mysql.connector:
Purpose: Connects Python applications to MySQL databases.
Key Features:
Usage: Used throughout the program to perform CRUD (Create, Read, Update, Delete)
operations on medication records.
2. datetime:
Purpose: Handles date and time operations.
Key Features:
Usage: Validates and processes manufacturing and expiry dates of medications to ensure
correct data entry.
3. logging:
Purpose: Provides a framework for logging events and errors.
Key Features:
~6~
Usage: Logs errors and important events to a file (pharmacy_errors.log) for
troubleshooting and monitoring.
4. re (Regular Expressions):
Purpose: Supports pattern matching and string manipulation.
Key Features:
Usage: Validates user input in the search_medication function to ensure it contains only
valid charac:ters.
5. json:
Purpose: Handles JSON data for serialization and deserialization.
Key Features:
Provides methods for converting Python objects to JSON format and vice versa.
6. os:
Purpose: Provides a way to use operating system-dependent functionality.
Key Features:
Usage: While not explicitly used in the provided code, it can be useful for file operations
and environment management.
7. sys:
Purpose: Provides access to system-specific parameters and functions.
Key Features:
Key Features:
9. copy:
Purpose: Supports shallow and deep copy operations.
Key Features:
Usage: Used to create a backup of medication data before exporting to ensure the
original data remains unchanged.
10. decimal:
Purpose: Provides support for decimal floating-point arithmetic.
Key Features:
11. collections:
Purpose: Implements specialized container datatypes.
Key Features:
Usage: Used to create a named tuple for medication records, making it easier to manage
and display medication data.
12. math:
Purpose: Provides mathematical functions.
Key Features:
~8~
Includes functions for mathematical operations like rounding, trigonometry, etc.
Usage: Used in the generate_bill function to calculate the total cost of medications,
ensuring proper rounding.
CODING
import mysql.connector
from mysql.connector import Error
from datetime import datetime, timedelta
import logging
import re
import json
import time
import copy
import decimal
import collections
import sys
~9~
try:
return mysql.connector.connect(
host='localhost',
user='root',
password='SSS@1416', # Update with your MySQL password if any
database='pharmacy_db' # Ensure this database exists
)
except Error as e:
logging.error(f"DB connection failed: {e}")
return None
# Validate quantity
if not quantity_str.isdigit() or int(quantity_str) < 0:
print("Quantity must be a positive integer.")
return
quantity = int(quantity_str)
# Validate rate
try:
~ 10 ~
rate = decimal.Decimal(rate_str)
if rate < 0:
print("Rate must be a positive number.")
return
except:
print("Invalid rate format.")
return
connection = create_connection()
if connection:
cursor = connection.cursor()
cursor.execute(
"INSERT INTO medications (name, quantity, rate, category, manufacturing_date,
expiry_date) "
"VALUES (%s, %s, %s, %s, %s, %s)",
(name, quantity, rate, category, mfg_date_str, exp_date_str)
~ 11 ~
)
connection.commit()
print(f"Medication '{name}' added successfully.")
cursor.close()
connection.close()
else:
print("Database connection error.")
except Exception as e:
logging.error(f"Add failed: {e}")
print(f"Failed to add medication: {e}")
~ 12 ~
cursor.close()
connection.close()
except Exception as e:
logging.error(f"View medications failed: {e}")
print(f"Failed to retrieve medications: {e}")
else:
print("Database connection error.")
~ 13 ~
except Exception as e:
logging.error(f"Delete failed: {e}")
print(f"Delete operation failed: {e}")
connection = create_connection()
if connection:
cursor = connection.cursor()
cursor.execute("SELECT quantity FROM medications WHERE id = %s", (med_id,))
result = cursor.fetchone()
if result:
new_qty = result[0] + change
if new_qty < 0:
print("Stock can't go below 0.")
cursor.close()
connection.close()
~ 14 ~
return
cursor.execute("UPDATE medications SET quantity = %s WHERE id = %s",
(new_qty, med_id))
connection.commit()
print(f"Stock updated successfully. New quantity: {new_qty}")
else:
print("Medication not found.")
cursor.close()
connection.close()
else:
print("Database connection error.")
except Exception as e:
logging.error(f"Stock update failed: {e}")
print(f"Failed to update stock: {e}")
~ 15 ~
print(f"Stock available: {result[0]}")
else:
print("Medication not found.")
cursor.close()
connection.close()
except Exception as e:
logging.error(f"View stock failed: {e}")
print(f"Failed to view stock: {e}")
else:
print("Database connection error.")
~ 16 ~
items.append((med_id, quantity)) # Add the item to the list
if not items:
print("No items entered for purchase.")
return
total_cost = decimal.Decimal('0.00')
bill_details = [] # To hold details for the bill
connection = create_connection()
if connection:
cursor = connection.cursor()
for med_id, quantity in items:
cursor.execute("SELECT name, rate, quantity FROM medications WHERE id =
%s", (med_id,))
result = cursor.fetchone()
if result:
name, rate, available = result
if quantity > available:
print(f"Insufficient stock for '{name}'. Available quantity: {available}. Item
skipped.")
continue
total = decimal.Decimal(rate) * quantity
total_cost += total
bill_details.append((name, quantity, rate, total))
cursor.execute("UPDATE medications SET quantity = quantity - %s WHERE id =
%s", (quantity, med_id))
else:
~ 17 ~
print(f"Medication ID {med_id} not found. Item skipped.")
connection.commit()
cursor.close()
connection.close()
if bill_details:
print("\n--- BILL ---")
print(f"{'Medication':<20} {'Qty':>5} {'Rate':>10} {'Total':>12}")
print("-" * 50)
for name, qty, rate, total in bill_details:
print(f"{name:<20} {qty:>5} {rate:>10.2f} {total:>12.2f}")
print("-" * 50)
print(f"{'Grand Total':<20} {'':>5} {'':>10} {total_cost:>12.2f}")
print("Thank you for your purchase!")
else:
print("No valid items purchased.")
else:
print("Database connection error.")
except Exception as e:
logging.error(f"Billing error: {e}")
print(f"Failed to generate bill: {e}")
~ 18 ~
connection = create_connection()
if connection:
try:
cursor = connection.cursor()
like_keyword = f"%{keyword}%"
cursor.execute("SELECT id, name, quantity FROM medications WHERE name LIKE
%s OR category LIKE %s", (like_keyword, like_keyword))
rows = cursor.fetchall()
if rows:
print(f"Search results for '{keyword}':")
for row in rows:
print(f"ID: {row[0]}, Name: {row[1]}, Quantity: {row[2]}")
else:
print("No matching medications found.")
cursor.close()
connection.close()
except Exception as e:
logging.error(f"Search failed: {e}")
print(f"Failed to search medications: {e}")
else:
print("Database connection error.")
~ 19 ~
connection = create_connection()
if connection:
try:
cursor = connection.cursor()
cursor.execute("SELECT id, name, expiry_date FROM medications WHERE
expiry_date <= %s", (check_date,))
rows = cursor.fetchall()
if rows:
print(f"Medications expiring within {days} day(s):")
for row in rows:
print(f"ID: {row[0]}, Name: {row[1]}, Expiry Date: {row[2]}")
else:
print("No medications expiring soon.")
cursor.close()
connection.close()
except Exception as e:
logging.error(f"Listing expiring medications failed: {e}")
print(f"Failed to list expiring medications: {e}")
else:
print("Database connection error.")
connection = create_connection()
if connection:
try:
~ 20 ~
cursor = connection.cursor()
cursor.execute("SELECT id, name, quantity FROM medications WHERE quantity <
%s", (threshold,))
rows = cursor.fetchall()
if rows:
print(f"Medications with stock below {threshold}:")
for row in rows:
print(f"ID: {row[0]}, Name: {row[1]}, Quantity: {row[2]}")
else:
print("All medications have sufficient stock.")
cursor.close()
connection.close()
except Exception as e:
logging.error(f"Low stock alert failed: {e}")
print(f"Failed to fetch low stock medications: {e}")
else:
print("Database connection error.")
~ 21 ~
7. Search Medication
8. List Expiring Medications
9. Low Stock Alert
10. Exit
""")
choice = input("Choose an option: ").strip()
if choice == '1':
add_medication()
elif choice == '2':
view_medications()
elif choice == '3':
delete_medication()
elif choice == '4':
update_stock()
elif choice == '5':
view_stock()
elif choice == '6':
generate_bill()
elif choice == '7':
search_medication()
elif choice == '8':
list_expiring_medications()
elif choice == '9':
low_stock_alert()
elif choice == '10':
print("Thank you! Exiting the system.")
sys.exit()
else:
print("Invalid choice. Please try again.")
~ 22 ~
if __name__== "__main__":
main()
OUTPUT
1.Adding a medication:
CASE 1:
~ 23 ~
CASE 2:
~ 24 ~
~ 25 ~
2.Viewing the medications available in the stock:
~ 26 ~
3.Deleting a medication:
CASE 1:
~ 27 ~
CASE 2:
~ 28 ~
CASE 2:
CASE 2:
6.Generating bill:
~ 30 ~
CASE 1:
CASE 2:
~ 31 ~
7.Searching a medication:
~ 32 ~
8.List of expiring medications according to number of days:
CASE 1:
~ 33 ~
CASE 2:
~ 34 ~
10.Exiting the system:
~ 35 ~
CONCLUSION
Developed using Python and MySQL, this solution offers an efficient and scalable
database for managing daily pharmacy operations. It aims to improve operational
efficiency, enhance inventory management, and streamline the billing process, providing
a valuable tool for
pharmacies to manage their resources effectively. The application lays a strong
foundation for future improvements, such as implementing user authentication,
graphical interfaces, and advanced reporting features, all aimed at adapting to evolving
healthcare needs and elevating pharmacy management standards. Overall, the Pharmacy
Management System serves as an essential resource for pharmacies, ensuring accurate
transactions and effective resource management.
~ 36 ~
BIBLIOGRAPHY
W3schools
sqlzoo.net
Simplilearn.net
BLACKBOX.AI
YouTube: Amit Thinks Channel
https://onecompiler.com/python
~ 37 ~