def delete_customer_address(cls, id): try: session.query(cls).filter_by(id=id).delete() session.commit() return True except Exception as e: print("Error: >>>>>>>>>>>>>", e) session.rollback() return False
def delete_image(cls, id): try: image = cls.query.filter_by(image_id=id).first() if image: session.query(cls).filter_by(image_id=id).delete() session.commit() return True else: return False except: session.rollback()
def login(): next_ = request.args.get("next") login_form = LoginForm(next_=next_) login_form.validate_on_submit() if login_form.validate_on_submit(): data = login_form.data username = data["username"] password = data["password"] customer = session.query(Customer).filter( Customer.email == username).first() if customer and customer.verify_password(password): login_user(customer, remember=True, duration=timedelta(1)) session.close() print(">>>>>>>>>>>>>>>", data['next_'], current_user.is_authenticated) if data['next_']: return redirect(data['next_']) return redirect(url_for('index_bp.index')) else: flash("Incorrect Credentials", "danger") signup_form = SignupForm(next_=next_) return render_template("signin_signup/signin-signup.html", show_login=True, login_form=login_form, signup_form=signup_form)
def customer_order_exists(cls, customer_id): try: return session.query(cls).filter_by(customer_id=customer_id, is_paid=False, is_terminated=False).first() except: session.rollback()
def read_product_rate(cls, product_id): try: pdt_ratings = session.query(func.count(cls.rate), cls.rate)\ .group_by(cls.rate).filter_by(product_id=product_id).all() numerator = 0 denomenator = 0 for rate in pdt_ratings: denomenator += rate[0] if rate[1] == 5: numerator += rate[0] * 100 elif rate[1] == 4: numerator += rate[0] * 80 elif rate[1] == 3: numerator += rate[0] * 60 elif rate[1] == 2: numerator += rate[0] * 40 elif rate[1] == 1: numerator += rate[0] * 20 if pdt_ratings: return int(((numerator / denomenator) / 100) * 5) else: return 0 except: session.rollback()
def promotional_price(self): if self.promotional_price_set: price = session.query(pdtds.ProductDiscounts).filter_by( product_id=self.product_id).first() return (price.price + self.commission_amount) if price else None else: return None
def customer_order_count(cls, customer_id): try: count = session.query(func.count(cls.id)).filter_by( is_paid=True, is_terminated=False).scalar() return count except: session.rollback()
def cart_total_amount(cls, customer_id): total = session.query(func.sum(cls.total))\ .filter_by( customer_id=customer_id, is_ordered=False ).scalar() return total if total else 0
def read_all_orders_delivery_details_filter(cls, *args): try: return session.query(cls).join(cls.delivery_details)\ .filter( *args ).order_by(cls.id.desc()).options( lazyload("*")).all() except: session.rollback()
def read_all_bandss_filter_by(cls,*args, **kwargs)->list: """ returns tuple objects tuples are made of attributes specified as args """ query = session.query(*[getattr(cls,i) for i in args]).filter_by(**kwargs).all() if len(args) == 1 and query: query = [i[0] for i in query] return query
def read_customer_count(cls): try: return session.query(func.count(cls.id)).scalar() except: session.rollback()
def get_products(): # code to get / search products products = session.query(Products).all() # render patches patches = { "form_templates": { "#productsPatch": render_template('product/products.html', products=products) } } return patches
def read_orders_not_prepared_count(cls): try: return session.query(func.count(cls.id))\ .filter( and_( cls.is_prepared==False, cls.is_terminated == False ) ).scalar() except: session.rollback()
def index(self): customer_number = session.query(func.count(db.Customer.id)).scalar() resturant_number = session.query(func.count(db.Resturant.id)).scalar() sales_amount = session.query(func.count(db.Sales.amount)).scalar() products_sold = session.query(func.sum(db.Sales.quantity)).scalar() if customer_number is None: customer_number = 0 if resturant_number is None: resturant_number = 0 if sales_amount is None: sales_amount = 0 if products_sold is None: products_sold = 0 return self.render("admin/index.html", customer_number=customer_number, resturant_number=resturant_number, sales_amount=sales_amount, products_sold=products_sold)
def get(self): # _date = datetime.now(ni_timezone) # current_time = _date.astimezone(timezone) args = searchStringsArgs.parse_args() products = [] # searched_pdts = [] if args.get("searchString", None): search_item = args["searchString"] products = session.query(Products).filter( Products.name.like(f"%{search_item}%") ).order_by(Products.product_id).all() if not products: products = session.query(Products).join(Products.brand)\ .filter( Brand.name.like(f"%{search_item}%") ).order_by(Products.product_id).all() if not products: products = session.query(Products).join(Products.sub_category)\ .filter( SubCategory.name.like(f"%{search_item}%") ).order_by(Products.product_id).all() return list(search_pdt_generator(products))
def get(self): home_products = Products.home_products() home_products.append( { "id": 3, "title":"Fruits & Vegetables", "products": sample(list(vegetables_generator(session.query(Products).join(Products.sub_category).join(SubCategory.category).filter(Category.name=="Fruits and Vegetables").order_by(Products.product_id).all())), 2) } ) top_selling_products = TopSellingProducts.read_all_top_discount_products() return { "home_images_products": home_products, "home_images": HomeImages.home_images(), "sub_cats": list(home_sub_cat_generator(SubCategory.read_sub_cat())), "all_products": list(all_products_generator(Products.read_products())), "top_selling_products": top_selling_products }
def add_product_to_cart(product_id): # code to order product product = session.query(Products).get(product_id) customer_id = None if current_user.is_authenticated: customer_id = current_user.id served_with = request.args.get("served_with") cart = Cart()( product_id=product.id, customer_id=customer_id, product_name=product.name, product_image=product.image, unit_price=product.unit_price, quantity=1, served_with=served_with, free_delivery=product.free_delivery, restaurant=product.restaurant.business_name ) return render_template('product/product.html', product=product)
def read_all(cls): return session.query(cls).all()
def customer_order_items_total(cls, order_id): total = session.query(func.sum(cls.total))\ .filter_by( order_id=order_id ).scalar() return total if total else 0
def read_item_shop_details(self): shop_details = session.query(shp.Resturant.business_name, shp.Resturant.address, shp.Resturant.contact, shp.Resturant.second_contact).join( "products" ).filter(pdts.Products.product_id == self.product_id).first() shop_details = Markup(f"{shop_details[0]}.<br> <b>Location:</b> {shop_details[1]} <br><b>Contact: </b>{shop_details[2]}/ {shop_details[3]}") if shop_details else "Unkown" return shop_details
def read_category(self, id): return session.query(self).filter_by(category_id=id).first()
def read_categories(cls): return session.query(cls).all()
def read_products_count(cls): try: return session.query(func.count(cls.product_id)).scalar() except: session.rollback()
def place_customer_order(cls, **kwargs): with current_app.app_context(): try: method = kwargs.get("payment_method") customer_id = kwargs.get("customer_id") delivery_contact = kwargs.get("delivery_contact") delivery_fee = kwargs.get("delivery_fee") pre_order = kwargs.get("pre_order") pre_order_time = kwargs.get("pre_order_time") county = kwargs.get("county"), sub_county = kwargs.get("sub_county"), village = kwargs.get("village"), other_details = kwargs.get("other_details"), customer_object = customer.Customer.read_customer( id=customer_id) payment_method = pym.PaymentMethods.read_method(method=method) if payment_method: new_ref = ReferenceGenerator() order_ref = new_ref.unique_id order_ref_simple_version = new_ref.simple_version order_ = Order( order_ref=order_ref, order_ref_simple_version=order_ref_simple_version, delivery_contact=delivery_contact, delivery_fee=delivery_fee, customer_id=customer_id, pre_order=pre_order, pre_order_time=pre_order_time) items = session.query(pdts.Cart).filter_by( customer_id=customer_id, is_ordered=False).all() for item in items: item.is_ordered = True item.order = order_ delivery = delivery_detials.DeliveryDetails( county=county, sub_county=sub_county, village=village, other_details=other_details, customer_id=customer_id, order=order_) session.add(delivery) payment = pym.Payment(payment_method_id=payment_method.id, order=order_) session.add(payment) if payment_method.method == "Cash on delivery": cash_on_delivery = pym.CashOnDelivery( payment=payment, transaction_ref=order_ref, status="pending") session.add(cash_on_delivery) else: session.rollback() return False #customer_care email cart_items_total = [] items_str = "" item_string = "" for i in items: item = i.serialize() item_string = f"<li>Item: {item['product_name']} from {item['restaurant']} Quantity: {item['quantity']} <b>SubTotal: {'{:,} Ugx'.format(item['total'])}</b></li>" items_str += item_string cart_items_total.append(item['total']) total = items[0].serialize() items_total = sum(cart_items_total) subject_customer_care = """ <html> <p>The following customer: <b>{customer_name}</b> has placed an order with the following details:</p> <p>Order Reference: {order_ref}</p> <p>Order Date: {order_date}</p> <p>Contact: {contact}</p> <hr> <ul style='list-style-type: none;display: block;width: 100%;padding: 0px 10px;overflow: hidden;'> {items_str} </ul> <hr> <p>Items Total: {total}</p> <hr> <p>Payment Method: <b>{payment_method}</b></p> <p>Delivery Price: <b>{delivery_fee}</b></p> <p>Total: <b>{order_total}</b></p> <hr> <p>Delivery Address: {delivery_address}</p> </html> """.format( customer_name=customer_object.name, order_ref=order_ref_simple_version, order_date="{: %d/%m/%Y}".format(datetime.now()), contact=customer_object.contact, items_str=items_str, total='{:,} Ugx'.format(items_total), payment_method=payment_method.method, delivery_fee='{:,} Ugx'.format(delivery_fee), order_total='{:,} Ugx'.format(delivery_fee + items_total), delivery_address= f"<br>County: {county}<br>,Sub County: {sub_county}<br>,Village: {village}<br>,Other_details: {other_details}<br>" ) customer_care_mail_ = customer_care_email customer_care_mail_.recipients = [ "*****@*****.**", "*****@*****.**", "*****@*****.**" ] # customer_care_mail_.context = dict( # customer_name=customer_object.name, # customer_contact=customer_object.contact, # order_ref=order_ref_simple_version, # order_date="{: %d/%m/%Y}".format(datetime.now()), # items=[i.serialize() for i in items], # delivery_method="Home delivery", # delivery_fee=delivery_fee, # payment_method=payment_method.method, # delivery_address= f"County: {county}\n,Sub County: {sub_county}\n,Village: {village}\n,Other_details: {other_details}" # ) customer_care_mail_.text = subject_customer_care customer_care_mail_.send() if customer_object.email: subject_customer = """ <html> <p>Written by: [email protected]<br> <b>Office Address:</b><br> Afra Road,<br> Near Hindu Temple,<br> Room 08,<br> Arua City, Uganda. </p> <p>You have successfully made an order for the following items.</p> <p>Order Reference: <b>{order_ref}</b></p> <p>Order Date: <b>{order_date}</b></p> <hr> <ul style='list-style-type: none;display: block;width: 100%;padding: 0px 10px;overflow: hidden;'> {items_str} </ul> <hr> <p>Items Total: <b>{total}</b></p> <hr> <p>Payment Method: <b>{payment_method}</b></p> <p>Delivery Price: <b>{delivery_fee}</b></p> <p>Total: <b>{order_total}</b></p> <p>Delivery Address: {delivery_address}</p> <hr> <p>You have received this email because you are a registered customer of ClickEat.</p> <p>For any help please contact us on: <b>0785857000/0777758880</b></p> </html> """.format( order_ref=order_ref_simple_version, order_date="{: %d/%m/%Y}".format(datetime.now()), items_str=items_str, total='{:,} Ugx'.format(items_total), payment_method=payment_method.method, delivery_fee='{:,} Ugx'.format(delivery_fee), order_total='{:,} Ugx'.format(delivery_fee + items_total), delivery_address= f"<br>County: {county}<br>,Sub County: {sub_county}<br>,Village: {village}<br>,Other_details: {other_details}<br>" ) mail_ = order_placed_email mail_.recipients = [customer_object.email] mail_.text = subject_customer # mail_.context = dict( # customer_name=customer_object.name, # customer_contact=customer_object.contact, # order_ref=order_ref_simple_version, # order_date="{: %d/%m/%Y}".format(datetime.now()), # items=[i.serialize() for i in items], # delivery_method="Home delivery", # delivery_fee=delivery_fee, # payment_method=payment_method.method, # delivery_address= f"County: {county}\n,Sub County: {sub_county}\n,Village: {village}\n,Other_details: {other_details}" # ) # mail_.text = "You have placed the following order with reference number: {order_ref_simple_version}".format( # order_ref_simple_version=order_ref_simple_version # ) mail_.send() session.commit() return True else: session.commit() return True else: print("No payment method") return False except Exception as e: print("Placing Order Error: ", e) session.rollback() return False
def read_sales_sum(cls, attr, *args): sales_sum = session.query(func.sum(attr)).filter(*args).scalar() return sales_sum if sales_sum else 0
def admin_exists(cls): return session.query(cls).join("account_type").filter( AccountType.type_name == "administrator").first()
def customer_care_register_order_sales(cls, **kwargs): with current_app.app_context(): try: order = kwargs.get("order") data = kwargs.get("data") if "order_id" not in data: abort(403) if int(data["order_id"]) != int(order.id): abort(403) if "customer_received" in data: if order.is_prepared == False: flash("Order has to first be prepared", "danger") return jsonify() if order.is_paid == False: flash("Order has to first be paid", "danger") return jsonify() if data["customer_received"] == True and order.customer_received == False: order.customer_received = True session.commit() flash("Order status 'Customer received' has been set", "success") else: flash( "Order status 'Customer received' was already set", "info") elif "is_prepared" in data: if data["is_prepared"] == True and order.is_prepared == False: order.is_prepared = True session.commit() flash("Order status 'Prepared' has been set", "success") else: flash("Order status 'Prepared' was already set", "info") elif "courier_id" in data: if order.is_prepared == False: flash("Order has to be first prepared", "danger") return jsonify() delivery_detials.DeliveryDetails.assign_courier( int(data["courier_id"]), int(order.id)) flash("Courier has been set for this order successfully", "success") elif "is_paid" in data: if order.is_prepared == False: flash("Order has to first be prepared", "danger") return jsonify() if data["is_paid"] == True and order.is_paid == False: order.is_paid = True cash_on_delivery = pym.CashOnDelivery.read_cash_on_delivery( payment_id=order.payment[0].payment_id) delivery_details = order.delivery_details[0] if delivery_details.courier_id == None: flash( "Order paid can only be set when courier has been set.", "danger") session.rollback() return jsonify() if not cash_on_delivery: flash( "Order paid can only be set for cash on delivery items.", "danger") session.rollback() return jsonify() else: cash_on_delivery.status = "confirmed" for pdt_ in order.cart: product = session.query(pdts.Products).filter_by( product_id=pdt_.product_id).first() if product: sales.Sales()( product_id=pdt_.product_id, quantity=pdt_.quantity, amount=pdt_.total, commission_amount=product.commission_amount if product.commission_amount else 0) if order.customer.email: items = order.cart cart_items_total = [] items_str = "" item_string = "" for i in items: item = i.serialize() item_string = f"<li>Item: {item['product_name']} from {item['restaurant']} Quantity: {item['quantity']} <b>SubTotal: {'{:,} Ugx'.format(item['total'])}</b></li>" items_str += item_string cart_items_total.append(item['total']) total = items[0].serialize() items_total = sum(cart_items_total) subject_customer = """ <html> <p>Written by [email protected]<br> Office Address:<br> Afra Road,<br> Near Hindu Temple,<br> Room 08,<br> Arua City, Uganda. </p> <p>Dear <b>{user_name}</b></p>, <p>You have made a payment for the following items.</p> <p>Order Reference: <b>{order_ref}</b></p> <p>Order Date: {order_date}</p> <hr> <ul style='list-style-type: none;display: block;width: 100%;padding: 0px 10px;overflow: hidden;'> {items_str} </ul> <hr> <p>Items Total: <b>{total}</b></p> <p>Payment Method: {payment_method}</p> <p>Delivery Price: {delivery_fee}</p> <p>Total: {order_total}</p> <p>Status: <b>Paid</b></p> <hr> <p><b>Thank you for buying on ClickEat, please come gain :)</b></p> <p>You have received this email because you are a member of ClickEat.</p> <p>For any help please contact us by clicking 0785857000/0777758880</p> </html> """.format( user_name=order.customer.name, order_ref=order.order_ref_simple_version, order_date="{: %d/%m/%Y}".format( order.order_date), items_str=items_str, total='{:,} Ugx'.format(items_total), payment_method=order.payment[0].payment_method. serialize(), delivery_fee='{:,} Ugx'.format( order.delivery_fee), order_total='{:,} Ugx'.format( order.delivery_fee + items_total)) mail_ = order_receipt_email mail_.recipients = [order.customer.email] mail_.text = subject_customer # mail_.context = dict( # items = [i.serialize() for i in order.cart], # order_ref = order.order_ref_simple_version, # order_date="{: %d/%m/%Y}".format(order.order_date), # user_name = order.customer.name, # delivery_fees = order.delivery_fee, # payment_method = order.payment[0].payment_method.serialize(), # customer_received = order.customer_received # ) mail_.send() session.commit() flash("Order status has been set to paid", "success") else: session.commit() flash("Order status has been set to paid", "success") else: session.rollback() flash("Order status already set to paid", "info") except Exception as e: session.rollback() print("Updating Order statuses error: ", e) flash(f"Error: {e}", "danger")
def read_all_categories_by_attr(cls, *args) -> list: query = session.query(*[getattr(cls, i) for i in args]).all() if len(args) == 1 and query: query = [i[0] for i in query] return query
def order_product(product_id): # code to order product product = session.query(Products).get(product_id) return render_template('product/product.html', product=product)
def read_orders_count(cls): try: return session.query(func.count(cls.id)).filter_by( is_paid=False, is_terminated=False).scalar() except: session.rollback()