views.py 16.7 KB
Newer Older
Skia's avatar
Skia committed
1 2
from django.views.generic import ListView, DetailView, RedirectView
from django.views.generic.edit import UpdateView, CreateView, DeleteView
Skia's avatar
Skia committed
3
from django.shortcuts import render
Skia's avatar
Skia committed
4
from django.core.urlresolvers import reverse_lazy
5 6
from django.forms.models import modelform_factory
from django.forms import HiddenInput
Skia's avatar
Skia committed
7
from django import forms
Krophil's avatar
Krophil committed
8 9 10 11
from django.http import HttpResponseRedirect, HttpResponse
from django.utils.translation import ugettext as _
from django.conf import settings

Skia's avatar
Skia committed
12 13

from ajax_select.fields import AutoCompleteSelectField, AutoCompleteSelectMultipleField
Skia's avatar
Skia committed
14

15
from core.views import CanViewMixin, CanEditMixin, CanEditPropMixin, CanCreateMixin
16
from core.views.forms import SelectFile, SelectDate
Skia's avatar
Skia committed
17
from accounting.models import BankAccount, ClubAccount, GeneralJournal, Operation, AccountingType, Company, SimplifiedAccountingType, Label
Skia's avatar
Skia committed
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

# Main accounting view

class BankAccountListView(CanViewMixin, ListView):
    """
    A list view for the admins
    """
    model = BankAccount
    template_name = 'accounting/bank_account_list.jinja'
    ordering = ['name']

# Simplified accounting types

class SimplifiedAccountingTypeListView(CanViewMixin, ListView):
    """
    A list view for the admins
    """
    model = SimplifiedAccountingType
    template_name = 'accounting/simplifiedaccountingtype_list.jinja'

class SimplifiedAccountingTypeEditView(CanViewMixin, UpdateView):
    """
    An edit view for the admins
    """
    model = SimplifiedAccountingType
    pk_url_kwarg = "type_id"
    fields = ['label', 'accounting_type']
    template_name = 'core/edit.jinja'

class SimplifiedAccountingTypeCreateView(CanCreateMixin, CreateView):
    """
    Create an accounting type (for the admins)
    """
    model = SimplifiedAccountingType
    fields = ['label', 'accounting_type']
    template_name = 'core/create.jinja'
Skia's avatar
Skia committed
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70

# Accounting types

class AccountingTypeListView(CanViewMixin, ListView):
    """
    A list view for the admins
    """
    model = AccountingType
    template_name = 'accounting/accountingtype_list.jinja'

class AccountingTypeEditView(CanViewMixin, UpdateView):
    """
    An edit view for the admins
    """
    model = AccountingType
    pk_url_kwarg = "type_id"
    fields = ['code', 'label', 'movement_type']
Skia's avatar
Skia committed
71
    template_name = 'core/edit.jinja'
Skia's avatar
Skia committed
72

73
class AccountingTypeCreateView(CanCreateMixin, CreateView):
Skia's avatar
Skia committed
74 75 76 77 78
    """
    Create an accounting type (for the admins)
    """
    model = AccountingType
    fields = ['code', 'label', 'movement_type']
Skia's avatar
Skia committed
79
    template_name = 'core/create.jinja'
Skia's avatar
Skia committed
80 81 82 83 84 85 86 87 88

# BankAccount views

class BankAccountEditView(CanViewMixin, UpdateView):
    """
    An edit view for the admins
    """
    model = BankAccount
    pk_url_kwarg = "b_account_id"
Skia's avatar
Skia committed
89
    fields = ['name', 'iban', 'number', 'club']
Skia's avatar
Skia committed
90
    template_name = 'core/edit.jinja'
Skia's avatar
Skia committed
91 92 93 94 95 96 97 98 99

class BankAccountDetailView(CanViewMixin, DetailView):
    """
    A detail view, listing every club account
    """
    model = BankAccount
    pk_url_kwarg = "b_account_id"
    template_name = 'accounting/bank_account_details.jinja'

100
class BankAccountCreateView(CanCreateMixin, CreateView):
Skia's avatar
Skia committed
101 102 103 104
    """
    Create a bank account (for the admins)
    """
    model = BankAccount
Skia's avatar
Skia committed
105
    fields = ['name', 'club', 'iban', 'number']
Skia's avatar
Skia committed
106
    template_name = 'core/create.jinja'
Skia's avatar
Skia committed
107

Skia's avatar
Skia committed
108
class BankAccountDeleteView(CanEditPropMixin, DeleteView): # TODO change Delete to Close
Skia's avatar
Skia committed
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
    """
    Delete a bank account (for the admins)
    """
    model = BankAccount
    pk_url_kwarg = "b_account_id"
    template_name = 'core/delete_confirm.jinja'
    success_url = reverse_lazy('accounting:bank_list')

# ClubAccount views

class ClubAccountEditView(CanViewMixin, UpdateView):
    """
    An edit view for the admins
    """
    model = ClubAccount
    pk_url_kwarg = "c_account_id"
    fields = ['name', 'club', 'bank_account']
Skia's avatar
Skia committed
126
    template_name = 'core/edit.jinja'
Skia's avatar
Skia committed
127 128 129 130 131 132 133 134 135

class ClubAccountDetailView(CanViewMixin, DetailView):
    """
    A detail view, listing every journal
    """
    model = ClubAccount
    pk_url_kwarg = "c_account_id"
    template_name = 'accounting/club_account_details.jinja'

136
class ClubAccountCreateView(CanCreateMixin, CreateView):
Skia's avatar
Skia committed
137 138 139 140 141
    """
    Create a club account (for the admins)
    """
    model = ClubAccount
    fields = ['name', 'club', 'bank_account']
Skia's avatar
Skia committed
142 143 144 145 146 147 148 149 150
    template_name = 'core/create.jinja'

    def get_initial(self):
        ret = super(ClubAccountCreateView, self).get_initial()
        if 'parent' in self.request.GET.keys():
            obj = BankAccount.objects.filter(id=int(self.request.GET['parent'])).first()
            if obj is not None:
                ret['bank_account'] = obj.id
        return ret
Skia's avatar
Skia committed
151

Skia's avatar
Skia committed
152
class ClubAccountDeleteView(CanEditPropMixin, DeleteView): # TODO change Delete to Close
Skia's avatar
Skia committed
153 154 155 156 157 158 159 160 161 162
    """
    Delete a club account (for the admins)
    """
    model = ClubAccount
    pk_url_kwarg = "c_account_id"
    template_name = 'core/delete_confirm.jinja'
    success_url = reverse_lazy('accounting:bank_list')

# Journal views

Skia's avatar
Skia committed
163
class JournalCreateView(CanCreateMixin, CreateView):
Skia's avatar
Skia committed
164 165 166 167
    """
    Create a general journal
    """
    model = GeneralJournal
Skia's avatar
Skia committed
168 169
    form_class = modelform_factory(GeneralJournal, fields=['name', 'start_date', 'club_account'],
            widgets={ 'start_date': SelectDate, })
Skia's avatar
Skia committed
170 171 172 173 174 175 176 177 178
    template_name = 'core/create.jinja'

    def get_initial(self):
        ret = super(JournalCreateView, self).get_initial()
        if 'parent' in self.request.GET.keys():
            obj = ClubAccount.objects.filter(id=int(self.request.GET['parent'])).first()
            if obj is not None:
                ret['club_account'] = obj.id
        return ret
Skia's avatar
Skia committed
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193

class JournalDetailView(CanViewMixin, DetailView):
    """
    A detail view, listing every operation
    """
    model = GeneralJournal
    pk_url_kwarg = "j_id"
    template_name = 'accounting/journal_details.jinja'

class JournalEditView(CanEditMixin, UpdateView):
    """
    Update a general journal
    """
    model = GeneralJournal
    pk_url_kwarg = "j_id"
Skia's avatar
Skia committed
194
    fields = ['name', 'start_date', 'end_date', 'club_account', 'closed']
Skia's avatar
Skia committed
195
    template_name = 'core/edit.jinja'
Skia's avatar
Skia committed
196

Krophil's avatar
Krophil committed
197

Skia's avatar
Skia committed
198 199
# Operation views

Skia's avatar
Skia committed
200 201 202 203
class OperationForm(forms.ModelForm):
    class Meta:
        model = Operation
        fields = ['amount', 'remark', 'journal', 'target_type', 'target_id', 'target_label', 'date', 'mode',
Skia's avatar
Skia committed
204
            'cheque_number', 'invoice', 'simpleaccounting_type', 'accounting_type', 'label', 'done']
Skia's avatar
Skia committed
205 206 207 208 209 210 211 212 213 214 215 216
        widgets = {
                'journal': HiddenInput,
                'target_id': HiddenInput,
                'date': SelectDate,
                'invoice': SelectFile,
                }
    user = AutoCompleteSelectField('users', help_text=None, required=False)
    club_account = AutoCompleteSelectField('club_accounts', help_text=None, required=False)
    club = AutoCompleteSelectField('clubs', help_text=None, required=False)
    company = AutoCompleteSelectField('companies', help_text=None, required=False)

    def __init__(self, *args, **kwargs):
Skia's avatar
Skia committed
217
        club_account = kwargs.pop('club_account', None)
Skia's avatar
Skia committed
218
        super(OperationForm, self).__init__(*args, **kwargs)
Skia's avatar
Skia committed
219 220
        if club_account:
            self.fields['label'].queryset = club_account.labels.order_by('name').all()
Skia's avatar
Skia committed
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
        if self.instance.target_type == "USER":
            self.fields['user'].initial = self.instance.target_id
        elif self.instance.target_type == "ACCOUNT":
            self.fields['club_account'].initial = self.instance.target_id
        elif self.instance.target_type == "CLUB":
            self.fields['club'].initial = self.instance.target_id
        elif self.instance.target_type == "COMPANY":
            self.fields['company'].initial = self.instance.target_id

    def clean(self):
        self.cleaned_data = super(OperationForm, self).clean()
        if self.cleaned_data['target_type'] == "USER":
            self.cleaned_data['target_id'] = self.cleaned_data['user'].id
        elif self.cleaned_data['target_type'] == "ACCOUNT":
            self.cleaned_data['target_id'] = self.cleaned_data['club_account'].id
        elif self.cleaned_data['target_type'] == "CLUB":
            self.cleaned_data['target_id'] = self.cleaned_data['club'].id
        elif self.cleaned_data['target_type'] == "COMPANY":
            self.cleaned_data['target_id'] = self.cleaned_data['company'].id
        return self.cleaned_data

    def save(self):
        ret = super(OperationForm, self).save()
        if self.instance.target_type == "ACCOUNT" and not self.instance.linked_operation and self.instance.target.has_open_journal():
            inst = self.instance
            club_account = inst.target
            acc_type = AccountingType.objects.exclude(movement_type="NEUTRAL").exclude(
                    movement_type=inst.accounting_type.movement_type).first() # Select a random opposite accounting type
            op = Operation(
                    journal=club_account.get_open_journal(),
                    amount=inst.amount,
                    date=inst.date,
                    remark=inst.remark,
                    mode=inst.mode,
                    cheque_number=inst.cheque_number,
                    invoice=inst.invoice,
                    done=False, # Has to be checked by hand
                    simpleaccounting_type=None,
                    accounting_type=acc_type,
                    target_type="ACCOUNT",
                    target_id=inst.journal.club_account.id,
                    target_label="",
                    linked_operation=inst,
                    )
            op.save()
            self.instance.linked_operation = op
            self.save()
        return ret

270
class OperationCreateView(CanCreateMixin, CreateView):
Skia's avatar
Skia committed
271 272 273 274
    """
    Create an operation
    """
    model = Operation
Skia's avatar
Skia committed
275 276
    form_class = OperationForm
    template_name = 'accounting/operation_edit.jinja'
Skia's avatar
Skia committed
277

Skia's avatar
Skia committed
278 279 280 281 282
    def get_form(self, form_class=None):
        self.journal = GeneralJournal.objects.filter(id=self.kwargs['j_id']).first()
        ca = self.journal.club_account if self.journal else None
        return self.form_class(club_account=ca, **self.get_form_kwargs())

Skia's avatar
Skia committed
283 284
    def get_initial(self):
        ret = super(OperationCreateView, self).get_initial()
Skia's avatar
Skia committed
285 286
        if self.journal is not None:
            ret['journal'] = self.journal.id
Skia's avatar
Skia committed
287
        return ret
Skia's avatar
Skia committed
288

Skia's avatar
Skia committed
289 290 291 292 293 294 295
    def get_context_data(self, **kwargs):
        """ Add journal to the context """
        kwargs = super(OperationCreateView, self).get_context_data(**kwargs)
        if self.journal:
            kwargs['object'] = self.journal
        return kwargs

Skia's avatar
Skia committed
296
class OperationEditView(CanEditMixin, UpdateView):
Skia's avatar
Skia committed
297 298 299 300 301
    """
    An edit view, working as detail for the moment
    """
    model = Operation
    pk_url_kwarg = "op_id"
Skia's avatar
Skia committed
302 303
    form_class = OperationForm
    template_name = 'accounting/operation_edit.jinja'
Skia's avatar
Skia committed
304

Skia's avatar
Skia committed
305 306
    def get_context_data(self, **kwargs):
        """ Add journal to the context """
Skia's avatar
Skia committed
307
        kwargs = super(OperationEditView, self).get_context_data(**kwargs)
Skia's avatar
Skia committed
308 309 310
        kwargs['object'] = self.object.journal
        return kwargs

Krophil's avatar
Krophil committed
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
class OperationPDFView(CanViewMixin, DetailView):
    """
    Display the PDF of a given operation
    """

    model = Operation
    pk_url_kwarg = "op_id"

    def get(self, request, *args, **kwargs):
        from reportlab.pdfgen import canvas
        from reportlab.lib.units import cm
        from reportlab.platypus import SimpleDocTemplate, Table, TableStyle
        from reportlab.lib import colors
        from reportlab.lib.pagesizes import letter
        from reportlab.lib.utils import ImageReader
        from reportlab.graphics.shapes import Drawing
        from reportlab.pdfbase.ttfonts import TTFont
        from reportlab.pdfbase import pdfmetrics

        pdfmetrics.registerFont(TTFont('DejaVu', 'DejaVuSerif.ttf'))



        self.object = self.get_object()
        amount = self.object.amount
        remark = self.object.remark
        nature = self.object.accounting_type.movement_type
        num = self.object.number
        date = self.object.date
        mode = self.object.mode
        cheque_number = self.object.cheque_number
        club_name = self.object.journal.club_account.name
        ti = self.object.journal.name
        op_label = self.object.label
        club_address = self.object.journal.club_account.club.address
        id_op = self.object.id

        if self.object.target_type == "OTHER":
            target = self.object.target_label
        else:
            target = self.object.target.get_display_name()


        response = HttpResponse(content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename="op-%d(%s_on_%s).pdf"'  %(num, ti, club_name)
        p = canvas.Canvas(response)

        p.setFont('DejaVu', 12)

        p.setTitle("%s %d" % (_("Operation"), num))
        width, height = letter
        im = ImageReader("core/static/core/img/logo.jpg")
        iw, ih = im.getSize()
        p.drawImage(im, 40, height - 50, width=iw/2, height=ih/2)
 
        labelStr = [["%s %s - %s %s" % (_("Journal"), ti, _("Operation"), num)]]

        label = Table(labelStr, colWidths=[150], rowHeights=[20])
        
        label.setStyle(TableStyle([
                                ('ALIGN',(0,0),(-1,-1),'CENTER'),
                                ('BOX', (0,0), (-1,-1), 0.25, colors.black),
                                ]))
        w, h = label.wrapOn(label, 0, 0)
        label.drawOn(p, width-180, height)

        p.drawString(90, height - 100, _("Financial proof: ") + "OP%010d" % (id_op)) #Justificatif du libellé
        p.drawString(90, height - 130, _("Club: %(club_name)s") % ({"club_name": club_name}))
        p.drawString(90, height - 160, _("Label: %(op_label)s") % {"op_label": op_label if op_label != None else ""})

        data = []
        
        data += [["%s" % (_("Credit").upper() if nature == 'CREDIT' else _("Debit").upper())]]

        data += [[_("Amount: %(amount).2f €") % {"amount": amount}]]
        
        payment_mode = ""
        for m in settings.SITH_ACCOUNTING_PAYMENT_METHOD:
            if m[0] == mode:
                payment_mode += "[\u00D7]"
            else:
                payment_mode += "[  ]"
            payment_mode += " %s\n" %(m[1])

        data += [[payment_mode]]
        
        data += [["%s : %s" % (_("Debtor") if nature == 'CREDIT' else _("Creditor"), target), ""]]

        data += [["%s \n%s" % (_("Comment:"), remark)]]
        
        t = Table(data, colWidths=[(width-90*2)/2]*2, rowHeights=[20, 20, 70, 20, 80])
        t.setStyle(TableStyle([
                        ('ALIGN',(0,0),(-1,-1),'CENTER'),
                        ('VALIGN',(-2,-1),(-1,-1),'TOP'),
                        ('VALIGN',(0,0),(-1,-2),'MIDDLE'),
                        ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
                        ('SPAN', (0, 0), (1, 0)), # line DEBIT/CREDIT
                        ('SPAN', (0, 1), (1, 1)), # line amount
                        ('SPAN',(-2, -1), (-1,-1)), # line comment
                        ('SPAN', (0, -2), (-1, -2)), # line creditor/debtor
                        ('SPAN', (0, 2), (1, 2)), # line payment_mode
                        ('ALIGN',(0, 2), (1, 2),'LEFT'), # line payment_mode
                        ('ALIGN', (-2, -1), (-1, -1), 'LEFT'),
                        ('BOX', (0,0), (-1,-1), 0.25, colors.black),
                        ]))

        w, h = t.wrapOn(p, 0, 0)

        t.drawOn(p, 90, 350)



        p.drawCentredString(10.5 * cm, 2 * cm, club_name)
        p.drawCentredString(10.5 * cm, 1 * cm, club_address)

        p.showPage()
        p.save()
        return response

Skia's avatar
Skia committed
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
# Company views

class CompanyCreateView(CanCreateMixin, CreateView):
    """
    Create a company
    """
    model = Company
    fields = ['name']
    template_name = 'core/create.jinja'

class CompanyEditView(CanCreateMixin, UpdateView):
    """
    Edit a company
    """
    model = Company
    pk_url_kwarg = "co_id"
    fields = ['name']
Skia's avatar
Skia committed
447
    template_name = 'core/edit.jinja'
Skia's avatar
Skia committed
448

Skia's avatar
Skia committed
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
# Label views

class LabelListView(CanViewMixin, DetailView):
    model = ClubAccount
    pk_url_kwarg = "clubaccount_id"
    template_name = 'accounting/label_list.jinja'

class LabelCreateView(CanEditMixin, CreateView): # FIXME we need to check the rights before creating the object
    model = Label
    form_class = modelform_factory(Label, fields=['name', 'club_account'], widgets={
        'club_account': HiddenInput,
        })
    template_name = 'core/create.jinja'

    def get_initial(self):
        ret = super(LabelCreateView, self).get_initial()
        if 'parent' in self.request.GET.keys():
            obj = ClubAccount.objects.filter(id=int(self.request.GET['parent'])).first()
            if obj is not None:
                ret['club_account'] = obj.id
        return ret

class LabelEditView(CanEditMixin, UpdateView):
    model = Label
    pk_url_kwarg = "label_id"
    fields = ['name']
    template_name = 'core/edit.jinja'

class LabelDeleteView(CanEditMixin, DeleteView):
    model = Label
    pk_url_kwarg = "label_id"
    template_name = 'core/delete_confirm.jinja'

    def get_success_url(self):
        return self.object.get_absolute_url()