示例#1
0
    def get(self, request):

        if request.GET.get('shop', '') == '':
            shop_name = request.session.get("shop_name")
        else:
            shop_name = request.GET.get('shop')

        shop = Shop.objects.get(name=shop_name)
        if shop.payment_token == '':
            return redirect("pricing")

        request.session['shop_name'] = shop.name
        request.session['shop_token'] = shop.token
        request.session["api_key"] = settings.SHOPIFY_API_KEY
        activate_shopify_session(request)

        try:
            orders = [shopify.Order.find()]
        except UnauthorizedAccess:
            return redirect(reverse('core:add_shop'))
        except ClientError:
            messages.add_message(
                request, messages.ERROR,
                'The shop exists but it is not reachable at the moment. Please \
                verify your shopify account.')
            return redirect(reverse('core:add_shop'))
        #orders = []
        host = request.get_host()
        products, max_product_reached = normalize_products(request, host)
        #orders = []
        if not products:
            messages.add_message(
                request, messages.ERROR,
                'Apparently you have no products in your shop at Shopify. Please \
                        add a product before using Roojet.')
            return redirect(reverse('core:add_shop'))
        elif products == 'ServerError':
            messages.add_message(
                request, messages.ERROR,
                'Shopify is not reachable at the moment. Please \
                        try again later.')
        for product in products:
            try:
                get_historic(shop=shop,
                             orders=orders,
                             product_id=product.shopify_variant_id)
            except:
                pass
                #messages.add_message(
                #request,
                #messages.ERROR,
                #'You are missing shopify variant id for your product, Please \
                #update your product before using Roojet.')
        objects_to_serialize = Historic.objects.filter(
            Product__created_by=shop).order_by('date')
        try:
            total_profit, profit_margin = get_increased_profit(
                products=products, historic=objects_to_serialize)
            historic = serializers.serialize("json", objects_to_serialize)
            products_serialized = serializers.serialize("json",
                                                        products,
                                                        fields=('pk', 'title'))
        except:
            products_serialized = None
            historic = None
            total_profit = 0
            profit_margin = 0

        try:
            shop = shopify.Shop.current()
        except ServerError:
            messages.add_message(
                request, messages.ERROR,
                'The shop exists but it is not reachable at the moment. Please \
                verify your shopify account.')
            shop = ''

        enough_data = settings.ENOUGH_DATA
        context = {
            'historic': historic,
            'shop': shop,
            'orders': orders,
            'products': products,
            'products_serialized': products_serialized,
            'total_profit': abs(total_profit),
            'profit_margin': profit_margin,
            'enough_data': enough_data,
            'max_product_reached': max_product_reached,
        }
        return render(request, self.template_name, context)
示例#2
0
def calculate_expected_improvement(shop,
                                   orders,
                                   product_id=None,
                                   variable='revenue'):
    """
    Calculates expected improvement for the given orders and product.
    By default calculates revenue, but can calculate profit if variable=profit.
    """
    if product_id is None:
        return None, None
    points = []
    dates = []
    items = {}
    get_historic(shop=shop, orders=orders, product_id=product_id)
    print Product.objects.filter(shopify_variant_id=product_id)
    product_cost = Product.objects.get(shopify_variant_id=product_id).cost
    product_current_price = Product.objects.get(
        shopify_variant_id=product_id).actual_shopify_price
    previous_price = -1.0
    max_price = 0
    for order in orders:
        for item in order.line_items:
            order_date = iso8601.parse_date(order.created_at)
            if item.variant_id is not None and\
               int(product_id) == int(item.variant_id):
                price = str(item.price)
                if items.get(price, None) is None:
                    items[price] = {}
                    items[price]['stats'] = Statistics()
                    items[price]['quantity'] = 0
                    items[price]['days'] = 0
                items[price]['stats'].push(item.quantity)
                if variable == 'revenue':
                    items[price]['quantity'] += item.quantity
                else:
                    items[price]['quantity'] += item.quantity * float(price)
                items[price]['last_date'] = order_date
                dates.append([order_date, item.price])
                if previous_price == item.price:
                    days = abs((order_date - items[price]['last_date']).days)
                    items[price]['days'] += days
                else:
                    items[price]['days'] += 1
                previous_price = price
                if float(price) > max_price:
                    max_price = float(price)
                else:
                    max_price = float(price)
    for key, value in items.iteritems():
        if len(value['stats']) > 1:
            variance = value['stats'].variance()
        else:
            variance = 0.1
        try:
            key_point = (float(key) / max_price) * 100.0
        except:
            key_point = 0.0

        points.append({
            "value_var": variance,
            "value": -value['quantity'] // value['days'],
            "point": [key_point]
        })

    output = {
        'domain_info': {
            'domain_bounds': [{
                "max": 100.0,
                "min": 0.0
            }],
            'dim': 1
        },
        'gp_historical_info': {
            'points_sampled': points,
        },
    }
    print output
    try:
        next_points = requests.post(settings.MOE_URL + 'gp/next_points/epi',
                                    json.dumps(output)).json()
    except:
        pass

    try:
        recommended_price = float(next_points['points_to_sample'][0][0])\
            * (max_price/100.0)
    except KeyError:
        recommended_price = None
    if recommended_price is not None:
        recommended_price = Decimal(recommended_price).\
            quantize(Decimal('.01'),
                     rounding=ROUND_DOWN)
    else:
        recommended_price = Decimal('0.00')
    if recommended_price < product_cost:
        recommended_price = product_current_price
    #if len(points) < settings.ENOUGH_DATA and variable == "profit":
    if variable == "profit":
        if recommended_price < Decimal('100.00'):
            recommended_price = recommended_price * Decimal("1.05")
        else:
            recommended_price = recommended_price * Decimal("1.025")
    Optimization.objects.create(Product=Product.objects.get(
        created_by=shop, shopify_variant_id=product_id),
                                optimized_price=recommended_price,
                                type_of_optimization=variable)