0% found this document useful (0 votes)
10 views8 pages

Car Sales Management System Code

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views8 pages

Car Sales Management System Code

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

# pip install bcrypt

import bcrypt # Library for secure password hashing


import datetime

# Base(OOP concept is uesd) User class with common


attributes and methods
class User:
def __init__(self, username, password):
"""
Initialize a User with a username and hashed
password.
:param username: The user's username
:param password: The user's plaintext password
"""
[Link] = username
self.password_hash =
[Link]([Link](), [Link]())

def verify_password(self, password):


"""
Verify if the provided password matches the stored
hash.
:param password: The plaintext password to verify
:return: True if the password is correct, False
otherwise
"""
return [Link]([Link](),
self.password_hash)

# Customer class inheriting from User(parent or base


class)
class Customer(User):
def __init__(self, username, password, email):
"""
Initialize a Customer with additional email attribute.
:param username: The customer's username
:param password: The customer's password
:param email: The customer's email address
"""
super().__init__(username, password)
[Link] = email

# SalesRep class inheriting from User(parent or base


class)
class SalesRep(User):
def __init__(self, username, password):
"""
Initialize a Sales Representative.
:param username: The sales representative's
username
:param password: The sales representative's password
"""
super().__init__(username, password)
[Link] = [] # Track sales made by the sales
representative

def record_sale(self, customer_name, car_model,


price):
"""
Record a sale made by the sales representative.
:param customer_name: Name of the customer
:param car_model: Model of the car sold
:param price: Sale price of the car
"""
sale = {
'customer': customer_name,
'car_model': car_model,
'price': price,
'date': [Link]().strftime('%Y-%m-%d
%H:%M:%S')
}
[Link](sale)

# Car class to manage car details


class Car:
def __init__(self, model, year, price):
"""
Initialize a Car with model, year, price, and sold status.
:param model: Car model name
:param year: Year of manufacture
:param price: Price of the car
"""
[Link] = model
[Link] = year
[Link] = price
[Link] = False # Indicates if the car is sold

# Main Car Sales Management System class


class CarSalesSystem:
def __init__(self):
"""
Initialize the Car Sales System with lists for users and
cars.
"""
[Link] = []
self.sales_reps = []
[Link] = []

def add_customer(self, username, password, email):


"""
Add a new customer to the system.
:param username: Customer's username
:param password: Customer's password
:param email: Customer's email
"""
[Link](Customer(username,
password, email))

def add_sales_rep(self, username, password):


"""
Add a new sales representative to the system.
:param username: Sales representative's username
:param password: Sales representative's password
"""
self.sales_reps.append(SalesRep(username,
password))
def add_car(self, model, year, price):
"""
Add a new car to the system.
:param model: Car model name
:param year: Year of manufacture
:param price: Price of the car
"""
[Link](Car(model, year, price))

def authenticate_user(self, username, password):


"""
Authenticate a user (customer or sales
representative).
:param username: Username of the user
:param password: Password of the user
:return: User object if authentication is successful,
None otherwise
"""
for user in [Link] + self.sales_reps:
if [Link] == username and
user.verify_password(password):
return user
return None

def browse_cars(self):
"""
Display a list of available cars.
"""
print("\nAvailable Cars:")
for car in [Link]:
if not [Link]:
print(f"Model: {[Link]}, Year: {[Link]}, Price: $
{[Link]}")
print()

def sell_car(self, sales_rep, customer_name,


car_model):
"""
Mark a car as sold and record the transaction.
:param sales_rep: SalesRep object
:param customer_name: Name of the customer buying
the car
:param car_model: Model of the car being sold
"""
for car in [Link]:
if [Link] == car_model and not [Link]:
[Link] = True
sales_rep.record_sale(customer_name, [Link],
[Link])
print(f"Car '{[Link]}' sold to {customer_name} by
{sales_rep.username}.\n")
return
print("Car not found or already sold.\n")

def show_sales(self, sales_rep):


"""
Display sales made by a sales representative.
:param sales_rep: SalesRep object
"""
print(f"\nSales by {sales_rep.username}:")
for sale in sales_rep.sales:
print(f"Customer: {sale['customer']}, Car:
{sale['car_model']}, Price: ${sale['price']}, Date:
{sale['date']}")
print()

# Simulate system usage


if __name__ == '__main__':
# Initialize the system
system = CarSalesSystem()

# Add sample data


system.add_customer("customer01", "Custom@01",
"customer01@[Link]")
system.add_sales_rep("salesrep01", "Sales@01")
system.add_car("Toyota", 2021, 50000)
system.add_car("BMW", 2024, 300000)
system.add_car("Ferrari", 2018, 80000)

# User interaction loop


print("Welcome to the Car Sales Management
System")
while True:
print("\n1. Login\n2. Browse Cars\n3. Exit")
choice = input("Enter your choice: ")

if choice == "1":
username = input("Enter username: ")
password = input("Enter password: ")
user = system.authenticate_user(username,
password)

if user:
if isinstance(user, Customer):
print(f"\nWelcome, Customer {[Link]}!")
system.browse_cars()
elif isinstance(user, SalesRep):
print(f"\nWelcome, Sales Representative
{[Link]}!")
while True:
print("\n1. View Available Cars\n2. Sell a Car\n3. View
Sales\n4. Logout")
rep_choice = input("Enter your choice: ")
if rep_choice == "1":
system.browse_cars()
elif rep_choice == "2":
customer_name = input("Enter customer name: ")
car_model = input("Enter car model to sell: ")
system.sell_car(user, customer_name, car_model)
elif rep_choice == "3":
system.show_sales(user)
elif rep_choice == "4":
break
else:
print("Invalid choice. Try again.")
else:
print("Invalid username or password. Try again.")
elif choice == "2":
system.browse_cars()
elif choice == "3":
print("Exiting the system. Goodbye!")
break
else:
print("Invalid choice. Try again.")

# Test Data for the Car Sales Management System

# Customers
# Username: customer01, Password: Custom@01,
Email: customer01@[Link]
# Username: customer02, Password: Custom@02,
Email: customer02@[Link]

# Sales Representatives
# Username: salesrep01, Password: Sales@01
# Username: salesrep02, Password: Sales@02

# Cars
# Model: Toyota, Year: 2021, Price: $50,000, Sold: No
# Model: BMW, Year: 2024, Price: $300,000, Sold: No
# Model: Ferrari, Year: 2018, Price: $80,000, Sold: No

# How to Use Test Data

# Scenario 1: Customer Login


# 1. Enter:
# - Username: customer01
# - Password: Custom@01
# 2. Browse the list of available cars.

# Scenario 2: Sales Representative Login


# 1. Enter:
# - Username: salesrep01
# - Password: Sales@01
# 2. After login, the Sales Representative can:
# - View available cars.
# - Sell a car (e.g., sell BMW to a customer like
customer01).
# - View sales transactions.

# Scenario 3: Car Sale


# 1. Login as salesrep01 (Sales Representative).
# 2. Sell Toyota to customer01:
# - Enter customer name: customer01
# - Enter car model: Toyota

# After the sale, the Toyota car should no longer


appear in the available cars list.

# Scenario 4: View Sales Transactions


# 1. Login as salesrep01.
# 2. View sales transactions to verify:
# - Customer: customer01
# - Car: Toyota
# - Price: $50,000
# - Date: Automatically recorded during the
transaction.

Common questions

Powered by AI

Selling a car involves the SalesRep logging into the system and selecting a customer and car model to proceed with the transaction. The sell_car method is used, which iterates through the cars to find a match that is available and unsold. It marks the car as sold and records the transaction details (customer name, car model, price, and timestamp) by calling the record_sale method on the SalesRep object. This ensures accurate record-keeping by updating the car's availability status and logging transaction specifics, which can be reviewed later in the show_sales method .

Sales representatives can manage their transactions using several methods within the CarSalesSystem. They are provided with login access through the authenticate_user method, which verifies credentials. After authentication, they can view available cars with the browse_cars method, execute sales through the sell_car method, and view their sales history using the show_sales method. This system supports strategic interaction by enabling sales reps to handle various duties, from conducting transactions to tracking sales performance over time .

The user interaction loop in the CarSalesSystem is designed to guide the user experience effectively by providing a clear, text-based menu-driven interface. The system presents options such as login, browsing cars, and exiting, simplifying navigation for users. Upon login, users are directed to further actions based on their role—Customers can view cars, while SalesReps can engage in more detailed functions like selling cars and tracking sales. This design supports user needs by clearly differentiating between customer and sales representative tasks, enhancing usability and focus. However, its text-based nature may limit accessibility compared to a GUI, especially for users unfamiliar with command line interfaces .

The Car class is pivotal for managing car inventory as it contains essential attributes like model, year, price, and a 'sold' status indicator. Upon initialization, a Car object is created with these attributes, allowing the CarSalesSystem to maintain a record of available versus sold cars. The 'sold' attribute is particularly crucial as it allows the system to track and update the availability status of cars seamlessly during transactions. Together with the browsing and selling functionalities, the Car class facilitates effective inventory management by providing structured and accessible car data .

The CarSalesSystem ensures user password security by utilizing the bcrypt library for hashing passwords. When a User object is initialized, the plaintext password is hashed using bcrypt's hashpw function, which employs a random salt and secure hashing algorithm. Verification of passwords during authentication involves checking the plaintext password against the stored hash using bcrypt's checkpw function. This approach prevents storing plaintext passwords and provides resilience against brute force and rainbow table attacks .

Encapsulation in the CarSalesSystem enhances data integrity and security by restricting direct access to object attributes and methods. For instance, password handling is encapsulated within the User class, where hashing and verification are managed internally, preventing external manipulation. Similarly, sales transactions are recorded and accessed through defined methods, ensuring that data modifications adhere to predefined rules and logic. Encapsulation thus protects internal data structures, reduces the risk of unintended interference, and retains system stability by ensuring that interactions occur only through controlled interfaces .

The datetime library in the CarSalesSystem is used to timestamp sales transactions by recording the precise date and time a sale is made. Within the record_sale method, datetime ensures that each transaction entry reflects an accurate sale timeline, critical for historical tracking and reports. This timestamp can support compliance, legal, and business analytics needs by providing context and reliability to sales data, improving the utility of the recorded information .

If a sales representative tries to sell a car that is already sold, the system provides feedback stating, "Car not found or already sold." This message indicates that while the system checks for availability before transaction completion (preventing duplicate sales), its error message could be more descriptive for a better user experience. This suggests limited error differentiation, as it does not explicitly distinguish between cases where a car model does not exist or is sold, which could enhance clarity and user confidence in the system's error handling capabilities .

The CarSalesSystem class employs object-oriented principles by defining classes and subclasses to efficiently manage users and car transactions. Users are modeled using a hierarchy where the User class serves as a base class with common attributes and methods like username and password hashing for security. Two subclasses, Customer and SalesRep, inherit from User, adding specific attributes such as email for Customer and sales records for SalesRep. The Car class encapsulates car-related data, while the CarSalesSystem aggregates these classes to manage lists of customers, sales representatives, and cars. This design leverages inheritance, encapsulation, and methods to validate user authentication and manage car sales transactions .

Inheritance benefits the structure of the CarSalesSystem by enabling shared functionality and attributes through a common base class, User, which includes key features like username and password handling. Customer and SalesRep, as subclasses of User, inherit these features while introducing additional specific attributes or behaviors, such as email management for Customers and sales tracking for SalesReps. This reduces redundancy, promotes code reusability, and supports maintainability by centralizing common functionalities and permitting extensions in subclasses .

You might also like