Beispiel #1
0
    def add_widgets(self):
        # Add 2 buttons-> Admin and user
        # Add 1 button-> new user
        # Add contact details
        self.admin_button = GrayButton(self.panel, "Admin login",
                                       lambda: self.get_login_screen("Admin"))
        self.admin_button.place(x=450, y=150)
        self.user_button = GrayButton(self.panel, "User login",
                                      lambda: self.get_login_screen("User"))
        self.user_button.place(x=620, y=150)
        self.new_user_button = GrayButton(self.panel,
                                          "New user? Sign up here",
                                          self.sign_up_form,
                                          borderwidth=2,
                                          relief=RIDGE)
        self.new_user_button.place(x=550, y=220)

        self.contact = WhiteMessage(self.f, text="Contact Details Here!")
        self.contact_detail = WhiteMessage(
            self.f,
            text=
            " Foodzapp Services,\n 221B Baker Street\n India\n +11 22 44 5556",
            font=("Times New Roman", 15, "bold", "italic"))
        self.contact.place(x=500, y=320)
        self.contact.bind("<Button-1>", self.show_contact_details)
 def add_admin_details(self):
     # Add image of admin
     # Add Name of admin as Message
     # Add email of admin as Message
     print(self.details)
     self.admin_raw_image = Image.open('images/' + self.details[4])
     self.admin_raw_image.resize((100, 180))
     self.profile_pic = ImageTk.PhotoImage(self.admin_raw_image)
     # ensure this size is same as image size, also we can use label instead of this
     self.c = Canvas(self.f, width=100, height=180)
     # give the starting cordinates wrt canvas i.e 0,0
     self.canvas_pic = self.c.create_image(0,
                                           0,
                                           image=self.profile_pic,
                                           anchor=NW)
     self.c.place(x=40, y=100)
     # message that displays admin's name
     self.admin_name = WhiteMessage(self.f,
                                    text="Name= " + self.details[1],
                                    width=200)
     self.admin_name.place(x=40, y=300)
     # message that displays admin's email address
     self.admin_email = WhiteMessage(self.f,
                                     text="Email " + self.details[3],
                                     width=300)
     self.admin_email.place(x=40, y=350)
 def __init__(self, root, customer_details):
     super().__init__(root)
     # store customer details tuple here
     self.details = customer_details
     self.root.state('zoomed')
     # create dictionary for food menu items
     self.dct_IntVar = {}
     self.m = WhiteMessage(self.panel, text=f"Welcome {self.details[1]}")
     self.m.place(x=50, y=20)
     self.add_buttons()
     # Add the menu frame that has an image
     self.add_menu()
    def __init__(self, root, admin_details):
        print("Admin home page called")
        super().__init__(root)
        self.root.state('zoomed')  # Maximize the screen
        # Tuple received from DATABASE. Eg=> (2, 'Ritesh', 'SGT', '*****@*****.**', 'RiteshPic3.jpg')
        self.details = admin_details
        # Dictionary to store the pending order checkbox IntVars
        self.dct_IntVar = {}

        self.admin_page = WhiteMessage(self.f, text="Admin Page")
        self.admin_page.place(x=320, y=20)
        self.add_admin_details()
        self.add_buttons()
Beispiel #5
0
class MainPage(DefaultPage):
    def __init__(self, root):
        # Calls the parent DefaultPage and adds its own widgets using add_widgets()
        super().__init__(root)
        self.root.geometry('900x600')
        # this is the reverse of 'zoomed' effect in AdminPage
        self.root.state('normal')
        self.add_widgets()

    def add_widgets(self):
        # Add 2 buttons-> Admin and user
        # Add 1 button-> new user
        # Add contact details
        self.admin_button = GrayButton(self.panel, "Admin login",
                                       lambda: self.get_login_screen("Admin"))
        self.admin_button.place(x=450, y=150)
        self.user_button = GrayButton(self.panel, "User login",
                                      lambda: self.get_login_screen("User"))
        self.user_button.place(x=620, y=150)
        self.new_user_button = GrayButton(self.panel,
                                          "New user? Sign up here",
                                          self.sign_up_form,
                                          borderwidth=2,
                                          relief=RIDGE)
        self.new_user_button.place(x=550, y=220)

        self.contact = WhiteMessage(self.f, text="Contact Details Here!")
        self.contact_detail = WhiteMessage(
            self.f,
            text=
            " Foodzapp Services,\n 221B Baker Street\n India\n +11 22 44 5556",
            font=("Times New Roman", 15, "bold", "italic"))
        self.contact.place(x=500, y=320)
        self.contact.bind("<Button-1>", self.show_contact_details)

    def show_contact_details(self, event):
        self.contact_detail.place(x=500, y=400)

    def reset(self):
        self.e_username.delete(0, END)
        self.e_password.delete(0, END)

    def get_login_screen(self, login_type):
        # Creates a temporary window to login
        # 2 labels-> username,password
        # 2 entry-> take username, password
        # 2 Button-> submit, reset
        login_window = Toplevel()
        login_window.title(login_type)
        f = Frame(login_window, height=200, width=400)
        l1 = Label(f, width=20, text="Enter username: "******"Enter password: "******"Submit",
                    height=2,
                    width=10,
                    command=lambda: self.validate(login_window, login_type))
        """Whenever enter is pressed anywhere on this temporary root, call my validate function."""
        login_window.bind(
            '<Return>', lambda event: self.validate(login_window, login_type))
        b1.grid(row=3, column=1, padx=10, sticky='e')
        b2 = Button(f,
                    text="Reset",
                    height=2,
                    width=10,
                    command=lambda: self.reset())
        b2.grid(row=3, column=4, padx=10, sticky='w')
        f.pack()
        f.grid_propagate(0)

    def validate(self, login_window, login_type):
        username = self.e_username.get()
        pwd = self.e_password.get()
        if login_type == "Admin":
            query = "Select * from world.Admin where AdminName= %s and AdminPassword=%s"
        else:
            query = "Select * from world.Customer where CustomerName= %s and CustomerPassword=%s"
        parameters = (username, pwd)
        result = DatabaseHelper.get_data(query, parameters)
        if result is None or len(result) == 0:
            messagebox.showerror("Login Failed", "Incorrect credentials")
            login_window.tkraise()
            self.e_username.focus()
        else:
            messagebox.showinfo('Login Success',
                                "Login successfully completed")
            # Destroying the temporary window created for login
            login_window.destroy()
            self.f.destroy()
            self.panel.destroy()
            # the type of login was admin so go to adminhomepage
            if login_type == "Admin":
                import adminpage
                self.redirect = adminpage.AdminHomePage(self.root, result)
            else:
                # the type of login was user, so go to user home page
                import customerpage
                self.redirect = customerpage.CustomerHomePage(
                    self.root, result)
        print(username)
        print(pwd)

    def sign_up_form(self):
        text_font = ("MS Serif", 12)
        registration_window = Toplevel()
        f = Frame(registration_window, width=650, height=400, bg="Gray")
        Message(f,
                width=300,
                font=("Monotype Corsiva", 20, "bold", "italic"),
                text="FoodzApp Services",
                bg="white",
                relief=SOLID,
                borderwidth=2).grid(row=0, column=0, columnspan=3, pady=5)
        Message(f,
                text="Register with us to get the best of food experience",
                width=600,
                font="Roman 20 bold italic",
                bg="white",
                relief=SOLID,
                borderwidth=2).grid(row=1, column=0, columnspan=3)
        f.pack()
        l = Label(f, text="Name", font=text_font)
        l.grid(row=2, column=0, padx=10, pady=10)
        self.register_e1 = Entry(f)
        self.register_e1.grid(row=2, column=1, padx=10, pady=10)
        self.register_e1.focus_set()
        l = Label(f, text="Contact", font=text_font)
        l.grid(row=3, column=0, padx=10, pady=10)
        self.register_e2 = Entry(f)
        self.register_e2.grid(row=3, column=1, padx=10, pady=10)
        l = Label(f, text="Email Id", font=text_font)
        l.grid(row=4, column=0, padx=10, pady=10)
        self.register_e3 = Entry(f)
        self.register_e3.grid(row=4, column=1, padx=10, pady=10)
        l = Label(f, text="Password", font=text_font)
        l.grid(row=5, column=0, padx=10, pady=10)
        self.register_e4 = Entry(f, show="*")
        self.register_e4.grid(row=5, column=1, padx=10, pady=10)
        l = Label(f, text="Re-enter Password", font=text_font)
        l.grid(row=6, column=0, padx=10, pady=10)
        self.register_e5 = Entry(f, show="*")
        self.register_e5.grid(row=6, column=1, padx=10, pady=10)
        b1 = Button(f,
                    text="Register",
                    width=20,
                    height=2,
                    bg="white",
                    fg="black",
                    activebackground="gray",
                    command=lambda: self.register_user(registration_window))
        b1.grid(row=7, column=0, padx=10, pady=10, sticky="e")
        b2 = Button(f,
                    text="Reset",
                    width=20,
                    height=2,
                    bg="white",
                    fg="black",
                    activebackground="gray",
                    command=self.register_reset)
        b2.grid(row=7, column=1, padx=10, pady=10, sticky="w")
        f.grid_propagate(0)

    def register_reset(self):
        self.register_e1.delete(0, END)
        self.register_e2.delete(0, END)
        self.register_e3.delete(0, END)
        self.register_e4.delete(0, END)
        self.register_e5.delete(0, END)

    def register_user(self, registration_window):
        name = self.register_e1.get()
        contact = self.register_e2.get()
        email = self.register_e3.get()
        pwd = self.register_e4.get()
        pwd2 = self.register_e5.get()
        if name == "" or contact == "" or email == "" or pwd == "":
            messagebox.showwarning("Mandatory fields",
                                   "Please fill all the fields")
            registration_window.tkraise()
        elif pwd != pwd2:
            messagebox.showerror("Password Error",
                                 "Passwords don't match.Please re-enter")
            registration_window.tkraise()
        else:
            query = "Insert into Customer(CustomerName, CustomerPassword,CustomerContact, CustomerEmailId) Values (%s,%s,%s,%s)"
            args = (name, pwd, contact, email)
            DatabaseHelper.execute_query(query, args)
            messagebox.showinfo("Success",
                                "User registered successfully. Please login")
            registration_window.destroy()
class CustomerHomePage(DefaultPage):
    def __init__(self, root, customer_details):
        super().__init__(root)
        # store customer details tuple here
        self.details = customer_details
        self.root.state('zoomed')
        # create dictionary for food menu items
        self.dct_IntVar = {}
        self.m = WhiteMessage(self.panel, text=f"Welcome {self.details[1]}")
        self.m.place(x=50, y=20)
        self.add_buttons()
        # Add the menu frame that has an image
        self.add_menu()

    def add_buttons(self):
        # Add 3 buttons- logout, check order status, order history
        self.logout = WhiteButton(self.f,
                                  text="Logout",
                                  command=self.customer_logout)
        self.logout.place(x=800, y=30)

        self.order_history_button = GrayButton(self.f,
                                               text="Check your order history",
                                               command=self.recent_orders)
        self.order_history_button.place(x=70, y=110)

        self.order_status_button = GrayButton(self.f,
                                              text="View Order Status",
                                              command=self.view_order_status)
        self.order_status_button.place(x=650, y=110)

    def customer_logout(self):
        import MainPage
        self.f.destroy()
        self.redirect = MainPage.MainPage(self.root)

    def recent_orders(self):
        query = """Select FoodDetails, FoodTotal,IsComplete,OrderDate
                from FoodOrder
                where CustomerId=%s
                order by FoodOrderId DESC"""
        parameters = (self.details[0], )
        result = DatabaseHelper.get_all_data(query, parameters)

        self.recent_orders_table = SimpleTable(self.f,
                                               rows=len(result),
                                               columns=len(result[0]),
                                               width=570,
                                               height=600)
        self.recent_orders_table.grid_propagate(0)
        self.recent_orders_table.place(x=30, y=170)
        for i in range(len(result)):
            for j in range(len(result[0])):
                if j == 0:
                    self.recent_orders_table.set(row=i,
                                                 column=j,
                                                 value=result[i][j],
                                                 width=50)
                else:
                    self.recent_orders_table.set(row=i,
                                                 column=j,
                                                 value=result[i][j],
                                                 width=10)

    def view_order_status(self):
        query = """
            Select FoodDetails,FoodTotal 
            from FoodOrder
            where CustomerId=%s
            and IsComplete=0
            order by FoodOrderId
        """
        parameters = (self.details[0], )

        result = DatabaseHelper.get_data(query, parameters)
        # Eg=("pizza,pasta",300)
        if result is None:
            messagebox.showinfo("Orders complete", "No orders pending")
        else:
            details = result[0]
            total = result[1]
            message = f"Currently preparing order for {details} and total amount {total}.Should be delivered soon"
            messagebox.showinfo("Order in progress", message)

    def add_menu(self):
        #  Add image, add 3 menu buttons
        # Add a button-> place order
        self.menu_frame = Frame(self.panel, height=600, width=600, bg="white")
        self.menu_frame.place(x=650, y=170)
        self.menu_frame.pack_propagate(0)

        self.raw_menu_image = Image.open("images/MenuBackground.jpg")
        self.raw_menu_image = self.raw_menu_image.resize((600, 600))
        self.menu_img = ImageTk.PhotoImage(self.raw_menu_image)
        self.menu_panel = Label(self.menu_frame, image=self.menu_img)
        self.menu_panel.pack()

        self.food_menu_button = GrayButton(
            self.menu_frame,
            text="Food Menu",
            command=lambda: self.add_menu_items("Starters"))
        self.food_menu_button.place(x=30, y=550)

        self.drinks_menu_button = GrayButton(
            self.menu_frame,
            text="Drinks Menu",
            command=lambda: self.add_menu_items("Drinks"))
        self.drinks_menu_button.place(x=230, y=550)

        self.dessert_menu_button = GrayButton(
            self.menu_frame,
            text="Dessert Menu",
            command=lambda: self.add_menu_items("Desserts"))
        self.dessert_menu_button.place(x=430, y=550)

        self.place_order_button = GrayButton(self.f,
                                             text="Place Order",
                                             command=self.place_order)
        self.place_order_button.place(x=900, y=110)

    def place_order(self):
        selected_items = []
        for key, item in self.dct_IntVar.items():
            if item.get() == 1:
                selected_items.append(key)

        if len(selected_items) == 0:
            messagebox.showwarning(
                "No order", "Please select atleast one food order to execute")

        else:
            query = """Select FoodName,FoodPrice
                            from FoodMenu
                            where FoodName in (%s)"""
            result = DatabaseHelper.get_all_data_multiple_input(
                query, selected_items)
            self.order_confirmation(result)

    def order_confirmation(self, result):
        print(f"Result is {result}")
        confirmation_window = Toplevel()
        confirmation_window.title('Confirm your order')
        f = SimpleTable(confirmation_window,
                        rows=len(result),
                        columns=len(result[0]),
                        height=300,
                        width=300)
        f.pack()

        for i in range(len(result)):
            for j in range(len(result[0])):
                f.set(row=i, column=j, value=result[i][j])

        b1 = Button(f,
                    text="Confirm",
                    height=2,
                    width=10,
                    command=lambda: self.send_order_to_admin(
                        result, confirmation_window))
        b1.grid(row=len(result), column=0, padx=10, sticky='e')

        b2 = Button(f,
                    text="Reset",
                    height=2,
                    width=10,
                    command=lambda: self.reset_menu(confirmation_window))
        b2.grid(row=len(result), column=1, padx=10, sticky='w')

    def reset_menu(self, confirmation_window):
        confirmation_window.destroy()
        for key, value in self.dct_IntVar.items():
            if value.get() == 1:
                self.dct_IntVar[key].set(0)

    def send_order_to_admin(self, result, temp_window):
        temp_window.destroy()
        print(f"Result is {result}")

        food_details = map(lambda x: x[0], result[1:])
        food_details = ",".join(food_details)

        total_price = map(lambda x: x[1], result[1:])
        total_price: Union[int, Any] = sum(total_price)

        print(food_details)
        print(total_price)

        query = """Insert into FoodOrder(CustomerId,FoodDetails,FoodTotal,OrderDate)
        Values(%s,%s,%s,%s)"""
        parameters = (self.details[0], food_details, total_price,
                      datetime.datetime.today().date())
        DatabaseHelper.execute_query(query, parameters)
        message = f"Your order for {food_details} and total amount {total_price} is with us.Should be delivered soon"
        messagebox.showinfo("Order Placed", message)

    def add_menu_items(self, food_type):
        query = """Select FoodMenuId,FoodName,FoodPrice
                from FoodMenu
                where FoodType=%s
        """
        parameters = (food_type, )
        result = DatabaseHelper.get_all_data(query, parameters)

        self.menu_items_frame = SimpleTable(self.menu_frame,
                                            rows=len(result),
                                            columns=len(result[0]),
                                            height=500,
                                            width=500)
        self.menu_items_frame.place(x=30, y=30)
        self.menu_items_frame.grid_propagate(0)
        self.text_font = ("MS Serif", 12)

        for i in range(1, len(result)):
            # Storing foodname as the key of dictionary
            self.dct_IntVar[result[i][1]] = IntVar()

        for i in range(len(result)):
            for j in range(len(result[0])):
                if j == 0 and i != 0:
                    c = Checkbutton(self.menu_items_frame,
                                    text=result[i][j],
                                    font=self.text_font,
                                    variable=self.dct_IntVar.get(
                                        result[i][1]))  # to get FoodName
                    self.menu_items_frame.set(row=i,
                                              column=j,
                                              value=result[i][j],
                                              widget=c)
                else:
                    self.menu_items_frame.set(row=i,
                                              column=j,
                                              value=result[i][j],
                                              width=25)
class AdminHomePage(DefaultPage):
    def __init__(self, root, admin_details):
        print("Admin home page called")
        super().__init__(root)
        self.root.state('zoomed')  # Maximize the screen
        # Tuple received from DATABASE. Eg=> (2, 'Ritesh', 'SGT', '*****@*****.**', 'RiteshPic3.jpg')
        self.details = admin_details
        # Dictionary to store the pending order checkbox IntVars
        self.dct_IntVar = {}

        self.admin_page = WhiteMessage(self.f, text="Admin Page")
        self.admin_page.place(x=320, y=20)
        self.add_admin_details()
        self.add_buttons()

    def add_admin_details(self):
        # Add image of admin
        # Add Name of admin as Message
        # Add email of admin as Message
        print(self.details)
        self.admin_raw_image = Image.open('images/' + self.details[4])
        self.admin_raw_image.resize((100, 180))
        self.profile_pic = ImageTk.PhotoImage(self.admin_raw_image)
        # ensure this size is same as image size, also we can use label instead of this
        self.c = Canvas(self.f, width=100, height=180)
        # give the starting cordinates wrt canvas i.e 0,0
        self.canvas_pic = self.c.create_image(0,
                                              0,
                                              image=self.profile_pic,
                                              anchor=NW)
        self.c.place(x=40, y=100)
        # message that displays admin's name
        self.admin_name = WhiteMessage(self.f,
                                       text="Name= " + self.details[1],
                                       width=200)
        self.admin_name.place(x=40, y=300)
        # message that displays admin's email address
        self.admin_email = WhiteMessage(self.f,
                                        text="Email " + self.details[3],
                                        width=300)
        self.admin_email.place(x=40, y=350)

    def add_buttons(self):
        # Add 3 buttons
        # View pending order
        # View recently completed order
        # logout

        # doesn't matter, you can add to the frame or panel(Label- for image)
        self.pending_button = WhiteButton(self.f, "View Pending Orders",
                                          self.view_pending_orders)
        self.pending_button.place(x=400, y=90)
        self.completed_button = WhiteButton(self.f,
                                            "View Recent Completed Orders",
                                            self.view_completed_orders)
        self.completed_button.place(x=600, y=90)
        self.logout = WhiteButton(self.f,
                                  "Logout",
                                  self.admin_logout,
                                  width=10)
        self.logout.place(x=800, y=20)

    def view_completed_orders(self):
        # same as pending orders, only diff is we dont need checkbutton here
        query = """select FoodOrderId,CustomerName,FoodDetails,FoodTotal,OrderDate
                from FoodOrder fo
                join Customer c on fo.CustomerId=c.CustomerID
                where IsComplete=1
                order by FoodOrderId desc LIMIT 10"""
        result = DatabaseHelper.get_all_data(query)
        self.execute_button.place_forget()
        self.menu_frame = SimpleTable(self.f,
                                      rows=len(result),
                                      columns=len(result[0]),
                                      height=500,
                                      width=660)
        self.menu_frame.place(x=500, y=200)
        self.menu_frame.grid_propagate(0)

        for i in range(len(result)):
            for j in range(len(result[0])):
                self.menu_frame.set(row=i, column=j, value=result[i][j])

    def execute_order(self):
        selected_items = []
        for key, value in self.dct_IntVar.items():
            if value.get() == 1:
                selected_items.append(key)
                self.dct_IntVar[key].set(0)
        print(selected_items)
        if len(selected_items) == 0:
            messagebox.showwarning(
                "No order", "Please select atleast one food order to execute")
        else:
            query = """Update world.FoodOrder 
                    Set IsComplete=1
                    where FoodOrderId in (%s)"""
            DatabaseHelper.execute_all_data_multiple_input(
                query, selected_items)
            messagebox.showinfo("Success",
                                f"Order Id(s) {selected_items} executed")
            self.view_pending_orders()

    def view_pending_orders(self):
        # Add execute button
        # Add table that shows pending orders with checkbutton
        self.execute_button = WhiteButton(self.f, "Execute Order",
                                          self.execute_order)
        self.execute_button.place(x=500, y=150)
        query = """select FoodOrderId,CustomerName,FoodDetails,FoodTotal,OrderDate
                from Customer c 
                join FoodOrder fo 
                on c.CustomerId=fo.CustomerId
                where fo.IsComplete=0 """
        result = DatabaseHelper.get_all_data(query)
        print(result)

        self.menu_frame = SimpleTable(self.f,
                                      rows=len(result),
                                      columns=len(result[0]),
                                      height=500,
                                      width=650)
        self.menu_frame.place(x=500, y=200)
        self.menu_frame.grid_propagate(0)
        self.text_font = ("MS Serif", 12)

        for i in range(1, len(result)):
            # store FoodOrderID as key and a checkbutton variable as value
            self.dct_IntVar[result[i][0]] = IntVar()

        for i in range(len(result)):
            for j in range(len(result[0])):
                if j == 0 and i != 0:
                    # Put checkbutton in the all first column apart from the first row
                    c = Checkbutton(self.menu_frame,
                                    text=result[i][j],
                                    font=self.text_font,
                                    variable=self.dct_IntVar.get(result[i][j]))
                    self.menu_frame.set(row=i,
                                        column=j,
                                        value=result[i][j],
                                        widget=c)
                else:
                    self.menu_frame.set(row=i, column=j, value=result[i][j])

    def admin_logout(self):
        import MainPage
        self.f.destroy()
        self.panel.destroy()
        self.redirect = MainPage.MainPage(self.root)