Пример #1
0
def order_status_change(order_id):
    if request.method == 'POST':
        order_status = request.form['order_status']
        order = Order.query.get(order_id)
        valid_status = [
            'pending', 'processing', 'shipped', 'cancelled', 'refunded'
        ]
        if order_status not in valid_status:
            return 'unknown order status'
        previous_status = order.status

        order.status = order_status
        order.update()

        context = mhelp.context()
        context.update({"previous_status": previous_status, "order": order})
        new_line = '\n'
        subject, from_email, to = 'Title', '*****@*****.**', f'{order.billing_detail.email}'
        text_content = f'Hi {order.billing_detail.first_name},{new_line}Just dropping you '\
            f'an email to notify you that your order with reference {order.get_ref()} has changed '\
            f'status from {previous_status} to {order.status}.{new_line}If you have any queries '\
            f'please do not hesistate to contact us.{new_line}Regards,{new_line}Your Team'
        html_content = mhelp.render("email_status_change.html", **context)
        msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
        msg.attach_alternative(html_content, "text/html")
        msg.send()
        flash(notify_success('Order Updated'))
        return mhelp.redirect_url('shopman.order_view', order_id=order_id)
Пример #2
0
def edit_sub_name(subcategory_id):
    if request.method == "POST":
        subcategory = SubCategory.query.get(subcategory_id)
        name = request.form["name"]
        if is_empty_str(name):
            flash(notify_warning("Name cannot be empty"))
            return redirect(
                url_for(
                    "category.manage_sub",
                    category_name=subcategory.category.name,
                )
            )
        category_name = subcategory.category.name
        existing = SubCategory.query.filter(
            (SubCategory.name == name) & (Category.name == category_name)
        ).first()
        if existing:
            flash(notify_warning("Name already exists for category"))
            return redirect(
                url_for(
                    "category.manage_sub",
                    category_name=subcategory.category.name,
                )
            )
        subcategory.name = name
        subcategory.update()
        flash(notify_success("Subcategory name updated successfully!"))
        return redirect(
            url_for(
                "category.manage_sub", category_name=subcategory.category.name
            )
        )
Пример #3
0
def delete(name):

    if is_empty_str(name):
        flash(notify_warning("Cannot delete a category with no name"))
        return redirect(url_for("category.dashboard"))

    if name != "uncategorised":

        category = Category.query.filter(Category.name == name).first()

        if not category:
            flash(notify_warning(f'Category "{name}" does not exist.'))
            return redirect(url_for("category.dashboard"))

        if category.subcategories:
            flash(
                notify_warning(
                    f'Please delete all subcategories for category "{name}"'
                )
            )
            return redirect(url_for("category.dashboard"))

        category.delete()
        flash(notify_success(f'Category "{name}" successfully deleted'))
        return redirect(url_for("category.dashboard"))

    flash(notify_warning("Cannot delete category uncategorised"))
    return redirect(url_for("category.dashboard"))
Пример #4
0
def cart_remove(product_barcode, size, color):
    if "cart" in session:
        Cart.remove(product_barcode, size, color)
        flash(notify_success("Removed!"))
        return mhelp.redirect_url("shop.cart")

    else:
        return mhelp.redirect_url("shop.cart")
Пример #5
0
def roles_add():
    if request.method == "POST":
        if not Role.query.filter(Role.name == request.form["name"]).first():
            role = Role(name=request.form["name"])
            role.save()
            flash(notify_success("Role successfully added"))
            return redirect(url_for("admin.roles"))
        flash(notify_warning("Role already exists"))
        return redirect(url_for("admin.roles"))
Пример #6
0
def roles_delete(role_id):
    role = Role.get_by_id(role_id)

    if role is None:
        flash(notify_warning("Unable to delete. Invalid role id"))
        return redirect(url_for("admin.roles"))

    role.delete()
    flash(notify_success("Role successfully deleted"))
    return redirect(url_for("admin.roles"))
Пример #7
0
def add():

    context = {}
    has_category = False

    if request.method == "POST":
        # convert name to lower case and remove leading
        # and trailing spaces
        name = request.form["name"].lower().strip()

        # case 1: do not allow adding empty category name
        if is_empty_str(name):
            flash(notify_warning("Category name cannot be empty"))
            return redirect(url_for("category.add"))

        # case 2: do not allow category name uncategorised
        # not sure if this is needed since if we add this
        # during initialization then this check will be covered
        # by case 3
        if name == "uncategorised" or name == "uncategorized":
            flash(notify_warning("Category cannot be named as uncategorised"))
            return redirect(url_for("category.add"))

        has_category = Category.category_exists(name)

        # case 3: do not allow adding existing category name
        if has_category:
            flash(notify_warning(f'Category "{name}" already exists'))
            return render_template("category/add.html", **context)

        # case 4: sucessfully add the category
        category = Category(name=name)
        try:
            if "photo" in request.files:
                file = request.files["photo"]

                filename = unique_sec_filename(file.filename)
                file.filename = filename
                categoryphotos.save(file)
                category.resources.append(
                    Resource(
                        type="image",
                        filename=filename,
                        category="category_image",
                    )
                )
        except flask_uploads.UploadNotAllowed as e:
            pass

        category.save()
        flash(notify_success(f'Category "{name}" added successfully'))
        return render_template("category/add.html", **context)

    context["has_category"] = str(has_category)
    return render_template("category/add.html", **context)
Пример #8
0
def roles_update():
    if request.method == "POST":
        role = Role.get_by_id(request.form["role_id"])

        if role is None:
            flash(notify_warning("Unable to update. Role does not exist"))
            return redirect(url_for("admin.roles"))

        role.name = request.form["role_name"]
        role.update()
        flash(notify_success("Role successfully updated"))

    return redirect(url_for("admin.roles"))
Пример #9
0
def delivery_add_option():
    if request.method == "POST":
        form = DeliveryOptionForm()
        if form.validate_on_submit():
            toadd = DeliveryOption()
            toadd.option = form.option.data
            toadd.price = float(form.price.data)
            toadd.insert()
            flash(notify_success("Option Added!"))
            return mhelp.redirect_url("shopman.delivery")
        else:
            flash_errors(form)
            return mhelp.redirect_url("shopman.delivery")
Пример #10
0
def payment_add_option():
    if request.method == "POST":
        form = PaymentOptionForm()
        if form.validate_on_submit():
            toadd = PaymentOption()
            toadd.name = form.name.data
            toadd.text = form.text.data
            toadd.insert()
            flash(notify_success("Option Added!"))
            return mhelp.redirect_url("shopman.payment")
        else:
            flash_errors(form)
            return mhelp.redirect_url("shopman.payment")
Пример #11
0
def edit_check(announce_id):

    if request.method == "POST":
        announcement = Announcement.query.get(announce_id)
        form = AnnounceForm(obj=announcement)
        if not form.validate_on_submit():
            flash_errors(form)
            return mhelp.redirect_url(
                mhelp.method("edit"), announce_id=announce_id
            )
        form.populate_obj(announcement)
        announcement.update()
        flash(notify_success("Announcement updated!"))
        return mhelp.redirect_url(mhelp.method("list"))
Пример #12
0
def login():
    context = {}
    login_form = LoginForm()
    context["form"] = login_form
    if request.method == 'POST':
        if login_form.validate_on_submit():
            email = login_form.email.data
            password = login_form.password.data
            user = User.query.filter(User.email == email).first()
            print(email, password, user)
            if user is None or not user.check_hash(password):
                flash('')
                flash(notify_danger("please check your user id and password"))
                return redirect(url_for("www.index"))
            login_user(user)
            if user.is_admin:
                flash(notify_success('Successfully logged in!'))
                return redirect(url_for("dashboard.index"))
            elif user.is_customer:
                flash(notify_success('Successfully logged in!'))
                return redirect(url_for("shop.homepage"))

    return render_template("auth/login.html", **context)
Пример #13
0
def payment_option_update():
    if request.method == "POST":

        opt_id = request.form["id"]
        option_data = request.form["name"]
        text_data = request.form["text"]

        option = PaymentOption.query.get(opt_id)
        option.name = option_data
        option.text = text_data
        option.update()

        flash(notify_success("Option updated!"))
        return mhelp.redirect_url("shopman.payment")
Пример #14
0
def delivery_option_update():
    if request.method == "POST":

        opt_id = request.form["id"]
        option_data = request.form["option"]
        price_data = request.form["price"]

        option = DeliveryOption.query.get(opt_id)
        option.option = option_data
        option.price = price_data
        option.update()

        flash(notify_success("Option updated!"))
        return mhelp.redirect_url("shopman.delivery")
Пример #15
0
def index():
    context = base_context()

    for module in os.listdir(os.path.join(current_app.config['BASE_DIR'], "modules")):
        if module.startswith("__"):
            continue
        if module not in ["control_panel"]:
            with open(os.path.join(current_app.config['BASE_DIR'], 'modules', module, 'info.json')) as f:
                module_info = json.load(f)
                all_info[module] = module_info

    context["all_info"] = all_info
    flash(notify_success('Notif test'))
    return render_template("control_panel/index.html", **context)
Пример #16
0
def coupon_add():
    if request.method == "POST":
        form = CouponForm()
        if form.validate_on_submit():
            toadd = Coupon()
            toadd.string = form.string.data
            toadd.type = form.type.data
            toadd.value = form.value.data
            toadd.insert()
            flash(notify_success("Coupon Added!"))
            return mhelp.redirect_url("shopman.coupon")
        else:
            flash_errors(form)
            return mhelp.redirect_url("shopman.coupon")
Пример #17
0
def coupon_update():
    if request.method == "POST":
        form = CouponForm()
        if form.validate_on_submit:
            coupon_id = request.form["id"]
            coupon = Coupon.query.get(coupon_id)
            coupon.string = form.string.data
            coupon.type = form.type.data
            coupon.value = form.value.data
            coupon.update()

            flash(notify_success("Coupon updated!"))
            return mhelp.redirect_url("shopman.coupon")
        else:
            flash_errors(form)
            return mhelp.redirect_url("shopman.coupon")
Пример #18
0
def admin_delete(id):
    """
               **Delete a User**

    :param id: id of the user
    :type id: int

    """
    user = User.query.get(id)

    if user is None:
        flash(notify_warning("Unable to delete. Invalid user id"))
        return redirect("/admin")

    user.delete()
    flash(notify_success("User successfully deleted"))
    return redirect("/admin")
Пример #19
0
def validate_message():
    if request.method == "POST":
        form = ContactForm()
        if not form.validate_on_submit():
            flash_errors(form)
            return redirect(url_for("contact.index"))

        name = form.name.data
        email = form.email.data
        message = form.message.data

        contact_message = ContactMessage(name=name,
                                         email=email,
                                         message=message)
        contact_message.insert()
        flash(notify_success("Message submitted!"))
        return redirect(url_for("contact.index"))
Пример #20
0
def index():
    context = {}

    for folder in os.listdir(
            os.path.join(current_app.config["BASE_DIR"], "modules")):
        if folder.startswith("__"):
            continue
        elif folder.startswith("box__"):
            for sub_folder in os.listdir(
                    os.path.join(current_app.config["BASE_DIR"], "modules",
                                 folder)):
                if sub_folder in ["dashboard"]:
                    continue
                if sub_folder.startswith("__"):  # ignore __pycache__
                    continue
                elif sub_folder.endswith(".json"):  # box_info.json
                    continue
                with open(
                        os.path.join(
                            current_app.config["BASE_DIR"],
                            "modules",
                            folder,
                            sub_folder,
                            "info.json",
                        )) as f:
                    module_info = json.load(f)
                    all_info[sub_folder] = module_info
        else:

            if folder not in ["dashboard"]:
                with open(
                        os.path.join(
                            current_app.config["BASE_DIR"],
                            "modules",
                            folder,
                            "info.json",
                        )) as f:
                    module_info = json.load(f)
                    all_info[folder] = module_info

    context["all_info"] = all_info
    flash(notify_success("Notif test"))
    return render_template("dashboard/index.html", **context)
Пример #21
0
def register():

    context = {}
    reg_form = RegistrationForm()
    context["form"] = reg_form

    if request.method == "POST":

        if reg_form.validate_on_submit():

            email = reg_form.email.data
            password = reg_form.password.data

            # add the user to the db
            User.create(email=email, password=password)

            flash(notify_success("Registered successfully! Please Log In"))
            return redirect(url_for("auth.login"))

    return render_template("auth/register.html", **context)
Пример #22
0
def admin_update():
    """
    **Update a User record**

    """
    id = request.form["id"]
    password = request.form["password"]
    email = request.form["email"]
    first_name = request.form["first_name"]
    last_name = request.form["last_name"]
    is_admin = request.form.get("is_admin")

    if is_admin:
        is_admin = True
    else:
        is_admin = False

    user = User.query.get(id)

    if user is None:
        flash(notify_warning("Unable to update. User does not exist."))
        return redirect("/admin")

    user.is_admin = is_admin
    user.email = email
    user.first_name = first_name
    user.last_name = last_name
    user.roles[:] = []

    if password.strip():
        user.password = password

    for key in request.form:
        if key.startswith("role_"):
            role_id = key.split("_")[1]
            role = Role.get_by_id(role_id)
            user.roles.append(role)

    user.update()
    flash(notify_success("User successfully updated"))
    return redirect("/admin")
Пример #23
0
def register():
    if request.method == 'POST':
        form = RegisterCustomerForm()
        if not form.validate_on_submit():
            flash_errors(form)
        user = User()
        if User.query.filter(User.email == form.email.data).first():
            flash(notify_warning("Email exists"))
            return mhelp.redirect_url('shop.homepage')
        user.email = form.email.data
        password1 = form.password.data
        password2 = form.reconfirm_password.data
        if not password1 == password2:
            flash(notify_warning("Passwords don't match"))
            return mhelp.redirect_url('shop.homepage')
        user.password = password1
        user.is_customer = True
        print(user.email, password1)
        user.save()
        flash(notify_success('Successfully registered, please log in!'))
        return mhelp.redirect_url('shop.homepage')
Пример #24
0
def delivery_option_delete(option_id):
    option = DeliveryOption.query.get(option_id)
    option.delete()

    flash(notify_success("Option Deleted!"))
    return mhelp.redirect_url("shopman.delivery")
Пример #25
0
def logout():
    logout_user()
    flash(notify_success("Successfully logged out"))
    return redirect(url_for('www.index'))
Пример #26
0
def checkout_process():
    if request.method == "POST":
        cart_info = get_cart_data()
        if len(cart_info["cart_data"]) == 0:
            flash(notify_warning("Cart cannot be empty!"))
            return mhelp.redirect_url("shop.checkout")

        form = CheckoutForm()
        with open(
                os.path.join(
                    current_app.config["BASE_DIR"],
                    "modules",
                    "box__ecommerce",
                    "shopman",
                    "data",
                    "country.json",
                )) as f:
            countries = json.load(f)
        # country_choices = [(c["name"], c["name"]) for c in countries]
        # form.default_country.choices = country_choices
        # form.diff_country.choices = country_choices

        country_choices = [('mauritius', 'Mauritius')]
        form.default_country.choices = country_choices
        form.diff_country.choices = country_choices

        # print(dir(form))
        # ordered dict print(form._fields[0][0])

        # print(form._fields['default_first_name'].data)

        checkout_data = {}
        for key in form._fields:
            checkout_data[key] = form._fields[key].data

        session["checkout_data"][0] = checkout_data

        print(request.form["paymentoption"])
        if form.validate_on_submit():
            if not form.diffAddress.data:
                first_name = form.default_first_name.data
                last_name = form.default_last_name.data
                country = form.default_country.data
                street = form.default_street.data
                town_city = form.default_town_city.data
                phone = form.default_phone.data
                email = form.default_email.data
                order_notes = form.default_order_notes.data

            elif form.diffAddress.data:
                first_name = form.diff_first_name.data
                last_name = form.diff_last_name.data
                country = form.diff_country.data
                street = form.diff_street.data
                town_city = form.diff_town_city.data
                phone = form.diff_phone.data
                email = form.diff_email.data
                order_notes = form.dif_order_notes.data

            billing_detail = BillingDetail()
            billing_detail.first_name = first_name
            billing_detail.last_name = last_name
            billing_detail.country = country
            billing_detail.street = street
            billing_detail.town_city = town_city
            billing_detail.phone = phone
            billing_detail.email = email
            billing_detail.order_notes = order_notes

            if form.createAccount.data:
                if not User.query.filter((User.email == email)).first():
                    user = User()
                    user.first_name = first_name
                    user.last_name = last_name
                    user.email = email
                    user.password = form.passoword.data
                    user.email_confirmed = True
                    user.is_customer = True
                    user.email_confirm_date = datetime.now()

            order = Order()
            order.billing_detail = billing_detail
            shipping_option = DeliveryOption.query.get(
                request.form["deliveryoption"])
            order.shipping_option = shipping_option
            payment_option = PaymentOption.query.get(
                request.form["paymentoption"])
            order.payment_option = payment_option
            if current_user.is_authenticated:
                order.logged_in_customer_email = current_user.email

            if form.applyCoupon.data:
                coupon = Coupon.query.filter(
                    Coupon.string == form.coupon.data).first()
                if coupon:
                    order.coupon = coupon
                else:
                    flash(notify_warning("Invalid Coupon"))

            cart_info = get_cart_data()
            cart_data = cart_info["cart_data"]

            for barcode in Cart.data()['items']:
                for item in Cart.data()['items'][barcode]:
                    order_item = OrderItem()
                    product = Product.query.filter_by(barcode=barcode).first()
                    order_item.barcode = barcode
                    order_item.quantity = int(item['quantity'])
                    order_item.size = item['size']
                    order_item.color = item['color']
                    order.order_items.append(order_item)

            template = "shop/emails/order_info"
            subject = "FreaksBoutique - Order Details"
            context = {}
            context.update({'order': order, 'int': int, 'sum': sum})
            send_async_email(email, subject, template, **context)

            order.insert()
            flash(notify_success("Great!"))
            context = mhelp.context()
            Cart.reset()
            return render_template("shop/order_complete.html", **context)
        else:
            flash_errors(form)
        return mhelp.redirect_url("shop.checkout")
Пример #27
0
def payment_option_delete(option_id):
    option = PaymentOption.query.get(option_id)
    option.delete()

    flash(notify_success("Option Deleted!"))
    return mhelp.redirect_url("shopman.payment")
Пример #28
0
def coupon_delete(coupon_id):
    coupon = Coupon.query.get(coupon_id)
    coupon.delete()

    flash(notify_success("Coupon Deleted!"))
    return mhelp.redirect_url("shopman.coupon")