def inventory_change(id): if is_authenticated(request) and is_staff(request): update_form = CreateProduct() if request.method == "POST": products = dat_loader.load_data("Products")["data"] for product in products: if product.get_id() == id: product.set_title(update_form.title.data) product.set_cost_price(update_form.cost_price.data) product.retail_price = update_form.retail_price.data product.set_description(update_form.description.data) product.stock = int(update_form.stock.data) dat_loader.write_data("Products", products, False) return redirect("/dashboard/inventory/") else: products = dat_loader.load_data("Products")["data"] for product in products: if product.get_id() == id: update_form.title.data = product.get_title() update_form.cost_price.data = product.get_cost_price() update_form.retail_price.data = product.retail_price update_form.description.data = product.get_description() update_form.stock.data = product.stock return render_template( "pages/staff_pages/update_inventory.html", product=product, form=update_form, user=get_user(request), staff=is_staff(request)) else: return redirect("/login/")
def get_user(request): sessions = dat_loader.load_data("Session")["data"] user_id = int(request.cookies.get("userID")) session_id = request.cookies.get("sessionID") user_list = dat_loader.load_data("Users")["data"] for session in sessions: if session.get_id() == session_id and user_id == session.get_user_id(): for user in user_list: if user.get_id() == session.get_user_id(): return user
def view_products(): query = request.args.get("search") if query is None: products = dat_loader.load_data("Products")["data"] return render_template("home/view_products.html", products=products) else: products = dat_loader.load_data("Products")["data"] search_results = [] for product in products: if query.upper() in product.get_title().upper() or query.upper( ) in product.get_description().upper(): search_results.append(product) return render_template("home/search_products.html", products=search_results)
def delete_product(id): if is_authenticated(request) and is_staff(request): products = dat_loader.load_data("Products")["data"] cart_list = dat_loader.load_data("Carts")["data"] for product in products: if product.get_id() == id: for cart in cart_list: cart_items = cart.get_items() for item in cart_items: if item.product.get_id() == id: cart.remove_item(id) dat_loader.write_data("Carts", cart_list, False) products.remove(product) dat_loader.write_data("Products", products) return redirect("/dashboard/inventory/")
def get_stored_attrs(): product_list = dat_loader.load_data("Products")["data"] attributes = [] products = [] product_title = [] for product in product_list: attrs = product.get_attr()["attrs"] p_type = product.get_attr()["type"] title_tok = product.get_title().split() title_tok.remove("Eclectic") title = " ".join(title_tok) product_title.append(title) if p_type == "powerbank": mapping["charge"] = "charging" mapping["battery"] = "battery life" elif p_type == "TV": mapping["type"] = "" for key in attrs.keys(): separated = key.replace("_", " ") rephrased_sep = rephrase(separated, mapping) attributes.append(rephrased_sep) p_split = p_type.split("-") for x in p_split: products.append(x) attributes.append("price") return { "attributes": attributes, "products": products, "title": product_title }
def add_item(self, product_id, quantity): product_list = dat_loader.load_data("Products")["data"] item_list = self.__item_list counter = 0 for product in product_list: if product.get_id() == product_id: if len(item_list) == 0: product_obj = product s = CartItem(product_obj, quantity) self.__item_list.append(s) total = float(self.__total) total += float(s.sub_total) self.__total = str(round(total, 2)) else: counter2 = 0 for item in item_list: if item.product.get_id() == product_id: c_q = item.quantity c_q += quantity self.update_item(product_id, c_q) else: counter2 += 1 if counter2 == len(item_list): product_obj = product s = CartItem(product_obj, quantity) self.__item_list.append(s) total = float(self.__total) total += float(s.sub_total) self.__total = str(round(total, 2)) else: counter += 1 if counter == len(product_list): raise Exception("No such product")
def product_detail(id): products = dat_loader.load_data("Products")["data"] for product in products: if product.get_id() == id: return render_template("home/product_details.html", product=product) return abort(404)
def customer_account_manage_address(): if is_authenticated(request) and not is_staff(request): form = AccountAddressChange() if request.method == "GET": user = get_user(request) form.address.data = user.get_address_line() form.city.data = user.get_address_city() form.country.data = user.get_country() form.postal.data = user.get_address_postal() return render_template( "pages/customer_pages/account_settings_address.html", form=form, staff=is_staff(request), user=user) elif request.method == "POST" and form.validate_on_submit(): c_user = get_user(request) user_list = dat_loader.load_data("Users")["data"] for user in user_list: if user.get_id() == c_user.get_id(): user.set_address(form.address.data, form.postal.data, form.country.data, form.city.data) dat_loader.write_data("Users", user_list, False) return redirect("/dashboard/account/") else: return redirect("/dashboard/account/") elif is_authenticated(request) and is_staff(request): return abort(403) else: return redirect("/login/")
def new_ticket(): if is_authenticated(request) and not is_staff(request): form = NewTicketForm() if request.method == "GET": return render_template("pages/customer_pages/ticket_create.html", staff=is_staff(request), user=get_user(request), form=form) elif request.method == "POST" and form.validate_on_submit(): user = get_user(request) ticket_dat = dat_loader.load_data("Tickets") messages = [] ticket_id = ticket_dat["id"] ticket_list = ticket_dat["data"] files = form.files.data uploaded_files = [] if files[0].filename != "": for x in files: try: uploaded_files.append(upload(x, False, user)) except ValueError: return abort(400) m_obj = Message(user, uploaded_files, form.description.data) messages.append(m_obj) t_obj = Ticket(ticket_id, user, form.subject.data, messages) ticket_list.append(t_obj) dat_loader.write_data("Tickets", ticket_list) return redirect("/dashboard/support/") elif is_authenticated(request) and is_staff(request): return abort(403) else: return redirect("/login/")
def user_account_validate_password(): if is_authenticated(request): dat = request.get_json(force=True) c_user = get_user(request) user_list = dat_loader.load_data("Users")["data"] counter = 0 for user in user_list: if user.get_id() == c_user.get_id(): if user.Check_password( dat["current"]) and dat["new"] == dat["confirm"]: return jsonify({"success": "true"}) elif not user.Check_password(dat["current"]): return jsonify({ "success": "false", "message": "Current password incorrect" }) else: return jsonify({ "success": "false", "message": "New passwords do not match" }) else: counter += 1 if counter == len(user_list): return abort(404) else: return abort(403)
def session_end(request): sessions = dat_loader.load_data("Session")["data"] session_id = request.cookies.get("sessionID") for session in sessions: if session.get_id() == session_id: session.logout() dat_loader.write_data("Session", sessions, False)
def upload(f, public=True, uploaded_by=None): if allowed_file(f.filename): filename = secure_filename(f.filename) file_path = os.path.join(upload_folder, filename) while True: if os.path.exists(file_path): file_name = filename.rsplit(".") name = file_name[0] name += str(secrets.randbelow(1000)) new_f_name = [name, file_name[1]] new_filename = ".".join(new_f_name) file_path = os.path.join(upload_folder, new_filename) else: break f.save(file_path) file_type = f.filename.rsplit('.', 1)[1].lower() file_size = size_readable(os.path.getsize(file_path)) file_dat = dat_loader.load_data("Files") file_id = file_dat["id"] if public: f_obj = Photo(file_id, file_path) else: f_obj = Attached_File(file_id, filename, file_path, file_type, file_size, uploaded_by) file_list = file_dat["data"] file_list.append(f_obj) dat_loader.write_data("Files", file_list) if not public: return f_obj else: return f_obj.get_link() else: raise ValueError("Invalid file type")
def view_orders(): if is_authenticated(request) and not is_staff(request): user = get_user(request) results = [] order_list = dat_loader.load_data("Orders")["data"] delivered = None if request.args.get("delivered") is None: for x in order_list: if x.get_customer_id() == user.get_id(): results.append(x) results.reverse() results.sort(key=lambda order: order.is_shipped()) results.sort(key=lambda order: not order.is_delivered()) results.reverse() elif request.args.get("delivered") == "false": delivered = False for x in order_list: if x.is_shipped() and not x.is_delivered( ) and x.get_customer_id() == user.get_id(): results.append(x) results.reverse() elif request.args.get("delivered") == "true": delivered = True for x in order_list: if x.is_delivered() and x.get_customer_id() == user.get_id(): results.append(x) results.reverse() return render_template("pages/customer_pages/view_orders.html", orders=results, user=user, delivered=delivered) else: return redirect("/login/")
def search_product(query): product_list = dat_loader.load_data("Products")["data"] query = " ".join(query) cosine_sim_list = [] for product in product_list: title = product.get_title().lower() title_tok = nltk.word_tokenize(title) del title_tok[0] title = " ".join(title_tok) cosine_sim = cosine_comparision(title, query) cosine_sim_list.append(cosine_sim) # print(f"Title:{title}, Query:{query.lower()}, score:{cosine_sim}") h_p = get_h_possibility(cosine_sim_list) if h_p["dupes"]: for x in h_p["dupe_list"]: if h_p["highest"] == x: r_list = [] for product in product_list: title = product.get_title().lower() title_tok = nltk.word_tokenize(title) del title_tok[0] title = " ".join(title_tok) cosine_sim = cosine_comparision(title, query) if cosine_sim == h_p["highest"]: r_list.append(product) p_query = pluralize(query.lower()) product_title_str = ", ".join( [product.get_title() for product in r_list]) return f"Sorry, you will need to be more specific, we have many {p_query}.\nWe sell {product_title_str}." else: if h_p["highest"] == 0: l_dis_list = [] for product in product_list: title = product.get_title().lower() title_tok = nltk.word_tokenize(title) del title_tok[0] title = " ".join(title_tok) l_dis = typo_compare(title, query.lower()) l_dis_list.append(l_dis) # print(f"Title:{title}, Query:{query.lower()}, score:{l_dis}") h_p = get_h_possibility(l_dis_list, True) if h_p["highest"] > 8: return None for product in product_list: title = product.get_title().lower() title_tok = nltk.word_tokenize(title) del title_tok[0] title = " ".join(title_tok) l_dis = typo_compare(title, query.lower()) if l_dis == h_p["highest"]: return product for product in product_list: title = product.get_title().lower() title_tok = nltk.word_tokenize(title) del title_tok[0] title = " ".join(title_tok) cosine_sim = cosine_comparision(title, query) if cosine_sim == h_p["highest"]: return product
def delete_product(id): if is_authenticated(request) and is_staff(request): products = dat_loader.load_data("Products")["data"] for product in products: if product.get_id() == id: products.remove(product) dat_loader.write_data("Products", products) return redirect("/dashboard/inventory/")
def is_authenticated(request): session_id = request.cookies.get("sessionID") if session_id is None: return False sessions = dat_loader.load_data("Session")["data"] for x in sessions: if x.get_id() == session_id and x.check(): return True
def upload(filename): file_path = os.path.join(base_path, filename) file_dat = dat_loader.load_data("Files") file_id = file_dat["id"] file_list = file_dat["data"] f_obj = Photo(file_id, file_path) file_list.append(f_obj) dat_loader.write_data("Files", file_list) return f_obj.get_link()
def inventory_update(self): product_list = dat_loader.load_data("Products")["data"] item_list = self.__item_list for i, item in enumerate(item_list): for product in product_list: if item.product.get_id() == product.get_id(): item.product = product item_list[i] = item self.__item_list = item_list
def login(): if is_authenticated(request): return redirect("/dashboard/") else: form = LoginForm() if request.method == "GET": form.username.data = "" form.password.data = "" return render_template("home/login.html", form=form) elif request.method == "POST" and form.validate_on_submit(): username = form.username.data.lower() password = form.password.data user_list = dat_loader.load_data("Users")["data"] counter = 0 for user in user_list: if isinstance( user, Customer ) and user.email == username and user.Check_password(password): s = Session(user) s_dat = dat_loader.load_data("Session")["data"] s_dat.append(s) dat_loader.write_data("Session", s_dat, False) resp = make_response(redirect("/dashboard/")) resp.set_cookie("userID", str(user.get_id()), httponly=True) resp.set_cookie("sessionID", s.get_id(), httponly=True) return resp elif isinstance(user, Staff) and user.get_staff_id( ) == username and user.Check_password(password): s = Session(user) s_dat = dat_loader.load_data("Session")["data"] s_dat.append(s) dat_loader.write_data("Session", s_dat, False) resp = make_response(redirect("/dashboard/")) resp.set_cookie("userID", str(user.get_id()), httponly=True) resp.set_cookie("sessionID", s.get_id(), httponly=True) return resp else: counter += 1 else: return abort(400)
def view_inventory(): if is_authenticated(request) and is_staff(request): products = dat_loader.load_data("Products")["data"] return render_template("pages/staff_pages/view_inventory.html", products=products, count=len(products), user=get_user(request), staff=is_staff(request)) else: return redirect("/login/")
def order_api_create(): if is_authenticated(request) and not is_staff(request): cart_list = dat_loader.load_data("Carts")["data"] user = get_user(request) counter = 0 for cart in cart_list: if cart.get_user() == user.get_id(): item_list = cart.get_items() sale_dat = dat_loader.load_data("Sales") sale_id = sale_dat["id"] sale_list = sale_dat["data"] order_sales = [] total = 0 product_list = dat_loader.load_data("Products")["data"] for item in item_list: product = item.product for obj in product_list: if obj.get_id() == product.get_id(): obj.stock -= int(item.quantity) s = Sale(sale_id, product, item.quantity, time.time()) sale_id += 1 sale_list.append(s) order_sales.append(s) total += float(s.sub_total) cart.clear() order_dat = dat_loader.load_data("Orders") order_id = order_dat["id"] order_list = order_dat["data"] o = Order(order_id, order_sales, str(round(total, 2)), user, time.time()) order_list.append(o) dat_loader.write_data("Sales", sale_list) dat_loader.write_data("Orders", order_list) dat_loader.write_data("Products", product_list, False) dat_loader.write_data("Carts", cart_list, False) return redirect("/dashboard/orders/") else: counter += 1 if counter == len(cart_list): return abort(500) else: return abort(403)
def is_staff(request): sessions = dat_loader.load_data("Session")["data"] user_id = int(request.cookies.get("userID")) session_id = request.cookies.get("sessionID") for session in sessions: if session.get_id() == session_id and user_id == session.get_user_id(): user = session.get_user() if isinstance(user, Staff): return True else: return False
def ticket_close(): if is_authenticated(request): data = request.json ticket_id = int(data["id"]) ticket_list = dat_loader.load_data("Tickets")["data"] for ticket in ticket_list: if ticket.get_id() == ticket_id: ticket.close() dat_loader.write_data("Tickets", ticket_list, False) return jsonify({"success": "true"}) else: return abort(403)
def dashboard_view_products_details(id): if is_authenticated(request) and not is_staff(request): refresh_session(request) products = dat_loader.load_data("Products")["data"] for product in products: if product.get_id() == id: return render_template( "pages/customer_pages/products_details.html", product=product, user=get_user(request), staff=is_staff(request)) return abort(404)
def __init__(self, id, first_name, last_name, password, gender, email, address, contact): super().__init__(id, first_name, last_name, password, gender, contact, email) self.__address = address # Customer's cart creation cart_dat = dat_loader.load_data("Carts") cart_id = cart_dat["id"] cart_list = cart_dat["data"] c = Cart(cart_id, id, []) cart_list.append(c) dat_loader.write_data("Carts", cart_list)
def get_file(id): file_list = dat_loader.load_data("Files")["data"] if len(file_list) == 0: abort(404) counter = 0 for x in file_list: if x.get_id() == id and isinstance(x, Photo): return send_file(x.get_file_path()) elif x.get_id() == id and is_authenticated(request) and isinstance( x, Attached_File): user = get_user(request) ticket_list = dat_loader.load_data("Tickets")["data"] m_list = [] for ticket in ticket_list: if ticket.created_by.get_id() == user.get_id(): m_list += ticket.get_messages() f_list = [] for message in m_list: m1_list = message.get_files() for file in m1_list: f_list.append(file) if x.get_uploaded_by().get_id() == user.get_id() or isinstance( user, Staff): return send_file(x.get_file_path()) else: count = 0 for file in f_list: if file.get_id() == x.get_id(): return send_file(x.get_file_path()) else: count += 1 if count == len(f_list): return abort(403) elif x.get_id() == id and not is_authenticated(request) and isinstance( x, Attached_File): return abort(403) else: counter += 1 if counter == len(file_list): return abort(404)
def user_deactivate(): if is_authenticated(request) and is_staff(request): user_list = dat_loader.load_data("Users")["data"] dat = request.get_json(force=True) for user in user_list: if user.get_id() == int(dat["id"]): user_list.remove(user) dat_loader.write_data("Users", user_list) return jsonify({"success": "true"}) elif is_authenticated(request) and not is_staff(request): return abort(403) else: return redirect("/login/")
def upload_attached(filename, user_obj): filename = secure_filename(filename) file_path = os.path.join(upload_folder, filename) file_type = filename.rsplit('.', 1)[1].lower() file_size = size_readable(os.path.getsize(file_path)) file_dat = dat_loader.load_data("Files") file_id = file_dat["id"] f_obj = Attached_File(file_id, filename, file_path, file_type, file_size, user_obj) file_list = file_dat["data"] file_list.append(f_obj) dat_loader.write_data("Files", file_list) return f_obj
def dashboard_view_products(): if is_authenticated(request) and not is_staff(request): refresh_session(request) query = request.args.get("search") if query is None: products = dat_loader.load_data("Products")["data"] return render_template("pages/customer_pages/products.html", products=products, user=get_user(request), staff=is_staff(request)) else: products = dat_loader.load_data("Products")["data"] search_results = [] for product in products: if query.upper() in product.get_title().upper() or query.upper( ) in product.get_description().upper(): search_results.append(product) return render_template("pages/customer_pages/search_products.html", products=search_results, user=get_user(request), staff=is_staff(request)) else: return redirect("/login/")
def add_inventory(): if is_authenticated(request) and is_staff(request): form = CreateProduct() upload_image = FileUploadForm() if request.method == "GET": return render_template("pages/staff_pages/add_inventory.html", form=form, upload_image=upload_image, user=get_user(request), staff=is_staff(request)) elif request.method == "POST": image = upload_image.file.data image_link = upload(image) products = dat_loader.load_data("Products")["data"] products_id = dat_loader.load_data("Products")["id"] new_product = Product(products_id, form.title.data, form.description.data, int(form.stock.data), form.retail_price.data, form.cost_price.data, image_link) products.append(new_product) dat_loader.write_data("Products", products) return redirect("/dashboard/inventory/") else: return redirect("/login/")