Ejemplo n.º 1
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
            )
        )
Ejemplo n.º 2
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"))
Ejemplo n.º 3
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)
Ejemplo n.º 4
0
def flash_errors(form):
    """Flashes form errors"""
    for field, errors in form.errors.items():
        for error in errors:
            error_msg = u"Error in the %s field - %s" % (getattr(
                form, field).label.text, error)
            flash(notify_warning(error_msg))
Ejemplo n.º 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"))
Ejemplo n.º 6
0
def manage_sub(category_name):
    context = {}
    category = Category.query.filter(Category.name == category_name).first()

    if category is None:
        flash(notify_warning("category name does not exist"))

    context.update({"category": category})
    return render_template("category/manage_sub.html", **context)
Ejemplo n.º 7
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"))
Ejemplo n.º 8
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')
Ejemplo n.º 9
0
def sub_delete(subcategory_id):
    subcategory = SubCategory.query.get(subcategory_id)
    category_name = subcategory.category.name
    if (
        subcategory.name == "uncategorised"
        and subcategory.category.name == "uncategorised"
    ):
        flash(
            notify_warning(
                "Cannot delete subcategory uncategorised "
                + "of category uncategorised"
            )
        )
        return redirect(
            url_for("category.manage_sub", category_name=category_name)
        )

    uncategorised_sub = (
        SubCategory.query.join(Category)
        .filter(
            and_(
                SubCategory.name == "uncategorised",
                Category.name == "uncategorised",
            )
        )
        .first()
    )

    # before removing the subcategory, move the products
    # in this subcategory to uncategorised subcategory
    for product in subcategory.products:
        uncategorised_sub.products.append(product)

    subcategory.products = []
    db.session.delete(subcategory)
    db.session.commit()

    # for resource in subcategory.resources:
    #     filename = resource.filename
    #     resource.delete()
    #     delete_file(
    #         os.path.join(
    #             current_app.config["UPLOADED_SUBCATEGORYPHOTOS_DEST"],
    #             filename
    #         )
    #     )
    # subcategory.delete()

    # add for products change
    return redirect(
        url_for("category.manage_sub", category_name=category_name)
    )
Ejemplo n.º 10
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"))
Ejemplo n.º 11
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")
Ejemplo n.º 12
0
def cart_add(product_barcode):
    if request.method == "POST":
        flash("")

        barcode = request.form["barcode"]
        quantity = int(request.form["quantity"])
        size = request.form['size']
        color = request.form['color']

        item_info = {'quantity': quantity, 'size': size, 'color': color}

        if Cart.add(barcode, item_info):
            return mhelp.redirect_url("shop.product", product_barcode=barcode)
        else:
            flash(
                notify_warning(
                    "Products in cart cannot be greater than product in stock")
            )
            return redirect(url_for("shop.product", product_barcode=barcode))
Ejemplo n.º 13
0
def admin_edit(id):
    """
               **Update information for a User**

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

    """
    context = {}
    user = User.query.get(id)

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

    context["user"] = user
    context["user_roles"] = [r.name for r in user.roles]
    context["roles"] = Role.query.all()
    return render_template("admin/edit.html", **context)
Ejemplo n.º 14
0
def user_add():
    """
       **Adds a User**

    adds a user to database.

    """
    context = {}
    if request.method == "POST":
        email = request.form["email"]
        password = request.form["password"]
        first_name = request.form["first_name"]
        last_name = request.form["last_name"]
        admin_user = request.form.get("is_admin")
        if admin_user == "True":
            is_admin = True
        else:
            is_admin = False

        has_user = db.session.query(
            exists().where(User.email == email)).scalar()

        if not has_user:
            new_user = User()
            new_user.email = email
            new_user.is_admin = is_admin
            new_user.first_name = first_name
            new_user.last_name = last_name
            new_user.password = password

            for key in request.form:
                if key.startswith("role_"):
                    role_id = key.split("_")[1]
                    role = Role.get_by_id(role_id)
                    new_user.roles.append(role)
            new_user.save()
            return redirect(url_for("admin.user_add"))

        flash(notify_warning("User with same email already exists"))

    context["roles"] = Role.query.all()
    return render_template("admin/add.html", **context)
Ejemplo n.º 15
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")
Ejemplo n.º 16
0
def flash_errors(form):
    """
    Auto flash errors from WKHtml forms
    Reqwires base module or similar notification
    mechanism

    Parameters
    ----------
    form: WKHtml form

    Returns
    -------
    None
    """
    for field, errors in form.errors.items():
        for error in errors:
            error_msg = u"Error in the %s field - %s" % (
                getattr(form, field).label.text,
                error,
            )
            flash(notify_warning(error_msg))
Ejemplo n.º 17
0
from functools import wraps

from flask import flash
from flask import redirect
from flask import url_for

from flask_login import current_user

from shopyoapi.init import login_manager
from shopyoapi.html import notify_warning

from modules.box__default.admin.models import User

login_manager.login_view = "auth.login"
login_manager.login_message = notify_warning("Please login for access")


@login_manager.user_loader
def load_user(id):
    return User.query.get(id)


def admin_required(f):
    @wraps(f)
    def wrap(*args, **kwargs):
        if current_user.is_anonymous or current_user.is_admin:
            return f(*args, **kwargs)
        else:
            flash(notify_warning("You need to be an admin to view this page."))
            return redirect(url_for("dashboard.index"))
Ejemplo n.º 18
0
 def wrap(*args, **kwargs):
     if current_user.is_anonymous or current_user.is_admin:
         return f(*args, **kwargs)
     else:
         flash(notify_warning("You need to be an admin to view this page."))
         return redirect(url_for("dashboard.index"))
Ejemplo n.º 19
0
def add_sub(category_name):
    if request.method == "POST":

        category = Category.query.filter(
            Category.name == category_name
        ).scalar()

        # case 1: do not allow adding subcategory to nonexisting
        # category
        if category is None:
            return "category does not exist", 400

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

        # case 2: do not allow adding subcategory with
        # empty name
        if is_empty_str(name):
            flash(notify_warning("Name cannot be empty"))
            return redirect(
                url_for(
                    "category.manage_sub",
                    category_name=category_name,
                )
            )

        existing = (
            SubCategory.query.join(Category)
            .filter(
                and_(SubCategory.name == name, Category.name == category_name)
            )
            .first()
        )

        # case 3: do not allow adding existing subcategory
        # inside a given category
        if existing:
            flash(notify_warning("Name already exists for category"))
            return redirect(
                url_for(
                    "category.manage_sub",
                    category_name=category_name,
                )
            )

        # case 4: successfully add subcategory to desired category
        category = Category.query.filter(
            Category.name == category_name
        ).first()
        subcategory = SubCategory(name=name)

        try:
            if "photo" in request.files:
                file = request.files["photo"]

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

        category.subcategories.append(subcategory)
        category.update()
    return redirect(
        url_for("category.manage_sub", category_name=category_name)
    )
Ejemplo n.º 20
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")