コード例 #1
0
 def create_merchant():
     try:
         body = request.get_json()
         merchant = Merchant(name=body['name'],
                             city=body['city'],
                             email=body['email'])
         merchant.insert()
     except KeyError:
         abort(500)
     return jsonify({"success": True, "merchant": merchant.format()})
コード例 #2
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')
コード例 #3
0
def upload_v1(conn, fileitem):
    import csv
    import repositories
    from models import Merchant, Sale, Upload

    upload = Upload()
    upload = repositories.UploadRepository(conn).create(upload)

    for row in csv.DictReader(fileitem.file, delimiter="\t"):
        merchant = Merchant(name=row['merchant name'].decode('utf-8'),
                            address=row['merchant address'].decode('utf-8'))
        merchant = repositories.MerchantRepository(conn).create(merchant)

        sale = Sale(upload=upload,
                    merchant=merchant,
                    purchaser_name=row['purchaser name'].decode('utf-8'),
                    description=row['item description'].decode('utf-8'),
                    unit_price=row['item price'],
                    count=row['purchase count'])
        sale = repositories.SaleRepository(conn).create(sale)
        upload.add_sale(sale)

    repositories.UploadRepository(conn).save(upload)

    return upload
コード例 #4
0
def otp(request):
    otp_entered = request.POST.get('otp_entered', False)

    username = request.session['username']
    password = request.session['password']
    email_id = request.session['email']
    user_type = request.session['user_type']
    otp_generated = request.session['otp_generated']

    if (otp_entered == False or otp_entered != otp_generated):
        return render(request, "signup/signup.html",
                      {'message': "Invalid OTP!!!"})

    if (user_type == "customer"):
        new_user = Customer()
        page_to_redirect = "customer/home.html"

    elif (user_type == "regular_employee" or user_type == "system_manager"
          or user_type == "system_admin"):
        new_user = Employee()
        new_user.cadre = user_type
        page_to_redirect = user_type + "/home.html"

    elif (user_type == "merchant"):
        new_user = Merchant()
        page_to_redirect = "merchant/home.html"

    new_user.username = username
    new_user.password = password
    new_user.email = email_id
    new_user.save()
    return render(request, page_to_redirect, {'username': username})
コード例 #5
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
コード例 #6
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 ''
コード例 #7
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)
コード例 #8
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)
コード例 #9
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')))
コード例 #10
0
ファイル: handlers.py プロジェクト: MikeLindenau/qrowder
 def post(self):
     data = request.json
     mid = new_id()
     name = "mikes bike shop"
     m = Merchant(mid = mid, name = name)
     success = m.put()
     if success:
         message = {
         'status': 200,
         'message': 'success',
         }
         resp = jsonify(message)
         resp.status_code = 200
     
         return resp
     else:
         message = {
             'status': 404,
             'message': 'bad data',
         }
         resp = jsonify(message)
         resp.status_code = 404
     
         return resp
コード例 #11
0
def add_merchant():
    user = g.user
    form = MerchantForm()
    if form.validate_on_submit():
        try:
            merchant = db.session.query(Merchant).filter_by(
                name=form.merchant.data.strip().lower()).one()
        except:
            merchant = Merchant(name=form.merchant.data.strip().lower())
            db.session.add(merchant)
            db.session.commit()
            flash(
                "The Merchant: '{}' was added".format(
                    form.merchant.data.strip()), 'success')
            return redirect(url_for('dashboard'))
    return render_template('add_merchant.html', user=user, form=form)
コード例 #12
0
ファイル: app.py プロジェクト: rithik/Financia
def merchant_create_user():
    if request.method == "POST":
        name = request.form["name"]
        email = request.form["email"]
        password = request.form["password"]
        confirm_password = request.form["confirm_password"]
        if not email.index("@") > 0 and not email.index(".") > email.index(
                "@"):
            return redirect(url_for('.home_page'))
        if not confirm_password == password:
            return redirect(url_for('.home_page'))
        u = Merchant.query.filter_by(email=email).count()
        if u == 0:
            new_merchant = Merchant(name, email, password)
            db_session.add(new_merchant)
            db_session.commit()
            print('Created Merchant', file=sys.stderr)
            return redirect(url_for('.home_page'))
        return redirect(url_for('.home_page'))
コード例 #13
0
ファイル: views.py プロジェクト: fhfengzhiyong/fan
def add():
    if request.method == 'GET':
        return render_template('merchant/add.html')
    #merchant  = addMerchantFrom()
    form = request.form
    merchant = Merchant()
    print merchant.id
    merchant.name = form.get('name')
    merchant.link_name = form.get('link_name')
    merchant.address = form.get('address')
    merchant.mobile = form.get('mobile')
    merchant.qq = form.get('qq')
    merchant.we_chat = form.get('we_chat')
    merchant.mail = form.get('mail')
    session = DBSession()
    state = session.add(merchant)
    session.commit()
    session.close()
    #print merchant.id
    retult=None
    flash('添加成功!')
    return render_template('merchant/add.html',retult=retult)
コード例 #14
0
ファイル: view_home.py プロジェクト: baljinderimpinge/shopify
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)
コード例 #15
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})
コード例 #16
0
def save():
    # import ipdb; ipdb.set_trace()
    create_merchant()
    create_purchase()

    lines = []
    i = 0
    receita_total = 0

    file_upload = request.files.get('file')
    content = file_upload.read()
    lines = content.split('\n')
    for line in lines:
        #pula o cabecalho
        if i == 0:
            i = i + 1
            continue

        if line == '':
            continue

        line = line.split('\t')
        merchant = Merchant(line[index_merchant_name],
                            line[index_merchant_adress])
        purchase = Purchase(line[index_puchaser_name],
                            line[index_item_description],
                            float(line[index_item_price]),
                            int(line[index_purchase_count]),
                            line[index_merchant_name])
        receita_total = float(line[index_item_price]) * int(
            line[index_purchase_count]) + receita_total

        insere_merchant(merchant)
        insere_purchase(purchase)

    return render_template('save.html', receita=receita_total)
コード例 #17
0
ファイル: view_home.py プロジェクト: baljinderimpinge/shopify
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)
コード例 #18
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)
コード例 #19
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
    })
コード例 #20
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 ''
コード例 #21
0
ファイル: admin.py プロジェクト: zhanghui9700/pykit
    def save_model(self,request,obj,form,change):
        if request.method =='POST':
            form=MerchantForm(request.POST)
            if form.is_valid():
                #pdb.set_trace()
                if not change:
                    Personc=form.cleaned_data
                    allowed_amount=Personc['allowed_amountv1']<<16|Personc['allowed_amountv2']
                    sa=Merchant(user = Personc['user'],
                              company = Personc['company'],
                              nickname = Personc['nickname'],
                              legal_person = Personc['legal_person'],
                              id_number = Personc['id_number'],
                              id_stat_date = Personc['id_stat_date'],
                              id_end_date = Personc['id_end_date'],
                              id_photo1 = Personc['id_photo1'],
                              id_photo2 = Personc['id_photo2'],
                              license_number = Personc['license_number'],
                              license_end_date = Personc['license_end_date'],
                              license_photo = Personc['license_photo'],
                              tax_number = Personc['tax_number'],
                              tax_end_date = Personc['tax_end_date'],
                              tax_photo = Personc['tax_photo'],
                              orgcode = Personc['orgcode'],
                              business_addr = Personc['business_addr'],
                              latitude = Personc['latitude'],
                              longitude = Personc['longitude'],
                              city = Personc['city'],
                              contact = Personc['contact'],
                              telephone = Personc['telephone'],
                              mobile = Personc['mobile'],
                              email = Personc['email'],
                              post = Personc['post'],
                              mcc = Personc['mcc'],
                              bankname = Personc['bankname'],
                              bankuser = Personc['bankuser'],
                              bankaccount = Personc['bankaccount'],
                              creditbank = Personc['creditbank'],
                              creditcard = Personc['creditcard'],
                              month_turnover = Personc['month_turnover'],

                              allowed_trade = Personc['allowed_trade'],
                              allowed_time = Personc['allowed_time'],
                              allowed_card = Personc['allowed_card'],
                              allowed_currency = Personc['allowed_currency'],
                              allowed_amount = allowed_amount,
                              last_admin = request.user.id)
                    sa.save()
                    return HttpResponseRedirect('/admin/usermanager/merchant/')
                else:
                    Personc = form.cleaned_data
                    allowed_amount=Personc['allowed_amountv1']<<16|Personc['allowed_amountv2']
                    userlevel = Personc['userlevel']
                    User.objects.filter(id=Personc['user'].id).update(
                            user_level = userlevel
                    )
                    Merchant.objects.filter(user=Personc['user']).update(
                              company = Personc['company'],
                              nickname = Personc['nickname'],
                              legal_person = Personc['legal_person'],
                              id_number = Personc['id_number'],
                              id_stat_date = Personc['id_stat_date'],
                              id_end_date = Personc['id_end_date'],
                              id_photo1 = Personc['id_photo1'],
                              id_photo2 = Personc['id_photo2'],
                              license_number = Personc['license_number'],
                              license_end_date = Personc['license_end_date'],
                              license_photo = Personc['license_photo'],
                              tax_number = Personc['tax_number'],
                              tax_end_date = Personc['tax_end_date'],
                              tax_photo = Personc['tax_photo'],
                              orgcode = Personc['orgcode'],
                              business_addr = Personc['business_addr'],
                              latitude = Personc['latitude'],
                              longitude = Personc['longitude'],
                              city = Personc['city'],
                              contact = Personc['contact'],
                              telephone = Personc['telephone'],
                              mobile = Personc['mobile'],
                              email = Personc['email'],
                              post = Personc['post'],
                              mcc = Personc['mcc'],
                              bankname = Personc['bankname'],
                              bankuser = Personc['bankuser'],
                              bankaccount = Personc['bankaccount'],
                              creditbank = Personc['creditbank'],
                              creditcard = Personc['creditcard'],
                              month_turnover = Personc['month_turnover'],

                              allowed_trade = Personc['allowed_trade'],
                              allowed_time = Personc['allowed_time'],
                              allowed_card = Personc['allowed_card'],
                              allowed_currency = Personc['allowed_currency'],
                              allowed_amount = allowed_amount,
                              last_admin = request.user.id)
                    return HttpResponseRedirect('/admin/usermanager/merchant/')
コード例 #22
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'))