def coin_listing():
    if REFRESH_COIN_LIST:
        mdb.db.currencies.remove({})

        url = 'https://api.coinmarketcap.com/v2/listings/'
        response = try_request(url)
        if response.status_code == 200:
            data = response.text
            data = json.loads(data)
            print(data)
            data = data['data']
            coin_list = []
            for coin in data:
                coin_list.append({
                    'id': coin['id'],
                    'name': coin['name'],
                    'symbol': coin['symbol'],
                    'websiteSlug': coin['website_slug']
                })
            Currency.insert_many(coin_list)
        else:
            print('get coin list fail')

    coin_objects = Currency.find({})
    return coin_objects
예제 #2
0
def update_currency():
    params = {'access_key': FIXER_ACCESS_KEY, 'format': 2}
    req = requests.get(FIXER_URL, params=params)
    if req.status_code != 200:
        logger.error("Currency API %s return status code %s" % (FIXER_URL, req.status_code))

        # Перезапрос в случае ошибки
        time.sleep(15)
        logger.info('New request...')

        req = requests.get(FIXER_URL, params=params)
        if req.status_code != 200:
            msg = "Currency Pairs API %s return status code %s" % (FIXER_URL, req.status_code)
            logger.error(msg)
            return bad_request(msg)
    data = req.json()
    base = data['base']
    for quote in data['rates']:
        if not Currency.query.filter_by(quote=quote).first():
            curr = Currency(base=base, quote=quote, rate=data['rates'][quote])
        else:
            curr = Currency.query.filter_by(quote=quote).first()
            curr.rate = data['rates'][quote]
        db.session.add(curr)
        db.session.commit()
    msg = 'Updated currency successful'
    logger.info(msg)
    return msg
예제 #3
0
def seed_currencies():
    currency1 = Currency(name="EUR/USD")
    currency2 = Currency(name="EUR/GBP")
    currency3 = Currency(name="AUD/USD")
    currency4 = Currency(name="USD/CAD")
    currency = [currency1, currency2, currency3, currency4]
    db.session.add_all(currency)
    db.session.commit()
예제 #4
0
def test_seed():
    user_list = [User(email='*****@*****.**'), User(email='*****@*****.**')]
    transaction_list = [
        Transaction(date=date(2019, 1, 12),
                    buy_currency='BTC',
                    buy_amount=1.1,
                    sell_currency='USD',
                    sell_amount=1000,
                    user_id=1),
        Transaction(date=date(2019, 3, 12),
                    buy_currency='USD',
                    buy_amount=600.0,
                    sell_currency='BTC',
                    sell_amount=0.7,
                    user_id=1),
        Transaction(date=date(2019, 5, 20),
                    buy_currency='ETH',
                    buy_amount=5.0,
                    sell_currency='USD',
                    sell_amount=1200.0,
                    user_id=1),
        Transaction(date=date(2019, 5, 20),
                    buy_currency='ETH',
                    buy_amount=5.0,
                    sell_currency='USD',
                    sell_amount=1200.0,
                    user_id=2)
    ]
    currency_list = [
        Currency(cd='USD', name='United States Dollar', asset_type='fiat'),
        Currency(cd='GBP', name='British Pound', asset_type='fiat'),
        Currency(cd='BTC', name='Bitcoin', asset_type='crypto'),
        Currency(cd='LTC', name='Litecoin', asset_type='crypto'),
        Currency(cd='ETH', name='Ethereum', asset_type='crypto')
    ]

    curr_dt = datetime.today()
    last_month = curr_dt + timedelta(days=-30)
    price_list = [
        Price(ts=last_month,
              buy_currency='BTC',
              sell_currency='USD',
              rate=10000),
        Price(ts=curr_dt, buy_currency='BTC', sell_currency='USD', rate=15000),
        Price(ts=last_month, buy_currency='ETH', sell_currency='USD',
              rate=100),
        Price(ts=curr_dt, buy_currency='ETH', sell_currency='USD', rate=200),
        Price(ts=last_month, buy_currency='USD', sell_currency='USD', rate=1),
        Price(ts=curr_dt, buy_currency='USD', sell_currency='USD', rate=1)
    ]

    drop_create_tables(3, 5)
    add_records(user_list, transaction_list, currency_list, price_list)
    def setUp(self):
        self.current_rate = Rate(
            from_currency=Currency(code="BTC"),
            to_currency=Currency(code="USD"),
            rate=Decimal("2"),
            rate_open=Decimal("11"),
            last_trade_at=datetime(2019, 3, 8, 11, 10, 0),
        )

        self.new_rate = Rate(
            from_currency=Currency(code="BTC"),
            to_currency=Currency(code="USD"),
            rate=Decimal("1"),
            last_trade_at=datetime(2019, 3, 9, 12, 11, 0),
        )
예제 #6
0
def save_course(result):

    for el in result:
        currency = Currency()
        currency.time = datetime.now()
        currency.ccy = el['ccy']
        currency.base_ccy = el['base_ccy']
        currency.buy = el['buy']
        currency.sale = el['sale']
        currency.save()

    return result
예제 #7
0
def get_currencies():
    with app.app_context():
        api_key = 'fe2fbe9c5446ea780042'
        # fe2fbe9c5446ea780042
        # 238c003007bb6d0ad0d8
        base_url = "https://free.currconv.com"
        currencies = [
            'USD_RUB', 'EUR_RUB', 'GBP_RUB', 'SEK_RUB', 'BTC_RUB', 'EUR_USD'
        ]

        response = {}

        params = {'q': '', 'compact': 'ultra', 'apiKey': api_key}

        for curr in currencies:
            params['q'] = curr
            r = requests.get('{}/api/v7/convert'.format(base_url),
                             params=params,
                             headers=headers)
            response[curr] = r.json()[curr]

        currencies = Currency(datetime.utcnow(), json.dumps(response),
                              r.status_code)

        db.session.add(currencies)
        db.session.commit()
        return response
예제 #8
0
def get_current_prices():
    all_cryptos = ",".join(Currency.list_codes())
    resp = get(
        url="https://min-api.cryptocompare.com/data/pricemulti",
        params={"fsyms": all_cryptos, "tsyms": "USD", "api_key": env["PRICE_API_KEY"]},
    )
    return resp.json()
예제 #9
0
def edit_currency(guid):
    if not current_user.is_admin:
        flash(_('Only an admin is allowed to edit currencies!'))
        log_page_access_denied(request, current_user)
        return redirect(url_for('main.currencies'))
    log_page_access(request, current_user)
    currency = Currency.get_by_guid_or_404(guid)
    form = CurrencyForm()
    if form.validate_on_submit():
        currency.code = form.code.data
        currency.name = form.name.data
        currency.number = form.number.data
        currency.exponent = form.exponent.data
        currency.inCHF = form.inCHF.data
        currency.description = form.description.data
        db.session.commit()
        flash(_('Your changes have been saved.'))
        return redirect(url_for('main.currencies'))
    elif request.method == 'GET':
        form.code.data = currency.code
        form.name.data = currency.name
        form.number.data = currency.number
        form.exponent.data = currency.exponent
        form.inCHF.data = currency.inCHF
        form.description.data = currency.description
    return render_template('edit_form.html',
                           title=_('Edit Currency'),
                           form=form)
예제 #10
0
def seed_command():
    Currency.query.delete()
    click.echo('-----------------')
    click.echo('Remove currencies')
    for data in Currencies.data:
        obj = Currency(**data)
        db.session.add(obj)
        db.session.commit()
        click.echo('Currency ' + obj.symbol + ' created')

    Category.query.delete()
    click.echo('-----------------')
    click.echo('Remove categories')
    for data in Categories.data:
        obj = Category(**data)
        db.session.add(obj)
        db.session.commit()
        click.echo('Category ' + obj.name + ' created')

    Account.query.delete()
    click.echo('---------------')
    click.echo('Remove accounts')
    for data in Accounts.data:
        obj = Account(**data)
        db.session.add(obj)
        db.session.commit()
        click.echo('Account ' + obj.name + ' created')
예제 #11
0
    def __init__(self, form_data: dict):
        self.data = form_data
        self.curr = form_data.get('currency') or form_data.get('shop_currency')
        self.method = self.methods_map.get(
            Currency().query.filter(Currency.code == self.curr).first().name,
            'invoice')
        self.fields = self.sign_fields[self.method]
        if not self.data.get('shop_order_id'):
            order = Order(amount=self.data['amount'],
                          currency_id=Currency().query.filter(
                              Currency.code == self.curr).first().id,
                          stime=datetime.now(),
                          user_id=current_user.id)
            db.session.add(order)
            db.session.commit()
            self.data['shop_order_id'] = order.id

        self.data.update({
            'shop_id': app.config['SHOP_ID'],
        })
예제 #12
0
def UpdateCurrencyTable(request):

    response = requests.get(
        'https://free.currencyconverterapi.com/api/v5/currencies')
    oData = response.json()
    oData = oData['results']

    for k, v in oData.items():
        try:
            cSymbol = v['currencySymbol']
        except:
            cSymbol = ''

        new_entry = Currency(Code=v['id'],
                             Name=v['currencyName'],
                             Symbol=cSymbol)
        new_entry.save()

    tmpl_vars = {}
    return render(req, 'app/index.html', tmpl_vars)
def pump_currencies_table():
    print('currencies')

    currencies = [
        ('Nigerian Naira',          'NGN',      '0.0028'),
        ('United States Dollar',    'USD',      '1'),
        ('Pound Sterling',          'GBP',      '1.30'),
        ('South African Rand',      'ZAR',      '0.07')
    ]

    for name, short_code, usd_equivalent in currencies:
        if Currency.get_active(name=name):
            continue

        Currency(
            name=name,
            short_code=short_code,
            usd_equivalent=usd_equivalent).save()

    return
예제 #14
0
파일: cli.py 프로젝트: mredle/expenseapp
    def currencies(overwrite):
        """Initialize currencies with predefined values."""

        # Fill currencies from CSV file
        currencies = []
        with open('app/resources/currencies.csv', 'r',
                  encoding='utf-8') as csv_file:
            csv_reader = csv.reader(csv_file, delimiter=';')
            line_count = 0
            for row in csv_reader:
                if line_count == 0:
                    line_count += 1
                else:
                    line_count += 1
                    if len(row[1]) > 64:
                        na = row[1][0:64]
                    else:
                        na = row[1]
                    try:
                        e = int(row[4])
                    except ValueError:
                        e = 0

                    try:
                        nu = int(row[3])
                    except ValueError:
                        nu = 0

                    c = Currency(code=row[2].upper(),
                                 name=na,
                                 number=nu,
                                 exponent=e,
                                 inCHF=1,
                                 description=row[0],
                                 db_created_by='flask dbinit currency')
                    currencies.append(c)

        for currency in currencies:
            existing_currency = Currency.query.filter_by(
                code=currency.code).first()
            if existing_currency:
                if overwrite:
                    existing_currency.code = currency.code
                    existing_currency.name = currency.name
                    existing_currency.number = currency.number
                    existing_currency.exponent = currency.exponent
                    existing_currency.description = currency.description
                    existing_currency.db_created_by = currency.db_created_by
                    db.session.commit()
            else:
                db.session.add(currency)
                db.session.commit()
예제 #15
0
    def fun():
        from app.models import Currency

        Currency.objects.all().delete()
        currency = Currency()
        currency.name = "test_currency"
        currency.endpoint = "test_endpoint"
        currency.save()
        return Currency.objects.all()[0]  # noqa
예제 #16
0
파일: routes.py 프로젝트: cdcf/t-e-manager
def add_currency():
    form = CurrencyForm()
    if current_user.can(Permission.WRITE) and form.validate_on_submit():
        currency = Currency(name=form.name.data,
                            description=form.description.data,
                            default_curr=form.default_curr.data)
        db.session.add(currency)
        db.session.commit()
        flash('Currency has been created', 'success')
        return redirect(url_for('currencies.add_currency'))
    elif request.method != "GET":
        flash_errors(form)
    page = request.args.get('page', 1, type=int)
    pagination = Currency.query.order_by(Currency.name.desc()).paginate(page, 5, False)
    currencies = pagination.items
    return render_template('settings/add_currency.html', title='Add a Currency', form=form,
                           currencies=currencies, pagination=pagination)
예제 #17
0
 def invoice(self):
     curr = Currency().query.filter(Currency.code == self.curr).first()
     self.data.update({
         'payway': curr.payway,
         'currency': curr.code,
     })
     self.sign = auth.sign(
         {k: v
          for k, v in self.data.items() if k in self.fields})
     self.data.update({
         'sign': self.sign,
         'amount': str(self.data['amount'])
     })
     data = self._request_piastrix()
     if data.get('error_code', 0):
         self.res.update({'tpl': 'error.html', 'data': data})
         return self.res
     res.update({'data': data.get('data', {})})
     return res
예제 #18
0
def create_currency(country_id,
                    id,
                    title,
                    prefix=None,
                    suffix=None,
                    quiet=True):
    currency = Currency()

    currency.country_id = country_id
    currency.id = id
    currency.title = title
    currency.prefix = prefix
    currency.suffix = suffix

    db.session.add(currency)
    db.session.commit()

    if not quiet:
        print 'Currency created: %s' % currency.id
예제 #19
0
def new_currency():
    if not current_user.is_admin:
        flash(_('Only an admin is allowed to create new currencies!'))
        log_page_access_denied(request, current_user)
        return redirect(url_for('main.currencies'))
    log_page_access(request, current_user)
    form = CurrencyForm()
    if form.validate_on_submit():
        currency = Currency(code=form.code.data,
                            name=form.name.data,
                            number=form.number.data,
                            exponent=form.exponent.data,
                            inCHF=form.inCHF.data,
                            description=form.description.data,
                            db_created_by=current_user.username)

        db.session.add(currency)
        db.session.commit()
        flash(_('Your new currency has been added.'))
        return redirect(url_for('main.currencies'))
    return render_template('edit_form.html',
                           title=_('New Currency'),
                           form=form)
예제 #20
0
from tasks.currency_mapping import crypto_mapping, fiat_mapping
from app.models import Currency
from app import db

print('Truncating currency table...')
Currency.query.delete()

print('Adding currencies...')
for name, code in crypto_mapping:
    curr = Currency(cd=code, name=name, asset_type='crypto')
    db.session.add(curr)
for name, code in fiat_mapping:
    curr = Currency(cd=code, name=name, asset_type='fiat')
    db.session.add(curr)
db.session.commit()
print('Finished')
예제 #21
0
def get_currencies():
    return make_response(jsonify(result=Currency.list_codes()), 200)
예제 #22
0
def pay_with_bank():
    user = User(current_user)
    party = user.party
    today = date.today()
    courses = []
    subscriptions = Subscription.search([('is_online', '=', True),
                                         ('party', '=', party.id),
                                         ('state', '=', 'running')])
    if len(subscriptions) < 1:
        return render_template(
            'bienvenido.html',
            user=user,
            flash_message=
            "Something wrong. Sorry the inconvenient. We will call you later.")
    else:
        for subscription in subscriptions:
            for line in subscription.lines:
                courses.append(line.service.id)
    with Transaction().set_context(courses=courses):
        if user.active_membership:
            return redirect(url_for('course.index'))

    ip_address = request.remote_addr
    if not ip_address or ip_address == '127.0.0.1':
        ip_address = '186.189.195.217'
    if ipaddress.ip_address(ip_address).is_private:
        ip_address = '186.189.195.217'
    access_token = 'cda5ddffc1e6b7'
    handler = ipinfo.getHandler(access_token)

    details = handler.getDetails(ip_address)
    country_code = details.country
    country_code = str(country_code)
    lcase_country_code = country_code.lower()
    currency_id = 16

    for currency in data:
        if str(currency['code']) == country_code:
            currency_id = currency['id']
            break
    currency = Currency(currency_id)

    subscriptions = Subscription.search([('party', '=', party.id),
                                         ('is_online', '=', True),
                                         ('state', '=', 'running')])

    invoices = Invoice.search([
        ('party', '=', party.id),
        ('state', '=', 'posted'),
    ],
                              limit=1)

    current_line = None
    for invoice in invoices:
        move = invoice.move
        lines = move.lines
        for line in lines:
            if line.debit > 0:
                current_line = MoveLine(line.id)
                break
    if current_line is not None:
        enroll_form = EnrollRegistrationForm(invoice=current_line.description,
                                             amount=current_line.debit)
    if len(subscriptions) >= 1 and len(invoices) >= 1:
        if enroll_form.validate_on_submit():

            def _group_payment_key(payment):
                return (('journal', payment.journal.id), ('kind',
                                                          payment.kind))

            def _new_group(values):
                return PaymentGroup(**values)

            invoice = enroll_form.invoice.data
            amount = enroll_form.amount.data
            ticket = enroll_form.ticket.data
            if not current_line:
                return redirect(url_for('main.welcome'))
            journal, = Journal.search([('name', '=', 'DCOMPENSA')], limit=1)
            new_payment = Payment.create([{
                'journal': journal.id,
                'kind': 'receivable',
                'party': party.id,
                'line': current_line.id,
                'description': ticket,
                'amount': current_line.debit,
            }])
            Payment.approve(new_payment)
            payment, = new_payment
            groups = []
            new_payment = sorted(new_payment, key=_group_payment_key)
            for key, grouped_payments in groupby(new_payment,
                                                 key=_group_payment_key):

                def group():
                    group = _new_group(dict(key))
                    group.save()
                    groups.append(group)
                    return group

                Payment.process(list(grouped_payments), group)
            body = "Hemos recibido la siguiente informacion: " + \
                "Nombre: "+ party.name + \
                " \n  Ticket: " + ticket + \
                " \n  Usuario: " + user.email

            msg = Message('Usuario Web API: '+ party.name, \
                sender = '*****@*****.**', \
                recipients = ['*****@*****.**'])
            msg.body = "Usuario Web API " + body
            mail.send(msg)

            return redirect(url_for('main.welcome'))
        return render_template('course/pay_enroll_with_bank.html',
                               user=user,
                               enroll_form=enroll_form,
                               invoices=invoices,
                               subscriptions=subscriptions,
                               currency=currency)
    else:
        return redirect(url_for('course.index'))
예제 #23
0
def validate_currency(curr):
    if curr not in Currency.list_codes():
        raise ValidationError("Invalid currency")
예제 #24
0
from app import app, db
from app.models import Currency
from datetime import date
import requests
import xml.etree.ElementTree as ET

today = date.today()
date = today.strftime("%Y-%m-%d")

response = requests.get("https://www.cbar.az/currencies/" +
                        today.strftime("%d.%m.%Y") + ".xml")
mytree = ET.fromstring(response.content)

for x in mytree[1]:
    code = x.attrib.get('Code')
    value = x.find('Value').text
    name = x.find('Name').text

    curr = Currency(name, code, value, date)
    db.session.add(curr)
    db.session.commit()
예제 #25
0
def enroll():
    bank_form = EnrollBankForm()
    cc_form = EnrollCreditCardForm()

    course_id = request.args.get('course')
    base_url = request.url_root
    if course_id == None:
        return redirect(url_for('course.index'))
    course_id = int(course_id)
    user = User(current_user)
    web_courses = Course.search([('id', '=', course_id)], limit=1)
    if len(web_courses) == 1:
        web_course, = web_courses
    else:
        print("NOT COURSE FOUND")
        return redirect(url_for('course.index'))

    ip_address = request.remote_addr
    if not ip_address or ip_address == '127.0.0.1':
        ip_address = '186.189.195.217'
    if ipaddress.ip_address(ip_address).is_private:
        ip_address = '186.189.195.217'
    access_token = 'cda5ddffc1e6b7'
    handler = ipinfo.getHandler(access_token)

    details = handler.getDetails(ip_address)
    country_code = details.country
    country_code = str(country_code)
    lcase_country_code = country_code.lower()
    currency_id = 16

    for currency in data:
        if str(currency['code']) == country_code:
            currency_id = currency['id']
            break
    currency = Currency(currency_id)

    courses = []
    courses.append(web_course.service.id)
    courses.append(web_course.yearly_service.id)
    with Transaction().set_context(courses=courses):
        user = User(current_user)
        if user.active_membership:
            return redirect(base_url + '/cursos/' + web_course.slug)
            #return redirect(url_for('course.index', web_course.slug))
    party = user.party
    courses = Course.search([('id', '=', course_id)], limit=1)
    today = date.today()
    if len(courses) == 1:
        course, = courses
        service_id = course.service.id
        yearly_service_id = course.yearly_service.id
        product_id = course.service.product.id
        yearly_product_id = course.yearly_service.product.id
        # for local currency
        with Transaction().set_context(product_web=product_id,
                                       currency_web=currency_id):
            price_monthly = Product.get_webshop_sale_price([])
        with Transaction().set_context(product_web=yearly_product_id,
                                       currency_web=currency_id):
            price_yearly = Product.get_webshop_sale_price([])
        # for US currency
        with Transaction().set_context(product_web=product_id,
                                       currency_web=64):
            dollar_price_monthly = Product.get_webshop_sale_price([])
        with Transaction().set_context(product_web=yearly_product_id,
                                       currency_web=64):
            dollar_price_yearly = Product.get_webshop_sale_price([])
    subscriptions = Subscription.search([
        ('party', '=', party.id),
        ('state', '=', 'running'),
        ('is_online', '=', True),
        ('lines.service', '=', service_id),
    ])
    subscriptions_yearly = Subscription.search([
        ('party', '=', party.id),
        ('state', '=', 'running'),
        ('is_online', '=', True),
        ('lines.service', '=', yearly_service_id),
    ])

    if len(subscriptions) >= 1 or len(subscriptions_yearly) >= 1:
        return redirect(url_for('course.payment'))
    else:
        defaults = {}
        defaults['user'] = user
        defaults['course'] = course_id
        defaults['web_course'] = web_course
        defaults['price_monthly'] = price_monthly
        defaults['price_yearly'] = price_yearly
        defaults['dollar_price_monthly'] = dollar_price_monthly
        defaults['dollar_price_yearly'] = dollar_price_yearly
        defaults['currency'] = currency
        defaults['country_code'] = country_code
        defaults['country_code_iso'] = lcase_country_code
        defaults['bank_form'] = bank_form
        defaults['cc_form'] = cc_form
        return render_template('course/enroll.html', **defaults)
예제 #26
0
def buy_with_bank():
    course_id = request.args.get('course')
    if course_id == None:
        return redirect(url_for('course.index'))

    bank_form = EnrollBankForm()
    cc_form = EnrollCreditCardForm()
    course_id = int(course_id)
    user = User(current_user)
    courses = []
    courses.append(course_id)
    with Transaction().set_context(courses=courses):
        user = User(current_user)
        if user.active_membership:
            return redirect(url_for('course.index'))
    courses = Course.search([('id', '=', course_id)], limit=1)
    if len(courses) == 1:
        course, = courses
        if bank_form.bank_membership.data == 'MONTHLY':
            service_id = course.service.id
        else:
            service_id = course.yearly_service.id
        service = Service(service_id)
    if course:
        web_course = course

    ip_address = request.remote_addr
    if not ip_address or ip_address == '127.0.0.1':
        ip_address = '186.189.195.217'
    if ipaddress.ip_address(ip_address).is_private:
        ip_address = '186.189.195.217'
    access_token = 'cda5ddffc1e6b7'
    handler = ipinfo.getHandler(access_token)

    details = handler.getDetails(ip_address)
    country_code = details.country
    country_code = str(country_code)
    lcase_country_code = country_code.lower()
    currency_id = 16

    for currency in data:
        if str(currency['code']) == country_code:
            currency_id = currency['id']
            break
    currency = Currency(currency_id)

    if bank_form.validate_on_submit():
        party = user.party
        today = date.today()
        subscriptions = Subscription.search([
            ('party', '=', party.id),
            ('state', '=', 'running'),
            ('lines.service', '=', service_id),
        ])
        if len(subscriptions) >= 1:
            print("NO ACTIVE SUBSCRIPTIONS")
            return redirect(url_for('course.payment'))
        else:
            enrolment, = Product.search([('is_enrolment', '=', True)], limit=1)
            payment_term, = PaymentTerm.search([()], limit=1)
            address = user.party.addresses[0]
            new_subscription = Subscription.create([{
                'party':
                user.party.id,
                'start_date':
                today,
                'invoice_start_date':
                today,
                'invoice_recurrence':
                service.consumption_recurrence,
                'enrolment':
                enrolment.id,
                'unit_price_enrolment':
                0,
                'invoice_address':
                address,
                'is_online':
                True,
                'payment_term':
                payment_term.id,
            }])
            new_subscription_line, = SubscriptionLine.create([{
                'subscription':
                new_subscription[0].id,
                'service':
                service.id,
                'quantity':
                1,
                'start_date':
                today,
                'consumption_recurrence':
                service.consumption_recurrence,
                'unit':
                1,
                'unit_price':
                service.product.list_price,
            }])
            Subscription.quote(new_subscription)
            Subscription.run(new_subscription)
            SaleSubscriptionLine.generate_consumption(date=today,
                                                      party=user.party)
            Subscription.generate_invoice(date=today, party=user.party)
            invoices = Invoice.search([('party', '=', user.party)],
                                      order=[('number', 'DESC')])
            if len(invoices) >= 1:
                for invoice in invoices:
                    if invoice.state == 'draft':
                        Invoice.post([invoice])

            current_line = None
            current_invoice = None

            for invoice in invoices:
                if invoice.state not in ['cancel', 'paid']:
                    move = invoice.move
                    for line in move.lines:
                        if line.debit > 0:
                            current_line = MoveLine(line.id)
                            current_invoice = invoice
                            break
            if not current_line or not current_invoice:
                return redirect(url_for('main.welcome'))

            def _group_payment_key(payment):
                return (('journal', payment.journal.id), ('kind',
                                                          payment.kind))

            def _new_group(values):
                return PaymentGroup(**values)

            invoice = current_invoice
            amount = current_invoice.total_amount
            ticket = bank_form.ticket.data
            journal, = Journal.search([('name', '=', 'DCOMPENSA')], limit=1)
            new_payment = Payment.create([{
                'journal': journal.id,
                'kind': 'receivable',
                'party': party.id,
                'line': current_line.id,
                'description': ticket,
                'amount': current_line.debit,
            }])
            Payment.approve(new_payment)
            payment, = new_payment
            groups = []
            new_payment = sorted(new_payment, key=_group_payment_key)
            for key, grouped_payments in groupby(new_payment,
                                                 key=_group_payment_key):

                def group():
                    group = _new_group(dict(key))
                    group.save()
                    groups.append(group)
                    return group

                Payment.process(list(grouped_payments), group)
            body = "Hemos recibido la siguiente informacion: " + \
                "Nombre: "+ party.name + \
                " \n  Ticket: " + ticket + \
                " \n  Usuario: " + user.email

            msg = Message('Usuario Web API: '+ party.name, \
                sender = '*****@*****.**', \
                recipients = ['*****@*****.**'])
            msg.body = "Usuario Web API " + body
            mail.send(msg)

            return redirect(url_for('main.welcome'))

    return render_template('course/enroll.html',
                           cc_form=cc_form,
                           bank_form=bank_form,
                           user=user,
                           web_course=course,
                           currency=currency)
예제 #27
0
def payment():
    #FIX WHEN CREDIT CARD IS ACTIVE
    return redirect(url_for('course.pay_with_bank'))
    user = User(current_user)
    party = user.party
    today = date.today()
    courses = []
    subscriptions = Subscription.search([('is_online', '=', True),
                                         ('party', '=', party.id),
                                         ('state', '=', 'running')])
    if len(subscriptions) < 1:
        return render_template(
            'bienvenido.html',
            user=user,
            flash_message=
            "Something wrong. Sorry the inconvenient. We will call you later.")
    else:
        for subscription in subscriptions:
            for line in subscription.lines:
                courses.append(line.service.id)
    with Transaction().set_context(courses=courses):
        user = User(current_user)
        if user.active_membership:
            return redirect(url_for('course.index'))

    ip_address = request.remote_addr
    if not ip_address or ip_address == '127.0.0.1':
        ip_address = '186.189.195.217'
    if ipaddress.ip_address(ip_address).is_private:
        ip_address = '186.189.195.217'
    access_token = 'cda5ddffc1e6b7'
    handler = ipinfo.getHandler(access_token)

    details = handler.getDetails(ip_address)
    country_code = details.country
    country_code = str(country_code)
    lcase_country_code = country_code.lower()
    currency_id = 16

    for currency in data:
        if str(currency['code']) == country_code:
            currency_id = currency['id']
            break
    currency = Currency(currency_id)

    with Transaction().set_context(currency_web=currency_id):
        invoices = Invoice.search([
            ('party', '=', party.id),
            ('state', '=', 'posted'),
        ])

    if len(subscriptions) >= 1 and len(invoices) >= 1:
        credentials = current_app.config['QPAYPRO_CREDENTIALS']
        cc_form = CreditCardForm()

        defaults = {}
        defaults['sessionid'] = uniqid()
        defaults['orgid'] = 'k8vif92e'  #'1snn5n9w' TEST OR PRODUCTION
        defaults['merchantid'] = credentials['merchantid']  #'visanetgt_qpay'
        defaults['user'] = user
        defaults['cc_form'] = cc_form
        defaults['invoices'] = invoices
        defaults['subscriptions'] = subscriptions
        defaults['currency'] = currency

        url_test = 'https://sandbox.qpaypro.com/payment/api_v1'
        url_production = 'https://payments.qpaypro.com/checkout/api_v1'

        if cc_form.validate_on_submit():
            credit_card = str(cc_form.card_number.data)
            credit_card.replace(' ', '')
            #invoice, = invoices
            success = True
            for invoice in invoices:
                params = {}
                params['x_login'] = credentials['x_login']  #'visanetgt_qpay'
                params['x_private_key'] = credentials[
                    'x_private_key']  # '88888888888'
                params['x_api_secret'] = credentials[
                    'x_api_secret']  #'99999999999'
                params['x_product_id'] = invoice.lines[0].product.id  #6
                params['x_audit_number'] = random.randint(1, 999999)
                params[
                    'x_fp_sequence'] = invoice.number  #1988679099 #INVOICE SEQUENCE NUMBER
                params[
                    'x_invoice_num'] = invoice.id  #random.randint(1,999999) #INVOICE SEQUENCE NUMBER
                params['x_fp_timestamp'] = time()
                params['x_currency_code'] = 'GTQ'
                params[
                    'x_amount'] = invoice.total_amount  #1.00 #invoice.total_amount
                params['x_line_item'] = invoice.lines[
                    0].product.name  #'T-shirt Live Dreams<|>w01<|><|>1<|>1000.00<|>N'
                params['x_freight'] = 0.00
                params['x_email'] = '*****@*****.**'
                params['cc_name'] = cc_form.name.data  #'john doe'
                params['cc_number'] = credit_card  #'4111111111111111'
                params['cc_exp'] = str(cc_form.expiration_date.data)  #'01/21'
                params['cc_cvv2'] = cc_form.code.data  #'4567'
                params['cc_type'] = 'visa'
                params['x_first_name'] = user.party.name  #'john'
                params['x_last_name'] = user.party.name  #'doe'
                params['x_company'] = 'API CENTRO'  #'Company'
                params['x_address'] = user.party.city  #'711-2880 Nulla'
                params['x_city'] = user.party.city  #'Guatemala'
                params['x_state'] = user.party.city  #'Guatemala'
                params['x_country'] = user.party.country  #'Guatemala'
                params['x_zip'] = '09001'
                params['x_relay_response'] = 'none'
                params['x_relay_url'] = 'none'
                params['x_type'] = 'AUTH_ONLY'
                params['x_method'] = 'CC'
                params[
                    'http_origin'] = 'https://www.apixela.net'  #'http://local.test.com'
                params['visaencuotas'] = 0
                params['device_fingerprint_id'] = defaults['sessionid']

                response = requests.post(url=url_production, params=params)

                res = response.raise_for_status()
                response_content = response.json()

                #response_content = {'responseCode':"100",
                #    'idTransaction':"102030"}

                response_code = response_content['responseCode']
                message = get_code(response_code)

                if response_code == "00":
                    transaction_id = response_content['idTransaction']
                    Invoice.card_payment_succeed([invoice],
                                                 reference=transaction_id)
                else:
                    success = False
                    break
            if success:
                return render_template('bienvenido.html',
                                       flash_message=message,
                                       user=user)
            else:
                return render_template(
                    'bienvenido.html',
                    user=user,
                    flash_message=
                    "Something wrong. Sorry the inconvenient. We will call you later."
                )
        return render_template('course/pay_enroll.html', **defaults)
    elif len(subscriptions) >= 1 and user.party.receivable != 0:
        return render_template(
            'bienvenido.html',
            user=user,
            flash_message=
            "Something wrong. Sorry the inconvenient. We will call you later.")
    else:
        return redirect(url_for('course.index'))