def user_search(): # Promps the user to enter a keyword for the user to search for in the name or city continueSearch = True while continueSearch: clear_screen() print( "Enter in a keyword to find users by name or email or type '!back' to go back to main menu" ) search = input("Search: ") if search == "!back": continueSearch = False else: like_search = "%" + search + "%" db.cur.execute( "SELECT DISTINCT email, name, city, gender FROM users WHERE email LIKE ? or name LIKE ? ", ( like_search, like_search, )) list = db.cur.fetchall() print(list) print_userSearch(list, search) if list: # There were users returned from the search user_select(list) return # Return back to main menu
def register(): # Gets the information of the user to register for the database # return: # user: if data provided is valid # -1: if the user selects to go back valid_entry = False clear_screen() print("Register for new account") while not valid_entry: email = input("Email: ") user_data = getUser(email) if user_data: print("Email already in use") else: valid_entry = True name = input("Name: ") pwd = input("Password: "******"City: ") valid_entry = False while not valid_entry: gender = input("Gender (M/F): ") if gender == "M" or gender == "F": valid_entry = True else: print("Entry is invalid, Please enter M or F for gender") db.cur.execute("INSERT INTO users VALUES (?, ?, ?, ?, ?)", (email, name, pwd, city, gender)) db.conn.commit() db.set_user(email, name, city, gender) return db.cur_user
def start(): # Prompts user to select login, register, or exit program # return: # user: upon successful login or register # -2: upon selection of quit clear_screen() valid_entry = False while not valid_entry: print("Welcome to the MiniProject 1 Store") print("1: Login 2. Register 3: Exit application") select = input("Selection: ") print(type(select)) print(select) if (select == "1"): user = login() if user != -1: valid_entry = True if (select == "2"): user = register() if user != -1: valid_entry = True if (select == "3"): close_program() else: clear_screen() print("Invalid entry") return user
def main(): filename = sys.argv[-1] # Get the last agument passed to the file name if filename == "main.py": print("Error: No database passed to file") print("Exiting program...") sys.exit() path = "./" + filename db.connect(path) isQuit = False while not isQuit: start() mainMenu() clear_screen() db.cur_user = None # User has logged out, set user to none
def active_sales(pID_choice): # List all active sales associated to the product, ordered based on the remaining time of the sale; includes the sale description, the maximum bid (if there is a bid on the item) or the reserved price (if there is no bid on the item), and the number of days, hours and minutes left until the sale expires clear_screen() sale_listing = """ select s.sid, s.descr, CASE WHEN maxAmt IS NULL THEN (CASE WHEN s.rprice IS NULL THEN 0 ELSE s.rprice END) ELSE maxAmt END, s.edate, datetime('now') from sales s left join (select sid, max(amount) as maxAmt from bids group by sid) b on b.sid = s.sid where pid = "{pid}" and s.edate > datetime('now') """ sale_query = sale_listing.format(pid=pID_choice) db.cur.execute(sale_query) rows = db.cur.fetchall() index = print_active_sale(rows) sale_select(rows[index][0])
def print_userSearch(list, search): # Prints the results that were returned from the user search # Takes in a list of tuples of users data: (email, name, city, gender) clear_screen() if list: dash = '-' * 90 print(dash) print('{:<6s} {:<20s} {:<20s} {:<16s} {:<6s}'.format( "Index", "Name", "Email", "City", "Gender")) print(dash) for i in range(len(list)): print('{:^6d} {:<20s} {:<20s} {:<16s} {:<6s}'.format( i, list[i][1], list[i][0], list[i][2], list[i][3])) else: print("No results returned for your search " + search)
def post_sale(): # Promps the user for data needed to post a sale clear_screen() print("Please enter the following information to post a sale:") valid_pid = False while not valid_pid: pid = input("Product ID (Optional, press Enter to skip): ") if pid == "": pid = None valid_pid = True else: db.cur.execute("SELECT * FROM products WHERE pid=?", (pid, )) results = db.cur.fetchall() if results: valid_pid = True else: print("The pid: " + pid + " Does not exist") edate = get_datetime() valid_input = False while not valid_input: desc = input("Sale Description (Max 25 char): ") if len(desc) <= 25: valid_input = True else: print("Error: input length to long") valid_input = False while not valid_input: cond = input("Condition (max 10 char): ") if len(cond) <= 10: valid_input = True else: print("Error: input length to long") r_price = input("Reserved price (Optional, press Enter to skip): ") if r_price == "": r_price = None sid = generateSID() db.cur.execute( "INSERT INTO sales VALUES (?, ?, ?, ?, ?, ?, ?)", (sid, db.cur_user.get_email(), pid, edate, desc, cond, r_price)) db.conn.commit()
def user_active_sales(email): # Takes in the email of a user for get their currently active sales clear_screen() sale_listing = """ select s.sid, s.descr, CASE WHEN maxAmt IS NULL THEN (CASE WHEN s.rprice IS NULL THEN 0 ELSE s.rprice END) ELSE maxAmt END, s.edate, datetime('now') from sales s left join (select sid, max(amount) as maxAmt from bids group by sid) b on b.sid = s.sid where s.lister = "{e}" and s.edate > datetime('now') """ sale_query = sale_listing.format(e=email) db.cur.execute(sale_query) rows = db.cur.fetchall() if rows: index = print_active_sale(rows) user_sale_select(rows[index][0]) else: print("User has no active sales") input("Press enter to go back.")
def print_reviews(email): # Prints all the reviews that are associated with the user # Takes in the email whom's reviews are to be printed clear_screen() db.cur.execute("SELECT * FROM reviews WHERE reviewee=?", (email, )) list = db.cur.fetchall() if list: # There are tuples in the list dash = '-' * 90 print(dash) print('{:<22s} {:<22s} {:<7s} {:<22s} {:<10s}'.format( "Reviewer", "Reviewee", "Rating", "Description", "Date")) print(dash) for i in range(len(list)): print('{:<22s} {:<22s} {:.2f} {:<22s} {:<10s}'.format( list[i][0], list[i][1], list[i][2], list[i][3], list[i][4])) else: # There are no tuples in the list print("This user has no reviews") input("Press Enter to go back")
def login(): # Gets the email and password of an existing user # return: # user: if the email and password exists # -1: if the user selects to go back clear_screen() valid_login = False while not valid_login: print("Enter email and password. Type 'back' to go back") email = input("Email: ") if (email.lower() == 'back'): login_user = -1 break pwd = input("Password: "******"Invalid email/password") else: # There is no data in the tuple clear_screen() print("Invalid email/password") return login_user
def mainMenu(): # Main menu of the program that prompts the user with the first initial options to choose from logout = False while not logout: clear_screen() print("Welcome to MiniProject 1 Store Main Menu") print("1. List products 2. Search for sales 3. Post a sale 4. Search for users Logout: Logout of account Exit: Exit Program") select = input("Select: ") if select == "logout": logout = True elif select.lower() == "exit": close_program() elif select == "1": list_products() elif select == "2": sale_search() elif select == "3": post_sale() elif select == "4": user_search() else: print("Invalid selection made")
def write_review(email): # Promps user to enter review text and a rating (from 1 to 5) # Fills in the other required field of date, reviewer, reviewee clear_screen() if email == db.cur_user.get_email(): print("You cannot write a review for yourself.") input("Press Enter to go back") else: print("Currently writing a review for: " + str(email)) valid_input = False while not valid_input: r_text = input("Review Text (max 20 char): ") if len(r_text) <= 20: valid_input = True else: print("Error: Max 20 characters allowed") valid_input = False while not valid_input: r_rating = input("Rating (1 to 5): ") if re.match("^[1-5]*$", r_rating): if int(r_rating) <= 5: valid_input = True r_rating = int(r_rating) else: print("Invalid Input") else: print("Invalid Input") today = date.today() r_date = today.strftime("%Y-%m-%d") db.cur.execute( "INSERT INTO reviews VALUES (?, ?, ?, ?, ?)", (db.cur_user.get_email(), email, r_rating, r_text, r_date)) db.conn.commit()
def list_products(): # Printing the product listing w/active sales (product id, description, number of reviews, average rating and # of active sales of product (active sale: sale end date and time has not reached yet)) # Prompts user to select a product ID # Prompts user to select an action: write a product review, list all the product's reviews, list all active sales associated to the product finished = False while not finished: clear_screen() product_listing = """ select p.pid, p.descr, CASE WHEN prCount IS NULL THEN 0 ELSE prCount END, CASE WHEN aRating IS NULL THEN 0 ELSE aRating END, activeC from products p left join (select pid, count(*) as prCount, avg(rating) as aRating from previews group by pid) pr on p.pid = pr.pid left join (select pid, count(*) as activeC from sales where edate > datetime('now') group by pid) s on p.pid = s.pid where activeC > 0 order by activeC desc """ db.cur.execute(product_listing) rows = db.cur.fetchall() dashes = "-" * 80 print(dashes) print("{:<7s}{:<12s}{:<22s}{:<14s}{:<16s}{:<12s}".format( "Index", "Product ID", "Description", "Review Count", "Average Rating", "Active Sales")) print(dashes) for i in range(len(rows)): print( "{:^7d}{pid:^12}{descr:<22}{r_count:^14}{avg_rating:^16}{sale_count:^12}" .format(i, pid=rows[i][0], descr=rows[i][1], r_count=rows[i][2], avg_rating=rows[i][3], sale_count=rows[i][4])) valid_index = False while not valid_index: try: index = int(input("Select a index for the product: ")) if index <= len(rows) - 1 and index >= 0: valid_index = True else: print("Error: invalid index selected") except ValueError: print("Invalid index selected") pID_choice = rows[index][0] print(""" What would you like to do with this selection? 1. Write a product review 2. List all reviews of the product 3. List active sales associated with the product 4. Return to Main Menu """) action = input("Select an action (1, 2, 3, or 4): ") if action == "1": write_preview(pID_choice) elif action == "2": list_preview(pID_choice) elif action == "3": active_sales(pID_choice) elif action == "4": finished = True else: print("Invalid selection.")