Skip to content

Commit

Permalink
filters, routes
Browse files Browse the repository at this point in the history
  • Loading branch information
bleeeana committed Dec 11, 2024
1 parent c9a332f commit d77a549
Show file tree
Hide file tree
Showing 2 changed files with 151 additions and 18 deletions.
57 changes: 43 additions & 14 deletions backend/app/routes/filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,6 @@ def sort_credit_request():
client_id = request.args.get('client_id')
sort_field = request.args.get('sort_field')
sort_direction = int(request.args.get('sort_direction', 0))
# sort_params = {
# 'request_time': int(request.args.get('request_time', 0)),
# 'status': int(request.args.get('status', 0)),
# 'loan_name': int(request.args.get('loan_name', 0)),
# 'amount': int(request.args.get('amount', 0)),
# 'interest_rate': int(request.args.get('interest_rate', 0)),
# 'expiration_time': int(request.args.get('expiration_time', 0))
# }

credit_requests = CreditRequest.objects(client_id=client_id)

Expand Down Expand Up @@ -47,6 +39,40 @@ def sort_credit_request():
return jsonify(result), 200


@bp.route('/sort_admins_request', methods=['GET'])
def sort_credit_requests():
print('Пришел запрос на сортировку CreditRequest у администратора со следующими аргументами:', request.args)

# получение параметров
sort_field = request.args.get('sort_field')
sort_direction = int(request.args.get('sort_direction', 0))

credit_requests = CreditRequest.objects(status="processing")

# Получение информации о кредитах
result = []
for req in credit_requests:
credit = Credit.objects(_id=req.loan_id).first()
client = Client.objects(_id=req.client_id).first()
if credit:
result.append({
"client_id": str(req.client_id),
"request_id": str(req._id),
"fio": client.name,
"loan_name": credit.loan_name,
"request_time": req.request_time.isoformat(),
"status": req.status,
"amount": credit.amount,
"interest_rate": credit.interest_rate,
"rating": client.rating,
"expiration_time": credit.expiration_time
})

if sort_direction != 0:
result = sorted(result, key=lambda x: x[sort_field], reverse=(sort_direction == -1))
return jsonify(result), 200


@bp.route('/sort_credit', methods=['GET'])
def sort_credit():
print('Пришел запрос на сортировку Credit со следующими аргументами:', request.args)
Expand Down Expand Up @@ -199,12 +225,12 @@ def filter_credit_request():

return jsonify(response_data), 200

@bp.route("/filter_admins_request", methods=['POST'])
@bp.route("/filter_admins_request", methods=['GET'])
def filter_admins_request():
print('Пришел запрос на фильтрацию с параметрами:', request.args)
data = request.args

query_filter = {}
query_filter = {'status': 'processing'}
client_filter = {}
credit_query_filter = {}
print(data.get('loan_name').split('@'))
Expand All @@ -226,14 +252,14 @@ def filter_admins_request():

filtered_credits = Credit.objects(**credit_query_filter)

if data.get('client_name'):
client_filter['name__icontains'] = str(data['client_name'])
if data.get('fio'):
client_filter['name__icontains'] = str(data['fio'])
if data.get('rating_from'):
client_filter['rating__gte'] = float(data['rating_from'])
if data.get('rating_to'):
client_filter['rating_lte'] = float(data['rating_to'])

filtered_clients = Client._objects(**client_filter)
filtered_clients = Client.objects(**client_filter)

if not filtered_credits:
return jsonify({}), 200
Expand All @@ -258,9 +284,11 @@ def filter_admins_request():
response_data.append({
'_id': str(req._id),
'client_id': str(req.client_id),
'fio': user_info.name,
'loan_id': str(req.loan_id),
'request_time': req.request_time.isoformat(),
'rating': str(user_info.rating),
'request_id': str(req._id),
'rating': user_info.rating,
'client_id': str(user_info._id),
'loan_name': credit_info.loan_name,
'amount': credit_info.amount,
Expand All @@ -270,6 +298,7 @@ def filter_admins_request():

return jsonify(response_data), 200


@bp.route("/active_credits", methods=['POST'])
def filter_active_credits():
pass
Expand Down
112 changes: 108 additions & 4 deletions backend/app/routes/request_routes.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from flask import Blueprint, request, jsonify
from models import CreditRequest, Credit
from models import CreditRequest, Credit, CreditHistory, Client, Coborrowers, Admin, InteractionHistory
from utils.validation import *
from mongoengine import ObjectIdField
from datetime import datetime
from bson import ObjectId
Expand All @@ -17,12 +18,61 @@ def create_credit_request():
loan_amount = data.get('loanAmount')
expiration_time = data.get('expirationTime')
co_borrowers = data.get('coBorrowers')
collateral = data.get('collateral')
deposit = data.get('deposit')

errors = []
if not deposit:
errors.append("Должен быть указан залог.")
else:
deposit = int(deposit)
if deposit and deposit < 0:
errors.append("Залог не может быть отрицательной величиной.")
if co_borrowers:
for co_borrower in co_borrowers:
current_post = co_borrower.get('post', None)
current_workplace = co_borrower.get('workplace', None)
current_name = co_borrower.get('fio', None)
current_phone = co_borrower.get('contactPhone', None)
current_passport_number = co_borrower.get('passportNumber', None)
current_passport_series = co_borrower.get('passportSeries', None)
if not current_name:
errors.append("Имя созаемщика не указано.")
break
if not current_workplace:
errors.append("Место работы созаемщика не указано.")
break
if not current_post:
errors.append("Должность созаемщика не указана.")
break
if not current_phone:
errors.append("Телефон созаемщика не указан.")
break
if not current_passport_number:
errors.append("Номер паспорта созаемщика не указан.")
break
if not current_passport_series:
errors.append("Серия паспорта созаемщика не указана.")
break
if not validate_phone_number(current_phone):
errors.append("Некорректный формат телефона.")
if not validate_passport_number(current_passport_number):
errors.append("Серия паспорта должен иметь длину 6 и содержать исключительно числа.")
break
if not validate_passport_series(current_passport_series):
errors.append("Серия паспорта должен иметь длину 4 и содержать исключительно числа.")
break


if errors:
print(errors)
return jsonify({"error": "Validation failed", "details": errors}), 400

if not client_id or not loan_type:
return jsonify({"error": "client_id and loan_type are required"}), 400

new_credit = Credit(_id=ObjectId("".join(random.choices(string.hexdigits.lower(), k=24))), loan_name=loan_type, amount=loan_amount, interest_rate=5.5, deposit=collateral, co_borrowers=co_borrowers.split(', '), expiration_time=expiration_time).save()
new_credit = Credit(_id=ObjectId("".join(random.choices(string.hexdigits.lower(), k=24))), loan_name=loan_type, amount=loan_amount, interest_rate=5.5, deposit=deposit,
co_borrowers=[Coborrowers(name=coborrower['fio'], workplace=coborrower['workplace'], phone=coborrower['contactPhone'], post=coborrower['post'], passport_number=coborrower['passportNumber'], passport_series=coborrower['passportSeries']) for coborrower in co_borrowers],
expiration_time=expiration_time).save()

credit_request = CreditRequest(
_id=ObjectId("".join(random.choices(string.hexdigits.lower(), k=24))),
Expand All @@ -34,7 +84,7 @@ def create_credit_request():
credit_request.save()
return jsonify({"message": "Credit request created successfully", "request_id": str(credit_request.id)}), 201

# (`http://127.0.0.1:5000/credit_request?client_id=${userId}`);

@bp.route('/credit_request/', methods=['GET'])
def get_all_credit_requests():
print("Пришел запрос на получение списка заявок на кредит:", request.args)
Expand All @@ -50,3 +100,57 @@ def get_all_credit_requests():
]

return jsonify(result), 200

@bp.route('/credit_request_decision', methods=['GET'])
def credit_request_decision():
data = request.args
print(f"Пришел запрос на решение заявки: ", data)
status = data.get('decision')
if status == 'true':
status = "approved"
else:
status = "rejected"
request_id = data.get('request_id')
admin_id = data.get('admin_id')
credit_request = CreditRequest.objects(_id=request_id).first()
new_interaction = InteractionHistory(
_id=ObjectId("".join(random.choices(string.hexdigits.lower(), k=24))),
processing_date = datetime.utcnow(),
credit_request_id = request_id,
decision=status
)

credit_request.status = status
credit_request.save()
Admin.objects(_id=admin_id).update_one(push__interaction_history=new_interaction)#.save()
if status == True:
credit_history = CreditHistory(
_id=ObjectId("".join(random.choices(string.hexdigits.lower(), k=24))),
client_id=credit_request.client_id,
loan_id=credit_request.loan_id,
closing_time = None,
status="opened"
)
credit_history.save()
Client.objects(_id=credit_request.client_id).update_one(push__credit_history=credit_history)#.save()
return jsonify({"message": "Credit request decision saved successfully"}), 200
else:
return jsonify({"message": "Credit request decision saved successfully"}), 200

@bp.route('/admins_request', methods=['GET'])
def admins_request():
print("Пришел запрос на получение списка заявок на кредит:", request.args)
credit_requests = CreditRequest.objects(status="processing")
result = [{"client_id": str(req.client_id),
"request_id": str(req._id),
"fio": Client.objects(_id=req.client_id).first().name,
"rating": Client.objects(_id=req.client_id).first().rating,
"loan_name": Credit.objects(_id=req.loan_id).first().loan_name,
"request_time": req.request_time.isoformat(),
"status": req.status,
"amount": Credit.objects(_id=req.loan_id).first().amount,
"interest_rate": Credit.objects(_id=req.loan_id).first().interest_rate,
"expiration_time": Credit.objects(_id=req.loan_id).first().expiration_time} for req in credit_requests
]
print(result)
return jsonify(result), 200

0 comments on commit d77a549

Please sign in to comment.