invoice.py 25.8 KB
Newer Older
Patrick's avatar
Patrick committed
1 2 3 4 5 6 7 8
# -*- coding: utf-8
from __future__ import unicode_literals

import datetime

from django.core.validators import MinValueValidator
from django.db import models
from django.db import transaction
Patrick's avatar
Patrick committed
9
from django.db.models import F, Sum
Patrick's avatar
Patrick committed
10
from django.utils.encoding import python_2_unicode_compatible
Patrick's avatar
Patrick committed
11
from django.utils.formats import number_format
Patrick's avatar
Patrick committed
12
from django.utils.text import slugify
Patrick's avatar
Patrick committed
13 14
from django.utils.translation import ugettext_lazy as _

Patrick's avatar
Patrick committed
15
import producer
16
import purchase
Patrick's avatar
Patrick committed
17
from repanier.apps import DJANGO_IS_MIGRATION_RUNNING
Patrick's avatar
Patrick committed
18 19
from repanier.const import *
from repanier.fields.RepanierMoneyField import ModelMoneyField
Patrick's avatar
Patrick committed
20
from repanier.tools import update_or_create_purchase, get_signature
Patrick's avatar
Patrick committed
21 22


Patrick's avatar
Patrick committed
23 24 25 26
def permanence_verbose_name():
    if DJANGO_IS_MIGRATION_RUNNING:
        return EMPTY_STRING
    from repanier.apps import REPANIER_SETTINGS_PERMANENCE_NAME
Patrick's avatar
Patrick committed
27
    return _('order') # lambda: "%s" % REPANIER_SETTINGS_PERMANENCE_NAME
Patrick's avatar
Patrick committed
28 29


Patrick's avatar
Patrick committed
30 31 32 33 34
@python_2_unicode_compatible
class CustomerInvoice(models.Model):
    customer = models.ForeignKey(
        'Customer', verbose_name=_("customer"),
        on_delete=models.PROTECT)
Patrick's avatar
Patrick committed
35 36 37
    customer_charged = models.ForeignKey(
        'Customer', verbose_name=_("customer"), related_name='invoices_paid', blank=True, null=True,
        on_delete=models.PROTECT, db_index=True)
Patrick's avatar
Patrick committed
38
    permanence = models.ForeignKey(
Patrick's avatar
Patrick committed
39
        'Permanence', verbose_name=permanence_verbose_name(),
Patrick's avatar
Patrick committed
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
        on_delete=models.PROTECT, db_index=True)
    delivery = models.ForeignKey(
        'DeliveryBoard', verbose_name=_("delivery board"),
        null=True, blank=True, default=None,
        on_delete=models.PROTECT)
    status = models.CharField(
        max_length=3,
        choices=LUT_PERMANENCE_STATUS,
        default=PERMANENCE_PLANNED,
        verbose_name=_("invoice_status"))

    # IMPORTANT: default = True -> for the order form, to display nothing at the begin of the order
    # is_order_confirm_send and total_price_with_tax = 0 --> display nothing
    # otherwise display
    # - send a mail with the order to me
    # - confirm the order (if REPANIER_SETTINGS_CUSTOMERS_MUST_CONFIRM_ORDERS) and send a mail with the order to me
    # - mail send to XYZ
    # - order confirmed (if REPANIER_SETTINGS_CUSTOMERS_MUST_CONFIRM_ORDERS) and mail send to XYZ
    is_order_confirm_send = models.BooleanField(_("is_order_confirm_send"), choices=LUT_CONFIRM, default=False)
    invoice_sort_order = models.IntegerField(
        _("invoice sort order"),
        default=None, blank=True, null=True, db_index=True)
    date_previous_balance = models.DateField(
        _("date_previous_balance"), default=datetime.date.today)
    previous_balance = ModelMoneyField(
        _("previous_balance"), max_digits=8, decimal_places=2, default=DECIMAL_ZERO)
    # Calculated with Purchase
    total_price_with_tax = ModelMoneyField(
        _("Total amount"),
        help_text=_('Total purchase amount vat included'),
        default=DECIMAL_ZERO, max_digits=8, decimal_places=2)
    total_vat = ModelMoneyField(
        _("Total vat"),
        help_text=_('Vat part of the total purchased'),
        default=DECIMAL_ZERO, max_digits=9, decimal_places=4)
    total_deposit = ModelMoneyField(
        _("deposit"),
        help_text=_('deposit to add to the original unit price'),
        default=DECIMAL_ZERO, max_digits=8, decimal_places=2)
    delta_price_with_tax = ModelMoneyField(
        _("Total amount"),
        help_text=_('purchase to add amount vat included'),
        default=DECIMAL_ZERO, max_digits=8, decimal_places=2)
    delta_vat = ModelMoneyField(
        _("Total vat"),
        help_text=_('vat to add'),
        default=DECIMAL_ZERO, max_digits=9, decimal_places=4)
    delta_transport = ModelMoneyField(
        _("Delivery point transport"),
        help_text=_("transport to add"),
        default=DECIMAL_ZERO, max_digits=5, decimal_places=2,
        validators=[MinValueValidator(0)])
    bank_amount_in = ModelMoneyField(
        _("bank_amount_in"), help_text=_('payment_on_the_account'),
        max_digits=8, decimal_places=2, default=DECIMAL_ZERO)
    bank_amount_out = ModelMoneyField(
        _("bank_amount_out"), help_text=_('payment_from_the_account'),
        max_digits=8, decimal_places=2, default=DECIMAL_ZERO)
    date_balance = models.DateField(
        _("date_balance"), default=datetime.date.today)
    balance = ModelMoneyField(
        _("balance"),
        max_digits=8, decimal_places=2, default=DECIMAL_ZERO)
    price_list_multiplier = models.DecimalField(
        _("Delivery point price list multiplier"),
        help_text=_("This multiplier is applied once for groups with entitled customer or at each customer invoice for open groups."),
        default=DECIMAL_ONE, max_digits=5, decimal_places=4, blank=True,
        validators=[MinValueValidator(0)])
    transport = ModelMoneyField(
        _("Delivery point shipping cost"),
        help_text=_("This amount is added once for groups with entitled customer or at each customer for open groups."),
        default=DECIMAL_ZERO, max_digits=5, decimal_places=2,
        validators=[MinValueValidator(0)])
    min_transport = ModelMoneyField(
        _("Minium order amount for free shipping cost"),
        help_text=_("This is the minimum order amount to avoid shipping cost."),
        default=DECIMAL_ZERO, max_digits=5, decimal_places=2,
        validators=[MinValueValidator(0)])
Patrick's avatar
Patrick committed
118 119 120 121 122
    master_permanence = models.ForeignKey(
        'Permanence', verbose_name=_("master permanence"),
        related_name='child_customer_invoice',
        blank=True, null=True, default=None,
        on_delete=models.PROTECT, db_index=True)
Patrick's avatar
WIP  
Patrick committed
123
    is_group = models.BooleanField(_("is a group"), default=False)
Patrick's avatar
Patrick committed
124 125 126 127 128 129 130 131 132 133

    def get_delta_price_with_tax(self):
        return self.delta_price_with_tax.amount

    def get_abs_delta_price_with_tax(self):
        return abs(self.delta_price_with_tax)

    def get_abs_delta_vat(self):
        return abs(self.delta_vat)

Patrick's avatar
Patrick committed
134 135
    def get_total_price_with_tax(self, customer_charged=False):
        if self.customer_id == self.customer_charged_id:
Patrick's avatar
Patrick committed
136 137
            return self.total_price_with_tax + self.delta_price_with_tax + self.delta_transport
        else:
Patrick's avatar
Patrick committed
138
            if self.status < PERMANENCE_INVOICED or not customer_charged:
Patrick's avatar
Patrick committed
139 140
                return self.total_price_with_tax
            else:
141
                return self.customer_charged # if self.total_price_with_tax != DECIMAL_ZERO else RepanierMoney()
Patrick's avatar
Patrick committed
142

Patrick's avatar
Patrick committed
143 144 145 146 147 148 149
    def get_total_price_wo_tax(self):
        return self.get_total_price_with_tax() - self.get_total_tax()

    def get_total_tax(self):
        # round to 2 decimals
        return RepanierMoney(self.total_vat.amount + self.delta_vat.amount)

Patrick's avatar
Patrick committed
150 151 152
    @transaction.atomic
    def set_delivery(self, delivery):
        # May not use delivery_id because it won't reload customer_invoice.delivery
Patrick's avatar
WIP  
Patrick committed
153 154 155 156 157 158 159 160
        # Important
        # Si c'est une facture du membre d'un groupe :
        #   self.customer_charged_id != self.customer_id
        #   self.customer_charged_id == owner of the group
        #   price_list_multiplier = DECIMAL_ONE
        # Si c'est une facture lambda ou d'un groupe :
        #   self.customer_charged_id = self.customer_id
        #   price_list_multiplier may vary
Patrick's avatar
Patrick committed
161 162 163 164 165 166 167 168 169 170 171
        from repanier.apps import REPANIER_SETTINGS_TRANSPORT, REPANIER_SETTINGS_MIN_TRANSPORT
        self.delivery = delivery
        if delivery is None:
            if self.permanence.with_delivery_point:
                delivery_point = self.customer.delivery_point
            else:
                delivery_point = None
        else:
            delivery_point = delivery.delivery_point

        if delivery_point is None:
Patrick's avatar
Patrick committed
172
            self.customer_charged = self.customer
Patrick's avatar
Patrick committed
173 174 175 176 177 178
            self.price_list_multiplier = DECIMAL_ONE
            self.transport = REPANIER_SETTINGS_TRANSPORT
            self.min_transport = REPANIER_SETTINGS_MIN_TRANSPORT
        else:
            customer_responsible = delivery_point.customer_responsible
            if customer_responsible is None:
Patrick's avatar
Patrick committed
179
                self.customer_charged = self.customer
Patrick's avatar
Patrick committed
180 181 182 183
                self.price_list_multiplier = delivery_point.price_list_multiplier
                self.transport = delivery_point.transport
                self.min_transport = delivery_point.min_transport
            else:
Patrick's avatar
Patrick committed
184 185
                self.customer_charged = customer_responsible
                self.price_list_multiplier = DECIMAL_ONE
Patrick's avatar
Patrick committed
186 187 188
                self.transport = REPANIER_MONEY_ZERO
                self.min_transport = REPANIER_MONEY_ZERO
                if self.customer_id != customer_responsible.id:
Patrick's avatar
Patrick committed
189
                    customer_invoice_charged = CustomerInvoice.objects.filter(
Patrick's avatar
Patrick committed
190 191
                        permanence_id=self.permanence_id,
                        customer_id=customer_responsible.id
Patrick's avatar
Patrick committed
192 193
                    ).order_by('?')
                    if not customer_invoice_charged.exists():
Patrick's avatar
Patrick committed
194 195 196 197
                        CustomerInvoice.objects.create(
                            permanence_id=self.permanence_id,
                            customer_id=customer_responsible.id,
                            status=self.status,
Patrick's avatar
Patrick committed
198
                            customer_charged_id=customer_responsible.id,
Patrick's avatar
Patrick committed
199 200 201
                            price_list_multiplier=delivery_point.price_list_multiplier,
                            transport=delivery_point.transport,
                            min_transport=delivery_point.min_transport,
Patrick's avatar
WIP  
Patrick committed
202
                            is_order_confirm_send=True,
Patrick's avatar
WIP  
Patrick committed
203 204
                            is_group=True,
                            delivery=delivery
Patrick's avatar
Patrick committed
205 206 207 208
                        )

    @transaction.atomic
    def confirm_order(self):
209 210 211
        purchase.Purchase.objects.filter(
            customer_invoice__id=self.id
        ).update(quantity_confirmed=F('quantity_ordered'))
Patrick's avatar
RC  
Patrick committed
212
        self.calculate_and_save_delta_buyinggroup(confirm_order=True)
Patrick's avatar
Patrick committed
213 214
        self.is_order_confirm_send = True

Patrick's avatar
RC  
Patrick committed
215
    def calculate_and_save_delta_buyinggroup(self, confirm_order=False):
Patrick's avatar
Patrick committed
216 217 218
        previous_delta_price_with_tax = self.delta_price_with_tax.amount
        previous_delta_vat = self.delta_vat.amount
        previous_delta_transport = self.delta_transport.amount
Patrick's avatar
Patrick committed
219

Patrick's avatar
RC  
Patrick committed
220
        self.calculate_delta_price(confirm_order)
Patrick's avatar
Patrick committed
221 222
        self.calculate_delta_transport()

Patrick's avatar
Patrick committed
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
        if previous_delta_price_with_tax != self.delta_price_with_tax.amount or previous_delta_vat != self.delta_vat.amount or previous_delta_transport != self.delta_transport.amount:
            producer_invoice_buyinggroup = ProducerInvoice.objects.filter(
                producer__represent_this_buyinggroup=True,
                permanence_id=self.permanence_id,
            ).order_by('?').first()
            if producer_invoice_buyinggroup is None:
                producer_buyinggroup = producer.Producer.objects.filter(
                    represent_this_buyinggroup=True
                ).order_by('?').first()
                producer_invoice_buyinggroup = ProducerInvoice.objects.create(
                    producer_id=producer_buyinggroup.id,
                    permanence_id=self.permanence_id,
                    status=self.permanence.status
                )
            producer_invoice_buyinggroup.delta_price_with_tax.amount += self.delta_price_with_tax.amount - previous_delta_price_with_tax
            producer_invoice_buyinggroup.delta_vat.amount += self.delta_vat.amount - previous_delta_vat
            producer_invoice_buyinggroup.delta_transport.amount += self.delta_transport.amount - previous_delta_transport

            producer_invoice_buyinggroup.save()
Patrick's avatar
Patrick committed
242

Patrick's avatar
RC  
Patrick committed
243
    def calculate_delta_price(self, confirm_order=False):
Patrick's avatar
Patrick committed
244 245
        getcontext().rounding = ROUND_HALF_UP

Patrick's avatar
WIP  
Patrick committed
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 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
        self.delta_price_with_tax.amount = DECIMAL_ZERO
        self.delta_vat.amount = DECIMAL_ZERO

        # Important
        # Si c'est une facture du membre d'un groupe :
        #   self.customer_charged_id == purchase.customer_charged_id != self.customer_id
        #   self.customer_charged_id == purchase.customer_charged_id == owner of the group
        #   self.price_list_multiplier = DECIMAL_ONE
        # Si c'est une facture lambda ou d'un groupe :
        #   self.customer_charged_id == purchase.customer_charged_id = self.customer_id
        #   self.price_list_multiplier may vary
        if self.customer_id == self.customer_charged_id:

            if self.price_list_multiplier != DECIMAL_ONE:
                result_set = purchase.Purchase.objects.filter(
                    permanence_id=self.permanence_id,
                    customer_invoice__customer_charged_id=self.customer_id,
                    is_resale_price_fixed=False
                ).order_by('?').aggregate(
                    Sum('customer_vat'),
                    Sum('deposit'),
                    Sum('selling_price')
                )

                if result_set["customer_vat__sum"] is not None:
                    total_vat = result_set["customer_vat__sum"]
                else:
                    total_vat = DECIMAL_ZERO
                if result_set["deposit__sum"] is not None:
                    total_deposit = result_set["deposit__sum"]
                else:
                    total_deposit = DECIMAL_ZERO
                if result_set["selling_price__sum"] is not None:
                    total_price_with_tax = result_set["selling_price__sum"]
                else:
                    total_price_with_tax = DECIMAL_ZERO

                total_price_with_tax_wo_deposit = total_price_with_tax - total_deposit
                self.delta_price_with_tax.amount = -(
                    total_price_with_tax_wo_deposit - (
                        total_price_with_tax_wo_deposit * self.price_list_multiplier
                    ).quantize(TWO_DECIMALS)
                )
                self.delta_vat.amount = -(
                    total_vat - (
                        total_vat * self.price_list_multiplier
                    ).quantize(FOUR_DECIMALS)
                )

Patrick's avatar
Patrick committed
295 296
            result_set = purchase.Purchase.objects.filter(
                permanence_id=self.permanence_id,
Patrick's avatar
WIP  
Patrick committed
297
                customer_invoice__customer_charged_id=self.customer_id,
Patrick's avatar
Patrick committed
298 299 300 301 302 303 304 305
            ).order_by('?').aggregate(
                Sum('customer_vat'),
                Sum('deposit'),
                Sum('selling_price')
            )
        else:
            result_set = purchase.Purchase.objects.filter(
                permanence_id=self.permanence_id,
Patrick's avatar
WIP  
Patrick committed
306
                customer_id=self.customer_id,
Patrick's avatar
Patrick committed
307 308 309 310 311
            ).order_by('?').aggregate(
                Sum('customer_vat'),
                Sum('deposit'),
                Sum('selling_price')
            )
Patrick's avatar
Patrick committed
312 313 314 315 316 317 318 319 320 321 322 323
        if result_set["customer_vat__sum"] is not None:
            self.total_vat.amount = result_set["customer_vat__sum"]
        else:
            self.total_vat.amount = DECIMAL_ZERO
        if result_set["deposit__sum"] is not None:
            self.total_deposit.amount = result_set["deposit__sum"]
        else:
            self.total_deposit.amount = DECIMAL_ZERO
        if result_set["selling_price__sum"] is not None:
            self.total_price_with_tax.amount = result_set["selling_price__sum"]
        else:
            self.total_price_with_tax.amount = DECIMAL_ZERO
Patrick's avatar
Patrick committed
324

Patrick's avatar
Patrick committed
325 326 327 328 329 330 331
    def calculate_delta_transport(self):

        self.delta_transport.amount = DECIMAL_ZERO
        if self.master_permanence_id is None and self.transport.amount != DECIMAL_ZERO:
            # Calculate transport only on master customer invoice
            # But take into account the children customer invoices
            result_set = CustomerInvoice.objects.filter(
Patrick's avatar
WIP  
Patrick committed
332
                master_permanence_id=self.permanence_id
Patrick's avatar
Patrick committed
333 334 335 336 337 338 339 340 341 342 343 344
            ).order_by('?').aggregate(
                Sum('total_price_with_tax'),
                Sum('delta_price_with_tax')
            )
            if result_set["total_price_with_tax__sum"] is not None:
                sum_total_price_with_tax = result_set["total_price_with_tax__sum"]
            else:
                sum_total_price_with_tax = DECIMAL_ZERO
            if result_set["delta_price_with_tax__sum"] is not None:
                sum_delta_price_with_tax = result_set["delta_price_with_tax__sum"]
            else:
                sum_delta_price_with_tax = DECIMAL_ZERO
Patrick's avatar
Patrick committed
345

Patrick's avatar
Patrick committed
346 347
            sum_total_price_with_tax += self.total_price_with_tax.amount
            sum_delta_price_with_tax += self.delta_price_with_tax.amount
Patrick's avatar
Patrick committed
348

Patrick's avatar
Patrick committed
349 350 351 352 353 354 355 356 357
            total_price_with_tax = sum_total_price_with_tax + sum_delta_price_with_tax
            if total_price_with_tax != DECIMAL_ZERO:
                if self.min_transport.amount == DECIMAL_ZERO:
                    self.delta_transport.amount = self.transport.amount
                elif total_price_with_tax < self.min_transport.amount:
                    self.delta_transport.amount = min(
                        self.min_transport.amount - total_price_with_tax,
                        self.transport.amount
                    )
Patrick's avatar
Patrick committed
358 359

    def cancel_confirm_order(self):
360 361 362 363 364 365 366
        if self.is_order_confirm_send:
            # Change of confirmation status
            self.is_order_confirm_send = False
            return True
        else:
            # No change of confirmation status
            return False
Patrick's avatar
Patrick committed
367

Patrick's avatar
Patrick committed
368
    def create_child(self, new_permanence):
Patrick's avatar
WIP  
Patrick committed
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
        if self.customer_id != self.customer_charged_id:
            # TODO : Créer la customer invoice du groupe
            customer_invoice = CustomerInvoice.objects.filter(
                permanence_id=self.permanence_id,
                customer_id=self.customer_charged_id
            ).only("id").order_by('?')
            if not customer_invoice.exists():
                customer_invoice = CustomerInvoice.objects.create(
                    permanence_id=self.permanence_id,
                    customer_id=self.customer_charged_id,
                    customer_charged_id=self.customer_charged_id,
                    status=self.status
                )
                customer_invoice.set_delivery(delivery=None)
                customer_invoice.save()
Patrick's avatar
Patrick committed
384 385 386 387
        return CustomerInvoice.objects.create(
            permanence_id=new_permanence.id,
            customer_id=self.customer_id,
            master_permanence_id=self.permanence_id,
Patrick's avatar
WIP  
Patrick committed
388
            customer_charged_id=self.customer_charged_id,
Patrick's avatar
Patrick committed
389 390 391
            status=self.status
        )

Patrick's avatar
Patrick committed
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
    def delete_if_unconfirmed(self, permanence):
        if not self.is_order_confirm_send:
            from repanier.email.email_order import export_order_2_1_customer

            filename = "{0}-{1}.xlsx".format(
                slugify(_("Canceled order")),
                slugify(permanence)
            )
            sender_email, sender_function, signature, cc_email_staff = get_signature(
                is_reply_to_order_email=True)
            export_order_2_1_customer(
                self.customer, filename, permanence, sender_email,
                sender_function, signature,
                cancel_order=True
            )
            purchase_qs = purchase.Purchase.objects.filter(
                customer_invoice_id=self.id,
                is_box_content=False,
            ).order_by('?')
            for a_purchase in purchase_qs.select_related("customer"):
                update_or_create_purchase(
                    customer=a_purchase.customer,
                    offer_item_id=a_purchase.offer_item_id,
                    q_order=DECIMAL_ZERO,
Patrick's avatar
Patrick committed
416
                    batch_job=True,
417
                    comment=_("Cancelled qty : %s") % number_format(a_purchase.quantity_ordered, 4)
Patrick's avatar
Patrick committed
418 419
                )

Patrick's avatar
Patrick committed
420 421 422 423 424 425 426 427 428 429 430 431 432
    def __str__(self):
        return '%s, %s' % (self.customer, self.permanence)

    class Meta:
        verbose_name = _("customer invoice")
        verbose_name_plural = _("customers invoices")
        unique_together = ("permanence", "customer",)


@python_2_unicode_compatible
class ProducerInvoice(models.Model):
    producer = models.ForeignKey(
        'Producer', verbose_name=_("producer"),
Patrick's avatar
WIP  
Patrick committed
433
        # related_name='producer_invoice',
Patrick's avatar
Patrick committed
434 435
        on_delete=models.PROTECT)
    permanence = models.ForeignKey(
Patrick's avatar
Patrick committed
436
        'Permanence', verbose_name=permanence_verbose_name(),
Patrick's avatar
Patrick committed
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
        on_delete=models.PROTECT, db_index=True)
    status = models.CharField(
        max_length=3,
        choices=LUT_PERMANENCE_STATUS,
        default=PERMANENCE_PLANNED,
        verbose_name=_("invoice_status"))
    date_previous_balance = models.DateField(
        _("date_previous_balance"), default=datetime.date.today)
    previous_balance = ModelMoneyField(
        _("previous_balance"), max_digits=8, decimal_places=2, default=DECIMAL_ZERO)
    # Calculated with Purchase
    total_price_with_tax = ModelMoneyField(
        _("Total amount"),
        help_text=_('Total purchase amount vat included'),
        default=DECIMAL_ZERO, max_digits=8, decimal_places=2)
    total_vat = ModelMoneyField(
        _("Total vat"),
        help_text=_('Vat part of the total purchased'),
        default=DECIMAL_ZERO, max_digits=9, decimal_places=4)
    total_deposit = ModelMoneyField(
        _("deposit"),
        help_text=_('deposit to add to the original unit price'),
        default=DECIMAL_ZERO, max_digits=8, decimal_places=2)
    bank_amount_in = ModelMoneyField(
        _("bank_amount_in"), help_text=_('payment_on_the_account'),
        max_digits=8, decimal_places=2, default=DECIMAL_ZERO)
    bank_amount_out = ModelMoneyField(
        _("bank_amount_out"), help_text=_('payment_from_the_account'),
        max_digits=8, decimal_places=2, default=DECIMAL_ZERO)
    date_balance = models.DateField(
        _("date_balance"), default=datetime.date.today)
    balance = ModelMoneyField(
        _("balance"),
        max_digits=8, decimal_places=2, default=DECIMAL_ZERO)
    delta_price_with_tax = ModelMoneyField(
        _("Total amount"),
        help_text=_('purchase to add amount vat included'),
        default=DECIMAL_ZERO, max_digits=8, decimal_places=2)
    delta_stock_with_tax = ModelMoneyField(
        _("Total stock"),
        help_text=_('stock taken amount vat included'),
        default=DECIMAL_ZERO, max_digits=8, decimal_places=2)
    delta_vat = ModelMoneyField(
        _("Total vat"),
        help_text=_('vat to add'),
        default=DECIMAL_ZERO, max_digits=9, decimal_places=4)
    delta_stock_vat = ModelMoneyField(
        _("Total stock vat"),
        help_text=_('vat to add'),
        default=DECIMAL_ZERO, max_digits=9, decimal_places=4)
    delta_transport = ModelMoneyField(
        _("Delivery point transport"),
        help_text=_("transport to add"),
        default=DECIMAL_ZERO, max_digits=5, decimal_places=2,
        validators=[MinValueValidator(0)])
    delta_deposit = ModelMoneyField(
        _("deposit"),
        help_text=_('deposit to add'),
        default=DECIMAL_ZERO, max_digits=8, decimal_places=2)
    delta_stock_deposit = ModelMoneyField(
        _("deposit"),
        help_text=_('deposit to add'),
        default=DECIMAL_ZERO, max_digits=8, decimal_places=2)
Patrick's avatar
Patrick committed
500 501

    to_be_paid = models.BooleanField(_("to be paid"), choices=LUT_BANK_NOTE, default=False)
Patrick's avatar
Patrick committed
502 503 504 505
    calculated_invoiced_balance = ModelMoneyField(
        _("calculated balance to be invoiced"), max_digits=8, decimal_places=2, default=DECIMAL_ZERO)
    to_be_invoiced_balance = ModelMoneyField(
        _("balance to be invoiced"), max_digits=8, decimal_places=2, default=DECIMAL_ZERO)
Patrick's avatar
Patrick committed
506 507 508
    invoice_sort_order = models.IntegerField(
        _("invoice sort order"),
        default=None, blank=True, null=True, db_index=True)
Patrick's avatar
Patrick committed
509 510 511
    invoice_reference = models.CharField(
        _("invoice reference"), max_length=100, null=True, blank=True)

Patrick's avatar
Patrick committed
512 513 514 515 516 517
    def get_negative_previous_balance(self):
        return - self.previous_balance

    def get_negative_balance(self):
        return - self.balance

Patrick's avatar
Patrick committed
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
    def get_delta_price_with_tax(self):
        return self.delta_price_with_tax.amount

    def get_abs_delta_price_with_tax(self):
        return abs(self.delta_price_with_tax)

    def get_total_price_with_tax(self):
        return self.total_price_with_tax + self.delta_price_with_tax + self.delta_transport + self.delta_stock_with_tax

    def get_total_vat(self):
        return self.total_vat + self.delta_stock_vat

    def get_total_deposit(self):
        return self.total_deposit + self.delta_stock_deposit

    def __str__(self):
        return '%s, %s' % (self.producer, self.permanence)

    class Meta:
        verbose_name = _("producer invoice")
        verbose_name_plural = _("producers invoices")
        unique_together = ("permanence", "producer",)


@python_2_unicode_compatible
class CustomerProducerInvoice(models.Model):
    customer = models.ForeignKey(
        'Customer', verbose_name=_("customer"),
        on_delete=models.PROTECT)
    producer = models.ForeignKey(
        'Producer', verbose_name=_("producer"),
        on_delete=models.PROTECT)
    permanence = models.ForeignKey(
Patrick's avatar
Patrick committed
551
        'Permanence', verbose_name=permanence_verbose_name(), on_delete=models.PROTECT,
Patrick's avatar
Patrick committed
552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
        db_index=True)
    # Calculated with Purchase
    total_purchase_with_tax = ModelMoneyField(
        _("producer amount invoiced"),
        help_text=_('Total selling amount vat included'),
        default=DECIMAL_ZERO, max_digits=8, decimal_places=2)
    # Calculated with Purchase
    total_selling_with_tax = ModelMoneyField(
        _("customer amount invoiced"),
        help_text=_('Total selling amount vat included'),
        default=DECIMAL_ZERO, max_digits=8, decimal_places=2)

    def get_html_producer_price_purchased(self):
        if self.total_purchase_with_tax != DECIMAL_ZERO:
            return _("<b>%(price)s</b>") % {'price': self.total_purchase_with_tax}
        return EMPTY_STRING

    get_html_producer_price_purchased.short_description = (_("producer amount invoiced"))
    get_html_producer_price_purchased.allow_tags = True
    get_html_producer_price_purchased.admin_order_field = 'total_purchase_with_tax'

    def __str__(self):
        return '%s, %s' % (self.producer, self.customer)

    class Meta:
        verbose_name = _("customer x producer invoice")
        verbose_name_plural = _("customers x producers invoices")
        unique_together = ("permanence", "customer", "producer",)


@python_2_unicode_compatible
class CustomerSend(CustomerProducerInvoice):
    def __str__(self):
        return '%s, %s' % (self.producer, self.customer)

    class Meta:
        proxy = True
        verbose_name = _("customer")
        verbose_name_plural = _("customers")