Basic Shopping Database Project Updated

PHOTO EMBED

Sun Nov 27 2022 01:45:19 GMT+0000 (Coordinated Universal Time)

Saved by @Shivam #python

### Initialization Process ###
 
# Creating Item Database #
 
import weakref
# Module for process involved with displaying all items available. Not sure what it is or does but it works...
 
class Item(object):
    items = []
    # Ignore. Empty list for displaying all items available. 
 
    def __init__(self, itemname, itemprice, itemstock):
        self.__class__.items.append(weakref.proxy(self))
        self.itemname = itemname
        self.itemprice = itemprice
        self.itemstock = itemstock
    # For defining new items; takes name of item, its price, and its stock.
 
    def GetItemName(self):
        return self.itemname
    # To get the name of a specific item
 
    def GetItemPrice(self):
        return self.itemprice
    # To get the price of a specific item.
    
    def GetItemStock(self):
        return self.itemstock
    # To get the stock of a specific item.
 
    def ChangeItemPrice(self, newprice):
        self.itemprice = newprice
    # To change price of a specific item.
    
    def ChangeItemStock(self, newstock):
        self.itemstock = newstock
    # To change stock of a specific item.
 
# Creating Cart Class #
 
class Cart(dict): 
    """cart dict format:  {itemname:[price,number]}"""
    def ShowCart(self):
        return self
    # To define user's cart.
 
# Creating Customer's Shopping Account #
 
class Customer(object):
    """Produces an objects that represent customers."""
 
    def __init__(self, customer_name, customer_id):   
        self.customer_name = customer_name
        self.customer_id = customer_id
        self.cartlist = {}
        self.cartlist[0] = Cart()
    # For defining new customers; takes person's name and id.
 
    def AddCart(self):
        self.cartlist[len(self.cartlist)] = Cart()
    # To create a new cart.
 
    def GetCart(self, cartindex = 0):
        return self.cartlist[cartindex]
    # To get a cart.
 
    def BuyItem(self, item, itemnum, cartindex = 0):
        try:
            self.cartlist[cartindex][item.GetItemName()][1] += itemnum
        except:
            self.cartlist[cartindex].update({item.GetItemName():[item.GetItemPrice(),itemnum]})
    # Process of buying an item
 
    def BuyCancle(self, item, itemnum, cartindex = 0):
        try:
            self.cartlist[cartindex][item.GetItemName()][1] -= itemnum
        except:
            self.cartlist[cartindex].update({item.GetItemName():[item.GetItemPrice(),itemnum]})
    # Process of cancelling buying an item
    
    def CheckOut(self):
        global order_history
        order_history = []
        items_bought = []
        for item in self.cartlist:
            items_bought.append(self.cartlist[item])
        #self.cartlist = {} --> removed due to bug
        print("Items bought were:", items_bought)
        print("""\nFormat to read bill is: [{'item_name': [unit price (USD), quantity]}]
\nTo calculate total price (USD), go through each cart, and in each cart, go through each item, and multiply the unit price by the quantity.""")
        order_history.append(items_bought)
        items_bought = []
    # To 'buy' the items and therefore reset the cart and add into order history.
    
    def ViewOrderHistory(self):
        print("Full history of items bought for" + str(customer_name.customer_name), "is:\n", order_history)
        print("""\nFormat to read bill is: [[{'item_name': [unit price (USD), quantity]}]]
\nTo calculate total price (USD), go through each cart, and in each cart, go through each item, and multiply the unit price by the quantity.""")
    # To view the order history of items bought from all checkouts.
 
# Initializing Item Database #
# Format: name = Item('name', price)
 
Apple = Item('Apple', 7.80, 54)
Pear = Item('Pear', 6.20, 61)
Gun = Item('Gun', 500.00, 5)
Cookie = Item('Cookie', 5.90, 100)
Dad = Item('Dad', 0.00, 0)
 
# Initializing Store For Item Database #
 
def ShowItems():
    for item in Item.items:
        print("Item name:", item.itemname, "| Item price: $", item.itemprice, "USD | Item stock:", item.itemstock)
# Above code is to display all items available.
 
# User Agreement Function #
 
def okay():
    okay = input("\n\nType 'okay' to continue: ")
    print("")
# Function that simply asks for a filler user input before proceeding to the code after it.
    
# User Add Item Loop Function #
 
def add_item_to_cart_function():
    error_count = -1
    while True:
        error_count += 1
        if error_count > 0:
            print("\nERROR: The item you input is not in our catalogue. Choose only one of specific items from our inventory, or make sure the input is case sensitive.\n")
        item_wanted = str(input("Enter the item you would like to add to the cart: "))
        # Asks for user input for item desired.
        global item_wanted_variable
        item_wanted_variable = item_wanted
        item_search = globals()
        if item_wanted_variable in item_search:
            try:
                item_wanted_variable = item_search[item_wanted_variable]
                break
            except UnboundLocalError:
                continue
    # Used to troubleshoot class attribution error where item_wanted was a string class and could not be identified as an item. Essentially takes item_wanted and its string class, and finds a variable in this code with the same name, and then goes from there.
    while True:
        qnty_wanted = int(input("\nEnter the quantity of the item you would like to purchase (qnty wanted <= item stock): "))
        # Asks for user input for item quantity desired.
        if qnty_wanted <= item_wanted_variable.itemstock:
            item_wanted_variable.itemstock -= qnty_wanted
            break
        else:
            print("\nERROR: The quantity you input is above the quantity available of the specified item. Choose only a value less than or equal to the stock. The stock of", item_wanted, "is", str(item_wanted_variable.itemstock) + ".\n")
            continue
    customer_name.BuyItem(item_wanted_variable, qnty_wanted, cart_num)
    total_price_for_item_added = float(item_wanted_variable.itemprice * qnty_wanted)
    print("\nYou are adding", qnty_wanted, str(item_wanted) + "s for", item_wanted_variable.itemprice, "USD each. This will cost", total_price_for_item_added, "USD.")
    print("\nThe stock for", item_wanted, "is now", str(item_wanted_variable.itemstock) + ".")
    okay()
    print("")
    print(str(customer_name.customer_name) + "'s Cart", cart_num, "has: %s" % customer_name.GetCart(cart_num))
    print("""\nFormat to read cart is: {'item_name': [unit price (USD), quantity]}
\nTo calculate total price (USD), go through each item in the cart, and multiply the unit price by the quantity.""")
    # Adds the item and quantity to the cart under the iteration.
 
# User Remove Item Loop Function #
 
def remove_item_from_cart_function():
    error_count = -1
    while True:
        error_count += 1
        if error_count > 0:
            print("\nERROR: The item you input is not in our catalogue. Choose only one of specific items from our inventory, or make sure the input is case sensitive.\n")
        cart_num_for_removal = int(input("Enter the cart number of which you are referencing here: "))
        # Asks for user input for cart being referenced.
        item_removed = str(input("Enter the name of item you would like to remove from the cart: "))
        # Asks for user input for item removal desired.
        global item_removed_variable
        item_removed_variable = item_removed
        item_search = globals()
        if item_removed_variable in item_search:
            try:
                item_removed_variable = item_search[item_removed_variable]
                break
            except UnboundLocalError:
                continue
    # Used to troubleshoot class attribution error where item_wanted was a string class and could not be identified as an item. Essentially takes item_wanted and its string class, and finds a variable in this code with the same name, and then goes from there.
    #while True:
    qnty_removed = int(input("Enter the quantity of the item you would like to have removed (qnty removed <= qnty in cart): "))
    # Asks for user input for item quantity desired.
        #if qnty_removed > customer_name.GetCart(cart_num_for_removal[item_removed][1]):
            #print("\nERROR: The quantity you input to have removed is above the quantity of the specified item that you bought. Choose only a value less than or equal to the quantity in your cart.\n")   
            #continue
        #else:
    item_removed_variable.itemstock += qnty_removed
            #break
    customer_name.BuyCancle(item_removed_variable, qnty_removed, cart_num_for_removal)
    total_price_for_item_removed = float(item_removed_variable.itemprice * qnty_removed)
    print("\nYou are removing", qnty_removed, str(item_removed) + "s in Cart", cart_num_for_removal, "worth", item_removed_variable.itemprice, "USD each. This will remove a total of", total_price_for_item_removed, "USD from the original total.")
    print("\nThe stock for", item_removed, "is now", str(item_removed_variable.itemstock) + ".")
    okay()
    print("")
    print(str(customer_name.customer_name) + "'s Cart", cart_num_for_removal, "now has: %s" % customer_name.GetCart(cart_num_for_removal))
    print("""\nFormat to read cart is: {'item_name': [unit price (USD), quantity]}
\nTo calculate total price (USD), go through each item in the cart, and multiply the unit price by the quantity.""")
    # Removes the item and quantity in the cart specified.
 
 
### UI Functioning Process ###
 
# User Input Warning #
 
print("**Program Note:**\n\nAll user inputs are CASE SENSITIVE. When typing a response given a set of options, please make sure input is case sensitive to the option. Furthermore, in the following program, at some point you may be required to enter the name of an 'item'. When prompted so, please make sure the name of the item is Title Case.\n\n")
 
print("-----\n\n")
 
# Initial Greeting #
 
print("Welcome to Capitalist Market! Everything and anything is offered here in all sorts of ranges, just with a bit of a twist on the pricing. Enjoy shopping here, and follow the steps appropriately for the best service.")
 
# Shop Function #
 
import sys
# Module that implements usage of a 'main menu' to make things easier.
 
from random import randint
# Module that was used for generating random user ID.
 
def MainMenu():
    while True:
        try:
            option = int(input("""\n-----\n
Select a number for the action that you would like to do (it is recommended to go in respective ascending order):\n
            1. Create your customer shopping account
            2. View all items available for purchase
            3. Add items to a shopping cart
            4. Proceed to checkout
            5. View past order history
            6. Exit shopping session
            \nEnter Your Choice: """))
            
            # Asks user to choose one of the numbers to continue on to the specified option.
        
        except ValueError:
            print("\nERROR: You did not make a valid selection. Choose only one of the digits from the given options.")
            continue
        
            # In the case that user enters an incorrect input; restarts the loop and asks again.
        
        else:
            if option == 1:
                print("\nHello! Let's create your shopping account. A few details will be needed, and there will be a few fewsmall things to note down.\n")
                confirming_response1 = input("\nYou're sure you want to proceed, right?\n\n Yes, continue. \n No, return me back to the menu.\n\n")
                if confirming_response1 == 'Yes':
                    print("\n\nOkay! System will continue...\n\n")
                    name = str(input("To create your account, we will need your name. Please enter it: "))
                    print("\nThank you. You're account will be under this name. Also, you'll need an ID for the account, which is below:\n")
                    random_id = randint(1111, 9999)
                    print(str(random_id))
                    print("\nIt'll be helpful to remember these for your own use once we obtain a log-in system. For now, though, this information will serve helpful for us to keep track of your account.\n")
                    global customer_name
                    customer_name = name
                    customer_name = Customer(customer_name, random_id)
                    print("\nThe following confirms your account:\n")
                    print(customer_name.customer_name)
                    print(customer_name.customer_id)
                    okay()
                    print("\nAll right! So your account is now created. You can use this to continue on with your shopping process.")
                    continue
                else:
                    print("\n\nOkay! Back to the main menu...\n")
                    continue
    
            if option == 2:
                print("\nHello! So you would like to see what we have to offer? No problem!\n")
                confirming_response2 = input("\nYou're sure you want to proceed, right?\n\n Yes, continue. \n No, return me back to the menu.\n\n")
                if confirming_response2 == 'Yes':
                    print("\n\nOkay! System will continue...\n\n")
                    print("We have a growing inventory of items to offer. You don't need to worry about the stock at the moment; we have more than you can count. Anyway, below is a list of the current inventory of items and unit prices (USD) for each:\n\n")
                    ShowItems()
                    print("\n\nThose are our concurrent items available for you to buy. Hopefully something catches your eye. Remember these items, as you'll want the full list when moving onto the buying process!")
                    okay()
                    print("\nAll right! So you're ready now. You can use this list later on in the shopping process.")
                    continue
                else:
                    print("\n\nOkay! Back to the main menu...\n")
                    continue
    
            elif option == 3:
                print("\nHello! So you would like add items to your cart? No problem, let's get you through the process!\n")
                confirming_response3 = input("\nYou're sure you want to proceed, right?\n\n Yes, continue. \n No, return me back to the menu.\n\n")
                if confirming_response3 == 'Yes':
                    print("\n\nOkay! System will continue...\n\n")
                    exit_loop = 0
                    global cart_num
                    cart_num = 0
                    while exit_loop == 0:
                        print("If you have not already seen, we have a growing inventory of items to offer. Keep in mind a specific item (or items) you would like to purchase.\n")
                        print("First off, before buying, you'll need to obtain a shopping cart. Luckily, this is virtual, and we'll create a digital shopping cart for you. If this is not your first time going through this process, a new cart defined by the next ascending natural number will be made.")
                        okay()
                        customer_name.AddCart()
                        cart_num += 1
                        print("\nAll right! A new cart has been created. You may now move on to the adding process.\n")
                        print("\nSo, let's add some of the items you would like.\n")
                        exit_item_buying_loop = 0
                        while exit_item_buying_loop == 0:
                            add_item_to_cart_function()
                            exit_item_bl_prompt = int(input("\n\nIf you are done adding items to the cart, then type '1'. Else, if you want to keep adding items, type '0': "))
                            print("")
                            if exit_item_bl_prompt == 1:
                                break
                            else:
                                continue
                        print("\nThank you for adding items to your cart; that completes this session. Hopefully you got everything you wanted.")
                        okay()
                        print("\nAll right! So that was Cart %s.\n" % cart_num)
                        exit_loop_prompt = int(input("Do you want to make a new session with a new cart and buy more items again? Or do you simply wish to continue back to the menu? Type '1' if you wish to exit back to the menu, and type '0' if you wish to start another session: "))
                        if exit_loop_prompt == 1:
                            print("\nOkay! Enough of the shopping spree, back to the main menu it is!\n")
                            break
                        else:
                            print("\nOkay! Continue the shopping spree!\n")
                            continue
                        continue
                else:
                    print("\n\nOkay! Back to the main menu...\n")
                    continue
    
            elif option == 4:
                print("\nHello! So you would like to proceed to checkout? No problem! Hopefully you have something in your cart(s).\n")
                confirming_response4 = input("\nYou're sure you want to proceed, right?\n\n Yes, continue. \n No, return me back to the menu.\n\n")
                if confirming_response4 == 'Yes':
                    print("\n\nOkay! System will continue...\n\n")
                    print("\nBelow is your full bill, which accounts every cart you had and the quantity of items in each. Read it carefully before proceeding.\n\n")
                    customer_name.CheckOut()
                    okay()
                    print("\nNow, this is your opportunity to cancel any orders of the items you bought and remove them from the bill.\n")
                    bill_prompt = str(input("Would you like to remove anything?\nYes or No: "))
                    if bill_prompt == "Yes":
                        print("\nAll right! We'll undergo the process of removing certain items.\n")
                        print("So, let's remove some of the items you would like.\n")
                        exit_item_removing_loop = 0
                        while exit_item_removing_loop == 0:
                            remove_item_from_cart_function()
                            exit_item_rl_prompt = int(input("\nIf you are done removing items from the cart(s), then type '1'. Else, if you want to keep removing items, type '0': "))
                            if exit_item_rl_prompt == 1:
                                break
                            else:
                                continue
                    else:
                        print("\nNo? Okay! Let the process continue.\n")
                    print("\nHere is your final bill:")
                    customer_name.CheckOut()
                    okay()
                    print("\nVery well! So you've checked out your items now. You can either repeat the process and explore further or go see your order history if you have checked out several times.\n")
                    continue
                else:
                    print("\n\nOkay! Back to the main menu...\n")
                    continue
            
            elif option == 5:
                print("\nHello! Want to see your order history? Okay!\n")
                confirming_response5 = input("\nYou're sure you want to proceed, right?\n\n Yes, continue. \n No, return me back to the menu.\n\n")
                if confirming_response5 == 'Yes':
                    print("\n\nOkay! System will continue...\n\n")
                    print("\nAssuming you have bought items recently, below is your order history:\n\n")
                    customer_name.ViewOrderHistory()
                    print("\n\nThere's your order history! There's nothing very special you can do with it, apart from totalling up everything you have bought.")
                    okay()
                    print("\nVery well then. At this point, you can either go back and explore the store again or you can visit the main menu and leave the store.\n")
                    continue
                else:
                    print("\n\nOkay! Back to the main menu...\n")
                    continue
 
            elif option == 6:
                confirming_response6 = input("\n\nYou're sure you want to proceed, right?\n\n Yes, continue. \n No, return me back to the menu.\n\n")
                if confirming_response6 == 'Yes':
                    print("\n\nLeaving already? All right! Thank you for shopping here at Capitalist Market. Hope to see you again soon!")
                    okay()
                    sys.exit()
                    # Forcefully turns off the function and stops the code. 
                else:
                    print("\n\nOkay! Back to the main menu...\n")
                    continue
 
# Running Code Process #
 
MainMenu()
 
# Runs function MainMenu() aka the whole code.
 
 
### Testing And Miscellaneous ###
 
# No testing left.
 
# Future Work Notes #
 
"""
* Implement log-in/log-out systems possibly and make it so there can be several accounts running at the same time.
 
* Implement subclasses of items (i.e. food, appliances).

* Properly implement price calculation system.

* Properly implement stock management system.
"""
content_copyCOPY