-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathviews.py
409 lines (331 loc) · 16.6 KB
/
views.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import render_to_response
from forms import *
from externalapis import *
from loans.models import *
import datetime;
def getCustomerId(request):
return 1
#sessionId = request.session.get("id","none")
#if (sessionId != "none"):
#return IdentityModule.getCustomerId(sessionId)
#else:
#return HttpResponseRedirect("/home")
def home(request):
"""Home page for a unsigned user."""
return render_to_response('home.html',locals())
def dueInstallments(request):
"""View for displaying all due and/or overdue installments for all loans of a customer."""
# Get the customerId and verify if the session is active.
customerID = getCustomerId(request)
# Get a list of all ActiveLoans associated with that Customer.
activeLoanList = Loan.objects.filter(customer=customerID, isActive=True)
# For each ActiveLoan get a list of all OverdueInstallment and merge these lists
# Make a list of due installments using nextInstallmentDueDate for each ActiveLoan
# Sort both these lists chronologically
overdueInstallments = []
dueInstallments = []
for activeLoan in activeLoanList:
ois = OverdueInstallment.objects.filter(loan=activeLoan)
for oi in ois:
overdueInstallments.append({'amount':oi.amount,
'dueDate':oi.dueDate,
'loan':oi.loan.name,
'payLink':"../payInstallment/"+str(oi.loan.id),
})
di = {'amount':activeLoan.activeloan.monthlyInstallment,
'dueDate':activeLoan.activeloan.nextInstallmentDueDate,
'loan':activeLoan.name,
'payLink':"../payInstallment/"+str(activeLoan.id),
}
dueInstallments.append(di)
def getDueDate(installment):
return installment['dueDate']
overdueInstallments = sorted(overdueInstallments, key=getDueDate)
dueInstallments = sorted(dueInstallments, key=getDueDate)
return render_to_response('dueInstallments.html', locals())
def allApplications(request):
"""
View for displaying all the loan applications a customer has made.
These applications include those which have been approved, rejected or are under consideration.
"""
# Get the customerId and verify if the session is active.
customerID = getCustomerId(request)
# Get a list of all Applications associated with that Customer.
# Sort them in three categories.
applicationList = Application.objects.filter(customer=customerID)
processedApplications = []
underProcessingApplications = []
archivedApplications = []
for application in applicationList:
if application.isArchived == False:
if application.status == "Active":
underProcessingApplications.append({'id':application.id,
'name':application.name,
'loanType':application.loanType,
'amountAppliedFor':application.amountAppliedFor,
'dateApplied':application.dateApplied,
'status':application.status,
'remark':application.remark,
'cancelLink':"/cancelOrArchive/cancel/"+str(application.id),})
elif application.status == "Allotted" or application.status == "Rejected":
processedApplications.append({'id':application.id,
'name':application.name,
'loanType':application.loanType,
'status':application.status,
'amountAllotted':application.amountAllotted,
'dateOfAllotment':application.dateOfAllotment,
'interestCategory':application.interestCategory,
'interestRate':application.interestRate,
'amountAppliedFor':application.amountAppliedFor,
'dateApplied':application.dateApplied,
'archiveLink':"/cancelOrArchive/archive/"+str(application.id),})
else:
archivedApplications.append({'id':application.id,
'name':application.name,
'loanType':application.loanType,
'status':application.status,
'amountAllotted':application.amountAllotted,
'dateOfAllotment':application.dateOfAllotment,
'interestCategory':application.interestCategory,
'interestRate':application.interestRate,
'amountAppliedFor':application.amountAppliedFor,
'dateApplied':application.dateApplied,
'remark':application.remark})
return render_to_response('allApplications.html', locals())
def allPayments(request):
"""View for displaying all payments made by a customer in reverse chronological order"""
# Get customer id and verify is the session is active
customer_id = getCustomerId(request)
# Get all the loans for the customer using the customer_id
loansList = Loan.objects.filter(customer=customer_id)
#the list to be returned
paymentsList = []
#loop over all the loans of the customer and get payments for every loan
for l in loansList:
paymentsList += Payment.objects.filter(loan = l) #add the list of payments corresponding to every loan to paymentsList
#the following function is defined for use with the sorted method
def getdatePaid(payment):
return payment.datePaid
#sort the payments reverse chronologically
paymentsList = sorted(paymentsList, key=getdatePaid, reverse=True)
return render_to_response('allPayments.html', locals())
def cancelOrArchive(request, cancelOrArchive, applicationID):
"""View for cancelling or archiving an application. Redirects back to allApplications. """
customerID = getCustomerId(request)
if cancelOrArchive=="cancel":
Application.objects.filter(id=applicationID).update(status="Cancelled", isArchived="True")
elif cancelOrArchive=="archive":
Application.objects.filter(id=applicationID).update(isArchived="True")
return HttpResponseRedirect("/allApplications/")
def allLoans(request):
"""Show all loans for a customer."""
# Get the customerId and verify if the session is active.
customerID = getCustomerId(request)
loanList=Loan.objects.filter(customer=customerID)
actDict = []
compDict = []
for loan in loanList:
if loan.isActive:
actDict.append({'id':loan.id,
'name':loan.name,
'loanType':loan.loanType,
'principal':loan.principal,
'totalMonths':loan.originalMonths,
'dateTaken':loan.dateTaken,
'expectedDateOfTermination':loan.activeloan.expectedDateOfTermination,
'outstandingLoanBalance':loan.activeloan.outstandingLoanBalance,
'monthsLeft':loan.originalMonths - loan.activeloan.elapsedMonths,
'interestCategory':loan.interestCategory,
'interestRate':loan.activeloan.interestRate,
'monthlyInstallment':loan.activeloan.monthlyInstallment,
'nextInstallmentDueDate':loan.activeloan.nextInstallmentDueDate,
'prepaymentPenaltyRate':loan.activeloan.prepaymentPenaltyRate,
'security':loan.security,
'detailLink':"/loanDetails/"+str(loan.id),
'prepayNowLink':"/payPrepayment/"+str(loan.id),
})
else:
compDict.append({'id':loan.id,
'name':loan.name,
'loanType':loan.loanType,
'principal':loan.principal,
'totalMonths':loan.originalMonths,
'dateTaken':loan.dateTaken,
'dateOfCompletion':loan.completedloan.dateOfCompletion,
'totalAmountPaid':loan.completedloan.totalAmountPaid,
'interestCategory':loan.interestCategory,
'averageInterestRate':loan.completedloan.averageInterestRate,
'detailLink':"../loanDetails/"+str(loan.id),
})
return render_to_response('allLoans.html',locals())
def loanDetails(request,loanId):
"""Display the loan details for a loanId"""
# Get the customerId and verify if the session is active.
customerId = getCustomerId(request)
loan = Loan.objects.get(id=loanId)
# Retrieve the payment list for a loan
paymentList = Payment.objects.filter(loan=loanId)
paymentDetails = []
for payment in paymentList:
paymentDetails.append({'amount':payment.amount,
'datePaid':payment.datePaid,
'type':payment.paymentType,
'merchant':payment.merchantUsed,
})
if (loan.isActive):
activeLoan = loan.activeloan
details = {'id':activeLoan.id,
'name':activeLoan.loan.name,
'loanType':activeLoan.loan.loanType,
'principal':activeLoan.loan.principal,
'totalMonths':activeLoan.loan.originalMonths,
'dateTaken':activeLoan.loan.dateTaken,
'expTermination':activeLoan.expectedDateOfTermination,
'outstandingAmount':activeLoan.outstandingLoanBalance,
'monthsLeft':activeLoan.elapsedMonths,
'interestCategory':activeLoan.loan.interestCategory,
'interestRate':activeLoan.interestRate,
'monthlyInstallment':activeLoan.monthlyInstallment,
'nextDueInstallment':activeLoan.nextInstallmentDueDate,
'prepayPenalty':activeLoan.prepaymentPenaltyRate,
'security':activeLoan.loan.security,
}
return render_to_response('activeLoanDetails.html', locals())
else:
completedLoan = loan.completedloan
details = {'id':completedLoan.loan.id,
'name':completedLoan.loan.name,
'loanType':completedLoan.loan.loanType,
'principal':completedLoan.loan.principal,
'totalMonths':completedLoan.loan.originalMonths,
'dateTaken':completedLoan.loan.dateTaken,
'dateOfCompletion':completedLoan.dateOfCompletion,
'totalAmountPaid':completedLoan.totalAmountPaid,
'interestCategory':completedLoan.loan.interestCategory,
'interestRate':completedLoan.averageInterestRate,
}
return render_to_response('completedLoanDetails.html', locals())
def payInstallment(request, loanId):
"""View for paying an installment"""
# Get the customerId and verify if the session is active.
customerId = getCustomerId(request)
if request.method == 'POST':
activeLoan = ActiveLoan.objects.get(loan__id=loanId)
# Adds the payment to Payment model
payment = Payment(amount=activeLoan.monthlyInstallment, loan=activeLoan.loan, paymentType="installment", merchantUsed="none")
payment.save()
# Updates the activeLoan or makes it a completed loan if this was the last installment.
if activeLoan.elapsedMonths + 1 == activeLoan.loan.originalMonths:
paymentList = Payment.objects.filter(loan__id=loanId)
totalAmountPaid = 0
for payment in paymentList:
totalAmountPaid += payment.amount
averageInterestRate = activeLoan.interestRate
completedLoan = CompletedLoan(loan=activeLoan.loan, totalAmountPaid=totalAmountPaid, averageInterestRate=averageInterestRate)
completedLoan.save()
activeLoan.loan.isActive = False
activeLoan.loan.save()
activeLoan.delete()
else:
activeLoan.elapsedMonths += 1
activeLoan.nextInstallmentDueDate += datetime.timedelta(days=30)
activeLoan.outstandingLoanBalance = activeLoan.computeOutstandingLoanBalance()
activeLoan.save()
return HttpResponseRedirect('/payInstallmentThanks/')
else:
try:
activeLoan = ActiveLoan.objects.get(loan__id=loanId)
except ActiveLoan.DoesNotExist:
raise Http404
dueDate = activeLoan.nextInstallmentDueDate
installment = activeLoan.monthlyInstallment
outstandingLoanBalance = activeLoan.outstandingLoanBalance
return render_to_response('payInstallment.html', locals())
def payInstallmentThanks(request):
"""
Redirects to thank you page after the payment of an installment.
"""
# Get the customerId and verify if the session is active.
customerId = getCustomerId(request)
return render_to_response('payInstallmentThanks.html',{})
def newApplication(request):
"""Files a new application."""
# Get the customerId and verify if the session is active.
customerId = getCustomerId(request)
if request.method == 'POST':
form = ApplicationForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
application = Application(name=cd["loanName"], amountAppliedFor=cd["loanAmount"], loanType=cd["loanCategory"], security=cd["security"], customer=Customer.objects.get(id=customerId), status="Active")
application.save()
return HttpResponseRedirect('/newApplicationThanks/')
else:
form = ApplicationForm()
return render_to_response('newApplication.html', locals())
def newApplicationThanks(request):
"""Thank you page after a new application request."""
# Get the customerId and verify if the session is active.
customerId = getCustomerId(request)
return render_to_response('newApplicationThanks.html')
def payPrepayment(request, loanId):
"""Prepay an amount for a loan."""
# Get the customerId and verify if the session is active.
customerId = getCustomerId(request)
try:
activeLoan = ActiveLoan.objects.get(loan__id=loanId)
except ActiveLoan.DoesNotExist:
raise Http404
loanName = activeLoan.loan.name
outstandingAmount = activeLoan.outstandingLoanBalance
if request.method == 'POST':
form = PrepaymentForm(loanId, request.POST)
if form.is_valid():
cd = form.cleaned_data
#amount = cd["prepaymentAmount"]/(1+(activeLoan.prepaymentPenaltyRate/100))
amount = cd["prepaymentAmount"]
activeLoan.outstandingLoanBalance = activeLoan.outstandingLoanBalance - amount
if activeLoan.outstandingLoanBalance != 0:
activeLoan.save()
else:
activeLoan.loan.isActive = False
activeLoan.loan.save()
paymentList = Payment.objects.filter(loan__id=loanId)
totalAmountPaid = 0
for payment in paymentList:
totalAmountPaid += payment.amount
averageInterestRate = activeLoan.interestRate
completedLoan = CompletedLoan(loan=activeLoan.loan, totalAmountPaid=totalAmountPaid, averageInterestRate=averageInterestRate)
completedLoan.save()
activeLoan.delete()
# Adds the payment to Payment model
payment = Payment(amount=amount, loan=activeLoan.loan, paymentType="prepayment", merchantUsed="none")
payment.save()
return HttpResponseRedirect('/payPrepaymentThanks/')
else:
form = PrepaymentForm(loanId, initial = {'prepaymentAmount': outstandingAmount/2})
return render_to_response('payPrepayment.html', locals())
def payPrepaymentThanks(request):
"""Thank you page after the payment of an installment."""
# Get the customerId and verify if the session is active.
customerId = getCustomerId(request)
return render_to_response('payPrepaymentThanks.html', locals())
def support(request):
"""View for filing a support request."""
# Get the customerId and verify if the session is active.
customerId = getCustomerId(request)
if request.method == 'POST':
form = SupportForm(customerId, request.POST)
if form.is_valid():
cd = form.cleaned_data
ticket = SupportTicket(loan=cd["loan"], complaintType=cd["complaintType"], complaintMessage=cd["message"], customer_id = customerId)
ticket.save()
return HttpResponseRedirect('/supportThanks/')
else:
form = SupportForm(customerId, initial={'message': 'Please enter your message here.'})
return render_to_response('support.html', locals())
def supportThanks(request):
"""Thank you page after a support request submission."""
# Get the customerId and verify if the session is active.
customerId = getCustomerId(request)
return render_to_response('supportThanks.html', locals())