summaryrefslogtreecommitdiff
path: root/sstreasury/views.py
blob: 9b1da591d98618153418d9383a287693697ca6bc (plain)
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
1#    Society Self-Service
2#    Copyright © 2018–2020  Yingtong Li (RunasSudo)
3#
4#    This program is free software: you can redistribute it and/or modify
5#    it under the terms of the GNU Affero General Public License as published by
6#    the Free Software Foundation, either version 3 of the License, or
7#    (at your option) any later version.
8#
9#    This program is distributed in the hope that it will be useful,
10#    but WITHOUT ANY WARRANTY; without even the implied warranty of
11#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12#    GNU Affero General Public License for more details.
13#
14#    You should have received a copy of the GNU Affero General Public License
15#    along with this program.  If not, see <https://www.gnu.org/licenses/>.
16
17from django.contrib.auth.decorators import login_required
18from django.contrib.auth.models import User
19from django.core.exceptions import PermissionDenied, ValidationError
20from django.core.validators import validate_email
21
22from django.conf import settings
23from django.db import transaction
24from django.http import HttpResponse
25from django.shortcuts import render, redirect
26from django.urls import reverse
27from django.utils import timezone
28from django.views import generic
29
30from . import aba
31from . import models
32from . import xero
33from ssmain.email import Emailer
34
35from datetime import datetime
36import functools
37import io
38import itertools
39import json
40import zipfile
41
42# HELPER DECORATORS
43
44def uses_budget(viewfunc):
45	@functools.wraps(viewfunc)
46	def func(request, id):
47		budget = models.Budget.objects.get(id=id)
48		revision = budget.budgetrevision_set.reverse()[0]
49		return viewfunc(request, budget, revision)
50	return func
51
52def budget_viewable(viewfunc):
53	@functools.wraps(viewfunc)
54	def func(request, budget, revision):
55		if not revision.can_view(request.user):
56			raise PermissionDenied
57		return viewfunc(request, budget, revision)
58	return func
59
60def budget_editable(viewfunc):
61	@functools.wraps(viewfunc)
62	def func(request, budget, revision):
63		if not revision.can_edit(request.user):
64			raise PermissionDenied
65		return viewfunc(request, budget, revision)
66	return func
67
68def uses_claim(viewfunc):
69	@functools.wraps(viewfunc)
70	def func(request, id):
71		claim = models.ReimbursementClaim.objects.get(id=id)
72		return viewfunc(request, claim)
73	return func
74
75def claim_viewable(viewfunc):
76	@functools.wraps(viewfunc)
77	def func(request, claim):
78		if not claim.can_view(request.user):
79			raise PermissionDenied
80		return viewfunc(request, claim)
81	return func
82
83def claim_editable(viewfunc):
84	@functools.wraps(viewfunc)
85	def func(request, claim):
86		if not claim.can_edit(request.user):
87			raise PermissionDenied
88		return viewfunc(request, claim)
89	return func
90
91# HELPER FUNCTIONS
92
93class FormValidationError(Exception):
94	def __init__(self, data, errors):
95		super().__init__(self)
96		self.data = data
97		self.errors = errors
98
99def revision_from_form(budget, revision, form):
100	errors = []
101	
102	revision.budget = budget
103	
104	if form['name']:
105		if len(form['name']) > 100:
106			errors.append('Title must be at most 100 characters')
107		revision.name = form['name']
108	else:
109		errors.append('A title must be specified')
110	
111	if form['date']:
112		try:
113			form_date = timezone.make_aware(datetime.strptime(form['date'], '%Y-%m-%d'))
114			revision.date = form_date
115		except ValueError:
116			errors.append('Due date is not a valid date')
117			revision.date = None
118	else:
119		errors.append('A due date must be specified')
120	
121	if form['event_dt']:
122		try:
123			form_event_dt = timezone.make_aware(datetime.strptime(form['event_dt'], '%Y-%m-%d %H:%M'))
124			revision.event_dt = form_event_dt
125		except ValueError:
126			errors.append('Event date/time is not a valid date-time')
127			revision.event_dt = None
128	else:
129		revision.event_dt = None
130	
131	if form['event_attendees']:
132		if len(form['event_attendees']) > 20:
133			errors.append('Event attendees must be at most 20 characters')
134		revision.event_attendees = form['event_attendees']
135	else:
136		revision.event_attendees = None
137	
138	if form['contributors']:
139		contributors = form['contributors'].split('\n')
140		try:
141			for contributor in contributors:
142				validate_email(contributor.strip())
143		except ValidationError:
144			errors.append('Contributors contains invalid data – type only valid email addresses, one per line')
145	else:
146		contributors = []
147	
148	revision.comments = form['comments']
149	revision.revenue = json.loads(form['revenue'])
150	revision.revenue_comments = form['revenue_comments']
151	revision.expense = json.loads(form['expense'])
152	revision.expense_comments = form['expense_comments']
153	revision.expense_no_emergency_fund = True if form.get('expense_no_emergency_fund', False) else False
154	
155	if errors:
156		raise FormValidationError(revision, errors)
157	
158	revision.save()
159	
160	for contributor in contributors:
161		try:
162			user = User.objects.get(email=contributor.strip())
163		except User.DoesNotExist:
164			user = User.objects.create_user(contributor.strip().split('@')[0], contributor.strip())
165		revision.contributors.add(user)
166	
167	revision.save()
168	
169	return revision
170
171def claim_from_form(claim, form, files):
172	claim.purpose = form['purpose']
173	claim.date = form['date'] if form['date'] else None
174	claim.budget_id = form['budget_id']
175	
176	claim.comments = form['comments']
177	claim.items = json.loads(form['items'])
178	
179	claim.payee_name = form['payee_name']
180	claim.payee_bsb = form['payee_bsb']
181	claim.payee_account = form['payee_account']
182	
183	claim.save()
184	
185	if files:
186		for f in files.getlist('upload_file'):
187			claim_receipt = models.ClaimReceipt()
188			claim_receipt.claim = claim
189			claim_receipt.uploaded_file = f
190			claim_receipt.save()
191	
192	return claim
193
194# INDEX VIEW
195
196@login_required
197def index(request):
198	return render(request, 'sstreasury/index.html')
199
200# BUDGET VIEWS
201
202@login_required
203def budget_list(request):
204	budgets_action = []
205	budgets_open = []
206	budgets_closed = []
207	
208	for budget in models.Budget.objects.all():
209		revision = budget.budgetrevision_set.reverse()[0]
210		state = models.BudgetState(revision.state)
211		
212		group = None
213		
214		if request.user.groups.filter(name='Treasury').exists() and state == models.BudgetState.AWAIT_REVIEW:
215			group = budgets_action
216		elif request.user.groups.filter(name='Secretary').exists() and state == models.BudgetState.ENDORSED:
217			group = budgets_action
218		elif request.user.groups.filter(name='Committee').exists() and state == models.BudgetState.ENDORSED:
219			group = budgets_action
220		elif request.user in revision.contributors.all():
221			if state in [models.BudgetState.DRAFT, models.BudgetState.RESUBMIT]:
222				group = budgets_action
223			elif state in [models.BudgetState.AWAIT_REVIEW, models.BudgetState.ENDORSED]:
224				group = budgets_open
225			else:
226				group = budgets_closed
227		elif request.user.groups.filter(name='Treasury').exists() or request.user.groups.filter(name='Secretary').exists() or request.user.groups.filter(name='Committee').exists():
228			if state == models.BudgetState.APPROVED:
229				group = budgets_closed
230			else:
231				group = budgets_open
232		
233		if group is not None:
234			group.append(revision)
235	
236	return render(request, 'sstreasury/budget_list.html', {
237		'budgets_action': budgets_action,
238		'budgets_open': budgets_open,
239		'budgets_closed': budgets_closed
240	})
241
242@login_required
243@uses_budget
244def budget_view(request, budget, revision):
245	if 'revision' in request.GET:
246		revision = budget.budgetrevision_set.get(id=int(request.GET['revision']))
247	
248	if not revision.can_view(request.user):
249		raise PermissionDenied
250	
251	history = list(itertools.chain(budget.budgetrevision_set.all(), revision.budget.budgetcomment_set.all()))
252	history.sort(key=lambda x: x.time, reverse=True)
253	
254	return render(request, 'sstreasury/budget_view.html', {
255		'revision': revision,
256		'history': history,
257		'is_latest': 'revision' not in request.GET
258	})
259
260@login_required
261@uses_budget
262def budget_print(request, budget, revision):
263	if 'revision' in request.GET:
264		revision = budget.budgetrevision_set.get(id=int(request.GET['revision']))
265	
266	if not revision.can_view(request.user):
267		raise PermissionDenied
268	
269	return render(request, 'sstreasury/budget_print.html', {
270		'revision': revision,
271		'is_latest': 'revision' not in request.GET
272	})
273
274@login_required
275def budget_new(request):
276	if request.method == 'POST':
277		try:
278			with transaction.atomic():
279				budget = models.Budget()
280				budget.save()
281				revision = models.BudgetRevision()
282				revision.author = request.user
283				revision.time = timezone.now()
284				revision.action = models.BudgetAction.CREATE.value
285				revision.state = models.BudgetState.DRAFT.value
286				revision = revision_from_form(budget, revision, request.POST)
287		except FormValidationError as form_error:
288			return render(request, 'sstreasury/budget_edit.html', {
289				'revision': form_error.data,
290				'contributors': request.POST['contributors'],
291				'errors': form_error.errors
292			})
293		
294		if request.POST['submit'] == 'Save':
295			return redirect(reverse('budget_view', kwargs={'id': budget.id}))
296		else:
297			return redirect(reverse('budget_edit', kwargs={'id': budget.id}))
298	else:
299		budget = models.Budget()
300		revision = models.BudgetRevision()
301		revision.budget = budget
302		
303		return render(request, 'sstreasury/budget_edit.html', {
304			'revision': revision,
305			'contributors': request.user.email,
306			'errors': []
307		})
308
309@login_required
310@uses_budget
311@budget_editable
312def budget_edit(request, budget, revision):
313	if request.method == 'POST':
314		if request.POST['submit'] == 'Delete':
315			budget.delete()
316			return redirect(reverse('budget_list'))
317		
318		try:
319			with transaction.atomic():
320				new_revision = models.BudgetRevision()
321				new_revision.author = request.user
322				new_revision.time = timezone.now()
323				new_revision.action = models.BudgetAction.EDIT.value
324				new_revision.state = revision.state
325				new_revision = revision_from_form(budget, new_revision, request.POST)
326		except FormValidationError as form_error:
327			return render(request, 'sstreasury/budget_edit.html', {
328				'revision': form_error.data,
329				'contributors': request.POST['contributors'],
330				'errors': form_error.errors
331			})
332		
333		if request.POST['submit'] == 'Save':
334			return redirect(reverse('budget_view', kwargs={'id': budget.id}))
335		else:
336			return redirect(reverse('budget_edit', kwargs={'id': budget.id}))
337	else:
338		return render(request, 'sstreasury/budget_edit.html', {
339			'revision': revision,
340			'contributors': '\n'.join(revision.contributors.all().values_list('email', flat=True)),
341			'errors': []
342		})
343
344@login_required
345@uses_budget
346@budget_viewable
347def budget_action(request, budget, revision):
348	actions = request.POST['action'].split(',')
349	
350	if 'Comment' in actions and request.POST.get('comment', None):
351		with transaction.atomic():
352			comment = models.BudgetComment()
353			comment.budget = budget
354			comment.author = request.user
355			comment.time = timezone.now()
356			comment.content = request.POST['comment']
357			comment.save()
358			
359			emailer = Emailer()
360			for user in User.objects.filter(groups__name='Treasury'):
361				if user != request.user:
362					emailer.send_mail([user.email], 'New comment on budget: {} (BU-{})'.format(revision.name, budget.id), 'sstreasury/email/budget_commented.md', {'revision': revision, 'comment': comment})
363			for user in revision.contributors.all():
364				if user != request.user:
365					emailer.send_mail([user.email], 'New comment on budget: {} (BU-{})'.format(revision.name, budget.id), 'sstreasury/email/budget_commented.md', {'revision': revision, 'comment': comment})
366	
367	if 'Submit' in actions:
368		if not revision.can_submit(request.user):
369			raise PermissionDenied
370		
371		with transaction.atomic():
372			revision.update_state(request.user, models.BudgetState.AWAIT_REVIEW)
373			
374			emailer = Emailer()
375			for user in User.objects.filter(groups__name='Treasury'):
376				emailer.send_mail([user.email], 'Action required: Budget submitted: {} (BU-{})'.format(revision.name, budget.id), 'sstreasury/email/budget_submitted_treasurer.md', {'revision': revision})
377			for user in revision.contributors.all():
378				emailer.send_mail([user.email], 'Budget submitted: {} (BU-{})'.format(revision.name, budget.id), 'sstreasury/email/budget_submitted_drafter.md', {'revision': revision})
379	
380	if 'Withdraw' in actions:
381		if not revision.can_withdraw(request.user):
382			raise PermissionDenied
383		
384		with transaction.atomic():
385			revision.update_state(request.user, models.BudgetState.DRAFT)
386	
387	if 'Endorse' in actions:
388		if not revision.can_endorse(request.user):
389			raise PermissionDenied
390		
391		with transaction.atomic():
392			revision.update_state(request.user, models.BudgetState.ENDORSED)
393			
394			emailer = Emailer()
395			for user in User.objects.filter(groups__name='Secretary'):
396				emailer.send_mail([user.email], 'Action required: Budget endorsed: {} (BU-{})'.format(revision.name, budget.id), 'sstreasury/email/budget_endorsed_secretary.md', {'revision': revision})
397			for user in revision.contributors.all():
398				emailer.send_mail([user.email], 'Budget endorsed, awaiting committee approval: {} (BU-{})'.format(revision.name, budget.id), 'sstreasury/email/budget_endorsed_drafter.md', {'revision': revision})
399	
400	if 'Return' in actions:
401		if not revision.can_return(request.user):
402			raise PermissionDenied
403		
404		with transaction.atomic():
405			revision.update_state(request.user, models.BudgetState.RESUBMIT)
406			
407			emailer = Emailer()
408			for user in revision.contributors.all():
409				emailer.send_mail([user.email], 'Action required: Budget returned for re-drafting: {} (BU-{})'.format(revision.name, budget.id), 'sstreasury/email/budget_returned.md', {'revision': revision})
410	
411	if 'Approve' in actions:
412		if not revision.can_approve(request.user):
413			return PermissionDenied
414		
415		with transaction.atomic():
416			revision.update_state(request.user, models.BudgetState.APPROVED)
417			
418			emailer = Emailer()
419			for user in revision.contributors.all():
420				emailer.send_mail([user.email], 'Budget approved: {} (BU-{})'.format(revision.name, budget.id), 'sstreasury/email/budget_approved.md', {'revision': revision})
421	
422	if 'CmteReturn' in actions:
423		if not revision.can_cmtereturn(request.user):
424			return PermissionDenied
425		
426		with transaction.atomic():
427			revision.update_state(request.user, models.BudgetState.RESUBMIT)
428			
429			emailer = Emailer()
430			for user in revision.contributors.all():
431				emailer.send_mail([user.email], 'Action required: Budget returned for re-drafting: {} (BU-{})'.format(revision.name, budget.id), 'sstreasury/email/budget_returned_committee.md', {'revision': revision})
432	
433	return redirect(reverse('budget_view', kwargs={'id': budget.id}))
434
435@login_required
436def claim_list(request):
437	claims_action = []
438	claims_open = []
439	claims_closed = []
440	
441	for claim in models.ReimbursementClaim.objects.all():
442		state = models.ClaimState(claim.state)
443		
444		group = None
445		
446		if request.user.groups.filter(name='Treasury').exists() and state in [models.ClaimState.AWAIT_REVIEW, models.ClaimState.APPROVED]:
447			group = claims_action
448		elif request.user == claim.author:
449			if state in [models.ClaimState.DRAFT, models.ClaimState.RESUBMIT]:
450				group = claims_action
451			elif state in [models.ClaimState.AWAIT_REVIEW, models.ClaimState.APPROVED]:
452				group = claims_open
453			else:
454				group = claims_closed
455		elif request.user.groups.filter(name='Treasury').exists():
456			if state == models.ClaimState.PAID:
457				group = claims_closed
458			else:
459				group = claims_open
460		
461		if group is not None:
462			group.append(claim)
463	
464	return render(request, 'sstreasury/claim_list.html', {
465		'claims_action': claims_action,
466		'claims_open': claims_open,
467		'claims_closed': claims_closed
468	})
469
470@login_required
471def claim_new(request):
472	if request.method == 'POST':
473		with transaction.atomic():
474			claim = models.ReimbursementClaim()
475			claim.author = request.user
476			claim.time = timezone.now()
477			claim.state = models.BudgetState.DRAFT.value
478			claim = claim_from_form(claim, request.POST, request.FILES)
479			
480			claim_history = models.ClaimHistory()
481			claim_history.claim = claim
482			claim_history.author = request.user
483			claim_history.state = claim.state
484			claim_history.time = timezone.now()
485			claim_history.action = models.ClaimAction.CREATE.value
486			claim_history.save()
487		
488		if request.POST['submit'] == 'Save':
489			return redirect(reverse('claim_view', kwargs={'id': claim.id}))
490		else:
491			return redirect(reverse('claim_edit', kwargs={'id': claim.id}))
492		pass
493	else:
494		claim = models.ReimbursementClaim()
495		claim.author = request.user
496		
497		return render(request, 'sstreasury/claim_edit.html', {
498			'claim': claim
499		})
500
501@login_required
502@uses_claim
503@claim_viewable
504def claim_view(request, claim):
505	history = list(itertools.chain(claim.claimhistory_set.all(), claim.claimcomment_set.all()))
506	history.sort(key=lambda x: x.time, reverse=True)
507	
508	budget = None
509	if claim.budget_id:
510		try:
511			budget = models.Budget.objects.get(id=claim.budget_id.split('-')[-1])
512		except models.Budget.DoesNotExist:
513			budget = None
514	
515	return render(request, 'sstreasury/claim_view.html', {
516		'claim': claim,
517		'budget': budget,
518		'history': history
519	})
520
521@login_required
522@uses_claim
523@claim_viewable
524def claim_print(request, claim):
525	budget = None
526	if claim.budget_id:
527		try:
528			budget = models.Budget.objects.get(id=claim.budget_id.split('-')[-1])
529		except models.Budget.DoesNotExist:
530			budget = None
531	
532	return render(request, 'sstreasury/claim_print.html', {
533		'claim': claim,
534		'budget': budget
535	})
536
537@login_required
538@uses_claim
539@claim_editable
540def claim_edit(request, claim):
541	if request.method == 'POST':
542		if request.POST['submit'].startswith('DeleteFile'):
543			file_id = int(request.POST['submit'][10:])
544			
545			claim_receipt = models.ClaimReceipt.objects.get(id=file_id)
546			if claim_receipt.claim != claim:
547				raise PermissionDenied
548			
549			claim_receipt.delete()
550			claim_receipt.uploaded_file.delete(save=False)
551			
552			return redirect(reverse('claim_edit', kwargs={'id': claim.id}))
553		
554		if request.POST['submit'] == 'Delete':
555			claim.delete()
556			return redirect(reverse('claim_list'))
557		
558		with transaction.atomic():
559			claim = claim_from_form(claim, request.POST, request.FILES)
560			
561			claim_history = models.ClaimHistory()
562			claim_history.claim = claim
563			claim_history.author = request.user
564			claim_history.state = claim.state
565			claim_history.time = timezone.now()
566			claim_history.action = models.ClaimAction.EDIT.value
567			claim_history.save()
568		
569		if request.POST['submit'] == 'Save':
570			return redirect(reverse('claim_view', kwargs={'id': claim.id}))
571		else:
572			return redirect(reverse('claim_edit', kwargs={'id': claim.id}))
573	else:
574		return render(request, 'sstreasury/claim_edit.html', {
575			'claim': claim
576		})
577
578@login_required
579@uses_claim
580@claim_editable
581def claim_action(request, claim):
582	actions = request.POST['action'].split(',')
583	
584	if 'Comment' in actions and request.POST.get('comment', None):
585		with transaction.atomic():
586			comment = models.ClaimComment()
587			comment.claim = claim
588			comment.author = request.user
589			comment.time = timezone.now()
590			comment.content = request.POST['comment']
591			comment.save()
592			
593			emailer = Emailer()
594			for user in User.objects.filter(groups__name='Treasury'):
595				if user != request.user:
596					emailer.send_mail([user.email], 'New comment on reimbursement claim: {} (RE-{})'.format(claim.purpose, claim.id), 'sstreasury/email/claim_commented.md', {'claim': claim, 'comment': comment})
597			if comment.author != request.user:
598				emailer.send_mail([comment.author], 'New comment on reimbursement claim: {} (RE-{})'.format(revision.name, claim.id), 'sstreasury/email/claim_commented.md', {'claim': claim, 'comment': comment})
599	
600	if 'Submit' in actions:
601		if not claim.can_submit(request.user):
602			raise PermissionDenied
603		
604		with transaction.atomic():
605			claim.update_state(request.user, models.ClaimState.AWAIT_REVIEW)
606			
607			emailer = Emailer()
608			for user in User.objects.filter(groups__name='Treasury'):
609				emailer.send_mail([user.email], 'Action required: Reimbursement claim submitted: {} (RE-{})'.format(claim.purpose, claim.id), 'sstreasury/email/claim_submitted_treasurer.md', {'claim': claim})
610			emailer.send_mail([claim.author.email], 'Reimbursement claim submitted: {} (RE-{})'.format(claim.purpose, claim.id), 'sstreasury/email/claim_submitted_drafter.md', {'claim': claim})
611	
612	if 'Withdraw' in actions:
613		if not claim.can_withdraw(request.user):
614			raise PermissionDenied
615		
616		with transaction.atomic():
617			claim.update_state(request.user, models.ClaimState.DRAFT)
618	
619	if 'Approve' in actions:
620		if not claim.can_approve(request.user):
621			raise PermissionDenied
622		
623		with transaction.atomic():
624			claim.update_state(request.user, models.ClaimState.APPROVED)
625			
626			emailer = Emailer()
627			emailer.send_mail([claim.author.email], 'Claim approved, awaiting payment: {} (RE-{})'.format(claim.purpose, claim.id), 'sstreasury/email/claim_approved.md', {'claim': claim})
628	
629	if 'Return' in actions:
630		if not claim.can_approve(request.user):
631			raise PermissionDenied
632		
633		with transaction.atomic():
634			claim.update_state(request.user, models.ClaimState.RESUBMIT)
635			
636			emailer = Emailer()
637			emailer.send_mail([claim.author.email], 'Action required: Reimbursement claim returned for re-drafting: {} (RE-{})'.format(claim.purpose, claim.id), 'sstreasury/email/claim_returned.md', {'claim': claim})
638	
639	return redirect(reverse('claim_view', kwargs={'id': claim.id}))
640
641@login_required
642def claim_processing(request):
643	if not request.user.groups.filter(name='Treasury').exists():
644		raise PermissionDenied
645	
646	if request.method == 'POST':
647		if request.POST['action'] == 'Export':
648			claims = models.ReimbursementClaim.objects.filter(state=models.ClaimState.APPROVED.value).all()
649			claims = [c for c in claims if request.POST.get('claim_{}'.format(c.id), False)]
650			
651			aba_file = io.BytesIO()
652			
653			aba.write_descriptive(aba_file, bank_name=settings.ABA_BANK_NAME, user_name=settings.ABA_USER_NAME, bank_code=settings.ABA_BANK_CODE, description='Reimburse', date=timezone.now())
654			
655			for claim in claims:
656				aba.write_detail(aba_file, dest_bsb=claim.payee_bsb, dest_account=claim.payee_account, cents=claim.get_total()*100, dest_name=claim.payee_name, reference='RE-{}'.format(claim.id), src_bsb=settings.ABA_SRC_BSB, src_account=settings.ABA_SRC_ACC, src_name=settings.ABA_USER_NAME)
657			
658			aba.write_total(aba_file, credit_cents=sum(c.get_total() for c in claims)*100, num_detail_records=len(claims))
659			aba_file.flush()
660			
661			response = HttpResponse(aba_file.getvalue(), content_type='text/plain')
662			response['Content-Disposition'] = 'attachment; filename="claims.aba"'
663			return response
664		
665		if request.POST['action'] == 'ExportXero':
666			claims = models.ReimbursementClaim.objects.filter(state=models.ClaimState.APPROVED.value).all()
667			claims = [c for c in claims if request.POST.get('claim_{}'.format(c.id), False)]
668			
669			# Export CSV
670			with io.StringIO() as csv_file:
671				csv_writer = xero.new_writer(csv_file)
672				for claim in claims:
673					xero.write_claim(csv_writer, claim)
674				
675				# Export resources to ZIP
676				with io.BytesIO() as zip_file_bytes:
677					with zipfile.ZipFile(zip_file_bytes, 'w') as zip_file:
678						zip_file.writestr('claims.csv', csv_file.getvalue())
679						
680						for claim in claims:
681							for claim_receipt in claim.claimreceipt_set.all():
682								with claim_receipt.uploaded_file.open() as f:
683									zip_file.writestr('RE-{}/{}'.format(claim.id, claim_receipt.uploaded_file.name.split('/')[-1]), f.read())
684					
685					response = HttpResponse(zip_file_bytes.getvalue(), content_type='application/zip')
686			response['Content-Disposition'] = 'attachment; filename="claims.zip"'
687			return response
688		
689		if request.POST['action'] == 'Pay':
690			claims = models.ReimbursementClaim.objects.filter(state=models.ClaimState.APPROVED.value).all()
691			claims = [c for c in claims if request.POST.get('claim_{}'.format(c.id), False)]
692			
693			for claim in claims:
694				with transaction.atomic():
695					claim.update_state(request.user, models.ClaimState.PAID)
696					
697					emailer = Emailer()
698					emailer.send_mail([claim.author.email], 'Claim paid: {} (RE-{})'.format(claim.purpose, claim.id), 'sstreasury/email/claim_paid.md', {'claim': claim})
699	
700	claims = models.ReimbursementClaim.objects.filter(state=models.ClaimState.APPROVED.value).all()
701	
702	return render(request, 'sstreasury/claim_processing.html', {
703		'claims': claims
704	})
Contact (issues, pull requests, etc.) at git@yingtongli.me. Generated by cgit.