views.py 25.4 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, TextInput
Sli's avatar
Sli committed
9
from django.db import transaction
Skia's avatar
Skia committed
10
from django.db.models import Sum
Sli's avatar
Sli committed
11
from django.conf import settings
Skia's avatar
Skia committed
12
from django import forms
Krophil's avatar
Krophil committed
13
14
15
16
from django.http import HttpResponseRedirect, HttpResponse
from django.utils.translation import ugettext as _
from django.conf import settings

Skia's avatar
Skia committed
17
import collections
Skia's avatar
Skia committed
18
19

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

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

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

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

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

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

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'

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

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

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'

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

Skia's avatar
Skia committed
159
class ClubAccountDeleteView(CanEditPropMixin, DeleteView): # TODO change Delete to Close
Skia's avatar
Skia committed
160
161
162
163
164
165
166
167
168
169
    """
    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

Krophil's avatar
Krophil committed
170
171
172
173
174
175
176
177
178
179
180
181
class JournalTabsMixin(TabedViewMixin):
    def get_tabs_title(self):
        return _("Journal")

    def get_list_of_tabs(self):
        tab_list = []
        tab_list.append({
                    'url': reverse('accounting:journal_details', kwargs={'j_id': self.object.id}),
                    'slug': 'journal',
                    'name': _("Journal"),
                    })
        tab_list.append({
Skia's avatar
Skia committed
182
183
184
                    'url': reverse('accounting:journal_nature_statement', kwargs={'j_id': self.object.id}),
                    'slug': 'nature_statement',
                    'name': _("Statement by nature"),
Krophil's avatar
Krophil committed
185
186
                    })
        tab_list.append({
Skia's avatar
Skia committed
187
188
189
                    'url': reverse('accounting:journal_person_statement', kwargs={'j_id': self.object.id}),
                    'slug': 'person_statement',
                    'name': _("Statement by person"),
Krophil's avatar
Krophil committed
190
191
                    })
        tab_list.append({
Skia's avatar
Skia committed
192
193
194
                    'url': reverse('accounting:journal_accounting_statement', kwargs={'j_id': self.object.id}),
                    'slug': 'accounting_statement',
                    'name': _("Accounting statement"),
Krophil's avatar
Krophil committed
195
196
197
                    })
        return tab_list

Skia's avatar
Skia committed
198
class JournalCreateView(CanCreateMixin, CreateView):
Skia's avatar
Skia committed
199
200
201
202
    """
    Create a general journal
    """
    model = GeneralJournal
Skia's avatar
Skia committed
203
204
    form_class = modelform_factory(GeneralJournal, fields=['name', 'start_date', 'club_account'],
            widgets={ 'start_date': SelectDate, })
Skia's avatar
Skia committed
205
206
207
208
209
210
211
212
213
    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
214

Krophil's avatar
Krophil committed
215
class JournalDetailView(JournalTabsMixin, CanViewMixin, DetailView):
Skia's avatar
Skia committed
216
217
218
219
220
221
    """
    A detail view, listing every operation
    """
    model = GeneralJournal
    pk_url_kwarg = "j_id"
    template_name = 'accounting/journal_details.jinja'
Krophil's avatar
Krophil committed
222
    current_tab = 'journal'
Skia's avatar
Skia committed
223
224
225
226
227
228
229

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

Krophil's avatar
Krophil committed
233

Skia's avatar
Skia committed
234
235
# Operation views

Skia's avatar
Skia committed
236
237
238
239
class OperationForm(forms.ModelForm):
    class Meta:
        model = Operation
        fields = ['amount', 'remark', 'journal', 'target_type', 'target_id', 'target_label', 'date', 'mode',
240
            'cheque_number', 'invoice', 'simpleaccounting_type', 'accounting_type', 'label', 'done' ]
Skia's avatar
Skia committed
241
242
243
244
245
246
247
248
249
250
251
252
        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
253
        club_account = kwargs.pop('club_account', None)
Skia's avatar
Skia committed
254
        super(OperationForm, self).__init__(*args, **kwargs)
Skia's avatar
Skia committed
255
256
        if club_account:
            self.fields['label'].queryset = club_account.labels.order_by('name').all()
Skia's avatar
Skia committed
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
        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(
284
                    movement_type=inst.accounting_type.movement_type).order_by('code').first() # Select a random opposite accounting type
Skia's avatar
Skia committed
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
            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

306
class OperationCreateView(CanCreateMixin, CreateView):
Skia's avatar
Skia committed
307
308
309
310
    """
    Create an operation
    """
    model = Operation
Skia's avatar
Skia committed
311
312
    form_class = OperationForm
    template_name = 'accounting/operation_edit.jinja'
Skia's avatar
Skia committed
313

Skia's avatar
Skia committed
314
315
316
317
318
    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
319
320
    def get_initial(self):
        ret = super(OperationCreateView, self).get_initial()
Skia's avatar
Skia committed
321
322
        if self.journal is not None:
            ret['journal'] = self.journal.id
Skia's avatar
Skia committed
323
        return ret
Skia's avatar
Skia committed
324

Skia's avatar
Skia committed
325
326
327
328
329
330
331
    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
332
class OperationEditView(CanEditMixin, UpdateView):
Skia's avatar
Skia committed
333
334
335
336
337
    """
    An edit view, working as detail for the moment
    """
    model = Operation
    pk_url_kwarg = "op_id"
Skia's avatar
Skia committed
338
339
    form_class = OperationForm
    template_name = 'accounting/operation_edit.jinja'
Skia's avatar
Skia committed
340

Skia's avatar
Skia committed
341
342
    def get_context_data(self, **kwargs):
        """ Add journal to the context """
Skia's avatar
Skia committed
343
        kwargs = super(OperationEditView, self).get_context_data(**kwargs)
Skia's avatar
Skia committed
344
345
346
        kwargs['object'] = self.object.journal
        return kwargs

Krophil's avatar
Krophil committed
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
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
398

Krophil's avatar
Krophil committed
399
400
401
        labelStr = [["%s %s - %s %s" % (_("Journal"), ti, _("Operation"), num)]]

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

Krophil's avatar
Krophil committed
403
404
405
406
407
408
409
410
411
412
        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 ""})
Krophil's avatar
Krophil committed
413
        p.drawString(90, height - 190, _("Date: %(date)s") % {"date": date})
Krophil's avatar
Krophil committed
414
415

        data = []
Skia's avatar
Skia committed
416

Krophil's avatar
Krophil committed
417
418
419
        data += [["%s" % (_("Credit").upper() if nature == 'CREDIT' else _("Debit").upper())]]

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

Krophil's avatar
Krophil committed
421
422
423
424
425
426
427
428
429
        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
430

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

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

Krophil's avatar
Krophil committed
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
        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),
                        ]))

Krophil's avatar
Krophil committed
451
452
453
454
455
456
457
458
459
460
461
        signature = []
        signature += [[_("Signature:")]]

        tSig = Table(signature, colWidths=[(width-90*2)], rowHeights=[80])
        tSig.setStyle(TableStyle([
            ('VALIGN',(0,0),(-1,-1),'TOP'),
            ('BOX', (0,0), (-1,-1), 0.25, colors.black)]))

        w, h = tSig.wrapOn(p, 0, 0)
        tSig.drawOn(p, 90, 200)

Krophil's avatar
Krophil committed
462
463
464
465
466
467
468
469
470
471
472
        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
473
class JournalNatureStatementView(JournalTabsMixin, CanViewMixin, DetailView):
474
    """
Skia's avatar
Skia committed
475
    Display a statement sorted by labels
476
477
478
    """
    model = GeneralJournal
    pk_url_kwarg = "j_id"
Skia's avatar
Skia committed
479
480
    template_name='accounting/journal_statement_nature.jinja'
    current_tab='nature_statement'
481

Skia's avatar
Skia committed
482
483
484
485
    def statement(self, queryset, movement_type):
        ret = collections.OrderedDict()
        statement = collections.OrderedDict()
        total_sum = 0
Skia's avatar
Skia committed
486
        for sat in [None] + list(SimplifiedAccountingType.objects.order_by('label').all()):
Skia's avatar
Skia committed
487
            sum = queryset.filter(accounting_type__movement_type=movement_type,
Skia's avatar
Skia committed
488
489
490
                simpleaccounting_type=sat).aggregate(amount_sum=Sum('amount'))['amount_sum']
            if sat: sat = sat.label
            else: sat = ""
Skia's avatar
Skia committed
491
492
            if sum:
                total_sum += sum
Skia's avatar
Skia committed
493
                statement[sat] = sum
Skia's avatar
Skia committed
494
495
496
        ret[movement_type] = statement
        ret[movement_type+"_sum"] = total_sum
        return ret
497

Skia's avatar
Skia committed
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
    def big_statement(self):
        label_list = self.object.operations.order_by('label').values_list('label').distinct()
        labels = Label.objects.filter(id__in=label_list).all()
        statement = collections.OrderedDict()
        gen_statement = collections.OrderedDict()
        no_label_statement = collections.OrderedDict()
        gen_statement.update(self.statement(self.object.operations.all(), "CREDIT"))
        gen_statement.update(self.statement(self.object.operations.all(), "DEBIT"))
        statement[_("General statement")] = gen_statement
        no_label_statement.update(self.statement(self.object.operations.filter(label=None).all(), "CREDIT"))
        no_label_statement.update(self.statement(self.object.operations.filter(label=None).all(), "DEBIT"))
        statement[_("No label operations")] = no_label_statement
        for l in labels:
            l_stmt = collections.OrderedDict()
            l_stmt.update(self.statement(self.object.operations.filter(label=l).all(), "CREDIT"))
            l_stmt.update(self.statement(self.object.operations.filter(label=l).all(), "DEBIT"))
            statement[l] = l_stmt
        return statement
516

517
    def get_context_data(self, **kwargs):
Skia's avatar
Skia committed
518
        """ Add infos to the context """
Skia's avatar
Skia committed
519
        kwargs = super(JournalNatureStatementView, self).get_context_data(**kwargs)
Skia's avatar
Skia committed
520
        kwargs['statement'] = self.big_statement()
521
522
        return kwargs

Skia's avatar
Skia committed
523
class JournalPersonStatementView(JournalTabsMixin, CanViewMixin, DetailView):
524
525
526
527
528
    """
    Calculate a dictionary with operation target and sum of operations
    """
    model = GeneralJournal
    pk_url_kwarg = "j_id"
Skia's avatar
Skia committed
529
530
    template_name='accounting/journal_statement_person.jinja'
    current_tab='person_statement'
531

532
533
534
    def sum_by_target(self, target_id, target_type, movement_type):
        return self.object.operations.filter(accounting_type__movement_type=movement_type,
                target_id=target_id, target_type=target_type).aggregate(amount_sum=Sum('amount'))['amount_sum']
535

536
    def statement(self, movement_type):
Skia's avatar
Skia committed
537
538
539
        statement = collections.OrderedDict()
        for op in self.object.operations.filter(accounting_type__movement_type=movement_type).order_by('target_type',
                'target_id').distinct():
540
            statement[op.target] = self.sum_by_target(op.target_id, op.target_type, movement_type)
Skia's avatar
Skia committed
541
        return statement
542

543
544
    def total(self, movement_type):
        return sum(self.statement(movement_type).values())
545
546
547

    def get_context_data(self, **kwargs):
        """ Add journal to the context """
Skia's avatar
Skia committed
548
        kwargs = super(JournalPersonStatementView, self).get_context_data(**kwargs)
549
550
551
552
        kwargs['credit_statement'] = self.statement("CREDIT")
        kwargs['debit_statement'] = self.statement("DEBIT")
        kwargs['total_credit'] = self.total("CREDIT")
        kwargs['total_debit'] = self.total("DEBIT")
553
554
        return kwargs

Skia's avatar
Skia committed
555
class JournalAccountingStatementView(JournalTabsMixin, CanViewMixin, DetailView):
556
557
558
559
560
    """
    Calculate a dictionary with operation type and sum of operations
    """
    model = GeneralJournal
    pk_url_kwarg = "j_id"
Skia's avatar
Skia committed
561
562
    template_name='accounting/journal_statement_accounting.jinja'
    current_tab = "accounting_statement"
563

Skia's avatar
Skia committed
564
565
    def statement(self):
        statement = collections.OrderedDict()
Krophil's avatar
Krophil committed
566
        for at in AccountingType.objects.order_by('code').all():
Skia's avatar
Skia committed
567
568
            sum_by_type = self.object.operations.filter(
                accounting_type__code__startswith=at.code).aggregate(amount_sum=Sum('amount'))['amount_sum']
Skia's avatar
Skia committed
569
            if sum_by_type:
Skia's avatar
Skia committed
570
571
                statement[at] = sum_by_type
        return statement
572
573
574

    def get_context_data(self, **kwargs):
        """ Add journal to the context """
Skia's avatar
Skia committed
575
        kwargs = super(JournalAccountingStatementView, self).get_context_data(**kwargs)
Skia's avatar
Skia committed
576
        kwargs['statement'] = self.statement()
577
        return kwargs
578

Skia's avatar
Skia committed
579
580
# Company views

Krophil's avatar
Krophil committed
581
582
583
584
class CompanyListView(CanViewMixin, ListView):
    model = Company
    template_name = 'accounting/co_list.jinja'

Skia's avatar
Skia committed
585
586
587
588
589
590
591
class CompanyCreateView(CanCreateMixin, CreateView):
    """
    Create a company
    """
    model = Company
    fields = ['name']
    template_name = 'core/create.jinja'
Krophil's avatar
Krophil committed
592
593
    success_url = reverse_lazy('accounting:co_list')

Skia's avatar
Skia committed
594
595
596
597
598
599
600
601

class CompanyEditView(CanCreateMixin, UpdateView):
    """
    Edit a company
    """
    model = Company
    pk_url_kwarg = "co_id"
    fields = ['name']
Skia's avatar
Skia committed
602
    template_name = 'core/edit.jinja'
Krophil's avatar
Krophil committed
603
    success_url = reverse_lazy('accounting:co_list')
Skia's avatar
Skia committed
604

Skia's avatar
Skia committed
605
606
607
608
609
610
611
# Label views

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

Skia's avatar
Skia committed
612
class LabelCreateView(CanCreateMixin, CreateView): # FIXME we need to check the rights before creating the object
Skia's avatar
Skia committed
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
    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
640
641
642
643
644
645
646
647
648
649
650
651

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
652
        if user.is_root or user.is_in_group(settings.SITH_GROUP_ACCOUNTING_ADMIN_ID):
Sli's avatar
Sli committed
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
            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
678
679
            refound_club_counter = Counter.objects.get(id=settings.SITH_COUNTER_REFOUND_ID)
            refound_club = refound_club_counter.club
Sli's avatar
Sli committed
680
681
682
            s = Selling(label=_('Refound account'), unit_price=uprice,
                        quantity=1, seller=self.operator,
                        customer=self.customer.customer,
Sli's avatar
Sli committed
683
684
                        club=refound_club, counter=refound_club_counter,
                        product=Product.objects.get(id=settings.SITH_PRODUCT_REFOUND_ID))
Sli's avatar
Sli committed
685
            s.save()