Files
PyRIGS/RIGS/finance.py
Arona Jones 2bf0175786 Toolchain/Dependency Upgrade (#418)
* Upgrade to heroku-20 stack

* Move some gulp deps to dev rather than prod

* npm upgrade

* Fix audit time check in asset audit test

* Attempt at parallelising tests where possible

* Add basic calendar button test

Mainly to pickup on FullCalendar loading errors

* Upgrade python deps

* Tends to help if I push valid yaml

* You valid now?

* Fix whoops in requirements.txt

* Change python ver

* Define service in coveralls task

* Run parallelised RIGS tests as one matrix job

* Update python version in tests

* Cache python dependencies

Should majorly speedup parallelillelelised testing

* Purge old vagrant config

* No Ruby compass bodge, no need for rubocop!

* Purge old .idea config

* Switch to gh-a artifact uploading instead of imgur 'hack'

For test failure screenshots. Happy now @mattysmith22? ;p

* Oops, remove unused import

* Exclude tests from the coverage stats

Seems to be artifically deflating our stats

* Refactor asset audit tests with better selectors

Also fixed a silly title error with the modal

* Add title checking to the slightly insane assets test

* Fix unauth test to not just immediately pass out

* Upload failure screenshots as individual artifacts not a zip

Turns out I can't unzip things from my phone, which is a pain

* Should fix asset test on CI

* What about this?

* What about this?

Swear I spend my life jiggerypokerying the damn test suite...

* Does this help the coverage be less weird?

* Revert "Does this help the coverage be less weird?"

This reverts commit 39ab9df836.

* Use pytest as our test runner for better parallelism

Also rewrote some asset tests to be in the pytest style. May do some more. Some warnings cleaned up in the process.

* Bah, codestyle

* Oops, remove obsolete if check

* Fix screenshot uploading on CI (again)

* Try this way of parallel coverage

* Add codeclimate maintainability badge

* Remove some unused gulp dependencies

* Run asset building serverside

* Still helps if I commit valid YAML

* See below

* Different approach to CI dependencies

* Exclude node_modules from codestyle

* Does this work?

* Parallel parallel builds were giving me a headache, try this

* Update codeclimate settings, purge some config files

* Well the YAML was *syntactically* valid....

* Switch back to old coveralls method

* Fix codeclimate config, mark 2

* Attempt to bodge asset test

* Oops, again

Probably bedtime..

* Might fix heroku building

* Attempt #2 at fixing heroku

* Belt and braces approach to coverage

* Github, you need a Actions YAML validator!

* Might fix actions?

* Try ignoring some third party deprecation warnings

* Another go at making coverage show up

* Some template cleanup

* Minor python cleanup

* Import optimisation

* Revert "Minor python cleanup"

This reverts commit 6a4620a2e5.

* Add format arg to coverage command

* Ignore test directories from Heroku slug

* Maybe this works to purge deps postbuild

* Bunch of test refactoring

* Restore signals import, screw you import optimisation

* Further template refactoring

* Add support for running tests with geckodriver, do this on CI

* Screw you codestyle

* Disable firefox tests for now

That was way more errors than I expected

* Run cleanup script from the right location

* Plausibly fix tests

* Helps if I don't delete the pipeline folder prior to collectstatic

* Enable whitenoise

* Can I delete pipeline here?

* Allow seconds difference in assert_times_equal

* Disable codeclimate

* Remove not working rm command

* Maybe this fixes coverage?

* Try different coverage reporter

* Fix search_help to need login

* Made versioning magic a bit less expansive

We have more apps than I thought...

* Fix IDI0T error in Assets URLS

* Refactor 'no access to unauthed' test to cover all of PyRIGS

* Add RAs/Checklists to sample data generator

* Fix some HTML errors in templates

Which apparently only Django's HTML parser cares about, browsers DGAF...

* Port title test to project level

* Fix more HTML

* Fix cable type detail
2021-01-31 04:05:33 +00:00

261 lines
9.2 KiB
Python

import datetime
import re
import reversion
from django import forms
from django.contrib import messages
from django.db import transaction
from django.db.models import Q
from django.http import Http404, HttpResponseRedirect
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from django.template.loader import get_template
from django.urls import reverse_lazy
from django.views import generic
from z3c.rml import rml2pdf
from RIGS import models
forms.DateField.widget = forms.DateInput(attrs={'type': 'date'})
class InvoiceIndex(generic.ListView):
model = models.Invoice
template_name = 'invoice_list.html'
def get_context_data(self, **kwargs):
context = super(InvoiceIndex, self).get_context_data(**kwargs)
total = 0
for i in context['object_list']:
total += i.balance
context['page_title'] = "Outstanding Invoices ({} Events, £{:.2f})".format(len(list(context['object_list'])), total)
context['description'] = "Paperwork for these events has been sent to treasury, but the full balance has not yet appeared on a ledger"
return context
def get_queryset(self):
# Manual query is the only way I have found to do this efficiently. Not ideal but needs must
sql = "SELECT * FROM " \
"(SELECT " \
"(SELECT COUNT(p.amount) FROM \"RIGS_payment\" AS p WHERE p.invoice_id=\"RIGS_invoice\".id) AS \"payment_count\", " \
"(SELECT SUM(ei.cost * ei.quantity) FROM \"RIGS_eventitem\" AS ei WHERE ei.event_id=\"RIGS_invoice\".event_id) AS \"cost\", " \
"(SELECT SUM(p.amount) FROM \"RIGS_payment\" AS p WHERE p.invoice_id=\"RIGS_invoice\".id) AS \"payments\", " \
"\"RIGS_invoice\".\"id\", \"RIGS_invoice\".\"event_id\", \"RIGS_invoice\".\"invoice_date\", \"RIGS_invoice\".\"void\" FROM \"RIGS_invoice\") " \
"AS sub " \
"WHERE (((cost > 0.0) AND (payment_count=0)) OR (cost - payments) <> 0.0) AND void = '0'" \
"ORDER BY invoice_date"
query = self.model.objects.raw(sql)
return query
class InvoiceDetail(generic.DetailView):
model = models.Invoice
template_name = 'invoice_detail.html'
def get_context_data(self, **kwargs):
context = super(InvoiceDetail, self).get_context_data(**kwargs)
context['page_title'] = "Invoice {} ({})".format(self.object.display_id, self.object.invoice_date.strftime("%d/%m/%Y"))
return context
class InvoicePrint(generic.View):
def get(self, request, pk):
invoice = get_object_or_404(models.Invoice, pk=pk)
object = invoice.event
template = get_template('event_print.xml')
context = {
'object': object,
'fonts': {
'opensans': {
'regular': 'RIGS/static/fonts/OPENSANS-REGULAR.TTF',
'bold': 'RIGS/static/fonts/OPENSANS-BOLD.TTF',
}
},
'invoice': invoice,
'current_user': request.user,
'filename': 'Invoice {} for {} {}.pdf'.format(invoice.display_id, object.display_id, re.sub(r'[^a-zA-Z0-9 \n\.]', '', object.name))
}
rml = template.render(context)
buffer = rml2pdf.parseString(rml)
pdfData = buffer.read()
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'filename="{}"'.format(context['filename'])
response.write(pdfData)
return response
class InvoiceVoid(generic.View):
def get(self, *args, **kwargs):
pk = kwargs.get('pk')
object = get_object_or_404(models.Invoice, pk=pk)
object.void = not object.void
object.save()
if object.void:
return HttpResponseRedirect(reverse_lazy('invoice_list'))
return HttpResponseRedirect(reverse_lazy('invoice_detail', kwargs={'pk': object.pk}))
class InvoiceDelete(generic.DeleteView):
model = models.Invoice
template_name = 'invoice_confirm_delete.html'
def get(self, request, pk):
obj = self.get_object()
if obj.payment_set.all().count() > 0:
messages.info(self.request, 'To delete an invoice, delete the payments first.')
return HttpResponseRedirect(reverse_lazy('invoice_detail', kwargs={'pk': obj.pk}))
return super(InvoiceDelete, self).get(pk)
def post(self, request, pk):
obj = self.get_object()
if obj.payment_set.all().count() > 0:
messages.info(self.request, 'To delete an invoice, delete the payments first.')
return HttpResponseRedirect(reverse_lazy('invoice_detail', kwargs={'pk': obj.pk}))
return super(InvoiceDelete, self).post(pk)
def get_success_url(self):
return self.request.POST.get('next')
class InvoiceArchive(generic.ListView):
model = models.Invoice
template_name = 'invoice_list_archive.html'
paginate_by = 25
def get_context_data(self, **kwargs):
context = super(InvoiceArchive, self).get_context_data(**kwargs)
context['page_title'] = "Invoice Archive"
context['description'] = "This page displays all invoices: outstanding, paid, and void"
return context
def get_queryset(self):
q = self.request.GET.get('q', "")
filter = Q(event__name__icontains=q)
# try and parse an int
try:
val = int(q)
filter = filter | Q(pk=val)
filter = filter | Q(event__pk=val)
except: # noqa
# not an integer
pass
try:
if q[0] == "N":
val = int(q[1:])
filter = Q(event__pk=val) # If string is Nxxxxx then filter by event number
elif q[0] == "#":
val = int(q[1:])
filter = Q(pk=val) # If string is #xxxxx then filter by invoice number
except: # noqa
pass
object_list = self.model.objects.filter(filter).order_by('-invoice_date')
return object_list
class InvoiceWaiting(generic.ListView):
model = models.Event
paginate_by = 25
template_name = 'invoice_list_waiting.html'
def get_context_data(self, **kwargs):
context = super(InvoiceWaiting, self).get_context_data(**kwargs)
total = 0
for obj in self.get_objects():
total += obj.sum_total
context['page_title'] = "Events for Invoice ({} Events, £{:.2f})".format(len(self.get_objects()), total)
return context
def get_queryset(self):
return self.get_objects()
def get_objects(self):
# @todo find a way to select items
events = self.model.objects.filter(
(
Q(start_date__lte=datetime.date.today(), end_date__isnull=True) | # Starts before with no end
Q(end_date__lte=datetime.date.today()) # Has end date, finishes before
) & Q(invoice__isnull=True) & # Has not already been invoiced
Q(is_rig=True) # Is a rig (not non-rig)
).order_by('start_date') \
.select_related('person',
'organisation',
'venue', 'mic') \
.prefetch_related('items')
return events
class InvoiceEvent(generic.View):
@transaction.atomic()
@reversion.create_revision()
def get(self, *args, **kwargs):
reversion.set_user(self.request.user)
epk = kwargs.get('pk')
event = models.Event.objects.get(pk=epk)
invoice, created = models.Invoice.objects.get_or_create(event=event)
if created:
invoice.invoice_date = datetime.date.today()
messages.success(self.request, 'Invoice created successfully')
if kwargs.get('void'):
invoice.void = not invoice.void
invoice.save()
messages.warning(self.request, 'Invoice voided')
return HttpResponseRedirect(reverse_lazy('invoice_detail', kwargs={'pk': invoice.pk}))
class PaymentCreate(generic.CreateView):
model = models.Payment
fields = ['invoice', 'date', 'amount', 'method']
template_name = 'payment_form.html'
def get_initial(self):
initial = super(generic.CreateView, self).get_initial()
invoicepk = self.request.GET.get('invoice', self.request.POST.get('invoice', None))
if invoicepk is None:
raise Http404()
invoice = get_object_or_404(models.Invoice, pk=invoicepk)
initial.update({'invoice': invoice})
return initial
@transaction.atomic()
@reversion.create_revision()
def form_valid(self, form, *args, **kwargs):
reversion.add_to_revision(form.cleaned_data['invoice'])
reversion.set_comment("Payment added")
return super().form_valid(form, *args, **kwargs)
def get_success_url(self):
messages.info(self.request, "location.reload()")
return reverse_lazy('closemodal')
class PaymentDelete(generic.DeleteView):
model = models.Payment
template_name = 'payment_confirm_delete.html'
@transaction.atomic()
@reversion.create_revision()
def delete(self, *args, **kwargs):
reversion.add_to_revision(self.get_object().invoice)
reversion.set_comment("Payment removed")
return super().delete(*args, **kwargs)
def get_success_url(self):
return self.request.POST.get('next')