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

import calendar
5
import datetime
Patrick's avatar
Patrick committed
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import json
import time
import urllib2
from smtplib import SMTPRecipientsRefused

from django.conf import settings
from django.contrib.auth.models import User
from django.core import mail
from django.core import urlresolvers
from django.core.cache import cache
from django.core.mail import EmailMessage, mail_admins
from django.core.serializers.json import DjangoJSONEncoder
from django.db import transaction
from django.db.models import F
from django.db.models import Q, Sum
21
from django.http import Http404
Patrick's avatar
Patrick committed
22
from django.template.loader import render_to_string
Patrick's avatar
Patrick committed
23
from django.utils import timezone
Patrick's avatar
Patrick committed
24
from django.utils import translation
pi's avatar
pi committed
25
from django.utils.formats import number_format
Patrick's avatar
Patrick committed
26
27
28
29
30
from django.utils.safestring import mark_safe
from django.utils.text import slugify
from django.utils.translation import ugettext_lazy as _
from parler.models import TranslationDoesNotExist

Patrick's avatar
Patrick committed
31
import models
Patrick's avatar
Patrick committed
32
33
34
from const import *
from repanier import apps
from repanier.fields.RepanierMoneyField import RepanierMoney
Patrick's avatar
Patrick committed
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50


def ignore_exception(exception=Exception, default_val=0):
    """Returns a decorator that ignores an exception raised by the function it
    decorates.

    Using it as a decorator:

    @ignore_exception(ValueError)
    def my_function():
    pass

    Using it as a function wrapper:

    int_try_parse = ignore_exception(ValueError)(int)
    """
Patrick's avatar
Patrick committed
51

Patrick's avatar
Patrick committed
52
53
54
55
56
57
    def decorator(function):
        def wrapper(*args, **kwargs):
            try:
                return function(*args, **kwargs)
            except exception:
                return default_val
Patrick's avatar
Patrick committed
58

Patrick's avatar
Patrick committed
59
        return wrapper
Patrick's avatar
Patrick committed
60

Patrick's avatar
Patrick committed
61
62
    return decorator

Patrick's avatar
Patrick committed
63

Patrick's avatar
Patrick committed
64
sint = ignore_exception(ValueError)(int)
65
sboolean = ignore_exception(ValueError)(bool)
Patrick's avatar
Patrick committed
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87


def next_row(query_iterator):
    try:
        return next(query_iterator)
    except StopIteration:
        # No rows were found, so do nothing.
        return None


def send_email(email=None, track_customer_on_error=False):
    if settings.DJANGO_SETTINGS_DEMO:
        email.to = [DEMO_EMAIL]
        email.cc = []
        email.bcc = []
        send_email_with_error_log(email)
    elif settings.DEBUG:
        print('############################ debug, send_email')
        print("to : %s" % email.to)
        print("cc : %s" % email.cc)
        print("bcc : %s" % email.bcc)
        print("subject : %s" % slugify(email.subject))
88
89
        if apps.REPANIER_SETTINGS_TEST_MODE:
            email.to = [v for k, v in settings.ADMINS]
Patrick's avatar
Patrick committed
90
91
            email.cc = []
            email.bcc = []
Patrick's avatar
Patrick committed
92
93
            print('the mail is send to : %s' % email.to)
            send_email_with_error_log(email)
94
    elif apps.REPANIER_SETTINGS_TEST_MODE:
Patrick's avatar
Patrick committed
95
        coordinator = models.Staff.objects.filter(is_coordinator=True, is_active=True).order_by("id").first()
Patrick's avatar
Patrick committed
96
97
98
99
100
101
        if coordinator is not None:
            email.to = [coordinator.user.email]
        else:
            email.to = [v for k, v in settings.ADMINS]
        email.cc = []
        email.bcc = []
Patrick's avatar
Patrick committed
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
        send_email_with_error_log(email)
    else:
        # chunks = [email.to[x:x+100] for x in xrange(0, len(email.to), 100)]
        # for chunk in chunks:
        if len(email.bcc) > 1:
            # Remove duplicate
            email_bcc = list(set(email.bcc))
            customer = None
            for bcc in email_bcc:
                email.bcc = [bcc]
                if track_customer_on_error:
                    # If the email is conained both in user__email and customer__email2
                    # select the customer based on user__email
                    customer = models.Customer.objects.filter(user__email=bcc).order_by('?').first()
                    if customer is None:
                        customer = models.Customer.objects.filter(email2=bcc).order_by('?').first()
                time.sleep(2)
                send_email_with_error_log(email, customer)
        else:
            send_email_with_error_log(email)


def send_email_with_error_log(email, customer=None):
    with mail.get_connection() as connection:
        email.connection = connection
        message = EMPTY_STRING
        try:
            print("################################## send_email")
            to = "to : %s" % email.to
            cc = "cc : %s" % email.cc
            bcc = "bcc : %s" % email.bcc
            subject = "subject : %s" % slugify(email.subject)
            print(to)
            print(cc)
            print(bcc)
            print(subject)
            message = "%s\n%s\n%s\n%s" % (to, cc, bcc, subject)
            email.send()
            valid_email = True
        except SMTPRecipientsRefused as error_str:
            valid_email = False
            print("################################## send_email error")
            print(error_str)
            time.sleep(2)
            connection = mail.get_connection()
            connection.open()
            mail_admins("ERROR", "%s\n%s" % (message, error_str), connection=connection)
            connection.close()
        except Exception as error_str:
            valid_email = None
            print("################################## send_email error")
            print(error_str)
            time.sleep(2)
            connection = mail.get_connection()
            connection.open()
            mail_admins("ERROR", "%s\n%s" % (message, error_str), connection=connection)
            connection.close()
        if customer is not None:
            customer.valid_email = valid_email
            customer.save(update_fields=['valid_email'])
        print("##################################")


def send_email_to_who(is_email_send, board=False):
    if not is_email_send:
        if board:
            if settings.DEBUG:
                if apps.REPANIER_SETTINGS_TEST_MODE:
                    return True, _("This email will be sent to %s.") % ' ,'.join(v for k, v in settings.ADMINS)
                else:
                    return False, _("No email will be sent.")
            elif apps.REPANIER_SETTINGS_TEST_MODE:
                coordinator = models.Staff.objects.filter(is_coordinator=True, is_active=True).order_by('?').first()
                if coordinator is not None:
                    return True, _("This email will be sent to %s.") % coordinator.user.email
                else:
                    return True, _("This email will be sent to %s.") % ' ,'.join(v for k, v in settings.ADMINS)
            else:
                return True, _("This email will be sent to the staff.")
        else:
            return False, _("No email will be sent.")
Patrick's avatar
Patrick committed
183
    else:
Patrick's avatar
Patrick committed
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
        if settings.DEBUG:
            if apps.REPANIER_SETTINGS_TEST_MODE:
                return True, _("This email will be sent to %s.") % ' ,'.join(v for k, v in settings.ADMINS)
            else:
                return False, _("No email will be sent.")
        elif apps.REPANIER_SETTINGS_TEST_MODE:
            coordinator = models.Staff.objects.filter(is_coordinator=True, is_active=True).order_by('?').first()
            if coordinator is not None:
                return True, _("This email will be sent to %s.") % coordinator.user.email
            else:
                return True, _("This email will be sent to %s.") % ' ,'.join(v for k, v in settings.ADMINS)
        else:
            if board:
                return True, _("This email will be sent to the preparation team and the staff.")
            else:
                return True, _("This email will be sent to customers or producers depending of the case.")


def send_sms(sms_nr=None, sms_msg=None):
    try:
        if sms_nr is not None and sms_msg is not None:
            valid_nr = "0"
            i = 0
            while i < len(sms_nr) and not sms_nr[i] == '4':
                i += 1
            while i < len(sms_nr):
                if '0' <= sms_nr[i] <= '9':
                    valid_nr += sms_nr[i]
                i += 1
            if len(valid_nr) == 10 \
                    and apps.REPANIER_SETTINGS_SMS_GATEWAY_MAIL is not None \
                    and len(apps.REPANIER_SETTINGS_SMS_GATEWAY_MAIL) > 0:
                # Send SMS with free gateway : Sms Gateway - Android.
                email = EmailMessage(valid_nr, sms_msg, "no-reply@repanier.be",
                                     [apps.REPANIER_SETTINGS_SMS_GATEWAY_MAIL, ])
                send_email(email=email)
    except:
        pass
Patrick's avatar
Patrick committed
222
223
224
225


def get_signature(is_reply_to_order_email=False, is_reply_to_invoice_email=False):
    sender_email = None
Patrick's avatar
Patrick committed
226
227
    sender_function = EMPTY_STRING
    signature = EMPTY_STRING
Patrick's avatar
Patrick committed
228
    cc_email_staff = []
Patrick's avatar
Patrick committed
229
    for staff in models.Staff.objects.filter(is_active=True).order_by('?'):
Patrick's avatar
Patrick committed
230
231
        if (is_reply_to_order_email and staff.is_reply_to_order_email) \
                or (is_reply_to_invoice_email and staff.is_reply_to_invoice_email):
232
            cc_email_staff.append(staff.user.email)
Patrick's avatar
Patrick committed
233
            sender_email = staff.user.email
Patrick's avatar
Patrick committed
234
235
236
237
            try:
                sender_function = staff.long_name
            except TranslationDoesNotExist:
                sender_function = EMPTY_STRING
Patrick's avatar
Patrick committed
238
239
240
241
242
243
            r = staff.customer_responsible
            if r:
                if r.long_basket_name:
                    signature = "%s - %s" % (r.long_basket_name, r.phone1)
                else:
                    signature = "%s - %s" % (r.short_basket_name, r.phone1)
Patrick's avatar
Patrick committed
244
                if r.phone2 and len(r.phone2.strip()) > 0:
Patrick's avatar
Patrick committed
245
                    signature += " / %s" % (r.phone2,)
246
247
248
        elif staff.is_coordinator:
            cc_email_staff.append(staff.user.email)

Patrick's avatar
Patrick committed
249
    if sender_email is None:
Patrick's avatar
Patrick committed
250
        sender_email = settings.DEFAULT_FROM_EMAIL
Patrick's avatar
Patrick committed
251
    return sender_email, sender_function, signature, cc_email_staff
pi's avatar
pi committed
252

Patrick's avatar
Patrick committed
253

Patrick's avatar
Patrick committed
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
def get_board_composition(permanence_id):
    board_composition = EMPTY_STRING
    board_composition_and_description = EMPTY_STRING
    for permanenceboard in models.PermanenceBoard.objects.filter(
            permanence=permanence_id).order_by(
        "permanence_role__tree_id",
        "permanence_role__lft"
    ):
        r = permanenceboard.permanence_role
        c = permanenceboard.customer
        if c is not None:
            if c.phone2 is not None:
                c_part = "%s, <b>%s</b>, <b>%s</b>" % (c.long_basket_name, c.phone1, c.phone2)
            else:
                c_part = "%s, <b>%s</b>" % (c.long_basket_name, c.phone1)
            member = "<b>%s</b> : %s, %s<br/>" % (r.short_name, c_part, c.user.email)
            board_composition += member
            board_composition_and_description += "%s%s<br/>" % (member, r.description)

    return board_composition, board_composition_and_description


Patrick's avatar
Patrick committed
276
LENGTH_BY_PREFIX = [
277
278
279
280
281
    (0xC0, 2),  # first byte mask, total codepoint length
    (0xE0, 3),
    (0xF0, 4),
    (0xF8, 5),
    (0xFC, 6),
Patrick's avatar
Patrick committed
282
283
]

284

Patrick's avatar
Patrick committed
285
286
def codepoint_length(first_byte):
    if first_byte < 128:
287
        return 1  # ASCII
Patrick's avatar
Patrick committed
288
289
    for mask, length in LENGTH_BY_PREFIX:
        if first_byte & 0xF0 == mask:
290
            return length
Patrick's avatar
Patrick committed
291
        elif first_byte & 0xF8 == 0xF8:
292
            return length
Patrick's avatar
Patrick committed
293
294
    assert False, 'Invalid byte %r' % first_byte

295

Patrick's avatar
Patrick committed
296
def cap_to_bytes_length(unicode_text, byte_limit):
Patrick's avatar
Patrick committed
297
    utf8_bytes = unicode_text.encode("utf8")
Patrick's avatar
Patrick committed
298
299
300
301
302
303
304
305
306
307
    cut_index = 0
    while cut_index < len(utf8_bytes):
        step = codepoint_length(ord(utf8_bytes[cut_index]))
        if cut_index + step > byte_limit:
            # can't go a whole codepoint further, time to cut
            return utf8_bytes[:cut_index] + '...'
        else:
            cut_index += step
    return utf8_bytes

308

Patrick's avatar
Patrick committed
309
def cap(s, l):
Patrick's avatar
Patrick committed
310
    if s is not None:
311
312
        if not isinstance(s, basestring):
            s = str(s)
Patrick's avatar
Patrick committed
313
        s = s if len(s) <= l else s[0:l - 4] + '...'
314
        return s
Patrick's avatar
Patrick committed
315
    else:
316
317
318
        return None


319
320
321
322
323
324
def permanence_ok_or_404(permanence):
    if permanence is None:
        raise Http404
    if permanence.status not in [PERMANENCE_OPENED, PERMANENCE_CLOSED, PERMANENCE_SEND]:
        if permanence.status in [PERMANENCE_DONE, PERMANENCE_ARCHIVED]:
            if permanence.permanence_date < (
Patrick's avatar
Patrick committed
325
                        timezone.now() - datetime.timedelta(weeks=LIMIT_DISPLAYED_PERMANENCE)
326
327
328
329
330
331
            ).date():
                raise Http404
        else:
            raise Http404


332
333
def get_invoice_unit(order_unit=PRODUCT_ORDER_UNIT_PC, qty=0):
    if order_unit in [PRODUCT_ORDER_UNIT_KG, PRODUCT_ORDER_UNIT_PC_KG]:
Patrick's avatar
Patrick committed
334
        unit = _("/ kg")
335
    elif order_unit == PRODUCT_ORDER_UNIT_LT:
Patrick's avatar
Patrick committed
336
        unit = _("/ l")
Patrick's avatar
Patrick committed
337
    else:
338
        if qty < 2:
Patrick's avatar
Patrick committed
339
            unit = _("/ piece")
340
        else:
Patrick's avatar
Patrick committed
341
            unit = _("/ pieces")
342
343
344
    return unit


Patrick's avatar
Patrick committed
345
def get_preparator_unit(order_unit=PRODUCT_ORDER_UNIT_PC):
346
    # Used when producing the preparation list.
347
348
    if order_unit in [PRODUCT_ORDER_UNIT_PC, PRODUCT_ORDER_UNIT_PC_PRICE_KG, PRODUCT_ORDER_UNIT_PC_PRICE_LT,
                      PRODUCT_ORDER_UNIT_PC_PRICE_PC]:
Patrick's avatar
Patrick committed
349
        unit = _("Piece(s) :")
350
    elif order_unit in [PRODUCT_ORDER_UNIT_KG, PRODUCT_ORDER_UNIT_PC_KG]:
Patrick's avatar
Patrick committed
351
        unit = _("%s or kg :") % (apps.REPANIER_SETTINGS_CURRENCY_DISPLAY.decode('utf-8'),)
352
    elif order_unit == PRODUCT_ORDER_UNIT_LT:
Patrick's avatar
Patrick committed
353
        unit = _("L :")
354
    else:
Patrick's avatar
Patrick committed
355
        unit = _("Kg :")
356
357
358
    return unit


Patrick's avatar
Patrick committed
359
360
def get_base_unit(qty=0, order_unit=PRODUCT_ORDER_UNIT_PC, status=None):
    if order_unit == PRODUCT_ORDER_UNIT_KG or (status >= PERMANENCE_SEND and order_unit == PRODUCT_ORDER_UNIT_PC_KG):
361
        if qty == DECIMAL_ZERO:
Patrick's avatar
Patrick committed
362
            base_unit = EMPTY_STRING
363
364
365
366
        else:
            base_unit = _('kg')
    elif order_unit == PRODUCT_ORDER_UNIT_LT:
        if qty == DECIMAL_ZERO:
Patrick's avatar
Patrick committed
367
            base_unit = EMPTY_STRING
368
369
370
371
        else:
            base_unit = _('l')
    else:
        if qty == DECIMAL_ZERO:
Patrick's avatar
Patrick committed
372
            base_unit = EMPTY_STRING
373
374
375
376
377
378
379
        elif qty < 2:
            base_unit = _('piece')
        else:
            base_unit = _('pieces')
    return base_unit


Patrick's avatar
Patrick committed
380
381
def get_display(qty=0, order_average_weight=0, order_unit=PRODUCT_ORDER_UNIT_PC, unit_price_amount=None,
                for_customer=True, for_order_select=False, without_price_display=False):
382
383
    magnitude = None
    display_qty = True
384
    if order_unit == PRODUCT_ORDER_UNIT_KG:
385
        if qty == DECIMAL_ZERO:
Patrick's avatar
Patrick committed
386
            unit = EMPTY_STRING
387
388
389
        elif for_customer and qty < 1:
            unit = "%s" % (_('gr'))
            magnitude = 1000
390
        else:
391
            unit = "%s" % (_('kg'))
392
    elif order_unit == PRODUCT_ORDER_UNIT_LT:
393
        if qty == DECIMAL_ZERO:
Patrick's avatar
Patrick committed
394
            unit = EMPTY_STRING
395
396
397
        elif for_customer and qty < 1:
            unit = "%s" % (_('cl'))
            magnitude = 100
398
        else:
399
            unit = "%s" % (_('l'))
400
    elif order_unit in [PRODUCT_ORDER_UNIT_PC_KG, PRODUCT_ORDER_UNIT_PC_PRICE_KG]:
401
        # display_qty = not (order_average_weight == 1 and order_unit == PRODUCT_ORDER_UNIT_PC_PRICE_KG)
402
403
404
        average_weight = order_average_weight
        if for_customer:
            average_weight *= qty
Patrick's avatar
Patrick committed
405
406
        if order_unit == PRODUCT_ORDER_UNIT_PC_KG and unit_price_amount is not None:
            unit_price_amount *= order_average_weight
407
        if average_weight < 1:
Patrick's avatar
Patrick committed
408
            average_weight_unit = _('gr')
409
410
            average_weight *= 1000
        else:
Patrick's avatar
Patrick committed
411
            average_weight_unit = _('kg')
412
413
414
415
416
417
418
        decimal = 3
        if average_weight == int(average_weight):
            decimal = 0
        elif average_weight * 10 == int(average_weight * 10):
            decimal = 1
        elif average_weight * 100 == int(average_weight * 100):
            decimal = 2
Patrick's avatar
Patrick committed
419
        tilde = EMPTY_STRING
420
421
        if order_unit == PRODUCT_ORDER_UNIT_PC_KG:
            tilde = '~'
422
        if for_customer:
Patrick's avatar
Patrick committed
423
            if qty == DECIMAL_ZERO:
Patrick's avatar
Patrick committed
424
                unit = EMPTY_STRING
425
            else:
426
                if order_average_weight == 1 and order_unit == PRODUCT_ORDER_UNIT_PC_PRICE_KG:
427
                    unit = "%s%s %s" % (tilde, number_format(average_weight, decimal), average_weight_unit)
428
429
                else:
                    unit = "%s%s%s" % (tilde, number_format(average_weight, decimal), average_weight_unit)
430
        else:
Patrick's avatar
Patrick committed
431
            if qty == DECIMAL_ZERO:
Patrick's avatar
Patrick committed
432
                unit = EMPTY_STRING
433
            else:
434
                unit = "%s%s%s" % (tilde, number_format(average_weight, decimal), average_weight_unit)
435
    elif order_unit == PRODUCT_ORDER_UNIT_PC_PRICE_LT:
436
        display_qty = order_average_weight != 1
437
438
439
        average_weight = order_average_weight
        if for_customer:
            average_weight *= qty
440
        if average_weight < 1:
Patrick's avatar
Patrick committed
441
            average_weight_unit = _('cl')
442
443
            average_weight *= 100
        else:
Patrick's avatar
Patrick committed
444
            average_weight_unit = _('l')
445
446
447
448
449
450
451
        decimal = 3
        if average_weight == int(average_weight):
            decimal = 0
        elif average_weight * 10 == int(average_weight * 10):
            decimal = 1
        elif average_weight * 100 == int(average_weight * 100):
            decimal = 2
452
        if for_customer:
Patrick's avatar
Patrick committed
453
            if qty == DECIMAL_ZERO:
Patrick's avatar
Patrick committed
454
                unit = EMPTY_STRING
455
            else:
456
457
458
459
                if display_qty:
                    unit = "%s%s" % (number_format(average_weight, decimal), average_weight_unit)
                else:
                    unit = "%s %s" % (number_format(average_weight, decimal), average_weight_unit)
460
        else:
Patrick's avatar
Patrick committed
461
            if qty == DECIMAL_ZERO:
Patrick's avatar
Patrick committed
462
                unit = EMPTY_STRING
463
            else:
464
                unit = "%s%s" % (number_format(average_weight, decimal), average_weight_unit)
465
    elif order_unit == PRODUCT_ORDER_UNIT_PC_PRICE_PC:
466
        display_qty = order_average_weight != 1
467
468
469
        average_weight = order_average_weight
        if for_customer:
            average_weight *= qty
Patrick's avatar
Patrick committed
470
            if qty == DECIMAL_ZERO:
Patrick's avatar
Patrick committed
471
                unit = EMPTY_STRING
472
            else:
Patrick's avatar
Patrick committed
473
                if average_weight < 2:
474
475
476
477
478
                    pc_pcs = _('pc')
                else:
                    pc_pcs = _('pcs')
                if display_qty:
                    unit = "%s%s" % (number_format(average_weight, 0), pc_pcs)
Patrick's avatar
Patrick committed
479
                else:
480
                    unit = "%s %s" % (number_format(average_weight, 0), pc_pcs)
481
        else:
Patrick's avatar
Patrick committed
482
            if average_weight == DECIMAL_ZERO:
Patrick's avatar
Patrick committed
483
                unit = EMPTY_STRING
Patrick's avatar
Patrick committed
484
            elif average_weight < 2:
485
                unit = '%s %s' % (number_format(average_weight, 0), _('pc'))
486
            else:
487
488
                unit = '%s %s' % (number_format(average_weight, 0), _('pcs'))
    else:
Patrick's avatar
Patrick committed
489
490
491
492
493
494
495
        if for_order_select:
            if qty == DECIMAL_ZERO:
                unit = EMPTY_STRING
            elif qty < 2:
                unit = "%s" % (_('unit'))
            else:
                unit = "%s" % (_('units'))
496
        else:
Patrick's avatar
Patrick committed
497
498
499
            unit = EMPTY_STRING
    if unit_price_amount is not None:
        price_display = " = %s" % (RepanierMoney(unit_price_amount * qty),)
Patrick's avatar
Patrick committed
500
    else:
Patrick's avatar
Patrick committed
501
        price_display = EMPTY_STRING
502
503
    if magnitude is not None:
        qty *= magnitude
504
505
506
507
508
509
510
    decimal = 3
    if qty == int(qty):
        decimal = 0
    elif qty * 10 == int(qty * 10):
        decimal = 1
    elif qty * 100 == int(qty * 100):
        decimal = 2
Patrick's avatar
Patrick committed
511
512
    if for_customer or for_order_select:
        if display_qty and len(unit) > 0:
513
514
            qty_display = "%s (%s)" % (number_format(qty, decimal), unit)
        else:
Patrick's avatar
Patrick committed
515
516
            if not for_order_select:
                qty_display = "%s" % number_format(qty, decimal)
517
            else:
Patrick's avatar
Patrick committed
518
519
520
521
                qty_display = EMPTY_STRING
    else:
        if len(unit) > 0:
            qty_display = "(%s)" % (unit,)
522
        else:
Patrick's avatar
Patrick committed
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
            qty_display = EMPTY_STRING
    if without_price_display:
        return qty_display
    else:
        display = "%s%s" % (qty_display, price_display,)
        return display


def on_hold_movement_message(customer, bank_not_invoiced=None, order_not_invoiced=None, total_price_with_tax=REPANIER_MONEY_ZERO):
    # If permanence_id is None, only "customer_on_hold_movement" is calculated
    if customer is None:
        customer_on_hold_movement = EMPTY_STRING
    else:
        if apps.REPANIER_SETTINGS_INVOICE:
            bank_not_invoiced = bank_not_invoiced if bank_not_invoiced is not None else customer.get_bank_not_invoiced()
            order_not_invoiced = order_not_invoiced if order_not_invoiced is not None else customer.get_order_not_invoiced()
            other_order_not_invoiced = order_not_invoiced - total_price_with_tax
        else:
            bank_not_invoiced = REPANIER_MONEY_ZERO
            other_order_not_invoiced = REPANIER_MONEY_ZERO

        if other_order_not_invoiced.amount != DECIMAL_ZERO or bank_not_invoiced.amount != DECIMAL_ZERO:
            if other_order_not_invoiced.amount != DECIMAL_ZERO:
                if bank_not_invoiced.amount == DECIMAL_ZERO:
                    customer_on_hold_movement = \
                        _('This balance does not take account of any unbilled sales %(other_order)s.') % {
                            'other_order': other_order_not_invoiced
                        }
                else:
                    customer_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': other_order_not_invoiced
                        }
559
            else:
Patrick's avatar
Patrick committed
560
561
562
563
564
                customer_on_hold_movement = \
                    _(
                        'This balance does not take account of any unrecognized payments %(bank)s.') % {
                        'bank': bank_not_invoiced
                    }
565
        else:
Patrick's avatar
Patrick committed
566
567
568
569
570
571
572
573
574
575
576
577
            customer_on_hold_movement = EMPTY_STRING

    return customer_on_hold_movement


def payment_message(customer, permanence):
    # If permanence_id is None, only "customer_on_hold_movement" is calculated
    customer_last_balance = EMPTY_STRING
    if customer is None or permanence is None:
        customer_order_amount = EMPTY_STRING
        customer_payment_needed = EMPTY_STRING
        customer_on_hold_movement = EMPTY_STRING
578
    else:
Patrick's avatar
Patrick committed
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
        customer_invoice = models.CustomerInvoice.objects.filter(
            customer_id=customer.id,
            permanence_id=permanence.id
        ).order_by('?').first()
        if customer_invoice is None:
            total_price_with_tax = REPANIER_MONEY_ZERO
        else:
            total_price_with_tax = customer_invoice.get_total_price_with_tax()
        customer_order_amount = \
            _('The amount of your order is %(amount)s.') % {
                'amount': total_price_with_tax
            }
        if apps.REPANIER_SETTINGS_INVOICE:
            bank_not_invoiced = customer.get_bank_not_invoiced()
            order_not_invoiced = customer.get_order_not_invoiced()
            payment_needed = - (customer.balance - order_not_invoiced + bank_not_invoiced)
            # other_order_not_invoiced = order_not_invoiced - total_price_with_tax
        else:
            bank_not_invoiced = REPANIER_MONEY_ZERO
            order_not_invoiced = DECIMAL_ZERO
            payment_needed = total_price_with_tax
            # other_order_not_invoiced = REPANIER_MONEY_ZERO

        if customer_invoice.customer_id != customer_invoice.customer_who_pays_id:
            invoices_sent_to = '<font color="green">%s</font>' % (
                _('Invoices for this delivery point are sent to %(name)s who is responsible for collecting the payments.') % {
                    'name': customer_invoice.customer_who_pays.long_basket_name
                }
            )
        else:
            invoices_sent_to = EMPTY_STRING
        customer_on_hold_movement = on_hold_movement_message(customer, bank_not_invoiced, order_not_invoiced, total_price_with_tax)
        if apps.REPANIER_SETTINGS_INVOICE:
            if customer.balance.amount != DECIMAL_ZERO:
                if customer.balance.amount < DECIMAL_ZERO:
                    balance = '<font color="#bd0926">%s</font>' % customer.balance
                else:
                    balance = '%s' % customer.balance
                customer_last_balance = \
                    _('The balance of your account as of %(date)s is %(balance)s.') % {
                        'date'   : customer.date_balance.strftime(settings.DJANGO_SETTINGS_DATE),
                        'balance': balance
                    }
            else:
                customer_last_balance = EMPTY_STRING

        bank_account_number = apps.REPANIER_SETTINGS_BANK_ACCOUNT
        if bank_account_number is not None:
            if payment_needed.amount > DECIMAL_ZERO:
                if permanence.short_name:
                    communication = "%s (%s)" % (customer.short_basket_name, permanence.short_name)
                else:
                    communication = customer.short_basket_name
                group_name = apps.REPANIER_SETTINGS_GROUP_NAME
                customer_payment_needed = '<br/><font color="#bd0926">%s</font>' % (
                    _('Please pay %(payment)s to the bank account %(name)s %(number)s with communication %(communication)s.') % {
                        'payment': payment_needed,
                        'name': group_name,
                        'number': bank_account_number,
                        'communication': communication
                    }
                )

            else:
                if customer.balance.amount != DECIMAL_ZERO:
                    customer_payment_needed = '<br/><font color="green">%s.</font>' % (_('Your account balance is sufficient'))
                else:
                    customer_payment_needed = EMPTY_STRING
            if invoices_sent_to:
                customer_payment_needed = invoices_sent_to + customer_payment_needed
        else:
            customer_payment_needed = invoices_sent_to

    return customer_last_balance, customer_on_hold_movement, customer_payment_needed, customer_order_amount


def recalculate_order_amount(permanence_id,
Patrick's avatar
Patrick committed
656
657
                             customer_id=None,
                             offer_item_queryset=None,
Patrick's avatar
Patrick committed
658
659
                             all_producers=True,
                             producers_id=None,
Patrick's avatar
Patrick committed
660
                             send_to_producer=False,
661
                             re_init=False):
Patrick's avatar
Patrick committed
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
    if send_to_producer or re_init:
        if all_producers:
            models.ProducerInvoice.objects.filter(
                permanence_id=permanence_id
            ).update(
                total_price_with_tax=DECIMAL_ZERO,
                total_vat=DECIMAL_ZERO,
                total_deposit=DECIMAL_ZERO,
                total_profit_with_tax=DECIMAL_ZERO,
                total_profit_vat=DECIMAL_ZERO
            )
            models.CustomerInvoice.objects.filter(
                permanence_id=permanence_id
            ).update(
                total_price_with_tax=DECIMAL_ZERO,
                total_vat=DECIMAL_ZERO,
                total_deposit=DECIMAL_ZERO
            )
            models.CustomerProducerInvoice.objects.filter(
                permanence_id=permanence_id
            ).update(
                total_purchase_with_tax=DECIMAL_ZERO,
                total_selling_with_tax=DECIMAL_ZERO
            )
            models.OfferItem.objects.filter(
                permanence_id=permanence_id
            ).update(
                quantity_invoiced=DECIMAL_ZERO,
                total_purchase_with_tax=DECIMAL_ZERO,
                total_selling_with_tax=DECIMAL_ZERO
            )
            for offer_item in models.OfferItem.objects.filter(
                    permanence_id=permanence_id,
                    is_active=True,
                    manage_replenishment=True
            ).exclude(add_2_stock=DECIMAL_ZERO).order_by('?'):
                # Recalculate the total_price_with_tax of ProducerInvoice and
                # the total_purchase_with_tax of OfferItem
                # taking into account "add_2_stock"
                offer_item.previous_add_2_stock = DECIMAL_ZERO
                offer_item.save()
        else:
            models.ProducerInvoice.objects.filter(
                permanence_id=permanence_id, producer_id__in=producers_id
            ).update(
                total_price_with_tax=DECIMAL_ZERO,
                total_vat=DECIMAL_ZERO,
                total_deposit=DECIMAL_ZERO
            )
            for ci in models.CustomerInvoice.objects.filter(
                    permanence_id=permanence_id):
                result_set = models.CustomerProducerInvoice.objects.filter(
                    permanence_id=permanence_id,
                    customer_id=ci.customer_id,
                    producer_id__in=producers_id
                ).order_by('?').aggregate(
                    Sum('total_selling_with_tax'),
Patrick's avatar
Patrick committed
719
                )
Patrick's avatar
Patrick committed
720
721
722
723
724
725
726
727
                if result_set["total_selling_with_tax__sum"] is not None:
                    sum_total_selling_with_tax = result_set["total_selling_with_tax__sum"]
                else:
                    sum_total_selling_with_tax = DECIMAL_ZERO
                models.CustomerInvoice.objects.filter(
                    permanence_id=permanence_id
                ).update(
                    total_price_with_tax=F('total_price_with_tax') - sum_total_selling_with_tax
Patrick's avatar
Patrick committed
728
                )
Patrick's avatar
Patrick committed
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
            models.CustomerProducerInvoice.objects.filter(
                permanence_id=permanence_id,
                producer_id__in=producers_id
            ).update(
                total_purchase_with_tax=DECIMAL_ZERO,
                total_selling_with_tax=DECIMAL_ZERO
            )
            models.OfferItem.objects.filter(
                permanence_id=permanence_id,
                producer_id__in=producers_id
            ).update(
                quantity_invoiced=DECIMAL_ZERO,
                total_purchase_with_tax=DECIMAL_ZERO,
                total_selling_with_tax=DECIMAL_ZERO
            )
            for offer_item in models.OfferItem.objects.filter(
                    permanence_id=permanence_id,
                    producer_id__in=producers_id,
                    is_active=True,
                    manage_replenishment=True
            ).exclude(add_2_stock=DECIMAL_ZERO).order_by('?'):
Patrick's avatar
Patrick committed
750
751
752
753
754
                # Recalculate the total_price_with_tax of ProducerInvoice and
                # the total_purchase_with_tax of OfferItem
                # taking into account "add_2_stock"
                offer_item.previous_add_2_stock = DECIMAL_ZERO
                offer_item.save()
Patrick's avatar
Patrick committed
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787

    if customer_id is None:
        if offer_item_queryset is not None:
            purchase_set = models.Purchase.objects \
                .filter(permanence_id=permanence_id, offer_item__in=offer_item_queryset) \
                .order_by('?')
        else:
            purchase_set = models.Purchase.objects \
                .filter(permanence_id=permanence_id) \
                .order_by('?')
            if not all_producers:
                purchase_set = purchase_set.filter(producer_id__in=producers_id)
    else:
        purchase_set = models.Purchase.objects \
            .filter(permanence_id=permanence_id, customer_id=customer_id) \
            .order_by('?')
        if not all_producers:
            purchase_set = purchase_set.filter(producer_id__in=producers_id)

    for purchase in purchase_set.select_related("offer_item"):
        # Recalcuate the total_price_with_tax of ProducerInvoice,
        # the total_price_with_tax of CustomerInvoice,
        # the total_purchase_with_tax + total_selling_with_tax of CustomerProducerInvoice,
        # and quantity_invoiced + total_purchase_with_tax + total_selling_with_tax of OfferItem
        offer_item = purchase.offer_item
        if send_to_producer or re_init:
            # purchase.admin_update = True
            purchase.previous_quantity = DECIMAL_ZERO
            purchase.previous_purchase_price = DECIMAL_ZERO
            purchase.previous_selling_price = DECIMAL_ZERO
            purchase.previous_producer_vat = DECIMAL_ZERO
            purchase.previous_customer_vat = DECIMAL_ZERO
            purchase.previous_deposit = DECIMAL_ZERO
Patrick's avatar
Patrick committed
788
789
            if send_to_producer:
                if offer_item.order_unit == PRODUCT_ORDER_UNIT_PC_KG:
Patrick's avatar
Patrick committed
790
                    purchase.quantity_invoiced = (purchase.quantity_ordered * offer_item.order_average_weight) \
Patrick's avatar
Patrick committed
791
792
793
794
795
                        .quantize(FOUR_DECIMALS)
                    if offer_item.wrapped:
                        purchase.quantity_for_preparation_sort_order = DECIMAL_ZERO
                    else:
                        purchase.quantity_for_preparation_sort_order = purchase.quantity_ordered
796
797
798
799
800
801
                elif offer_item.order_unit == PRODUCT_ORDER_UNIT_KG:
                    purchase.quantity_invoiced = purchase.quantity_ordered
                    if offer_item.wrapped:
                        purchase.quantity_for_preparation_sort_order = DECIMAL_ZERO
                    else:
                        purchase.quantity_for_preparation_sort_order = purchase.quantity_ordered
Patrick's avatar
Patrick committed
802
803
804
                else:
                    purchase.quantity_invoiced = purchase.quantity_ordered
                    purchase.quantity_for_preparation_sort_order = DECIMAL_ZERO
Patrick's avatar
Patrick committed
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
        purchase.save()


def display_selected_value(customer, offer_item, quantity_ordered):
    if offer_item.may_order:
        if quantity_ordered <= DECIMAL_ZERO:
            q_min = offer_item.customer_minimum_order_quantity
            if offer_item.limit_order_quantity_to_stock:
                q_alert = offer_item.stock - offer_item.quantity_invoiced
                if q_alert < DECIMAL_ZERO:
                    q_alert = DECIMAL_ZERO
            else:
                q_alert = offer_item.customer_alert_order_quantity
            if q_min <= q_alert:
                qs = models.ProducerInvoice.objects.filter(
                    permanence__offeritem=offer_item.id,
                    producer__offeritem=offer_item.id,
                    status=PERMANENCE_OPENED
                ).order_by('?')
                if qs.exists():
                    option_dict = {
                        'id'  : "#offer_item%d" % offer_item.id,
                        'html': '<option value="0" selected>---</option>'
                    }
                else:
                    closed = _("Closed")
                    option_dict = {
                        'id'  : "#offer_item%d" % offer_item.id,
                        'html': '<option value="0" selected>%s</option>' % closed
                    }
            else:
                sold_out = _("Sold out")
                option_dict = {
                    'id'  : "#offer_item%d" % offer_item.id,
                    'html': '<option value="0" selected>%s</option>' % sold_out
                }

        else:
            unit_price_amount = offer_item.customer_unit_price.amount + offer_item.unit_deposit.amount
            display = get_display(
                qty=quantity_ordered,
                order_average_weight=offer_item.order_average_weight,
                order_unit=offer_item.order_unit,
                unit_price_amount=unit_price_amount,
                for_order_select=True
            )
            option_dict = {
                'id'  : "#offer_item%d" % offer_item.id,
                'html': '<option value="%d" selected>%s</option>' % (quantity_ordered, display,)
            }
    else:
        option_dict = {
            'id'  : "#box_offer_item%d" % offer_item.id,
            'html': ''
        }
    return option_dict


def display_selected_box_value(customer, offer_item):
    if offer_item.is_box_content:
        # box_name = _not_lazy("Composition")
        box_name = BOX_UNICODE
        # Select one purchase
        box_purchase = models.Purchase.objects.filter(
            customer_id=customer.id,
            offer_item_id=offer_item.id,
            # counter=0,
            is_box_content=True
        ).only("quantity_ordered").order_by('?')
        if box_purchase.exists():
            box_purchase = box_purchase.first()
            if box_purchase.quantity_ordered > DECIMAL_ZERO:
                qty_display = get_display(
                    qty=box_purchase.quantity_ordered,
                    order_average_weight=offer_item.order_average_weight,
                    order_unit=offer_item.order_unit,
                    for_order_select=True,
                    without_price_display=True
                )
                option_dict = {
                    'id'  : "#box_offer_item%d" % offer_item.id,
                    'html': '<select name="box_offer_item%d" disabled class="form-control"><option value="0" selected>☑ %s %s</option></select>'
                            % (offer_item.id, qty_display, box_name)
                }
            else:
                option_dict = {
                    'id'  : "#box_offer_item%d" % offer_item.id,
                    'html': '<select name="box_offer_item%d" disabled class="form-control"><option value="0" selected>☑ --- %s</option></select>'
                            % (offer_item.id, box_name)
                }
        else:
            option_dict = {
                'id'  : "#box_offer_item%d" % offer_item.id,
                'html': '<select name="box_offer_item%d" disabled class="form-control"><option value="0" selected>☑ --- %s</option></select>'
                        % (offer_item.id, box_name)
            }
    else:
        option_dict = {
            'id'  : "#box_offer_item%d" % offer_item.id,
            'html': ''
        }
    return option_dict
907
908
909


@transaction.atomic
Patrick's avatar
Patrick committed
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
def update_or_create_purchase(customer=None, offer_item_id=None, value_id=None, basket=False, batch_job=False):
    to_json = []
    if offer_item_id is not None and value_id is not None and customer is not None:
        offer_item = models.OfferItem.objects.select_for_update(nowait=False) \
            .filter(id=offer_item_id, is_active=True) \
            .order_by('?').select_related("product", "producer").first()
        if offer_item is not None and offer_item.may_order:
            purchase = None
            permanence_id = offer_item.permanence_id
            updated = True
            if offer_item.is_box:
                # Select one purchase
                purchase = models.Purchase.objects.filter(
                    customer_id=customer.id,
                    offer_item_id=offer_item.id,
                    is_box_content=False
                ).only('quantity_ordered').order_by('?').first()
                if purchase is not None:
                    delta_value_id = value_id - purchase.quantity_ordered
                else:
                    delta_value_id = value_id
                with transaction.atomic():
                    sid = transaction.savepoint()
                    # This code executes inside a transaction.
                    for content in models.BoxContent.objects.filter(
                            box=offer_item.product_id
                    ).only(
                        "product_id","content_quantity"
                    ).order_by('?'):
                        # box_offer_item = models.OfferItem.objects.select_for_update(nowait=False)\
                        box_offer_item = models.OfferItem.objects \
                            .filter(product_id=content.product_id, permanence_id=offer_item.permanence_id) \
                            .order_by('?').select_related("producer").first()
                        if box_offer_item is not None:
                            # Select one purchase
                            purchase = models.Purchase.objects.filter(
                                customer_id=customer.id,
                                offer_item_id=box_offer_item.id,
                                is_box_content=True
                            ).only('quantity_ordered').order_by('?').first()
                            if purchase is not None:
                                quantity_ordered = purchase.quantity_ordered + delta_value_id * content.content_quantity
Patrick's avatar
Patrick committed
952
                            else:
Patrick's avatar
Patrick committed
953
954
955
956
957
958
                                quantity_ordered = delta_value_id * content.content_quantity
                            if quantity_ordered < DECIMAL_ZERO:
                                quantity_ordered = DECIMAL_ZERO
                            purchase, updated = create_or_update_one_purchase(
                                customer, box_offer_item, None, quantity_ordered, close_orders=batch_job, is_box_content=True
                            )
Patrick's avatar
Patrick committed
959
                        else:
Patrick's avatar
Patrick committed
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
                            updated = False
                        if not updated:
                            break
                    if updated:
                        for content in models.BoxContent.objects.filter(box=offer_item.product_id).only(
                                "product_id").order_by('?'):
                            box_offer_item = models.OfferItem.objects.filter(
                                product_id=content.product_id,
                                permanence_id=offer_item.permanence_id
                            ).order_by('?').first()
                            if box_offer_item is not None:
                                # Select one purchase
                                purchase = models.Purchase.objects.filter(
                                    customer_id=customer.id,
                                    offer_item_id=box_offer_item.id,
                                    is_box_content=False
                                ).only("quantity_ordered").order_by('?').first()
                                option_dict = display_selected_value(customer, box_offer_item,
                                                                     purchase.quantity_ordered if purchase is not None else DECIMAL_ZERO)
                                to_json.append(option_dict)

                            option_dict = display_selected_box_value(customer, box_offer_item)
                            to_json.append(option_dict)
                        transaction.savepoint_commit(sid)
                    else:
                        transaction.savepoint_rollback(sid)
            if not offer_item.is_box or updated:
                purchase, updated = create_or_update_one_purchase(customer, offer_item, value_id, None, close_orders=batch_job,
                                                                  is_box_content=False)
                if not batch_job and apps.REPANIER_SETTINGS_DISPLAY_PRODUCER_ON_ORDER_FORM:
                    producer_invoice = models.ProducerInvoice.objects.filter(
                        producer_id=offer_item.producer_id, permanence_id=offer_item.permanence_id
                    ).only("total_price_with_tax").order_by('?').first()
                    if producer_invoice is None:
                        ratio = 0
                    else:
                        if offer_item.producer.minimum_order_value.amount == DECIMAL_ZERO:
                            ratio = 100
Patrick's avatar
Patrick committed
998
                        else:
Patrick's avatar
Patrick committed
999
1000
1001
                            ratio = producer_invoice.total_price_with_tax.amount / offer_item.producer.minimum_order_value.amount
                        if ratio >= DECIMAL_ONE:
                            ratio = 100
Patrick's avatar
Patrick committed
1002
                        else:
Patrick's avatar
Patrick committed
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
                            ratio *= 100
                    option_dict = {'id'  : "#order_procent" + str(offer_item.producer_id),
                                   'html': "%s%%" % number_format(ratio, 0)}
                    to_json.append(option_dict)
            elif not batch_job:
                # Select one purchase
                purchase = models.Purchase.objects.filter(
                    customer_id=customer.id,
                    offer_item_id=offer_item.id,
                    is_box_content=False
                ).order_by('?').first()

            if not batch_job:
                if purchase is None:
                    if offer_item.is_box:
                        sold_out = _("Sold out")
                        option_dict = {
                            'id'  : "#offer_item%d" % offer_item.id,
                            'html': '<option value="0" selected>%s</option>' % sold_out
                        }
                    else:
                        option_dict = display_selected_value(customer, offer_item, DECIMAL_ZERO)
                    to_json.append(option_dict)
                else:
                    offer_item = models.OfferItem.objects.filter(id=offer_item_id).order_by('?').first()
                    if offer_item is not None:
                        option_dict = display_selected_value(customer, offer_item, purchase.quantity_ordered)
                        to_json.append(option_dict)
Patrick's avatar
Patrick committed
1031

Patrick's avatar
Patrick committed
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
                customer_invoice = models.CustomerInvoice.objects.filter(
                    permanence_id=permanence_id,
                    customer_id=customer.id
                ).order_by('?').first()
                permanence = models.Permanence.objects.filter(
                    id=permanence_id
                ).only("id", "with_delivery_point", "status").order_by('?').first()
                if customer_invoice is not None and permanence is not None:
                    order_amount = customer_invoice.get_total_price_with_tax()
                    customer_invoice.cancel_confirm_order()
                    customer_invoice.save()
                    my_basket(customer_invoice.is_order_confirm_send, order_amount, to_json)
                    if basket:
                        basket_message = calc_basket_message(customer, permanence, customer_invoice.status)
                    else:
                        basket_message = EMPTY_STRING
                    my_order_confirmation(
                        permanence=permanence,
                        customer_invoice=customer_invoice,
                        is_basket=basket,
                        basket_message=basket_message,
                        to_json=to_json
                    )
    return json.dumps(to_json, cls=DjangoJSONEncoder)


def my_basket(is_order_confirm_send, order_amount, to_json):
    if not is_order_confirm_send and apps.REPANIER_SETTINGS_CUSTOMERS_MUST_CONFIRM_ORDERS:
        msg_html = '<span class="glyphicon glyphicon-shopping-cart"></span> %s&nbsp;&nbsp;&nbsp;<span class="glyphicon glyphicon-exclamation-sign"></span>&nbsp;<span class="glyphicon glyphicon-floppy-remove"></span></a>' % (
        order_amount,)
    else:
        msg_html = '<span class="glyphicon glyphicon-shopping-cart"></span> %s&nbsp;&nbsp;&nbsp;<span class="glyphicon glyphicon-floppy-saved"></span></a>' % (
        order_amount,)
    option_dict = {'id': "#my_basket", 'html': msg_html}
    to_json.append(option_dict)
    option_dict = {'id': "#prepared_amount_visible_xs", 'html': msg_html}
    to_json.append(option_dict)


def my_order_confirmation(permanence, customer_invoice, is_basket=False,
                          basket_message=EMPTY_STRING, to_json=None):

    if permanence.with_delivery_point:
        if customer_invoice.delivery is not None:
            label = customer_invoice.delivery.get_delivery_customer_display()
            delivery_id = customer_invoice.delivery_id
1078
        else:
Patrick's avatar
Patrick committed
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
            delivery_id = -1
            if customer_invoice.customer.delivery_point is not None:
                qs = models.DeliveryBoard.objects.filter(
                    Q(
                        permanence_id=permanence.id,
                        delivery_point_id=customer_invoice.customer.delivery_point_id,
                        status=PERMANENCE_OPENED
                    ) | Q(
                        permanence_id=permanence.id,
                        delivery_point__closed_group=False,
                        status=PERMANENCE_OPENED
                    )
                ).order_by('?')
            else:
                qs = models.DeliveryBoard.objects.filter(
                    permanence_id=permanence.id,
                    delivery_point__closed_group=False,
                    status=PERMANENCE_OPENED
                ).order_by('?')
            if qs.exists():
                label = "%s" % _('Please, select a delivery point')
                models.CustomerInvoice.objects.filter(
                    permanence_id=permanence.id,
                    customer_id=customer_invoice.customer_id).order_by('?').update(
                    status=PERMANENCE_OPENED)
            else:
                label = "%s" % _('No delivery point is open for you. You can not place order.')
                # IMPORTANT :
                # 1 / This prohibit to place an order into the customer UI
                # 2 / task_order.close_send_order will delete any CLOSED orders without any delivery point
                models.CustomerInvoice.objects.filter(
                    permanence_id=permanence.id,
                    customer_id=customer_invoice.customer_id
                ).order_by('?').update(
                    status=PERMANENCE_CLOSED)
        if customer_invoice.customer_id != customer_invoice.customer_who_pays_id:
            msg_price = msg_transport = EMPTY_STRING
        else:
            if customer_invoice.transport.amount <= DECIMAL_ZERO:
                transport = False
                msg_transport = EMPTY_STRING
            else:
                transport = True
                if customer_invoice.min_transport.amount > DECIMAL_ZERO:
                    msg_transport = "%s<br/>" % \
                                    _(
                                        'The shipping costs for this delivery point amount to %(transport)s for orders of less than %(min_transport)s.') % {
                                        'transport'    : customer_invoice.transport,
                                        'min_transport': customer_invoice.min_transport
                                    }
                else:
                    msg_transport = "%s<br/>" % \
                                    _(
                                        'The shipping costs for this delivery point amount to %(transport)s.') % {
                                        'transport': customer_invoice.transport,
                                    }
            if customer_invoice.price_list_multiplier == DECIMAL_ONE:
                msg_price = EMPTY_STRING
            else:
                if transport:
                    if customer_invoice.price_list_multiplier > DECIMAL_ONE:
                        msg_price = "%s<br/>" % \
                                        _(
                                            'A price increase of %(increase)s %% of the total invoiced is due for this delivery point. This does not apply to the cost of transport which is fixed.') % {
                                            'increase'    : number_format((customer_invoice.price_list_multiplier - DECIMAL_ONE) * 100, 2)
                                        }
                    else:
                        msg_price = "%s<br/>" % \
                                        _(
                                            'A price decrease of %(decrease)s %% of the total invoiced is given for this delivery point. This does not apply to the cost of transport which is fixed.') % {
                                            'decrease': number_format((DECIMAL_ONE - customer_invoice.price_list_multiplier) * 100, 2)
                                        }
                else:
                    if customer_invoice.price_list_multiplier > DECIMAL_ONE:
                        msg_price = "%s<br/>" % \
                                        _(
                                            'A price increase of %(increase)s %% of the total invoiced is due for this delivery point.') % {
                                            'increase'    : number_format((customer_invoice.price_list_multiplier - DECIMAL_ONE) * 100, 2)
                                        }
                    else:
                        msg_price = "%s<br/>" % \
                                        _(
                                            'A price decrease of %(decrease)s %% of the total invoiced is given for this delivery point.') % {
                                            'decrease': number_format((DECIMAL_ONE - customer_invoice.price_list_multiplier) * 100, 2)
                                        }

        msg_delivery = '%s<b><i><select name="delivery" id="delivery" onmouseover="delivery_select_ajax()" onchange="delivery_ajax()" class="form-control"><option value="%d" selected>%s</option></select></i></b><br/>%s%s' % (
            _("Delivery point"),
            delivery_id,
            label,
            msg_transport,
            msg_price
        )
    else:
        msg_delivery = EMPTY_STRING
    if not is_basket and not apps.REPANIER_SETTINGS_CUSTOMERS_MUST_CONFIRM_ORDERS:
        # or customer_invoice.total_price_with_tax.amount != DECIMAL_ZERO:
        # If apps.REPANIER_SETTINGS_CUSTOMERS_MUST_CONFIRM_ORDERS is True,
        # then permanence.with_delivery_point is also True
        msg_confirmation = msg_html = EMPTY_STRING
    else:
        if customer_invoice.is_order_confirm_send:
            msg_confirmation = my_order_confirmation_email_send_to(customer_invoice.customer)
            msg_html = """
            <div class="row">
            <div class="panel panel-default">
            <div class="panel-heading">
            %s
            <button id="btn_confirm_order" class="btn" disabled>%s</button>
            <div class="clearfix"></div>
            %s
            </div>
            </div>
            </div>
             """ % (msg_delivery, msg_confirmation, basket_message)
        else:
            msg_html = None
            btn_disabled = EMPTY_STRING
            msg_confirmation = EMPTY_STRING
            if apps.REPANIER_SETTINGS_CUSTOMERS_MUST_CONFIRM_ORDERS:
                if is_basket:
                    if permanence.with_delivery_point and customer_invoice.delivery is None:
                        btn_disabled = "disabled"
                    msg_confirmation = '<span class="glyphicon glyphicon-floppy-disk"></span>&nbsp;&nbsp;%s' % _("Confirm this order and receive an email containing its summary.")
                else:
                    href = urlresolvers.reverse(
                        'basket_view', args=(permanence.id,)
                    )
                    msg_confirmation = _("Verify my order content before validating it.")
                    msg_html = """
                        <div class="row">
                        <div class="panel panel-default">
                        <div class="panel-heading">
                        %s
                        <a href="%s" class="btn btn-info" %s>%s</a>
                        </div>
                        </div>
                        </div>
                         """ % (msg_delivery, href, btn_disabled, msg_confirmation)
            else:
                if is_basket:
                    msg_confirmation = _("Receive an email containing this order summary.")
                elif permanence.with_delivery_point:
                    msg_html = """
                        <div class="row">
                        <div class="panel panel-default">
                        <div class="panel-heading">
                        %s
                        </div>
                        </div>
                        </div>
                         """ % msg_delivery
                else:
                    msg_html = EMPTY_STRING
            if msg_html is None:
                msg_html = """
                <div class="row">
                <div class="panel panel-default">
                <div class="panel-heading">
                %s
                <button id="btn_confirm_order" class="btn btn-info" %s onclick="btn_receive_order_email();">%s</button>
                <div class="clearfix"></div>
                %s
                </div>
                </div>
                </div>
                 """ % (msg_delivery, btn_disabled, msg_confirmation, basket_message)
    if to_json is not None:
        option_dict = {'id': "#span_btn_confirm_order", 'html': msg_html}
        to_json.append(option_dict)
    return msg_confirmation
Patrick's avatar
Patrick committed
1250
1251


Patrick's avatar
Patrick committed
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
def my_order_confirmation_email_send_to(customer):
    if customer is not None and customer.email2 is not None and len(customer.email2) > 0:
        to_email = (customer.user.email, customer.email2)
    else:
        to_email = (customer.user.email,)
    sent_to = ", ".join(to_email) if to_email is not None else EMPTY_STRING
    if apps.REPANIER_SETTINGS_CUSTOMERS_MUST_CONFIRM_ORDERS:
        msg_confirmation = _(
            "Your order is confirmed. An email containing this order summary has been sent to %s.") % sent_to
    else:
        msg_confirmation = _("An email containing this order summary has been sent to %s.") % sent_to
    return msg_confirmation


def create_or_update_one_purchase(customer, offer_item, value_id, value, close_orders, is_box_content):
    status = models.CustomerInvoice.objects.filter(
        permanence_id=offer_item.permanence_id, customer_id=customer.id) \
        .only("status") \
        .order_by('?').first().status
    # The close_orders flag is used because we need to forbid
    # customers to add purchases during the close_orders_async process
    # when the status is PERMANENCE_WAIT_FOR_SEND
    if (status == PERMANENCE_OPENED) or close_orders:
        # The offer_item belong to an open permanence
        # Select one purchase
        purchase = models.Purchase.objects.filter(
            customer_id=customer.id,
            offer_item_id=offer_item.id,
            is_box_content=is_box_content
        ).order_by('?').first()
        if purchase is not None:
            q_previous_order = purchase.quantity_ordered
        else:
            q_previous_order = DECIMAL_ZERO
        if value is not None:
            q_order = value if value > 0 else DECIMAL_ZERO
        else:
            q_min = offer_item.customer_minimum_order_quantity
            q_step = offer_item.customer_increment_order_quantity
            if value_id <= 0:
                q_order = DECIMAL_ZERO
            elif value_id == 1:
                q_order = q_min
            else:
                if q_min < q_step:
                    # 1; 2; 4; 6; 8 ... q_min = 1; q_step = 2
                    # 0,5; 1; 2; 3 ... q_min = 0,5; q_step = 1
                    if value_id == 2:
                        q_order = q_step
                    else:
                        q_order = q_step * (value_id - 1)
                else:
                    # 1; 2; 3; 4 ... q_min = 1; q_step = 1
                    # 0,125; 0,175; 0,225 ... q_min = 0,125; q_step = 0,50
                    q_order = q_min + q_step * (value_id - 1)
        if status == PERMANENCE_OPENED and offer_item.limit_order_quantity_to_stock:
            q_alert = offer_item.stock - offer_item.quantity_invoiced + q_previous_order
            if is_box_content and q_alert < q_order:
                # Select one purchase
                non_box_purchase = models.Purchase.objects.filter(
                    customer_id=customer.id,
                    offer_item_id=offer_item.id,
                    is_box_content=False
                ).order_by('?').first()
                if non_box_purchase is not None:
                    tbd_qty = min(q_order - q_alert, non_box_purchase.quantity_ordered)
                    tbk_qty = non_box_purchase.quantity_ordered - tbd_qty
                    non_box_purchase.quantity_ordered = tbk_qty
                    non_box_purchase.save()
                    q_alert += tbd_qty
        else:
            if is_box_content:
                q_alert = q_order
            else:
                q_alert = offer_item.customer_alert_order_quantity
        if q_order <= q_alert:
            if purchase is not None:
                if close_orders and value_id == DECIMAL_ZERO:
                    purchase.comment = _("Cancelled qty : %s") % number_format(purchase.quantity_ordered, 4)
                purchase.quantity_ordered = q_order
                purchase.save()
            else:
                permanence = models.Permanence.objects.filter(id=offer_item.permanence_id) \
                    .only("permanence_date") \
                    .order_by('?').first()
                purchase = models.Purchase.objects.create(
                    permanence_id=offer_item.permanence_id,
                    permanence_date=permanence.permanence_date,
                    offer_item_id=offer_item.id,
                    producer_id=offer_item.producer_id,
                    customer_id=customer.id,
                    quantity_ordered=q_order,
                    quantity_invoiced=DECIMAL_ZERO,
                    is_box_content=is_box_content,
                    status=status
                )
            return purchase, True
        else:
            return purchase, False


def clean_offer_item(permanence, queryset, reset_add_2_stock=False):
    if permanence.status > PERMANENCE_SEND:
        # The purchases are already invoiced.
        # The offer item may not be modified any more
        return
    getcontext().rounding = ROUND_HALF_UP
1359
    for offer_item in queryset.select_related("product", "producer"):
Patrick's avatar
Patrick committed
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
        product = offer_item.product
        producer = offer_item.producer
        if product.order_unit < PRODUCT_ORDER_UNIT_DEPOSIT:
            offer_item.is_active = product.is_into_offer
        offer_item.picture2 = product.picture2
        offer_item.reference = product.reference
        offer_item.department_for_customer_id = product.department_for_customer_id
        offer_item.producer_id = product.producer_id
        offer_item.order_unit = product.order_unit
        offer_item.wrapped = product.wrapped
        offer_item.order_average_weight = product.order_average_weight
        offer_item.placement = product.placement
        offer_item.producer_vat = product.producer_vat
        offer_item.customer_vat = product.customer_vat
        # Important : the group must pay the VAT, so it's easier to allways have
        # offer_item with VAT included
        if producer.producer_price_are_wo_vat:
            offer_item.producer_unit_price = product.producer_unit_price + offer_item.producer_vat
            offer_item.producer_price_are_wo_vat = False
        else:
            offer_item.producer_unit_price = product.producer_unit_price
            offer_item.producer_price_are_wo_vat = producer.producer_price_are_wo_vat
        offer_item.customer_unit_price = product.customer_unit_price
        # Important : for purchasing : the price is * by order_average_weight
        # Thus, the unit deposit must be Zero.
        offer_item.unit_deposit = DECIMAL_ZERO if product.order_unit == PRODUCT_ORDER_UNIT_PC_KG else product.unit_deposit
        offer_item.vat_level = product.vat_level
        offer_item.limit_order_quantity_to_stock = product.limit_order_quantity_to_stock
        offer_item.producer_pre_opening = producer.producer_pre_opening
        if offer_item.order_unit < PRODUCT_ORDER_UNIT_DEPOSIT:
            offer_item.manage_replenishment = producer.manage_replenishment
        else:
            offer_item.manage_replenishment = False
        offer_item.manage_production = producer.manage_production
        # Important : or product.is_box -> impact into Purchase.get_customer_unit_price
        # The boxes prices are not subjects to price modifications
        offer_item.is_resale_price_fixed = producer.is_resale_price_fixed or product.is_box
        offer_item.price_list_multiplier = DECIMAL_ONE if offer_item.is_resale_price_fixed else producer.price_list_multiplier
        offer_item.stock = product.stock
        if reset_add_2_stock:
Patrick's avatar
Patrick committed
1400
            offer_item.add_2_stock = DECIMAL_ZERO
Patrick's avatar
Patrick committed
1401
1402
1403
1404
1405
1406
        offer_item.customer_minimum_order_quantity = product.customer_minimum_order_quantity
        offer_item.customer_increment_order_quantity = product.customer_increment_order_quantity
        offer_item.customer_alert_order_quantity = product.customer_alert_order_quantity
        offer_item.producer_order_by_quantity = product.producer_order_by_quantity
        offer_item.is_box = product.is_box
        offer_item.is_membership_fee = product.is_membership_fee
Patrick's avatar
Patrick committed
1407
1408
1409
        offer_item.save()

    # Now got everything to calculate the sort order of the order display screen
Patrick's avatar
Patrick committed
1410
    cur_language = translation.get_language()
Patrick's avatar
Patrick committed
1411
1412
    for language in settings.PARLER_LANGUAGES[settings.SITE_ID]:
        translation.activate(language["code"])
1413
        for offer_item in queryset.select_related("product", "producer", "department_for_customer"):
Patrick's avatar
Patrick committed
1414
            offer_item.long_name = offer_item.product.long_name
Patrick Colmant's avatar
Patrick Colmant committed
1415
1416
1417
1418
1419
1420
            offer_item.cache_part_a = render_to_string('repanier/cache_part_a.html',
                                                       {'offer': offer_item, 'MEDIA_URL': settings.MEDIA_URL})
            offer_item.cache_part_b = render_to_string('repanier/cache_part_b.html',
                                                       {'offer': offer_item, 'MEDIA_URL': settings.MEDIA_URL})
            offer_item.cache_part_e = render_to_string('repanier/cache_part_e.html',
                                                       {'offer': offer_item, 'MEDIA_URL': settings.MEDIA_URL})
Patrick's avatar
Patrick committed
1421
1422
1423
            offer_item.save_translations()

        departementforcustomer_set = models.LUT_DepartmentForCustomer.objects.filter(
Patrick's avatar
Patrick committed
1424
1425
1426
            offeritem__permanence_id=permanence.id,
            offeritem__order_unit__lt=PRODUCT_ORDER_UNIT_DEPOSIT) \
            .order_by("tree_id", "lft") \
Patrick's avatar
Patrick committed
1427
1428
1429
            .distinct("id", "tree_id", "lft")
        if departementforcustomer_set:
            pass
1430
        if apps.REPANIER_SETTINGS_DISPLAY_PRODUCER_ON_ORDER_FORM:
Patrick's avatar
Patrick committed
1431
1432
1433
1434
            producer_set = models.Producer.objects.filter(permanence=permanence.id).only("id", "short_profile_name")
        else:
            producer_set = None
        permanence.cache_part_d = render_to_string('repanier/cache_part_d.html',
Patrick's avatar
Patrick committed
1435
1436
                                                   {'producer_set'              : producer_set,
                                                    'departementforcustomer_set': departementforcustomer_set})
Patrick's avatar
Patrick committed
1437
1438
        permanence.save_translations()
    translation.activate(cur_language)
Patrick's avatar
Patrick committed
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774


def reorder_offer_items(permanence_id):
    # calculate the sort order of the order display screen
    cur_language = translation.get_language()
    offer_item_qs = models.OfferItem.objects.filter(permanence_id=permanence_id).order_by('?')
    for language in settings.PARLER_LANGUAGES[settings.SITE_ID]:
        language_code = language["code"]
        translation.activate(language_code)
        # customer order lists sort order
        i = 0
        reorder_queryset = offer_item_qs.filter(
            is_box=False,
            translations__language_code=language_code
        ).order_by(
            "department_for_customer__tree_id",
            "department_for_customer__lft",
            "translations__long_name",
            "order_average_weight",
            "producer__short_profile_name"
        )
        for offer_item in reorder_queryset:
            offer_item.producer_sort_order = offer_item.order_sort_order = i
            offer_item.save_translations()
            if i < 9999:
                i += 1
        # producer lists sort order : sort by reference if needed, otherwise sort by order_sort_order
        i = 9999
        reorder_queryset = offer_item_qs.filter(
            is_box=False,
            producer__sort_products_by_reference=True,
            translations__language_code=language_code
        ).order_by(
            "department_for_customer__tree_id",
            "department_for_customer__lft",
            "reference"
        )
        for offer_item in reorder_queryset:
            offer_item.producer_sort_order = i
            offer_item.save_translations()
            if i < 19999:
                i += 1
        # preparation lists sort order
        i = 0
        reorder_queryset = offer_item_qs.filter(
            is_box=False,
            translations__language_code=language_code
        ).order_by(
            "department_for_customer__tree_id",
            # "department_for_customer__lft",
            "translations__long_name",
            "order_average_weight",
            "producer__short_profile_name"
        )
        for offer_item in reorder_queryset:
            offer_item.preparation_sort_order = i
            offer_item.save_translations()
            if i < 9999:
                i += 1
        i = -9999
        reorder_queryset = offer_item_qs.filter(
            is_box=True,
            translations__language_code=language_code
        ).order_by(
            "customer_unit_price",
            "department_for_customer__lft",
            "unit_deposit",
            "translations__long_name"
        )
        # 'TranslatableQuerySet' object has no attribute 'desc'
        for offer_item in reorder_queryset:
            # display box on top
            offer_item.order_sort_order = i
            offer_item.producer_sort_order = i
            offer_item.preparation_sort_order = i
            offer_item.save_translations()
            if i < -1:
                i += 1
    translation.activate(cur_language)


def update_offer_item(product_id=None, producer_id=None):
    # Important : If the user want to modify the price of a product PERMANENCE_SEND
    # Then he can do it via "rule_of_3_per_product"
    for permanence in models.Permanence.objects.filter(
            status__in=[PERMANENCE_PRE_OPEN, PERMANENCE_OPENED, PERMANENCE_CLOSED]
    ):
        if producer_id is None:
            offer_item_qs = models.OfferItem.objects.filter(
                permanence_id=permanence.id,
                product_id=product_id,
            ).order_by('?')
        else:
            offer_item_qs = models.OfferItem.objects.filter(
                permanence_id=permanence.id,
                producer_id=producer_id,
            ).order_by('?')
        clean_offer_item(permanence, offer_item_qs)
        recalculate_order_amount(
            permanence_id=permanence.id,
            offer_item_queryset=offer_item_qs,
            all_producers=True,
            send_to_producer=False
        )
    cache.clear()


def get_or_create_offer_item(permanence, product_id, producer_id=None):
    offer_item_qs = models.OfferItem.objects.filter(
        permanence_id=permanence.id,
        product_id=product_id,
    ).order_by('?')
    if not offer_item_qs.exists():
        if producer_id is None:
            producer_id = models.Product.objects.filter(id=product_id).only("producer_id").order_by(
                '?').first().producer_id
        models.OfferItem.objects.create(
            permanence_id=permanence.id,
            product_id=product_id,
            producer_id=producer_id,
            is_active=False,
            may_order=False
        )
        clean_offer_item(permanence, offer_item_qs)
    offer_item = offer_item_qs.first()
    return offer_item


def producer_web_services_activated(reference_site=None):
    web_services_activated = False
    web_service_version = None
    if reference_site is not None and len(reference_site) > 0:
        try:
            web_services = urllib2.urlopen(
                '%s%s' % (reference_site, urlresolvers.reverse('version_rest')),
                timeout=0.5
            )
            version_rest = json.load(web_services)
            if version_rest['version'] == '1':
                web_services_activated = True
                web_service_version = 1
        except:
            pass
    return web_services_activated, "Repanier", web_service_version


def add_months(sourcedate, months):
    # months must be an integer
    months = int(months)
    month = sourcedate.month - 1 + months
    year = int(sourcedate.year + month / 12)
    month = month % 12 + 1
    day = min(sourcedate.day, calendar.monthrange(year, month)[1])
    return datetime.date(year, month, day)


def calc_basket_message(customer, permanence, status):
    if apps.REPANIER_SETTINGS_CUSTOMERS_MUST_CONFIRM_ORDERS:
        customer_invoice = models.CustomerInvoice.objects.filter(
            customer_id=customer.id, permanence_id=permanence.id
        ).only("is_order_confirm_send").order_by('?').first()
        if not customer_invoice.is_order_confirm_send:
            return EMPTY_STRING
        else:
            invoice_msg = EMPTY_STRING
            customer_last_balance, customer_on_hold_movement, customer_payment_needed, customer_order_amount = payment_message(
                customer, permanence)
            if apps.REPANIER_SETTINGS_INVOICE:
                invoice_msg = "<br/>%s %s" % (
                    customer_last_balance,
                    customer_on_hold_movement,
                )
            basket_message = "%s%s%s" % (
                customer_order_amount,
                invoice_msg,
                customer_payment_needed
            )
            return basket_message
    else:
        if status == PERMANENCE_OPENED:
            if permanence.with_delivery_point:
                you_can_change = "<br/>%s" % (
                    _("You can change the order quantities as long as the orders are open for your delivery point."),
                )
            else:
                you_can_change = "<br/>%s" % (
                    _("You can change the order quantities as long as the orders are open."),
                )
        else:
            if permanence.with_delivery_point:
                you_can_change = "<br/>%s" % (
                    _('The orders are closed for your delivery point.'),
                )
            else:
                you_can_change = "<br/>%s" % (
                    _('The orders are closed.'),
                )
        invoice_msg = EMPTY_STRING
        payment_msg = EMPTY_STRING
        customer_last_balance, customer_on_hold_movement, customer_payment_needed, customer_order_amount = payment_message(
            customer, permanence)
        if apps.REPANIER_SETTINGS_INVOICE:
            if customer_last_balance:
                invoice_msg = "<br/>%s %s" % (
                    customer_last_balance,
                    customer_on_hold_movement,
                )
        if apps.REPANIER_SETTINGS_BANK_ACCOUNT is not None:
            payment_msg = "<br/>%s" % (
                customer_payment_needed,
            )
        basket_message = "%s%s%s%s" % (
            customer_order_amount,
            invoice_msg,
            payment_msg,
            you_can_change
        )
        return basket_message


def recalculate_prices(product, producer_price_are_wo_vat, is_resale_price_fixed, price_list_multiplier):
    getcontext().rounding = ROUND_HALF_UP
    vat = DICT_VAT[product.vat_level]
    vat_rate = vat[DICT_VAT_RATE]
    if producer_price_are_wo_vat:
        product.producer_vat.amount = (product.producer_unit_price.amount * vat_rate).quantize(FOUR_DECIMALS)
        if not is_resale_price_fixed:
            if product.order_unit < PRODUCT_ORDER_UNIT_DEPOSIT:
                product.customer_unit_price.amount = (
                    product.producer_unit_price.amount * price_list_multiplier).quantize(
                    TWO_DECIMALS)
            else:
                product.customer_unit_price = product.producer_unit_price
        product.customer_vat.amount = (product.customer_unit_price.amount * vat_rate).quantize(FOUR_DECIMALS)
        if not is_resale_price_fixed:
            product.customer_unit_price += product.customer_vat
    else:
        product.producer_vat.amount = product.producer_unit_price.amount - (
            product.producer_unit_price.amount / (DECIMAL_ONE + vat_rate)).quantize(
            FOUR_DECIMALS)
        if not is_resale_price_fixed:
            if product.order_unit < PRODUCT_ORDER_UNIT_DEPOSIT:
                product.customer_unit_price.amount = (
                    product.producer_unit_price.amount * price_list_multiplier).quantize(
                    TWO_DECIMALS)
            else:
                product.customer_unit_price = product.producer_unit_price

        product.customer_vat.amount = product.customer_unit_price.amount - (
            product.customer_unit_price.amount / (DECIMAL_ONE + vat_rate)).quantize(
            FOUR_DECIMALS)


def html_box_content(offer_item, user, result=EMPTY_STRING):
    if offer_item.is_box:
        box_id = offer_item.product_id
        if result is not None and result != EMPTY_STRING:
            result += '<hr/>'
        product_ids = models.BoxContent.objects.filter(
            box_id=box_id
        ).only("product_id")