producer.py 15.1 KB
Newer Older
Patrick's avatar
Patrick committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
# -*- coding: utf-8
from __future__ import unicode_literals

import datetime
import uuid

from django.conf import settings
from django.core import urlresolvers
# from django.core.validators import MinLengthValidator
from django.core.validators import MinValueValidator
from django.db import models
from django.db.models import Q
from django.db.models import Sum
from django.utils import timezone
from django.db.models.signals import pre_save
from django.dispatch import receiver
from django.utils.encoding import python_2_unicode_compatible
from django.utils.formats import number_format
from django.utils.translation import ugettext_lazy as _

import bankaccount
import invoice
import offeritem
from repanier.const import *
from repanier.fields.RepanierMoneyField import ModelMoneyField, RepanierMoney


@python_2_unicode_compatible
class Producer(models.Model):
    short_profile_name = models.CharField(
        _("short_profile_name"), max_length=25, null=False, default=EMPTY_STRING,
        db_index=True, unique=True)
    long_profile_name = models.CharField(
        _("long_profile_name"), max_length=100, null=True, default=EMPTY_STRING)
    email = models.EmailField(
        _("email"), null=True, blank=True, default=EMPTY_STRING)
    email2 = models.EmailField(
        _("secondary email"), null=True, blank=True, default=EMPTY_STRING)
Patrick's avatar
Reorder  
Patrick committed
39 40
    email3 = models.EmailField(
        _("secondary email"), null=True, blank=True, default=EMPTY_STRING)
Patrick's avatar
Patrick committed
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
    language = models.CharField(
        max_length=5,
        choices=settings.LANGUAGES,
        default=settings.LANGUAGE_CODE,
        verbose_name=_("language"))
    phone1 = models.CharField(
        _("phone1"),
        max_length=25,
        null=True, blank=True, default=EMPTY_STRING)
    phone2 = models.CharField(
        _("phone2"), max_length=25, null=True, blank=True, default=EMPTY_STRING)
    bank_account = models.CharField(_("bank account"), max_length=100, null=True, blank=True, default=EMPTY_STRING)
    vat_id = models.CharField(
        _("vat_id"), max_length=20, null=True, blank=True, default=EMPTY_STRING)
    fax = models.CharField(
        _("fax"), max_length=100, null=True, blank=True, default=EMPTY_STRING)
    address = models.TextField(_("address"), null=True, blank=True, default=EMPTY_STRING)
    memo = models.TextField(
        _("memo"), null=True, blank=True, default=EMPTY_STRING)
    reference_site = models.URLField(
        _("reference site"), null=True, blank=True, default=EMPTY_STRING)
    web_services_activated = models.BooleanField(_('Web services activated'), default=False)
    # uuid used to access to producer invoices without login
    uuid = models.CharField(
        _("uuid"), max_length=36, null=True, default=EMPTY_STRING,
        db_index=True
    )
    offer_uuid = models.CharField(
        _("uuid"), max_length=36, null=True, default=EMPTY_STRING,
        db_index=True
    )
    offer_filled = models.BooleanField(_("offer filled"), default=False)
    invoice_by_basket = models.BooleanField(_("invoice by basket"), default=False)
    manage_replenishment = models.BooleanField(_("manage stock"), default=False)
    manage_production = models.BooleanField(_("manage production"), default=False)
    producer_pre_opening = models.BooleanField(_("producer pre-opening"), default=False)
    producer_price_are_wo_vat = models.BooleanField(_("producer price are wo vat"), default=False)
    sort_products_by_reference = models.BooleanField(_("sort products by reference"), default=False)

    price_list_multiplier = models.DecimalField(
        _("price_list_multiplier"),
        help_text=_("This multiplier is applied to each price automatically imported/pushed."),
        default=DECIMAL_ONE, max_digits=5, decimal_places=4, blank=True,
        validators=[MinValueValidator(0)])
    is_resale_price_fixed = models.BooleanField(_("the resale price is set by the producer"),
                                                default=False)
    minimum_order_value = ModelMoneyField(
        _("minimum order value"),
        help_text=_("0 mean : no minimum order value."),
        max_digits=8, decimal_places=2, default=DECIMAL_ZERO,
        validators=[MinValueValidator(0)])

    date_balance = models.DateField(
        _("date_balance"), default=datetime.date.today)
    balance = ModelMoneyField(
        _("balance"), max_digits=8, decimal_places=2, default=DECIMAL_ZERO)
    initial_balance = ModelMoneyField(
        _("initial balance"), max_digits=8, decimal_places=2, default=DECIMAL_ZERO)
    represent_this_buyinggroup = models.BooleanField(
        _("represent_this_buyinggroup"), default=False)
    is_active = models.BooleanField(_("is_active"), default=True)

Patrick's avatar
Patrick committed
103 104 105
    def get_negative_balance(self):
        return - self.balance

Patrick's avatar
Patrick committed
106
    def get_products(self):
Patrick's avatar
Patrick committed
107 108 109 110 111 112
        # This producer may have product's list
        changeproductslist_url = urlresolvers.reverse(
            'admin:repanier_product_changelist',
        )
        link = '<a href="%s?is_active__exact=1&producer=%s" class="btn addlink">&nbsp;%s</a>' \
               % (changeproductslist_url, str(self.id), _("his_products"))
Patrick's avatar
Patrick committed
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
        return link

    get_products.short_description = (_("link to his products"))
    get_products.allow_tags = True

    def get_admin_date_balance(self):
        if self.id is not None:
            bank_account = bankaccount.BankAccount.objects.filter(
                producer_id=self.id, producer_invoice__isnull=True
            ).order_by("-operation_date").only("operation_date").first()
            if bank_account is not None:
                return bank_account.operation_date
            return self.date_balance
        else:
            return timezone.now().date()

    get_admin_date_balance.short_description = (_("date_balance"))
    get_admin_date_balance.allow_tags = False

    def get_admin_balance(self):
        if self.id is not None:
Patrick's avatar
Patrick committed
134
            return self.balance - self.get_bank_not_invoiced() + self.get_order_not_invoiced()
Patrick's avatar
Patrick committed
135 136 137 138 139 140
        else:
            return REPANIER_MONEY_ZERO

    get_admin_balance.short_description = (_("balance"))
    get_admin_balance.allow_tags = False

Patrick's avatar
Patrick committed
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
    def get_order_not_invoiced(self):
        result_set = invoice.ProducerInvoice.objects.filter(
            producer_id=self.id,
            status__gte=PERMANENCE_OPENED,
            status__lte=PERMANENCE_SEND
        ).order_by('?').aggregate(Sum('total_price_with_tax'), Sum('delta_price_with_tax'), Sum('delta_transport'))
        if result_set["total_price_with_tax__sum"] is not None:
            order_not_invoiced = RepanierMoney(result_set["total_price_with_tax__sum"])
        else:
            order_not_invoiced = REPANIER_MONEY_ZERO
        if result_set["delta_price_with_tax__sum"] is not None:
            order_not_invoiced += RepanierMoney(result_set["delta_price_with_tax__sum"])
        if result_set["delta_transport__sum"] is not None:
            order_not_invoiced += RepanierMoney(result_set["delta_transport__sum"])
        return order_not_invoiced

    def get_bank_not_invoiced(self):
Patrick's avatar
Patrick committed
158
        result_set = bankaccount.BankAccount.objects.filter(
Patrick's avatar
Patrick committed
159
            producer_id=self.id, producer_invoice__isnull=True
Patrick's avatar
Patrick committed
160 161 162 163 164 165 166 167 168
        ).order_by('?').aggregate(Sum('bank_amount_in'), Sum('bank_amount_out'))
        if result_set["bank_amount_in__sum"] is not None:
            bank_in = RepanierMoney(result_set["bank_amount_in__sum"])
        else:
            bank_in = REPANIER_MONEY_ZERO
        if result_set["bank_amount_out__sum"] is not None:
            bank_out = RepanierMoney(result_set["bank_amount_out__sum"])
        else:
            bank_out = REPANIER_MONEY_ZERO
Patrick's avatar
Patrick committed
169 170 171 172 173
        bank_not_invoiced = bank_in - bank_out
        return bank_not_invoiced

    def get_calculated_invoiced_balance(self, permanence_id):
        bank_not_invoiced = self.get_bank_not_invoiced()
Patrick's avatar
Patrick committed
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
        # IMPORTANT : when is_resale_price_fixed=True then price_list_multiplier == 1
        # Do not take into account product whose order unit is >= PRODUCT_ORDER_UNIT_DEPOSIT
        result_set = offeritem.OfferItem.objects.filter(
            permanence_id=permanence_id,
            producer_id=self.id,
            price_list_multiplier__lt=1
        ).exclude(
            order_unit__gte=PRODUCT_ORDER_UNIT_DEPOSIT
        ).order_by('?').aggregate(
            Sum('total_selling_with_tax')
        )
        if result_set["total_selling_with_tax__sum"] is not None:
            payment_needed = result_set["total_selling_with_tax__sum"]
        else:
            payment_needed = DECIMAL_ZERO
Patrick's avatar
Patrick committed
189
        # print("payment_needed (1) %f" % payment_needed)
Patrick's avatar
Patrick committed
190 191 192 193 194 195 196 197 198 199 200
        result_set = offeritem.OfferItem.objects.filter(
            permanence_id=permanence_id,
            producer_id=self.id,
            price_list_multiplier__gte=1,
        ).exclude(
            order_unit__gte=PRODUCT_ORDER_UNIT_DEPOSIT
        ).order_by('?').aggregate(
            Sum('total_purchase_with_tax'),
        )
        if result_set["total_purchase_with_tax__sum"] is not None:
            payment_needed += result_set["total_purchase_with_tax__sum"]
Patrick's avatar
Patrick committed
201
        # print("payment_needed (2) %f" % payment_needed)
Patrick's avatar
Patrick committed
202
        calculated_invoiced_balance = self.balance - bank_not_invoiced + payment_needed
Patrick's avatar
Patrick committed
203
        # print("calculated_invoiced_balance %f" % calculated_invoiced_balance)
Patrick's avatar
Patrick committed
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
        if self.manage_replenishment:
            for offer_item in offeritem.OfferItem.objects.filter(
                    is_active=True,
                    permanence_id=permanence_id,
                    producer_id=self.id,
                    manage_replenishment=True,
            ).order_by('?'):
                invoiced_qty, taken_from_stock, customer_qty = offer_item.get_producer_qty_stock_invoiced()
                if offer_item.price_list_multiplier < DECIMAL_ONE: # or offer_item.is_resale_price_fixed:
                    unit_price = offer_item.customer_unit_price.amount
                else:
                    unit_price = offer_item.producer_unit_price.amount
                if taken_from_stock > DECIMAL_ZERO:
                    delta_price_with_tax = (
                        (unit_price + offer_item.unit_deposit.amount)
                        * taken_from_stock
                    ).quantize(TWO_DECIMALS)
                    calculated_invoiced_balance -= delta_price_with_tax
        return calculated_invoiced_balance

    get_calculated_invoiced_balance.short_description = (_("balance"))
    get_calculated_invoiced_balance.allow_tags = False

    def get_balance(self):
        last_producer_invoice_set = invoice.ProducerInvoice.objects.filter(
            producer_id=self.id, invoice_sort_order__isnull=False
        ).order_by('?')
Patrick's avatar
Patrick committed
231 232

        # label = "%s, %s, %s, %s" % (self.balance, self.get_bank_not_invoiced(), self.get_order_not_invoiced(), self.get_admin_balance())
Patrick's avatar
Patrick committed
233 234 235 236
        balance = self.get_admin_balance()
        if last_producer_invoice_set.exists():
            if balance.amount < 0:
                return '<a href="' + urlresolvers.reverse('producer_invoice_view', args=(0,)) + '?producer=' + str(
Patrick's avatar
Patrick committed
237 238
                    self.id) + '" class="btn" target="_blank" >' + (
                           '<span style="color:#298A08">%s</span>' % (-balance,)) + '</a>'
Patrick's avatar
Patrick committed
239 240
            elif balance.amount == 0:
                return '<a href="' + urlresolvers.reverse('producer_invoice_view', args=(0,)) + '?producer=' + str(
Patrick's avatar
Patrick committed
241 242
                    self.id) + '" class="btn" target="_blank" >' + (
                           '<span style="color:#32CD32">%s</span>' % (-balance,)) + '</a>'
Patrick's avatar
Patrick committed
243 244
            elif balance.amount > 30:
                return '<a href="' + urlresolvers.reverse('producer_invoice_view', args=(0,)) + '?producer=' + str(
Patrick's avatar
Patrick committed
245 246
                    self.id) + '" class="btn" target="_blank" >' + (
                           '<span style="color:red">%s</span>' % (-balance,)) + '</a>'
Patrick's avatar
Patrick committed
247 248
            else:
                return '<a href="' + urlresolvers.reverse('producer_invoice_view', args=(0,)) + '?producer=' + str(
Patrick's avatar
Patrick committed
249 250
                    self.id) + '" class="btn" target="_blank" >' + (
                           '<span style="color:#696969">%s</span>' % (-balance,)) + '</a>'
Patrick's avatar
Patrick committed
251 252
        else:
            if balance.amount < 0:
Patrick's avatar
Patrick committed
253
                return '<span style="color:#298A08">%s</span>' % (-balance,)
Patrick's avatar
Patrick committed
254
            elif balance.amount == 0:
Patrick's avatar
Patrick committed
255
                return '<span style="color:#32CD32">%s</span>' % (-balance,)
Patrick's avatar
Patrick committed
256
            elif balance.amount > 30:
Patrick's avatar
Patrick committed
257
                return '<span style="color:red">%s</span>' % (-balance,)
Patrick's avatar
Patrick committed
258
            else:
Patrick's avatar
Patrick committed
259
                return '<span style="color:#696969">%s</span>' % (-balance,)
Patrick's avatar
Patrick committed
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274

    get_balance.short_description = _("balance")
    get_balance.allow_tags = True
    get_balance.admin_order_field = 'balance'

    def get_last_invoice(self):
        producer_last_invoice = invoice.ProducerInvoice.objects.filter(producer_id=self.id).order_by("-id").first()
        if producer_last_invoice:
            if producer_last_invoice.total_price_with_tax < DECIMAL_ZERO:
                return '<span style="color:#298A08">%s</span>' % (
                    number_format(producer_last_invoice.total_price_with_tax, 2))
            elif producer_last_invoice.total_price_with_tax == DECIMAL_ZERO:
                return '<span style="color:#32CD32">%s</span>' % (
                    number_format(producer_last_invoice.total_price_with_tax, 2))
            elif producer_last_invoice.total_price_with_tax > 30:
275
                return '<span style="color:red">%s</span>' % (
Patrick's avatar
Patrick committed
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
                    number_format(producer_last_invoice.total_price_with_tax, 2))
            else:
                return '<span style="color:#696969">%s</span>' % (
                    number_format(producer_last_invoice.total_price_with_tax, 2))
        else:
            return '<span style="color:#32CD32">%s</span>' % (number_format(0, 2))

    get_last_invoice.short_description = _("last invoice")
    get_last_invoice.allow_tags = True

    def __str__(self):
        if self.producer_price_are_wo_vat:
            return "%s %s" % (self.short_profile_name, _("wo tax"))
        return self.short_profile_name

    class Meta:
        verbose_name = _("producer")
        verbose_name_plural = _("producers")
        ordering = ("short_profile_name",)


@receiver(pre_save, sender=Producer)
def producer_pre_save(sender, **kwargs):
    producer = kwargs["instance"]
    if producer.represent_this_buyinggroup:
        # The buying group may not be de activated
        producer.is_active = True
Patrick's avatar
Reorder  
Patrick committed
303
    if producer.email:
Patrick's avatar
Patrick committed
304
        producer.email = producer.email.lower()
Patrick's avatar
Reorder  
Patrick committed
305
    if producer.email2:
Patrick's avatar
Patrick committed
306
        producer.email2 = producer.email2.lower()
Patrick's avatar
Reorder  
Patrick committed
307 308
    if producer.email3:
        producer.email3 = producer.email3.lower()
Patrick's avatar
Patrick committed
309 310 311 312 313 314 315 316 317 318 319 320 321 322
    if producer.producer_pre_opening:
        # Important to make difference between the stock of the group and the stock of the producer
        producer.manage_replenishment = False
        producer.manage_production = True
        producer.is_resale_price_fixed = False
    elif producer.manage_replenishment:
        # Important to compute ProducerInvoice.total_price_with_tax
        producer.invoice_by_basket = False
    if producer.price_list_multiplier <= DECIMAL_ZERO:
        producer.price_list_multiplier = DECIMAL_ONE
    if not producer.uuid:
        producer.uuid = uuid.uuid4()
    if producer.bank_account is not None and len(producer.bank_account.strip()) == 0:
        producer.bank_account = None