def insert(self, **kwargs): new_lending = Loan(client_id=kwargs.get('client_id'), book_id=kwargs.get('book_id'), created_at=kwargs.get('created_at'), devolution_date=kwargs.get('devolution_date'), value=kwargs.get('value')) db.session.add(new_lending) db.session.commit() return new_lending
def app(): global_app.create_app( global_app.app, f'sqlite:///{DB_TEST}') with global_app.app.app_context(): assert db.engine.name == 'sqlite', 'Database for tests must be SQLITE!' db.session.add(Book(title='Livro 1', avaiable=True)) db.session.add(Book(title='Livro 2', avaiable=True)) db.session.add(Book(title='Livro 3', avaiable=True)) db.session.add(Client(name='Cliente 1')) db.session.add(Client(name='Cliente 2')) db.session.add(Client(name='Cliente 3')) db.session.add(Loan(client_id=1, book_id=3, created_at=datetime(2021, 3, 20), devolution_date=datetime(2021, 3, 23), value=10.0)) db.session.add(Loan(client_id=3, book_id=2, created_at=datetime(2021, 3, 27), devolution_date=datetime(2021, 3, 30), value=18.0)) db.session.commit() return global_app.app
def create_loan(loan_name, loan_description, loan_website, loan_gov, loan_region, loan_city, loan_credit_union, category_loans_id, loan_photo): loan = Loan(loan_name=loan_name, loan_description=loan_description, loan_website=loan_website, loan_gov=loan_gov, loan_region=loan_region, loan_city=loan_city, loan_credit_union=loan_credit_union, category_loans_id=category_loans_id, loan_photo=loan_photo) db.session.add(loan) db.session.commit() return loan
def import_file_content(balance_date, file): file_name = str(int(time.time())) + "_" + file.filename file_loc = "data/balance_reports/" + file_name file.save(file_loc) rows_df = pd.read_csv(file_loc, na_filter=False) rows_df["Applicant"] = rows_df["Applicant"].astype(str) rows_dict = rows_df.to_dict(orient="index") balance_date = datetime.strptime(balance_date, '%Y-%m-%d') nr_entries = len(rows_dict) B = BalanceFile(FileName=file_name, BalanceDate=balance_date, NrEntries=nr_entries) db.session.add(B) for i in rows_dict: loan = Loan(FileName=file_name, BalanceDate=balance_date, LoanNumber=rows_dict[i]["LoanNumber"], Applicant=str(rows_dict[i]["Applicant"]), CoApplicant=str(rows_dict[i]["CoApplicant"]), CollateralType=rows_dict[i]["CollateralType"], NominalOutstandingAmount=float( rows_dict[i]["NominalOutstandingAmount"]), CurrentValuation=float(rows_dict[i]["CurrentValuation"]), RiskClass=rows_dict[i]["RiskClass"]) db.session.add(loan) return_data = { "upload_result": None, "upload_result_msg": None, "uploaded_file_name": file_name, "nr_entries": nr_entries, "balance_date": balance_date } try: db.session.commit() except SQLAlchemyError as e: return_data["upload_result"] = "Error" return_data["upload_result_msg"] = str(e.__dict__["orig"]) return_data["upload_result"] = "Success" return_data[ "upload_result_msg"] = f'Succé! En fil med {nr_entries} rader laddades upp!' return return_data
def post(self): try: requestDict = request.get_json() if not requestDict: response = {'error': 'No input data provided'} return response, status.HTTP_400_BAD_REQUEST idClient = int(requestDict['idClient']) totalShares = int(requestDict['totalShares']) amount = float(requestDict['amount']) interestRate = float(requestDict['interestRate']) idCampaign = int(requestDict['idCampaign']) idLead = int(requestDict['idLead']) idShareType = int(requestDict['idShareType']) share = float(requestDict['share']) idAccount = int(requestDict['idAccount']) commission = float(requestDict['commission']) #Update boolean in client client = Client.query.get_or_404(idClient) if client.activeLoans == 1: response = {'error': 'El cliente tiene un préstamo activo'} return response, status.HTTP_400_BAD_REQUEST client.activeLoans = 0 # Esto deberia ser 0 (Soli) client.update() today = datetime.now() - timedelta(hours=5) #Calculo de tea y tem tea = interestRate tem = (((1 + (tea / 100))**(1 / 12)) - 1) month = today.month countExtraMonths = 0 numberExtra = 0 auxDate = today for i in range(totalShares): auxDate = auxDate + timedelta(days=30) monthAuxDate = auxDate.month if (monthAuxDate == 7 or monthAuxDate == 12): countExtraMonths += 1 if (idShareType == 2): numberExtra = countExtraMonths pot = totalShares + numberExtra auxTem = tem + 1 shareBase = round( (amount * ((1 + tem)**(totalShares + numberExtra)) * tem) / (((1 + tem)**(totalShares + numberExtra)) - 1), 2) initialDebt = amount day = today totalAmortization = 0 totalInterest = 0 totalComission = commission * totalShares totalShare = 0 today = datetime.now() - timedelta(hours=5) #Obteniendo campaign campaign = Campaign.query.get_or_404(idCampaign) #Minus en bank account bankAccount = BankAccount.query.get_or_404(campaign.idCurrency) bankAccount.balance = bankAccount.balance - amount bankAccount.update() #Plus in AccountClient account = Account.query.get_or_404(idAccount) account.balance = account.balance + amount account.update() #Insert in salesRecord salesRecord = SalesRecord(origin='Web', requestDate=datetime.now() - timedelta(hours=5), idRecordStatus=1, active=1, idClient=idClient, idProduct=2) salesRecord.add(salesRecord) db.session.flush() #Insert in loan loan = Loan(totalShares=totalShares, amount=amount, interestRate=interestRate, idLead=idLead, idClient=idClient, idSalesRecord=salesRecord.id, idShareType=idShareType, active=1, idAccount=idAccount, share=share, commission=commission) loan.add(loan) db.session.flush() #Insert in shares for i in range(totalShares): auxShareBase = shareBase interest = round(initialDebt * tem, 2) day = day + timedelta(days=30) if (idShareType == 2): if (day.month == 7 or day.month == 12): auxShareBase = round(shareBase * 2, 2) amortization = auxShareBase - interest if (i == totalShares - 1): amortization = initialDebt feeAmount = amortization + commission + interest totalAmortization += amortization totalInterest += interest totalShare += feeAmount share = Share(initialBalance=initialDebt, amortization=amortization, interest=interest, commission=commission, feeAmount=feeAmount, dueDate=day, idLoan=loan.id, shareNumber=i + 1) share.add(share) initialDebt = initialDebt - amortization #Insert in transaction transaction = Transaction(datetime=today, amount=amount, idAccount=idAccount, idBankAccount=campaign.idCurrency, active=1) transaction.add(transaction) lead = Lead.query.get_or_404(idLead) lead.active = 0 lead.update() #Commit changes db.session.commit() regLoan = Loan.query.get(loan.id) d = {} d['idLoan'] = str(regLoan.id) d['totalShares'] = str(regLoan.totalShares) d['amount'] = str(regLoan.amount) d['interestRate'] = str(regLoan.interestRate) d['idClient'] = str(regLoan.idClient) d['idSalesRecord'] = str(regLoan.idSalesRecord) d['idShareType'] = str(regLoan.idShareType) d['active'] = str(regLoan.active) prospectiveClient = ProspectiveClient.query.get_or_404( client.idProspectiveClient) person = Person.query.get_or_404(prospectiveClient.idPerson) currency = Currency.query.get_or_404(campaign.idCurrency) sharesA = Share.query.filter_by(idLoan=loan.id) shares = [] for sha in sharesA: e = sha.toJson() shares.append(e) from mailing import mail msg = Message("Tunke - Prestamo exitoso", sender="*****@*****.**", recipients=[prospectiveClient.email1]) msg.body = 'Enhorabuena, tu prestamo se realizo satisfactoriamente' fullName = person.firstName + ' ' + person.fatherLastname accNumber = str(account.accountNumber) curName = str(currency.currencyName) amount = str(d['amount']) currencySymbol = str(currency.currencySymbol) msg.html = render_template('loans.html', name=fullName, accountNumber=accNumber, currency=curName, amount=amount) logging.debug('Rendered') rendered = render_template( 'calendar.html', shares=shares, currencySymbol=currencySymbol, totalAmortization=str(round(totalAmortization, 2)), totalInterest=str(round(totalInterest, 2)), totalComission=str(round(totalComission, 2)), totalShare=str(round(totalShare, 2))) logging.debug('Pdfkit') pdf = pdfkit.from_string(rendered, False) logging.debug('PDF') msg.attach("Calendario.pdf", "application/pdf", pdf) mail.send(msg) return d, status.HTTP_201_CREATED except SQLAlchemyError as e: db.session.rollback() response = {'error': str(e)} return response, status.HTTP_400_BAD_REQUEST except Exception as e: db.session.rollback() response = {'error': str(e)} logging.debug(str(e)) return response, status.HTTP_400_BAD_REQUEST
def __init__(self, loans): self.loans = [ Loan(*[field for field in loan]).__dict__ for loan in loans ]
def post(self): try: requestDict = request.get_json() if not requestDict: response = {'error': 'No input data provided'} return response, status.HTTP_400_BAD_REQUEST idClient = int(requestDict['idClient']) totalShares = int(requestDict['totalShares']) amount = float(requestDict['amount']) interestRate = float(requestDict['interestRate']) idShareType = int(requestDict['idShareType']) idAccount = int(requestDict['idAccount']) share = float(requestDict['share']) commission = float(requestDict['commission']) idCampaign = int(requestDict['idCampaign']) client = Client.query.get_or_404(idClient) if client.activeLoans == 1: response = {'error': ' El cliente tiene un préstamo activo'} return response, status.HTTP_400_BAD_REQUEST client.activeLoans = 1 client.update() today = datetime.now() - timedelta(hours=5) tea = interestRate tem = (((1 + (tea / 100))**(1 / 12)) - 1) month = today.month countExtraMonths = 0 numberExtra = 0 auxDate = today for i in range(totalShares): auxDate = auxDate + timedelta(days=30) monthAuxDate = auxDate.month if (monthAuxDate == 7 or monthAuxDate == 12): countExtraMonths += 1 if (idShareType == 2): numberExtra = countExtraMonths shareBase = round( (amount * ((1 + tem)**(totalShares + numberExtra)) * tem) / (((1 + tem)**(totalShares + numberExtra)) - 1), 2) initialDebt = amount day = today totalAmortization = 0 totalInterest = 0 totalCommission = commission * totalShares totalShare = 0 salesRecord = SalesRecord(origin='Ventanilla', requestDate=today, idRecordStatus=3, active=1, idClient=idClient, idProduct=2) salesRecord.add(salesRecord) db.session.flush() lead = Lead(idClient=idClient, idCampaign=idCampaign, minimumLoan=0, maximumLoan=amount, active=0, minimumPeriod=6, maximumPeriod=totalShares, interestRate=interestRate) lead.add(lead) db.session.flush() #Prestamo con campaña para clientes sin campaña loan = Loan(totalShares=totalShares, amount=amount, interestRate=interestRate, idLead=lead.id, idClient=idClient, idSalesRecord=salesRecord.id, idShareType=idShareType, active=1, idAccount=idAccount, share=share, commission=commission) loan.add(loan) db.session.flush() #Insert in shares for i in range(totalShares): auxShareBase = shareBase interest = round(initialDebt * tem, 2) day = day + timedelta(days=30) if (idShareType == 2): if (day.month == 7 or day.month == 12): auxShareBase = round(shareBase * 2, 2) amortization = auxShareBase - interest if (i == totalShares - 1): amortization = initialDebt feeAmount = amortization + commission + interest totalAmortization += amortization totalInterest += interest totalShare += feeAmount share = Share(initialBalance=initialDebt, amortization=amortization, interest=interest, commission=commission, feeAmount=feeAmount, dueDate=day, idLoan=loan.id, shareNumber=i + 1) share.add(share) initialDebt = initialDebt - amortization db.session.commit() regLoan = Loan.query.get(loan.id) d = {} d['idLoan'] = regLoan.id d['totalShares'] = regLoan.totalShares d['amount'] = regLoan.amount d['interestRate'] = regLoan.interestRate d['idClient'] = regLoan.idClient d['idSalesRecord'] = regLoan.idSalesRecord d['idShareType'] = regLoan.idShareType d['active'] = regLoan.active return d, status.HTTP_201_CREATED except SQLAlchemyError as e: db.session.rollback() response = {'error': str(e)} return response, status.HTTP_400_BAD_REQUEST except Exception as e: db.session.rollback() response = {'error': str(e)} print(e) return response, status.HTTP_400_BAD_REQUEST