diff --git a/registrasion/forms.py b/registrasion/forms.py index 68c69d36..2de043f2 100644 --- a/registrasion/forms.py +++ b/registrasion/forms.py @@ -3,6 +3,40 @@ import models as rego from django import forms +class ApplyCreditNoteForm(forms.Form): + + def __init__(self, user, *a, **k): + ''' User: The user whose invoices should be made available as + choices. ''' + self.user = user + super(ApplyCreditNoteForm, self).__init__(*a, **k) + + self.fields["invoice"].choices = self._unpaid_invoices_for_user + + def _unpaid_invoices_for_user(self): + invoices = rego.Invoice.objects.filter( + status=rego.Invoice.STATUS_UNPAID, + user=self.user, + ) + + return [ + (invoice.id, "Invoice %(id)d - $%(value)d" % invoice.__dict__) + for invoice in invoices + ] + + invoice = forms.ChoiceField( + #choices=_unpaid_invoices_for_user, + required=True, + ) + + +class ManualCreditNoteRefundForm(forms.ModelForm): + + class Meta: + model = rego.ManualCreditNoteRefund + fields = ["reference"] + + class ManualPaymentForm(forms.ModelForm): class Meta: diff --git a/registrasion/views.py b/registrasion/views.py index 13f1b857..b2ca8eca 100644 --- a/registrasion/views.py +++ b/registrasion/views.py @@ -561,8 +561,39 @@ def credit_note(request, note_id, access_code=None): current_note = CreditNoteController(note) + apply_form = forms.ApplyCreditNoteForm( + note.invoice.user, + request.POST or None, + prefix="apply_note" + ) + + refund_form = forms.ManualCreditNoteRefundForm( + request.POST or None, + prefix="refund_note" + ) + + if request.POST and apply_form.is_valid(): + inv_id = apply_form.cleaned_data["invoice"] + invoice = rego.Invoice.objects.get(pk=inv_id) + current_note.apply_to_invoice(invoice) + messages.success(request, + "Applied credit note %d to invoice." % note_id + ) + return redirect("invoice", invoice.id) + + elif request.POST and refund_form.is_valid(): + refund_form.instance.entered_by = request.user + refund_form.instance.parent = note + refund_form.save() + messages.success(request, + "Applied manual refund to credit note." + ) + return redirect("invoice", invoice.id) + data = { "credit_note": current_note.credit_note, + "apply_form": apply_form, + "refund_form": refund_form, } return render(request, "registrasion/credit_note.html", data)