views.py 28.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
# -*- coding:utf-8 -*
#
# Copyright 2016,2017
# - Skia <skia@libskia.so>
#
# Ce fichier fait partie du site de l'Association des Étudiants de l'UTBM,
# http://ae.utbm.fr.
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License a published by the Free Software
# Foundation; either version 3 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Sofware Foundation, Inc., 59 Temple
# Place - Suite 330, Boston, MA 02111-1307, USA.
#
#

Krophil's avatar
Krophil committed
25
from django.views.generic import ListView, DetailView
Sli's avatar
Sli committed
26 27 28
from django.views.generic.edit import UpdateView, CreateView, DeleteView, FormView
from django.core.urlresolvers import reverse_lazy, reverse
from django.utils.translation import ugettext_lazy as _
29
from django.forms.models import modelform_factory
30
from django.core.exceptions import PermissionDenied, ValidationError
Krophil's avatar
Krophil committed
31
from django.forms import HiddenInput
Sli's avatar
Sli committed
32
from django.db import transaction
Skia's avatar
Skia committed
33
from django.db.models import Sum
Sli's avatar
Sli committed
34
from django.conf import settings
Skia's avatar
Skia committed
35
from django import forms
Krophil's avatar
Krophil committed
36
from django.http import HttpResponse
Skia's avatar
Skia committed
37
import collections
Skia's avatar
Skia committed
38

Krophil's avatar
Krophil committed
39
from ajax_select.fields import AutoCompleteSelectField
Skia's avatar
Skia committed
40

Sli's avatar
Sli committed
41 42 43 44 45 46 47
from core.views import (
    CanViewMixin,
    CanEditMixin,
    CanEditPropMixin,
    CanCreateMixin,
    TabedViewMixin,
)
48
from core.views.forms import SelectFile, SelectDate
Sli's avatar
Sli committed
49 50 51 52 53 54 55 56 57 58
from accounting.models import (
    BankAccount,
    ClubAccount,
    GeneralJournal,
    Operation,
    AccountingType,
    Company,
    SimplifiedAccountingType,
    Label,
)
59
from counter.models import Counter, Selling, Product
Skia's avatar
Skia committed
60 61 62

# Main accounting view

Krophil's avatar
Krophil committed
63

Skia's avatar
Skia committed
64 65 66 67
class BankAccountListView(CanViewMixin, ListView):
    """
    A list view for the admins
    """
Sli's avatar
Sli committed
68

Skia's avatar
Skia committed
69
    model = BankAccount
Sli's avatar
Sli committed
70 71
    template_name = "accounting/bank_account_list.jinja"
    ordering = ["name"]
Skia's avatar
Skia committed
72

Krophil's avatar
Krophil committed
73

Skia's avatar
Skia committed
74 75
# Simplified accounting types

Sli's avatar
Sli committed
76

Skia's avatar
Skia committed
77 78 79 80
class SimplifiedAccountingTypeListView(CanViewMixin, ListView):
    """
    A list view for the admins
    """
Sli's avatar
Sli committed
81

Skia's avatar
Skia committed
82
    model = SimplifiedAccountingType
Sli's avatar
Sli committed
83
    template_name = "accounting/simplifiedaccountingtype_list.jinja"
Skia's avatar
Skia committed
84

Krophil's avatar
Krophil committed
85

Skia's avatar
Skia committed
86 87 88 89
class SimplifiedAccountingTypeEditView(CanViewMixin, UpdateView):
    """
    An edit view for the admins
    """
Sli's avatar
Sli committed
90

Skia's avatar
Skia committed
91 92
    model = SimplifiedAccountingType
    pk_url_kwarg = "type_id"
Sli's avatar
Sli committed
93 94
    fields = ["label", "accounting_type"]
    template_name = "core/edit.jinja"
Skia's avatar
Skia committed
95

Krophil's avatar
Krophil committed
96

Skia's avatar
Skia committed
97 98 99 100
class SimplifiedAccountingTypeCreateView(CanCreateMixin, CreateView):
    """
    Create an accounting type (for the admins)
    """
Sli's avatar
Sli committed
101

Skia's avatar
Skia committed
102
    model = SimplifiedAccountingType
Sli's avatar
Sli committed
103 104
    fields = ["label", "accounting_type"]
    template_name = "core/create.jinja"
Skia's avatar
Skia committed
105

Krophil's avatar
Krophil committed
106

Skia's avatar
Skia committed
107 108
# Accounting types

Sli's avatar
Sli committed
109

Skia's avatar
Skia committed
110 111 112 113
class AccountingTypeListView(CanViewMixin, ListView):
    """
    A list view for the admins
    """
Sli's avatar
Sli committed
114

Skia's avatar
Skia committed
115
    model = AccountingType
Sli's avatar
Sli committed
116
    template_name = "accounting/accountingtype_list.jinja"
Skia's avatar
Skia committed
117

Krophil's avatar
Krophil committed
118

Skia's avatar
Skia committed
119 120 121 122
class AccountingTypeEditView(CanViewMixin, UpdateView):
    """
    An edit view for the admins
    """
Sli's avatar
Sli committed
123

Skia's avatar
Skia committed
124 125
    model = AccountingType
    pk_url_kwarg = "type_id"
Sli's avatar
Sli committed
126 127
    fields = ["code", "label", "movement_type"]
    template_name = "core/edit.jinja"
Skia's avatar
Skia committed
128

Krophil's avatar
Krophil committed
129

130
class AccountingTypeCreateView(CanCreateMixin, CreateView):
Skia's avatar
Skia committed
131 132 133
    """
    Create an accounting type (for the admins)
    """
Sli's avatar
Sli committed
134

Skia's avatar
Skia committed
135
    model = AccountingType
Sli's avatar
Sli committed
136 137
    fields = ["code", "label", "movement_type"]
    template_name = "core/create.jinja"
Skia's avatar
Skia committed
138

Krophil's avatar
Krophil committed
139

Skia's avatar
Skia committed
140 141
# BankAccount views

Sli's avatar
Sli committed
142

Skia's avatar
Skia committed
143 144 145 146
class BankAccountEditView(CanViewMixin, UpdateView):
    """
    An edit view for the admins
    """
Sli's avatar
Sli committed
147

Skia's avatar
Skia committed
148 149
    model = BankAccount
    pk_url_kwarg = "b_account_id"
Sli's avatar
Sli committed
150 151
    fields = ["name", "iban", "number", "club"]
    template_name = "core/edit.jinja"
Skia's avatar
Skia committed
152

Krophil's avatar
Krophil committed
153

Skia's avatar
Skia committed
154 155 156 157
class BankAccountDetailView(CanViewMixin, DetailView):
    """
    A detail view, listing every club account
    """
Sli's avatar
Sli committed
158

Skia's avatar
Skia committed
159 160
    model = BankAccount
    pk_url_kwarg = "b_account_id"
Sli's avatar
Sli committed
161
    template_name = "accounting/bank_account_details.jinja"
Skia's avatar
Skia committed
162

Krophil's avatar
Krophil committed
163

164
class BankAccountCreateView(CanCreateMixin, CreateView):
Skia's avatar
Skia committed
165 166 167
    """
    Create a bank account (for the admins)
    """
Sli's avatar
Sli committed
168

Skia's avatar
Skia committed
169
    model = BankAccount
Sli's avatar
Sli committed
170 171
    fields = ["name", "club", "iban", "number"]
    template_name = "core/create.jinja"
Skia's avatar
Skia committed
172

Krophil's avatar
Krophil committed
173

Sli's avatar
Sli committed
174 175 176
class BankAccountDeleteView(
    CanEditPropMixin, DeleteView
):  # TODO change Delete to Close
Skia's avatar
Skia committed
177 178 179
    """
    Delete a bank account (for the admins)
    """
Sli's avatar
Sli committed
180

Skia's avatar
Skia committed
181 182
    model = BankAccount
    pk_url_kwarg = "b_account_id"
Sli's avatar
Sli committed
183 184
    template_name = "core/delete_confirm.jinja"
    success_url = reverse_lazy("accounting:bank_list")
Skia's avatar
Skia committed
185

Krophil's avatar
Krophil committed
186

Skia's avatar
Skia committed
187 188
# ClubAccount views

Sli's avatar
Sli committed
189

Skia's avatar
Skia committed
190 191 192 193
class ClubAccountEditView(CanViewMixin, UpdateView):
    """
    An edit view for the admins
    """
Sli's avatar
Sli committed
194

Skia's avatar
Skia committed
195 196
    model = ClubAccount
    pk_url_kwarg = "c_account_id"
Sli's avatar
Sli committed
197 198
    fields = ["name", "club", "bank_account"]
    template_name = "core/edit.jinja"
Skia's avatar
Skia committed
199

Krophil's avatar
Krophil committed
200

Skia's avatar
Skia committed
201 202 203 204
class ClubAccountDetailView(CanViewMixin, DetailView):
    """
    A detail view, listing every journal
    """
Sli's avatar
Sli committed
205

Skia's avatar
Skia committed
206 207
    model = ClubAccount
    pk_url_kwarg = "c_account_id"
Sli's avatar
Sli committed
208
    template_name = "accounting/club_account_details.jinja"
Skia's avatar
Skia committed
209

Krophil's avatar
Krophil committed
210

211
class ClubAccountCreateView(CanCreateMixin, CreateView):
Skia's avatar
Skia committed
212 213 214
    """
    Create a club account (for the admins)
    """
Sli's avatar
Sli committed
215

Skia's avatar
Skia committed
216
    model = ClubAccount
Sli's avatar
Sli committed
217 218
    fields = ["name", "club", "bank_account"]
    template_name = "core/create.jinja"
Skia's avatar
Skia committed
219 220 221

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

Krophil's avatar
Krophil committed
228

Sli's avatar
Sli committed
229 230 231
class ClubAccountDeleteView(
    CanEditPropMixin, DeleteView
):  # TODO change Delete to Close
Skia's avatar
Skia committed
232 233 234
    """
    Delete a club account (for the admins)
    """
Sli's avatar
Sli committed
235

Skia's avatar
Skia committed
236 237
    model = ClubAccount
    pk_url_kwarg = "c_account_id"
Sli's avatar
Sli committed
238 239
    template_name = "core/delete_confirm.jinja"
    success_url = reverse_lazy("accounting:bank_list")
Skia's avatar
Skia committed
240

Krophil's avatar
Krophil committed
241

Skia's avatar
Skia committed
242 243
# Journal views

Sli's avatar
Sli committed
244

Krophil's avatar
Krophil committed
245 246 247 248 249 250
class JournalTabsMixin(TabedViewMixin):
    def get_tabs_title(self):
        return _("Journal")

    def get_list_of_tabs(self):
        tab_list = []
Sli's avatar
Sli committed
251 252 253 254 255 256 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 284 285 286 287 288 289
        tab_list.append(
            {
                "url": reverse(
                    "accounting:journal_details", kwargs={"j_id": self.object.id}
                ),
                "slug": "journal",
                "name": _("Journal"),
            }
        )
        tab_list.append(
            {
                "url": reverse(
                    "accounting:journal_nature_statement",
                    kwargs={"j_id": self.object.id},
                ),
                "slug": "nature_statement",
                "name": _("Statement by nature"),
            }
        )
        tab_list.append(
            {
                "url": reverse(
                    "accounting:journal_person_statement",
                    kwargs={"j_id": self.object.id},
                ),
                "slug": "person_statement",
                "name": _("Statement by person"),
            }
        )
        tab_list.append(
            {
                "url": reverse(
                    "accounting:journal_accounting_statement",
                    kwargs={"j_id": self.object.id},
                ),
                "slug": "accounting_statement",
                "name": _("Accounting statement"),
            }
        )
Krophil's avatar
Krophil committed
290 291
        return tab_list

Krophil's avatar
Krophil committed
292

Skia's avatar
Skia committed
293
class JournalCreateView(CanCreateMixin, CreateView):
Skia's avatar
Skia committed
294 295 296
    """
    Create a general journal
    """
Sli's avatar
Sli committed
297

Skia's avatar
Skia committed
298
    model = GeneralJournal
Sli's avatar
Sli committed
299 300 301 302 303 304
    form_class = modelform_factory(
        GeneralJournal,
        fields=["name", "start_date", "club_account"],
        widgets={"start_date": SelectDate},
    )
    template_name = "core/create.jinja"
Skia's avatar
Skia committed
305 306 307

    def get_initial(self):
        ret = super(JournalCreateView, self).get_initial()
Sli's avatar
Sli committed
308 309
        if "parent" in self.request.GET.keys():
            obj = ClubAccount.objects.filter(id=int(self.request.GET["parent"])).first()
Skia's avatar
Skia committed
310
            if obj is not None:
Sli's avatar
Sli committed
311
                ret["club_account"] = obj.id
Skia's avatar
Skia committed
312
        return ret
Skia's avatar
Skia committed
313

Krophil's avatar
Krophil committed
314

Krophil's avatar
Krophil committed
315
class JournalDetailView(JournalTabsMixin, CanViewMixin, DetailView):
Skia's avatar
Skia committed
316 317 318
    """
    A detail view, listing every operation
    """
Sli's avatar
Sli committed
319

Skia's avatar
Skia committed
320 321
    model = GeneralJournal
    pk_url_kwarg = "j_id"
Sli's avatar
Sli committed
322 323
    template_name = "accounting/journal_details.jinja"
    current_tab = "journal"
Skia's avatar
Skia committed
324

Krophil's avatar
Krophil committed
325

Skia's avatar
Skia committed
326 327 328 329
class JournalEditView(CanEditMixin, UpdateView):
    """
    Update a general journal
    """
Sli's avatar
Sli committed
330

Skia's avatar
Skia committed
331 332
    model = GeneralJournal
    pk_url_kwarg = "j_id"
Sli's avatar
Sli committed
333 334
    fields = ["name", "start_date", "end_date", "club_account", "closed"]
    template_name = "core/edit.jinja"
Skia's avatar
Skia committed
335

Krophil's avatar
Krophil committed
336

337 338 339 340
class JournalDeleteView(CanEditPropMixin, DeleteView):
    """
    Delete a club account (for the admins)
    """
Sli's avatar
Sli committed
341

342 343
    model = GeneralJournal
    pk_url_kwarg = "j_id"
Sli's avatar
Sli committed
344 345
    template_name = "core/delete_confirm.jinja"
    success_url = reverse_lazy("accounting:club_details")
346

Krophil's avatar
Krophil committed
347
    def dispatch(self, request, *args, **kwargs):
Krophil's avatar
Krophil committed
348 349 350 351 352 353
        self.object = self.get_object()
        if self.object.operations.count() == 0:
            return super(JournalDeleteView, self).dispatch(request, *args, **kwargs)
        else:
            raise PermissionDenied

Krophil's avatar
Krophil committed
354

Skia's avatar
Skia committed
355 356
# Operation views

Sli's avatar
Sli committed
357

Skia's avatar
Skia committed
358 359 360
class OperationForm(forms.ModelForm):
    class Meta:
        model = Operation
Sli's avatar
Sli committed
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
        fields = [
            "amount",
            "remark",
            "journal",
            "target_type",
            "target_id",
            "target_label",
            "date",
            "mode",
            "cheque_number",
            "invoice",
            "simpleaccounting_type",
            "accounting_type",
            "label",
            "done",
        ]
Skia's avatar
Skia committed
377
        widgets = {
Sli's avatar
Sli committed
378 379 380 381
            "journal": HiddenInput,
            "target_id": HiddenInput,
            "date": SelectDate,
            "invoice": SelectFile,
Krophil's avatar
Krophil committed
382
        }
Sli's avatar
Sli committed
383 384 385 386 387 388 389 390 391 392 393 394

    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)
    need_link = forms.BooleanField(
        label=_("Link this operation to the target account"),
        required=False,
        initial=False,
    )
Skia's avatar
Skia committed
395 396

    def __init__(self, *args, **kwargs):
Sli's avatar
Sli committed
397
        club_account = kwargs.pop("club_account", None)
Skia's avatar
Skia committed
398
        super(OperationForm, self).__init__(*args, **kwargs)
Skia's avatar
Skia committed
399
        if club_account:
Sli's avatar
Sli committed
400
            self.fields["label"].queryset = club_account.labels.order_by("name").all()
Skia's avatar
Skia committed
401
        if self.instance.target_type == "USER":
Sli's avatar
Sli committed
402
            self.fields["user"].initial = self.instance.target_id
Skia's avatar
Skia committed
403
        elif self.instance.target_type == "ACCOUNT":
Sli's avatar
Sli committed
404
            self.fields["club_account"].initial = self.instance.target_id
Skia's avatar
Skia committed
405
        elif self.instance.target_type == "CLUB":
Sli's avatar
Sli committed
406
            self.fields["club"].initial = self.instance.target_id
Skia's avatar
Skia committed
407
        elif self.instance.target_type == "COMPANY":
Sli's avatar
Sli committed
408
            self.fields["company"].initial = self.instance.target_id
Skia's avatar
Skia committed
409 410 411

    def clean(self):
        self.cleaned_data = super(OperationForm, self).clean()
Sli's avatar
Sli committed
412 413 414 415 416 417 418 419 420 421 422
        if "target_type" in self.cleaned_data.keys():
            if (
                self.cleaned_data.get("user") is None
                and self.cleaned_data.get("club") is None
                and self.cleaned_data.get("club_account") is None
                and self.cleaned_data.get("company") is None
                and self.cleaned_data.get("target_label") is None
            ):
                self.add_error(
                    "target_type", ValidationError(_("The target must be set."))
                )
423
            else:
Sli's avatar
Sli committed
424 425 426 427 428 429 430 431 432 433
                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
434 435

        if self.cleaned_data.get("amount") is None:
Sli's avatar
Sli committed
436
            self.add_error("amount", ValidationError(_("The amount must be set.")))
437

Skia's avatar
Skia committed
438 439 440 441
        return self.cleaned_data

    def save(self):
        ret = super(OperationForm, self).save()
Sli's avatar
Sli committed
442 443 444 445 446 447
        if (
            self.instance.target_type == "ACCOUNT"
            and not self.instance.linked_operation
            and self.instance.target.has_open_journal()
            and self.cleaned_data["need_link"]
        ):
Skia's avatar
Skia committed
448 449
            inst = self.instance
            club_account = inst.target
Sli's avatar
Sli committed
450 451 452 453 454 455
            acc_type = (
                AccountingType.objects.exclude(movement_type="NEUTRAL")
                .exclude(movement_type=inst.accounting_type.movement_type)
                .order_by("code")
                .first()
            )  # Select a random opposite accounting type
Skia's avatar
Skia committed
456
            op = Operation(
Krophil's avatar
Krophil committed
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
                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,
            )
Skia's avatar
Skia committed
472 473 474 475 476
            op.save()
            self.instance.linked_operation = op
            self.save()
        return ret

Krophil's avatar
Krophil committed
477

478
class OperationCreateView(CanCreateMixin, CreateView):
Skia's avatar
Skia committed
479 480 481
    """
    Create an operation
    """
Sli's avatar
Sli committed
482

Skia's avatar
Skia committed
483
    model = Operation
Skia's avatar
Skia committed
484
    form_class = OperationForm
Sli's avatar
Sli committed
485
    template_name = "accounting/operation_edit.jinja"
Skia's avatar
Skia committed
486

Skia's avatar
Skia committed
487
    def get_form(self, form_class=None):
Sli's avatar
Sli committed
488
        self.journal = GeneralJournal.objects.filter(id=self.kwargs["j_id"]).first()
Skia's avatar
Skia committed
489 490 491
        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
492 493
    def get_initial(self):
        ret = super(OperationCreateView, self).get_initial()
Skia's avatar
Skia committed
494
        if self.journal is not None:
Sli's avatar
Sli committed
495
            ret["journal"] = self.journal.id
Skia's avatar
Skia committed
496
        return ret
Skia's avatar
Skia committed
497

Skia's avatar
Skia committed
498 499 500 501
    def get_context_data(self, **kwargs):
        """ Add journal to the context """
        kwargs = super(OperationCreateView, self).get_context_data(**kwargs)
        if self.journal:
Sli's avatar
Sli committed
502
            kwargs["object"] = self.journal
Skia's avatar
Skia committed
503 504
        return kwargs

Krophil's avatar
Krophil committed
505

Skia's avatar
Skia committed
506
class OperationEditView(CanEditMixin, UpdateView):
Skia's avatar
Skia committed
507 508 509
    """
    An edit view, working as detail for the moment
    """
Sli's avatar
Sli committed
510

Skia's avatar
Skia committed
511 512
    model = Operation
    pk_url_kwarg = "op_id"
Skia's avatar
Skia committed
513
    form_class = OperationForm
Sli's avatar
Sli committed
514
    template_name = "accounting/operation_edit.jinja"
Skia's avatar
Skia committed
515

Skia's avatar
Skia committed
516 517
    def get_context_data(self, **kwargs):
        """ Add journal to the context """
Skia's avatar
Skia committed
518
        kwargs = super(OperationEditView, self).get_context_data(**kwargs)
Sli's avatar
Sli committed
519
        kwargs["object"] = self.object.journal
Skia's avatar
Skia committed
520 521
        return kwargs

Krophil's avatar
Krophil committed
522

Krophil's avatar
Krophil committed
523 524 525 526 527 528 529 530 531 532 533
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
Krophil's avatar
Krophil committed
534
        from reportlab.platypus import Table, TableStyle
Krophil's avatar
Krophil committed
535 536 537 538 539 540
        from reportlab.lib import colors
        from reportlab.lib.pagesizes import letter
        from reportlab.lib.utils import ImageReader
        from reportlab.pdfbase.ttfonts import TTFont
        from reportlab.pdfbase import pdfmetrics

Sli's avatar
Sli committed
541
        pdfmetrics.registerFont(TTFont("DejaVu", "DejaVuSerif.ttf"))
Krophil's avatar
Krophil committed
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560

        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
        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()

Sli's avatar
Sli committed
561 562 563 564 565 566
        response = HttpResponse(content_type="application/pdf")
        response["Content-Disposition"] = 'filename="op-%d(%s_on_%s).pdf"' % (
            num,
            ti,
            club_name,
        )
Krophil's avatar
Krophil committed
567 568
        p = canvas.Canvas(response)

Sli's avatar
Sli committed
569
        p.setFont("DejaVu", 12)
Krophil's avatar
Krophil committed
570 571 572 573 574

        p.setTitle("%s %d" % (_("Operation"), num))
        width, height = letter
        im = ImageReader("core/static/core/img/logo.jpg")
        iw, ih = im.getSize()
Krophil's avatar
Krophil committed
575
        p.drawImage(im, 40, height - 50, width=iw / 2, height=ih / 2)
Skia's avatar
Skia committed
576

Krophil's avatar
Krophil committed
577 578 579
        labelStr = [["%s %s - %s %s" % (_("Journal"), ti, _("Operation"), num)]]

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

Sli's avatar
Sli committed
581
        label.setStyle(TableStyle([("ALIGN", (0, 0), (-1, -1), "RIGHT")]))
Krophil's avatar
Krophil committed
582
        w, h = label.wrapOn(label, 0, 0)
Krophil's avatar
Krophil committed
583
        label.drawOn(p, width - 180, height)
Krophil's avatar
Krophil committed
584

Sli's avatar
Sli committed
585 586 587 588 589 590 591 592 593 594 595 596
        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 is not None else ""},
        )
Krophil's avatar
Krophil committed
597
        p.drawString(90, height - 190, _("Date: %(date)s") % {"date": date})
Krophil's avatar
Krophil committed
598 599

        data = []
Skia's avatar
Skia committed
600

Sli's avatar
Sli committed
601 602 603
        data += [
            ["%s" % (_("Credit").upper() if nature == "CREDIT" else _("Debit").upper())]
        ]
Krophil's avatar
Krophil committed
604 605

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

Krophil's avatar
Krophil committed
607 608 609 610 611 612
        payment_mode = ""
        for m in settings.SITH_ACCOUNTING_PAYMENT_METHOD:
            if m[0] == mode:
                payment_mode += "[\u00D7]"
            else:
                payment_mode += "[  ]"
Krophil's avatar
Krophil committed
613
            payment_mode += " %s\n" % (m[1])
Krophil's avatar
Krophil committed
614 615

        data += [[payment_mode]]
Skia's avatar
Skia committed
616

Sli's avatar
Sli committed
617 618 619 620 621 622 623
        data += [
            [
                "%s : %s"
                % (_("Debtor") if nature == "CREDIT" else _("Creditor"), target),
                "",
            ]
        ]
Krophil's avatar
Krophil committed
624 625

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

Sli's avatar
Sli committed
627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
        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
648

Krophil's avatar
Krophil committed
649 650 651
        signature = []
        signature += [[_("Signature:")]]

Krophil's avatar
Krophil committed
652
        tSig = Table(signature, colWidths=[(width - 90 * 2)], rowHeights=[80])
Sli's avatar
Sli committed
653 654 655 656 657 658 659 660
        tSig.setStyle(
            TableStyle(
                [
                    ("VALIGN", (0, 0), (-1, -1), "TOP"),
                    ("BOX", (0, 0), (-1, -1), 0.25, colors.black),
                ]
            )
        )
Krophil's avatar
Krophil committed
661 662 663 664

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

Krophil's avatar
Krophil committed
665 666 667 668 669 670 671 672 673 674 675
        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

Krophil's avatar
Krophil committed
676

Skia's avatar
Skia committed
677
class JournalNatureStatementView(JournalTabsMixin, CanViewMixin, DetailView):
678
    """
Skia's avatar
Skia committed
679
    Display a statement sorted by labels
680
    """
Sli's avatar
Sli committed
681

682 683
    model = GeneralJournal
    pk_url_kwarg = "j_id"
Sli's avatar
Sli committed
684 685
    template_name = "accounting/journal_statement_nature.jinja"
    current_tab = "nature_statement"
686

Skia's avatar
Skia committed
687 688 689 690
    def statement(self, queryset, movement_type):
        ret = collections.OrderedDict()
        statement = collections.OrderedDict()
        total_sum = 0
Sli's avatar
Sli committed
691 692 693 694 695 696
        for sat in [None] + list(
            SimplifiedAccountingType.objects.order_by("label").all()
        ):
            sum = queryset.filter(
                accounting_type__movement_type=movement_type, simpleaccounting_type=sat
            ).aggregate(amount_sum=Sum("amount"))["amount_sum"]
Krophil's avatar
Krophil committed
697 698 699 700
            if sat:
                sat = sat.label
            else:
                sat = ""
Skia's avatar
Skia committed
701 702
            if sum:
                total_sum += sum
Skia's avatar
Skia committed
703
                statement[sat] = sum
Skia's avatar
Skia committed
704
        ret[movement_type] = statement
Krophil's avatar
Krophil committed
705
        ret[movement_type + "_sum"] = total_sum
Skia's avatar
Skia committed
706
        return ret
707

Skia's avatar
Skia committed
708
    def big_statement(self):
Sli's avatar
Sli committed
709 710 711
        label_list = (
            self.object.operations.order_by("label").values_list("label").distinct()
        )
Skia's avatar
Skia committed
712 713 714 715 716 717 718
        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
Sli's avatar
Sli committed
719 720 721 722 723 724
        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")
        )
Skia's avatar
Skia committed
725 726 727
        statement[_("No label operations")] = no_label_statement
        for l in labels:
            l_stmt = collections.OrderedDict()
Sli's avatar
Sli committed
728 729 730 731 732 733
            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")
            )
Skia's avatar
Skia committed
734 735
            statement[l] = l_stmt
        return statement
736

737
    def get_context_data(self, **kwargs):
Skia's avatar
Skia committed
738
        """ Add infos to the context """
Skia's avatar
Skia committed
739
        kwargs = super(JournalNatureStatementView, self).get_context_data(**kwargs)
Sli's avatar
Sli committed
740
        kwargs["statement"] = self.big_statement()
741 742
        return kwargs

Krophil's avatar
Krophil committed
743

Skia's avatar
Skia committed
744
class JournalPersonStatementView(JournalTabsMixin, CanViewMixin, DetailView):
745 746 747
    """
    Calculate a dictionary with operation target and sum of operations
    """
Sli's avatar
Sli committed
748

749 750
    model = GeneralJournal
    pk_url_kwarg = "j_id"
Sli's avatar
Sli committed
751 752
    template_name = "accounting/journal_statement_person.jinja"
    current_tab = "person_statement"
753

754
    def sum_by_target(self, target_id, target_type, movement_type):
Sli's avatar
Sli committed
755 756 757 758 759
        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"]
760

761
    def statement(self, movement_type):
Skia's avatar
Skia committed
762
        statement = collections.OrderedDict()
Sli's avatar
Sli committed
763 764 765 766 767 768 769 770
        for op in (
            self.object.operations.filter(accounting_type__movement_type=movement_type)
            .order_by("target_type", "target_id")
            .distinct()
        ):
            statement[op.target] = self.sum_by_target(
                op.target_id, op.target_type, movement_type
            )
Skia's avatar
Skia committed
771
        return statement
772

773 774
    def total(self, movement_type):
        return sum(self.statement(movement_type).values())
775 776 777

    def get_context_data(self, **kwargs):
        """ Add journal to the context """
Skia's avatar
Skia committed
778
        kwargs = super(JournalPersonStatementView, self).get_context_data(**kwargs)
Sli's avatar
Sli committed
779 780 781 782
        kwargs["credit_statement"] = self.statement("CREDIT")
        kwargs["debit_statement"] = self.statement("DEBIT")
        kwargs["total_credit"] = self.total("CREDIT")
        kwargs["total_debit"] = self.total("DEBIT")
783 784
        return kwargs

Krophil's avatar
Krophil committed
785

Skia's avatar
Skia committed
786
class JournalAccountingStatementView(JournalTabsMixin, CanViewMixin, DetailView):
787 788 789
    """
    Calculate a dictionary with operation type and sum of operations
    """
Sli's avatar
Sli committed
790

791 792
    model = GeneralJournal
    pk_url_kwarg = "j_id"
Sli's avatar
Sli committed
793
    template_name = "accounting/journal_statement_accounting.jinja"
Skia's avatar
Skia committed
794
    current_tab = "accounting_statement"
795

Skia's avatar
Skia committed
796 797
    def statement(self):
        statement = collections.OrderedDict()
Sli's avatar
Sli committed
798
        for at in AccountingType.objects.order_by("code").all():
Skia's avatar
Skia committed
799
            sum_by_type = self.object.operations.filter(
Sli's avatar
Sli committed
800 801
                accounting_type__code__startswith=at.code
            ).aggregate(amount_sum=Sum("amount"))["amount_sum"]
Skia's avatar
Skia committed
802
            if sum_by_type:
Skia's avatar
Skia committed
803 804
                statement[at] = sum_by_type
        return statement
805 806 807

    def get_context_data(self, **kwargs):
        """ Add journal to the context """
Skia's avatar
Skia committed
808
        kwargs = super(JournalAccountingStatementView, self).get_context_data(**kwargs)
Sli's avatar
Sli committed
809
        kwargs["statement"] = self.statement()
810
        return kwargs
811

Sli's avatar
Sli committed
812

Skia's avatar
Skia committed
813 814
# Company views

Krophil's avatar
Krophil committed
815

Krophil's avatar
Krophil committed
816 817
class CompanyListView(CanViewMixin, ListView):
    model = Company
Sli's avatar
Sli committed
818
    template_name = "accounting/co_list.jinja"
Krophil's avatar
Krophil committed
819

Krophil's avatar
Krophil committed
820

Skia's avatar
Skia committed
821 822 823 824
class CompanyCreateView(CanCreateMixin, CreateView):
    """
    Create a company
    """
Sli's avatar
Sli committed
825

Skia's avatar
Skia committed
826
    model = Company
Sli's avatar
Sli committed
827 828 829
    fields = ["name"]
    template_name = "core/create.jinja"
    success_url = reverse_lazy("accounting:co_list")
Krophil's avatar
Krophil committed
830

Skia's avatar
Skia committed
831 832 833 834 835

class CompanyEditView(CanCreateMixin, UpdateView):
    """
    Edit a company
    """
Sli's avatar
Sli committed
836

Skia's avatar
Skia committed
837 838
    model = Company
    pk_url_kwarg = "co_id"
Sli's avatar
Sli committed
839 840 841
    fields = ["name"]
    template_name = "core/edit.jinja"
    success_url = reverse_lazy("accounting:co_list")
Skia's avatar
Skia committed
842

Krophil's avatar
Krophil committed
843

Skia's avatar
Skia committed
844 845
# Label views

Sli's avatar
Sli committed
846

Skia's avatar
Skia committed
847 848 849
class LabelListView(CanViewMixin, DetailView):
    model = ClubAccount
    pk_url_kwarg = "clubaccount_id"
Sli's avatar
Sli committed
850
    template_name = "accounting/label_list.jinja"
Skia's avatar
Skia committed
851

Krophil's avatar
Krophil committed
852

Sli's avatar
Sli committed
853 854 855
class LabelCreateView(
    CanCreateMixin, CreateView
):  # FIXME we need to check the rights before creating the object
Skia's avatar
Skia committed
856
    model = Label
Sli's avatar
Sli committed
857 858 859 860
    form_class = modelform_factory(
        Label, fields=["name", "club_account"], widgets={"club_account": HiddenInput}
    )
    template_name = "core/create.jinja"
Skia's avatar
Skia committed
861 862 863

    def get_initial(self):
        ret = super(LabelCreateView, self).get_initial()
Sli's avatar
Sli committed
864 865
        if "parent" in self.request.GET.keys():
            obj = ClubAccount.objects.filter(id=int(self.request.GET["parent"])).first()
Skia's avatar
Skia committed
866
            if obj is not None:
Sli's avatar
Sli committed
867
                ret["club_account"] = obj.id
Skia's avatar
Skia committed
868 869
        return ret

Krophil's avatar
Krophil committed
870

Skia's avatar
Skia committed
871 872 873
class LabelEditView(CanEditMixin, UpdateView):
    model = Label
    pk_url_kwarg = "label_id"
Sli's avatar
Sli committed
874 875
    fields = ["name"]
    template_name = "core/edit.jinja"
Skia's avatar
Skia committed
876

Krophil's avatar
Krophil committed
877

Skia's avatar
Skia committed
878 879 880
class LabelDeleteView(CanEditMixin, DeleteView):
    model = Label
    pk_url_kwarg = "label_id"
Sli's avatar
Sli committed
881
    template_name = "core/delete_confirm.jinja"
Skia's avatar
Skia committed
882 883 884

    def get_success_url(self):
        return self.object.get_absolute_url()
Sli's avatar
Sli committed
885

Krophil's avatar
Krophil committed
886

Sli's avatar
Sli committed
887
class CloseCustomerAccountForm(forms.Form):
Sli's avatar
Sli committed
888 889 890
    user = AutoCompleteSelectField(
        "users", label=_("Refound this account"), help_text=None, required=True
    )
Sli's avatar
Sli committed
891

Krophil's avatar
Krophil committed
892

Sli's avatar
Sli committed
893 894 895 896
class RefoundAccountView(FormView):
    """
    Create a selling with the same amount than the current user money
    """
Sli's avatar
Sli committed
897

Sli's avatar
Sli committed
898 899 900 901
    template_name = "accounting/refound_account.jinja"
    form_class = CloseCustomerAccountForm

    def permission(self, user):
Skia's avatar
Skia committed
902
        if user.is_root or user.is_in_group(settings.SITH_GROUP_ACCOUNTING_ADMIN_ID):
Sli's avatar
Sli committed
903 904 905 906 907 908 909 910 911 912 913 914 915 916 917
            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):
Sli's avatar
Sli committed
918
        self.customer = form.cleaned_data["user"]
Sli's avatar
Sli committed
919 920 921 922
        self.create_selling()
        return super(RefoundAccountView, self).form_valid(form)

    def get_success_url(self):
Sli's avatar
Sli committed
923
        return reverse("accounting:refound_account")
Sli's avatar
Sli committed
924 925 926 927

    def create_selling(self):
        with transaction.atomic():
            uprice = self.customer.customer.amount
Sli's avatar
Sli committed
928 929 930
            refound_club_counter = Counter.objects.get(
                id=settings.SITH_COUNTER_REFOUND_ID
            )
Sli's avatar
Sli committed
931
            refound_club = refound_club_counter.club
Sli's avatar
Sli committed
932 933 934 935 936 937 938 939 940 941
            s = Selling(
                label=_("Refound account"),
                unit_price=uprice,
                quantity=1,
                seller=self.operator,
                customer=self.customer.customer,
                club=refound_club,
                counter=refound_club_counter,
                product=Product.objects.get(id=settings.SITH_PRODUCT_REFOUND_ID),
            )
Sli's avatar
Sli committed
942
            s.save()