producer.py 17.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
# -*- 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
Patrick's avatar
Patrick committed
19
from django.utils.safestring import mark_safe
Patrick's avatar
Patrick committed
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
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
40 41
    email3 = models.EmailField(
        _("secondary email"), null=True, blank=True, default=EMPTY_STRING)
Patrick's avatar
Patrick committed
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
    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
104 105 106
    def get_negative_balance(self):
        return - self.balance

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

    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
137
            return self.balance - self.get_bank_not_invoiced() + self.get_order_not_invoiced()
Patrick's avatar
Patrick committed
138 139 140 141 142 143
        else:
            return REPANIER_MONEY_ZERO

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

Patrick's avatar
Patrick committed
144
    def get_order_not_invoiced(self):
Patrick's avatar
Patrick committed
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
        from repanier.apps import REPANIER_SETTINGS_INVOICE
        if REPANIER_SETTINGS_INVOICE:
            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"])
Patrick's avatar
Patrick committed
160 161 162 163 164
        else:
            order_not_invoiced = REPANIER_MONEY_ZERO
        return order_not_invoiced

    def get_bank_not_invoiced(self):
Patrick's avatar
Patrick committed
165 166 167 168 169 170 171 172 173 174 175 176 177 178
        from repanier.apps import REPANIER_SETTINGS_INVOICE
        if REPANIER_SETTINGS_INVOICE:
            result_set = bankaccount.BankAccount.objects.filter(
                producer_id=self.id, producer_invoice__isnull=True
            ).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
            bank_not_invoiced = bank_in - bank_out
Patrick's avatar
Patrick committed
179
        else:
Patrick's avatar
Patrick committed
180 181
            bank_not_invoiced = REPANIER_MONEY_ZERO

Patrick's avatar
Patrick committed
182 183 184 185
        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
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
        # 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
201
        # print("payment_needed (1) %f" % payment_needed)
Patrick's avatar
Patrick committed
202 203 204 205 206 207 208 209 210 211 212
        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
213
        # print("payment_needed (2) %f" % payment_needed)
Patrick's avatar
Patrick committed
214
        calculated_invoiced_balance = self.balance - bank_not_invoiced + payment_needed
Patrick's avatar
Patrick committed
215
        # print("calculated_invoiced_balance %f" % calculated_invoiced_balance)
Patrick's avatar
Patrick committed
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
        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
243 244

        # 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
245 246 247 248
        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
249 250
                    self.id) + '" class="btn" target="_blank" >' + (
                           '<span style="color:#298A08">%s</span>' % (-balance,)) + '</a>'
Patrick's avatar
Patrick committed
251 252
            elif balance.amount == 0:
                return '<a href="' + urlresolvers.reverse('producer_invoice_view', args=(0,)) + '?producer=' + str(
Patrick's avatar
Patrick committed
253 254
                    self.id) + '" class="btn" target="_blank" >' + (
                           '<span style="color:#32CD32">%s</span>' % (-balance,)) + '</a>'
Patrick's avatar
Patrick committed
255 256
            elif balance.amount > 30:
                return '<a href="' + urlresolvers.reverse('producer_invoice_view', args=(0,)) + '?producer=' + str(
Patrick's avatar
Patrick committed
257 258
                    self.id) + '" class="btn" target="_blank" >' + (
                           '<span style="color:red">%s</span>' % (-balance,)) + '</a>'
Patrick's avatar
Patrick committed
259 260
            else:
                return '<a href="' + urlresolvers.reverse('producer_invoice_view', args=(0,)) + '?producer=' + str(
Patrick's avatar
Patrick committed
261 262
                    self.id) + '" class="btn" target="_blank" >' + (
                           '<span style="color:#696969">%s</span>' % (-balance,)) + '</a>'
Patrick's avatar
Patrick committed
263 264
        else:
            if balance.amount < 0:
Patrick's avatar
Patrick committed
265
                return '<span style="color:#298A08">%s</span>' % (-balance,)
Patrick's avatar
Patrick committed
266
            elif balance.amount == 0:
Patrick's avatar
Patrick committed
267
                return '<span style="color:#32CD32">%s</span>' % (-balance,)
Patrick's avatar
Patrick committed
268
            elif balance.amount > 30:
Patrick's avatar
Patrick committed
269
                return '<span style="color:red">%s</span>' % (-balance,)
Patrick's avatar
Patrick committed
270
            else:
Patrick's avatar
Patrick committed
271
                return '<span style="color:#696969">%s</span>' % (-balance,)
Patrick's avatar
Patrick committed
272 273 274 275 276 277

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

    def get_last_invoice(self):
Patrick's avatar
Patrick committed
278 279 280 281
        producer_last_invoice = invoice.ProducerInvoice.objects.filter(
            producer_id=self.id, invoice_sort_order__isnull=False
        ).order_by("-id").first()
        if producer_last_invoice is not None:
Patrick's avatar
Patrick committed
282 283 284 285 286 287 288
            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:
289
                return '<span style="color:red">%s</span>' % (
Patrick's avatar
Patrick committed
290 291 292 293 294 295 296 297 298 299
                    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

Patrick's avatar
Patrick committed
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
    def get_on_hold_movement_json(self, to_json):
        bank_not_invoiced = self.get_bank_not_invoiced()
        order_not_invoiced = self.get_order_not_invoiced()

        if order_not_invoiced.amount != DECIMAL_ZERO or bank_not_invoiced.amount != DECIMAL_ZERO:
            if order_not_invoiced.amount != DECIMAL_ZERO:
                if bank_not_invoiced.amount == DECIMAL_ZERO:
                    producer_on_hold_movement = \
                        _('This balance does not take account of any unbilled sales %(other_order)s.') % {
                            'other_order': order_not_invoiced
                        }
                else:
                    producer_on_hold_movement = \
                        _(
                            'This balance does not take account of any unrecognized payments %(bank)s and any unbilled order %(other_order)s.') \
                        % {
                            'bank'       : bank_not_invoiced,
                            'other_order': order_not_invoiced
                        }
            else:
                producer_on_hold_movement = \
                    _(
                        'This balance does not take account of any unrecognized payments %(bank)s.') % {
                        'bank': bank_not_invoiced
                    }
            option_dict = {'id': "#basket_message", 'html': mark_safe(producer_on_hold_movement)}
            to_json.append(option_dict)

        return

Patrick's avatar
Patrick committed
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
    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
347
    if producer.email:
Patrick's avatar
Patrick committed
348
        producer.email = producer.email.lower()
Patrick's avatar
Reorder  
Patrick committed
349
    if producer.email2:
Patrick's avatar
Patrick committed
350
        producer.email2 = producer.email2.lower()
Patrick's avatar
Reorder  
Patrick committed
351 352
    if producer.email3:
        producer.email3 = producer.email3.lower()
Patrick's avatar
Patrick committed
353 354 355 356 357 358 359 360 361 362 363 364 365 366
    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