FIRST FULL COMMIT

This commit is contained in:
Velz2020 2023-10-06 16:44:28 +05:30
parent 23f5c92263
commit 3ff97cb775
45 changed files with 78007 additions and 1 deletions

4
.gitignore vendored
View File

@ -22,4 +22,6 @@ docs/_build/
htmlcov/
.coverage
.coverage.*
*,cover
*,cover
logs/*
!logs/sample.log

View File

@ -0,0 +1,92 @@
from flask import render_template
from services.dbservice import DbService
from flask import Response, request
from flask_restful import Resource,reqparse
from services.utilityservices import sendRestResponse
from services.CibilBusinessOperationService import CibilBusinessOperationService
from flask_restful_swagger import swagger
import json
#this one for sample of individual modules/components in flask
class CIBIL(Resource):
@swagger.operation(
notes='This API is entry point of Credit Bureau Summary of single applicant',
responseClass='None',
nickname='CIBIL Single Applicant Credit Bureau Summary API',
parameters=[
{
"name": "reference_number",
"description": "member reference number or applicant individual id",
"required": True,
"allowMultiple": False,
"dataType": 'int',
"paramType": "query"
},
{
"name": "los_id",
"description": "LOSID",
"required": True,
"allowMultiple": False,
"dataType": 'int',
"paramType": "query"
}
],
responseMessages=[
{
"code": 200,
"message": "Process Started...!"
},
{
"code": 404,
"message": "Some Err"
}
]
)
def get(self):
return_data = []
los_id = request.args.get('los_id') if request.args.get('los_id') is not None else None
reference_number = request.args.get('reference_number') if request.args.get('reference_number') is not None else None
cibil_type = request.args.get('cibil_type') if request.args.get('cibil_type') is not None and request.args.get('cibil_type') in ['1','2'] else None # consumer = 1,commercial = 2
output_type = request.args.get('output_type') if request.args.get('los_id') is not None else None
# print(output_type,'--',type(output_type))
# print(request.args.get('cibil_type') == 2)
# print(cibil_type,request.args.get('cibil_type'))
action = request.args.get('action') if request.args.get('action') is not None and request.args.get('action') in ['1','2','3'] else None
# print(request.args.get('action') in [1,2,3])
# print(action,request.args.get('action'))
if los_id == None or reference_number == None or cibil_type == None or action == None:
return sendRestResponse(404,{'msg':'insufficient/invalid params'})
if int(action) == 1:#active&closedloans
print('active&closed Loans-')
return_data = CibilBusinessOperationService.doCIBILActiveCloseLoansSummary(los_id,reference_number,cibil_type)
return sendRestResponse(200,{'msg':'success','data':return_data})
elif int(action) == 2:#sanctioned loans summary
if output_type in ['1','2']:output_type = int(output_type)
else:return sendRestResponse(404,{'msg':'insufficient/invalid params'})
print('sanctioned loans summary')
return_data = CibilBusinessOperationService.doCIBILSanctionedLoansSummary(los_id,reference_number,cibil_type,output_type)
return sendRestResponse(200,{'msg':'success','data':return_data})
elif int(action) == 3:#enquiry summary
print('enquiry summary')
if output_type in ['1','2']:output_type = int(output_type)
else:return sendRestResponse(404,{'msg':'insufficient/invalid params'})
return_data = CibilBusinessOperationService.doCIBILEnquirySummary(los_id,reference_number,cibil_type,output_type)
return sendRestResponse(200,{'msg':'success','data':return_data})
else:
return sendRestResponse(200,{'msg':'success','data':return_data})
# raise Exception('manual stop')
# print('cool')
# CibilBusinessOperationServiceObj = CibilBusinessOperationService()
# data = CibilBusinessOperationService.doConsumerCIBILOperations(member_reference_number)
# return render_template('about.html', name='ponniy')
return sendRestResponse(200,return_data)
# return sendRestResponse(200,{'msg':return_data})

View File

@ -0,0 +1,40 @@
from services.dbservice import DbService
from flask import Response, request
from flask_restful import Resource,reqparse
from services.utilityservices import sendRestResponse
from flask_restful_swagger import swagger
#this one for sample of individual modules/components in flask
class WorkingController(Resource):
@swagger.operation(
notes='Test Implemetaion of swaagger UI API',
responseClass='None',
nickname='Test API1',
parameters=[
{
"name": "name",
"description": "blueprint object that needs to be added. YAML.",
"required": False,
"allowMultiple": False,
"dataType": 'string',
"paramType": "query"
}
],
responseMessages=[
{
"code": 201,
"message": "Created. The URL of the created blueprint should be in the Location header"
},
{
"code": 405,
"message": "Invalid input"
}
]
)
def get(self, id=100):
page = request.args
print(page)
# return Response({'msg':'Welcome'},status=200)
return sendRestResponse(200,{'msg':id})

11
Controllers/testclass.py Normal file
View File

@ -0,0 +1,11 @@
class Test:
# def __init__(self):
# print('inir called')
def testFunction(self):
return 10 * 5
def testFunction2(self):
print(self)
self.testFunction()
return 10 * 50

View File

@ -0,0 +1,49 @@
from services.dbservice import DbService
from sqlalchemy.sql import text
# from flask_sqlalchemy import SQLAlchemy
# from app import db
def testFunction():
return 10 * 10
def testDBcon():
# conn = DbService.getDBConnection(DbService)
myDBservice = DbService();
conn = myDBservice.getDBConnection();
# print(conn)
cursor = conn.cursor()
# cursor.execute('SELECT * FROM charge_type')
cursor.execute('SELECT id,BDeatailsID ,MemberReferenceNumber ,EnquiryMemberUserID ,SubjectReturnCode ,EnquiryControlNumber ,DateTimeProcessed ,ConsumerNameField1 ,ConsumerNameField2 ,ConsumerNameField3 ,ConsumerNameField4 ,ConsumerNameField5 ,DateofBirth ,Gender ,DateofEntryforErrorCode ,ErrorSegmentTag ,ErrorCode ,DateofEntryforCIBILRemarksCode ,CIBILRemarks ,DateofEntryforErrorDisputeRemarksCode ,ErrorDisputeRemarksCode ,ErrorDisputeRemarksCode2 ,AccountType ,DateReportedAndCertified ,Occupation ,Income ,NetGrossIncomeIndicator ,MonthlyAnnualIncomeIndicator ,DateOfEntryforErrorCode1 ,ErrorCode1 ,DateOfEntryForCIBILRemarksCode1 ,CIBILRemarksCode ,DateOfEntryForErrorDisputeRemarksCode1 ,ErrorDisputeRemarksCode1 ,ATErrorDisputeRemarksCode1 ,ATErrorDisputeRemarksCode2 ,DateOfEntry ,DisputeRemarksLine ,EMailID ,AccountNumber FROM con_borrower_detail where MemberReferenceNumber = ?',['202201121036280000000'])
# where MemberReferenceNumber = 202201121036280000000"
# ,createdAt ,updatedAt ,createdby ,updatedby
data = [];
records = cursor.fetchall()
field_names = [i[0] for i in cursor.description]
print(field_names)
# print(records)
for i in records:
print('###### START #######')
print((i))
print('**************************************')
print(dict(zip(field_names,i)))
print('###### END #######')
data.append(dict(zip(field_names,i)))
# data.append(dict(i))
conn.close();
return data
def testDBRaw():
# db = SQLAlchemy()
records = db.engine.execute("SELECT id,charge_type,charge_type_description,created_at,modified_at FROM charge_type")
data = [];
field_names = records.keys()
records = records.fetchall()
print(field_names)
for i in records:
print(i)
data.append(dict(i))
# print(result)
return data

View File

@ -0,0 +1,13 @@
# import db object from flask app
from app import db
# database tables
class Com_ac_history_and_dpd(db.Model):
id = db.Column(db.Integer, primary_key =True)
temp_id = db.Column(db.Integer, nullable = False)
ApplicationRefno = db.Column(db.Numeric, nullable = False)
BorrowerCurrentDetailsID = db.Column(db.Integer, nullable = False)
CFHistory24Monthsmonth = db.Column(db.DateTime, nullable = False)
CFHistory24MonthsACorDPD = db.Column(db.String, nullable = False)
CFHistory24MonthsOSAmount = db.Column(db.Numeric, nullable = False)

View File

@ -0,0 +1,11 @@
# import db object from flask app
from app import db
# database tables
class Com_borrower_profile(db.Model):
id = db.Column(db.Integer, primary_key =True)
temp_id = db.Column(db.Integer, nullable = False)
ApplicationRefno = db.Column(db.Numeric, nullable = False)
EnqInfoBorrowerName = db.Column(db.String, nullable = False)

View File

@ -0,0 +1,55 @@
# import db object from flask app
from app import db
# database tables
class Com_credit_facility_current_detail(db.Model):
id = db.Column(db.Integer, primary_key =True)
temp_id = db.Column(db.Integer, nullable = False)
ApplicationRefno = db.Column(db.Numeric, nullable = False)
CreditFacilityDetailsBorrowerSecMsg = db.Column(db.String, nullable = False)
CreditFacilityCDDerivative = db.Column(db.String, nullable = False)
CreditFacilityCDAccountNo = db.Column(db.String, nullable = False)
CreditFacilityCDcfSrNo = db.Column(db.String, nullable = False)
CreditFacilityCDcfType = db.Column(db.String, nullable = False)
CreditFacilityCDcfMember = db.Column(db.String, nullable = False)
CreditFacilityCDAssetCDPDueDpd = db.Column(db.String, nullable = False)
CreditFacilityCDStatus = db.Column(db.String, nullable = False)
CreditFacilityCDStatusDate = db.Column(db.DateTime, nullable = False)
CreditFacilityCDLstReportedDate = db.Column(db.DateTime, nullable = False)
CreditFacilityCDAmtCurrency = db.Column(db.String, nullable = False)
CreditFacilityCDAmtSanctionedAmt = db.Column(db.Numeric, nullable = False)
CreditFacilityCDAmtSanctionedAmtDP = db.Column(db.Numeric, nullable = False)
CreditFacilityCDAmtoutstandingBalance = db.Column(db.Numeric, nullable = False)
CreditFacilityCDAmtmarkToMarket = db.Column(db.String, nullable = False)
CreditFacilityCDAmtOverdue = db.Column(db.Numeric, nullable = False)
CreditFacilityCDAmtHighCredit = db.Column(db.Numeric, nullable = False)
CreditFacilityCDAmtinstallmentAmt = db.Column(db.Numeric, nullable = False)
CreditFacilityCDAmtSuitFiledAmt = db.Column(db.Numeric, nullable = False)
CreditFacilityCDAmtLastRepaid = db.Column(db.Numeric, nullable = False)
CreditFacilityCDAmtWrittenOFF = db.Column(db.Numeric, nullable = False)
CreditFacilityCDAmtSettled = db.Column(db.Numeric, nullable = False)
CreditFacilityCDAmtNaorc = db.Column(db.Numeric, nullable = False)
CreditFacilityCDAmtContrctCAsNPA = db.Column(db.String, nullable = False)
CreditFacilityCDAmtNAmtOfContracts = db.Column(db.String, nullable = False)
CreditFacilityCDDatesSanctionedDt = db.Column(db.DateTime, nullable = False)
CreditFacilityCDDatesLoanExpiryDt = db.Column(db.DateTime, nullable = False)
CreditFacilityCDDatesLoanRenewalDt = db.Column(db.DateTime, nullable = False)
CreditFacilityCDDatesSuitFiledDt = db.Column(db.DateTime, nullable = False)
CreditFacilityCDDatesWilfulDefault = db.Column(db.DateTime, nullable = False)
CreditFacilityCDODRepaymentFrequency = db.Column(db.String, nullable = False)
CreditFacilityCDODTenure = db.Column(db.Integer, nullable = False)
CreditFacilityCDODWAMPContracts = db.Column(db.String, nullable = False)
CreditFacilityCDODRestructingReason = db.Column(db.String, nullable = False)
CreditFacilityCDODABSecurityCoverage = db.Column(db.String, nullable = False)
CreditFacilityOverdueDetailsMsg = db.Column(db.String, nullable = False)
CreditFacilityOverdueDetailsDPD1to30Amt = db.Column(db.Numeric, nullable = False)
CreditFacilityOverdueDetailsDPD31to60amt = db.Column(db.Numeric, nullable = False)
CreditFacilityOverdueDetailsDPD61t090amt = db.Column(db.Numeric, nullable = False)
CreditFacilityOverdueDetailsDPD91to180amt = db.Column(db.Numeric, nullable = False)
CreditFacilityOverdueDetailsDPDabove180amt = db.Column(db.Numeric, nullable = False)
ChequeDDIFundsMsg = db.Column(db.String, nullable = False)
ChequeDDIFundsCD3monthcount = db.Column(db.Integer, nullable = False)
ChequeDDIFundsCD4to6monthcount = db.Column(db.Integer, nullable = False)
ChequeDDIFundsCD10to12monthcount = db.Column(db.Integer, nullable = False)
CFSecurityDetailsMsg = db.Column(db.String, nullable = False)
CreditFacilityGuarantorDVecMsg = db.Column(db.String, nullable = False)

View File

@ -0,0 +1,13 @@
# import db object from flask app
from app import db
# database tables
class Com_enquiry_detail(db.Model):
id = db.Column(db.Integer, primary_key =True)
temp_id = db.Column(db.Integer, nullable = False)
ApplicationRefno = db.Column(db.Numeric, nullable = False)
EnquiryDetailsEnquiryDt = db.Column(db.DateTime, nullable = False)
EnquiryDetailsEnquiryPurpose = db.Column(db.String, nullable = False)
EnquiryDetailsEnquiryAmt = db.Column(db.Numeric, nullable = False)

View File

@ -0,0 +1,49 @@
# import db object from flask app
from app import db
# database tables
class Con_account_transaction_detail(db.Model):
id = db.Column(db.Integer, primary_key =True)
AccountTranDetailsID = db.Column(db.Integer, nullable = False)
MemberReferenceNumber = db.Column(db.Numeric, nullable = False)
ReportingMemberShortName = db.Column(db.String, nullable = False)
AccountNumber = db.Column(db.String, nullable = False)
AccountType = db.Column(db.String, nullable = False)
OwnershipIndicator = db.Column(db.DateTime, nullable = False)
DateOpenedDisbursed = db.Column(db.DateTime, nullable = False)
DateOfLastPayment = db.Column(db.DateTime, nullable = False)
DateClosed = db.Column(db.DateTime, nullable = False)
DateReportedAndCertified = db.Column(db.DateTime, nullable = False)
HighCreditSanctionedAmount = db.Column(db.Numeric, nullable = False)
CurrentBalance = db.Column(db.Numeric, nullable = False)
AmountOverdue = db.Column(db.Numeric, nullable = False)
PaymentHistory1 = db.Column(db.String, nullable = False)
PaymentHistory2 = db.Column(db.String, nullable = False)
PaymentHistoryStartDate = db.Column(db.DateTime, nullable = False)
PaymentHistoryEndDate = db.Column(db.DateTime, nullable = False)
SuitFiledWilfulDefault = db.Column(db.String, nullable = False)
WrittenOffAndSettledStatus = db.Column(db.String, nullable = False)
ValueOfCollateral = db.Column(db.String, nullable = False)
TypeOfCollateral = db.Column(db.String, nullable = False)
CreditLimit = db.Column(db.Numeric, nullable = False)
CashLimit = db.Column(db.Numeric, nullable = False)
RateOfInterest = db.Column(db.Numeric, nullable = False)
RepaymentTenure = db.Column(db.Numeric, nullable = False)
EMIAmount = db.Column(db.Numeric, nullable = False)
WrittenOffAmountTotal = db.Column(db.Numeric, nullable = False)
WrittenOffAmountPrincipal = db.Column(db.Numeric, nullable = False)
SettlementAmount = db.Column(db.Numeric, nullable = False)
PaymentFrequency = db.Column(db.String, nullable = False)
ActualPaymentAmount = db.Column(db.Numeric, nullable = False)
DateOfEntryForErrorCode = db.Column(db.String, nullable = False)
ErrorCode = db.Column(db.String, nullable = False)
DateOfEntryForCIBILRemarksCode = db.Column(db.String, nullable = False)
CIBILRemarksCode = db.Column(db.String, nullable = False)
DateOfEntryForErrorDisputeRemarksCode = db.Column(db.String, nullable = False)
DateOfEntryForErrorDisputeRemarksCode = db.Column(db.String, nullable = False)
ErrorDisputeRemarksCode1 = db.Column(db.String, nullable = False)
ErrorDisputeRemarksCode2 = db.Column(db.String, nullable = False)
createdAt = db.Column(db.DateTime, nullable = False)
updatedAt = db.Column(db.DateTime, nullable = False)
createdby = db.Column(db.Integer, nullable = False)
updatedby = db.Column(db.Integer, nullable = False)

View File

@ -0,0 +1,16 @@
# import db object from flask app
from app import db
# database tables
class Con_dpd_transaction_detail(db.Model):
id = db.Column(db.Integer, primary_key =True)
DetailID = db.Column(db.Integer, nullable = False)
AccountTranDetailsID = db.Column(db.Integer, nullable = False)
MemberRefNo = db.Column(db.Numeric, nullable = False)
StartDate = db.Column(db.DateTime, nullable = False)
Code = db.Column(db.String, nullable = False)
EntryDate = db.Column(db.DateTime, nullable = False)
createdAt = db.Column(db.DateTime, nullable = False)
updatedAt = db.Column(db.DateTime, nullable = False)
createdby = db.Column(db.Integer, nullable = False)
updatedby = db.Column(db.Integer, nullable = False)

View File

@ -0,0 +1,16 @@
# import db object from flask app
from app import db
# database tables
class Con_enquiry_detail(db.Model):
id = db.Column(db.Integer, primary_key =True)
EnquiryID = db.Column(db.Integer, nullable = False)
MemberReferenceNumber = db.Column(db.Numeric, nullable = False)
DateOfEnquiry = db.Column(db.DateTime, nullable = False)
EnquiringMemberShortName = db.Column(db.String, nullable = False)
EnquiryPurpose = db.Column(db.String, nullable = False)
EnquiryAmount = db.Column(db.Numeric, nullable = False)
createdAt = db.Column(db.DateTime, nullable = False)
updatedAt = db.Column(db.DateTime, nullable = False)
createdby = db.Column(db.Integer, nullable = False)
updatedby = db.Column(db.Integer, nullable = False)

View File

@ -0,0 +1,69 @@
# import db object from flask app
from app import db
# database tables
class In_borrower_detail(db.Model):
id = db.Column(db.Integer, primary_key =True)
losid = db.Column(db.String, nullable = False)
ReferenceNumber = db.Column(db.String, nullable = False)
ConsumerNameField1 = db.Column(db.String, nullable = False)
ConsumerNameField2 = db.Column(db.String, nullable = False)
ConsumerNameField3 = db.Column(db.String, nullable = False)
ConsumerNameField4 = db.Column(db.String, nullable = False)
ConsumerNameField5 = db.Column(db.String, nullable = False)
PAN = db.Column(db.String, nullable = False)
cibil_type = db.Column(db.String, nullable = False)
class In_credit_facility(db.Model):
AccountTranDetailsID = db.Column(db.Integer, primary_key =True)
losid = db.Column(db.String, nullable = False)
ReferenceNumber = db.Column(db.String, nullable = False)
cibil_type = db.Column(db.String, nullable = False)
month_bucket_index = db.Column(db.Integer, nullable = False)
AccountType = db.Column(db.String, nullable = False)
WrittenOffAndSettledStatus = db.Column(db.String, nullable = False)
OwnershipIndicator = db.Column(db.DateTime, nullable = False)
DateOpenedDisbursed = db.Column(db.DateTime, nullable = False)
DateClosed = db.Column(db.DateTime, nullable = False)
DateReportedAndCertified = db.Column(db.DateTime, nullable = False)
HighCreditSanctionedAmount = db.Column(db.Numeric, nullable = False)
CurrentBalance = db.Column(db.Numeric, nullable = False)
AmountOverdue = db.Column(db.Numeric, nullable = False)
CreditLimit = db.Column(db.Numeric, nullable = False)
RepaymentTenure = db.Column(db.Numeric, nullable = False)
EMIAmount = db.Column(db.Numeric, nullable = False)
grp_str = db.Column(db.String, nullable = False)
class In_dpd_transaction_detail(db.Model):
id = db.Column(db.Integer, primary_key =True)
# losid = db.Column(db.String, nullable = False)
AccountTranDetailsID = db.Column(db.Integer, nullable = False)
ReferenceNumber = db.Column(db.String, nullable = False)
cibil_type = db.Column(db.Integer, nullable = False)
month_bucket_index = db.Column(db.Integer, nullable = False)
StartDate = db.Column(db.DateTime, nullable = False)
Code = db.Column(db.String, nullable = False)
# DateOpenedDisbursed = db.Column(db.DateTime, nullable = False)
# DateReportedAndCertified = db.Column(db.DateTime, nullable = False)
# HighCreditSanctionedAmount = db.Column(db.Numeric, nullable = False)
# CurrentBalance = db.Column(db.Numeric, nullable = False)
# AmountOverdue = db.Column(db.Numeric, nullable = False)
# CreditLimit = db.Column(db.Numeric, nullable = False)
# RepaymentTenure = db.Column(db.Numeric, nullable = False)
# EMIAmount = db.Column(db.Numeric, nullable = False)
class In_enquiry_detail(db.Model):
id = db.Column(db.Integer, primary_key =True)
losid = db.Column(db.String, nullable = False)
ReferenceNumber = db.Column(db.String, nullable = False)
cibil_type = db.Column(db.Integer, nullable = False)
month_bucket_index = db.Column(db.Integer, nullable = False)
DateOfEnquiry = db.Column(db.Date, nullable = False)
EnquiryPurpose = db.Column(db.String, nullable = False)
EnquiryAmount = db.Column(db.Numeric, nullable = False)
grp_str = db.Column(db.String, nullable = False)

View File

@ -0,0 +1,13 @@
# import db object from flask app
from app import db
# database tables
class Month_bucket_master(db.Model):
id = db.Column(db.Integer, primary_key =True)
name = db.Column(db.String, nullable = False)
range_from = db.Column(db.String, nullable = False)
range_to = db.Column(db.Numeric, nullable = False)
type = db.Column(db.DateTime, nullable = False)
isactive = db.Column(db.DateTime, nullable = False)
createdon = db.Column(db.Integer, nullable = False)
updatedon = db.Column(db.Integer, nullable = False)

66
Models/op_enquiry.py Normal file
View File

@ -0,0 +1,66 @@
# import db object from flask app
from app import db
from sqlalchemy import Column, ForeignKey, Integer, Table, Numeric, String, DateTime,Boolean
from sqlalchemy.orm import declarative_base, relationship
Base = declarative_base()
class EnquiryParent(Base):
__tablename__ = "out_enquity_amount_p"
id = Column(Integer, primary_key=True)
losid = Column(Integer, nullable = False)
ref_no = Column(Integer, nullable = False)
facility_type = Column(Integer, nullable = False)
total_amt = Column(Numeric, nullable = False)
total_count = Column(Integer, nullable = False)
is_active = Column(Boolean, nullable = False)
createdAt = Column(DateTime, nullable = False)
updatedAt = Column(DateTime, nullable = False)
createdby = Column(Integer, nullable = False)
updatedby = Column(Integer, nullable = False)
output_type = Column(Integer, nullable = False)
# children = relationship("Child")
class EnquiryChild(Base):
__tablename__ = "out_enquiry_amount_c"
id = Column(Integer, primary_key=True)
# enquiry_amount_id = Column(Integer, ForeignKey("parent.id"))
enquiry_amount_id = Column(Integer, nullable = False)
months_range = Column(String, nullable = False)
amt = Column(Integer, nullable = False)
count = Column(Integer, nullable = False)
is_active = Column(Integer, nullable = False)
createdAt = Column(DateTime, nullable = True)
createdby = Column(Integer, nullable = True)
updatedAt = Column(DateTime, nullable = True)
updatedby = Column(Integer, nullable = True)
# parent = relationship("Parent")
# database tables
# class Op_enquiry_amount_and_count_unique_enquiries(db.Model):
# id = db.Column(db.Integer, primary_key =True)
# temp_id = db.Column(db.Integer, nullable = False)
# ApplicationRefno = db.Column(db.Numeric, nullable = False)
# BorrowerCurrentDetailsID = db.Column(db.Integer, nullable = False)
# CFHistory24Monthsmonth = db.Column(db.DateTime, nullable = False)
# CFHistory24MonthsACorDPD = db.Column(db.String, nullable = False)
# CFHistory24MonthsOSAmount = db.Column(db.Numeric, nullable = False)
# [id]
# ,[enquiry_amount_count_cedit_facility]
# ,[enquiry_amount_count_1]
# ,[enquiry_amount_count_2_to_3]
# ,[enquiry_amount_count_4_to_6]
# ,[enquiry_amount_count_7_to_12]
# ,[enquiry_amount_count_13_to_24]
# ,[enquiry_amount_count_25_to_36]
# ,[enquiry_amount_count_greater_than_36]
# ,[enquiry_amount_count_total]
# ,[is_active]
# ,[createdAt]
# ,[createdby]
# ,[updatedAt]
# ,[updatedby]

View File

@ -0,0 +1,61 @@
# import db object from flask app
from app import db
# database tables[out_active_and_closed_loans_details]
class Out_active_and_closed_loans_details(db.Model):
id = db.Column(db.Integer, primary_key =True)
losid = db.Column(db.String, nullable = False)
ref_no = db.Column(db.String, nullable = False)
account_type = db.Column(db.String, nullable = False)
consumer_name = db.Column(db.String, nullable = False)
ownership = db.Column(db.String, nullable = False)
reported_and_certified_date = db.Column(db.DateTime, nullable = False)
opened_date = db.Column(db.DateTime, nullable = False)
sanctioned_amount = db.Column(db.Numeric, nullable = False)
current_balance = db.Column(db.Numeric, nullable = False)
repayment_tenure = db.Column(db.Integer, nullable = False)
emi_amount = db.Column(db.Numeric, nullable = False)
overdue_amount = db.Column(db.Numeric, nullable = False)
status = db.Column(db.String, nullable = False)
current_dpd = db.Column(db.String, nullable = False)
DateClosed = db.Column(db.DateTime, nullable = False)
grp_str = db.Column(db.String, nullable = False)
# dpd0_6 = db.Column(db.String, nullable = False)
# dpd7_12 = db.Column(db.String, nullable = False)
# dpd13_24 = db.Column(db.String, nullable = False)
# dpd25_36 = db.Column(db.String, nullable = False)
highest_dpd_month_wise_bucket_or_count_0_to_6 = db.Column(db.String, nullable = False)
highest_dpd_month_wise_bucket_or_count_07_to_12 = db.Column(db.String, nullable = False)
highest_dpd_month_wise_bucket_or_count_13_to_24 = db.Column(db.String, nullable = False)
highest_dpd_month_wise_bucket_or_count_25_to_36 = db.Column(db.String, nullable = False)
is_active = db.Column(db.Boolean, nullable = False)
createdAt = db.Column(db.DateTime, nullable = False)
updatedAt = db.Column(db.DateTime, nullable = False)
createdby = db.Column(db.Integer, nullable = False)
updatedby = db.Column(db.Integer, nullable = False)
# def __init__(self, los_id):
# self.los_id = occurences
# # [id]
# ,[account_type]
# ,[consumer_name]
# ,[ownership]
# ,[reported_and_certified_date]
# ,[opened_date]
# ,[sanctioned_amount]
# ,[current_balance]
# ,[repayment_tenure]
# ,[emi_amount]
# ,[overdue_amount]
# ,[status]
# ,[current_dpd]
# ,[highest_dpd_month_wise_bucket_or_count_0_to_6]
# ,[highest_dpd_month_wise_bucket_or_count_07_to_12]
# ,[highest_dpd_month_wise_bucket_or_count_13_to_24]
# ,[highest_dpd_month_wise_bucket_or_count_25_to_36]
# ,[is_active]
# ,[createdAt]
# ,[createdby]
# ,[updatedAt]
# ,[updatedby]
#

74
Models/op_sanction.py Normal file
View File

@ -0,0 +1,74 @@
# import db object from flask app
from app import db
from sqlalchemy import Column, ForeignKey, Integer, Table, Numeric, String, DateTime,Boolean
from sqlalchemy.orm import declarative_base, relationship
Base = declarative_base()
class SanctionParent(Base):
__tablename__ = "out_sanction_amt_and_replacement_of_debt_p"
id = Column(Integer, primary_key=True)
losid = Column(Integer, nullable = False)
ref_no = Column(Integer, nullable = False)
facility_type = Column(Integer, nullable = False)
total_amt = Column(Numeric, nullable = False)
total_count = Column(Integer, nullable = False)
open_total_amt = Column(Numeric, nullable = False)
closed_total_amt = Column(Numeric, nullable = False)
open_total_count = Column(Integer, nullable = False)
closed_total_count = Column(Integer, nullable = False)
output_type = Column(Integer, nullable = False)
# is_active = Column(Boolean, nullable = False)
createdAt = Column(DateTime, nullable = False)
updatedAt = Column(DateTime, nullable = False)
createdby = Column(Integer, nullable = False)
updatedby = Column(Integer, nullable = False)
# children = relationship("Child")
class SanctionChild(Base):
__tablename__ = "out_sanction_amt_and_replacement_of_debt_c"
id = Column(Integer, primary_key=True)
# enquiry_amount_id = Column(Integer, ForeignKey("parent.id"))
sanction_amt_id = Column(Integer, nullable = False)
months_range = Column(String, nullable = False)
amt = Column(Integer, nullable = False)
count = Column(Integer, nullable = False)
opening_amt = Column(Integer, nullable = False)
opening_count = Column(Integer, nullable = False)
closing_amt = Column(Integer, nullable = False)
closing_count = Column(Integer, nullable = False)
# is_active = Column(Integer, nullable = False)
createdAt = Column(DateTime, nullable = True)
createdby = Column(Integer, nullable = True)
updatedAt = Column(DateTime, nullable = True)
updatedby = Column(Integer, nullable = True)
# parent = relationship("Parent")
# database tables
# class Op_enquiry_amount_and_count_unique_enquiries(db.Model):
# id = db.Column(db.Integer, primary_key =True)
# temp_id = db.Column(db.Integer, nullable = False)
# ApplicationRefno = db.Column(db.Numeric, nullable = False)
# BorrowerCurrentDetailsID = db.Column(db.Integer, nullable = False)
# CFHistory24Monthsmonth = db.Column(db.DateTime, nullable = False)
# CFHistory24MonthsACorDPD = db.Column(db.String, nullable = False)
# CFHistory24MonthsOSAmount = db.Column(db.Numeric, nullable = False)
# [id]
# ,[enquiry_amount_count_cedit_facility]
# ,[enquiry_amount_count_1]
# ,[enquiry_amount_count_2_to_3]
# ,[enquiry_amount_count_4_to_6]
# ,[enquiry_amount_count_7_to_12]
# ,[enquiry_amount_count_13_to_24]
# ,[enquiry_amount_count_25_to_36]
# ,[enquiry_amount_count_greater_than_36]
# ,[enquiry_amount_count_total]
# ,[is_active]
# ,[createdAt]
# ,[createdby]
# ,[updatedAt]
# ,[updatedby]

View File

@ -0,0 +1,27 @@
# import db object from flask app
from app import db
# database tables
class Op_sanction_amount_frequency(db.Model):
id = db.Column(db.Integer, primary_key =True)
temp_id = db.Column(db.Integer, nullable = False)
ApplicationRefno = db.Column(db.Numeric, nullable = False)
BorrowerCurrentDetailsID = db.Column(db.Integer, nullable = False)
CFHistory24Monthsmonth = db.Column(db.DateTime, nullable = False)
CFHistory24MonthsACorDPD = db.Column(db.String, nullable = False)
CFHistory24MonthsOSAmount = db.Column(db.Numeric, nullable = False)
# [id]
# ,[sanction_amount_count_cedit_facility]
# ,[sanction_amount_count_1]
# ,[sanction_amount_count_2_to_3]
# ,[sanction_amount_count_4_to_6]
# ,[sanction_amount_count_7_to_12]
# ,[sanction_amount_count_13_to_24]
# ,[sanction_amount_count_25_to_36]
# ,[sanction_amount_count_greater_than_36]
# ,[sanction_amount_count_total]
# ,[is_active]
# ,[createdAt]
# ,[createdby]
# ,[updatedAt]
# ,[updatedby]

View File

@ -0,0 +1,36 @@
# import db object from flask app
from app import db
# database tables
class Op_snapshot_of_closed_loans(db.Model):
id = db.Column(db.Integer, primary_key =True)
temp_id = db.Column(db.Integer, nullable = False)
ApplicationRefno = db.Column(db.Numeric, nullable = False)
BorrowerCurrentDetailsID = db.Column(db.Integer, nullable = False)
CFHistory24Monthsmonth = db.Column(db.DateTime, nullable = False)
CFHistory24MonthsACorDPD = db.Column(db.String, nullable = False)
CFHistory24MonthsOSAmount = db.Column(db.Numeric, nullable = False)
# [id]
# ,[account_type]
# ,[consumer_name]
# ,[ownership]
# ,[reported_and_certified_date]
# ,[opened_date]
# ,[sanctioned_amount]
# ,[current_balance]
# ,[repayment_tenure]
# ,[emi_amount]
# ,[overdue_amount]
# ,[status]
# ,[current_dpd]
# ,[highest_dpd_month_wise_bucket_or_count_0_to_6]
# ,[highest_dpd_month_wise_bucket_or_count_07_to_12]
# ,[highest_dpd_month_wise_bucket_or_count_13_to_24]
# ,[highest_dpd_month_wise_bucket_or_count_25_to_36]
# ,[is_active]
# ,[createdAt]
# ,[createdby]
# ,[updatedAt]
# ,[updatedby]

127
app.py Normal file
View File

@ -0,0 +1,127 @@
#sys imports
from flask import Flask
from flask_restful import Resource, Api
from flask import render_template
from flask_restful_swagger import swagger
import logging
from datetime import datetime
# from flask_sqlalchemy import SQLAlchemy
# from app import db
# import pypyodbc
#user import
from Controllers.testcontroller import *
# from Controllers.WorkingController import WorkingController
from Controllers.testclass import Test
# from routes import initialize_routes
from services.db import db
from services.PandsSampleDataDrameServeice import *
# from services.MyCustomJSONEncoder import MyJSONEncoder
from services.dbservice import DbService
from services.utilityservices import sendRestResponse #utility_blueprint
# import Controllers.testclass as testclass
app = Flask('cibil')
logFileName = './logs/'+datetime.now().strftime("%Y-%m-%d")+'.log';
########### LOG METHOD 1 #################
# logging.basicConfig(filename=logFileName,level=logging.WARNING, format=f'%(asctime)s %(levelname)s %(name)s %(threadName)s : %(message)s')
logging.basicConfig(filename=logFileName,level=logging.DEBUG, format=f'%(asctime)s %(levelname)s : %(message)s')
logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)
########### LOG METHOD 1 #################
#######METHOD 2#########################
# logger = logging.getLogger(name='cibil')
# logger.setLevel(logging.DEBUG)
# handler = logging.FileHandler(filename=logFileName)
# handler.setLevel(logging.DEBUG)
# handler.setFormatter(logging.Formatter(
# '%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
# app.logger.addHandler(handler)
# app.logger.info('Manual INfo')
#######METHOD 2#########################
# app.json_encoder = MyJSONEncoder
dbConnectionString = DbService.getDBConnectionString()
# print(dbConnectionString)
app.config['SQLALCHEMY_DATABASE_URI'] = dbConnectionString
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# db = SQLAlchemy(app)
db.init_app(app)
api = Api(app)
api = swagger.docs(api, apiVersion='0.1')
# init_app()
# result = db.engine.execute("SELECT id,charge_type,charge_type_description,created_at,modified_at FROM charge_type")
# print(result)
# for i in result:
# print(i)
# REST API's
class HelloWorld(Resource):
def get(self):
return {'hello': 'world'}
class TestFunction(Resource):
def get(self):
return testFunction()
class TestingClass(Resource):
def get(self):
print(self)
return(Test().testFunction2())
class TestDB(Resource):
def get(self):
# return(testDBcon())
return sendRestResponse(data = testDBcon())
api.add_resource(HelloWorld, '/api/')
api.add_resource(TestFunction, '/api/test')
api.add_resource(TestingClass, '/api/testclass')
api.add_resource(TestDB, '/api/db')
# Normal FLask routes
@app.route("/")
def hello_world():
app.logger.info('Manual INfo')
# app.logger.warning('Manual Warning')
# app.logger.error('Manual error')
# app.logger.critical('Manual critical')
return "<p>Hello, World!</p>"
@app.route("/aboutme/<string:name>")
def about(name=None):
# app.logger.info('Manual INfo')
# app.logger.warning('Manual Warning')
# app.logger.error('Manual error')
# app.logger.critical('Manual critical')
# print(name)
return render_template('about.html', name=name)
@app.route("/dataframe")
def dataframe():
dateframe = getDataFrame()
return render_template('dataframe.html', tables=[dateframe.to_html(classes='data')], titles=dateframe.columns.values)
@app.route("/cibildf")
def cibildataframe():
dateframe = getCIBILDataFrame()
return render_template('dataframe.html', tables=[dateframe.to_html(classes='data')], titles=dateframe.columns.values)
if __name__ == '__main__':
from routes import initialize_routes
initialize_routes(api)
app.run(debug=True)

24684
cibil.json Normal file

File diff suppressed because it is too large Load Diff

24684
com.json Normal file

File diff suppressed because it is too large Load Diff

11
consumer logic - done Normal file
View File

@ -0,0 +1,11 @@
consumer logic - done
commercial logic - done
o/p insertion logic - have to do
los id
refeence no
------------------------------
general
- logs
- aysnc functions
- queue server method

25198
data.json Normal file

File diff suppressed because it is too large Load Diff

308
logs/sample.log Normal file
View File

@ -0,0 +1,308 @@
2022-06-28 22:47:59,875 INFO : * Restarting with stat
2022-06-28 22:48:01,846 WARNING : * Debugger is active!
2022-06-28 22:48:01,863 INFO : * Debugger PIN: 245-792-354
2022-06-28 22:48:01,883 INFO : * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
2022-06-28 22:48:14,902 INFO : LOSID - MW112233, REFNO - 202201121116395000000, CTYPE - 2
2022-06-28 22:48:22,597 INFO : TOTAL CREDIT FACILITY - 68 FOUND
2022-06-28 22:48:22,997 INFO : 127.0.0.1 - - [28/Jun/2022 22:48:22] "GET /api/cibil?reference_number=202201121116395000000&los_id=MW112233&cibil_type=2&action=1 HTTP/1.1" 200 -
2022-06-28 22:49:38,798 INFO : * Detected change in 'C:\\Users\\Venba\\AppData\\Local\\Programs\\Python\\pyenv\\flask_rest\\services\\CibilBusinessOperationService.py', reloading
2022-06-28 22:49:39,023 INFO : * Restarting with stat
2022-06-28 22:49:41,127 WARNING : * Debugger is active!
2022-06-28 22:49:41,177 INFO : * Debugger PIN: 245-792-354
2022-06-28 22:49:41,217 INFO : * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
2022-06-28 22:50:46,172 INFO : * Detected change in 'C:\\Users\\Venba\\AppData\\Local\\Programs\\Python\\pyenv\\flask_rest\\services\\CibilBusinessOperationService.py', reloading
2022-06-28 22:50:46,357 INFO : * Restarting with stat
2022-06-28 22:50:48,799 WARNING : * Debugger is active!
2022-06-28 22:50:48,820 INFO : * Debugger PIN: 245-792-354
2022-06-28 22:50:48,840 INFO : * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
2022-06-28 22:51:21,922 INFO : * Detected change in 'C:\\Users\\Venba\\AppData\\Local\\Programs\\Python\\pyenv\\flask_rest\\services\\CibilBusinessOperationService.py', reloading
2022-06-28 22:51:22,141 INFO : * Restarting with stat
2022-06-28 22:51:24,208 WARNING : * Debugger is active!
2022-06-28 22:51:24,228 INFO : * Debugger PIN: 245-792-354
2022-06-28 22:51:24,245 INFO : * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
2022-06-28 22:51:44,432 INFO : * Detected change in 'C:\\Users\\Venba\\AppData\\Local\\Programs\\Python\\pyenv\\flask_rest\\Controllers\\CIBILController.py', reloading
2022-06-28 22:51:44,592 INFO : * Restarting with stat
2022-06-28 22:51:47,553 WARNING : * Debugger is active!
2022-06-28 22:51:47,577 INFO : * Debugger PIN: 245-792-354
2022-06-28 22:51:47,596 INFO : * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
2022-06-28 22:51:47,762 INFO : LOSID - MW112233, REFNO - 202201121116395000000, CTYPE - 2
2022-06-28 22:51:55,186 INFO : TOTAL CREDIT FACILITY - 68 FOUND
2022-06-28 22:51:55,587 INFO : 127.0.0.1 - - [28/Jun/2022 22:51:55] "GET /api/cibil?reference_number=202201121116395000000&los_id=MW112233&cibil_type=2&action=1 HTTP/1.1" 200 -
2022-06-28 22:53:29,120 INFO : * Detected change in 'C:\\Users\\Venba\\AppData\\Local\\Programs\\Python\\pyenv\\flask_rest\\services\\CibilBusinessOperationService.py', reloading
2022-06-28 22:53:29,296 INFO : * Restarting with stat
2022-06-28 22:53:31,454 WARNING : * Debugger is active!
2022-06-28 22:53:31,473 INFO : * Debugger PIN: 245-792-354
2022-06-28 22:53:31,494 INFO : * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
2022-06-28 22:53:37,277 INFO : LOSID - MW112233, REFNO - 202201121116395000000, CTYPE - 2
2022-06-28 22:53:45,930 INFO : TOTAL CREDIT FACILITY - 68 FOUND
2022-06-28 22:53:46,431 INFO : 127.0.0.1 - - [28/Jun/2022 22:53:46] "GET /api/cibil?reference_number=202201121116395000000&los_id=MW112233&cibil_type=2&action=1 HTTP/1.1" 500 -
2022-06-28 22:53:47,158 INFO : 127.0.0.1 - - [28/Jun/2022 22:53:47] "GET /api/cibil?__debugger__=yes&cmd=resource&f=jquery.js HTTP/1.1" 200 -
2022-06-28 22:53:47,187 INFO : 127.0.0.1 - - [28/Jun/2022 22:53:47] "GET /api/cibil?__debugger__=yes&cmd=resource&f=style.css HTTP/1.1" 200 -
2022-06-28 22:53:47,191 INFO : 127.0.0.1 - - [28/Jun/2022 22:53:47] "GET /api/cibil?__debugger__=yes&cmd=resource&f=debugger.js HTTP/1.1" 200 -
2022-06-28 22:53:47,285 INFO : 127.0.0.1 - - [28/Jun/2022 22:53:47] "GET /api/cibil?__debugger__=yes&cmd=resource&f=ubuntu.ttf HTTP/1.1" 200 -
2022-06-28 22:53:47,755 INFO : 127.0.0.1 - - [28/Jun/2022 22:53:47] "GET /api/cibil?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 -
2022-06-28 22:54:49,150 INFO : * Detected change in 'C:\\Users\\Venba\\AppData\\Local\\Programs\\Python\\pyenv\\flask_rest\\Models\\intermediate_tables.py', reloading
2022-06-28 22:54:49,335 INFO : * Restarting with stat
2022-06-28 22:54:51,997 WARNING : * Debugger is active!
2022-06-28 22:54:52,020 INFO : * Debugger PIN: 245-792-354
2022-06-28 22:54:52,044 INFO : * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
2022-06-28 22:54:52,107 INFO : LOSID - MW112233, REFNO - 202201121116395000000, CTYPE - 2
2022-06-28 22:55:00,931 INFO : TOTAL CREDIT FACILITY - 68 FOUND
2022-06-28 22:55:01,864 INFO : 127.0.0.1 - - [28/Jun/2022 22:55:01] "GET /api/cibil?reference_number=202201121116395000000&los_id=MW112233&cibil_type=2&action=1 HTTP/1.1" 500 -
2022-06-28 22:55:02,501 INFO : 127.0.0.1 - - [28/Jun/2022 22:55:02] "GET /api/cibil?__debugger__=yes&cmd=resource&f=jquery.js HTTP/1.1" 200 -
2022-06-28 22:55:02,505 INFO : 127.0.0.1 - - [28/Jun/2022 22:55:02] "GET /api/cibil?__debugger__=yes&cmd=resource&f=style.css HTTP/1.1" 200 -
2022-06-28 22:55:02,521 INFO : 127.0.0.1 - - [28/Jun/2022 22:55:02] "GET /api/cibil?__debugger__=yes&cmd=resource&f=debugger.js HTTP/1.1" 200 -
2022-06-28 22:55:02,899 INFO : 127.0.0.1 - - [28/Jun/2022 22:55:02] "GET /api/cibil?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 -
2022-06-28 22:56:00,755 INFO : * Detected change in 'C:\\Users\\Venba\\AppData\\Local\\Programs\\Python\\pyenv\\flask_rest\\Models\\intermediate_tables.py', reloading
2022-06-28 22:56:00,993 INFO : * Restarting with stat
2022-06-28 22:56:03,578 WARNING : * Debugger is active!
2022-06-28 22:56:03,600 INFO : * Debugger PIN: 245-792-354
2022-06-28 22:56:03,620 INFO : * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
2022-06-28 22:56:22,930 INFO : * Detected change in 'C:\\Users\\Venba\\AppData\\Local\\Programs\\Python\\pyenv\\flask_rest\\services\\CibilDataService.py', reloading
2022-06-28 22:56:23,196 INFO : * Restarting with stat
2022-06-28 22:56:25,621 WARNING : * Debugger is active!
2022-06-28 22:56:25,641 INFO : * Debugger PIN: 245-792-354
2022-06-28 22:56:25,659 INFO : * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
2022-06-28 22:56:37,291 INFO : LOSID - MW112233, REFNO - 202201121116395000000, CTYPE - 2
2022-06-28 22:56:45,051 INFO : TOTAL CREDIT FACILITY - 68 FOUND
2022-06-28 22:56:45,507 INFO : 127.0.0.1 - - [28/Jun/2022 22:56:45] "GET /api/cibil?reference_number=202201121116395000000&los_id=MW112233&cibil_type=2&action=1 HTTP/1.1" 500 -
2022-06-28 22:56:46,155 INFO : 127.0.0.1 - - [28/Jun/2022 22:56:46] "GET /api/cibil?__debugger__=yes&cmd=resource&f=style.css HTTP/1.1" 200 -
2022-06-28 22:56:46,187 INFO : 127.0.0.1 - - [28/Jun/2022 22:56:46] "GET /api/cibil?__debugger__=yes&cmd=resource&f=debugger.js HTTP/1.1" 200 -
2022-06-28 22:56:46,194 INFO : 127.0.0.1 - - [28/Jun/2022 22:56:46] "GET /api/cibil?__debugger__=yes&cmd=resource&f=jquery.js HTTP/1.1" 200 -
2022-06-28 22:56:46,473 INFO : 127.0.0.1 - - [28/Jun/2022 22:56:46] "GET /api/cibil?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 -
2022-06-28 22:58:15,963 INFO : * Detected change in 'C:\\Users\\Venba\\AppData\\Local\\Programs\\Python\\pyenv\\flask_rest\\Models\\intermediate_tables.py', reloading
2022-06-28 22:58:16,198 INFO : * Restarting with stat
2022-06-28 22:58:18,717 WARNING : * Debugger is active!
2022-06-28 22:58:18,740 INFO : * Debugger PIN: 245-792-354
2022-06-28 22:58:18,758 INFO : * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
2022-06-28 22:58:27,323 INFO : LOSID - MW112233, REFNO - 202201121116395000000, CTYPE - 2
2022-06-28 22:58:35,570 INFO : TOTAL CREDIT FACILITY - 68 FOUND
2022-06-28 22:58:38,125 INFO : 127.0.0.1 - - [28/Jun/2022 22:58:38] "GET /api/cibil?reference_number=202201121116395000000&los_id=MW112233&cibil_type=2&action=1 HTTP/1.1" 500 -
2022-06-28 22:58:38,708 INFO : 127.0.0.1 - - [28/Jun/2022 22:58:38] "GET /api/cibil?__debugger__=yes&cmd=resource&f=jquery.js HTTP/1.1" 200 -
2022-06-28 22:58:38,719 INFO : 127.0.0.1 - - [28/Jun/2022 22:58:38] "GET /api/cibil?__debugger__=yes&cmd=resource&f=style.css HTTP/1.1" 200 -
2022-06-28 22:58:38,739 INFO : 127.0.0.1 - - [28/Jun/2022 22:58:38] "GET /api/cibil?__debugger__=yes&cmd=resource&f=debugger.js HTTP/1.1" 200 -
2022-06-28 22:58:38,948 INFO : 127.0.0.1 - - [28/Jun/2022 22:58:38] "GET /api/cibil?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 -
2022-06-28 22:59:07,633 INFO : * Detected change in 'C:\\Users\\Venba\\AppData\\Local\\Programs\\Python\\pyenv\\flask_rest\\services\\CibilDataService.py', reloading
2022-06-28 22:59:07,876 INFO : * Restarting with stat
2022-06-28 22:59:11,231 WARNING : * Debugger is active!
2022-06-28 22:59:11,249 INFO : * Debugger PIN: 245-792-354
2022-06-28 22:59:11,274 INFO : * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
2022-06-28 22:59:11,412 INFO : LOSID - MW112233, REFNO - 202201121116395000000, CTYPE - 2
2022-06-28 22:59:19,561 INFO : TOTAL CREDIT FACILITY - 68 FOUND
2022-06-28 22:59:21,784 INFO : 127.0.0.1 - - [28/Jun/2022 22:59:21] "GET /api/cibil?reference_number=202201121116395000000&los_id=MW112233&cibil_type=2&action=1 HTTP/1.1" 200 -
2022-06-28 23:00:15,830 INFO : * Detected change in 'C:\\Users\\Venba\\AppData\\Local\\Programs\\Python\\pyenv\\flask_rest\\services\\CibilBusinessOperationService.py', reloading
2022-06-28 23:00:16,010 INFO : * Restarting with stat
2022-06-28 23:00:18,217 WARNING : * Debugger is active!
2022-06-28 23:00:18,233 INFO : * Debugger PIN: 245-792-354
2022-06-28 23:00:18,255 INFO : * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
2022-06-28 23:01:19,971 INFO : * Detected change in 'C:\\Users\\Venba\\AppData\\Local\\Programs\\Python\\pyenv\\flask_rest\\services\\DpdCalculationService.py', reloading
2022-06-28 23:01:20,128 INFO : * Restarting with stat
2022-06-28 23:01:22,887 WARNING : * Debugger is active!
2022-06-28 23:01:22,940 INFO : * Debugger PIN: 245-792-354
2022-06-28 23:01:22,979 INFO : * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
2022-06-28 23:02:07,120 INFO : * Detected change in 'C:\\Users\\Venba\\AppData\\Local\\Programs\\Python\\pyenv\\flask_rest\\services\\DpdCalculationService.py', reloading
2022-06-28 23:02:07,302 INFO : * Restarting with stat
2022-06-28 23:02:10,764 WARNING : * Debugger is active!
2022-06-28 23:02:10,818 INFO : * Debugger PIN: 245-792-354
2022-06-28 23:02:10,846 INFO : * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
2022-06-28 23:05:30,173 INFO : * Detected change in 'C:\\Users\\Venba\\AppData\\Local\\Programs\\Python\\pyenv\\flask_rest\\services\\CibilBusinessOperationService.py', reloading
2022-06-28 23:05:30,342 INFO : * Restarting with stat
2022-06-28 23:05:32,948 WARNING : * Debugger is active!
2022-06-28 23:05:32,964 INFO : * Debugger PIN: 245-792-354
2022-06-28 23:05:32,989 INFO : * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
2022-06-28 23:05:46,743 INFO : * Detected change in 'C:\\Users\\Venba\\AppData\\Local\\Programs\\Python\\pyenv\\flask_rest\\services\\CibilBusinessOperationService.py', reloading
2022-06-28 23:05:47,011 INFO : * Restarting with stat
2022-06-28 23:05:49,396 WARNING : * Debugger is active!
2022-06-28 23:05:49,415 INFO : * Debugger PIN: 245-792-354
2022-06-28 23:05:49,435 INFO : * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
2022-06-28 23:05:51,867 INFO : LOSID - MW112233, REFNO - 202201121116395000000, CTYPE - 2
2022-06-28 23:05:59,563 INFO : TOTAL CREDIT FACILITY - 68 FOUND
2022-06-28 23:06:01,878 INFO : 127.0.0.1 - - [28/Jun/2022 23:06:01] "GET /api/cibil?reference_number=202201121116395000000&los_id=MW112233&cibil_type=2&action=1 HTTP/1.1" 500 -
2022-06-28 23:06:02,523 INFO : 127.0.0.1 - - [28/Jun/2022 23:06:02] "GET /api/cibil?__debugger__=yes&cmd=resource&f=jquery.js HTTP/1.1" 200 -
2022-06-28 23:06:02,548 INFO : 127.0.0.1 - - [28/Jun/2022 23:06:02] "GET /api/cibil?__debugger__=yes&cmd=resource&f=debugger.js HTTP/1.1" 200 -
2022-06-28 23:06:02,557 INFO : 127.0.0.1 - - [28/Jun/2022 23:06:02] "GET /api/cibil?__debugger__=yes&cmd=resource&f=style.css HTTP/1.1" 200 -
2022-06-28 23:06:02,620 INFO : 127.0.0.1 - - [28/Jun/2022 23:06:02] "GET /api/cibil?__debugger__=yes&cmd=resource&f=ubuntu.ttf HTTP/1.1" 200 -
2022-06-28 23:06:02,927 INFO : 127.0.0.1 - - [28/Jun/2022 23:06:02] "GET /api/cibil?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 -
2022-06-28 23:07:11,579 INFO : * Detected change in 'C:\\Users\\Venba\\AppData\\Local\\Programs\\Python\\pyenv\\flask_rest\\services\\CibilDataService.py', reloading
2022-06-28 23:07:11,829 INFO : * Restarting with stat
2022-06-28 23:07:14,184 WARNING : * Debugger is active!
2022-06-28 23:07:14,205 INFO : * Debugger PIN: 245-792-354
2022-06-28 23:07:14,226 INFO : * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
2022-06-28 23:08:08,919 INFO : LOSID - MW112233, REFNO - 202201121116395000000, CTYPE - 2
2022-06-28 23:08:17,186 INFO : TOTAL CREDIT FACILITY - 68 FOUND
2022-06-28 23:08:20,722 INFO : 127.0.0.1 - - [28/Jun/2022 23:08:20] "GET /api/cibil?reference_number=202201121116395000000&los_id=MW112233&cibil_type=2&action=1 HTTP/1.1" 500 -
2022-06-28 23:08:21,341 INFO : 127.0.0.1 - - [28/Jun/2022 23:08:21] "GET /api/cibil?__debugger__=yes&cmd=resource&f=debugger.js HTTP/1.1" 200 -
2022-06-28 23:08:21,341 INFO : 127.0.0.1 - - [28/Jun/2022 23:08:21] "GET /api/cibil?__debugger__=yes&cmd=resource&f=style.css HTTP/1.1" 200 -
2022-06-28 23:08:21,343 INFO : 127.0.0.1 - - [28/Jun/2022 23:08:21] "GET /api/cibil?__debugger__=yes&cmd=resource&f=jquery.js HTTP/1.1" 200 -
2022-06-28 23:08:21,642 INFO : 127.0.0.1 - - [28/Jun/2022 23:08:21] "GET /api/cibil?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 -
2022-06-28 23:08:43,003 INFO : * Detected change in 'C:\\Users\\Venba\\AppData\\Local\\Programs\\Python\\pyenv\\flask_rest\\services\\CibilDataService.py', reloading
2022-06-28 23:08:43,262 INFO : * Restarting with stat
2022-06-28 23:08:45,743 WARNING : * Debugger is active!
2022-06-28 23:08:45,766 INFO : * Debugger PIN: 245-792-354
2022-06-28 23:08:45,785 INFO : * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
2022-06-28 23:08:45,873 INFO : LOSID - MW112233, REFNO - 202201121116395000000, CTYPE - 2
2022-06-28 23:08:53,642 INFO : TOTAL CREDIT FACILITY - 68 FOUND
2022-06-28 23:08:56,801 INFO : 127.0.0.1 - - [28/Jun/2022 23:08:56] "GET /api/cibil?reference_number=202201121116395000000&los_id=MW112233&cibil_type=2&action=1 HTTP/1.1" 500 -
2022-06-28 23:08:57,473 INFO : 127.0.0.1 - - [28/Jun/2022 23:08:57] "GET /api/cibil?__debugger__=yes&cmd=resource&f=style.css HTTP/1.1" 200 -
2022-06-28 23:08:57,502 INFO : 127.0.0.1 - - [28/Jun/2022 23:08:57] "GET /api/cibil?__debugger__=yes&cmd=resource&f=jquery.js HTTP/1.1" 200 -
2022-06-28 23:08:57,504 INFO : 127.0.0.1 - - [28/Jun/2022 23:08:57] "GET /api/cibil?__debugger__=yes&cmd=resource&f=debugger.js HTTP/1.1" 200 -
2022-06-28 23:08:57,601 INFO : 127.0.0.1 - - [28/Jun/2022 23:08:57] "GET /api/cibil?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 -
2022-06-28 23:08:57,784 INFO : 127.0.0.1 - - [28/Jun/2022 23:08:57] "GET /api/cibil?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 -
2022-06-28 23:09:20,775 INFO : * Detected change in 'C:\\Users\\Venba\\AppData\\Local\\Programs\\Python\\pyenv\\flask_rest\\services\\CibilDataService.py', reloading
2022-06-28 23:09:21,016 INFO : * Restarting with stat
2022-06-28 23:09:23,410 WARNING : * Debugger is active!
2022-06-28 23:09:23,430 INFO : * Debugger PIN: 245-792-354
2022-06-28 23:09:23,448 INFO : * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
2022-06-28 23:09:26,477 INFO : LOSID - MW112233, REFNO - 202201121116395000000, CTYPE - 2
2022-06-28 23:09:36,847 INFO : TOTAL CREDIT FACILITY - 68 FOUND
2022-06-28 23:09:39,519 INFO : 127.0.0.1 - - [28/Jun/2022 23:09:39] "GET /api/cibil?reference_number=202201121116395000000&los_id=MW112233&cibil_type=2&action=1 HTTP/1.1" 500 -
2022-06-28 23:09:40,177 INFO : 127.0.0.1 - - [28/Jun/2022 23:09:40] "GET /api/cibil?__debugger__=yes&cmd=resource&f=jquery.js HTTP/1.1" 200 -
2022-06-28 23:09:40,191 INFO : 127.0.0.1 - - [28/Jun/2022 23:09:40] "GET /api/cibil?__debugger__=yes&cmd=resource&f=style.css HTTP/1.1" 200 -
2022-06-28 23:09:40,230 INFO : 127.0.0.1 - - [28/Jun/2022 23:09:40] "GET /api/cibil?__debugger__=yes&cmd=resource&f=debugger.js HTTP/1.1" 200 -
2022-06-28 23:09:40,473 INFO : 127.0.0.1 - - [28/Jun/2022 23:09:40] "GET /api/cibil?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 -
2022-06-28 23:10:05,228 INFO : * Detected change in 'C:\\Users\\Venba\\AppData\\Local\\Programs\\Python\\pyenv\\flask_rest\\services\\CibilDataService.py', reloading
2022-06-28 23:10:05,419 INFO : * Restarting with stat
2022-06-28 23:10:08,124 WARNING : * Debugger is active!
2022-06-28 23:10:08,147 INFO : * Debugger PIN: 245-792-354
2022-06-28 23:10:08,174 INFO : * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
2022-06-28 23:10:08,349 INFO : LOSID - MW112233, REFNO - 202201121116395000000, CTYPE - 2
2022-06-28 23:10:15,967 INFO : TOTAL CREDIT FACILITY - 68 FOUND
2022-06-28 23:10:18,672 INFO : 127.0.0.1 - - [28/Jun/2022 23:10:18] "GET /api/cibil?reference_number=202201121116395000000&los_id=MW112233&cibil_type=2&action=1 HTTP/1.1" 500 -
2022-06-28 23:10:19,418 INFO : 127.0.0.1 - - [28/Jun/2022 23:10:19] "GET /api/cibil?__debugger__=yes&cmd=resource&f=style.css HTTP/1.1" 200 -
2022-06-28 23:10:19,443 INFO : 127.0.0.1 - - [28/Jun/2022 23:10:19] "GET /api/cibil?__debugger__=yes&cmd=resource&f=jquery.js HTTP/1.1" 200 -
2022-06-28 23:10:19,467 INFO : 127.0.0.1 - - [28/Jun/2022 23:10:19] "GET /api/cibil?__debugger__=yes&cmd=resource&f=debugger.js HTTP/1.1" 200 -
2022-06-28 23:10:19,835 INFO : 127.0.0.1 - - [28/Jun/2022 23:10:19] "GET /api/cibil?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 -
2022-06-28 23:12:45,584 INFO : LOSID - MW112233, REFNO - 202201121116395000000, CTYPE - 2
2022-06-28 23:12:48,311 INFO : TOTAL CREDIT FACILITY - 68 FOUND
2022-06-28 23:12:50,185 INFO : 127.0.0.1 - - [28/Jun/2022 23:12:50] "GET /api/cibil?reference_number=202201121116395000000&los_id=MW112233&cibil_type=2&action=1 HTTP/1.1" 500 -
2022-06-28 23:12:50,588 INFO : 127.0.0.1 - - [28/Jun/2022 23:12:50] "GET /api/cibil?__debugger__=yes&cmd=resource&f=style.css HTTP/1.1" 200 -
2022-06-28 23:12:50,594 INFO : 127.0.0.1 - - [28/Jun/2022 23:12:50] "GET /api/cibil?__debugger__=yes&cmd=resource&f=jquery.js HTTP/1.1" 200 -
2022-06-28 23:12:50,596 INFO : 127.0.0.1 - - [28/Jun/2022 23:12:50] "GET /api/cibil?__debugger__=yes&cmd=resource&f=debugger.js HTTP/1.1" 200 -
2022-06-28 23:12:50,923 INFO : 127.0.0.1 - - [28/Jun/2022 23:12:50] "GET /api/cibil?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 -
2022-06-28 23:13:10,601 INFO : * Detected change in 'C:\\Users\\Venba\\AppData\\Local\\Programs\\Python\\pyenv\\flask_rest\\services\\CibilDataService.py', reloading
2022-06-28 23:13:10,952 INFO : * Restarting with stat
2022-06-28 23:13:14,649 WARNING : * Debugger is active!
2022-06-28 23:13:14,694 INFO : * Debugger PIN: 245-792-354
2022-06-28 23:13:14,725 INFO : * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
2022-06-28 23:13:14,733 INFO : LOSID - MW112233, REFNO - 202201121116395000000, CTYPE - 2
2022-06-28 23:13:22,136 INFO : TOTAL CREDIT FACILITY - 68 FOUND
2022-06-28 23:13:26,657 INFO : 127.0.0.1 - - [28/Jun/2022 23:13:26] "GET /api/cibil?reference_number=202201121116395000000&los_id=MW112233&cibil_type=2&action=1 HTTP/1.1" 500 -
2022-06-28 23:13:27,435 INFO : 127.0.0.1 - - [28/Jun/2022 23:13:27] "GET /api/cibil?__debugger__=yes&cmd=resource&f=style.css HTTP/1.1" 200 -
2022-06-28 23:13:27,452 INFO : 127.0.0.1 - - [28/Jun/2022 23:13:27] "GET /api/cibil?__debugger__=yes&cmd=resource&f=jquery.js HTTP/1.1" 200 -
2022-06-28 23:13:27,511 INFO : 127.0.0.1 - - [28/Jun/2022 23:13:27] "GET /api/cibil?__debugger__=yes&cmd=resource&f=debugger.js HTTP/1.1" 200 -
2022-06-28 23:13:27,765 INFO : 127.0.0.1 - - [28/Jun/2022 23:13:27] "GET /api/cibil?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 -
2022-06-28 23:17:49,169 INFO : * Detected change in 'C:\\Users\\Venba\\AppData\\Local\\Programs\\Python\\pyenv\\flask_rest\\Models\\intermediate_tables.py', reloading
2022-06-28 23:17:49,404 INFO : * Restarting with stat
2022-06-28 23:17:52,761 WARNING : * Debugger is active!
2022-06-28 23:17:52,786 INFO : * Debugger PIN: 245-792-354
2022-06-28 23:17:52,805 INFO : * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
2022-06-28 23:17:57,641 INFO : LOSID - MW112233, REFNO - 202201121116395000000, CTYPE - 2
2022-06-28 23:18:06,302 INFO : TOTAL CREDIT FACILITY - 68 FOUND
2022-06-28 23:18:10,382 INFO : 127.0.0.1 - - [28/Jun/2022 23:18:10] "GET /api/cibil?reference_number=202201121116395000000&los_id=MW112233&cibil_type=2&action=1 HTTP/1.1" 500 -
2022-06-28 23:18:11,142 INFO : 127.0.0.1 - - [28/Jun/2022 23:18:11] "GET /api/cibil?__debugger__=yes&cmd=resource&f=style.css HTTP/1.1" 200 -
2022-06-28 23:18:11,142 INFO : 127.0.0.1 - - [28/Jun/2022 23:18:11] "GET /api/cibil?__debugger__=yes&cmd=resource&f=jquery.js HTTP/1.1" 200 -
2022-06-28 23:18:11,145 INFO : 127.0.0.1 - - [28/Jun/2022 23:18:11] "GET /api/cibil?__debugger__=yes&cmd=resource&f=debugger.js HTTP/1.1" 200 -
2022-06-28 23:18:11,562 INFO : 127.0.0.1 - - [28/Jun/2022 23:18:11] "GET /api/cibil?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 -
2022-06-28 23:18:37,988 INFO : * Detected change in 'C:\\Users\\Venba\\AppData\\Local\\Programs\\Python\\pyenv\\flask_rest\\services\\CibilBusinessOperationService.py', reloading
2022-06-28 23:18:38,214 INFO : * Restarting with stat
2022-06-28 23:18:40,938 WARNING : * Debugger is active!
2022-06-28 23:18:40,957 INFO : * Debugger PIN: 245-792-354
2022-06-28 23:18:40,975 INFO : * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
2022-06-28 23:18:47,757 INFO : LOSID - MW112233, REFNO - 202201121116395000000, CTYPE - 2
2022-06-28 23:18:56,397 INFO : TOTAL CREDIT FACILITY - 68 FOUND
2022-06-28 23:19:00,260 INFO : 127.0.0.1 - - [28/Jun/2022 23:19:00] "GET /api/cibil?reference_number=202201121116395000000&los_id=MW112233&cibil_type=2&action=1 HTTP/1.1" 200 -
2022-06-28 23:19:34,776 INFO : * Detected change in 'C:\\Users\\Venba\\AppData\\Local\\Programs\\Python\\pyenv\\flask_rest\\services\\CibilBusinessOperationService.py', reloading
2022-06-28 23:19:35,003 INFO : * Restarting with stat
2022-06-28 23:19:37,794 WARNING : * Debugger is active!
2022-06-28 23:19:37,814 INFO : * Debugger PIN: 245-792-354
2022-06-28 23:19:37,841 INFO : * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
2022-06-28 23:19:59,338 INFO : * Detected change in 'C:\\Users\\Venba\\AppData\\Local\\Programs\\Python\\pyenv\\flask_rest\\services\\CibilDataService.py', reloading
2022-06-28 23:19:59,567 INFO : * Restarting with stat
2022-06-28 23:20:01,964 WARNING : * Debugger is active!
2022-06-28 23:20:01,988 INFO : * Debugger PIN: 245-792-354
2022-06-28 23:20:02,008 INFO : * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
2022-06-28 23:21:07,814 INFO : * Detected change in 'C:\\Users\\Venba\\AppData\\Local\\Programs\\Python\\pyenv\\flask_rest\\services\\CibilSummaryDataUpdateService.py', reloading
2022-06-28 23:21:08,041 INFO : * Restarting with stat
2022-06-28 23:21:11,062 WARNING : * Debugger is active!
2022-06-28 23:21:11,089 INFO : * Debugger PIN: 245-792-354
2022-06-28 23:21:11,109 INFO : * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
2022-06-28 23:24:04,342 INFO : * Detected change in 'C:\\Users\\Venba\\AppData\\Local\\Programs\\Python\\pyenv\\flask_rest\\services\\CibilSummaryDataUpdateService.py', reloading
2022-06-28 23:24:04,559 INFO : * Restarting with stat
2022-06-28 23:24:07,390 WARNING : * Debugger is active!
2022-06-28 23:24:07,412 INFO : * Debugger PIN: 245-792-354
2022-06-28 23:24:07,432 INFO : * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
2022-06-28 23:25:21,575 INFO : * Detected change in 'C:\\Users\\Venba\\AppData\\Local\\Programs\\Python\\pyenv\\flask_rest\\services\\CibilBusinessOperationService.py', reloading
2022-06-28 23:25:21,793 INFO : * Restarting with stat
2022-06-28 23:25:24,119 WARNING : * Debugger is active!
2022-06-28 23:25:24,141 INFO : * Debugger PIN: 245-792-354
2022-06-28 23:25:24,160 INFO : * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
2022-06-28 23:25:48,175 INFO : * Detected change in 'C:\\Users\\Venba\\AppData\\Local\\Programs\\Python\\pyenv\\flask_rest\\services\\CibilBusinessOperationService.py', reloading
2022-06-28 23:25:48,449 INFO : * Restarting with stat
2022-06-28 23:25:50,838 WARNING : * Debugger is active!
2022-06-28 23:25:50,860 INFO : * Debugger PIN: 245-792-354
2022-06-28 23:25:50,878 INFO : * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
2022-06-28 23:27:46,571 INFO : LOSID - MW112233, REFNO - 202201121116395000000, CTYPE - 2
2022-06-28 23:27:55,390 INFO : TOTAL CREDIT FACILITY - 68 FOUND
2022-06-28 23:27:58,299 INFO : 127.0.0.1 - - [28/Jun/2022 23:27:58] "GET /api/cibil?reference_number=202201121116395000000&los_id=MW112233&cibil_type=2&action=1 HTTP/1.1" 500 -
2022-06-28 23:27:59,294 INFO : 127.0.0.1 - - [28/Jun/2022 23:27:59] "GET /api/cibil?__debugger__=yes&cmd=resource&f=style.css HTTP/1.1" 200 -
2022-06-28 23:27:59,303 INFO : 127.0.0.1 - - [28/Jun/2022 23:27:59] "GET /api/cibil?__debugger__=yes&cmd=resource&f=jquery.js HTTP/1.1" 200 -
2022-06-28 23:27:59,327 INFO : 127.0.0.1 - - [28/Jun/2022 23:27:59] "GET /api/cibil?__debugger__=yes&cmd=resource&f=debugger.js HTTP/1.1" 200 -
2022-06-28 23:27:59,434 INFO : 127.0.0.1 - - [28/Jun/2022 23:27:59] "GET /api/cibil?__debugger__=yes&cmd=resource&f=ubuntu.ttf HTTP/1.1" 200 -
2022-06-28 23:27:59,770 INFO : 127.0.0.1 - - [28/Jun/2022 23:27:59] "GET /api/cibil?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 -
2022-06-28 23:31:13,905 INFO : * Detected change in 'C:\\Users\\Venba\\AppData\\Local\\Programs\\Python\\pyenv\\flask_rest\\services\\DpdCalculationService.py', reloading
2022-06-28 23:31:14,232 INFO : * Restarting with stat
2022-06-28 23:31:17,244 WARNING : * Debugger is active!
2022-06-28 23:31:17,274 INFO : * Debugger PIN: 245-792-354
2022-06-28 23:31:17,303 INFO : * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
2022-06-28 23:31:37,756 INFO : * Detected change in 'C:\\Users\\Venba\\AppData\\Local\\Programs\\Python\\pyenv\\flask_rest\\services\\CibilBusinessOperationService.py', reloading
2022-06-28 23:31:37,947 INFO : * Restarting with stat
2022-06-28 23:31:40,474 WARNING : * Debugger is active!
2022-06-28 23:31:40,562 INFO : * Debugger PIN: 245-792-354
2022-06-28 23:31:40,614 INFO : * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
2022-06-28 23:31:41,084 INFO : LOSID - MW112233, REFNO - 202201121116395000000, CTYPE - 2
2022-06-28 23:31:48,718 INFO : TOTAL CREDIT FACILITY - 68 FOUND
2022-06-28 23:31:51,650 INFO : 127.0.0.1 - - [28/Jun/2022 23:31:51] "GET /api/cibil?reference_number=202201121116395000000&los_id=MW112233&cibil_type=2&action=1 HTTP/1.1" 500 -
2022-06-28 23:31:52,390 INFO : 127.0.0.1 - - [28/Jun/2022 23:31:52] "GET /api/cibil?__debugger__=yes&cmd=resource&f=style.css HTTP/1.1" 200 -
2022-06-28 23:31:52,442 INFO : 127.0.0.1 - - [28/Jun/2022 23:31:52] "GET /api/cibil?__debugger__=yes&cmd=resource&f=jquery.js HTTP/1.1" 200 -
2022-06-28 23:31:52,575 INFO : 127.0.0.1 - - [28/Jun/2022 23:31:52] "GET /api/cibil?__debugger__=yes&cmd=resource&f=debugger.js HTTP/1.1" 200 -
2022-06-28 23:31:53,212 INFO : 127.0.0.1 - - [28/Jun/2022 23:31:53] "GET /api/cibil?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 -
2022-06-28 23:37:54,616 INFO : * Detected change in 'C:\\Users\\Venba\\AppData\\Local\\Programs\\Python\\pyenv\\flask_rest\\services\\DpdCalculationService.py', reloading
2022-06-28 23:37:54,841 INFO : * Restarting with stat
2022-06-28 23:37:58,818 WARNING : * Debugger is active!
2022-06-28 23:37:58,872 INFO : * Debugger PIN: 245-792-354
2022-06-28 23:37:58,908 INFO : * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
2022-06-28 23:37:59,041 INFO : LOSID - MW112233, REFNO - 202201121116395000000, CTYPE - 2
2022-06-28 23:38:06,626 INFO : TOTAL CREDIT FACILITY - 68 FOUND
2022-06-28 23:38:09,814 INFO : 127.0.0.1 - - [28/Jun/2022 23:38:09] "GET /api/cibil?reference_number=202201121116395000000&los_id=MW112233&cibil_type=2&action=1 HTTP/1.1" 500 -
2022-06-28 23:38:10,868 INFO : 127.0.0.1 - - [28/Jun/2022 23:38:10] "GET /api/cibil?__debugger__=yes&cmd=resource&f=jquery.js HTTP/1.1" 200 -
2022-06-28 23:38:10,914 INFO : 127.0.0.1 - - [28/Jun/2022 23:38:10] "GET /api/cibil?__debugger__=yes&cmd=resource&f=style.css HTTP/1.1" 200 -
2022-06-28 23:38:10,945 INFO : 127.0.0.1 - - [28/Jun/2022 23:38:10] "GET /api/cibil?__debugger__=yes&cmd=resource&f=debugger.js HTTP/1.1" 200 -
2022-06-28 23:38:11,448 INFO : 127.0.0.1 - - [28/Jun/2022 23:38:11] "GET /api/cibil?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 -
2022-06-28 23:39:23,038 INFO : * Detected change in 'C:\\Users\\Venba\\AppData\\Local\\Programs\\Python\\pyenv\\flask_rest\\services\\DpdCalculationService.py', reloading
2022-06-28 23:39:23,233 INFO : * Restarting with stat
2022-06-28 23:39:26,051 WARNING : * Debugger is active!
2022-06-28 23:39:26,116 INFO : * Debugger PIN: 245-792-354
2022-06-28 23:39:26,152 INFO : * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
2022-06-28 23:39:26,271 INFO : LOSID - MW112233, REFNO - 202201121116395000000, CTYPE - 2
2022-06-28 23:39:33,965 INFO : TOTAL CREDIT FACILITY - 68 FOUND
2022-06-28 23:39:39,134 INFO : TOTAL ACTIVE&CLOSE LOANS - 68
2022-06-28 23:39:39,483 INFO : 127.0.0.1 - - [28/Jun/2022 23:39:39] "GET /api/cibil?reference_number=202201121116395000000&los_id=MW112233&cibil_type=2&action=1 HTTP/1.1" 200 -
2022-06-28 23:40:20,833 INFO : * Detected change in 'C:\\Users\\Venba\\AppData\\Local\\Programs\\Python\\pyenv\\flask_rest\\services\\CibilBusinessOperationService.py', reloading
2022-06-28 23:40:21,022 INFO : * Restarting with stat
2022-06-28 23:40:23,766 WARNING : * Debugger is active!
2022-06-28 23:40:23,797 INFO : * Debugger PIN: 245-792-354
2022-06-28 23:40:23,829 INFO : * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
2022-06-28 23:41:11,060 INFO : LOSID - MW112233, REFNO - 202201121116395000000, CTYPE - 2
2022-06-28 23:41:16,239 INFO : TOTAL CREDIT FACILITY - 68 FOUND
2022-06-28 23:41:18,813 INFO : TOTAL ACTIVE&CLOSED LOANS - 68
2022-06-28 23:41:57,978 INFO : 127.0.0.1 - - [28/Jun/2022 23:41:57] "GET /api/cibil?reference_number=202201121116395000000&los_id=MW112233&cibil_type=2&action=1 HTTP/1.1" 500 -
2022-06-28 23:41:58,903 INFO : 127.0.0.1 - - [28/Jun/2022 23:41:58] "GET /api/cibil?__debugger__=yes&cmd=resource&f=style.css HTTP/1.1" 200 -
2022-06-28 23:41:58,951 INFO : 127.0.0.1 - - [28/Jun/2022 23:41:58] "GET /api/cibil?__debugger__=yes&cmd=resource&f=debugger.js HTTP/1.1" 200 -
2022-06-28 23:41:58,961 INFO : 127.0.0.1 - - [28/Jun/2022 23:41:58] "GET /api/cibil?__debugger__=yes&cmd=resource&f=jquery.js HTTP/1.1" 200 -
2022-06-28 23:41:59,416 INFO : 127.0.0.1 - - [28/Jun/2022 23:41:59] "GET /api/cibil?__debugger__=yes&cmd=resource&f=ubuntu.ttf HTTP/1.1" 200 -
2022-06-28 23:41:59,741 INFO : 127.0.0.1 - - [28/Jun/2022 23:41:59] "GET /api/cibil?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 -
2022-06-28 23:42:44,033 INFO : * Detected change in 'C:\\Users\\Venba\\AppData\\Local\\Programs\\Python\\pyenv\\flask_rest\\services\\CibilSummaryDataUpdateService.py', reloading
2022-06-28 23:42:44,229 INFO : * Restarting with stat
2022-06-28 23:42:47,000 WARNING : * Debugger is active!
2022-06-28 23:42:47,020 INFO : * Debugger PIN: 245-792-354
2022-06-28 23:42:47,038 INFO : * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

16
oldweb.config Normal file
View File

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<handlers>
<add name="Python" path="*.py" verb="*" modules="FastCgiModule" scriptProcessor="C:\Users\Venba\AppData\Local\Programs\Python\Python310\python.exe" resourceType="File" />
</handlers>
<rewrite>
<rules>
<rule name="ReverseProxyInboundRule2" stopProcessing="true">
<match url="(.*)" />
<action type="Rewrite" url="http://localhost:5000/{R:1}" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>

914
oldwfastcgi.py Normal file
View File

@ -0,0 +1,914 @@
# Python Tools for Visual Studio
# Copyright(c) Microsoft Corporation
# All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the License); you may not use
# this file except in compliance with the License. You may obtain a copy of the
# License at http://www.apache.org/licenses/LICENSE-2.0
#
# THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
# OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
# IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
# MERCHANTABLITY OR NON-INFRINGEMENT.
#
# See the Apache Version 2.0 License for specific language governing
# permissions and limitations under the License.
from __future__ import absolute_import, print_function, with_statement
__author__ = "Microsoft Corporation <ptvshelp@microsoft.com>"
__version__ = "3.0.0"
import ctypes
import datetime
import os
import re
import struct
import sys
import traceback
from xml.dom import minidom
try:
from cStringIO import StringIO
BytesIO = StringIO
except ImportError:
from io import StringIO, BytesIO
try:
from thread import start_new_thread
except ImportError:
from _thread import start_new_thread
if sys.version_info[0] == 3:
def to_str(value):
return value.decode(sys.getfilesystemencoding())
else:
def to_str(value):
return value.encode(sys.getfilesystemencoding())
# http://www.fastcgi.com/devkit/doc/fcgi-spec.html#S3
FCGI_VERSION_1 = 1
FCGI_HEADER_LEN = 8
FCGI_BEGIN_REQUEST = 1
FCGI_ABORT_REQUEST = 2
FCGI_END_REQUEST = 3
FCGI_PARAMS = 4
FCGI_STDIN = 5
FCGI_STDOUT = 6
FCGI_STDERR = 7
FCGI_DATA = 8
FCGI_GET_VALUES = 9
FCGI_GET_VALUES_RESULT = 10
FCGI_UNKNOWN_TYPE = 11
FCGI_MAXTYPE = FCGI_UNKNOWN_TYPE
FCGI_NULL_REQUEST_ID = 0
FCGI_KEEP_CONN = 1
FCGI_RESPONDER = 1
FCGI_AUTHORIZER = 2
FCGI_FILTER = 3
FCGI_REQUEST_COMPLETE = 0
FCGI_CANT_MPX_CONN = 1
FCGI_OVERLOADED = 2
FCGI_UNKNOWN_ROLE = 3
FCGI_MAX_CONNS = "FCGI_MAX_CONNS"
FCGI_MAX_REQS = "FCGI_MAX_REQS"
FCGI_MPXS_CONNS = "FCGI_MPXS_CONNS"
class FastCgiRecord(object):
"""Represents a FastCgiRecord. Encapulates the type, role, flags. Holds
onto the params which we will receive and update later."""
def __init__(self, type, req_id, role, flags):
self.type = type
self.req_id = req_id
self.role = role
self.flags = flags
self.params = {}
def __repr__(self):
return '<FastCgiRecord(%d, %d, %d, %d)>' % (self.type,
self.req_id,
self.role,
self.flags)
#typedef struct {
# unsigned char version;
# unsigned char type;
# unsigned char requestIdB1;
# unsigned char requestIdB0;
# unsigned char contentLengthB1;
# unsigned char contentLengthB0;
# unsigned char paddingLength;
# unsigned char reserved;
# unsigned char contentData[contentLength];
# unsigned char paddingData[paddingLength];
#} FCGI_Record;
class _ExitException(Exception):
pass
if sys.version_info[0] >= 3:
# indexing into byte strings gives us an int, so
# ord is unnecessary on Python 3
def ord(x):
return x
def chr(x):
return bytes((x, ))
def wsgi_decode(x):
return x.decode('iso-8859-1')
def wsgi_encode(x):
return x.encode('iso-8859-1')
def fs_encode(x):
return x
def exception_with_traceback(exc_value, exc_tb):
return exc_value.with_traceback(exc_tb)
zero_bytes = bytes
else:
# Replace the builtin open with one that supports an encoding parameter
from codecs import open
def wsgi_decode(x):
return x
def wsgi_encode(x):
return x
def fs_encode(x):
return x if isinstance(x, str) else x.encode(sys.getfilesystemencoding())
def exception_with_traceback(exc_value, exc_tb):
# x.with_traceback() is not supported on 2.x
return exc_value
bytes = str
def zero_bytes(length):
return '\x00' * length
def read_fastcgi_record(stream):
"""reads the main fast cgi record"""
data = stream.read(8) # read record
if not data:
# no more data, our other process must have died...
raise _ExitException()
fcgi_ver, reqtype, req_id, content_size, padding_len, _ = struct.unpack('>BBHHBB', data)
content = stream.read(content_size) # read content
stream.read(padding_len)
if fcgi_ver != FCGI_VERSION_1:
raise Exception('Unknown fastcgi version %s' % fcgi_ver)
processor = REQUEST_PROCESSORS.get(reqtype)
if processor is not None:
return processor(stream, req_id, content)
# unknown type requested, send response
log('Unknown request type %s' % reqtype)
send_response(stream, req_id, FCGI_UNKNOWN_TYPE, chr(reqtype) + zero_bytes(7))
return None
def read_fastcgi_begin_request(stream, req_id, content):
"""reads the begin request body and updates our _REQUESTS table to include
the new request"""
# typedef struct {
# unsigned char roleB1;
# unsigned char roleB0;
# unsigned char flags;
# unsigned char reserved[5];
# } FCGI_BeginRequestBody;
# TODO: Ignore request if it exists
res = FastCgiRecord(
FCGI_BEGIN_REQUEST,
req_id,
(ord(content[0]) << 8) | ord(content[1]), # role
ord(content[2]), # flags
)
_REQUESTS[req_id] = res
def read_encoded_int(content, offset):
i = struct.unpack_from('>B', content, offset)[0]
if i < 0x80:
return offset + 1, i
return offset + 4, struct.unpack_from('>I', content, offset)[0] & ~0x80000000
def read_fastcgi_keyvalue_pairs(content, offset):
"""Reads a FastCGI key/value pair stream"""
offset, name_len = read_encoded_int(content, offset)
offset, value_len = read_encoded_int(content, offset)
name = content[offset:(offset + name_len)]
offset += name_len
value = content[offset:(offset + value_len)]
offset += value_len
return offset, name, value
def get_encoded_int(i):
"""Writes the length of a single name for a key or value in a key/value
stream"""
if i <= 0x7f:
return struct.pack('>B', i)
elif i < 0x80000000:
return struct.pack('>I', i | 0x80000000)
else:
raise ValueError('cannot encode value %s (%x) because it is too large' % (i, i))
def write_fastcgi_keyvalue_pairs(pairs):
"""Creates a FastCGI key/value stream and returns it as a byte string"""
parts = []
for raw_key, raw_value in pairs.items():
key = wsgi_encode(raw_key)
value = wsgi_encode(raw_value)
parts.append(get_encoded_int(len(key)))
parts.append(get_encoded_int(len(value)))
parts.append(key)
parts.append(value)
return bytes().join(parts)
# Keys in this set will be stored in the record without modification but with a
# 'wsgi.' prefix. The original key will have the decoded version.
# (Following mod_wsgi from http://wsgi.readthedocs.org/en/latest/python3.html)
RAW_VALUE_NAMES = {
'SCRIPT_NAME' : 'wsgi.script_name',
'PATH_INFO' : 'wsgi.path_info',
'QUERY_STRING' : 'wsgi.query_string',
'HTTP_X_ORIGINAL_URL' : 'wfastcgi.http_x_original_url',
}
def read_fastcgi_params(stream, req_id, content):
if not content:
return None
offset = 0
res = _REQUESTS[req_id].params
while offset < len(content):
offset, name, value = read_fastcgi_keyvalue_pairs(content, offset)
name = wsgi_decode(name)
raw_name = RAW_VALUE_NAMES.get(name)
if raw_name:
res[raw_name] = value
res[name] = wsgi_decode(value)
def read_fastcgi_input(stream, req_id, content):
"""reads FastCGI std-in and stores it in wsgi.input passed in the
wsgi environment array"""
res = _REQUESTS[req_id].params
if 'wsgi.input' not in res:
res['wsgi.input'] = content
else:
res['wsgi.input'] += content
if not content:
# we've hit the end of the input stream, time to process input...
return _REQUESTS[req_id]
def read_fastcgi_data(stream, req_id, content):
"""reads FastCGI data stream and publishes it as wsgi.data"""
res = _REQUESTS[req_id].params
if 'wsgi.data' not in res:
res['wsgi.data'] = content
else:
res['wsgi.data'] += content
def read_fastcgi_abort_request(stream, req_id, content):
"""reads the wsgi abort request, which we ignore, we'll send the
finish execution request anyway..."""
pass
def read_fastcgi_get_values(stream, req_id, content):
"""reads the fastcgi request to get parameter values, and immediately
responds"""
offset = 0
request = {}
while offset < len(content):
offset, name, value = read_fastcgi_keyvalue_pairs(content, offset)
request[name] = value
response = {}
if FCGI_MAX_CONNS in request:
response[FCGI_MAX_CONNS] = '1'
if FCGI_MAX_REQS in request:
response[FCGI_MAX_REQS] = '1'
if FCGI_MPXS_CONNS in request:
response[FCGI_MPXS_CONNS] = '0'
send_response(
stream,
req_id,
FCGI_GET_VALUES_RESULT,
write_fastcgi_keyvalue_pairs(response)
)
# Our request processors for different FastCGI protocol requests. Only those
# requests that we receive are defined here.
REQUEST_PROCESSORS = {
FCGI_BEGIN_REQUEST : read_fastcgi_begin_request,
FCGI_ABORT_REQUEST : read_fastcgi_abort_request,
FCGI_PARAMS : read_fastcgi_params,
FCGI_STDIN : read_fastcgi_input,
FCGI_DATA : read_fastcgi_data,
FCGI_GET_VALUES : read_fastcgi_get_values
}
APPINSIGHT_CLIENT = None
def log(txt):
"""Logs messages to a log file if WSGI_LOG env var is defined."""
if APPINSIGHT_CLIENT:
try:
APPINSIGHT_CLIENT.track_event(txt)
except:
pass
log_file = os.environ.get('WSGI_LOG')
if log_file:
with open(log_file, 'a+', encoding='utf-8') as f:
txt = txt.replace('\r\n', '\n')
f.write('%s: %s%s' % (datetime.datetime.now(), txt, '' if txt.endswith('\n') else '\n'))
def maybe_log(txt):
"""Logs messages to a log file if WSGI_LOG env var is defined, and does not
raise exceptions if logging fails."""
try:
log(txt)
except:
pass
def send_response(stream, req_id, resp_type, content, streaming=True):
"""sends a response w/ the given id, type, and content to the server.
If the content is streaming then an empty record is sent at the end to
terminate the stream"""
if not isinstance(content, bytes):
raise TypeError("content must be encoded before sending: %r" % content)
offset = 0
while True:
len_remaining = max(min(len(content) - offset, 0xFFFF), 0)
data = struct.pack(
'>BBHHBB',
FCGI_VERSION_1, # version
resp_type, # type
req_id, # requestIdB1:B0
len_remaining, # contentLengthB1:B0
0, # paddingLength
0, # reserved
) + content[offset:(offset + len_remaining)]
offset += len_remaining
os.write(stream.fileno(), data)
if len_remaining == 0 or not streaming:
break
stream.flush()
def get_environment(dir):
web_config = os.path.join(dir, 'Web.config')
if not os.path.exists(web_config):
return {}
d = {}
doc = minidom.parse(web_config)
config = doc.getElementsByTagName('configuration')
for configSection in config:
appSettings = configSection.getElementsByTagName('appSettings')
for appSettingsSection in appSettings:
values = appSettingsSection.getElementsByTagName('add')
for curAdd in values:
key = curAdd.getAttribute('key')
value = curAdd.getAttribute('value')
if key and value is not None:
d[key.strip()] = value
return d
ReadDirectoryChangesW = ctypes.windll.kernel32.ReadDirectoryChangesW
ReadDirectoryChangesW.restype = ctypes.c_uint32
ReadDirectoryChangesW.argtypes = [
ctypes.c_void_p, # HANDLE hDirectory
ctypes.c_void_p, # LPVOID lpBuffer
ctypes.c_uint32, # DWORD nBufferLength
ctypes.c_uint32, # BOOL bWatchSubtree
ctypes.c_uint32, # DWORD dwNotifyFilter
ctypes.POINTER(ctypes.c_uint32), # LPDWORD lpBytesReturned
ctypes.c_void_p, # LPOVERLAPPED lpOverlapped
ctypes.c_void_p # LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
]
try:
from _winapi import (CreateFile, CloseHandle, GetLastError, ExitProcess,
WaitForSingleObject, INFINITE, OPEN_EXISTING)
except ImportError:
CreateFile = ctypes.windll.kernel32.CreateFileW
CreateFile.restype = ctypes.c_void_p
CreateFile.argtypes = [
ctypes.c_wchar_p, # lpFilename
ctypes.c_uint32, # dwDesiredAccess
ctypes.c_uint32, # dwShareMode
ctypes.c_void_p, # LPSECURITY_ATTRIBUTES,
ctypes.c_uint32, # dwCreationDisposition,
ctypes.c_uint32, # dwFlagsAndAttributes,
ctypes.c_void_p # hTemplateFile
]
CloseHandle = ctypes.windll.kernel32.CloseHandle
CloseHandle.argtypes = [ctypes.c_void_p]
GetLastError = ctypes.windll.kernel32.GetLastError
GetLastError.restype = ctypes.c_uint32
ExitProcess = ctypes.windll.kernel32.ExitProcess
ExitProcess.restype = ctypes.c_void_p
ExitProcess.argtypes = [ctypes.c_uint32]
WaitForSingleObject = ctypes.windll.kernel32.WaitForSingleObject
WaitForSingleObject.argtypes = [ctypes.c_void_p, ctypes.c_uint32]
WaitForSingleObject.restype = ctypes.c_uint32
OPEN_EXISTING = 3
INFINITE = -1
FILE_LIST_DIRECTORY = 1
FILE_SHARE_READ = 0x00000001
FILE_SHARE_WRITE = 0x00000002
FILE_SHARE_DELETE = 0x00000004
FILE_FLAG_BACKUP_SEMANTICS = 0x02000000
MAX_PATH = 260
FILE_NOTIFY_CHANGE_LAST_WRITE = 0x10
ERROR_NOTIFY_ENUM_DIR = 1022
INVALID_HANDLE_VALUE = 0xFFFFFFFF
class FILE_NOTIFY_INFORMATION(ctypes.Structure):
_fields_ = [('NextEntryOffset', ctypes.c_uint32),
('Action', ctypes.c_uint32),
('FileNameLength', ctypes.c_uint32),
('Filename', ctypes.c_wchar)]
_ON_EXIT_TASKS = None
def run_exit_tasks():
global _ON_EXIT_TASKS
maybe_log("Running on_exit tasks")
while _ON_EXIT_TASKS:
tasks, _ON_EXIT_TASKS = _ON_EXIT_TASKS, []
for t in tasks:
try:
t()
except Exception:
maybe_log("Error in exit task: " + traceback.format_exc())
def on_exit(task):
global _ON_EXIT_TASKS
if _ON_EXIT_TASKS is None:
_ON_EXIT_TASKS = tasks = []
try:
evt = int(os.getenv('_FCGI_SHUTDOWN_EVENT_'))
except (TypeError, ValueError):
maybe_log("Could not wait on event %s" % os.getenv('_FCGI_SHUTDOWN_EVENT_'))
else:
def _wait_for_exit():
WaitForSingleObject(evt, INFINITE)
run_exit_tasks()
ExitProcess(0)
start_new_thread(_wait_for_exit, ())
_ON_EXIT_TASKS.append(task)
def start_file_watcher(path, restart_regex):
if restart_regex is None:
restart_regex = ".*((\\.py)|(\\.config))$"
elif not restart_regex:
# restart regex set to empty string, no restart behavior
return
def enum_changes(path):
"""Returns a generator that blocks until a change occurs, then yields
the filename of the changed file.
Yields an empty string and stops if the buffer overruns, indicating that
too many files were changed."""
buffer = ctypes.create_string_buffer(32 * 1024)
bytes_ret = ctypes.c_uint32()
try:
the_dir = CreateFile(
path,
FILE_LIST_DIRECTORY,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
0,
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS,
0,
)
except OSError:
maybe_log("Unable to create watcher")
return
if not the_dir or the_dir == INVALID_HANDLE_VALUE:
maybe_log("Unable to create watcher")
return
while True:
ret_code = ReadDirectoryChangesW(
the_dir,
buffer,
ctypes.sizeof(buffer),
True,
FILE_NOTIFY_CHANGE_LAST_WRITE,
ctypes.byref(bytes_ret),
None,
None,
)
if ret_code:
cur_pointer = ctypes.addressof(buffer)
while True:
fni = ctypes.cast(cur_pointer, ctypes.POINTER(FILE_NOTIFY_INFORMATION))
# FileName is not null-terminated, so specifying length is mandatory.
filename = ctypes.wstring_at(cur_pointer + 12, fni.contents.FileNameLength // 2)
yield filename
if fni.contents.NextEntryOffset == 0:
break
cur_pointer = cur_pointer + fni.contents.NextEntryOffset
elif GetLastError() == ERROR_NOTIFY_ENUM_DIR:
CloseHandle(the_dir)
yield ''
return
else:
CloseHandle(the_dir)
return
log('wfastcgi.py will restart when files in %s are changed: %s' % (path, restart_regex))
def watcher(path, restart):
for filename in enum_changes(path):
if not filename:
log('wfastcgi.py exiting because the buffer was full')
run_exit_tasks()
ExitProcess(0)
elif restart.match(filename):
log('wfastcgi.py exiting because %s has changed, matching %s' % (filename, restart_regex))
# we call ExitProcess directly to quickly shutdown the whole process
# because sys.exit(0) won't have an effect on the main thread.
run_exit_tasks()
ExitProcess(0)
restart = re.compile(restart_regex)
start_new_thread(watcher, (path, restart))
def get_wsgi_handler(handler_name):
if not handler_name:
raise Exception('WSGI_HANDLER env var must be set')
if not isinstance(handler_name, str):
handler_name = to_str(handler_name)
module_name, _, callable_name = handler_name.rpartition('.')
should_call = callable_name.endswith('()')
callable_name = callable_name[:-2] if should_call else callable_name
name_list = [(callable_name, should_call)]
handler = None
last_tb = ''
while module_name:
try:
handler = __import__(module_name, fromlist=[name_list[0][0]])
last_tb = ''
for name, should_call in name_list:
handler = getattr(handler, name)
if should_call:
handler = handler()
break
except ImportError:
module_name, _, callable_name = module_name.rpartition('.')
should_call = callable_name.endswith('()')
callable_name = callable_name[:-2] if should_call else callable_name
name_list.insert(0, (callable_name, should_call))
handler = None
last_tb = ': ' + traceback.format_exc()
if handler is None:
raise ValueError('"%s" could not be imported%s' % (handler_name, last_tb))
return handler
def read_wsgi_handler(physical_path):
global APPINSIGHT_CLIENT
env = get_environment(physical_path)
os.environ.update(env)
for path in (v for k, v in env.items() if k.lower() == 'pythonpath'):
# Expand environment variables manually.
expanded_path = re.sub(
'%(\\w+?)%',
lambda m: os.getenv(m.group(1), ''),
path
)
sys.path.extend(fs_encode(p) for p in expanded_path.split(';') if p)
handler = get_wsgi_handler(os.getenv("WSGI_HANDLER"))
instr_key = os.getenv("APPINSIGHTS_INSTRUMENTATIONKEY")
if instr_key:
try:
# Attempt the import after updating sys.path - sites must
# include applicationinsights themselves.
from applicationinsights.requests import WSGIApplication
except ImportError:
maybe_log("Failed to import applicationinsights: " + traceback.format_exc())
else:
handler = WSGIApplication(instr_key, handler)
APPINSIGHT_CLIENT = handler.client
# Ensure we will flush any remaining events when we exit
on_exit(handler.client.flush)
return env, handler
class handle_response(object):
"""A context manager for handling the response. This will ensure that
exceptions in the handler are correctly reported, and the FastCGI request is
properly terminated.
"""
def __init__(self, stream, record, get_output, get_errors):
self.stream = stream
self.record = record
self._get_output = get_output
self._get_errors = get_errors
self.error_message = ''
self.fatal_errors = False
self.physical_path = ''
self.header_bytes = None
self.sent_headers = False
def __enter__(self):
record = self.record
record.params['wsgi.input'] = BytesIO(record.params['wsgi.input'])
record.params['wsgi.version'] = (1, 0)
record.params['wsgi.url_scheme'] = 'https' if record.params.get('HTTPS', '').lower() == 'on' else 'http'
record.params['wsgi.multiprocess'] = True
record.params['wsgi.multithread'] = False
record.params['wsgi.run_once'] = False
self.physical_path = record.params.get('APPL_PHYSICAL_PATH', os.path.dirname(__file__))
if 'HTTP_X_ORIGINAL_URL' in record.params:
# We've been re-written for shared FastCGI hosting, so send the
# original URL as PATH_INFO.
record.params['PATH_INFO'] = record.params['HTTP_X_ORIGINAL_URL']
record.params['wsgi.path_info'] = record.params['wfastcgi.http_x_original_url']
# PATH_INFO is not supposed to include the query parameters, so remove them
record.params['PATH_INFO'] = record.params['PATH_INFO'].partition('?')[0]
record.params['wsgi.path_info'] = record.params['wsgi.path_info'].partition(wsgi_encode('?'))[0]
return self
def __exit__(self, exc_type, exc_value, exc_tb):
# Send any error message on FCGI_STDERR.
if exc_type and exc_type is not _ExitException:
error_msg = "%s:\n\n%s\n\nStdOut: %s\n\nStdErr: %s" % (
self.error_message or 'Error occurred',
''.join(traceback.format_exception(exc_type, exc_value, exc_tb)),
self._get_output(),
self._get_errors(),
)
if not self.header_bytes or not self.sent_headers:
self.header_bytes = wsgi_encode('Status: 500 Internal Server Error\r\n')
self.send(FCGI_STDERR, wsgi_encode(error_msg))
# Best effort at writing to the log. It's more important to
# finish the response or the user will only see a generic 500
# error.
maybe_log(error_msg)
# End the request. This has to run in both success and failure cases.
self.send(FCGI_END_REQUEST, zero_bytes(8), streaming=False)
# Remove the request from our global dict
del _REQUESTS[self.record.req_id]
# Suppress all exceptions unless requested
return not self.fatal_errors
@staticmethod
def _decode_header(key, value):
if not isinstance(key, str):
key = wsgi_decode(key)
if not isinstance(value, str):
value = wsgi_decode(value)
return key, value
def start(self, status, headers, exc_info=None):
"""Starts sending the response. The response is ended when the context
manager exits."""
if exc_info:
try:
if self.sent_headers:
# We have to re-raise if we've already started sending data.
raise exception_with_traceback(exc_info[1], exc_info[2])
finally:
exc_info = None
elif self.header_bytes:
raise Exception('start_response has already been called')
if not isinstance(status, str):
status = wsgi_decode(status)
header_text = 'Status: %s\r\n' % status
if headers:
header_text += ''.join('%s: %s\r\n' % handle_response._decode_header(*i) for i in headers)
self.header_bytes = wsgi_encode(header_text + '\r\n')
return lambda content: self.send(FCGI_STDOUT, content)
def send(self, resp_type, content, streaming=True):
'''Sends part of the response.'''
if not self.sent_headers:
if not self.header_bytes:
raise Exception("start_response has not yet been called")
self.sent_headers = True
send_response(self.stream, self.record.req_id, FCGI_STDOUT, self.header_bytes)
self.header_bytes = None
return send_response(self.stream, self.record.req_id, resp_type, content, streaming)
_REQUESTS = {}
def main():
initialized = False
log('wfastcgi.py %s started' % __version__)
log('Python version: %s' % sys.version)
try:
fcgi_stream = sys.stdin.detach() if sys.version_info[0] >= 3 else sys.stdin
try:
import msvcrt
msvcrt.setmode(fcgi_stream.fileno(), os.O_BINARY)
except ImportError:
pass
while True:
record = read_fastcgi_record(fcgi_stream)
if not record:
continue
errors = sys.stderr = sys.__stderr__ = record.params['wsgi.errors'] = StringIO()
output = sys.stdout = sys.__stdout__ = StringIO()
with handle_response(fcgi_stream, record, output.getvalue, errors.getvalue) as response:
if not initialized:
log('wfastcgi.py %s initializing' % __version__)
os.chdir(response.physical_path)
sys.path[0] = '.'
# Initialization errors should be treated as fatal.
response.fatal_errors = True
response.error_message = 'Error occurred while reading WSGI handler'
env, handler = read_wsgi_handler(response.physical_path)
response.error_message = 'Error occurred starting file watcher'
start_file_watcher(response.physical_path, env.get('WSGI_RESTART_FILE_REGEX'))
# Enable debugging if possible. Default to local-only, but
# allow a web.config to override where we listen
ptvsd_secret = env.get('WSGI_PTVSD_SECRET')
if ptvsd_secret:
ptvsd_address = (env.get('WSGI_PTVSD_ADDRESS') or 'localhost:5678').split(':', 2)
try:
ptvsd_port = int(ptvsd_address[1])
except LookupError:
ptvsd_port = 5678
except ValueError:
log('"%s" is not a valid port number for debugging' % ptvsd_address[1])
ptvsd_port = 0
if ptvsd_address[0] and ptvsd_port:
try:
import ptvsd
except ImportError:
log('unable to import ptvsd to enable debugging')
else:
addr = ptvsd_address[0], ptvsd_port
ptvsd.enable_attach(secret=ptvsd_secret, address=addr)
log('debugging enabled on %s:%s' % addr)
response.error_message = ''
response.fatal_errors = False
log('wfastcgi.py %s initialized' % __version__)
initialized = True
os.environ.update(env)
# SCRIPT_NAME + PATH_INFO is supposed to be the full path
# (http://www.python.org/dev/peps/pep-0333/) but by default
# (http://msdn.microsoft.com/en-us/library/ms525840(v=vs.90).aspx)
# IIS is sending us the full URL in PATH_INFO, so we need to
# clear the script name here
if 'AllowPathInfoForScriptMappings' not in os.environ:
record.params['SCRIPT_NAME'] = ''
record.params['wsgi.script_name'] = wsgi_encode('')
# correct SCRIPT_NAME and PATH_INFO if we are told what our SCRIPT_NAME should be
if 'SCRIPT_NAME' in os.environ and record.params['PATH_INFO'].lower().startswith(os.environ['SCRIPT_NAME'].lower()):
record.params['SCRIPT_NAME'] = os.environ['SCRIPT_NAME']
record.params['PATH_INFO'] = record.params['PATH_INFO'][len(record.params['SCRIPT_NAME']):]
record.params['wsgi.script_name'] = wsgi_encode(record.params['SCRIPT_NAME'])
record.params['wsgi.path_info'] = wsgi_encode(record.params['PATH_INFO'])
# Send each part of the response to FCGI_STDOUT.
# Exceptions raised in the handler will be logged by the context
# manager and we will then wait for the next record.
result = handler(record.params, response.start)
try:
for part in result:
if part:
response.send(FCGI_STDOUT, part)
finally:
if hasattr(result, 'close'):
result.close()
except _ExitException:
pass
except Exception:
maybe_log('Unhandled exception in wfastcgi.py: ' + traceback.format_exc())
except BaseException:
maybe_log('Unhandled exception in wfastcgi.py: ' + traceback.format_exc())
raise
finally:
run_exit_tasks()
maybe_log('wfastcgi.py %s closed' % __version__)
def _run_appcmd(args):
from subprocess import check_call, CalledProcessError
if len(sys.argv) > 1 and os.path.isfile(sys.argv[1]):
appcmd = sys.argv[1:]
else:
appcmd = [os.path.join(os.getenv('SystemRoot'), 'system32', 'inetsrv', 'appcmd.exe')]
if not os.path.isfile(appcmd[0]):
print('IIS configuration tool appcmd.exe was not found at', appcmd, file=sys.stderr)
return -1
args = appcmd + args
try:
return check_call(args)
except CalledProcessError as ex:
print('''An error occurred running the command:
%r
Ensure your user has sufficient privileges and try again.''' % args, file=sys.stderr)
return ex.returncode
def enable():
executable = '"' + sys.executable + '"' if ' ' in sys.executable else sys.executable
quoted_file = '"' + __file__ + '"' if ' ' in __file__ else __file__
res = _run_appcmd([
"set", "config", "/section:system.webServer/fastCGI",
"/+[fullPath='" + executable + "', arguments='" + quoted_file + "', signalBeforeTerminateSeconds='30']"
])
if res == 0:
print('"%s|%s" can now be used as a FastCGI script processor' % (executable, quoted_file))
return res
def disable():
executable = '"' + sys.executable + '"' if ' ' in sys.executable else sys.executable
quoted_file = '"' + __file__ + '"' if ' ' in __file__ else __file__
res = _run_appcmd([
"set", "config", "/section:system.webServer/fastCGI",
"/-[fullPath='" + executable + "', arguments='" + quoted_file + "', signalBeforeTerminateSeconds='30']"
])
if res == 0:
print('"%s|%s" is no longer registered for use with FastCGI' % (executable, quoted_file))
return res
if __name__ == '__main__':
main()

13
r.txt Normal file
View File

@ -0,0 +1,13 @@
aniso8601==9.0.1
click==8.0.4
colorama==0.4.4
Flask==2.0.3
# Editable install with no version control (Flask-RESTful==0.3.9)
-e c:\users\venba\appdata\local\programs\python\pyenv\p10\lib\site-packages
itsdangerous==2.1.2
Jinja2==3.1.0
MarkupSafe==2.1.1
pypyodbc==1.3.6
pytz==2022.1
six==1.16.0
Werkzeug==2.0.3

8
routes.py Normal file
View File

@ -0,0 +1,8 @@
from Controllers.WorkingController import WorkingController
from Controllers.CIBILController import CIBIL
def initialize_routes(api):
api.add_resource(WorkingController, '/api/component','/api/component/<int:id>')
api.add_resource(CIBIL, '/api/cibil')
# api.add_resource(WorkingController, '/api/component/<int:id>')
# api.add_resource(MovieApi, '/movies/<id>')

View File

@ -0,0 +1,439 @@
from flask import current_app as my_app
import pandas as pd
import re,copy
import logging
from datetime import datetime
from time import time
# from .CibilMasterDataService import CibilMasterDataService
from .SampleDataProviderService import SampleDataProviderService
from .DpdCalculationService import DpdCalculationService
from .CibilSummaryDataUpdateService import CibilSummaryDataUpdateService
from .CibilDataService import CibilDataService
from Models.op_rtr_summary_of_active_loans import Out_active_and_closed_loans_details
class CibilBusinessOperationService:
# start making summary of single member/applicant's credit bureau summary
# report by @param : member_reference_number
#to store master data like configured bucket details
# dpd_month_bucket_master = []
# sanction_summary_month_buckets = []
# enquiry_summary_month_buckets = []
# #data generating using masters synamic bucket skeletons/headers
# sanction_summary_skeleton = {}
# enquiry_summary_skeleton = {}
# #for hold all summary reports
# unique_credit_facility_summary = {'total_count':0,'overdue_count':0,'zero_bal_count':0,'nil_overdue':0,'adv_high_credit':0,'current_balance':0,'overdue_balance':0,'date_latest_opened': '','date_oldest_opened': ''}
# live_and_closed_account_summary = []
# sanctioned_amt_details_summary = {}
# enquiry_amt_details_summary = {}
#http://127.0.0.1:5000/api/cibil?reference_number=202201121116395000000&los_id=MW112233&cibil_type=1&action=1
def doCIBILActiveCloseLoansSummary(los_id,reference_number,cibil_type):
# raise Exception('manual stop')
logText = 'doCIBILActiveCloseLoansSummary - LOSID - '+los_id+', '+'REFNO - '+reference_number+', '+'CTYPE - '+cibil_type+' '
my_app.logger.info(logText)
print('doCIBILActiveCloseLoansSummary - ',logText)
# logger = logging.getLogger('cibil.sub')
# logger.info(logText)
# return True
live_and_closed_account_summary = []
credit_facility_details = CibilDataService.getCreditFacilityDetails(reference_number,los_id,cibil_type)
logText = 'TOTAL CREDIT FACILITY - ' + str(len(credit_facility_details)) + ' FOUND'
my_app.logger.info(logText)
print(logText)
dpd_details = CibilDataService.getDPDDetails(reference_number,los_id,cibil_type)
# return dpd_details
borrower_details = CibilDataService.getBorrowerDetails(reference_number,los_id,cibil_type)
# cibil_raw_data = SampleDataProviderService.getCIBILRawData(reference_number=member_reference_number,type=1)
dpd_month_bucket_master = CibilDataService.getMonthBucketMaster('DPD'
) # raise Exception('manual stop')
# start
if len(credit_facility_details) > 0:
# print('####LOGIC STARTED#######')
# over_start_time = time()
for idx,row in enumerate(credit_facility_details):
# if row['AccountTranDetailsID'] == '388857':
# print('#########################BREAK')
# break
CustomerName1 = "" if borrower_details[0]['ConsumerNameField1'] == None else borrower_details[0]['ConsumerNameField1'].strip()
CustomerName2 = "" if borrower_details[0]['ConsumerNameField2'] == None else borrower_details[0]['ConsumerNameField2'].strip()
CustomerName = CustomerName1+' '+CustomerName2
GroupString = row['grp_str']
AccountType = row['AccountType'].strip()
ReportedandCertifiedDate = row['DateReportedAndCertified']
OpendDate = (row['DateOpenedDisbursed']) if row['DateOpenedDisbursed'] != "" and row['DateOpenedDisbursed'] != None and row['DateOpenedDisbursed'] != 'None' else None
DateClosed = (row['DateClosed']) if row['DateClosed'] != "" and row['DateClosed'] != None and row['DateClosed'] != 'None' else None
SanctionedAmount = (row['HighCreditSanctionedAmount']) if row['HighCreditSanctionedAmount'] != "" and row['HighCreditSanctionedAmount'] != None and row['HighCreditSanctionedAmount'] != 'None' else 0
CurrentBalance = (row['CurrentBalance']) if row['CurrentBalance'] != "" and row['CurrentBalance'] != None and row['CurrentBalance'] != 'None' else 0
EMIAmount = (row['EMIAmount']) if row['EMIAmount'] != "" and row['EMIAmount'] != None and row['EMIAmount'] != 'None' else 0
OverdueAmount = (row['AmountOverdue']) if row['AmountOverdue'] != "" and row['AmountOverdue'] != None and row['AmountOverdue'] != 'None' else 0
RepaymentTenure = (int(float(row['RepaymentTenure']))) if row['RepaymentTenure'] != "" and row['RepaymentTenure'] != None and row['RepaymentTenure'] != 'None' else 0
Status = row['WrittenOffAndSettledStatus'].strip()
Ownership = row['OwnershipIndicator'].strip()
Ownership = "I" if Ownership == "Individual" else "J" if Ownership == "Joint" else "AU" if re.search("Authorised User", Ownership) else "G" if Ownership == "Guarantor" else Ownership
if AccountType == 'Credit Card':
SanctionedAmount = (row['CreditLimit']) if row['CreditLimit'] != "" and row['CreditLimit'] != None and row['CreditLimit'] != 'None' else 0
#unique credit facility function call , if current credit facility is J and G #currently ot in use
# if Own == "J" or Own == "G":
#CibilBusinessOperationService.getUniqueCreditFacilitySummary(row)
#DPD logic start
dpd_result = DpdCalculationService.dpdCalculation(row['AccountTranDetailsID'],dpd_details,dpd_month_bucket_master)
CurrentDPD = dpd_result['currentDPD']
DPD0_6 = dpd_result['DPD0_6']
DPD7_12 = dpd_result['DPD7_12']
DPD13_24 = dpd_result['DPD13_24']
DPD25_36 = dpd_result['DPD25_36']
# LatestDPD = 0
# DPD0_6 = 0
# DPD7_12 = 0
# DPD13_24 = 0
# DPD25_36 = 0
# temp = {"CustomerName":CustomerName,"AccountType":AccountType,"SanctionedDate":SanctionedDate,"SanctionedAmount":SanctionedAmount,"CurrentBalance":CurrentBalance,"EMIAmount":EMIAmount,"Overdue":Overdue,"Tenure":Tenure,"Own":Own,"LatestDPD":LatestDPD,'DPD0_6':DPD0_6,'DPD7_12':DPD7_12,'DPD13_24':DPD13_24,'DPD25_36':DPD25_36}
temp = Out_active_and_closed_loans_details(losid=los_id,ref_no=reference_number,consumer_name=CustomerName,account_type=AccountType,reported_and_certified_date=ReportedandCertifiedDate,opened_date=OpendDate,DateClosed=DateClosed,sanctioned_amount=SanctionedAmount,current_balance=CurrentBalance,emi_amount=EMIAmount,overdue_amount=OverdueAmount,repayment_tenure=RepaymentTenure,status=Status,ownership=Ownership,current_dpd=CurrentDPD,highest_dpd_month_wise_bucket_or_count_0_to_6=DPD0_6,highest_dpd_month_wise_bucket_or_count_07_to_12=DPD7_12,highest_dpd_month_wise_bucket_or_count_13_to_24=DPD13_24,highest_dpd_month_wise_bucket_or_count_25_to_36=DPD25_36,is_active=1,createdAt=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),updatedAt=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),createdby=1,updatedby=1,grp_str=GroupString)
live_and_closed_account_summary.append(temp);
# start_time = time()
# print('idx',idx)
# print("--- %s seconds ---" %(time() - start_time))
##### All o/p data insertion startes here except open & closed ac summary. it gets inserted in above loop
logText = 'TOTAL ACTIVE&CLOSED LOANS - ' + str(len(live_and_closed_account_summary))
my_app.logger.info(logText)
print(logText)
res = CibilSummaryDataUpdateService.updateActiveOrClosedLoans(live_and_closed_account_summary)
logText = (res) +' INSERTED'
my_app.logger.info(logText)
print(logText)
##### End of All o/p data insertion startes here except open & closed ac summary. it gets inserted in above loop
# return live_and_closed_account_summary
# print("--- %s seconds overall ---" %(time() - over_start_time))
return True
# transform Sansactioned Amt table from transactions details
# def getSanctionedAmtDetails(accountTranDetails):
def doCIBILSanctionedLoansSummary(los_id,reference_number,cibil_type,output_type):
logText = 'doCIBILSanctionedLoansSummary - LOSID - '+los_id+', '+'REFNO - '+reference_number+', '+'CTYPE - '+cibil_type+', O/PTYPE - '+str(output_type)
my_app.logger.info(logText)
print(logText)
sanctioned_amt_details_summary = {}
credit_facility_details = []
month_bucket_master = CibilDataService.getMonthBucketMaster('SAN_SUM')#SAN_SUM = sanction summary bucket master
sanction_summary_skeleton = CibilBusinessOperationService.prepareSkeletons(month_bucket_master,type = 2)# 2 = sanction
if output_type == 1:credit_facility_details = CibilDataService.getCreditFacilityDetails(reference_number,los_id,cibil_type)
elif output_type == 2:credit_facility_details = CibilDataService.getUniqueCreditFacilityDetails(los_id)
# print(credit_facility_details)
# return(credit_facility_details)
logText = 'TOTAL '+ str(len(credit_facility_details))+' CREDIT FACILITIES FOUND'
my_app.logger.info(logText)
print(logText)
# print(month_bucket_master)
# print(sanction_summary_skeleton)
# print(credit_facility_details)
# raise Exception('doCIBILSanctionedLoansSummary')
total_enquiry_count_for_log = 0
for index,credit_facility_detail in enumerate(credit_facility_details):
creditFacility = credit_facility_detail['AccountType'].strip()
SanctionedDate = credit_facility_detail['DateOpenedDisbursed']
DateClosed = credit_facility_detail['DateClosed']
CurrentBalance = credit_facility_detail['CurrentBalance']
SanctionedAmount = credit_facility_detail['HighCreditSanctionedAmount']
if creditFacility == 'Credit Card':
SanctionedAmount = credit_facility_detail['CreditLimit']
# print((SanctionedAmount))
SanctionedAmount = float(SanctionedAmount) if SanctionedAmount != "" and SanctionedAmount != 'None' and SanctionedAmount != None else 0
# print('###Credit Card### - ', SanctionedAmount,SanctionedAmount.isnumeric())
month_bucket_index = credit_facility_detail['month_bucket_index']
# month = (datetime.strptime((SanctionedDate.split(" ")[0]), "%Y-%m-%d")).month if SanctionedDate != 'None' else 1
# month_bucket = '1' if month == 1 else '2-3' if month >= 2 and month <= 3 else '4-6' if month >=4 and month <= 6 else '7-12' if month >= 7 and month <= 12 else '13-24' if month >= 13 and month <= 24 else '25-36' if month >= 25 and month <= 36 else '>36' if month > 36 else 'None'
month_bucket = DpdCalculationService.dpdFindDaysBucket(month_bucket_master,month_bucket_index)
sanctioned_amt_detail = { 'creditFacility': creditFacility, 'SanctionedDate':SanctionedDate,'SanctionedAmount':SanctionedAmount,'monthBucket':month_bucket,'CurrentBalance':CurrentBalance, 'DateClosed' : DateClosed }
# print('mergeSanctionAmtDetails')
#check current credit facility exists in sanctioned_amt_details_summary
if sanctioned_amt_detail['creditFacility'] not in sanctioned_amt_details_summary.keys():
# print("FIRST TIME SKELETON ADDED-",sanctioned_amt_detail['creditFacility'],'-',sanctioned_amt_detail['monthBucket'],'-',sanctioned_amt_detail['SanctionedAmount'])
sanctioned_amt_details_summary[ sanctioned_amt_detail['creditFacility'] ] = copy.deepcopy(sanction_summary_skeleton)
# print("BEFORE ADDED***********",sanctioned_amt_detail['SanctionedAmount'],type(sanctioned_amt_detail['SanctionedAmount']),sanctioned_amt_detail['monthBucket'],(sanctioned_amt_detail['SanctionedAmount'] != "" and sanctioned_amt_detail['SanctionedAmount'] != None))
# print(sanctioned_amt_details_summary)
tempSanctionedAmount = float(sanctioned_amt_detail['SanctionedAmount'])
# if sanctioned_amt_detail['SanctionedAmount'].isnumeric()else 0
sanctioned_amt_details_summary[sanctioned_amt_detail['creditFacility']][sanctioned_amt_detail['monthBucket']]['amt'] += tempSanctionedAmount
sanctioned_amt_details_summary[sanctioned_amt_detail['creditFacility']][sanctioned_amt_detail['monthBucket']]['count'] += 1
sanctioned_amt_details_summary[sanctioned_amt_detail['creditFacility']]['total_amt'] += tempSanctionedAmount
sanctioned_amt_details_summary[sanctioned_amt_detail['creditFacility']]['total_count'] += 1
total_enquiry_count_for_log += 1
#for Amount & Count of open and closed accounts
if (sanctioned_amt_detail['DateClosed'] == None or sanctioned_amt_detail['DateClosed'] == "" or sanctioned_amt_detail['DateClosed'] == 'None'):
sanctioned_amt_details_summary[sanctioned_amt_detail['creditFacility']][sanctioned_amt_detail['monthBucket']]['openamt'] += tempSanctionedAmount
sanctioned_amt_details_summary[sanctioned_amt_detail['creditFacility']][sanctioned_amt_detail['monthBucket']]['opencount'] += 1
sanctioned_amt_details_summary[sanctioned_amt_detail['creditFacility']]['open_total_amt'] += tempSanctionedAmount
sanctioned_amt_details_summary[sanctioned_amt_detail['creditFacility']]['open_total_count'] += 1
else:
sanctioned_amt_details_summary[sanctioned_amt_detail['creditFacility']][sanctioned_amt_detail['monthBucket']]['closeamt'] += tempSanctionedAmount
sanctioned_amt_details_summary[sanctioned_amt_detail['creditFacility']][sanctioned_amt_detail['monthBucket']]['closecount'] += 1
sanctioned_amt_details_summary[sanctioned_amt_detail['creditFacility']]['closed_total_amt'] += tempSanctionedAmount
sanctioned_amt_details_summary[sanctioned_amt_detail['creditFacility']]['closed_total_count'] += 1
# print("AFTER ADDED***********")
# print(sanctioned_amt_details_summary[sanctioned_amt_detail['creditFacility']])
# print("")
# print("SKELTON-",sanction_summary_skeleton)
# print("")
logText = str(total_enquiry_count_for_log) +' CREDIT FACILITIES SUMMARIZED AS ' + str(len(sanctioned_amt_details_summary))
my_app.logger.info(logText)
print(logText)
res = CibilSummaryDataUpdateService.updateSanctionedSummaryAndOverallOpenedClosedLoans(sanctioned_amt_details_summary,reference_number,los_id,cibil_type,output_type)
logText = str(res) +' INSERTED'
my_app.logger.info(logText)
print(logText)
return sanctioned_amt_details_summary
def prepareSkeletons(month_buckets,type):
# print('prepareSkeletons')
return_skelton = {}
if type == 2: # sanction
for month_bucket in month_buckets:
return_skelton[month_bucket['name']] = {'amt':0,'count':0,'openamt':0,'opencount':0,'closeamt':0,'closecount':0}
return_skelton['total_amt'] = 0
return_skelton['total_count'] = 0
return_skelton['open_total_amt'] = 0
return_skelton['open_total_count'] = 0
return_skelton['closed_total_amt'] = 0
return_skelton['closed_total_count'] = 0
elif type == 1:#enquiry
for month_bucket in month_buckets:
return_skelton[month_bucket['name']] = {'amt':0,'count':0}
return_skelton['total_amt'] = 0
return_skelton['total_count'] = 0
# print(return_skelton)
return return_skelton
# def doCIBILEnquirySummary(enquiry_details, type):
def doCIBILEnquirySummary(los_id,reference_number,cibil_type,output_type):
logText = 'doCIBILEnquirySummary - LOSID - '+los_id+', '+'REFNO - '+reference_number+', '+'CTYPE - '+cibil_type+', O/P TYPE - '+str(output_type)
my_app.logger.info(logText)
print(logText)
enquiry_amt_details_summary = {}
enquiry_details = []
month_bucket_master = CibilDataService.getMonthBucketMaster('ENQ_SUM')#ENQ_SUM = enquiry summary bucket master
enquiry_skeleton = CibilBusinessOperationService.prepareSkeletons(month_bucket_master,type = 1)# 1 = enquiry
if output_type == 1 : enquiry_details = CibilDataService.getEnquriyDetails(reference_number,los_id,cibil_type)
elif output_type == 2 : enquiry_details = CibilDataService.getUniqueEnquriyDetails(los_id)
logText = 'TOTAL '+ str(len(enquiry_details))+' ENQURIES FOUND'
my_app.logger.info(logText)
print(logText)
# return enquiry_details
# print(month_bucket_master)
# print(enquiry_skeleton)
# print(enquiry_details)
# raise Exception('dssd')
total_enquiry_count_for_log = 0
#transform/filter raw consumer enquiry data to necessary data
for enquiry_detail in enquiry_details:
creditFacility = enquiry_detail['EnquiryPurpose'].strip()
SanctionedDate = enquiry_detail['DateOfEnquiry']
SanctionedAmount = float(enquiry_detail['EnquiryAmount'])
month_bucket_index = enquiry_detail['month_bucket_index']
# month = (datetime.strptime((SanctionedDate.split(" ")[0]), "%Y-%m-%d")).month
# month_bucket = '1' if month == 1 else '2-3' if month >= 2 and month <= 3 else '4-6' if month >=4 and month <= 6 else '7-12' if month >= 7 and month <= 12 else '13-24' if month >= 13 and month <= 24 else '25-36' if month >= 25 and month <= 36 else '>36' if month > 36 else 'None'
month_bucket = DpdCalculationService.dpdFindDaysBucket(month_bucket_master,month_bucket_index)
# print("")
# print("DATA - ",creditFacility,'-',SanctionedDate,'-',SanctionedAmount,'-',month,'-',month_bucket)
# print("")
#check current credit facility exists in enquiry_amt_details_summary
if creditFacility not in enquiry_amt_details_summary.keys():
# print("FIRST TIME SKELETON ADDED-")
enquiry_amt_details_summary[ creditFacility ] = copy.deepcopy(enquiry_skeleton)
# print("BEFORE ADDED***********")
# print(CibilBusinessOperationService.enquiry_amt_details_summary)
enquiry_amt_details_summary[creditFacility][month_bucket]['amt'] += SanctionedAmount
enquiry_amt_details_summary[creditFacility][month_bucket]['count'] += 1
enquiry_amt_details_summary[creditFacility]['total_count'] += 1
enquiry_amt_details_summary[creditFacility]['total_amt'] += SanctionedAmount
total_enquiry_count_for_log += 1
logText = str(total_enquiry_count_for_log) +' ENQURIES SUMMARIZED AS ' + str(len(enquiry_amt_details_summary))
my_app.logger.info(logText)
print(logText)
#update data
res = CibilSummaryDataUpdateService.updateEnquirySummaryData(enquiry_amt_details_summary,reference_number,los_id,cibil_type,output_type)
logText = str(res) +' INSERTED'
my_app.logger.info(logText)
print(logText)
return res
#not in use not in use not in use not in use
def getUniqueCreditFacilitySummary(creditFacility):
print('UniqueCreditFacilitySummary-',creditFacility['AmountOverdue'],creditFacility['CurrentBalance'],creditFacility['DateOpenedDisbursed'],type(creditFacility['CurrentBalance']))
CibilBusinessOperationService.unique_credit_facility_summary['total_count'] += 1
if creditFacility['AmountOverdue'] != 'None' :
CibilBusinessOperationService.unique_credit_facility_summary['overdue_count'] += 1
CibilBusinessOperationService.unique_credit_facility_summary['overdue_balance'] += float((creditFacility['AmountOverdue'])) if creditFacility['AmountOverdue'] != 'None' else 0
else:
CibilBusinessOperationService.unique_credit_facility_summary['nil_overdue'] +=1
if float(creditFacility['CurrentBalance']) == float(0) or creditFacility['CurrentBalance'] == "": CibilBusinessOperationService.unique_credit_facility_summary['zero_bal_count'] +=1
else: CibilBusinessOperationService.unique_credit_facility_summary['current_balance'] += float(creditFacility['CurrentBalance']) if creditFacility['CurrentBalance'] !='None' else 0
if CibilBusinessOperationService.unique_credit_facility_summary['date_latest_opened'] == "":
CibilBusinessOperationService.unique_credit_facility_summary['date_latest_opened'] = creditFacility['DateOpenedDisbursed'] if creditFacility['DateOpenedDisbursed'] != 'None' else ""
else:
CibilBusinessOperationService.unique_credit_facility_summary['date_latest_opened'] = creditFacility['DateOpenedDisbursed'] if CibilBusinessOperationService.unique_credit_facility_summary['date_latest_opened'] > creditFacility['DateOpenedDisbursed'] else CibilBusinessOperationService.unique_credit_facility_summary['date_latest_opened']
if CibilBusinessOperationService.unique_credit_facility_summary['date_oldest_opened'] == "":
CibilBusinessOperationService.unique_credit_facility_summary['date_oldest_opened'] = creditFacility['DateOpenedDisbursed'] if creditFacility['DateOpenedDisbursed'] != 'None' else ""
else:
CibilBusinessOperationService.unique_credit_facility_summary['date_oldest_opened'] = CibilBusinessOperationService.unique_credit_facility_summary['date_latest_opened'] if CibilBusinessOperationService.unique_credit_facility_summary['date_oldest_opened'] > creditFacility['DateOpenedDisbursed'] else creditFacility['DateOpenedDisbursed']
###################################END OF CONSUMER CIBIL BUSINESS SERVICE##################################################
###################################END OF CONSUMER CIBIL BUSINESS SERVICE##################################################
###################################END OF CONSUMER CIBIL BUSINESS SERVICE##################################################
###################################START OF COMMERCIAL CIBIL BUSINESS SERVICE#########################################
###################################START OF COMMERCIAL CIBIL BUSINESS SERVICE#########################################
###################################START OF COMMERCIAL CIBIL BUSINESS SERVICE#########################################
###################################NOT IN USE * NOT IN USE * NOT IN USE * NOT IN USE#########################################
#http://127.0.0.1:5000/api/cibil?application_reference_number=202201111930347000000
def doCommercialCIBILOperations(application_reference_number,los_id):
print('CommercialCIBILOperations')
cibil_raw_data = CibilMasterDataService.getCIBILRawData(reference_number=application_reference_number,los_id=los_id,type = 2)
# cibil_raw_data = SampleDataProviderService.getCIBILRawData(reference_number=application_reference_number,type = 2)
CibilBusinessOperationService.dpd_month_bucket_master = cibil_raw_data['masters']['dpd_month_buckets']
CibilBusinessOperationService.sanction_summary_month_buckets = cibil_raw_data['masters']['sanction_summary_month_buckets']
CibilBusinessOperationService.enquiry_summary_month_buckets = cibil_raw_data['masters']['enquiry_summary_month_buckets']
CibilBusinessOperationService.prepareSkeletons()
# print(cibil_raw_data['commercial_cibil_rawdata']['com_credit_facility_current_details'])
# raise Exception('asknalk')
# print(cibil_raw_data['commercial_cibil_rawdata']['com_dpd_details'])
CibilBusinessOperationService.prepareEnquirySummary(cibil_raw_data['commercial_cibil_rawdata']['com_enquiry_details'],type = 2)#2 = commercials
if len(cibil_raw_data['commercial_cibil_rawdata']['com_credit_facility_current_details']) > 0:
print('####COMMERCIAL LOGIC STARTED#######')
for idx,row in enumerate(cibil_raw_data['commercial_cibil_rawdata']['com_credit_facility_current_details']):
# if idx == 2:
# print('#########################MAINBREAK')
# break
CustomerName = cibil_raw_data['commercial_cibil_rawdata']['com_borrower_details'][0]['EnqInfoBorrowerName'] if cibil_raw_data['commercial_cibil_rawdata']['com_borrower_details'][0].get('EnqInfoBorrowerName') is not None else 'NA'
AccountType = row['CreditFacilityCDcfType'].strip()
ReportedandCertifiedDate = row['CreditFacilityCDLstReportedDate']
OpendDate = (row['CreditFacilityCDDatesSanctionedDt']) if row['CreditFacilityCDDatesSanctionedDt'] != "" and row['CreditFacilityCDDatesSanctionedDt'] != None and row['CreditFacilityCDDatesSanctionedDt'] != 'None' else None
SanctionedAmount = (row['CreditFacilityCDAmtSanctionedAmt']) if row['CreditFacilityCDAmtSanctionedAmt'] != "" and row['CreditFacilityCDAmtSanctionedAmt'] != None and row['CreditFacilityCDAmtSanctionedAmt'] != 'None' else 0
CurrentBalance = row['CreditFacilityCDAmtoutstandingBalance']
EMIAmount = (row['CreditFacilityCDAmtinstallmentAmt']) if row['CreditFacilityCDAmtinstallmentAmt'] != "" and row['CreditFacilityCDAmtinstallmentAmt'] != None and row['CreditFacilityCDAmtinstallmentAmt'] != 'None' else 0
row['CreditFacilityCDAmtinstallmentAmt']
OverdueAmount = (row['CreditFacilityCDAmtOverdue']) if row['CreditFacilityCDAmtOverdue'] != "" and row['CreditFacilityCDAmtOverdue'] != None and row['CreditFacilityCDAmtOverdue'] != 'None' else 0
RepaymentTenure = (row['CreditFacilityCDODTenure']) if row['CreditFacilityCDODTenure'] != "" and row['CreditFacilityCDODTenure'] != None and row['CreditFacilityCDODTenure'] != 'None' else 0
Status = row['CreditFacilityCDStatus']
Ownership = 'NA'
# CurrentDPD = row['CreditFacilityCDAssetCDPDueDpd']
dpd_result = DpdCalculationService.commercialDpdCalculation(row['CreditFacilityCDcfSrNo'],cibil_raw_data['commercial_cibil_rawdata']['com_dpd_details'],CibilBusinessOperationService.dpd_month_bucket_master)
CurrentDPD = dpd_result['currentDPD']
DPD0_6 = dpd_result['DPD0_6']
DPD7_12 = dpd_result['DPD7_12']
DPD13_24 = dpd_result['DPD13_24']
DPD25_36 = dpd_result['DPD25_36']
# LatestDPD = 0
# DPD0_6 = 0
# DPD7_12 = 0
# DPD13_24 = 0
# DPD25_36 = 0
# call sansactioned amt transformation function
# for calculate sanctioned amt summary
sanctioned_amt_detail = CibilBusinessOperationService.getSanctionedAmtDetails({'AccountType':AccountType,'DateOpenedDisbursed':row['CreditFacilityCDDatesSanctionedDt'],'CurrentBalance':CurrentBalance,'HighCreditSanctionedAmount':SanctionedAmount})
CibilBusinessOperationService.mergeSanctionAmtDetails(sanctioned_amt_detail)
# end of call sansactioned amt transformation function
# temp = {'los_id':'MW12345','ref_no':application_reference_number,"consumer_name":CustomerName,"account_type":AccountType,"reported_and_certified_date":ReportedandCertifiedDate,"opened_date":OpendDate,"sanctioned_amount":SanctionedAmount,"current_balance":CurrentBalance,"emi_amount":EMIAmount,"overdue_amount":OverdueAmount,"repayment_tenure":RepaymentTenure,"status":Status,"ownership":Ownership,"current_dpd":CurrentDPD,'dpd0_6':DPD0_6,'dpd7_12':DPD7_12,'dpd13_24':DPD25_36,'dpd25_36':DPD25_36,'is_active':1,'createdAt':datetime.now().strftime("%Y-%m-%d %H:%M:%S"),'updatedAt':datetime.now().strftime("%Y-%m-%d %H:%M:%S"),'createdby':1,'updatedby':1}
temp = Out_active_and_closed_loans_details(losid=los_id,ref_no=application_reference_number,consumer_name=CustomerName,account_type=AccountType,reported_and_certified_date=ReportedandCertifiedDate,opened_date=OpendDate,sanctioned_amount=SanctionedAmount,current_balance=CurrentBalance,emi_amount=EMIAmount,overdue_amount=OverdueAmount,repayment_tenure=RepaymentTenure,status=Status,ownership=Ownership,current_dpd=CurrentDPD,highest_dpd_month_wise_bucket_or_count_0_to_6=DPD0_6,highest_dpd_month_wise_bucket_or_count_07_to_12=DPD7_12,highest_dpd_month_wise_bucket_or_count_13_to_24=DPD13_24,highest_dpd_month_wise_bucket_or_count_25_to_36=DPD25_36,is_active=1,createdAt=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),updatedAt=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),createdby=1,updatedby=1)
# print(temp);
# raise Exception('tata')
# temp = {'los_id':'MW12345'}
# if CurrentBalance != 0:
CibilBusinessOperationService.live_and_closed_account_summary.append(temp);
# print('idx',idx)
# raise Exception('manual stop')
CibilSummaryDataUpdateService.updateActiveOrClosedLoans(CibilBusinessOperationService.live_and_closed_account_summary)
CibilSummaryDataUpdateService.updateEnquirySummaryData(CibilBusinessOperationService.enquiry_amt_details_summary,application_reference_number,los_id)
CibilSummaryDataUpdateService.updateSanctionedSummaryAndOverallOpenedClosedLoans(CibilBusinessOperationService.sanctioned_amt_details_summary,application_reference_number,los_id)
return (CibilBusinessOperationService.sanctioned_amt_details_summary)
# return cibil_raw_data

View File

@ -0,0 +1,92 @@
from services.dbservice import DbService
from sqlalchemy.sql import text
from app import db
import time
from Models.com_ac_history_and_dpd import Com_ac_history_and_dpd
from Models.com_credit_facility_current_detail import Com_credit_facility_current_detail
# from Models.con_enquiry_detail import Con_enquiry_detail
from Models.month_bucket_master import Month_bucket_master
from Models.com_borrower_profile import Com_borrower_profile
from Models.com_enquiry_detail import Com_enquiry_detail
class CibilCommercialDataService:
def getCreditFacilityCurrentDetails(application_reference_number,los_id):
# https://flask-sqlalchemy.palletsprojects.com/en/2.x/queries/
# print(application_reference_number)
# records = Com_credit_facility_current_detail.query.all()
start_time = time.time()
records = Com_credit_facility_current_detail.query.filter_by(ApplicationRefno = application_reference_number).all()
temp = []
for idx,record in enumerate(records):
# print(record.temp_id,'---',record.CreditFacilityCDcfSrNo[16:])
row_as_dict = {column: str(getattr(record, column)) for column in record.__table__.c.keys()}
# print(row_as_dict)
temp.append(row_as_dict)
# print("--- %s seconds ---" % (time.time() - start_time))
return temp
def getCommercialAcHistoryAndDPDDetails(application_reference_number,los_id):
# records = Com_ac_history_and_dpd.query.filter_by(ApplicationRefno = application_reference_number,BorrowerCurrentDetailsID = credit_facility_id).order_by(Com_ac_history_and_dpd.BorrowerCurrentDetailsID.asc()).all()
records = Com_ac_history_and_dpd.query.filter_by(ApplicationRefno = application_reference_number).order_by(Com_ac_history_and_dpd.BorrowerCurrentDetailsID.asc()).all()
temp = []
# print(records)
for record in records:
# print(record.id,'---',record.AccountTranDetailsID)
row_as_dict = {column: str(getattr(record, column)) for column in record.__table__.c.keys()}
# print(row_as_dict)
temp.append(row_as_dict)
return temp
def getMonthBucketMaster(mtype=None):
# records = Con_dpd_transaction_detail.query.filter_by(MemberRefNo = member_reference_number,AccountTranDetailsID = account_tran_details_id).order_by(Con_dpd_transaction_detail.StartDate.desc()).all()
records = Month_bucket_master.query.filter_by(type = (mtype),isactive = 1).order_by(Month_bucket_master.id.asc()).all()
temp = []
# print(records)
for record in records:
# print(record.id,'---',record.AccountTranDetailsID)
row_as_dict = {column: str(getattr(record, column)) for column in record.__table__.c.keys()}
# print(row_as_dict)
temp.append(row_as_dict)
return temp
def getCommercialBorrowerDetails(application_reference_number,los_id):
# records = Con_dpd_transaction_detail.query.filter_by(MemberRefNo = member_reference_number,AccountTranDetailsID = account_tran_details_id).order_by(Con_dpd_transaction_detail.StartDate.desc()).all()
records = Com_borrower_profile.query.filter_by(ApplicationRefno = application_reference_number).all()
temp = []
# print(records)
for record in records:
# print(record.id,'---',record.AccountTranDetailsID)
row_as_dict = {column: str(getattr(record, column)) for column in record.__table__.c.keys()}
# print(row_as_dict)
temp.append(row_as_dict)
return temp
def getCommercialsEnquriyDetails(application_reference_number,los_id):
# records = Con_dpd_transaction_detail.query.filter_by(MemberRefNo = member_reference_number,AccountTranDetailsID = account_tran_details_id).order_by(Con_dpd_transaction_detail.StartDate.desc()).all()
records = Com_enquiry_detail.query.filter_by(ApplicationRefno = application_reference_number).all()
temp = []
# print(records)
for record in records:
# print(record.id,'---',record.AccountTranDetailsID)
row_as_dict = {column: str(getattr(record, column)) for column in record.__table__.c.keys()}
# print(row_as_dict)
temp.append(row_as_dict)
return temp

View File

@ -0,0 +1,164 @@
# from services.dbservice import DbService
from sqlalchemy.sql import text,func
from app import db
from flask import jsonify
import decimal, datetime, json
# from Models.con_account_transaction_detail import Con_account_transaction_detail
# from Models.con_dpd_transaction_detail import Con_dpd_transaction_detail
# from Models.con_enquiry_detail import Con_enquiry_detail
from Models.month_bucket_master import Month_bucket_master
from Models.intermediate_tables import In_borrower_detail,In_credit_facility,In_dpd_transaction_detail,In_enquiry_detail
class CibilDataService:
# start Collecting Consumer CIBIL RawData of single member/applicant
# report by @param : member_reference_number
def getBorrowerDetails(reference_number,los_id,cibil_type):
# records = db.engine.execute(text('SELECT id ,BDeatailsID ,CONVERT(NVARCHAR, MemberReferenceNumber) as MemberReferenceNumber ,EnquiryMemberUserID ,SubjectReturnCode ,CONVERT(NVARCHAR, EnquiryControlNumber) as EnquiryControlNumber ,CONVERT(VARCHAR,DateTimeProcessed) as DateTimeProcessed ,ConsumerNameField1 ,ConsumerNameField2 ,ConsumerNameField3 ,ConsumerNameField4 ,ConsumerNameField5 ,CONVERT(VARCHAR,DateofBirth) as DateofBirth ,Gender ,DateofEntryforErrorCode ,ErrorSegmentTag ,ErrorCode ,DateofEntryforCIBILRemarksCode ,CIBILRemarks ,DateofEntryforErrorDisputeRemarksCode ,ErrorDisputeRemarksCode ,ErrorDisputeRemarksCode2 ,AccountType ,CONVERT(VARCHAR,DateReportedAndCertified) as DateReportedAndCertified ,Occupation ,CONVERT(NVARCHAR, Income) as Income ,NetGrossIncomeIndicator ,MonthlyAnnualIncomeIndicator ,DateOfEntryforErrorCode1 ,ErrorCode1 ,DateOfEntryForCIBILRemarksCode1 ,CIBILRemarksCode ,DateOfEntryForErrorDisputeRemarksCode1 ,ErrorDisputeRemarksCode1 ,ATErrorDisputeRemarksCode1 ,ATErrorDisputeRemarksCode2 ,DateOfEntry ,DisputeRemarksLine ,EMailID ,AccountNumber ,CONVERT(VARCHAR,createdAt) as createdAt ,CONVERT(VARCHAR,updatedAt) as updatedAt ,createdby ,updatedby FROM con_borrower_detail where MemberReferenceNumber = :member_reference_number'),{'member_reference_number':member_reference_number})
# records = records.fetchall()
# print(len(records))
records = In_borrower_detail.query.filter_by(ReferenceNumber = reference_number,losid = los_id,cibil_type = cibil_type).all()
# print(len(records))
# print((records))
data = []
# print(field_names)
for idx,i in enumerate(records):
# print('###### START #######')
# print((i))
# print(idx,str(i.MemberReferenceNumber))
# records[idx].MemberReferenceNumber = str(i.MemberReferenceNumber)
# print('**************************************')
row_as_dict = {column: str(getattr(i, column)) for column in i.__table__.c.keys()}
# print('###### END #######')
data.append(row_as_dict)
# print(result)
# exit()
return data
def getCreditFacilityDetails(reference_number,los_id,cibil_type):
# https://flask-sqlalchemy.palletsprojects.com/en/2.x/queries/
# records = Con_account_transaction_detail.query.all()
records = In_credit_facility.query.filter_by(ReferenceNumber = reference_number,losid = los_id,cibil_type = cibil_type).all()
# records = In_credit_facility.query.filter_by(losid = los_id).all()
temp = []
# print(records)
for record in records:
# print(record.id,'---',record.AccountTranDetailsID)
row_as_dict = {column: str(getattr(record, column)) for column in record.__table__.c.keys()}
# print(row_as_dict)
# t = CibilConsumerDataService.getConsumerDPDDetails(member_reference_number,row_as_dict['AccountTranDetailsID'
# ])
# row_as_dict['dpd'] = t
temp.append(row_as_dict)
return temp
def getUniqueCreditFacilityDetails(los_id):
# https://flask-sqlalchemy.palletsprojects.com/en/2.x/queries/
# records = Con_account_transaction_detail.query.all() func.max(In_credit_facility.grp_str)
# records = db.session.query(In_credit_facility.losid, db.func.max(In_credit_facility.losid).label('active_machines')).group_by(In_credit_facility.losid).all()
records = db.session.query(db.func.max(In_credit_facility.losid).label('losid'),db.func.max(In_credit_facility.AccountType).label('AccountType'),db.func.max(In_credit_facility.month_bucket_index).label('month_bucket_index'),db.func.max(In_credit_facility.DateOpenedDisbursed).label('DateOpenedDisbursed'),db.func.max(In_credit_facility.DateClosed).label('DateClosed'),db.func.max(In_credit_facility.CurrentBalance).label('CurrentBalance'),db.func.max(In_credit_facility.HighCreditSanctionedAmount).label('HighCreditSanctionedAmount'),db.func.max(In_credit_facility.CreditLimit).label('CreditLimit'),func.max(In_credit_facility.grp_str).label('grp_str')).filter(In_credit_facility.losid == los_id).group_by(In_credit_facility.grp_str).all()
return json.loads(json.dumps([dict(r) for r in records], default=CibilDataService.alchemyencoder))
# records = In_credit_facility.query(func.max(In_credit_facility.grp_str)).filter_by(losid = los_id).all()
temp = []
# print(type(records))
# print(len(records))
for record in records:
# print('---',record.active_machines)
# print(type(record),'--',(record))
# print(dict(record),'--')
# row_as_dict = {column: str(getattr(record, column.name)) for column in record.__table__.columns}
# row_as_dict = record._mapping
# print(jsonify(json_list = record))
# t = CibilConsumerDataService.getConsumerDPDDetails(member_reference_number,row_as_dict['AccountTranDetailsID'
# ])
# row_as_dict['dpd'] = t
temp.append(dict(record))
return temp
def getDPDDetails(reference_number,los_id,cibil_type):
records = In_dpd_transaction_detail.query.filter_by(ReferenceNumber = reference_number,cibil_type = cibil_type).order_by(In_dpd_transaction_detail.AccountTranDetailsID.desc(),In_dpd_transaction_detail.StartDate.desc()).all()
# records = In_dpd_transaction_detail.query.filter_by(ReferenceNumber = reference_number,losid = los_id,cibil_type = cibil_type).order_by(In_dpd_transaction_detail.AccountTranDetailsID.desc(),In_dpd_transaction_detail.StartDate.desc()).all()
temp = []
# print(records)
for record in records:
# print(record.id,'---',record.AccountTranDetailsID)
row_as_dict = {column: str(getattr(record, column)) for column in record.__table__.c.keys()}
# print(row_as_dict)
temp.append(row_as_dict)
return temp
def getEnquriyDetails(reference_number,los_id,cibil_type):
# records = Con_dpd_transaction_detail.query.filter_by(MemberRefNo = member_reference_number,AccountTranDetailsID = account_tran_details_id).order_by(Con_dpd_transaction_detail.StartDate.desc()).all()
records = In_enquiry_detail.query.filter_by(ReferenceNumber = reference_number,losid = los_id,cibil_type = cibil_type).order_by(In_enquiry_detail.DateOfEnquiry.desc()).all()
temp = []
# print(records)
for record in records:
# print(record.id,'---',record.AccountTranDetailsID)
row_as_dict = {column: str(getattr(record, column)) for column in record.__table__.c.keys()}
# print(row_as_dict)
temp.append(row_as_dict)
return temp
def getUniqueEnquriyDetails(los_id):
# print('getUniqueEnquriyDetails' + los_id)
# records = Con_dpd_transaction_detail.query.filter_by(MemberRefNo = member_reference_number,AccountTranDetailsID = account_tran_details_id).order_by(Con_dpd_transaction_detail.StartDate.desc()).all()
records = In_enquiry_detail.query.filter_by(losid = los_id).order_by(In_enquiry_detail.DateOfEnquiry.desc()).all()
temp = []
# print(records)
for record in records:
# print(record.id,'---',record.AccountTranDetailsID)
row_as_dict = {column: str(getattr(record, column)) for column in record.__table__.c.keys()}
# print(row_as_dict)
temp.append(row_as_dict)
return temp
def getMonthBucketMaster(mtype=None):
# records = Con_dpd_transaction_detail.query.filter_by(MemberRefNo = member_reference_number,AccountTranDetailsID = account_tran_details_id).order_by(Con_dpd_transaction_detail.StartDate.desc()).all()
records = Month_bucket_master.query.filter_by(type = (mtype),isactive = 1).order_by(Month_bucket_master.id.asc()).all()
temp = []
# print(records)
for record in records:
# print(record.id,'---',record.AccountTranDetailsID)
row_as_dict = {column: str(getattr(record, column)) for column in record.__table__.c.keys()}
# print(row_as_dict)
temp.append(row_as_dict)
return temp
def alchemyencoder(obj):
# """JSON encoder function for SQLAlchemy special classes."""
if isinstance(obj, datetime.date):
return obj.isoformat()
elif isinstance(obj, decimal.Decimal):
return float(obj)

View File

@ -0,0 +1,98 @@
# from .CibilConsumerDataService import CibilConsumerDataService
from .CibilCommercialDataService import CibilCommercialDataService
class CibilMasterDataService :
cibil_rawdata = {}
# consumer_cibil_rawdata = []
# commercial_cibil_rawdata = []
consumer_borrower_details = []
account_transaction_details = []
consumer_dpd_details = []
consumer_enquiry_details = []
dpd_month_buckets = []
sanction_summary_month_buckets = []
enquiry_summary_month_buckets = []
com_credit_facility_current_details = []
com_dpd_details = []
com_enquiry_details = []
com_borrower_details = []
# start Collecting both Consumer and Commercial CIBIL RawData of single member/applicant
# report by @param : member_reference_number
def getCIBILRawData(reference_number,los_id,type):#type 1 = consumer, type 2 = commercial
if type == 1:# if consumer
CibilMasterDataService.cibil_rawdata['consumer_cibil_rawdata'] = CibilMasterDataService.getAllConsumerCIBILRawData(reference_number,los_id)
elif type == 2:
CibilMasterDataService.cibil_rawdata['commercial_cibil_rawdata'] = CibilMasterDataService.getAllCommercialCIBILRawData(reference_number,los_id)
CibilMasterDataService.cibil_rawdata['masters'] = CibilMasterDataService.getAllMastersData()
# CibilMasterDataService.cibil_rawdata.append({'consumer_cibil_rawdata':CibilMasterDataService.getAllConsumerCIBILRawData(member_reference_number)})
return CibilMasterDataService.cibil_rawdata
# start Collecting Consumer CIBIL RawData of single member/applicant
# report by @param : member_reference_number
def getAllConsumerCIBILRawData(member_reference_number,los_id):
CibilMasterDataService.consumer_borrower_details = CibilConsumerDataService.getConsumerBorrowerDetails(member_reference_number,los_id)
CibilMasterDataService.account_transaction_details = CibilConsumerDataService.getConsumerAccountTransactionDetails(member_reference_number,los_id)
CibilMasterDataService.consumer_dpd_details = CibilConsumerDataService.getConsumerDPDDetails(member_reference_number,los_id)
CibilMasterDataService.consumer_enquiry_details = CibilConsumerDataService.getConsumerEnquriyDetails(member_reference_number,los_id)
# print(len(CibilMasterDataService.account_transaction_details),type(CibilMasterDataService.account_transaction_details))
# if len(CibilMasterDataService.account_transaction_details) > 0:
# for i,acc_trans_detail in enumerate(CibilMasterDataService.account_transaction_details):
# # consumer_dpd_details = {'data':'msg'}
# consumer_dpd_details = CibilConsumerDataService.getConsumerDPDDetails(member_reference_number,acc_trans_detail['AccountTranDetailsID'])
# CibilMasterDataService.account_transaction_details[i]['consumer_dpd_details'] = consumer_dpd_details
overall_data = {}
overall_data['consumer_borrower_details'] = CibilMasterDataService.consumer_borrower_details
overall_data['account_transaction_details'] = CibilMasterDataService.account_transaction_details
overall_data['consumer_dpd_details'] = CibilMasterDataService.consumer_dpd_details
overall_data['consumer_enquiry_details'] = CibilMasterDataService.consumer_enquiry_details
return overall_data
# start Collecting Commercial CIBIL RawData of single member/applicant
# report by @param : member_reference_number
def getAllCommercialCIBILRawData(application_reference_number,los_id):
print('getAllCommercialCIBILRawData')
CibilMasterDataService.com_borrower_details = CibilCommercialDataService.getCommercialBorrowerDetails(application_reference_number,los_id)
CibilMasterDataService.com_credit_facility_current_details = CibilCommercialDataService.getCreditFacilityCurrentDetails(application_reference_number,los_id)
CibilMasterDataService.com_dpd_details = CibilCommercialDataService.getCommercialAcHistoryAndDPDDetails(application_reference_number,los_id)
CibilMasterDataService.com_enquiry_details = CibilCommercialDataService.getCommercialsEnquriyDetails(application_reference_number,los_id)
overall_data = {}
overall_data['com_credit_facility_current_details'] = CibilMasterDataService.com_credit_facility_current_details
overall_data['com_dpd_details'] = CibilMasterDataService.com_dpd_details
overall_data['com_enquiry_details'] = CibilMasterDataService.com_enquiry_details
overall_data['com_borrower_details'] = CibilMasterDataService.com_borrower_details
return overall_data
def getAllMastersData():
print('getAllMastersData')
CibilMasterDataService.dpd_month_buckets = CibilConsumerDataService.getMonthBucketMaster('DPD')
CibilMasterDataService.sanction_summary_month_buckets = CibilConsumerDataService.getMonthBucketMaster('SAN_SUM')
CibilMasterDataService.enquiry_summary_month_buckets = CibilConsumerDataService.getMonthBucketMaster('ENQ_SUM')
overall_data = {}
overall_data['dpd_month_buckets'] = CibilMasterDataService.dpd_month_buckets
overall_data['sanction_summary_month_buckets'] = CibilMasterDataService.sanction_summary_month_buckets
overall_data['enquiry_summary_month_buckets'] = CibilMasterDataService.enquiry_summary_month_buckets
return overall_data

View File

@ -0,0 +1,108 @@
from app import db
from flask import current_app as my_app
from datetime import datetime
from time import time
# from Models.op_sanction_amount_frequency import Op_sanction_amount_frequency
# from Models.op_rtr_summary_of_active_loans import Op_rtr_summary_of_active_loans
# from Models.op_snapshot_of_closed_loans import Op_snapshot_of_closed_loans
from Models.op_enquiry import EnquiryParent,EnquiryChild
from Models.op_sanction import SanctionParent,SanctionChild
class CibilSummaryDataUpdateService :
def updateActiveOrClosedLoans(dataSet):
# obj = Op_rtr_summary_of_active_loans(los_id=data['los_id'],ref_no=data['ref_no'],consumer_name=data['consumer_name'],account_type=data['account_type'],reported_and_certified_date=data['reported_and_certified_date'],opened_date=data['opened_date'],sanctioned_amount=data['sanctioned_amount'],current_balance=data['current_balance'],emi_amount=data['emi_amount'],overdue_amount=data['overdue_amount'],repayment_tenure=data['repayment_tenure'],status=data['status'],ownership=data['ownership'],current_dpd=data['current_dpd'],dpd0_6=data['dpd0_6'],dpd7_12=data['dpd7_12'],dpd13_24=data['dpd13_24'],dpd25_36=data['dpd25_36'],is_active=data['is_active'],createdAt=data['createdAt'],updatedAt=data['updatedAt'],createdby=data['createdby'],updatedby=data['updatedby'])
# db.session.add(dataSet)
# db.session.add_all(dataSet)
db.session.bulk_save_objects(dataSet,return_defaults = True)
db.session.commit()
logText = str(len(dataSet)) + ' - Active Closed loans Saved'
print(logText)
return str(len(dataSet))
def updateSanctionedSummaryAndOverallOpenedClosedLoans(sanctioned_amt_details,reference_number,los_id,cibil_type,output_type):
print('updateSanctionedSummaryAndOverallOpenedClosedLoans',len(sanctioned_amt_details))
parent_inserted_count = 0
# over_start_time = time()
if len(sanctioned_amt_details) > 0:
# over_all_enquiry_data = []
for index,sanctioned_amt in enumerate(sanctioned_amt_details):
# print(index,sanctioned_amt,sanctioned_amt_details[sanctioned_amt])
# print('*********************************')
parent = SanctionParent(output_type=output_type,losid=los_id,ref_no=reference_number,facility_type=sanctioned_amt,createdAt=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),updatedAt=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),createdby=1,updatedby=1,total_amt=sanctioned_amt_details[sanctioned_amt]['total_amt'],total_count=sanctioned_amt_details[sanctioned_amt]['total_count'],open_total_amt=sanctioned_amt_details[sanctioned_amt]['open_total_amt'],open_total_count=sanctioned_amt_details[sanctioned_amt]['open_total_count'],closed_total_amt=sanctioned_amt_details[sanctioned_amt]['closed_total_amt'],closed_total_count=sanctioned_amt_details[sanctioned_amt]['closed_total_count'])
start_time = time()
db.session.add(parent)
# Child(months_range="bar",amt=10,count=12,is_active=1,parent=parent)
db.session.commit()
# print("--- %s Parent insert time seconds ---" %(time() - start_time))
if parent.id: parent_inserted_count += 1
childDataSet = []
for idx,sanction_child_data in enumerate(sanctioned_amt_details[sanctioned_amt]):
if sanction_child_data != "total_amt" and sanction_child_data != "total_count" and sanction_child_data != "open_total_amt" and sanction_child_data != "open_total_count" and sanction_child_data != "closed_total_amt" and sanction_child_data != "closed_total_count":
# print(sanction_child_data,sanctioned_amt_details[sanctioned_amt][sanction_child_data])
child = SanctionChild(sanction_amt_id=parent.id,months_range=sanction_child_data,amt=sanctioned_amt_details[sanctioned_amt][sanction_child_data]['amt'],count=sanctioned_amt_details[sanctioned_amt][sanction_child_data]['count'],opening_amt=sanctioned_amt_details[sanctioned_amt][sanction_child_data]['openamt'],opening_count=sanctioned_amt_details[sanctioned_amt][sanction_child_data]['opencount'],closing_amt=sanctioned_amt_details[sanctioned_amt][sanction_child_data]['closeamt'],closing_count=sanctioned_amt_details[sanctioned_amt][sanction_child_data]['closecount'],createdAt=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),updatedAt=datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
childDataSet.append(child)
# print(childDataSet)
db.session.bulk_save_objects(childDataSet)
db.session.commit()
# print("--- %s Child insert time seconds ---" %(time() - start_time))
# print("--- %s overall time ---" %(time() - over_start_time))
return parent_inserted_count
def updateEnquirySummaryData(enquiry_details,reference_number,los_id,cibil_type,output_type):
print('updateEnquirySummaryData', len(enquiry_details))
parent_inserted_count = 0
# raise Exception('tata')
if len(enquiry_details) > 0:
# over_all_enquiry_data = []
for index,enquiry_detail in enumerate(enquiry_details):
# over_all_enquiry_data.append(EnquiryParent(los_id='MWTEST',ref_no='TESTREF',facility_type=enquiry_detail,is_active=1,createdAt=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),updatedAt=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),createdby=1,updatedby=1,total=enquiry_details[enquiry_detail]['total']))
# print(index,enquiry_detail,enquiry_details[enquiry_detail])
# print('*********************************')
# print(over_all_enquiry_data)
parent = EnquiryParent(output_type=output_type,losid=los_id,ref_no=reference_number,facility_type=enquiry_detail,is_active=1,createdAt=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),updatedAt=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),createdby=1,updatedby=1,total_amt=enquiry_details[enquiry_detail]['total_amt'],total_count=enquiry_details[enquiry_detail]['total_count'])
start_time = time()
db.session.add(parent)
# Child(months_range="bar",amt=10,count=12,is_active=1,parent=parent)
db.session.commit()
# print("--- %s Parent insert time seconds ---" %(time() - start_time))
if parent.id: parent_inserted_count += 1
childDataSet = []
for idx,enquiry_child_data in enumerate(enquiry_details[enquiry_detail]):
if enquiry_child_data != "total_amt" and enquiry_child_data != "total_count":
# print(enquiry_child_data,enquiry_details[enquiry_detail][enquiry_child_data])
child = EnquiryChild(enquiry_amount_id=parent.id,months_range=enquiry_child_data,amt=enquiry_details[enquiry_detail][enquiry_child_data]['amt'],count=enquiry_details[enquiry_detail][enquiry_child_data]['count'],is_active=1,createdAt=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),updatedAt=datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
childDataSet.append(child)
# print(childDataSet)
db.session.bulk_save_objects(childDataSet)
db.session.commit()
# print("--- %s Child insert time seconds ---" %(time() - start_time))
return parent_inserted_count

View File

@ -0,0 +1,220 @@
from datetime import datetime
from collections import Counter
import re
class DpdCalculationService:
def dpdCalculation(accountTranDetailsID=None,Consumer_dpd_details=None,dpd_month_bucket_master=None):
# print('dpdCalculation called',accountTranDetailsID,len(Consumer_dpd_details))
# print(dpd_month_bucket_master)
# month_index = 0
currentDPD = 0;
DPD0_6,DPD7_12,DPD13_24,DPD25_36 = [],[],[],[]
# DPD0_6_BUCKET,DPD7_12_BUCKET,DPD13_24_BUCKET,DPD25_36_BUCKET = [{'name':'20-30','from':20,'to':30},{'name':'31-40','from':31,'to':40},{'name':'41-50','from':41,'to':60}],[],[],[]
for idx,dpd in enumerate(Consumer_dpd_details):
# if accountTranDetailsID == '388857':
# print('#########################BREAK')
# break
#in future introduce if condition like idx <=36
if dpd['AccountTranDetailsID'] == accountTranDetailsID:
# month_index+=1
# if month_index == 37:break
# month = (datetime.strptime((dpd['StartDate'].split(" ")[0]), "%Y-%m-%d")).month
month_bucket_index = int(dpd['month_bucket_index'])
if month_bucket_index == 1: currentDPD = month_bucket_index
month_bucket = '0_6' if month_bucket_index <= 6 else '7_12' if month_bucket_index >= 7 and month_bucket_index <= 12 else '13_24' if month_bucket_index >=13 and month_bucket_index <= 24 else '25_36' if month_bucket_index >= 25 and month_bucket_index <= 36 else None
currentDPDcode = (int(dpd['Code'])) if dpd['Code'].isnumeric() else 0
dynamic_dpd_month_bucket = None if month_bucket is None else 'DPD'+month_bucket
# dynamic_dpd_month_range_bucket = dynamic_dpd_month_bucket + '_BUCKET'
# print(vars()[dynamic_dpd_month_bucket],vars()[dynamic_dpd_month_range_bucket])
# if len(vars()[dynamic_dpd_month_range_bucket]) > 0:
# for single_date_range in vars()[dynamic_dpd_month_range_bucket]:
# if currentDPDcode != 0 and currentDPDcode >= int(single_date_range['from']) and currentDPDcode <= int(single_date_range['to']):
# print(currentDPDcode,'-',single_date_range['name'])
# vars()[dynamic_dpd_month_bucket].append(single_date_range['name'])
# break
currentDPDMonth = 0
if dynamic_dpd_month_bucket is not None:
currentDPDMonth = DpdCalculationService.dpdFindDaysBucket(dpd_month_bucket_master,currentDPDcode)
if currentDPDMonth != 0:
vars()[dynamic_dpd_month_bucket].append(currentDPDMonth)
# print(vars()[dynamic_dpd_month_bucket])
# print(idx,dpd['AccountTranDetailsID'],dpd['StartDate'],month,month_bucket,dynamic_dpd_month_bucket,currentDPDMonth,currentDPDcode)
# print(DPD0_6,DPD7_12,DPD13_24,DPD25_36)
DPD0_6 = DpdCalculationService.findMaxCountofDPDDays(DPD0_6);
DPD7_12 = DpdCalculationService.findMaxCountofDPDDays(DPD7_12);
DPD13_24 = DpdCalculationService.findMaxCountofDPDDays(DPD13_24);
DPD25_36 = DpdCalculationService.findMaxCountofDPDDays(DPD25_36);
# print('final*****',DPD0_6)
DPD0_6 = DPD0_6['days_range'] +'(' + DPD0_6['count'] +')' if 'days_range' in DPD0_6 else '0'
DPD7_12 = DPD7_12['days_range'] +'(' + DPD7_12['count'] +')' if 'days_range' in DPD7_12 else '0'
DPD13_24 = DPD13_24['days_range'] +'(' + DPD13_24['count'] +')' if 'days_range' in DPD13_24 else '0'
DPD25_36 = DPD25_36['days_range'] +'(' + DPD25_36['count'] +')' if 'days_range' in DPD25_36 else '0'
return {'currentDPD':currentDPD,'DPD0_6':DPD0_6,'DPD7_12':DPD7_12,'DPD13_24':DPD13_24,'DPD25_36':DPD25_36}
def monthDiffBWDates(fromDate,endDate):
# start = datetime.strptime((fromDate.split(" ")[0]), "%Y-%m-%d")
# end = datetime.strptime((endDate.split(" ")[0]), "%Y-%m-%d")
# months = (end.year - start.year) * 12 + (end.month - start.month )
# print('monhs',months)
# print('')
# return months
str = 'xxx'
try:
val = int(str)
print(type(val))
except IOError:
print(type(str))
def dpdFindDaysBucket(month_bucket_master,factor):
#DPD month bucket calculation start
# print(dpd_month_bucket_master)
for dpd_month_bucket in month_bucket_master:
# print(dpd_month_bucket)
# print(type(dpd_month_bucket['range_from']),'***',dpd_month_bucket['range_from'].isnumeric())
# print(type(dpd_month_bucket['range_to']),'***',dpd_month_bucket['range_to'].isnumeric())
range_from = int(dpd_month_bucket['range_from']) if (type(dpd_month_bucket['range_from']) is str and dpd_month_bucket['range_from'].isnumeric()) else None
range_to = int(dpd_month_bucket['range_to']) if (type(dpd_month_bucket['range_to']) is str and dpd_month_bucket['range_to'].isnumeric()) else None
# range_to = int(dpd_month_bucket['range_to']) if (dpd_month_bucket['range_to'] is str and dpd_month_bucket['range_to'].isnumeric()) else dpd_month_bucket['range_to']
factor = int(factor) if isinstance(factor,str) and factor.isnumeric() else factor if isinstance(factor,int) else 0
if range_from != None and range_to != None:
# print((range_from),'###',(range_to),range_from != None,currentDPDcode)
if factor >= (range_from) and factor <= (range_to):
# vars()[dynamic_dpd_month_bucket].append(dpd_month_bucket['name'])
return dpd_month_bucket['name']
# break
elif range_to == None:
if factor >= (range_from):
# vars()[dynamic_dpd_month_bucket].append(dpd_month_bucket['name'])
return dpd_month_bucket['name']
# break
elif range_from == None:
if factor >= (range_to):
# vars()[dynamic_dpd_month_bucket].append(dpd_month_bucket['name'])
return dpd_month_bucket['name']
# break
else:
return 0
# break
#DPD month bucket calculation end
def findMaxCountofDPDDays(listOfDaysCount):
# print('findMaxCountofDPDDays******',listOfDaysCount)
UniquelistOfDaysCount = Counter(listOfDaysCount)
days_count_list = (list(UniquelistOfDaysCount.values()))
if len(days_count_list) > 0:
return {'days_range':(listOfDaysCount[days_count_list.index(max(days_count_list))]),'count': str(max(days_count_list))}
else:
return {}
# DpdCalculationService.monthDiffBWDates('2014-02-03 00:00:00','2022-01-14 11:16:55.097000')
def commercialDpdCalculation(creditFacilitySno = None,com_dpd_details=None,dpd_month_bucket_master=None):
# print('dpdCalculation called',creditFacilitySno,len(com_dpd_details))
# print(dpd_month_bucket_master)
month_index = 0
currentDPD = 0;
DPD0_6,DPD7_12,DPD13_24,DPD25_36 = [],[],[],[]
# DPD0_6_BUCKET,DPD7_12_BUCKET,DPD13_24_BUCKET,DPD25_36_BUCKET = [{'name':'20-30','from':20,'to':30},{'name':'31-40','from':31,'to':40},{'name':'41-50','from':41,'to':60}],[],[],[]
for idx,dpd in enumerate(com_dpd_details):
if creditFacilitySno[16:] == 2:
print('#########################BREAK')
break
#in future introduce if condition like idx <=36
if dpd['BorrowerCurrentDetailsID'] == creditFacilitySno[16:]:
month_index+=1
#find number in string i.e 25 in 25 days past
tempDPD = re.findall('[0-9]+', dpd['CFHistory24MonthsACorDPD'])
tempDPD = tempDPD[0] if len(tempDPD) > 0 else 0
if month_index == 1: currentDPD = tempDPD
if month_index == 37:break
# month = (datetime.strptime((dpd['StartDate'].split(" ")[0]), "%Y-%m-%d")).month
month = month_index
month_bucket = '0_6' if month <= 6 else '7_12' if month >= 7 and month <= 12 else '13_24' if month >=13 and month <= 24 else '25_36' if month >= 25 and month <= 36 else 'None'
currentDPDcode = (int(tempDPD)) if tempDPD is not str else 0
dynamic_dpd_month_bucket = 'DPD'+month_bucket
currentDPDMonth = DpdCalculationService.dpdFindDaysBucket(dpd_month_bucket_master,currentDPDcode)
if currentDPDMonth != 0:
vars()[dynamic_dpd_month_bucket].append(currentDPDMonth)
# print(vars()[dynamic_dpd_month_bucket])
# print(idx,dpd['BorrowerCurrentDetailsID'],dpd['CFHistory24Monthsmonth'],month,month_bucket,dynamic_dpd_month_bucket,currentDPDMonth,currentDPDcode)
# print(DPD0_6,DPD7_12,DPD13_24,DPD25_36)
DPD0_6 = DpdCalculationService.findMaxCountofDPDDays(DPD0_6);
DPD7_12 = DpdCalculationService.findMaxCountofDPDDays(DPD7_12);
DPD13_24 = DpdCalculationService.findMaxCountofDPDDays(DPD13_24);
DPD25_36 = DpdCalculationService.findMaxCountofDPDDays(DPD25_36);
# print('final*****',DPD0_6)
DPD0_6 = DPD0_6['days_range'] +'(' + DPD0_6['count'] +')' if 'days_range' in DPD0_6 else '0'
DPD7_12 = DPD7_12['days_range'] +'(' + DPD7_12['count'] +')' if 'days_range' in DPD7_12 else '0'
DPD13_24 = DPD13_24['days_range'] +'(' + DPD13_24['count'] +')' if 'days_range' in DPD13_24 else '0'
DPD25_36 = DPD25_36['days_range'] +'(' + DPD25_36['count'] +')' if 'days_range' in DPD25_36 else '0'
return {'currentDPD':currentDPD,'DPD0_6':DPD0_6,'DPD7_12':DPD7_12,'DPD13_24':DPD13_24,'DPD25_36':DPD25_36}
def checkDateInLatest36Months(date,latest_36months_skeleton):
print('checkDateInLatest36Months')
temp_dpd_date = (datetime.datetime.strptime(date, "%Y-%m-%d"))
# print(temp_dpd_date.month)
return_data = 0
for month_index,skeleton_date in enumerate(latest_36months_skeleton):
if (temp_dpd_date.year == skeleton_date.year) and (temp_dpd_date.month == skeleton_date.month):
print(month_index,':',date, ' - is in - ', (month_index + 1), ' bucket')
return_data = (month_index + 1)
break
return return_data
def generateMonthSkeleton(date,month_size = 36,):
latest_36months_skeleton = []
print('generateMonthSkeleton')
date = datetime.datetime.strptime(date, "%Y-%m-%d")
month_count = 1
while month_count <= 36 :
day = date - relativedelta(months=month_count)
latest_36months_skeleton.append((day))
month_count += 1
return latest_36months_skeleton

View File

@ -0,0 +1,10 @@
import decimal
from flask import Flask, json
class MyJSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, decimal.Decimal):
# Convert decimal instances to strings.
return str(obj)
return super(MyJSONEncoder, self).default(obj)

View File

@ -0,0 +1,23 @@
import pandas as pd
from services.CibilBusinessOperationService import CibilBusinessOperationService
def getDataFrame():
dataFrame = pd.DataFrame()
# dataFrame = pd.DataFrame(columns = ['Name', 'Articles', 'Improved'])
# print(df)
# append rows to an empty DataFrame
dataFrame = dataFrame.append({'Name' : 'Ankit', 'Articles' : 97, 'Improved' : 2200},
ignore_index = True)
dataFrame = dataFrame.append({'Name' : 'Aishwary', 'Articles' : 30, 'Improved' : 50},
ignore_index = True)
dataFrame = dataFrame.append({'Name' : 'yash', 'Articles' : 17, 'Improved' : 220},
ignore_index = True)
print(dataFrame)
return dataFrame
def getCIBILDataFrame():
py_dict = CibilBusinessOperationService.doCIBILOperations(99999999999)
dataFrame = pd.DataFrame.from_dict(py_dict)
return dataFrame

View File

@ -0,0 +1,12 @@
import json
class SampleDataProviderService:
def getCIBILRawData(reference_number,type):
filename = './data.json' if type == 1 else './com.json' if type == 2 else ''
with open(filename) as json_file:
data = json.load(json_file)
return data

10
services/db.py Normal file
View File

@ -0,0 +1,10 @@
# from __main__ import app
from flask_sqlalchemy import SQLAlchemy
# from app import db
# def db():
db = SQLAlchemy()

32
services/dbservice.py Normal file
View File

@ -0,0 +1,32 @@
import pypyodbc
import urllib
class DbService:
myDB = None
def __init__(self):
print('DbService init called')
self.Driver = '{ODBC Driver 17 for SQL Server}'
def getDBConnection(self,Server ='',Database = '',uid='', pwd=''):
# myDB = pypyodbc.connect('Driver={ODBC Driver 17 for SQL Server};Server=34.121.71.79,1433;Database=gst_staging;uid=cet;pwd=fpw@lu,win,iis@2021C')
# Driver = '{ODBC Driver 17 for SQL Server}'
Server = '34.121.71.79,1433' if Server == '' else Server
# Database = 'gst_staging' if Database == '' else Database
Database = 'cibil_staging' if Database == '' else Database
uid='cet' if uid == '' else uid
pwd='fpw@lu,win,iis@2021C' if pwd == '' else pwd
self.myDB = pypyodbc.connect(Driver=self.Driver,Server=Server,Database=Database,uid=uid,pwd=pwd)
return self.myDB
def getDBConnectionString():
connStr = urllib.parse.quote_plus('Driver={ODBC Driver 17 for SQL Server};Server=34.121.71.79,1433;Database=cibil_staging;uid=cet;pwd=fpw@lu,win,iis@2021C;')
connStr = "mssql+pyodbc:///?odbc_connect=%s" % connStr
return connStr
def __del__(self):
print('DbService destructor called')
# self.myDB.close()

View File

@ -0,0 +1,45 @@
{
// The tab key will cycle through the settings when first created
// Visit https://codexns.io/products/sftp_for_subime/settings for help
// sftp, ftp or ftps
"type": "sftp",
"save_before_upload": true,
"upload_on_save": false,
"sync_down_on_open": false,
"sync_skip_deletes": false,
"sync_same_age": true,
"confirm_downloads": false,
"confirm_sync": true,
"confirm_overwrite_newer": false,
"host": "example.com",
"user": "username",
//"password": "password",
//"port": "22",
"remote_path": "/example/path/",
"ignore_regexes": [
"\\.sublime-(project|workspace)", "sftp-config(-alt\\d?)?\\.json",
"sftp-settings\\.json", "/venv/", "\\.svn/", "\\.hg/", "\\.git/",
"\\.bzr", "_darcs", "CVS", "\\.DS_Store", "Thumbs\\.db", "desktop\\.ini"
],
//"file_permissions": "664",
//"dir_permissions": "775",
//"extra_list_connections": 0,
"connect_timeout": 30,
//"keepalive": 120,
//"ftp_passive_mode": true,
//"ftp_obey_passive_host": false,
//"ssh_key_file": "~/.ssh/id_rsa",
//"sftp_flags": ["-F", "/path/to/ssh_config"],
//"preserve_modification_times": false,
//"remote_time_offset_in_hours": 0,
//"remote_encoding": "utf-8",
//"remote_locale": "C",
//"allow_config_upload": false,
}

45
services/sftp-config.json Normal file
View File

@ -0,0 +1,45 @@
{
// The tab key will cycle through the settings when first created
// Visit https://codexns.io/products/sftp_for_subime/settings for help
// sftp, ftp or ftps
"type": "sftp",
"save_before_upload": true,
"upload_on_save": false,
"sync_down_on_open": false,
"sync_skip_deletes": false,
"sync_same_age": true,
"confirm_downloads": false,
"confirm_sync": true,
"confirm_overwrite_newer": false,
"host": "example.com",
"user": "username",
//"password": "password",
//"port": "22",
"remote_path": "/example/path/",
"ignore_regexes": [
"\\.sublime-(project|workspace)", "sftp-config(-alt\\d?)?\\.json",
"sftp-settings\\.json", "/venv/", "\\.svn/", "\\.hg/", "\\.git/",
"\\.bzr", "_darcs", "CVS", "\\.DS_Store", "Thumbs\\.db", "desktop\\.ini"
],
//"file_permissions": "664",
//"dir_permissions": "775",
//"extra_list_connections": 0,
"connect_timeout": 30,
//"keepalive": 120,
//"ftp_passive_mode": true,
//"ftp_obey_passive_host": false,
//"ssh_key_file": "~/.ssh/id_rsa",
//"sftp_flags": ["-F", "/path/to/ssh_config"],
//"preserve_modification_times": false,
//"remote_time_offset_in_hours": 0,
//"remote_encoding": "utf-8",
//"remote_locale": "C",
//"allow_config_upload": false,
}

View File

@ -0,0 +1,11 @@
# from flask import Blueprint
# utility_blueprint = Blueprint('utility_blueprint', __name__)
def sendRestResponse(datastatus = 200,data = {'msg':'Data Not available...!'}):
print('sendRestResponse called')
return {'datastatus' : datastatus, 'data' : data}

7
templates/about.html Normal file
View File

@ -0,0 +1,7 @@
<!doctype html>
<title>Hello from Flask</title>
{% if name %}
<h1>Hello Mr {{ name }}!, You're a Fraud</h1>
{% else %}
<h1>Hello, Mr Anonomys!</h1>
{% endif %}

14
templates/dataframe.html Normal file
View File

@ -0,0 +1,14 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% for table in tables %}
{{titles[0]}}
{{ table|safe }}
{% endfor %}
</body>
</html>