Пример #1
0
    def shoppingcart(self):
        """ This function renders the shopping cart for the user."""

        # Set vars, get profile_id and het shopping cart items
        items_in_cart = []
        limit = 4
        profile_id = session['profile_id'] if session['profile_id'] is not None else '5a393d68ed295900010384ca'
        shopping_cart = session['shopping_cart']

        # Convert de items naar onze Product objecten en tel de kwantiteit
        for tup in shopping_cart:
            prod_obj = convert_to_model.toProduct(
                database.retrieve_properties("products", {"product_id": f"{tup[0]}"})[0])
            product = self.prepproduct(prod_obj)
            product["itemcount"] = tup[1]
            items_in_cart.append(product)

        # Haal de recommended producten op
        r_prods = [convert_to_model.toProduct(e) if type(e) == tuple else e for e in
                   page_cart.cart_alg_selection(limit, shopping_cart, profile_id)]

        return self.renderpackettemplate('shoppingcart.html', {'itemsincart': items_in_cart, \
                                                               'r_products': r_prods, \
                                                               'r_type': list(self.recommendationtypes.keys())[2], \
                                                               'r_string': list(self.recommendationtypes.values())[2],
                                                               'header_text_base': 'Aanbevolen voor jou' if len(
                                                                   items_in_cart) == 0 else ''})
Пример #2
0
    def productpage(self, cat1=None, cat2=None, cat3=None, cat4=None, page=1):
        """ This function renders the product page template with the products it
        can retrieve from the database, based on the URL path provided (which
        corresponds to product categories). """
        limit = session['items_per_page'] if session['items_per_page'] != 0 else \
            database.execute_query("select count(product_id) from products", '')[0][0]

        rec_limit = 4
        catlist = [cat1, cat2, cat3, cat4]
        nononescats = [e for e in catlist if e is not None]
        skipindex = session['items_per_page'] * (page - 1)

        """ Get all products (this need to be based on profile if has profile id) """
        profile_id = session['profile_id'] if session['profile_id'] is not None else '5a393d68ed295900010384ca'
        retrieved_ids = page_home.get_recommendations(profile_id, nononescats, limit)

        id_batch = retrieved_ids[skipindex:(skipindex + limit)]

        """ Convert the recommended ids to product objects """
        prodList = [convert_to_model.toProduct(e) for e in id_batch]

        """ Get 'anderen kochten ook' recommendations """
        recs = page_home.get_anderen_kochten_ook(id_batch, rec_limit, profile_id)
        recs = [convert_to_model.toProduct(e) if type(e) != product.Product else e for e in recs]

        """ Set the url path to match the categries and page we are in """
        if len(nononescats) > 0:
            pagepath = "/producten/" + ("/".join(nononescats)) + "/"
        else:
            pagepath = "/producten/"

        return self.renderpackettemplate('products.html', {'products': prodList,
                                                           'productcount': len(retrieved_ids),
                                                           'pstart': skipindex + 1,
                                                           'pend': skipindex + session['items_per_page'] if session[
                                                                                                                'items_per_page'] > 0 else len(
                                                               retrieved_ids),
                                                           'prevpage': pagepath + str(page - 1) if (
                                                                   page > 1) else False,
                                                           'nextpage': pagepath + str(page + 1) if (session[
                                                                                                        'items_per_page'] * page < len(
                                                               retrieved_ids)) else False,
                                                           'r_products': recs[:rec_limit],
                                                           'r_type': list(self.recommendationtypes.keys())[0],
                                                           'r_string': list(self.recommendationtypes.values())[0],
                                                           'header_text': 'Voor u aanbevolen' if len(
                                                               nononescats) == 0 else ''
                                                           })
Пример #3
0
def get_recommendations(product_id):
    """
              Get the recommended items from the database given a product ID
          """
    product_id = product_id.replace("'", "''")
    results = database.execute_query(
        "select recommendations from simplerecs where product_id = %s",
        (product_id, ))
    recs = [
        convert_to_model.toProduct(
            database.execute_query(
                "select * from products where product_id = %s", (e, ))[0])
        for e in results[0][0]
    ]
    return recs
Пример #4
0
    def productdetail(self, productid):
        """ This function renders the product detail page based on the product
        id provided. """

        try:
            product = convert_to_model.toProduct(
                database.retrieve_properties("products", {"product_id": str(productid)})[0])

            r_products = page_details.product_detail_alg_selection(product)

        except IndexError:
            print('No product found, returning back to productpage')
            return self.productpage()

        return self.renderpackettemplate('productdetail.html', {'product': product, \
                                                                'prepproduct': self.prepproduct(product), \
                                                                'r_products': r_products, \
                                                                'r_type': list(self.recommendationtypes.keys())[1], \
                                                                'r_string': list(self.recommendationtypes.values())[1]})
Пример #5
0
def cart_alg_selection(limit, shopping_cart, profile_id):
    "code that decides what algorithm to use in the shopping cart based on the accuracy of the recommendations, returns *limit* recommendations"

    # get all the ids from the cart
    ids_in_cart = [x[0] for x in shopping_cart]

    # if there is only 1 element in the list Psycopg2 will crash. Hence the statement add a blank string.
    # (does not affect the results)
    if len(ids_in_cart) == 1:
        ids_in_cart.append('')
    if len(ids_in_cart) > 0:
        recs_data = database.execute_query(
            f"select * from order_based_recs where product_id in {tuple(ids_in_cart)}",
            "")
        recs_data = list(reversed(sorted(recs_data,
                                         key=lambda x: x[2])))[:limit]
        recs_data_simple = database.execute_query(
            f"select * from simplerecs where product_id in {tuple(ids_in_cart)}",
            "")
        recs_data_behaviour = behaviour.recommend(ids_in_cart, limit)
        # print(f'{ids_in_cart}, {recs_data_behaviour}')

        sample_size_limit = 10
        if recs_data[0][2] >= sample_size_limit:
            print('Algorithm: Bought_together')

            recs = list(
                set([
                    rec for data in recs_data if (data[2] > sample_size_limit)
                    for rec in data[1]
                ]))

            # recs = prioritze_discount.prioritize_discount(recs, limit)
            random.shuffle(recs)
            recs = recs[:4]
        else:
            if len(recs_data_behaviour) == limit:
                print('Algorithm: Behaviour')
                recs = recs_data_behaviour
            else:
                print('Algorithm: Simple')
                recs = list(
                    set([
                        z for x in recs_data_simple
                        for z in random.sample(x[1], k=len(x[1]))
                    ]))[:limit]

        print(recs)
        if len(recs) < 4:
            recs = list(
                set([
                    z for x in recs_data_simple
                    for z in random.sample(x[1], k=len(x[1]))
                ]))[:limit]
            print(recs)
        r_prods = convert_to_model.convert_to_product_list(
            "select * from products where product_id in %s", (tuple(recs), ))

    else:
        try:
            if profile_id is None:
                raise NameError
            r_prods = page_home.get_profile_recommendations(profile_id,
                                                            limit=limit)
        except NameError:
            r_prods = [
                convert_to_model.toProduct(e)
                for e in database.get_based_on_categories([], limit)
            ]

    return r_prods