Repository navigation
Expand file tree
/
Copy pathviews.py
More file actions
756 lines (646 loc) · 23.3 KB
/
Copy pathviews.py
File metadata and controls
756 lines (646 loc) · 23.3 KB
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib.auth.models import User
from projects.forms import projectForm, milestoneForm, MyForm, UserForm, StaffForm
from django.contrib.auth.decorators import user_passes_test
from django.views.decorators.csrf import ensure_csrf_cookie
from django.contrib.auth import logout, login, authenticate
from django.views.generic.edit import FormView
from datetime import datetime,date
from django.db.models import Q
from projects.models import Attachment, Project, Milestone, Staff, Allocation, Message, Invoice
import os
import json
import mimetypes
import decimal
from django.http import StreamingHttpResponse
from django.core.servers.basehttp import FileWrapper
from django.core import serializers
from itertools import chain
def send_message(request, project_id):
if request.method == "POST":
try:
data = json.loads(request.body)
except Exception as inst:
print(inst)
message = data['message']
text = message
link_id = project_id
frm = request.user
try:
project = Project.objects.get(id=link_id)
message = project.message_set.create(
time = datetime.now(),
text = text,
frm = frm,
)
mentions = data['mentions']
for user_id in mentions:
try:
user=User.objects.get(id = user_id)
except:
print("No such User")
else:
message.to.add(user)
message.save()
print(message.to.all())
message.save()
except Exception as inst:
print(inst)
return HttpResponse(status=404)
print("Create")
return HttpResponse(status=200)
return HttpResponse(status = 404)
def get_messages(request, project_id, limit= None):
try:
project = Project.objects.get(id=project_id)
except Exception as isnt:
print(inst)
return HttpResponse(status=404)
try:
limit = int(limit)
except:
limit= 30
username = request.user
user = User.objects.get(username = username)
if user.is_superuser:
messages = project.message_set.all().order_by('time')
#data = serializers.serialize('json', messages)
#return HttpResponse(data, content_type='application/json')
else:
messages = project.message_set.all().filter(Q(to = user)|Q(to=None)|Q(frm=user)).order_by('time')
if limit:
messages = messages[:limit]
try:
return render(request,'projects/messages.html',{'messages': messages})
except:
return HttpResponse("Error in template")
def person_list(request, project_id):
worker_list = []
try:
milestones = Project.objects.get(id=project_id).milestone_set.all()
except Exception as inst:
print(inst)
return HttpResponse("Not found", status=404)
for milestone in milestones:
worker_list.append( allocations(request, milestone.url_id) )
result =[]
for worker in worker_list:
result = list(chain(result, worker))
sorted_result = sorted(
result,
key=lambda instance: not instance.active)
raw_list =[]
for alloc in sorted_result:
raw_list.append({'person': alloc.person.full_name, 'milestone':alloc.milestone.title , 'active':alloc.active, 'cost':(alloc.pay_type+str(alloc.pay)) })
try:
data = json.dumps(raw_list)
except Exception as inst:
print(inst)
return HttpResponse(data, content_type='application/json')
def get_person(request, person_id):
try:
user = User.objects.get(username= person_id)
person = Staff.objects.get(user=user)
except:
print("Failed")
HttpResponse("No such person found", status= 404)
if request.GET.get("toggle", False):
#Set active
user.is_active = not user.is_active
print("Status")
user.save()
return HttpResponse(status=200)
whole = person.allocation_set.all()
total = len(whole)
#Add completed
# current = whole.filter(active = True, completed = False)
filtered = whole.filter(active = True)
# woriking = len(current)
completed = len(filtered)
failed = total - (completed)
pay_dollar=0
pay_euro=0
pay_pound=0
for job in filtered:
if job.pay_type == '$':
pay_dollar += job.pay
elif job.pay_type == u'\u00A3':
pay_pound += job.pay
elif job.pay_type == u'\u20AC':
pay_euro += job.pay
failure = whole.filter(active = False)
lost_dollar=0
lost_euro=0
lost_pound=0
for job in failure:
if job.pay_type == '$':
lost_dollar += job.pay
elif job.pay_type == u'\u00A3':
lost_pound += job.pay
elif job.pay_type == u'\u20AC':
lost_euro += job.pay
person_details = {'email': person.user.email}
person_details['full_name'] = person.full_name
person_details['active']= person.user.is_active
#person_details = {}
person_details['picture'] = str(person.picture)
person_details['contact'] = person.phone
person_details['type']= person.type
person_details['total']=total
# person_details['working']=working
person_details['completed']=completed
person_details['failed']= failed
person_details['pay_gain']= [pay_dollar, pay_euro, pay_pound]
person_details['pay_lost']= [lost_dollar, lost_euro, lost_pound]
print("here")
print(person_details)
try:
#For normal Dictionaries, Use serializer for QuerySet
data = json.dumps(person_details)
except Exception as inst:
print( inst)
print("Sending data")
return HttpResponse(data, content_type='application/json')
#person.allocation_set.all().filter(active = True)
#return HttpResponse(status=200)
def get_staff_list(max_results =0, starts_with=""):
user_list = []
staff_list = []
# print("Searching for staff", starts_with)
if starts_with:
user_list = User.objects.filter(first_name__istartswith=starts_with)
for user in user_list:
staff_list.append(Staff.objects.get(user = user))
print(staff_list)
# if max_results > 0:
# if staff_list.count() > max_results:
# staff_list = staff_list[:max_results]
print("Returning")
return staff_list
def suggest_staff(request):
staff_list = []
starts_with = ''
if request.method == 'GET':
starts_with = request.GET['suggestion']
#print("Request Recieved", starts_with)
staff_list = get_staff_list(4,starts_with)
#print("Response Ready")
data = serializers.serialize("json",staff_list)
#print( data)
return HttpResponse(data, content_type='application/json')
def allocations(request, milestone_id):
try:
milestone = Milestone.objects.get(url_id = milestone_id)
except:
return HttpResponse("No such milestone", status = 404)
allocations = milestone.allocation_set.all().order_by("-active")
return allocations
def download_file(request, path, document_root):
the_file = os.path.join(document_root,path)
#print the_file.encode('ascii', errors='backslashreplace')
filename = os.path.basename(the_file.encode('ascii', errors='backslashreplace'))
chunk_size = 8192
response = StreamingHttpResponse(FileWrapper(open(the_file), chunk_size),
content_type=mimetypes.guess_type(the_file)[0])
response['Content-Length'] = os.path.getsize(the_file)
response['Content-Disposition'] = "attachment; filename=%s" % the_file
return response
@user_passes_test(lambda u: u.is_superuser)
def projects(request, year=0,month=None):
MONTHS = {
'jan' : 0,
'feb':1,
'mar':2,
'apr':3,
'may':4,
'jun':5,
'jul':6,
'aug':7,
'sep':8,
'oct':9,
'nov':10,
'dec':11,
}
MONTH_NAMES = [
'jan',
'feb',
'mar',
'apr',
'may',
'jun',
'jul',
'aug',
'sep',
'oct',
'nov',
'dec',
]
if not year:
year = datetime.now().year
else:
year = int(year)
if month is None or month not in MONTHS:
current_month = datetime.now().month
else:
current_month = MONTHS[month]+1
projects = Project.objects.filter(start_date__month = current_month, start_date__year = year).order_by('completed','start_date')
context_dic= {}
current_month -=1
prev_month = (current_month-1)%12
next_month = (current_month+1)%12
context_dic["current_month"] = MONTH_NAMES[current_month]
if prev_month > current_month:
context_dic["prev_month"] = str(year-1) + '/' + MONTH_NAMES[prev_month]
else:
context_dic["prev_month"] = str(year) + '/' + MONTH_NAMES[prev_month]
if next_month < current_month:
context_dic["next_month"] = str(year+1) + '/' + MONTH_NAMES[next_month]
else:
context_dic["next_month"] = str(year) + '/' + MONTH_NAMES[next_month]
context_dic['projects'] = projects
if request.method == "POST":
form = projectForm(request.POST)
if form.is_valid():
project = form.save(commit=False)
project.last_updated = datetime.now()
project.save()
else:
pass
else:
form = projectForm()
context_dic['form'] = form;
return render(request, 'projects/project_list.html', context_dic)
@ensure_csrf_cookie
def milestone_page(request, project_id, mile_id):
context_dic={}
try:
project = Project.objects.get(pk=project_id)
milestone = Milestone.objects.get(project= project_id, url_id=mile_id)
except:
return HttpResponseRedirect('/projects/'+project_id)
if request.GET.get("complete", False):
milestone.completed = True;
milestone.save()
if request.GET.get("important", False):
current = milestone.important
milestone.important = not current
milestone.save()
#In case on input request
if request.method == "POST":
if 'username' in request.POST:
username = request.POST['username']
password = request.POST['password']
user = authenticate(username = username, password = password)
if user is not None:
if user.is_active:
login(request, user)
else:
pass
else:
HttpResponse("Invalid Username or Password")
elif 'name' in request.POST:
name = request.POST['name']
allocation = request.POST['allocation']
user_id = request.POST['user_id']
try:
print("Trying Allocation")
pay = int(allocation)
except:
#produce an error saying incorect field or something
pass
else:
try:
print("Trying User")
person = Staff.objects.get(user= user_id)
#user = User.objects.get(username = name)
except:
#produce an error saying incorect username or something
pass
else:
print("Found User")
pay_type = project.pay_type
try:
prev = milestone.allocation_set.get(active = True)
except:
pass
else:
prev.active = False
prev.save()
alloc = milestone.allocation_set.create(person=person,
pay= pay,
pay_type= pay_type,
active=True,
)
project.calculate_revenue()
return HttpResponseRedirect('/projects/'+project_id+"/"+mile_id)
# if request.GET.get('success', False) and not milestone.success:
# print ("In Milestone")
# project.save()
# milestone.completed = True
# milestone.save()
# #print ("Saved")
# try:
# context_dic['project'] = project;
# return HttpResponse(status=200)
# except:
# print "Couldn't respond"
#
# if request.GET.get('fail', False) and not milestone.completed:
# #print ("In Milestone")
# milestone.completed = True
# milestone.success = False
# milestone.save()
# #print ("Saved")
# try:
# #context_dic['project'] = project;
# return HttpResponse(status=200)
# except:
# print "Couldn't respond"
context_dic['project_id'] = project_id
context_dic['milestone'] = milestone
attachments = Attachment.objects.all().filter(milestone= milestone)
context_dic['attachments'] = attachments
context_dic['allocations'] = allocations(request, milestone.url_id)
context_dic['days_left'] = (milestone.deadline -date.today()).days
print(context_dic['days_left'])
return render(request, 'projects/milestone_view.html', context_dic)
def project_page(request, project_id, month=0):
context_dic = {id: 'project_id'}
try:
project = Project.objects.get(id= project_id)
except:
return HttpResponseRedirect('/')
context_dic['project'] = project;
# print project.id
if request.GET.get("success", False):
project.success = True
project.completed = True
project.completed_date= datetime.now()
project.save()
if request.GET.get("fail", False):
project.success = False
project.completed = True
project.completed_date= datetime.now()
project.save()
project.update_cost()
project.calculate_revenue();
#Delete this after checking if its still in use
if request.GET.get('click', False) and not project.completed:
project.completed= True
print(project.completed)
project.save()
try:
#context_dic['project'] = project;
return HttpResponse(status=200)
except:
print "Couldn't respond"
milestones = Milestone.objects.filter(project=project_id).order_by("completed", "start_date")
context_dic['milestones'] = milestones
return milestone_form(request, project_id, context_dic)
def milestone_form(request, project_id, context_dic={}):
project = context_dic["project"]
if request.method == "POST":
form2 = milestoneForm(request.POST)
form = MyForm(request.POST, request.FILES)
form2.data['project'] = project.id
if form2.is_valid():
form2.save(commit= False)
data = form2.cleaned_data
#print data['title']
#print data['project'], "DATA"
form2.save()
project.update_cost()
current = Milestone.objects.get(title=data['title'], project = project_id)
print current
if form.is_valid():
for f in request.FILES.getlist('file'):
Attachment.objects.create(milestone=current, file=f)
return HttpResponseRedirect('/projects/'+project_id)
else:
print form2.errors
else:
form2 = milestoneForm()
form = MyForm()
print(project.last_updated)
context_dic['updated'] = project.last_updated.isoformat()
context_dic['form'] = form
context_dic['form2'] = form2
return render(request,'projects/project_view.html', context_dic)
@user_passes_test(lambda u: u.is_superuser)
def staff(request):
staff = Staff.objects.all()
if request.method == "POST":
print request.FILES
user_form = UserForm(request.POST)
staff_form = StaffForm(request.POST)
if user_form.is_valid() and staff_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.save()
staff = staff_form.save(commit=False)
staff.user = user
if 'picture' in request.FILES:
staff.picture = request.FILES['picture']
staff.save()
print "Saved"
return HttpResponseRedirect('/projects/staff/')
else:
print user_form.errors, staff_form.errors
else:
user_form = UserForm()
staff_form = StaffForm()
return render(request, "projects/staff.html", {'staff': staff, 'user_form': user_form, 'staff_form': staff_form})
@user_passes_test(lambda u: u.is_superuser)
def analytics(request, year=0, month=None):
MONTHS = {
'jan' : 0,
'feb':1,
'mar':2,
'apr':3,
'may':4,
'jun':5,
'jul':6,
'aug':7,
'sep':8,
'oct':9,
'nov':10,
'dec':11,
}
MONTH_NAMES = [
'jan',
'feb',
'mar',
'apr',
'may',
'jun',
'jul',
'aug',
'sep',
'oct',
'nov',
'dec',
]
if not year:
year = datetime.now().year
else:
year = int(year)
if month is None or month not in MONTHS:
current_month = datetime.now().month
else:
current_month = MONTHS[month]+1
prev_month = ((current_month-2)%12)+1 #Current month is one ahead of the ordinal month list so prev month is 2 behind is actual position; additional 1 to convert it back to cardinal
print("prev month", prev_month)
if prev_month > current_month:
prev_year = year-1
else:
prev_year = year
projects_current = Project.objects.filter(start_date__month = current_month, start_date__year = year).order_by('completed','start_date')
projects_prev = Project.objects.filter(start_date__month = prev_month, start_date__year = prev_year).order_by('completed','start_date')
context_dic={}
current_month -=1
prev_month -=1
next_month = (current_month+1)%12
context_dic["current_month"] = MONTH_NAMES[current_month]
context_dic["prev_month"] = str(prev_year) + '/' + MONTH_NAMES[prev_month]
if next_month < current_month:
context_dic["next_month"] = str(year+1) + '/' + MONTH_NAMES[next_month]
else:
context_dic["next_month"] = str(year) + '/' + MONTH_NAMES[next_month]
revenue= 0
profit=0
for project in projects_current:
revenue += project.cost
profit += project.revenue
context_dic['revenue'] =float(revenue)/ 100
context_dic['profit'] = float(profit)/100
current_growth = len(projects_current.filter(completed=True))
prev_growth = len(projects_prev.filter(completed=True))
current_activity = len(projects_current)
prev_activity = len(projects_prev)
try:
context_dic['activity'] = (decimal.Decimal(current_activity-prev_activity)/decimal.Decimal(current_activity))*100
#except DivisionByZero:
except:
context_dic['activity'] = 0
try:
context_dic['growth'] = (decimal.Decimal(current_growth-prev_growth)/decimal.Decimal(current_growth))*100
except:
#except DivisionByZero:
context_dic['growth'] = 0
return render(request, 'projects/analytics.html', context_dic)
def logout_view(request):
print("Recieved")
logout(request)
return HttpResponseRedirect('/')
@user_passes_test(lambda u: u.is_superuser)
def invoice_page(request):
pass
@user_passes_test(lambda u: u.is_superuser)
def invoice_list(request):
invoices = Invoice.objects.all()
return render(request, 'projects/invoice_list.html', {'invoices': invoices})
@user_passes_test(lambda u: u.is_superuser)
def invoice(request, project_id):
project = Project.objects.get(id=project_id)
if request.method == "POST":
data= []
total = 0
#print(request.POST)
address = request.POST['address']
try:
discount = int(request.POST["discount"])
except ValueError:
discount = 0
invoice = project.invoice_set.create(
address = address,
discount=discount,
total = 0,
)
for key in request.POST:
try:
x = project.milestone_set.get(title = key)
except:
pass
else:
x.paid = True
x.save()
try:
qty = int(request.POST[key+"_qty"])
except ValueError:
qty = 1
total += (x.cost * qty)
invoice.details_set.create(title = x.title,
desc = x.description[0:20],
cost = x.cost,
type = project.pay_type,
qty= qty)
invoice.total = total
invoice.save()
name = generate(invoice)
chunk_size = 8192
response = StreamingHttpResponse(FileWrapper(open(name+".pdf"), chunk_size),
content_type=mimetypes.guess_type(name+".pdf"))
response['Content-Length'] = os.path.getsize(name+".pdf")
response['Content-Disposition'] = "attachment; filename=%s" % (name+".pdf")
return response
else:
unpaid = project.milestone_set.all().filter(paid=False)
return render(request,'projects/invoice.html', {'unpaid':unpaid, 'project_id':project.id})
def generate(invoice):
print ("Generating PDF")
from reportlab.pdfgen import canvas
from reportlab.lib.units import inch
from reportlab.lib.pagesizes import letter
print(invoice.project.id)
project = Project.objects.get(id=invoice.project.id)
name = project.client
email = project.client_mail
addr = invoice.address
total = invoice.total
discount = invoice.discount
data = invoice.details_set.all()
c = canvas.Canvas(name+".pdf", pagesize = letter)
c.drawString(1*inch, 9*inch, "Sofza")
c.drawString(1*inch, 8.7*inch, "Raised By")
c.drawString(1*inch, 8.4*inch, "Haris Mehmood")
c.drawString(1*inch, 8.1*inch, "Invoice Payment Notice")
c.drawString(4*inch, 9*inch, "Towards")
c.drawString(4*inch, 8.7*inch, name)
c.drawString(4*inch, 8.4*inch, email)
c.drawString(4*inch, 8.1*inch, addr)
c.line(0, 7.7*inch, 8*inch, 7.7*inch)
point = 7.5
c.setfont("Courier-Bold", 10)
c.drawString(1*inch, point*inch, 'Title')
c.drawString(3*inch, point*inch, 'Title')
c.drawString(5*inch, point*inch, 'Cost')
c.drawString(6*inch, point*inch, 'Qty')
c.drawString(7*inch, point*inch, 'Amount')
point -= 0.1
c.line(0, point*inch, 8*inch, point*inch)
c.setfont("Courier", 10)
for x in data:
point -= 0.2
if point < 1:
pass #Handle page overflow
c.drawString(1*inch, point*inch, x.title)
c.drawString(3*inch, point*inch, x.desc)
c.drawString(5*inch, point*inch, x.type + str(x.cost))
c.drawString(6*inch, point*inch, str(x.qty))
c.drawString(7*inch, point*inch, x.type+str(x.qty *x.cost ))
point -= 0.1
c.line(0, point*inch, 8*inch, point*inch)
point -= 0.3
c.setfont("Courier-Bold", 10)
c.drawString(1*inch, point*inch, "Total: "+x.type +str(total))
point -= 0.3
if discount:
c.drawString(1*inch, point*inch, "Discount: "+x.type + str(discount))
point -= 0.3
total-=discount
c.drawString(1*inch, point*inch, "Due amount: "+x.type +str(total))
point -= 0.3
c.save()
return name
#x_max = 8.3", y_max = 11.7"