Пример #1
0
def create_debt():
    try:
        other_id = int(request.form['user'])
        other = User.query.get(other_id)

        amount = int(request.form['amount'])
        debtor = lender = None

        if amount == 0:
            raise Exception('Amount is 0.')
        elif amount < 0:
            # I owe other
            debtor = g.user
            lender = other
            amount *= -1
        elif amount > 0:
            # other owes me
            debtor = other
            lender = g.user

        description = request.form['description']
        description = description.strip()[:300]

        if len(description) == 0:
            raise Exception('Decription cannot be empty.')

        new_debt = Debt(debtor, lender, amount, description)

        db.session.add(new_debt)
        db.session.commit()

        return new_debt.json()
    except Exception as e:
        app.logger.error(e)
        abort(500)
Пример #2
0
def get_n_penalties(debt):
    date_debt = date(day=1, month=debt.month, year=debt.year)
    debts = [
        1 for dbt in Debt.filter(Debt.type == debt.type)
        if date(day=1, month=dbt.month, year=dbt.year) > date_debt
    ]
    return len(debts)
Пример #3
0
    def process(sielf, commit, *args, **kwargs):
        data = commit.data
        debt = Debt.objects(id=data["id"]).first()

        debt.error = data.get("error")
        # debt.commits.append(commit)
        commit.save()
        debt.save()
Пример #4
0
def get_debts_to_pay(student):
    debts = Debt.select()
    debts = [
        debt for debt in debts
        if student.entrou < datetime(debt.year, debt.month, 1) < student.saiu
    ]
    if not student.drink_coffee:
        debts = [debt for debt in debts if debt.type == 1]
    payments = Payment.filter(Payment.student_id == student.id)
    paid_debts = [pay.debt for pay in payments]
    return [debt for debt in debts if not debt in paid_debts]
Пример #5
0
 def create_debt_item(token):
     body = request.get_json()
     new_name = body.get('name', None)
     new_category = body.get('category', None)
     new_amount = body.get('amount', None)
     search = body.get('searchTerm')
     try:
         debt = Debt(name=new_name,
                     category=new_category,
                     amount=new_amount)
         debt.insert()
         selection = Debt.query.order_by(Debt.id).all()
         current_debt = paginate_debt_items(request, selection)
         return jsonify({
             "success": True,
             "create": debt.id,
             "debt": debt.format(),
             "total_debt": session.query(func.count(Debt.amount)),
             "debt_items": current_debt
         }), 201
     except:
         abort(422)
Пример #6
0
def initialize():
    db.drop_all()
    db.metadata.create_all(
        db.engine,
        tables=[
            Person.__table__,
            Address.__table__,
            Debt.__table__]
    )

    list_persons = []
    list_debts = []
    list_address = []
    for person_info in persons:
        person = Person(
            cpf=person_info.get('cpf'),
            nome=person_info.get('nome')
        )

        address = Address(
            rua=person_info['endereco']['rua'],
            numero=person_info['endereco']['numero'],
            cidade=person_info['endereco']['cidade'],
            estado=person_info['endereco']['estado'],
            person_id=person_info.get('cpf')
        )

        list_address.append(address)
        list_persons.append(person)

        for debt_info in person_info.get('lista_dividas'):
            debt = Debt(
                tipo=debt_info.get('tipo'),
                valor=debt_info.get('valor'),
                person_id=person_info.get('cpf')
            )
            list_debts.append(debt)
    db.session.add_all(list_persons)
    db.session.add_all(list_debts)
    db.session.add_all(list_address)
    db.session.commit()
Пример #7
0
 def process(self, commit, *args, **kwargs):
     data = commit.data
     debt = Debt()
     debt.id = data.get("id")
     debt.error = data.get("error")
     debt.balance = data.get("balance")
     debt.model = data.get("model")
     debt.creator = data.get("creator")
     debt.oracle = data.get("oracle")
     debt.created = data.get("created")
     # debt.commits.append(commit)
     commit.save()
     debt.save()
Пример #8
0
def create_debt(month, year, type, value, penalty):
    Debt.create(month=month,
                year=year,
                type=type,
                value=value,
                penalty=penalty)
Пример #9
0
def debts(*args, **kwargs):
    if request.method == 'GET':
        debts = Debt. \
            where('complete', False). \
            join(table=Currency.__table__,
                 one='{}.id'.format(Currency.__table__),
                 operator='=',
                 two='{}.currency'.format(Debt.__table__),
                 type='left outer'). \
            group_by(
                '{}.id'.format(Debt.__table__),
                '{}.name'.format(Currency.__table__),
            ). \
            order_by_raw('created_at DESC NULLS LAST'). \
            get([
                '{}.*'.format(Debt.__table__),
                '{}.name as currency_name'.format(Currency.__table__),
            ]). \
            serialize()
        debts_sum = 0.0
        for debt in debts:
            value = debt['value']
            if debt['currency_name'] != 'rub':
                value = replace_value_with_rate(
                    value=value,
                    current_currency=debt['currency_name'],
                    target_currency='rub')
            debts_sum += value
        return app_response(data={'items': debts, 'sum': debts_sum})
    elif request.method == 'POST':
        body = request.json
        name = body.get('name', '')
        value = body.get('value', 0.0)
        value = float(value)
        currency = body.get('currency', None)
        if currency is None:
            currency = Currency.where('name', 'rub').first().id
        end_date = body.get('end_date', None)
        if end_date is not None and end_date == '':
            end_date = None
        description = body.get('description', None)
        user = kwargs.get('user_info')
        debt = Debt.create(creator=user.id,
                           value=value,
                           currency=currency,
                           name=name,
                           end_date=end_date)
        purchase = ComingIns.create(name=name,
                                    value=value,
                                    currency=currency,
                                    creator=user.id,
                                    description=description,
                                    debt=debt.id)
        purchase = purchase.serialize()
        purchase['currency_name'] = Currency.where('id', currency).first().name
        purchase['debt_complete'] = False
        purchase['end_date'] = debt.end_date
        replace_balance(value=float(value), currency=currency)
        if purchase['currency_name'] != 'rub':
            value = replace_value_with_rate(
                value=float(value),
                current_currency=purchase['currency_name'],
                target_currency='rub')
        return app_response(data={'item': purchase, 'rub_value': value})
    elif request.method == 'PUT':
        body = request.json
        debt_id = body.get('id', None)
        name = body.get('name', None)
        value = body.get('value', 0.0)
        value = float(value)
        currency = body.get('currency', None)
        if currency is None:
            currency = Currency.where('name', 'rub').first().id
        complete = body.get('complete', False)
        end_date = body.get('end_date', None)
        if end_date is not None and end_date == '':
            end_date = None
        description = body.get('description', None)
        user = kwargs.get('user_info')
        debt = Debt.where('id', debt_id).first()
        if debt and not debt.complete:
            debt_currency = Currency.where('id', debt.currency).first()
            if currency != debt_currency.id:
                body_currency = Currency.where('id', currency).first()
                value = replace_value_with_rate(
                    value=float(value),
                    current_currency=body_currency.name,
                    target_currency=debt_currency.name)
            debt_pay_value = debt.value - value
            if value > 0.0:
                DebtPayment.create(user_id=user.id, value=debt_pay_value)
                debt.value = value
            if end_date is not None:
                if end_date == '':
                    debt.end_date = None
                else:
                    debt.end_date = end_date
            debt.name = name if name is not None else debt.name
            debt.complete = complete
            debt.save()
            if debt_pay_value > 0.0:
                purchase = Purchase.create(name=debt.name,
                                           value=abs(debt_pay_value),
                                           currency=debt.currency,
                                           complete=True,
                                           creator=user.id,
                                           description=description,
                                           debt=debt.id)
            elif debt_pay_value < 0.0:
                purchase = ComingIns.create(name=debt.name,
                                            value=abs(debt_pay_value),
                                            currency=debt.currency,
                                            creator=user.id,
                                            description=description,
                                            debt=debt.id)
            else:
                purchase = Debt.where('id', debt_id).first()
            purchase = purchase.serialize()
            purchase['currency_name'] = Currency.where('id',
                                                       currency).first().name
            purchase['debt_complete'] = complete
            purchase['debt_end_date'] = debt.end_date
            if debt_pay_value > 0.0:
                replace_balance(value=float(debt_pay_value) * (-1),
                                currency=currency)
            elif debt_pay_value < 0.0:
                replace_balance(value=abs(float(debt_pay_value)),
                                currency=currency)
            if purchase['currency_name'] != 'rub':
                debt_pay_value = replace_value_with_rate(
                    value=float(debt_pay_value),
                    current_currency=purchase['currency_name'],
                    target_currency='rub')
            return app_response(data={
                'item': purchase,
                'rub_value': debt_pay_value
            })
        return {}