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 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 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 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 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 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 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 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 __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 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 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 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 cart_api_delete(): if is_authenticated(request) and not is_staff(request): json_dat = request.get_json(force=True) 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(): product_id = int(json_dat["id"]) cart.remove_item(product_id) dat_loader.write_data("Carts", cart_list, False) return Response(status=200) else: counter += 1 if counter == len(cart_list): return abort(500)
def register(): form = RegistrationForm() if request.method == "POST": user_dat = dat_loader.load_data("Users") user_id = user_dat["id"] user_list = user_dat["data"] a = Address(form.address.data, form.postal.data, form.country.data, form.city.data) c1 = Customer(user_id, form.firstName.data, form.lastName.data, form.password.data, form.gender.data, form.email.data.lower(), a, form.phoneNumber.data) user_list.append(c1) dat_loader.write_data("Users", user_list) return redirect("/login/") elif request.method == "GET": return render_template("home/register.html", form=form)
def cart_api_confirm(): domain_name = "http://127.0.0.1:5000" if is_authenticated(request) and not is_staff(request): json_dat = request.get_json(force=True) 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(): for x in json_dat: q = int(x["quantity"]) product_id = int(x["id"]) cart.update_item(product_id, q) dat_loader.write_data("Carts", cart_list, False) item_list = cart.get_items() stripe_items = [] for item in item_list: product = item.product item_img_list = [] img_url = domain_name + product.pic_link item_img_list.append(img_url) item_price = int(float(product.retail_price) * 100) item_dict = { "name": product.get_title(), "description": product.get_description()[:100], "images": item_img_list, "amount": item_price, "currency": "sgd", "quantity": item.quantity } stripe_items.append(item_dict) stripe.api_key = app.config["STRIPE_SECRET"] session = stripe.checkout.Session.create( payment_method_types=["card"], line_items=stripe_items, success_url=domain_name + "/api-service/payment/success/", cancel_url=domain_name + "/checkout/cart/", ) json_response = {"status": "ok", "id": session["id"]} return jsonify(json_response) else: counter += 1 if counter == len(cart_list): return abort(500) else: return abort(403)
def cart_api_add(): if is_authenticated(request) and not is_staff(request): cart_list = dat_loader.load_data("Carts")["data"] user = get_user(request) counter = 0 form = AddCart() if form.validate_on_submit(): for cart in cart_list: if cart.get_user() == user.get_id(): product_id = int(form.id.data) quantity = form.quantity.data cart.add_item(product_id, quantity) else: counter += 1 if counter == len(cart_list): return abort(500) dat_loader.write_data("Carts", cart_list, False) return redirect("/dashboard/products/")
def customer_account_manage_pass(): if is_authenticated(request): form = AccountPasswordChange() if request.method == "GET": return render_template("pages/account_settings_password.html", staff=is_staff(request), user=get_user(request), form=form) 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.Change_password(form.n_pass.data) dat_loader.write_data("Users", user_list, False) return redirect("/dashboard/account/") else: return redirect("/login/")
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 ticket_detail(id): if is_authenticated(request): user = get_user(request) form = NewMessageForm() ticket_list = dat_loader.load_data("Tickets")["data"] if request.method == "GET": count = 0 for ticket in ticket_list: if ticket.get_id() == id: if ticket.get_staff_usr_id() == user.get_id( ) or ticket.created_by.get_id() == user.get_id(): return render_template("pages/ticket_detail.html", ticket=ticket, user=user, staff=is_staff(request), form=form) else: return abort(403) else: count += 1 if count == len(ticket_list): return abort(404) elif request.method == "POST" and form.validate_on_submit(): for ticket in ticket_list: if ticket.get_id() == int(form.id.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) m1 = Message(user, uploaded_files, None) else: m1 = Message(user, [], form.message.data) ticket.add_new_reply(m1) dat_loader.write_data("Tickets", ticket_list, False) return redirect( url_for("ticket_detail", id=ticket.get_id())) else: return redirect("/login/")
def __init__(self, id, created_by, subject, message_list): # messages must be a list self.__id = id self.created_by = created_by self.subject = subject self.__message_list = message_list self.__closed = False self.__created_on = time.time() # Assign ticket to a staff user_list = dat_loader.load_data("Users")["data"] count_list = [] for user in user_list: if isinstance(user, Staff): count_list.append(user.customer_count) min_c = min(count_list) for user in user_list: if isinstance(user, Staff): if user.customer_count == min_c: self.__assigned_to = user user.customer_count += 1 break dat_loader.write_data("Users", user_list, False)
def user_account_update_email(): if is_authenticated(request): dat = request.get_json(force=True) c_user = get_user(request) user_list = dat_loader.load_data("Users")["data"] e_list = [] for user in user_list: e_list.append(user.email) counter = 0 email_regex = re.compile( r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)") for user in user_list: if user.get_id() == c_user.get_id(): if dat["data"] in e_list: return jsonify({ "success": "false", "message": "Your email address cannot match with a existing user" }) elif email_regex.fullmatch(dat["data"]): user.email = dat["data"] dat_loader.write_data("Users", user_list, False) return jsonify({ "success": "true", "new_email": user.email }) else: return jsonify({ "success": "false", "message": "Invalid email address" }) else: counter += 1 if counter == len(user_list): return abort(404) else: return abort(403)
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/")
def user_account_update_number(): 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 number_list = [] for user in user_list: number_list.append(user.contact_number) for user in user_list: if user.get_id() == c_user.get_id(): if dat["data"] in number_list: return jsonify({ "success": "false", "message": "Your number cannot match with a existing user" }) elif len(dat["data"]) != 8 or not dat["data"].isnumeric(): return jsonify({ "success": "false", "message": "Invalid phone number" }) else: user.contact_number = dat["data"] dat_loader.write_data("Users", user_list, False) return jsonify({ "success": "true", "new_number": user.contact_number }) else: counter += 1 if counter == len(user_list): return abort(404) else: return abort(403)
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)
for z in range(0, random.randint(2, 4)): product = random.choice(product_list) if len(s_list) != 0: while True: counter = 0 for sale in s_list: if sale.product.get_id() == product.get_id(): product = random.choice(product_list) else: counter += 1 if counter == len(s_list): break s = Sale(sale_id, product, random.randint(1, 5), ts) sale_id += 1 sale_list.append(s) s_list.append(s) for sale in s_list: total += float(sale.sub_total) o = Order(order_id, s_list, str(round(total, 2)), user, ts) ran_status = random.randint(1, 3) if ran_status == 1: o.mark_shipped() elif ran_status == 2: o.mark_shipped() o.mark_complete() order_id += 1 order_list.append(o) dat_loader.write_data("Sales", sale_list) dat_loader.write_data("Orders", order_list)
"98362626", "*****@*****.**") user_id += 1 s2 = Staff(user_id, "dy_staff", "Dylan", "Liew", "password", "Male", "94956325", "*****@*****.**") user_id += 1 a = Address("2 Ang Mo Kio Street 44", "569250", "Singapore", "Singapore") c = Customer(user_id, "Joel", "Peh", "password", "Male", "*****@*****.**", a, "98283783") r = requests.get( "https://randomuser.me/api/?inc=location,name,email,gender&results=9&nat=us" ) dat = json.loads(r.text)["results"] user_id += 1 user_list = [s1, s2, c] for x in dat: p_number = ["9"] for y in range(0, 7): p_number.append(str(random.randint(0, 9))) phone_number = "".join(p_number) address_dat = x["location"] street_dat = address_dat["street"] address = str(street_dat["number"]) + " " + street_dat["name"] postal_code = str(address_dat["postcode"]) + str(random.randint(0, 9)) name_dat = x["name"] a = Address(address, postal_code, "Singapore", "Singapore") c = Customer(user_id, name_dat["first"], name_dat["last"], "password", x["gender"].capitalize(), x["email"], a, phone_number) user_list.append(c) write_data("Users", user_list)
import load_helper as dat_loader import random cart_list = dat_loader.load_data("Carts")["data"] product_list = dat_loader.load_data("Products")["data"] for cart in cart_list: for x in range(0, 4): product = random.choice(product_list) cart.add_item(product.get_id(), random.randint(1, 4)) dat_loader.write_data("Carts", cart_list, False)
import load_helper as dat_loader from order import Cart dat_loader.write_data("Carts", []) carts = dat_loader.load_data("Carts")["data"] cart_dat = dat_loader.load_data("Carts") cart_id = cart_dat["id"] cart_list = cart_dat["data"] c = Cart(cart_id, 1, []) cart_list.append(c) dat_loader.write_data("Carts", cart_list)
def forget(): form_reset = PasswordResetForm() form_forget = ForgetPasswordForm() if form_forget.validate_on_submit(): user_email = form_forget.email.data user_list = dat_loader.load_data("Users")["data"] customer_list = [] for x in user_list: if isinstance(x, Customer): customer_list.append(x) for x in customer_list: if x.email == user_email: p_token = Pass_token(x.get_id()) m1 = Mail() m1.content = f""" <!DOCTYPE html> <html lang="en"> <body> <pre> Dear {x.get_name()}, You have requested to reset your password for your Eclectic account. Copy or paste the link below to your browser or click on the link to reset your password. The link will expire after 2 hours. <a href="{p_token.get_link()}">{p_token.get_link()}</a> Warmest regards, Eclectic Support Team </pre> </body> </html> """ m1.subject = "Eclectic Password Reset Link" m1.send(x.email) new_list = dat_loader.load_data("Tokens")["data"] new_list.append(p_token) dat_loader.write_data("Tokens", new_list, False) return redirect("/login/") elif request.args.get("auth") is None and not is_authenticated(request): return render_template("home/forget_password.html", form=form_forget) elif form_reset.validate_on_submit(): user_id = int(form_reset.id.data) new_pass = form_reset.password1.data confirm_pass = form_reset.password2.data if new_pass == confirm_pass: user_list = dat_loader.load_data("Users")["data"] for x in user_list: if x.get_id() == user_id: x.Change_password(new_pass) dat_loader.write_data("Users", user_list, False) return redirect("/login/") auth_token = request.args.get("auth") token_list = dat_loader.load_data("Tokens")["data"] for x in token_list: trial = x.use(auth_token) if trial is None: pass else: form_reset.id.data = trial dat_loader.write_data("Tokens", token_list, False) else: return abort(400) elif not is_authenticated(request): auth_token = request.args.get("auth") token_list = dat_loader.load_data("Tokens")["data"] for x in token_list: trial = x.use(auth_token) if trial is None: pass else: form_reset.id.data = trial return render_template("home/new_password.html", form=form_reset) return redirect("/login/")
return f_obj.get_link() p1 = Product(0, "Eclectic TWS earbuds", p1_desc, 20, "250", "40", upload("earbuds.jpg")) p2 = Product(1, "Eclectic headphone", p2_desc, 10, "105.99", "30", upload("headphone.jpg")) p3 = Product(2, "Eclectic gaming laptop", p3_desc, 5, "4109.99", "3000", upload("laptop.jpeg")) p4 = Product(3, "Eclectic F9 smartphone", p4_desc, 40, "1800", "550", upload("f9.jpg")) p5 = Product(4, "Eclectic C6 smartphone", p5_desc, 20, "1000", "200", upload("c6.jpg")) p6 = Product(5, "Eclectic TV 65''", p6_desc, 10, "4000", "2300", upload("TV.jpg")) p7 = Product(6, "20000 mAh Eclectic powerbank", p7_desc, 200, "54.99", "20", upload("powerbank.jpg")) p_list.append(p1) p_list.append(p2) p_list.append(p3) p_list.append(p4) p_list.append(p5) p_list.append(p6) p_list.append(p7) for x in p_list: print("%s: %s" % (x.get_title(), x.pic_link)) dat_loader.write_data("Products", p_list)