views.py 18.8 KB
Newer Older
Skia's avatar
Skia committed
1
from django.views.generic import ListView, DetailView, RedirectView
Sli's avatar
Sli committed
2
from django.views.generic.edit import UpdateView, CreateView, DeleteView, FormView
Skia's avatar
Skia committed
3
from django.shortcuts import render
Sli's avatar
Sli committed
4
5
from django.core.urlresolvers import reverse_lazy, reverse
from django.utils.translation import ugettext_lazy as _
6
from django.forms.models import modelform_factory
Sli's avatar
Sli committed
7
from django.core.exceptions import PermissionDenied
8
from django.forms import HiddenInput
Sli's avatar
Sli committed
9
10
from django.db import transaction
from django.conf import settings
Skia's avatar
Skia committed
11
from django import forms
Krophil's avatar
Krophil committed
12
13
14
15
from django.http import HttpResponseRedirect, HttpResponse
from django.utils.translation import ugettext as _
from django.conf import settings

Skia's avatar
Skia committed
16
17

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

19
from core.views import CanViewMixin, CanEditMixin, CanEditPropMixin, CanCreateMixin
20
from core.views.forms import SelectFile, SelectDate
Skia's avatar
Skia committed
21
from accounting.models import BankAccount, ClubAccount, GeneralJournal, Operation, AccountingType, Company, SimplifiedAccountingType, Label
Sli's avatar
Sli committed
22
from counter.models import Counter, Selling, Product
Skia's avatar
Skia committed
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

# 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75

# 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
76
    template_name = 'core/edit.jinja'
Skia's avatar
Skia committed
77

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

# 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
94
    fields = ['name', 'iban', 'number', 'club']
Skia's avatar
Skia committed
95
    template_name = 'core/edit.jinja'
Skia's avatar
Skia committed
96
97
98
99
100
101
102
103
104

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'

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

Skia's avatar
Skia committed
113
class BankAccountDeleteView(CanEditPropMixin, DeleteView): # TODO change Delete to Close
Skia's avatar
Skia committed
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
    """
    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
131
    template_name = 'core/edit.jinja'
Skia's avatar
Skia committed
132
133
134
135
136
137
138
139
140

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'

141
class ClubAccountCreateView(CanCreateMixin, CreateView):
Skia's avatar
Skia committed
142
143
144
145
146
    """
    Create a club account (for the admins)
    """
    model = ClubAccount
    fields = ['name', 'club', 'bank_account']
Skia's avatar
Skia committed
147
148
149
150
151
152
153
154
155
    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
156

Skia's avatar
Skia committed
157
class ClubAccountDeleteView(CanEditPropMixin, DeleteView): # TODO change Delete to Close
Skia's avatar
Skia committed
158
159
160
161
162
163
164
165
166
167
    """
    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
168
class JournalCreateView(CanCreateMixin, CreateView):
Skia's avatar
Skia committed
169
170
171
172
    """
    Create a general journal
    """
    model = GeneralJournal
Skia's avatar
Skia committed
173
174
    form_class = modelform_factory(GeneralJournal, fields=['name', 'start_date', 'club_account'],
            widgets={ 'start_date': SelectDate, })
Skia's avatar
Skia committed
175
176
177
178
179
180
181
182
183
    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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198

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
199
    fields = ['name', 'start_date', 'end_date', 'club_account', 'closed']
Skia's avatar
Skia committed
200
    template_name = 'core/edit.jinja'
Skia's avatar
Skia committed
201

Krophil's avatar
Krophil committed
202

Skia's avatar
Skia committed
203
204
# Operation views

Skia's avatar
Skia committed
205
206
207
208
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
209
            'cheque_number', 'invoice', 'simpleaccounting_type', 'accounting_type', 'label', 'done']
Skia's avatar
Skia committed
210
211
212
213
214
215
216
217
218
219
220
221
        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
222
        club_account = kwargs.pop('club_account', None)
Skia's avatar
Skia committed
223
        super(OperationForm, self).__init__(*args, **kwargs)
Skia's avatar
Skia committed
224
225
        if club_account:
            self.fields['label'].queryset = club_account.labels.order_by('name').all()
Skia's avatar
Skia committed
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
        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

275
class OperationCreateView(CanCreateMixin, CreateView):
Skia's avatar
Skia committed
276
277
278
279
    """
    Create an operation
    """
    model = Operation
Skia's avatar
Skia committed
280
281
    form_class = OperationForm
    template_name = 'accounting/operation_edit.jinja'
Skia's avatar
Skia committed
282

Skia's avatar
Skia committed
283
284
285
286
287
    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
288
289
    def get_initial(self):
        ret = super(OperationCreateView, self).get_initial()
Skia's avatar
Skia committed
290
291
        if self.journal is not None:
            ret['journal'] = self.journal.id
Skia's avatar
Skia committed
292
        return ret
Skia's avatar
Skia committed
293

Skia's avatar
Skia committed
294
295
296
297
298
299
300
    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
301
class OperationEditView(CanEditMixin, UpdateView):
Skia's avatar
Skia committed
302
303
304
305
306
    """
    An edit view, working as detail for the moment
    """
    model = Operation
    pk_url_kwarg = "op_id"
Skia's avatar
Skia committed
307
308
    form_class = OperationForm
    template_name = 'accounting/operation_edit.jinja'
Skia's avatar
Skia committed
309

Skia's avatar
Skia committed
310
311
    def get_context_data(self, **kwargs):
        """ Add journal to the context """
Skia's avatar
Skia committed
312
        kwargs = super(OperationEditView, self).get_context_data(**kwargs)
Skia's avatar
Skia committed
313
314
315
        kwargs['object'] = self.object.journal
        return kwargs

Krophil's avatar
Krophil committed
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
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)
Skia's avatar
Skia committed
370

Krophil's avatar
Krophil committed
371
372
373
        labelStr = [["%s %s - %s %s" % (_("Journal"), ti, _("Operation"), num)]]

        label = Table(labelStr, colWidths=[150], rowHeights=[20])
Skia's avatar
Skia committed
374

Krophil's avatar
Krophil committed
375
376
377
378
379
380
381
382
383
384
385
386
        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 = []
Skia's avatar
Skia committed
387

Krophil's avatar
Krophil committed
388
389
390
        data += [["%s" % (_("Credit").upper() if nature == 'CREDIT' else _("Debit").upper())]]

        data += [[_("Amount: %(amount).2f €") % {"amount": amount}]]
Skia's avatar
Skia committed
391

Krophil's avatar
Krophil committed
392
393
394
395
396
397
398
399
400
        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]]
Skia's avatar
Skia committed
401

Krophil's avatar
Krophil committed
402
403
404
        data += [["%s : %s" % (_("Debtor") if nature == 'CREDIT' else _("Creditor"), target), ""]]

        data += [["%s \n%s" % (_("Comment:"), remark)]]
Skia's avatar
Skia committed
405

Krophil's avatar
Krophil committed
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
        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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
# 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
452
    template_name = 'core/edit.jinja'
Skia's avatar
Skia committed
453

Skia's avatar
Skia committed
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
# 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()
Sli's avatar
Sli committed
489
490
491
492
493
494
495
496
497
498
499
500

class CloseCustomerAccountForm(forms.Form):
    user = AutoCompleteSelectField('users', label=_('Refound this account'), help_text=None, required=True)

class RefoundAccountView(FormView):
    """
    Create a selling with the same amount than the current user money
    """
    template_name = "accounting/refound_account.jinja"
    form_class = CloseCustomerAccountForm

    def permission(self, user):
Skia's avatar
Skia committed
501
        if user.is_root or user.is_in_group(settings.SITH_GROUP_ACCOUNTING_ADMIN_ID):
Sli's avatar
Sli committed
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
            return True
        else:
            raise PermissionDenied

    def dispatch(self, request, *arg, **kwargs):
        res = super(RefoundAccountView, self).dispatch(request, *arg, **kwargs)
        if self.permission(request.user):
            return res

    def post(self, request, *arg, **kwargs):
        self.operator = request.user
        if self.permission(request.user):
            return super(RefoundAccountView, self).post(self, request, *arg, **kwargs)

    def form_valid(self, form):
        self.customer = form.cleaned_data['user']
        self.create_selling()
        return super(RefoundAccountView, self).form_valid(form)

    def get_success_url(self):
        return reverse('accounting:refound_account')

    def create_selling(self):
        with transaction.atomic():
            uprice = self.customer.customer.amount
Sli's avatar
Sli committed
527
            main_club_counter = Counter.objects.get(name=settings.SITH_COUNTER_REFOUND[1])
Sli's avatar
Sli committed
528
529
530
531
            main_club = main_club_counter.club
            s = Selling(label=_('Refound account'), unit_price=uprice,
                        quantity=1, seller=self.operator,
                        customer=self.customer.customer,
Sli's avatar
Sli committed
532
533
                        club=main_club, counter=main_club_counter,
                        product=Product.objects.get(code=settings.SITH_COUNTER_REFOUND_PRODUCT[1]))
Sli's avatar
Sli committed
534
            s.save()