Exemple #1
0
def add_record():
    record_schema = Record.from_json(json.loads(request.data.decode('utf-8')))

    if record_schema.errors:
        return {'errors': record_schema.errors}, 400

    record_data = record_schema.data
    if record_data['record_type'] == Record.RECORD_TYPE_EXPENSE and record_data['amount'] > 0:
        record_data['amount'] = 0 - record_data['amount']

    if record_data['record_type'] == Record.RECORD_TYPE_INCOME and record_data['amount'] < 0:
        record_data['amount'] = 0 - record_data['amount']

    account = Account.query.filter(Account.id == record_data['account_id']).first()

    if not account:
        return {'errors': {'account': 'Account with this id does not exist'}}, 400

    category = GroupCategory.query.filter(
        GroupCategory.id == record_data['category_id']
    ).first()

    if not category:
        return {'errors': {'category': 'GroupCategory with this id does not exist'}}, 400

    currency = GroupCurrency.query.filter(
        GroupCurrency.id == record_data['currency_id']
    ).first()

    if not currency:
        return {'errors': {'currency': 'Group currency with this id does not exist'}}, 400

    record = Record(**record_data)
    record.user = current_user

    db.session.add(record)
    db.session.commit()

    return record, 201