permanence.py 30.8 KB
Newer Older
Patrick's avatar
Patrick committed
1 2 3
# -*- coding: utf-8
from __future__ import unicode_literals

Patrick's avatar
Patrick committed
4 5
import datetime

Patrick's avatar
Patrick committed
6 7 8 9 10
from django.conf import settings
from django.core import urlresolvers
from django.core.cache import cache
from django.db import models
from django.db.models import F
Patrick's avatar
Patrick committed
11
from django.utils import timezone, translation
Patrick's avatar
Patrick committed
12
from django.utils.encoding import python_2_unicode_compatible
Patrick's avatar
Patrick committed
13
from django.utils.formats import number_format
Patrick's avatar
Patrick committed
14 15 16
from django.utils.translation import ugettext_lazy as _
from djangocms_text_ckeditor.fields import HTMLField
from menus.menu_pool import menu_pool
Patrick's avatar
Patrick committed
17
from parler.models import TranslatableModel, TranslatedFields, TranslationDoesNotExist
Patrick's avatar
Patrick committed
18 19 20 21 22 23 24 25

import customer
import deliveryboard
import invoice
import permanenceboard
import producer
import purchase
import repanier.apps
26 27
from repanier.picture.const import SIZE_L
from repanier.picture.fields import AjaxPictureField
Patrick's avatar
Patrick committed
28
from repanier.fields.RepanierMoneyField import ModelMoneyField
Patrick's avatar
Patrick committed
29
from repanier.const import *
Patrick's avatar
Patrick committed
30 31 32
from repanier.tools import get_full_status_display, cap


33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
# def verbose_name():
#     if repanier.apps.DJANGO_IS_MIGRATION_RUNNING:
#         return EMPTY_STRING
#     return lambda: "%s" % repanier.apps.REPANIER_SETTINGS_PERMANENCE_NAME
#
#
# def verbose_name_plural():
#     if repanier.apps.DJANGO_IS_MIGRATION_RUNNING:
#         return EMPTY_STRING
#     return lambda: "%s" % repanier.apps.REPANIER_SETTINGS_PERMANENCES_NAME
#
#
# def verbose_name_in_preparation():
#     if repanier.apps.DJANGO_IS_MIGRATION_RUNNING:
#         return EMPTY_STRING
#     return lambda: _("%(name)s in preparation list") % {'name': repanier.apps.REPANIER_SETTINGS_PERMANENCES_NAME}
#
#
# def verbose_name_plural_in_preparation():
#     if repanier.apps.DJANGO_IS_MIGRATION_RUNNING:
#         return EMPTY_STRING
#     return lambda: _("%(name)s in preparation list") % {'name': repanier.apps.REPANIER_SETTINGS_PERMANENCES_NAME}
#
#
# def verbose_name_done():
#     if repanier.apps.DJANGO_IS_MIGRATION_RUNNING:
#         return EMPTY_STRING
#     return lambda: _("%(name)s done list") % {
#         'name': repanier.apps.REPANIER_SETTINGS_PERMANENCES_NAME} if repanier.apps.REPANIER_SETTINGS_INVOICE else "%s" % _(
#         "%(name)s archived list") % {'name': repanier.apps.REPANIER_SETTINGS_PERMANENCES_NAME}
#
#
# def verbose_name_plural_done():
#     if repanier.apps.DJANGO_IS_MIGRATION_RUNNING:
#         return EMPTY_STRING
#     return lambda: _("%(name)s done list") % {
#         'name': repanier.apps.REPANIER_SETTINGS_PERMANENCES_NAME} if repanier.apps.REPANIER_SETTINGS_INVOICE else "%s" % _(
#         "%(name)s archived list") % {'name': repanier.apps.REPANIER_SETTINGS_PERMANENCES_NAME}
Patrick's avatar
Patrick committed
71 72 73 74 75


@python_2_unicode_compatible
class Permanence(TranslatableModel):
    translations = TranslatedFields(
Patrick's avatar
Patrick committed
76
        short_name=models.CharField(_("offer name"), max_length=50, blank=True),
Patrick's avatar
Patrick committed
77
        offer_description=HTMLField(_("offer_description"),
78
                                    configuration='CKEDITOR_SETTINGS_MODEL2',
Patrick's avatar
Patrick committed
79 80 81 82 83
                                    help_text=_(
                                        "This message is send by mail to all customers when opening the order or on top "),
                                    blank=True, default=EMPTY_STRING),
        invoice_description=HTMLField(
            _("invoice_description"),
84
            configuration='CKEDITOR_SETTINGS_MODEL2',
Patrick's avatar
Patrick committed
85 86 87
            help_text=_(
                'This message is send by mail to all customers having bought something when closing the permanence.'),
            blank=True, default=EMPTY_STRING),
88
        cache_part_d=HTMLField(configuration='CKEDITOR_SETTINGS_MODEL2', blank=True, default=EMPTY_STRING)
Patrick's avatar
Patrick committed
89 90 91 92 93 94 95 96
    )

    status = models.CharField(
        max_length=3,
        choices=LUT_PERMANENCE_STATUS,
        default=PERMANENCE_PLANNED,
        verbose_name=_("permanence_status"),
        help_text=_('status of the permanence from planned, orders opened, orders closed, send, done'))
Patrick's avatar
Patrick committed
97
    permanence_date = models.DateField(_("date"), db_index=True)
Patrick's avatar
Patrick committed
98 99 100 101 102 103
    payment_date = models.DateField(_("payment_date"), blank=True, null=True, db_index=True)
    producers = models.ManyToManyField(
        'Producer',
        verbose_name=_("producers"),
        blank=True
    )
Patrick's avatar
Patrick committed
104 105 106 107 108 109 110 111 112
    total_price_wo_tax = ModelMoneyField(
        _("Total amount"),
        help_text=_('Total purchase amount vat excluded'),
        default=DECIMAL_ZERO, max_digits=8, decimal_places=2)
    total_profit = ModelMoneyField(
        _("Total profit"),
        help_text=_('Total profit'),
        default=DECIMAL_ZERO, max_digits=8, decimal_places=2)

Patrick's avatar
Patrick committed
113 114 115 116 117 118 119 120 121 122 123 124
    with_delivery_point = models.BooleanField(
        _("with_delivery_point"), default=False)
    automatically_closed = models.BooleanField(
        _("automatically_closed"), default=False)
    is_updated_on = models.DateTimeField(
        _("is_updated_on"), auto_now=True)
    highest_status = models.CharField(
        max_length=3,
        choices=LUT_PERMANENCE_STATUS,
        default=PERMANENCE_PLANNED,
        verbose_name=_("highest permanence_status"),
        help_text=_('status of the permanence from planned, orders opened, orders closed, send, done'))
Patrick's avatar
Patrick committed
125 126 127 128 129 130 131 132
    master_permanence = models.ForeignKey(
        'Permanence', verbose_name=_("master permanence"),
        related_name='child_permanence',
        blank=True, null=True, default=None,
        on_delete=models.PROTECT, db_index=True)
    invoice_sort_order = models.IntegerField(
        _("invoice sort order"),
        default=None, blank=True, null=True)
133 134 135 136 137 138
    offer_description_on_home_page = models.BooleanField(
        _("Publish the offer description on the home page when the permanence is open"), default=True)
    picture = AjaxPictureField(
        verbose_name=_("picture"),
        null=True, blank=True,
        upload_to="permanence", size=SIZE_L)
Patrick's avatar
Patrick committed
139 140

    def get_producers(self):
Patrick's avatar
Patrick committed
141
        if self.status == PERMANENCE_PLANNED:
Patrick's avatar
Patrick committed
142
            if len(self.producers.all()) > 0:
Patrick's avatar
Patrick committed
143 144 145 146 147 148 149 150 151
                changelist_url = urlresolvers.reverse(
                    'admin:repanier_product_changelist',
                )
                link = []
                for p in self.producers.all():
                    link.append(
                        '<a href="%s?producer=%d">&nbsp;%s</a>' % (
                            changelist_url, p.id, p.short_profile_name))
                return '<div class="wrap-text">%s</div>' % ", ".join(link)
Patrick's avatar
Patrick committed
152
            else:
153
                return '<div class="wrap-text">%s</div>' % _("No offer")
Patrick's avatar
Patrick committed
154 155 156 157 158 159
        elif self.status == PERMANENCE_PRE_OPEN:
            return '<div class="wrap-text">%s</div>' % ", ".join([p.short_profile_name + " (" + p.phone1 + ")" for p in self.producers.all()])
        elif self.status in [PERMANENCE_OPENED, PERMANENCE_CLOSED]:
            close_offeritem_changelist_url = urlresolvers.reverse(
                'admin:repanier_offeritemclosed_changelist',
            )
Patrick's avatar
Patrick committed
160

Patrick's avatar
Patrick committed
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
            link = []
            for p in self.producers.all().only("id"):
                pi = invoice.ProducerInvoice.objects.filter(
                    producer_id=p.id, permanence_id=self.id
                ).order_by('?').first()
                if pi is not None:
                    if pi.status == PERMANENCE_OPENED:
                        label = ('%s (%s) ' % (p.short_profile_name, pi.get_total_price_with_tax())).replace(
                            ' ', '&nbsp;')
                        offeritem_changelist_url = close_offeritem_changelist_url
                    else:
                        label = ('%s (%s) %s' % (
                        p.short_profile_name, pi.get_total_price_with_tax(), LOCK_UNICODE)).replace(' ',
                                                                                                    '&nbsp;')
                        offeritem_changelist_url = close_offeritem_changelist_url
                else:
                    label = ('%s ' % (p.short_profile_name,)).replace(' ', '&nbsp;')
                    offeritem_changelist_url = close_offeritem_changelist_url
                link.append(
                    '<a href="%s?permanence=%s&producer=%d">%s</a>' % (
                        offeritem_changelist_url, self.id, p.id, label))
            return '<div class="wrap-text">%s</div>' % ", ".join(link)
Patrick's avatar
Patrick committed
183

Patrick's avatar
Patrick committed
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
        elif self.status in [PERMANENCE_SEND, PERMANENCE_INVOICED, PERMANENCE_ARCHIVED]:
            send_offeritem_changelist_url = urlresolvers.reverse(
                'admin:repanier_offeritemsend_changelist',
            )
            send_customer_changelist_url = urlresolvers.reverse(
                'admin:repanier_customersend_changelist',
            )
            link = []
            at_least_one_permanence_send = False
            for pi in invoice.ProducerInvoice.objects.filter(permanence_id=self.id).select_related(
                    "producer").order_by('producer'):
                if pi.status == PERMANENCE_SEND:
                    at_least_one_permanence_send = True
                    if pi.producer.invoice_by_basket:
                        changelist_url = send_customer_changelist_url
Patrick's avatar
Patrick committed
199
                    else:
Patrick's avatar
Patrick committed
200
                        changelist_url = send_offeritem_changelist_url
201
                    # Important : no target="_blank"
Patrick's avatar
Patrick committed
202 203
                    label = '%s (%s) %s' % (
                    pi.producer.short_profile_name, pi.get_total_price_with_tax(), LOCK_UNICODE)
Patrick's avatar
Patrick committed
204
                    link.append(
Patrick's avatar
Patrick committed
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
                        '<a href="%s?permanence=%d&producer=%d">&nbsp;%s</a>' % (
                            changelist_url, self.id, pi.producer_id, label.replace(' ', '&nbsp;')
                        ))
                else:
                    if pi.invoice_reference:
                        if pi.to_be_invoiced_balance != DECIMAL_ZERO:
                            label = "%s (%s - %s)" % (
                                pi.producer.short_profile_name,
                                pi.to_be_invoiced_balance,
                                cap(pi.invoice_reference, 15)
                            )
                        else:
                            label = "%s (%s)" % (
                                pi.producer.short_profile_name,
                                cap(pi.invoice_reference, 15)
                            )
                    else:
                        if pi.to_be_invoiced_balance != DECIMAL_ZERO:
                            label = "%s (%s)" % (
                                pi.producer.short_profile_name,
                                pi.to_be_invoiced_balance
                            )
                        else:
228 229 230 231
                            # label = "%s" % (
                            #     pi.producer.short_profile_name
                            # )
                            continue
232
                    # Important : target="_blank" because the invoices must be displayed without the cms_toolbar
Patrick's avatar
Patrick committed
233
                    # Such that they can be accessed by the producer and by the staff
Patrick's avatar
Patrick committed
234
                    link.append(
Patrick's avatar
Patrick committed
235
                        '<a href="%s?producer=%d" target="_blank">%s</a>'
Patrick's avatar
Patrick committed
236
                        % (
Patrick's avatar
Patrick committed
237 238 239 240 241 242 243
                            urlresolvers.reverse('producer_invoice_view', args=(pi.id,)),
                            pi.producer_id,
                            label.replace(' ', '&nbsp;')))

            producers = ", ".join(link)
            if at_least_one_permanence_send:
                msg_html = '<div class="wrap-text">%s</div>' % producers
Patrick's avatar
Patrick committed
244 245
            else:
                msg_html = """
246
                    <div class="wrap-text"><button
Patrick's avatar
Patrick committed
247
                    onclick="django.jQuery('#id_get_producers_%d').toggle();
Patrick's avatar
Patrick committed
248 249 250 251 252 253 254
                        if(django.jQuery(this).html()=='%s'){
                            django.jQuery(this).html('%s')
                        }else{
                            django.jQuery(this).html('%s')
                        };
                        return false;"
                    >%s</button>
Patrick's avatar
Patrick committed
255
                    <div id="id_get_producers_%d" style="display:none;">%s</div></div>
Patrick's avatar
Patrick committed
256
                """ % (
Patrick's avatar
Patrick committed
257
                    self.id, _("Show"), _("Hide"), _("Show"), _("Show"), self.id, producers
Patrick's avatar
Patrick committed
258
                )
Patrick's avatar
Patrick committed
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 295 296 297 298 299 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 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
            return msg_html
        else:
            return '<div class="wrap-text">%s</div>' % ", ".join([p.short_profile_name
                                   for p in
                                   producer.Producer.objects.filter(
                                       producerinvoice__permanence_id=self.id).only(
                                       'short_profile_name')])

    get_producers.short_description = (_("producers in this permanence"))
    get_producers.allow_tags = True

    def get_customers(self):
        if self.status in [
            PERMANENCE_OPENED, PERMANENCE_CLOSED, PERMANENCE_SEND
        ]:
            changelist_url = urlresolvers.reverse(
                'admin:repanier_purchase_changelist',
            )
            link = []
            for ci in invoice.CustomerInvoice.objects.filter(permanence_id=self.id).select_related(
                "customer").order_by('customer'):
                ci_customer = ci.customer
                if ci.is_order_confirm_send:
                    label = '%s%s (%s) %s%s' % (
                        "<b><i>" if ci_customer.is_group else EMPTY_STRING,
                        ci.customer.short_basket_name, ci.get_total_price_with_tax(customer_charged=True),
                        ci.get_is_order_confirm_send_display(),
                        "</i></b>" if ci_customer.is_group else EMPTY_STRING,
                    )
                else:
                    label = '%s%s (%s) %s%s' % (
                        "<b><i>" if ci_customer.is_group else EMPTY_STRING,
                        ci.customer.short_basket_name, ci.total_price_with_tax,
                        ci.get_is_order_confirm_send_display(),
                        "</i></b>" if ci_customer.is_group else EMPTY_STRING,
                    )
                # Important : no target="_blank"
                link.append(
                    '<a href="%s?permanence=%d&customer=%d">%s</a>'
                    % (changelist_url, self.id, ci.customer_id, label.replace(' ', '&nbsp;')))
            customers = ", ".join(link)
        elif self.status in [PERMANENCE_INVOICED, PERMANENCE_ARCHIVED]:
            link = []
            for ci in invoice.CustomerInvoice.objects.filter(permanence_id=self.id).select_related(
                "customer").order_by('customer'):
                ci_customer = ci.customer
                label = "%s%s (%s) %s%s" % (
                    "<b><i>" if ci_customer.is_group else EMPTY_STRING,
                    ci_customer.short_basket_name,
                    ci.get_total_price_with_tax(customer_charged=True),
                    ci.get_is_order_confirm_send_display(),
                    "</i></b>" if ci_customer.is_group else EMPTY_STRING,
                )
                # Important : target="_blank" because the invoices must be displayed without the cms_toolbar
                # Such that they can be accessed by the customer and by the staff
                link.append(
                    '<a href="%s?customer=%d" target="_blank">%s</a>'
                    % (
                        urlresolvers.reverse('customer_invoice_view', args=(ci.id,)),
                        ci.customer_id,
                        label.replace(' ', '&nbsp;')
                    )
                )
            customers = ", ".join(link)
        else:
            customers = ", ".join([c.short_basket_name
                                   for c in
                                   customer.Customer.objects.filter(customerinvoice__permanence_id=self.id).only(
                                       'short_basket_name')])
        if len(customers) > 0:
            msg_html = """
                <div class="wrap-text"><button
                onclick="django.jQuery('#id_get_customers_%d').toggle();
                    if(django.jQuery(this).html()=='%s'){
                        django.jQuery(this).html('%s')
                    }else{
                        django.jQuery(this).html('%s')
                    };
                    return false;"
                >%s</button>
                <div id="id_get_customers_%d" style="display:none;">%s</div></div>
            """ % (
                self.id, _("Show"), _("Hide"), _("Show"), _("Show"), self.id, customers
            )
            return msg_html
        else:
            return '<div class="wrap-text">%s</div>' % _("No purchase")
Patrick's avatar
Patrick committed
346 347 348 349 350

    get_customers.short_description = (_("customers in this permanence"))
    get_customers.allow_tags = True

    def get_board(self):
Patrick's avatar
Patrick committed
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
        permanenceboard_set = permanenceboard.PermanenceBoard.objects.filter(
            permanence=self, permanence_role__rght=F('permanence_role__lft') + 1
        ).order_by("permanence_role__tree_id", "permanence_role__lft")
        first_board = True
        board = EMPTY_STRING
        if permanenceboard_set:
            for permanenceboard_row in permanenceboard_set:
                r_link = EMPTY_STRING
                r = permanenceboard_row.permanence_role
                if r:
                    r_url = urlresolvers.reverse(
                        'admin:repanier_lut_permanencerole_change',
                        args=(r.id,)
                    )
                    r_link = '<a href="' + r_url + \
                             '" target="_blank">' + r.short_name.replace(' ', '&nbsp;') + '</a>'
                c_link = EMPTY_STRING
                c = permanenceboard_row.customer
                if c:
                    c_url = urlresolvers.reverse(
                        'admin:repanier_customer_change',
                        args=(c.id,)
                    )
                    c_link = '&nbsp;->&nbsp;<a href="' + c_url + \
                             '" target="_blank">' + c.short_basket_name.replace(' ', '&nbsp;') + '</a>'
                if not first_board:
                    board += '<br/>'
                board += r_link + c_link
                first_board = False
        if not first_board:
            # At least one role is defined in the permanence board
            msg_html = """
                <div class="wrap-text"><button
                onclick="django.jQuery('#id_get_board_%d').toggle();
                    if(django.jQuery(this).html()=='%s'){
                        django.jQuery(this).html('%s')
                    }else{
                        django.jQuery(this).html('%s')
                    };
                    return false;"
                >%s</button>
                <div id="id_get_board_%d" style="display:none;">%s</div></div>
            """ % (
                self.id, _("Show"), _("Hide"), _("Show"), _("Show"), self.id, board
            )
            return msg_html
        else:
            return '<div class="wrap-text">%s</div>' % _("Empty board")
Patrick's avatar
Patrick committed
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416

    get_board.short_description = (_("permanence board"))
    get_board.allow_tags = True

    def set_status(self, new_status, all_producers=True, producers_id=None, update_payment_date=False,
                   payment_date=None, allow_downgrade=True):
        if all_producers:
            now = timezone.now().date()
            self.is_updated_on = now
            self.status = new_status
            if self.highest_status < new_status:
                self.highest_status = new_status
            if update_payment_date:
                if payment_date is None:
                    self.payment_date = now
                else:
                    self.payment_date = payment_date
                self.save(
417
                    update_fields=['status', 'is_updated_on', 'highest_status', 'payment_date'])
Patrick's avatar
Patrick committed
418
            else:
419
                self.save(update_fields=['status', 'is_updated_on', 'highest_status'])
Patrick's avatar
Patrick committed
420 421 422 423 424 425 426 427 428 429 430 431 432
            if new_status == PERMANENCE_WAIT_FOR_OPEN:
                for a_producer in producer.Producer.objects.filter(
                        permanence=self.id
                ).only('id').order_by('?'):
                    # Create ProducerInvoice to be able to close those producer on demand
                    if not invoice.ProducerInvoice.objects.filter(
                            permanence_id=self.id,
                            producer_id=a_producer.id
                    ).order_by('?').exists():
                        invoice.ProducerInvoice.objects.create(
                            permanence_id=self.id,
                            producer_id=a_producer.id
                        )
433 434 435 436

            self.with_delivery_point = deliveryboard.DeliveryBoard.objects.filter(
                permanence_id=self.id
            ).order_by('?').exists()
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
            if self.with_delivery_point:
                qs = deliveryboard.DeliveryBoard.objects.filter(
                    permanence_id=self.id
                ).exclude(status=new_status).order_by('?')
                for delivery_point in qs:
                    if allow_downgrade or delivery_point.status < new_status:
                        # --> or delivery_point.status < new_status -->
                        # Set new status except if PERMANENCE_SEND, PERMANENCE_WAIT_FOR_SEND
                        #  -> PERMANENCE_CLOSED, PERMANENCE_WAIT_FOR_CLOSED
                        # This occur if directly sending order of a opened delivery point
                        delivery_point.set_status(new_status)
            invoice.CustomerInvoice.objects.filter(
                permanence_id=self.id,
                delivery__isnull=True
            ).order_by('?').update(
                status=new_status
            )
            purchase.Purchase.objects.filter(
                permanence_id=self.id,
                customer_invoice__delivery__isnull=True
            ).order_by('?').update(
                status=new_status)
            invoice.ProducerInvoice.objects.filter(
                permanence_id=self.id
            ).order_by('?').update(
                status=new_status
            )
            if update_payment_date:
                if payment_date is None:
                    self.payment_date = now
                else:
                    self.payment_date = payment_date
                self.save(
                    update_fields=['status', 'is_updated_on', 'highest_status', 'with_delivery_point', 'payment_date'])
            else:
472
                self.save(update_fields=['status', 'is_updated_on', 'highest_status', 'with_delivery_point'])
Patrick's avatar
Patrick committed
473 474 475 476 477 478 479 480 481
            menu_pool.clear()
            cache.clear()
        else:
            # /!\ If one delivery point has been closed, I may not close anymore by producer
            purchase.Purchase.objects.filter(permanence_id=self.id, producer__in=producers_id).order_by('?').update(
                status=new_status)
            invoice.ProducerInvoice.objects.filter(permanence_id=self.id, producer__in=producers_id).order_by(
                '?').update(status=new_status)

Patrick's avatar
Patrick committed
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 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 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
    def duplicate(self, repeat_counter=0, repeat_step=1):
        creation_counter = 0
        if 1 <= repeat_counter * repeat_step <= 54:
            # 54 weeks in a year
            repeat_counter += 1
            starting_date = self.permanence_date
            short_name = self.safe_translation_getter(
                'short_name', any_language=True, default=EMPTY_STRING
            )
            cur_language = translation.get_language()
            every_x_days = 7 * int(repeat_step)
            for i in range(1, repeat_counter):
                new_date = starting_date + datetime.timedelta(days=every_x_days * i)
                # Mandatory because of Parler
                if short_name != EMPTY_STRING:
                    already_exists = Permanence.objects.filter(
                        permanence_date=new_date,
                        translations__language_code=cur_language,
                        translations__short_name=short_name
                    ).exists()
                else:
                    already_exists = False
                    for existing_permanence in Permanence.objects.filter(
                            permanence_date=new_date
                    ):
                        try:
                            short_name = existing_permanence.short_name
                            already_exists = short_name == EMPTY_STRING
                        except TranslationDoesNotExist:
                            already_exists = True
                        if already_exists:
                            break
                if not already_exists:
                    creation_counter += 1
                    new_permanence = Permanence.objects.create(
                        permanence_date=new_date
                    )
                    self.duplicate_short_name(
                        new_permanence,
                        cur_language=translation.get_language(),
                    )
                    for permanence_board in permanenceboard.PermanenceBoard.objects.filter(
                            permanence=self
                    ):
                        permanenceboard.PermanenceBoard.objects.create(
                            permanence=new_permanence,
                            permanence_role=permanence_board.permanence_role
                        )
                    for delivery_board in deliveryboard.DeliveryBoard.objects.filter(
                            permanence=self
                    ):
                        new_delivery_board = deliveryboard.DeliveryBoard.objects.create(
                            permanence=new_permanence,
                            delivery_point=delivery_board.delivery_point,
                            delivery_date=delivery_board.delivery_date + datetime.timedelta(days=every_x_days * i)
                        )
                        for language in settings.PARLER_LANGUAGES[settings.SITE_ID]:
                            language_code = language["code"]
                            translation.activate(language_code)
                            new_delivery_board.set_current_language(language_code)
                            delivery_board.set_current_language(language_code)
                            try:
                                new_delivery_board.delivery_comment = delivery_board.delivery_comment
                                new_delivery_board.save()
                            except TranslationDoesNotExist:
                                pass
                        translation.activate(cur_language)
                    for producer in self.producers.all():
                        new_permanence.producers.add(producer)
        return creation_counter

    def duplicate_short_name(self, new_permanence, cur_language):
        for language in settings.PARLER_LANGUAGES[settings.SITE_ID]:
            language_code = language["code"]
            translation.activate(language_code)
            new_permanence.set_current_language(language_code)
            self.set_current_language(language_code)
            try:
                new_permanence.short_name = self.short_name
                new_permanence.save()
            except TranslationDoesNotExist:
                pass
        translation.activate(cur_language)
        return new_permanence

567
    def create_child(self, status):
Patrick's avatar
Patrick committed
568 569
        child_permanence = Permanence.objects.create(
            permanence_date=self.permanence_date,
570 571
            master_permanence_id=self.id,
            status=status
Patrick's avatar
Patrick committed
572 573 574 575 576 577
        )
        return self.duplicate_short_name(
            child_permanence,
            cur_language=translation.get_language(),
        )

Patrick's avatar
Patrick committed
578 579 580 581 582 583
    def get_full_status_display(self):
        return get_full_status_display(self)

    get_full_status_display.short_description = (_("permanence_status"))
    get_full_status_display.allow_tags = True

Patrick's avatar
Patrick committed
584 585 586
    def get_permanence_display(self):
        short_name = self.safe_translation_getter(
            'short_name', any_language=True
587
        )
Patrick's avatar
Patrick committed
588 589 590 591 592 593 594 595
        if short_name:
            permanence_display = "%s" % short_name
        else:
            permanence_display = '%s%s' % (
                repanier.apps.REPANIER_SETTINGS_PERMANENCE_ON_NAME,
                self.permanence_date.strftime(settings.DJANGO_SETTINGS_DATE)
            )
        return permanence_display
596

Patrick's avatar
Patrick committed
597 598 599 600 601 602 603 604 605 606 607 608 609
    def get_permanence_admin_display(self):
        if self.total_price_wo_tax != DECIMAL_ZERO:
            if self.total_profit.amount != DECIMAL_ZERO:
                return '%s<br/>%s %s<br/>৺ %s<br/>%s%%' % (
                    self.get_permanence_display(), _('wo tax'), self.total_price_wo_tax, self.total_profit,
                    number_format((self.total_profit.amount / self.total_price_wo_tax.amount) * 100, 2)
                )
            else:
                return '%s<br/>%s %s' % (
                    self.get_permanence_display(), _('wo tax'), self.total_price_wo_tax)
        else:
            if self.total_profit.amount != DECIMAL_ZERO:
                return '%s<br/>%s ৺ %s' % (self.get_permanence_display(), _('wo tax'), self.total_profit)
Patrick's avatar
Patrick committed
610
            else:
Patrick's avatar
Patrick committed
611 612 613 614 615
                return self.get_permanence_display()

    get_permanence_admin_display.short_description = lambda: "%s" % repanier.apps.REPANIER_SETTINGS_PERMANENCES_NAME
    get_permanence_admin_display.allow_tags = True

616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
    # def get_permanence_order_display(self):
    #     if self.with_delivery_point:
    #         if self.status == PERMANENCE_OPENED:
    #             deliveries_count = 0
    #         else:
    #             deliveries_qs = deliveryboard.DeliveryBoard.objects.filter(
    #                 permanence_id=self.id,
    #                 status=PERMANENCE_OPENED
    #             ).order_by('?')
    #             deliveries_count = deliveries_qs.count()
    #     else:
    #         deliveries_count = 0
    #     if deliveries_count == 0:
    #         return "%s - %s" % (self.get_permanence_display(), self.get_status_display())
    #     return self.get_permanence_display()
Patrick's avatar
Patrick committed
631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646

    def get_permanence_customer_display(self, with_status=True):
        if with_status:
            if self.with_delivery_point:
                if self.status == PERMANENCE_OPENED:
                    deliveries_count = 0
                else:
                    deliveries_qs = deliveryboard.DeliveryBoard.objects.filter(
                        permanence_id=self.id,
                        status=PERMANENCE_OPENED
                    ).order_by('?')
                    deliveries_count = deliveries_qs.count()
            else:
                deliveries_count = 0
            if deliveries_count == 0:
                if self.status != PERMANENCE_SEND:
Patrick's avatar
Patrick committed
647
                    return "%s - %s" % (self.get_permanence_display(), self.get_status_display())
Patrick's avatar
Patrick committed
648
                else:
Patrick's avatar
Patrick committed
649 650
                    return "%s - %s" % (self.get_permanence_display(), _('orders closed'))
        return self.get_permanence_display()
Patrick's avatar
Patrick committed
651 652

    def __str__(self):
Patrick's avatar
Patrick committed
653
        return self.get_permanence_display()
Patrick's avatar
Patrick committed
654 655

    class Meta:
656 657
        verbose_name = _('order')
        verbose_name_plural = _('orders')
Patrick's avatar
Patrick committed
658 659 660 661 662 663 664 665 666

        index_together = [
            ["permanence_date"],
        ]


class PermanenceInPreparation(Permanence):
    class Meta:
        proxy = True
667 668
        verbose_name = _('In preparation')
        verbose_name_plural = _('In preparation')
Patrick's avatar
Patrick committed
669 670 671 672 673


class PermanenceDone(Permanence):
    class Meta:
        proxy = True
674 675
        verbose_name = _('In billing')
        verbose_name_plural = _('In billing')
Patrick's avatar
Patrick committed
676