Пример #1
0
def instruction():
    shop_name = request.args.get('shop')
    api_version = app.config.get('SHOPIFY_API_VERSION')

    if not shop_name:
        abort(403)

    try:
        # проверка подписи
        if not signature_validation(request.args.items(),
                                    app.config['SHOPIFY_API_SECRET']):
            raise Exception('bad sign')

        merchant = Merchant.get(Merchant.shop_name == shop_name)

        with shopify.Session.temp(shop_name, api_version, merchant.token):
            shop = shopify.Shop.current()
            myshopify_domain = shop.myshopify_domain
            app.logger.info(myshopify_domain)

    except Merchant.DoesNotExist:
        return reinstall_app(shop_name)

    except pyactiveresource.connection.UnauthorizedAccess:
        # если токен не активен переустановить апп
        return reinstall_app(shop_name)

    except:
        app.logger.warning(traceback.format_exc())
        abort(403)

    return render_template('instruction.html')
Пример #2
0
def style_css():
    shop_name = request.args.get('shop_name')

    if not shop_name:
        abort(403)

    try:
        merchant = Merchant.get(Merchant.shop_name == shop_name)
        merchant_settings = MerchantSettings.get(
            MerchantSettings.merchant == merchant)

    except Merchant.DoesNotExist:
        app.logger.warning('not merchant')
        abort(403)

    if not merchant.enable:
        app.logger.warning('merchant disable')
        abort(403)

    data = ''

    if merchant_settings.default_view:
        html_path = app.config.get('DEFAULT_SETTINGS_HTML_PATH')

        with open(os.path.join(html_path, 'style.css')) as f:
            data = f.read()

    else:
        data = merchant_settings.style

    response = make_response(data)
    response.headers['Content-Type'] = 'text/css'

    return response
Пример #3
0
def uninstalled_view():
    """Обработчик вебхука удаления аппа
    :return:
    """

    if not verify(request.get_data(),
                  request.headers.get('X-Shopify-Hmac-Sha256'),
                  app.config.get('SHOPIFY_API_SECRET')):
        app.logger.warning('bad sign')
        abort(403)

    if not request.is_json:
        app.logger.warning('not json')
        abort(403)

    shop_name = request.headers.get('X-Shopify-Shop-Domain')

    try:
        merchant = Merchant.get(Merchant.shop_name == shop_name)

    except Merchant.DoesNotExist:
        abort(404)

    try:
        _ = requests.get(app.config.get('DELETE_APP_URL').format(merchant.id),
                         timeout=30)

    except:
        app.logger.warning('DELETE_APP_URL exception')

    return ''
Пример #4
0
def ecocart_json():
    shop_name = request.args.get('shop_name')

    if not shop_name:
        abort(403)

    try:
        merchant = Merchant.get(Merchant.shop_name == shop_name)
        merchant_settings = MerchantSettings.get(MerchantSettings.merchant == merchant)
        company = merchant_settings.company

        if not company:
            company = '[Company]'

    except Merchant.DoesNotExist:
        app.logger.warning('not merchant')
        abort(403)

    if not merchant.enable:
        app.logger.warning('merchant disable')
        abort(403)

    html_path = app.config.get('DEFAULT_SETTINGS_HTML_PATH')
    data = dict()

    if merchant_settings.default_view:

        with open(os.path.join(html_path, 'loading.html')) as f:
            data['loading'] = f.read()

        with open(os.path.join(html_path, 'estimate.html')) as f:
            data['estimate'] = f.read()

        with open(os.path.join(html_path, 'shipment.html')) as f:
            data['shipment'] = f.read()

        with open(os.path.join(html_path, 'error.html')) as f:
            data['error'] = f.read()

    else:
        data['loading'] = merchant_settings.loading
        data['estimate'] = merchant_settings.estimate
        data['shipment'] = merchant_settings.shipment
        data['error'] = merchant_settings.error_field

    with open(os.path.join(html_path, 'company.html')) as f:
        data['company'] = f.read()
        data['company'] = data['company'].replace('##COMPANY##', company)

    return jsonify(data)
Пример #5
0
def ecocart_js():
    shop_name = request.args.get('shop_name')

    if not shop_name:
        abort(403)

    try:
        merchant = Merchant.get(Merchant.shop_name == shop_name)
        merchant_settings = MerchantSettings.get(
            MerchantSettings.merchant == merchant)

    except Merchant.DoesNotExist:
        app.logger.warning('not merchant')
        abort(403)

    except MerchantSettings.DoesNotExist:
        app.logger.warning('not merchant_settings')
        abort(403)

    if not merchant.enable:
        app.logger.warning('merchant disable')
        abort(403)

    settings = merchant.settings

    if settings:
        settings = json.loads(settings)

    else:
        settings = dict()

    if not settings.get('production'):
        app.logger.warning('production disable')
        abort(403)

    selector = merchant_settings.selector

    if not selector:
        selector = ''

    placement = merchant_settings.placement
    js = merchant_settings.js or ''
    hostname = app.config.get('HOSTNAME')

    return render_template('ecocart.js',
                           selector=selector,
                           placement=placement,
                           js=js,
                           hostname=hostname)
Пример #6
0
def activatecharge(shop_name):
    charge_id = request.args.get('charge_id')

    try:
        merchant = Merchant.get(Merchant.shop_name == shop_name)

    except Merchant.DoesNotExist:
        abort(403)

    token = merchant.token
    run_activate_charge(shop_name, token, charge_id)
    # редирект в админку
    url = 'https://{}/admin/apps/{}'

    return redirect(url.format(shop_name, app.config.get('SHOPIFY_API_KEY')))
Пример #7
0
def home2():
    shop_name = request.args.get('shop')
    merchant = Merchant.get(Merchant.shop_name == shop_name)
    if request.method == 'POST':
        form = SettingsForm()
        if form.validate():
            settings = json.dumps(form.data)
            merchant.settings = settings
            merchant.save()
            return ''
        else:
            errors = form.errors
            _errors = ['{} - {}<br>'.format(k, errors[k]) for k in errors]
            _errors = ''.join(_errors)
            return _errors
    else:
        settings = merchant.settings
        if settings:
            settings = json.loads(settings)
        else:
            settings = dict()
        form = SettingsForm(**settings)
    return render_template('home.html', form=form)
Пример #8
0
def ecocart():
    shop_name = request.args.get('shop_name')
    shipping_weight = float(request.args.get('total_weight', 0))  # граммы
    if not shop_name or not shipping_weight:
        abort(403)
    shipping_weight = shipping_weight / 1000 * 2.205
    shipping_weight = round(shipping_weight,
                            4)  # подогнать под количество знаков shopify
    try:
        merchant = Merchant.get(Merchant.shop_name == shop_name)
        token = merchant.token
        print(token)
    except Merchant.DoesNotExist:
        app.logger.warning('not merchant')
        abort(403)

    remote_ip = request.headers.get('X-Real-IP')
    latitude = request.form.get('latitude')
    longitude = request.form.get('longitude')
    shipping_po = None
    if latitude and longitude:
        shipping_po = (float(latitude), float(longitude))
    path_geo_db = app.config.get('PATH_GEO_DB')
    path_geo_db_us = app.config.get('PATH_GEO_DB_US')
    _kwargs = dict(shipping_weight=shipping_weight,
                   ip_address=remote_ip,
                   shipping_po=shipping_po,
                   path_db=path_geo_db,
                   path_db_us=path_geo_db_us)
    print(_kwargs)
    shopify_location_address = get_location_address(shop_name, token)
    _kwargs.update({'shopify_location_address': shopify_location_address})
    calc_amount = calc_ecocart(**_kwargs)
    app.logger.warning('calc_amount {}'.format(calc_amount))
    variant_id = get_ecocart_variant(merchant, shipping_weight, calc_amount)

    return jsonify({'calc': calc_amount, 'variant_id': variant_id})
Пример #9
0
def home():
    shop_name = request.args.get('shop')
    api_version = app.config.get('SHOPIFY_API_VERSION')

    if not shop_name:
        abort(403)

    try:
        # проверка подписи
        if not signature_validation(request.args.items(),
                                    app.config['SHOPIFY_API_SECRET']):
            raise Exception('bad sign')

        merchant = Merchant.get(Merchant.shop_name == shop_name)

        with shopify.Session.temp(shop_name, api_version, merchant.token):
            shop = shopify.Shop.current()
            email = shop.email
            myshopify_domain = shop.myshopify_domain
            app.logger.info(myshopify_domain)

    except Merchant.DoesNotExist:
        return reinstall_app(shop_name)

    except pyactiveresource.connection.UnauthorizedAccess:
        # если токен не активен переустановить апп
        return reinstall_app(shop_name)

    except:
        app.logger.warning(traceback.format_exc())
        abort(403)

    #r = requests.get(app.config.get('ECOCART_SETTINGS_URL'))
    #ecocart_settings = r.json()
    with open(app.config.get('ECOCART_SETTINGS_PATH')) as f:
        ecocart_settings = json.load(f)

    product_types = ecocart_settings.get('product_types').items()
    product_types = sorted(product_types, key=lambda item: item[1], reverse=True)
    #product_types = [(row[0], '{} - {}'.format(row[0], row[1])) for row in
    #                 product_types]
    product_types = [(row[0], row[0]) for row in product_types]

    h = ecocart_settings.get('h', 1)
    estimated_calc = ''

    if request.method == 'POST':
        form = SettingsForm()
        form.product_types.choices = product_types
        if form.validate():
            settings = form.data

            # пересчитаем в граммы
            default_weight = 0

            if settings.get('weight_unit') == 'lbs':
                default_weight = float(settings.get('weight'))

            default_weight = round(default_weight, 2)
            settings.update({'default_weight': default_weight})
            settings = json.dumps(settings)
            merchant.settings = settings
            merchant.save()
            return ''
        else:
            errors = form.errors
            _errors = ['{} - {}<br>'.format(k, errors[k]) for k in errors]
            _errors = ''.join(_errors)
            return _errors

    else:
        settings = merchant.settings

        if settings:
            settings = json.loads(settings)

        else:
            settings = dict()

        form = SettingsForm(**settings)
        form.product_types.choices = product_types
        prefix_calc = ''

        try:
            ni_values = {
                '0': 99,
                '100': [100, 249],
                '250': [250, 499],
                '500': [500, 999],
                '1000': [1000, 2499],
                '2500': [2500, 4999],
                '5000': [5000, 7499],
                '7500': [7500, 9999],
                '10000': 10000,
            }
            default_weight = settings.get('default_weight')
            number_of_items = settings.get('number_of_items')
            print(default_weight)
            print(number_of_items)
            ni = ni_values.get(number_of_items)
            print('ni')
            print(ni)
            locale.setlocale(locale.LC_ALL, 'en_US.utf8')

            if isinstance(ni, list):
                result_0 = int(default_weight * ni[0] * h)
                result_1 = int(default_weight * ni[1] * h)
                result_0 = locale.format_string('%d', result_0, True)
                result_1 = locale.format_string('%d', result_1, True)
                estimated_calc = '${}-{}'.format(result_0, result_1)

            else:
                estimated_calc = default_weight * ni * h
                estimated_calc = locale.format_string('%d', estimated_calc, True)
                estimated_calc = '$' + str(estimated_calc)

                if ni == 99:
                    prefix_calc = 'less than'

                elif ni == 10000:
                    prefix_calc = 'more than'

            print(estimated_calc)


        except:
            pass

    return render_template('home.html', form=form, ecocart_h=h,
                           estimated_calc=estimated_calc, shop_name=shop_name,
                           enable=merchant.enable, email=email,
                           prefix_calc=prefix_calc)
Пример #10
0
def finalize():
    code = request.args.get('code')
    shop_name = request.args.get('shop')
    timestamp = request.args.get('timestamp')
    hmac = request.args.get('hmac')
    params = {
        'code': code,
        'timestamp': timestamp,
        'hmac': hmac,
        'shop': shop_name
    }
    api_version = app.config.get('SHOPIFY_API_VERSION')
    shopify.Session.setup(api_key=app.config['SHOPIFY_API_KEY'],
                          secret=app.config['SHOPIFY_API_SECRET'])
    session = shopify.Session(shop_name, api_version)
    token = session.request_token(params)

    try:
        merchant = Merchant.get(Merchant.shop_name == shop_name)

    except Merchant.DoesNotExist:
        merchant = Merchant()
        merchant.enable = False
        merchant.shop_name = shop_name

    merchant.token = token
    merchant.save()

    save_default_html(merchant)

    shop_short = shop_name.replace('.myshopify.com', '')

    need_webhooks = [
        {
            'url': 'https://{}/create_order/{}'.format(
                app.config.get('HOSTNAME'), shop_short),
            'topic': 'orders/create',
            'created': False
        },
        {
            'url': 'https://{}/uninstalled'.format(
                app.config.get('HOSTNAME')),
            'topic': 'app/uninstalled',
            'created': False
        },
    ]

    with shopify.Session.temp(shop_name, api_version, merchant.token):
        webhooks = shopify.Webhook.find()

        for webhook in webhooks:

            for need_webhook in need_webhooks:

                if webhook.topic == need_webhook.get('topic') and \
                        webhook.address == need_webhook.get('url'):
                    need_webhook.update({'created': True})

        for need_webhook in need_webhooks:

            if need_webhook.get('created'):
                continue

            app.logger.info('create webhook {}'.format(need_webhook.get('topic')))
            webhook = shopify.Webhook()
            webhook.topic = need_webhook.get('topic')
            webhook.address = need_webhook.get('url')
            webhook.format = 'json'
            webhook.save()
            pause_sdk(2)

        ecocart_script = shopify.ScriptTag()
        ecocart_script.event = 'onload'
        ecocart_script.src = 'https://{}/ecocart.js?shop_name={}'.format(
            app.config.get('HOSTNAME'), shop_name)
        ecocart_script.save()

    image_url = app.config.get('ECOCART_IMAGE_URL')
    e = Ecocart(image_url, merchant)
    e.install()

    if not app.config.get('CHARGE_ENABLE'):
        url = 'https://{}/admin/apps/{}'
        # редирект в админку
        return redirect(url.format(shop_name, app.config.get('SHOPIFY_API_KEY')))

    # подписка
    return_url = 'https://{}/activatecharge/{}'
    return_url = return_url.format(app.config.get('HOSTNAME'), shop_name)
    data_create = {
        'name': app.config.get('CHARGE_NAME'),
        'price': 0.5,
        'return_url': return_url,
        'test': app.config.get('CHARGE_TEST'),
    }
    url = create_application_charge(shop_name, token, data_create)

    return redirect(url)
Пример #11
0
def create_order_view(shop_short):
    """Обработчик вебхука создания ордера
    :param shop_short:
    :return:
    """
    if not verify(request.get_data(),
                  request.headers.get('X-Shopify-Hmac-Sha256'),
                  app.config.get('SHOPIFY_API_SECRET')):
        app.logger.warning('bad sign')
        abort(403)

    if not request.is_json:
        app.logger.warning('not json')
        abort(403)

    order = request.get_json()
    shop_name = request.headers.get('X-Shopify-Shop-Domain')
    order_id = int(request.headers.get('X-Shopify-Order-Id'))

    try:
        merchant = Merchant.get(Merchant.shop_name == shop_name)

    except Merchant.DoesNotExist:
        abort(404)

    try:
        settings = json.loads(merchant.settings)
        fee = int(settings.get('fee'))

    except:
        app.logger.warning('fee = None')
        fee = None

    ecocart_product = Ecocart_Product.get(Ecocart_Product.merchant == merchant)
    product_id = ecocart_product.shopify_product_id
    order_eco_sum = None

    for item in order.get('line_items'):

        if str(item.get('product_id')) != product_id:
            continue

        order_eco_sum = Decimal(item.get('price'))

    shopify_order = Shopify_Order()
    shopify_order.merchant = merchant
    shopify_order.order_id = order_id

    if order_eco_sum:
        shopify_order.order_eco_sum = order_eco_sum

    shopify_order.currency = order.get('currency')
    shopify_order.order_sum = Decimal(order.get('total_price'))
    shopify_order.fee = fee
    shopify_order.save()
    shopify_order_data = Shopify_Order_Data()
    shopify_order_data.shopify_order = shopify_order
    shopify_order_data.data = json.dumps(order, ensure_ascii=False)
    shopify_order_data.save()

    return ''
Пример #12
0
def ecocart2():
    shop_name = request.form.get('shop_name')
    cart = request.form.get('cart')

    if not shop_name or not cart:
        abort(403)
    cart = json.loads(cart)
    try:
        merchant = Merchant.get(Merchant.shop_name == shop_name)
        token = merchant.token
        print(token)

    except Merchant.DoesNotExist:
        app.logger.warning('not merchant')
        abort(403)

    if not merchant.enable:
        abort(403)

    # проверить экопродукт, установить если удален
    image_url = app.config.get('ECOCART_IMAGE_URL')
    e = Ecocart(image_url, merchant, shop_name)
    shopify_product_id = e.install()

    cart, cart_clear = clear_cart(cart, shopify_product_id)
    shipping_weight = float(cart.get('total_weight', 0))  # граммы
    shipping_weight = shipping_weight * 0.002205
    shipping_weight = round(shipping_weight,
                            1)  # подогнать под количество знаков shopify
    remote_ip = request.headers.get('X-Real-IP')
    latitude = request.form.get('latitude')
    longitude = request.form.get('longitude')
    shipping_po = None
    if latitude and longitude:
        shipping_po = (float(latitude), float(longitude))
    path_geo_db = app.config.get('PATH_GEO_DB')
    path_geo_db_us = app.config.get('PATH_GEO_DB_US')

    try:
        settings = json.loads(merchant.settings)
        default_weight = settings.get('default_weight')

        print('default_weight')
        print(default_weight)

        with open(app.config.get('ECOCART_SETTINGS_PATH')) as f:
            ecocart_settings = json.load(f)

        product_types = ecocart_settings.get('product_types')
        offset_shipping_cost = ecocart_settings.get('offset_shipping_cost')
        offset_manufacturing_cost = ecocart_settings.get(
            'offset_manufacturing_cost')
        fee = ecocart_settings.get('fee')
        secondary_product_types = ecocart_settings.get(
            'secondary_product_types')
        tons_of_co2_offset_variable = ecocart_settings.get(
            'tons_of_co2_offset_variable')

    except:
        print('x')
        abort(403)

    if not settings.get('production'):
        print('prod')
        abort(403)

    _kwargs = dict(cart=cart,
                   ip_address=remote_ip,
                   shipping_po=shipping_po,
                   path_db=path_geo_db,
                   path_db_us=path_geo_db_us,
                   default_weight=default_weight,
                   product_types=product_types,
                   offset_shipping_const=offset_shipping_cost,
                   offset_manufacturing_cost=offset_manufacturing_cost,
                   fee=fee,
                   primary_product_types=settings.get('product_types'),
                   default_shipping_distance=ecocart_settings.get(
                       'default_shipping_distance'),
                   secondary_product_types=secondary_product_types)
    print(_kwargs)
    shopify_location_address = get_location_address(shop_name, token)
    print('*')
    print(shopify_location_address)
    _kwargs.update({'shopify_location_address': shopify_location_address})

    # тип расчета
    calc_amount, ecocart_calc = calc_ecocart(**_kwargs)

    app.logger.warning('calc_amount {}'.format(calc_amount))

    # co 2
    co2 = ((calc_amount - 0.15) * tons_of_co2_offset_variable) * 2205
    co2 = round(co2, 2)
    shipping_weight = co2

    if calc_amount:
        variant_id = get_ecocart_variant(merchant, shipping_weight,
                                         calc_amount)
        calc_amount = '{:.2f}'.format(calc_amount)

    else:
        variant_id = None

    # для компани еще 1 плашку

    return jsonify({
        'calc': calc_amount,
        'variant_id': variant_id,
        'fee': settings.get('fee'),
        'run_result': ecocart_calc.run_result
    })
Пример #13
0
def settings_view():
    shop_name = request.args.get('shop')

    if not shop_name:
        abort(403)

    try:
        # проверка подписи
        if not signature_validation(request.args.items(),
                                    app.config['SHOPIFY_API_SECRET']):
            raise Exception('bad sign')

        merchant = Merchant.get(Merchant.shop_name == shop_name)

    except:
        app.logger.warning(traceback.format_exc())
        abort(403)

    if request.method == 'POST':
        form = SettingsForm()

        if form.validate():
            print(form.data)

            try:
                settings = MerchantSettings.get(
                    MerchantSettings.merchant == merchant)

            except MerchantSettings.DoesNotExist:
                settings = MerchantSettings()
                settings.merchant = merchant

            settings.selector = form.data.get('selector')
            settings.placement = form.data.get('placement')
            settings.selector_method = form.data.get('selector_method')
            settings.js = form.data.get('js')
            default_view = True if form.data.get(
                'default_view') == 'yes' else False
            settings.default_view = default_view
            settings.style = form.data.get('style')
            settings.estimate = form.data.get('estimate')
            settings.shipment = form.data.get('shipment')
            settings.loading = form.data.get('loading')
            settings.error_field = form.data.get('error_field')
            settings.save()

            return ''

        else:
            errors = form.errors
            _errors = ['{} - {}<br>'.format(k, errors[k]) for k in errors]
            _errors = ''.join(_errors)
            return _errors

    else:
        try:
            settings = MerchantSettings.get(
                MerchantSettings.merchant == merchant)
            selector = settings.selector if settings.selector else ''
            placement = settings.placement if settings.placement else ''
            selector_method = settings.selector_method if settings.selector_method else ''
            js = settings.js if settings.js else ''
            default_view = 'yes' if settings.default_view else 'no'
            style = settings.style if settings.style else ''
            estimate = settings.estimate if settings.estimate else ''
            shipment = settings.shipment if settings.shipment else ''
            loading = settings.loading if settings.loading else ''
            error_field = settings.error_field if settings.error_field else ''
            form = SettingsForm(selector=selector,
                                placement=placement,
                                selector_method=selector_method,
                                js=js,
                                default_view=default_view,
                                style=style,
                                estimate=estimate,
                                shipment=shipment,
                                loading=loading,
                                error_field=error_field)

        except MerchantSettings.DoesNotExist:
            form = SettingsForm()

    return render_template('settings.html',
                           form=form,
                           company=settings.company,
                           url_dashboard=settings.url_dashboard,
                           enable=merchant.enable,
                           shop_name=shop_name,
                           hostname=app.config.get('HOSTNAME'))