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

from django.http import HttpResponse
from django.utils import translation
from django.utils.text import slugify
from django.utils.translation import ugettext_lazy as _
from openpyxl.style import Fill
from openpyxl.styles import Color
from parler.models import TranslationDoesNotExist

import repanier.apps
from export_tools import *
from repanier.const import *
from repanier.models import Customer, OfferItem, CustomerInvoice, ProducerInvoice, \
    DeliveryBoard, Purchase, Configuration
from repanier.models import Permanence
from repanier.models import PermanenceBoard
from repanier.models import Producer
from repanier.models import Staff
from repanier.tools import get_base_unit, next_row
from xlsx_stock import export_permanence_stock


def next_purchase(purchases):
    purchase = next_row(purchases)
    return purchase


def export_abstract(permanence, deliveries_id=None, wb=None):
    if permanence is not None:
        row_num = 1
        # Customer info
34 35
        Customer.objects.all().update(preparation_order=0)
        preparation_order = 1
Patrick's avatar
Patrick committed
36
        if deliveries_id is not None:
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
            header = [
                (_('delivery point'),20),
                (_('Family'), 35),
                (_('Phone1'), 15),
                (_('Phone2'), 15),
                (_('Total vat'), 15),
                (_('email'), 35),
            ]
            wb, ws = new_portrait_a4_sheet(wb, permanence, EMPTY_STRING, header=header, add_print_title=False)
            for delivery_ref, delivery in enumerate(DeliveryBoard.objects.filter(id__in=deliveries_id).order_by("id")):
                customer_set = Customer.objects.filter(
                    customerinvoice__permanence_id=permanence.id,
                    represent_this_buyinggroup=False,
                    customerinvoice__delivery_id=delivery.id
                )
                for customer in customer_set:
                    invoice = CustomerInvoice.objects.filter(
                        permanence=permanence, customer=customer
                    ).order_by('?').first()
                    if invoice is not None and invoice.total_price_with_tax.amount != DECIMAL_ZERO:
                        customer.preparation_order = preparation_order
                        customer.save(update_fields=['preparation_order'])
                        preparation_order += 1
Patrick's avatar
Patrick committed
60

61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
                        row = [
                            "%d - %s" % (delivery_ref, delivery.get_delivery_display()),
                            "  %d - %s" % (customer.preparation_order, customer.long_basket_name),
                            customer.phone1,
                            customer.phone2,
                            invoice.total_price_with_tax.amount,
                            # Used to send mail to customer with an order (via copy-paste to mail)
                            ";".join(
                                [customer.user.email, customer.email2, EMPTY_STRING]
                            ) if customer.email2 else ";".join(
                                [customer.user.email, customer.email2]
                            )
                        ]
                        for col_num in range(len(row)):
                            c = ws.cell(row=row_num, column=col_num)
                            c.value = row[col_num]
                            if col_num == 4:
                                c.style.number_format.format_code = repanier.apps.REPANIER_SETTINGS_CURRENCY_XLSX
                            else:
                                c.style.number_format.format_code = NumberFormat.FORMAT_TEXT
                                c.style.alignment.wrap_text = False
                            if row_num % 2 == 0:
                                c.style.borders.bottom.border_style = Border.BORDER_THIN
                        row_num += 1
        else:
            header = [
                (_("Basket"), 20),
                (_('Family'), 35),
                (_('Phone1'), 15),
                (_('Phone2'), 15),
                (_('Total vat'), 15),
                (_('email'), 35),
Patrick's avatar
Patrick committed
93
            ]
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
            wb, ws = new_portrait_a4_sheet(wb, permanence, EMPTY_STRING, header=header, add_print_title=False)
            customer_set = Customer.objects.filter(
                customerinvoice__permanence_id=permanence.id,
                represent_this_buyinggroup=False
            )
            for customer in customer_set:
                invoice = CustomerInvoice.objects.filter(
                    permanence=permanence, customer=customer
                ).order_by('?').first()
                if invoice is not None and invoice.total_price_with_tax.amount != DECIMAL_ZERO:
                    customer.preparation_order = preparation_order
                    customer.save(update_fields=['preparation_order'])
                    preparation_order += 1

                    row = [
                        "%d - %s" % (customer.preparation_order, customer.short_basket_name),
                        customer.long_basket_name,
                        customer.phone1,
                        customer.phone2,
                        invoice.total_price_with_tax.amount,
                        # Used to send mail to customer with an order (via copy-paste to mail)
                        ";".join(
                            [customer.user.email, customer.email2, EMPTY_STRING]
                        ) if customer.email2 else ";".join(
                            [customer.user.email, customer.email2]
                        )
                    ]
                    for col_num in range(len(row)):
                        c = ws.cell(row=row_num, column=col_num)
                        c.value = row[col_num]
                        if col_num == 4:
                            c.style.number_format.format_code = repanier.apps.REPANIER_SETTINGS_CURRENCY_XLSX
                        else:
                            c.style.number_format.format_code = NumberFormat.FORMAT_TEXT
                            c.style.alignment.wrap_text = False
                        if row_num % 2 == 0:
                            c.style.borders.bottom.border_style = Border.BORDER_THIN
                    row_num += 1

        for col_num in range(5):
            c = ws.cell(row=row_num-1, column=col_num)
            c.style.borders.bottom.border_style = Border.BORDER_THIN

Patrick's avatar
Patrick committed
137
        c = ws.cell(row=row_num, column=0)
138
        c.value = "-------"
Patrick's avatar
Patrick committed
139 140 141 142 143
        c = ws.cell(row=row_num, column=1)
        c.value = "%s" % (_('Permanence Board Member List'))
        c.style.alignment.wrap_text = False
        c.style.font.bold = True
        c = ws.cell(row=row_num, column=2)
144
        c.value = "-------"
Patrick's avatar
Patrick committed
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
        row_num += 1
        # Permanence board info
        permanence_date_save = None
        next_permanence_set = Permanence.objects.filter(permanence_date__gte=permanence.permanence_date).order_by(
            "permanence_date")[:5]
        for next_permanence in next_permanence_set:
            for permanenceboard in PermanenceBoard.objects.filter(
                    permanence_id=next_permanence.id).order_by(
                "permanence_role__tree_id",
                "permanence_role__lft"
            ):
                c = permanenceboard.customer
                if c is not None:
                    row = [
                        (next_permanence.permanence_date, NumberFormat.FORMAT_DATE_DMYSLASH,),
                        (c.long_basket_name, NumberFormat.FORMAT_TEXT,),
                        (c.phone1, NumberFormat.FORMAT_TEXT,),
                        (c.phone2, NumberFormat.FORMAT_TEXT,),
                        (permanenceboard.permanence_role.short_name, NumberFormat.FORMAT_TEXT),
                    ]
                    for col_num in range(len(row)):
                        c = ws.cell(row=row_num, column=col_num)
                        c.value = "%s" % (row[col_num][0])
                        c.style.number_format.format_code = row[col_num][1]
                        c.style.alignment.wrap_text = False
                        if permanence_date_save != next_permanence.permanence_date:
                            c.style.font.bold = True
                            permanence_date_save = next_permanence.permanence_date
                    row_num += 1
174 175 176 177
            for col_num in range(5):
                c = ws.cell(row=row_num, column=col_num)
                c.style.borders.bottom.border_style = Border.BORDER_THIN
            row_num += 1
Patrick's avatar
Patrick committed
178
        c = ws.cell(row=row_num, column=0)
179
        c.value = "-------"
Patrick's avatar
Patrick committed
180 181 182 183 184
        c = ws.cell(row=row_num, column=1)
        c.value = "%s" % (_('Staff Member List'))
        c.style.alignment.wrap_text = False
        c.style.font.bold = True
        c = ws.cell(row=row_num, column=2)
185
        c.value = "-------"
Patrick's avatar
Patrick committed
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
        row_num += 1
        for staff in Staff.objects.filter(is_active=True).order_by('?'):
            c = staff.customer_responsible
            if c is not None:
                try:
                    staff_long_name = staff.long_name
                except TranslationDoesNotExist:
                    staff_long_name = EMPTY_STRING
                row = [
                    staff_long_name,
                    c.long_basket_name,
                    c.phone1,
                    c.phone2
                ]
                for col_num in range(len(row)):
                    c = ws.cell(row=row_num, column=col_num)
                    c.value = row[col_num]
                    c.style.number_format.format_code = NumberFormat.FORMAT_TEXT
                    c.style.alignment.wrap_text = True
                row_num += 1

207 208 209 210
        for col_num in range(5):
            c = ws.cell(row=row_num-1, column=col_num)
            c.style.borders.bottom.border_style = Border.BORDER_THIN

Patrick's avatar
Patrick committed
211
        c = ws.cell(row=row_num, column=0)
212
        c.value = "-------"
Patrick's avatar
Patrick committed
213 214 215 216 217
        c = ws.cell(row=row_num, column=1)
        c.value = "%s" % (_('producers'))
        c.style.alignment.wrap_text = False
        c.style.font.bold = True
        c = ws.cell(row=row_num, column=2)
218
        c.value = "-------"
Patrick's avatar
Patrick committed
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
        row_num += 1
        # Producer info
        for producer in Producer.objects.filter(permanence=permanence).order_by("short_profile_name"):
            invoice = ProducerInvoice.objects.filter(
                permanence=permanence, producer=producer
            ).order_by('?').first()
            if invoice is None:
                total_price_with_tax = REPANIER_MONEY_ZERO
            else:
                total_price_with_tax = invoice.total_price_with_tax
            row = [
                producer.short_profile_name,
                producer.long_profile_name,
                producer.phone1,
                producer.phone2,
                total_price_with_tax.amount,
            ]
            for col_num in range(len(row)):
                c = ws.cell(row=row_num, column=col_num)
                c.value = row[col_num]
                if col_num == 4:
                    c.style.number_format.format_code = repanier.apps.REPANIER_SETTINGS_CURRENCY_XLSX
                else:
                    c.style.number_format.format_code = NumberFormat.FORMAT_TEXT
                    c.style.alignment.wrap_text = False
            row_num += 1
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
        # if deliveries_id is not None:
        #     c = ws.cell(row=row_num, column=0)
        #     c.value = "-------"
        #     c = ws.cell(row=row_num, column=1)
        #     c.value = "%s" % (_('Delivery Point List'))
        #     c.style.alignment.wrap_text = False
        #     c.style.font.bold = True
        #     c = ws.cell(row=row_num, column=2)
        #     c.value = "-------"
        #     row_num += 1
        #     for delivery_ref, delivery in enumerate(DeliveryBoard.objects.filter(id__in=deliveries_id).order_by("id")):
        #         c = ws.cell(row=row_num, column=0)
        #         c.value = delivery_ref
        #         c.style.number_format.format_code = NumberFormat.FORMAT_TEXT
        #         c = ws.cell(row=row_num, column=1)
        #         c.value = delivery.get_delivery_display()
        #         row_num += 1
Patrick's avatar
Patrick committed
262 263 264 265 266 267 268 269 270 271 272

        return wb

    return None


def export_customer_label(permanence, deliveries_id=None, wb=None):
    # Customer label
    wb, ws = new_portrait_a4_sheet(wb, _('Label'), permanence, add_print_title=False)
    row_num = 0
    customer_set = Customer.objects.filter(
273 274 275 276 277 278
        customerinvoice__permanence_id=permanence.id,
        represent_this_buyinggroup=False,
        preparation_order__gt=0
    ).order_by(
        'preparation_order'
    )
Patrick's avatar
Patrick committed
279 280 281 282

    if deliveries_id is not None:
        customer_set = customer_set.filter(customerinvoice__delivery_id__in=deliveries_id)

283
    for customer in customer_set:
Patrick's avatar
Patrick committed
284
        c = ws.cell(row=row_num, column=0)
285
        c.value = "%d - %s" % (customer.preparation_order, customer.short_basket_name)
Patrick's avatar
Patrick committed
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
        c.style.font.size = 36
        c.style.alignment.wrap_text = False
        c.style.borders.top.border_style = Border.BORDER_THIN
        c.style.borders.bottom.border_style = Border.BORDER_THIN
        c.style.borders.left.border_style = Border.BORDER_THIN
        c.style.borders.right.border_style = Border.BORDER_THIN
        c.style.alignment.vertical = 'center'
        c.style.alignment.horizontal = 'center'
        row_num += 1
        ws.row_dimensions[row_num].height = 60
        # vvvv c = ... is nedeed for row_dimensions
        c = ws.cell(row=row_num, column=0)
        row_num += 1
        ws.row_dimensions[row_num].height = 5
        # ^^^^ c = ... is nedeed for row_dimensions
    if row_num > 0:
        ws.column_dimensions[get_column_letter(1)].width = 120
        return wb

    return None


def export_preparation(permanence, deliveries_id=None, wb=None):
    yellowFill = Fill()
    yellowFill.start_color.index = 'FFEEEE11'
    yellowFill.end_color.index = 'FFEEEE11'
    yellowFill.fill_type = Fill.FILL_SOLID

    header = [
        (_("Id"), 10),
        (_("OfferItem"), 5),
        (_("Placement"), 7),
        (_("producer"), 15),
        (_("department_for_customer"), 7),
        (_("product"), 60),
        (_("customer"), 15),
        (_("quantity ordered"), 10),
        (_("Unit"), 10),
        (_("Prepared"), 22),
        (_("To distribute"), 10),
    ]
    if deliveries_id is None:
        return export_preparation_for_a_delivery(0, None, header, permanence, wb, yellowFill)
    else:
330 331
        for delivery_ref, delivery_id in enumerate(deliveries_id):
            wb = export_preparation_for_a_delivery(delivery_ref, delivery_id, header, permanence, wb, yellowFill)
Patrick's avatar
Patrick committed
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
        return wb


def export_preparation_for_a_delivery(delivery_cpt, delivery_id, header, permanence, wb, yellowFill):
    producer_set = Producer.objects.filter(
        producerinvoice__permanence_id=permanence.id
    ).only('invoice_by_basket', 'short_profile_name')
    if delivery_id is not None:
        producer_set = producer_set.filter(purchase__customer_invoice__delivery_id=delivery_id)
    producers = producer_set.distinct().iterator()
    producer = next_row(producers)
    if producer is not None:
        wb, ws = new_landscape_a4_sheet(
            wb,
            _("Preparation") if delivery_id is None else "%d-%s" % (delivery_cpt, _("Preparation")),
            permanence,
            header
        )
        row_num = 1
351 352 353 354 355
        if delivery_id is not None:
            c = ws.cell(row=row_num, column=5)
            c.style.font.bold = True
            c.value = DeliveryBoard.objects.filter(id=delivery_id).order_by('?').first().get_delivery_display()
            row_num += 1
356
        producer_counter = 0
357
        hide_column_placement = True
358
        placement_save = None
Patrick's avatar
Patrick committed
359
        while producer is not None:
360
            producer_counter += 1
Patrick's avatar
Patrick committed
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 399 400 401 402 403 404 405 406 407 408
            producer_save = producer
            at_least_one_product = False
            ######################################################################################################################
            if producer.invoice_by_basket and not producer.manage_production:
                # If the producer manage the production, he need to go into his field to pick up products.
                # In this cas, the preparation list must not be done by basket.
                # But the invoice must be done by basket.
                purchase_set = Purchase.objects.filter(
                    permanence_id=permanence.id,
                    producer_id=producer.id,
                    offer_item__translations__language_code=translation.get_language()
                ).order_by(
                    "customer__short_basket_name",
                    "offer_item__translations__preparation_sort_order"
                ).select_related('customer', 'offer_item', 'offer_item__department_for_customer')
                if delivery_id is not None:
                    purchase_set = purchase_set.filter(customer_invoice__delivery_id=delivery_id)
                purchases = purchase_set.iterator()
                purchase = next_purchase(purchases)
                while purchase is not None:
                    at_least_one_product = True
                    customer_save = purchase.customer
                    c = ws.cell(row=row_num, column=6)
                    c.style.font.bold = True
                    row_num += 1
                    count_purchase = 0
                    purchases_price = DECIMAL_ZERO
                    purchases_price_formula = []
                    while purchase is not None and customer_save.id == purchase.customer_id:
                        department_for_customer_save = purchase.offer_item.department_for_customer
                        department_for_customer_save__short_name = department_for_customer_save.short_name \
                            if department_for_customer_save is not None else EMPTY_STRING
                        while purchase is not None and customer_save.id == purchase.customer_id \
                                and department_for_customer_save == purchase.offer_item.department_for_customer:
                            qty = purchase.get_quantity()
                            if qty != DECIMAL_ZERO:
                                base_unit = get_base_unit(
                                    qty,
                                    purchase.offer_item.order_unit,
                                    purchase.status
                                )
                                c = ws.cell(row=row_num, column=0)
                                c.value = purchase.id
                                c = ws.cell(row=row_num, column=1)
                                c.value = purchase.offer_item_id
                                c.style.number_format.format_code = NumberFormat.FORMAT_DATE_DDMMYYYY
                                c = ws.cell(row=row_num, column=2)
                                c.value = purchase.offer_item.get_placement_display()
409 410
                                if placement_save is None:
                                    placement_save = c.value
411
                                elif hide_column_placement:
412
                                    if placement_save != c.value:
413
                                        hide_column_placement = False
Patrick's avatar
Patrick committed
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
                                c = ws.cell(row=row_num, column=3)
                                c.value = producer_save.short_profile_name
                                c = ws.cell(row=row_num, column=4)
                                c.value = department_for_customer_save__short_name
                                c.style.font.italic = True
                                c.style.alignment.horizontal = 'right'
                                c.style.number_format.format_code = NumberFormat.FORMAT_TEXT
                                c = ws.cell(row=row_num, column=5)
                                if department_for_customer_save__short_name is not None:
                                    c.value = "%s - %s" % (
                                        purchase.get_long_name(), department_for_customer_save__short_name)
                                else:
                                    c.value = "%s" % purchase.get_long_name()
                                c.style.number_format.format_code = NumberFormat.FORMAT_TEXT
                                c = ws.cell(row=row_num, column=6)
429
                                c.value = "%d - %s" % (customer_save.preparation_order, customer_save.short_basket_name)
Patrick's avatar
Patrick committed
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 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
                                c.style.number_format.format_code = NumberFormat.FORMAT_TEXT
                                c = ws.cell(row=row_num, column=7)
                                c.value = qty
                                c.style.number_format.format_code = '#,##0.????'
                                c.style.font.color = Color(Color.BLUE)
                                ws.conditional_formatting.addCellIs(
                                    get_column_letter(8) + str(row_num + 1), 'notEqual',
                                    [str(qty)], True, wb,
                                    None, None, yellowFill
                                )
                                c = ws.cell(row=row_num, column=8)
                                c.value = "%s" % base_unit
                                c.style.number_format.format_code = NumberFormat.FORMAT_TEXT
                                customer_unit_price = purchase.get_customer_unit_price()
                                if purchase.status < PERMANENCE_SEND and purchase.offer_item.order_unit == PRODUCT_ORDER_UNIT_PC_KG:
                                    price_qty = qty * purchase.offer_item.order_average_weight
                                    purchases_price_formula.append('ROUND(H%s*%s*%s,2)' % \
                                                                   (row_num + 1,
                                                                    purchase.offer_item.order_average_weight,
                                                                    customer_unit_price + purchase.offer_item.unit_deposit.amount))
                                else:
                                    price_qty = qty
                                    purchases_price_formula.append('ROUND(H%s*%s,2)' % \
                                                                   (row_num + 1,
                                                                    customer_unit_price + purchase.offer_item.unit_deposit.amount))
                                if purchase.offer_item.order_unit == PRODUCT_ORDER_UNIT_PC_KG:
                                    c = ws.cell(row=row_num, column=9)
                                    if purchase.offer_item.wrapped:
                                        c.value = "%s :" % repanier.apps.REPANIER_SETTINGS_CURRENCY_DISPLAY
                                    else:
                                        c.value = "%s" % (_('kg :'))
                                    c.style.number_format.format_code = NumberFormat.FORMAT_TEXT
                                else:
                                    if purchase.offer_item.wrapped:
                                        c = ws.cell(row=row_num, column=9)
                                        c.value = "%s :" % repanier.apps.REPANIER_SETTINGS_CURRENCY_DISPLAY
                                        c.style.number_format.format_code = NumberFormat.FORMAT_TEXT
                                purchases_price += (price_qty *
                                                    (customer_unit_price + purchase.offer_item.unit_deposit.amount)
                                                    ).quantize(TWO_DECIMALS)
                                count_purchase += 1
                                delta = 6
                                for col_num in range(4):
                                    c = ws.cell(row=row_num, column=delta + col_num)
                                    c.style.borders.bottom.border_style = Border.BORDER_THIN
                                row_num += 1

                            purchase = next_purchase(purchases)
                    c = ws.cell(row=row_num - 1, column=10)
                    if len(purchases_price_formula) > 0:
                        c.value = "=%s" % ("+".join(purchases_price_formula))
                    else:
                        c.value = DECIMAL_ZERO
                    c.style.number_format.format_code = repanier.apps.REPANIER_SETTINGS_CURRENCY_XLSX
                    c.style.font.color = Color(Color.BLUE)
                    ws.conditional_formatting.addCellIs(
                        get_column_letter(11) + str(row_num), 'notEqual',
                        [str(purchases_price)], True, wb,
                        None, None, yellowFill
                    )
                row_num -= 1
                #############################################################################################################################
            else:
                # Using quantity_for_preparation_sort_order the order is by customer__short_basket_name if the product
                # is to be distributed by piece, otherwise by lower qty first.
                for offer_item in OfferItem.objects.filter(
                        permanence_id=permanence.id,
                        producer_id=producer.id,
                        translations__language_code=translation.get_language()
                ).order_by(
                    "translations__preparation_sort_order"
                ):
                    purchase_set = Purchase.objects.filter(
                        offer_item_id=offer_item.id
                    ).order_by(
                        "quantity_for_preparation_sort_order",
                        "customer__short_basket_name"
                    ).select_related('customer', 'offer_item', 'offer_item__department_for_customer')
                    if delivery_id is not None:
                        purchase_set = purchase_set.filter(customer_invoice__delivery_id=delivery_id)
                    purchases = purchase_set.iterator()
                    purchase = next_purchase(purchases)
                    while purchase is not None:
                        at_least_one_product = True
                        while purchase is not None:
                            department_for_customer_save = purchase.offer_item.department_for_customer
                            department_for_customer_save__short_name = department_for_customer_save.short_name \
                                if department_for_customer_save is not None else None
                            offer_item_save = purchase.offer_item
                            row_start_offer_item = row_num + 2
                            count_offer_item = 0
                            for col_num in range(11):
                                c = ws.cell(row=row_num, column=col_num)
                                c.style.borders.bottom.border_style = Border.BORDER_THIN
                            purchases_quantity = DECIMAL_ZERO
                            row_num += 1
                            while purchase is not None and offer_item_save == purchase.offer_item:
                                qty = purchase.get_quantity()
                                if qty != DECIMAL_ZERO:
                                    base_unit = get_base_unit(
                                        qty,
                                        offer_item_save.order_unit,
                                        purchase.status
                                    )
                                    c = ws.cell(row=row_num, column=0)
                                    c.value = purchase.id
                                    c = ws.cell(row=row_num, column=1)
                                    c.value = purchase.offer_item_id
                                    if count_offer_item == 0:
                                        c = ws.cell(row=row_num, column=2)
                                        c.value = purchase.offer_item.get_placement_display()
541 542
                                        if placement_save is None:
                                            placement_save = c.value
543
                                        elif hide_column_placement:
544
                                            if placement_save != c.value:
545
                                                hide_column_placement = False
Patrick's avatar
Patrick committed
546 547 548 549 550 551 552 553 554 555 556 557
                                        c = ws.cell(row=row_num, column=3)
                                        c.value = producer_save.short_profile_name
                                    c = ws.cell(row=row_num, column=5)
                                    if department_for_customer_save__short_name is not None:
                                        c.value = "%s - %s" % (
                                            purchase.get_long_name(), department_for_customer_save__short_name)
                                    else:
                                        c.value = "%s" % purchase.get_long_name()
                                    if count_offer_item != 0:
                                        c.style.font.color.index = 'FF939393'
                                    c.style.number_format.format_code = NumberFormat.FORMAT_TEXT
                                    c = ws.cell(row=row_num, column=6)
558
                                    c.value = "%d - %s" % (purchase.customer.preparation_order, purchase.customer.short_basket_name)
Patrick's avatar
Patrick committed
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
                                    c.style.number_format.format_code = NumberFormat.FORMAT_TEXT
                                    c = ws.cell(row=row_num, column=7)
                                    c.value = qty
                                    c.style.number_format.format_code = '#,##0.????'
                                    c.style.font.color = Color(Color.BLUE)
                                    ws.conditional_formatting.addCellIs(
                                        get_column_letter(8) + str(row_num + 1), 'notEqual',
                                        [str(qty)], True, wb,
                                        None, None, yellowFill
                                    )
                                    c = ws.cell(row=row_num, column=8)
                                    c.value = "%s" % base_unit
                                    c.style.number_format.format_code = NumberFormat.FORMAT_TEXT
                                    if purchase.status < PERMANENCE_SEND and offer_item_save.order_unit == PRODUCT_ORDER_UNIT_PC_KG:
                                        c = ws.cell(row=row_num, column=9)
                                        if offer_item_save.wrapped:
                                            c.value = "%s :" % repanier.apps.REPANIER_SETTINGS_CURRENCY_DISPLAY
                                        else:
                                            c.value = "%s" % (_('kg :'))
                                        c.style.number_format.format_code = NumberFormat.FORMAT_TEXT
                                    else:
                                        if offer_item_save.wrapped:
                                            c = ws.cell(row=row_num, column=9)
                                            c.value = "%s :" % repanier.apps.REPANIER_SETTINGS_CURRENCY_DISPLAY
                                            c.style.number_format.format_code = NumberFormat.FORMAT_TEXT
                                    purchases_quantity += qty
                                    count_offer_item += 1
                                    delta = 6
                                    for col_num in range(4):
                                        c = ws.cell(row=row_num, column=delta + col_num)
                                        c.style.borders.bottom.border_style = Border.BORDER_THIN
                                    row_num += 1

                                purchase = next_purchase(purchases)
                            if count_offer_item > 1:
                                c = ws.cell(row=row_num - 1, column=10)
                                c.value = '=SUM(H%s:H%s)' % (row_start_offer_item, row_num)
                                c.style.number_format.format_code = '#,##0.????'
                                if not offer_item_save.wrapped and offer_item_save.order_unit in [PRODUCT_ORDER_UNIT_KG,
                                                                                                  PRODUCT_ORDER_UNIT_PC_KG]:
                                    c.style.font.color = Color(Color.BLUE)
                                ws.conditional_formatting.addCellIs(
                                    get_column_letter(11) + str(row_num), 'notEqual',
                                    [str(purchases_quantity)], True, wb,
                                    None, None, yellowFill
                                )
                            row_num -= 1

            if at_least_one_product:
                for col_num in range(11):
                    c = ws.cell(row=row_num, column=col_num)
                    c.style.borders.bottom.border_style = Border.BORDER_MEDIUMDASHED
                row_num += 1
            producer = next_row(producers)
        ws.column_dimensions[get_column_letter(2)].visible = False
614
        if hide_column_placement:
615 616 617 618
            ws.column_dimensions[get_column_letter(3)].visible = False
        if producer_counter <= 1:
            # hide producer name
            ws.column_dimensions[get_column_letter(4)].visible = False
Patrick's avatar
Patrick committed
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 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
        ws.column_dimensions[get_column_letter(5)].visible = False
    return wb


def export_producer_by_product(permanence, producer, wb=None):
    yellowFill = Fill()
    yellowFill.start_color.index = 'FFEEEE11'
    yellowFill.end_color.index = 'FFEEEE11'
    yellowFill.fill_type = Fill.FILL_SOLID

    language_code = translation.get_language()
    translation.activate(producer.language)

    header = [
        (_("Basket"), 20),
        (_("Quantity"), 10),
        (_("Unit"), 10),
        (_("Reference"), 20),
        (_("Product"), 60),
        (_("Unit Price"), 10),
        (_("Deposit"), 10),
        (_("Total Price"), 12),
    ]
    show_column_reference = False
    hide_column_short_basket_name = True
    hide_column_unit_deposit = True
    formula_main_total = []
    offer_items = OfferItem.objects.filter(
        permanence_id=permanence.id,
        producer_id=producer.id,
        translations__language_code=translation.get_language(),
        quantity_invoiced__gt=DECIMAL_ZERO
    ).order_by(
        "department_for_customer",
        "translations__producer_sort_order"
    ).iterator()
    offer_item = next_row(offer_items)
    if offer_item:
        wb, ws = new_landscape_a4_sheet(
            wb,
            "%s %s" % (producer.short_profile_name, _("by product")),
            permanence,
            header
        )
        row_num = 1
        producer_purchases_price = DECIMAL_ZERO
        status = ProducerInvoice.objects.filter(
            permanence_id=permanence.id, producer_id=producer.id
        ).order_by('?').only("status").first().status
        while offer_item is not None:
            department_for_customer_save = offer_item.department_for_customer
            c = ws.cell(row=row_num, column=1)
            c.value = department_for_customer_save.short_name \
                if department_for_customer_save is not None else "---"
            c.style.font.bold = True
            row_num += 1
            row_start_department = row_num
            department_purchases_price = DECIMAL_ZERO
            while offer_item is not None and department_for_customer_save == offer_item.department_for_customer:
                if offer_item.unit_deposit != DECIMAL_ZERO:
                    hide_column_unit_deposit = False
                show_column_reference = show_column_reference | len(offer_item.reference) < 36
681
                if offer_item.wrapped:
Patrick's avatar
Patrick committed
682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703
                    hide_column_short_basket_name = False
                    first_purchase = True
                    purchase_set = Purchase.objects.filter(
                        offer_item_id=offer_item.id,
                        offer_item__translations__language_code=translation.get_language()
                    ).order_by(
                        "offer_item__translations__producer_sort_order",
                        "customer__short_basket_name"
                    )
                    for purchase in purchase_set:
                        if offer_item.limit_order_quantity_to_stock:
                            # Don't purchase anything to the producer in this case
                            qty = DECIMAL_ZERO
                        else:
                            qty = purchase.get_quantity()
                        if qty != DECIMAL_ZERO:
                            base_unit = get_base_unit(
                                qty,
                                offer_item.order_unit,
                                status
                            )
                            c = ws.cell(row=row_num, column=0)
704
                            c.value = "%d - %s" % (purchase.customer.preparation_order, purchase.customer.short_basket_name)
Patrick's avatar
Patrick committed
705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 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 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 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 907 908 909 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
                            c.style.number_format.format_code = NumberFormat.FORMAT_TEXT
                            c.style.borders.bottom.border_style = Border.BORDER_THIN
                            c = ws.cell(row=row_num, column=1)
                            c.value = qty
                            c.style.number_format.format_code = '#,##0.???'
                            c.style.borders.bottom.border_style = Border.BORDER_THIN
                            c.style.font.bold = True
                            c.style.font.color = Color(Color.BLUE)
                            ws.conditional_formatting.addCellIs(
                                get_column_letter(2) + str(row_num + 1), 'notEqual',
                                [str(qty)], True, wb,
                                None, None, yellowFill
                            )
                            c = ws.cell(row=row_num, column=2)
                            c.value = "%s" % base_unit
                            c.style.number_format.format_code = NumberFormat.FORMAT_TEXT
                            c.style.borders.bottom.border_style = Border.BORDER_THIN
                            c = ws.cell(row=row_num, column=3)
                            c.value = offer_item.reference if len(offer_item.reference) < 36 else EMPTY_STRING
                            c.style.number_format.format_code = NumberFormat.FORMAT_TEXT
                            c.style.borders.bottom.border_style = Border.BORDER_THIN
                            c = ws.cell(row=row_num, column=4)
                            c.value = offer_item.get_long_name(customer_price=False)
                            c.style.number_format.format_code = NumberFormat.FORMAT_TEXT
                            c.style.borders.bottom.border_style = Border.BORDER_THIN
                            if first_purchase:
                                first_purchase = False
                            else:
                                c.style.font.color.index = 'FF939393'
                            c = ws.cell(row=row_num, column=5)
                            producer_unit_price = purchase.get_producer_unit_price()
                            customer_unit_price = purchase.get_customer_unit_price()
                            if producer_unit_price < customer_unit_price:
                                unit_price = producer_unit_price
                            else:
                                unit_price = customer_unit_price
                            c.value = unit_price
                            c.style.number_format.format_code = repanier.apps.REPANIER_SETTINGS_CURRENCY_XLSX
                            c.style.borders.bottom.border_style = Border.BORDER_THIN
                            c = ws.cell(row=row_num, column=6)
                            unit_deposit = offer_item.unit_deposit.amount
                            c.value = unit_deposit
                            c.style.number_format.format_code = repanier.apps.REPANIER_SETTINGS_CURRENCY_XLSX
                            c.style.borders.bottom.border_style = Border.BORDER_THIN
                            c = ws.cell(row=row_num, column=7)
                            if status < PERMANENCE_SEND and offer_item.order_unit == PRODUCT_ORDER_UNIT_PC_KG:
                                price_qty = qty * offer_item.order_average_weight
                                c.value = '=ROUND(B%s*%s*(F%s+G%s),2)' % (
                                row_num + 1, offer_item.order_average_weight, row_num + 1, row_num + 1)
                            else:
                                price_qty = qty
                                c.value = '=ROUND(B%s*(F%s+G%s),2)' % (row_num + 1, row_num + 1, row_num + 1)
                            purchase_price = (
                                price_qty * (unit_price + unit_deposit)
                            ).quantize(TWO_DECIMALS)
                            c.style.number_format.format_code = repanier.apps.REPANIER_SETTINGS_CURRENCY_XLSX
                            c.style.borders.bottom.border_style = Border.BORDER_THIN
                            department_purchases_price += purchase_price
                            ws.conditional_formatting.addCellIs(
                                get_column_letter(8) + str(row_num + 1), 'notEqual',
                                [str(purchase_price)], True, wb,
                                None, None, yellowFill
                            )

                            row_num += 1
                else:
                    qty, taken_from_stock, customer_qty = offer_item.get_producer_qty_stock_invoiced()
                    if qty != DECIMAL_ZERO:
                        # Important : in this case, the qty comes from offer item.
                        # Offer item contains weight, not pieces
                        if status == PERMANENCE_WAIT_FOR_SEND:
                            if offer_item.order_unit == PRODUCT_ORDER_UNIT_PC_KG and offer_item.order_average_weight > DECIMAL_ZERO:
                                qty = (qty / offer_item.order_average_weight).quantize(TWO_DECIMALS)
                        base_unit = get_base_unit(
                            qty,
                            offer_item.order_unit,
                            status
                        )
                        c = ws.cell(row=row_num, column=0)
                        c.value = repanier.apps.REPANIER_SETTINGS_GROUP_NAME
                        c.style.number_format.format_code = NumberFormat.FORMAT_TEXT
                        c.style.borders.bottom.border_style = Border.BORDER_THIN
                        c = ws.cell(row=row_num, column=1)
                        c.value = qty
                        c.style.number_format.format_code = '#,##0.???'
                        c.style.borders.bottom.border_style = Border.BORDER_THIN
                        c.style.font.bold = True
                        c.style.font.color = Color(Color.BLUE)
                        ws.conditional_formatting.addCellIs(
                            get_column_letter(2) + str(row_num + 1), 'notEqual',
                            [str(qty)], True, wb,
                            None, None, yellowFill
                        )
                        c = ws.cell(row=row_num, column=2)
                        c.value = "%s" % base_unit
                        c.style.number_format.format_code = NumberFormat.FORMAT_TEXT
                        c.style.borders.bottom.border_style = Border.BORDER_THIN
                        c = ws.cell(row=row_num, column=3)
                        c.value = offer_item.reference if len(offer_item.reference) < 36 else EMPTY_STRING
                        c.style.number_format.format_code = NumberFormat.FORMAT_TEXT
                        c.style.borders.bottom.border_style = Border.BORDER_THIN
                        c = ws.cell(row=row_num, column=4)
                        c.value = offer_item.get_long_name(customer_price=False)
                        c.style.number_format.format_code = NumberFormat.FORMAT_TEXT
                        c.style.borders.bottom.border_style = Border.BORDER_THIN
                        c = ws.cell(row=row_num, column=5)
                        producer_unit_price = offer_item.producer_unit_price.amount
                        customer_unit_price = offer_item.customer_unit_price.amount
                        if producer_unit_price < customer_unit_price:
                            unit_price = producer_unit_price
                        else:
                            unit_price = customer_unit_price
                        c.value = unit_price
                        c.style.number_format.format_code = repanier.apps.REPANIER_SETTINGS_CURRENCY_XLSX
                        c.style.borders.bottom.border_style = Border.BORDER_THIN
                        c = ws.cell(row=row_num, column=6)
                        unit_deposit = offer_item.unit_deposit.amount
                        c.value = unit_deposit
                        c.style.number_format.format_code = repanier.apps.REPANIER_SETTINGS_CURRENCY_XLSX
                        c.style.borders.bottom.border_style = Border.BORDER_THIN
                        c = ws.cell(row=row_num, column=7)
                        if status < PERMANENCE_SEND and offer_item.order_unit == PRODUCT_ORDER_UNIT_PC_KG:
                            price_qty = qty * offer_item.order_average_weight
                            c.value = '=ROUND(B%s*%s*(F%s+G%s),2)' % (
                            row_num + 1, offer_item.order_average_weight, row_num + 1, row_num + 1)
                        else:
                            price_qty = qty
                            c.value = '=ROUND(B%s*(F%s+G%s),2)' % (row_num + 1, row_num + 1, row_num + 1)
                        purchase_price = (
                            price_qty * (unit_price + unit_deposit)
                        ).quantize(TWO_DECIMALS)
                        c.style.number_format.format_code = repanier.apps.REPANIER_SETTINGS_CURRENCY_XLSX
                        c.style.borders.bottom.border_style = Border.BORDER_THIN
                        department_purchases_price += purchase_price
                        ws.conditional_formatting.addCellIs(
                            get_column_letter(8) + str(row_num + 1), 'notEqual',
                            [str(purchase_price)], True, wb,
                            None, None, yellowFill
                        )

                        row_num += 1
                offer_item = next_row(offer_items)
            for col_num in range(8):
                c = ws.cell(row=row_num, column=col_num)
                c.style.borders.bottom.border_style = Border.BORDER_THIN
                if col_num == 4:
                    if producer.producer_price_are_wo_vat:
                        c.value = "%s %s %s" % (
                            _("Total Price"), _("wo tax"), department_for_customer_save.short_name \
                                if department_for_customer_save is not None else "---")
                    else:
                        c.value = "%s %s %s" % (
                            _("Total Price"), _("w tax"), department_for_customer_save.short_name \
                                if department_for_customer_save is not None else "---")
                    c.style.number_format.format_code = NumberFormat.FORMAT_TEXT
                if col_num == 7:
                    formula = 'SUM(H%s:H%s)' % (row_start_department, row_num)
                    c.value = '=' + formula
                    c.style.number_format.format_code = repanier.apps.REPANIER_SETTINGS_CURRENCY_XLSX
                    c.style.font.bold = True
                    producer_purchases_price += department_purchases_price
                    ws.conditional_formatting.addCellIs(
                        get_column_letter(8) + str(row_num + 1), 'notEqual',
                        [str(department_purchases_price)], True, wb,
                        None, None, yellowFill
                    )
                    formula_main_total.append(formula)
            row_num += 1
        for col_num in range(8):
            c = ws.cell(row=row_num, column=col_num)
            c.style.borders.bottom.border_style = Border.BORDER_THIN
            if col_num == 1:
                if producer.producer_price_are_wo_vat:
                    c.value = "%s %s %s" % (_("Total Price"), _("wo tax"), repanier.apps.REPANIER_SETTINGS_GROUP_NAME)
                else:
                    c.value = "%s %s %s" % (_("Total Price"), _("w tax"), repanier.apps.REPANIER_SETTINGS_GROUP_NAME)
                c.style.number_format.format_code = NumberFormat.FORMAT_TEXT
            if col_num == 7:
                c.value = "=" + "+".join(formula_main_total)
                c.style.number_format.format_code = repanier.apps.REPANIER_SETTINGS_CURRENCY_XLSX
                c.style.font.bold = True
                ws.conditional_formatting.addCellIs(
                    get_column_letter(8) + str(row_num + 1), 'notEqual',
                    [str(producer_purchases_price)], True, wb,
                    None, None, yellowFill
                )

        if hide_column_short_basket_name:
            ws.column_dimensions[get_column_letter(1)].visible = False
        if not show_column_reference:
            ws.column_dimensions[get_column_letter(4)].visible = False
        if hide_column_unit_deposit:
            ws.column_dimensions[get_column_letter(7)].visible = False
    translation.activate(language_code)
    return wb


def export_producer_by_customer(permanence, producer, wb=None):
    language_code = translation.get_language()
    translation.activate(producer.language)

    header = [
        (_("Quantity"), 10),
        (_("Unit"), 10),
        (_("Reference"), 20),
        (_("Product"), 60),
        (_("Unit Price"), 10),
        (_("Deposit"), 10),
        (_("Total Price"), 12),
        (EMPTY_STRING, 15),
    ]
    show_column_reference = False
    hide_column_unit_deposit = True
    formula_main_total = []
    purchase_set = Purchase.objects.filter(
        permanence_id=permanence.id,
        producer_id=producer.id,
        offer_item__translations__language_code=translation.get_language(),
    ).order_by(
        "customer__short_basket_name",
        "offer_item__translations__preparation_sort_order"
    ).select_related("offer_item")
    purchases = purchase_set.iterator()
    purchase = next_row(purchases)
    if purchase:
        wb, ws = new_landscape_a4_sheet(
            wb,
            "%s %s" % (producer.short_profile_name, _("by basket")),
            permanence,
            header
        )
        row_num = 1
        while purchase is not None:
            customer_save = purchase.customer
            c = ws.cell(row=row_num, column=0)
940
            c.value = "%d - %s" % (customer_save.preparation_order, customer_save.short_basket_name)
Patrick's avatar
Patrick committed
941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 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 998 999 1000 1001 1002 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 1031 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 1078 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
            c.style.font.bold = True
            row_num += 1
            row_start_customer = row_num
            first_purchase = True
            while purchase is not None and customer_save.id == purchase.customer_id:
                qty = purchase.get_quantity()
                if qty != DECIMAL_ZERO:
                    offer_item_save = purchase.offer_item
                    base_unit = get_base_unit(
                        qty,
                        purchase.offer_item.order_unit,
                        purchase.status
                    )
                    c = ws.cell(row=row_num, column=0)
                    c.value = qty
                    c.style.number_format.format_code = '#,##0.???'
                    c.style.borders.bottom.border_style = Border.BORDER_THIN
                    c.style.font.bold = True
                    c = ws.cell(row=row_num, column=1)
                    c.value = "%s" % base_unit
                    c.style.number_format.format_code = NumberFormat.FORMAT_TEXT
                    c.style.borders.bottom.border_style = Border.BORDER_THIN
                    c = ws.cell(row=row_num, column=2)
                    c.value = offer_item_save.reference if len(offer_item_save.reference) < 36 else EMPTY_STRING
                    c.style.number_format.format_code = NumberFormat.FORMAT_TEXT
                    c.style.borders.bottom.border_style = Border.BORDER_THIN
                    c = ws.cell(row=row_num, column=3)
                    c.value = offer_item_save.get_long_name(customer_price=False)
                    c.style.number_format.format_code = NumberFormat.FORMAT_TEXT
                    c.style.borders.bottom.border_style = Border.BORDER_THIN
                    if first_purchase:
                        first_purchase = False
                    c = ws.cell(row=row_num, column=4)
                    producer_unit_price = purchase.get_producer_unit_price(with_price_list_multiplier=False)
                    customer_unit_price = purchase.get_customer_unit_price(with_price_list_multiplier=False)
                    if producer_unit_price < customer_unit_price:
                        unit_price = producer_unit_price
                    else:
                        unit_price = customer_unit_price
                    c.value = unit_price
                    c.style.number_format.format_code = repanier.apps.REPANIER_SETTINGS_CURRENCY_XLSX
                    c.style.borders.bottom.border_style = Border.BORDER_THIN
                    c = ws.cell(row=row_num, column=5)
                    c.value = offer_item_save.unit_deposit.amount
                    c.style.number_format.format_code = repanier.apps.REPANIER_SETTINGS_CURRENCY_XLSX
                    c.style.borders.bottom.border_style = Border.BORDER_THIN
                    c = ws.cell(row=row_num, column=6)
                    if purchase.status < PERMANENCE_SEND and offer_item_save.order_unit == PRODUCT_ORDER_UNIT_PC_KG:
                        c.value = '=ROUND(A%s*%s*(E%s+F%s),2)' % (
                        row_num + 1, offer_item_save.order_average_weight, row_num + 1, row_num + 1)
                    else:
                        c.value = '=ROUND(A%s*(E%s+F%s),2)' % (row_num + 1, row_num + 1, row_num + 1)
                    c.style.number_format.format_code = repanier.apps.REPANIER_SETTINGS_CURRENCY_XLSX
                    c.style.borders.bottom.border_style = Border.BORDER_THIN
                    row_num += 1
                purchase = next_row(purchases)
            for col_num in range(7):
                c = ws.cell(row=row_num, column=col_num)
                c.style.borders.bottom.border_style = Border.BORDER_THIN
                if col_num == 3:
                    if producer.producer_price_are_wo_vat:
                        c.value = "%s %s %s" % (
                            _("Total Price"), _("wo tax"), customer_save.short_basket_name)
                    else:
                        c.value = "%s %s %s" % (
                            _("Total Price"), _("w tax"), customer_save.short_basket_name)
                    c.style.number_format.format_code = NumberFormat.FORMAT_TEXT
                if col_num == 6:
                    formula = 'SUM(G%s:G%s)' % (row_start_customer, row_num)
                    c.value = '=' + formula
                    c.style.number_format.format_code = repanier.apps.REPANIER_SETTINGS_CURRENCY_XLSX
                    c.style.font.bold = True
                    formula_main_total.append(formula)
            row_num += 1
        for col_num in range(7):
            c = ws.cell(row=row_num, column=col_num)
            c.style.borders.bottom.border_style = Border.BORDER_THIN
            if col_num == 0:
                if producer.producer_price_are_wo_vat:
                    c.value = "%s %s %s" % (_("Total Price"), _("wo tax"), repanier.apps.REPANIER_SETTINGS_GROUP_NAME)
                else:
                    c.value = "%s %s %s" % (_("Total Price"), _("w tax"), repanier.apps.REPANIER_SETTINGS_GROUP_NAME)
                c.style.number_format.format_code = NumberFormat.FORMAT_TEXT
            if col_num == 6:
                c.value = "=" + "+".join(formula_main_total)
                c.style.number_format.format_code = repanier.apps.REPANIER_SETTINGS_CURRENCY_XLSX
                c.style.font.bold = True
        if hide_column_unit_deposit:
            ws.column_dimensions[get_column_letter(6)].visible = False
        if not show_column_reference:
            ws.column_dimensions[get_column_letter(3)].visible = False
    translation.activate(language_code)
    return wb


def export_customer(
        permanence=None,
        customer=None,
        deliveries_id=None,
        deposit=False,
        xlsx_formula=True,
        wb=None, ws_preparation_title=None):
    yellowFill = Fill()
    yellowFill.start_color.index = 'FFEEEE11'
    yellowFill.end_color.index = 'FFEEEE11'
    yellowFill.fill_type = Fill.FILL_SOLID

    header = [
        (_("Purchase"), 5),
        (_("OfferItem"), 5),
        (_("Placement"), 15),
        (_("Producer"), 15),
        (_("Product"), 60),
        (_("Quantity"), 10),
        (_("Unit"), 10),
        (_("Unit Price"), 10),
        (_("Deposit"), 10),
        (_("Total Price"), 12),
        (_("Basket"), 20),
    ]
    if deliveries_id is None:
        return export_customer_for_a_delivery(
            customer, 0, None, deposit, header, permanence, wb,
            ws_preparation_title, yellowFill, xlsx_formula
        )
    else:
        for delivery_cpt, delivery_id in enumerate(deliveries_id):
            wb = export_customer_for_a_delivery(
                customer, delivery_cpt, delivery_id, deposit, header, permanence, wb,
                ws_preparation_title, yellowFill, xlsx_formula
            )
        return wb


def export_customer_for_a_delivery(
        customer, delivery_cpt, delivery_id, deposit, header, permanence, wb, ws_preparation_title,
        yellowFill, xlsx_formula):
    language_code = translation.get_language()
    if customer is not None:
        translation.activate(customer.language)
        if deposit:
            purchase_set = Purchase.objects.filter(
                permanence_id=permanence.id,
                customer_id=customer.id,
                producer__isnull=False,
                offer_item__translations__language_code=customer.language,
                offer_item__order_unit=PRODUCT_ORDER_UNIT_DEPOSIT
            ).order_by(
                "offer_item__translations__long_name",
                "offer_item__order_average_weight",
            ).select_related('customer', 'offer_item', 'offer_item__department_for_customer')
        else:
            purchase_set = Purchase.objects.filter(
                permanence_id=permanence.id,
                customer_id=customer.id,
                producer__isnull=False,
                offer_item__translations__language_code=customer.language,
            ).exclude(
                offer_item__order_unit=PRODUCT_ORDER_UNIT_DEPOSIT
            ).order_by(
                "offer_item__translations__long_name",
                "offer_item__order_average_weight",
            ).select_related('customer', 'offer_item', 'offer_item__department_for_customer')
    else:
        if deposit:
            purchase_set = Purchase.objects.filter(
                permanence_id=permanence.id,
                producer__isnull=False,
                offer_item__translations__language_code=language_code,
                offer_item__order_unit=PRODUCT_ORDER_UNIT_DEPOSIT
            ).order_by(
                "customer__short_basket_name",
                "offer_item__producer",
                "offer_item__translations__long_name",
                "offer_item__order_average_weight",
            ).select_related('customer', 'offer_item', 'offer_item__department_for_customer')
        else:
            purchase_set = Purchase.objects.filter(
                permanence_id=permanence.id,
                producer__isnull=False,
                offer_item__translations__language_code=language_code,
            ).exclude(
                offer_item__order_unit=PRODUCT_ORDER_UNIT_DEPOSIT
            ).order_by(
                "customer__short_basket_name",
                "offer_item__producer",
                "offer_item__translations__long_name",
                "offer_item__order_average_weight",
            ).select_related('customer', 'offer_item', 'offer_item__department_for_customer')
        if delivery_id is not None:
            purchase_set = purchase_set.filter(customer_invoice__delivery_id=delivery_id)
    purchases = purchase_set.iterator()
    purchase = next_purchase(purchases)
1134
    if purchase is not None:
Patrick's avatar
Patrick committed
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
        config = Configuration.objects.get(id=DECIMAL_ONE)
        group_label = config.group_label
        if deposit:
            if repanier.apps.REPANIER_SETTINGS_PAGE_BREAK_ON_CUSTOMER_CHECK:
                # Change the orientation to reduce the number of page breaks, i.e. the number of printed pages
                wb, ws = new_portrait_a4_sheet(
                    wb,
                    _("Deposits") if delivery_id is None else "%d-%s" % (delivery_cpt, _("Deposits")),
                    permanence,
                    header
                )
            else:
                wb, ws = new_landscape_a4_sheet(
                    wb,
                    _("Deposits") if delivery_id is None else "%d-%s" % (delivery_cpt, _("Deposits")),
                    permanence,
                    header
                )
        else:
            if repanier.apps.REPANIER_SETTINGS_PAGE_BREAK_ON_CUSTOMER_CHECK:
                # Change the orientation to reduce the number of page breaks, i.e. the number of printed pages
                wb, ws = new_portrait_a4_sheet(
                    wb,
                    _("Customer check") if delivery_id is None else "%d-%s" % (delivery_cpt, _("Customer check")),
                    permanence,
                    header
                )
            else:
                wb, ws = new_landscape_a4_sheet(
                    wb,
                    _("Customer check") if delivery_id is None else "%d-%s" % (delivery_cpt, _("Customer check")),
                    permanence,
                    header
                )
        hide_column_placement = True
1170
        hide_column_producer = True
Patrick's avatar
Patrick committed
1171 1172
        offer_item_save = purchase.offer_item
        placement_save = offer_item_save.placement
1173
        producer_save = offer_item_save.producer
Patrick's avatar
Patrick committed
1174
        row_num = 1
1175 1176 1177 1178 1179
        if delivery_id is not None:
            c = ws.cell(row=row_num, column=4)
            c.style.font.bold = True
            c.value = DeliveryBoard.objects.filter(id=delivery_id).order_by('?').first().get_delivery_display()
            row_num += 1
Patrick's avatar
Patrick committed
1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197
        if ws_preparation_title is not None and xlsx_formula:
            ref_preparation_sheet = ws_preparation_title if delivery_id is None else "%d-%s" % (
            delivery_cpt, ws_preparation_title)
        else:
            ref_preparation_sheet = None
        while purchase is not None:
            customer_save = purchase.customer
            row_start_customer = row_num + 1
            first_purchase = True
            total_price = DECIMAL_ZERO
            while purchase is not None and customer_save.id == purchase.customer_id:
                department_for_customer_save__id = offer_item_save.department_for_customer_id
                department_for_customer_save__short_name = offer_item_save.department_for_customer.short_name \
                    if offer_item_save.department_for_customer is not None else None
                while purchase is not None and customer_save.id == purchase.customer_id and \
                                offer_item_save.department_for_customer_id == department_for_customer_save__id:
                    if placement_save != offer_item_save.placement:
                        hide_column_placement = False
1198 1199
                    if producer_save != offer_item_save.producer:
                        hide_column_producer = False
Patrick's avatar
Patrick committed
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 1250 1251 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
                    qty = purchase.get_quantity()
                    if qty != DECIMAL_ZERO:
                        base_unit = get_base_unit(
                            qty,
                            offer_item_save.order_unit,
                            purchase.status
                        )
                        c = ws.cell(row=row_num, column=0)
                        c.value = purchase.id
                        c = ws.cell(row=row_num, column=1)
                        c.value = offer_item_save.id
                        c = ws.cell(row=row_num, column=2)
                        c.value = offer_item_save.get_placement_display()
                        c.style.number_format.format_code = NumberFormat.FORMAT_TEXT
                        c.style.borders.bottom.border_style = Border.BORDER_THIN
                        c = ws.cell(row=row_num, column=3)
                        c.value = purchase.producer.short_profile_name
                        c.style.number_format.format_code = NumberFormat.FORMAT_TEXT
                        c.style.borders.bottom.border_style = Border.BORDER_THIN
                        c = ws.cell(row=row_num, column=4)
                        if department_for_customer_save__short_name is not None:
                            c.value = "%s - %s" % (purchase.get_long_name(), department_for_customer_save__short_name)
                        else:
                            c.value = "%s" % purchase.get_long_name()
                        c.style.number_format.format_code = NumberFormat.FORMAT_TEXT
                        c.style.borders.bottom.border_style = Border.BORDER_THIN
                        c = ws.cell(row=row_num, column=5)
                        if ref_preparation_sheet is None:
                            c.value = qty
                        else:
                            c.value = "=SUMIF('%s'!A2:A5000,A%s,'%s'!H2:H5000)" % \
                                      (ref_preparation_sheet, row_num + 1, ref_preparation_sheet)

                        c.style.number_format.format_code = '#,##0.???'
                        c.style.borders.bottom.border_style = Border.BORDER_THIN
                        if not deposit:
                            c.style.font.color = Color(Color.BLUE)
                        if xlsx_formula:
                            ws.conditional_formatting.addCellIs(
                                get_column_letter(6) + str(row_num + 1), 'notEqual',
                                [str(qty)], True, wb,
                                None, None, yellowFill
                            )
                        c = ws.cell(row=row_num, column=6)
                        c.value = "%s" % base_unit
                        c.style.number_format.format_code = NumberFormat.FORMAT_TEXT
                        c.style.borders.bottom.border_style = Border.BORDER_THIN
                        if purchase.is_box_content:
                            # No price infos : The customer pay for a box not for a product
                            for x in range(6, 10):
                                c = ws.cell(row=row_num, column=x)
                                c.style.borders.bottom.border_style = Border.BORDER_THIN
                        else:
                            c = ws.cell(row=row_num, column=7)
                            customer_unit_price = purchase.get_customer_unit_price()
                            c.value = customer_unit_price
                            c.style.number_format.format_code = repanier.apps.REPANIER_SETTINGS_CURRENCY_XLSX
                            c.style.borders.bottom.border_style = Border.BORDER_THIN
                            c = ws.cell(row=row_num, column=8)
                            unit_deposit = offer_item_save.unit_deposit.amount
                            c.value = unit_deposit
                            c.style.number_format.format_code = repanier.apps.REPANIER_SETTINGS_CURRENCY_XLSX
                            c.style.borders.bottom.border_style = Border.BORDER_THIN
                            c = ws.cell(row=row_num, column=9)
                            if purchase.status < PERMANENCE_SEND and offer_item_save.order_unit == PRODUCT_ORDER_UNIT_PC_KG:
                                price_qty = qty * offer_item_save.order_average_weight
                                c.value = '=ROUND(F%s*%s*(H%s+I%s),2)' % (
                                    row_num + 1, offer_item_save.order_average_weight, row_num + 1, row_num + 1)
                            else:
                                price_qty = qty
                                c.value = '=ROUND(F%s*(H%s+I%s),2)' % (row_num + 1, row_num + 1, row_num + 1)
                            purchases_price = (
                                price_qty * (customer_unit_price + unit_deposit)
                            ).quantize(TWO_DECIMALS)
                            if not xlsx_formula:
                                c.value = purchases_price
                                total_price += purchases_price
                            c.style.number_format.format_code = repanier.apps.REPANIER_SETTINGS_CURRENCY_XLSX
                            c.style.borders.bottom.border_style = Border.BORDER_THIN
                            if xlsx_formula:
                                ws.conditional_formatting.addCellIs(
                                    get_column_letter(10) + str(row_num + 1), 'notEqual',
                                    [str(purchases_price)], True, wb,
                                    None, None, yellowFill
                                )

                        c = ws.cell(row=row_num, column=10)
1287 1288 1289 1290
                        if xlsx_formula:
                            c.value = "%d - %s" % (purchase.customer.preparation_order, purchase.customer.short_basket_name)
                        else:
                            c.value = purchase.customer.long_basket_name
Patrick's avatar
Patrick committed
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
                        c.style.number_format.format_code = NumberFormat.FORMAT_TEXT
                        c.style.borders.bottom.border_style = Border.BORDER_THIN
                        if first_purchase:
                            c.style.font.bold = True
                            first_purchase = False
                        c.style.font.italic = True
                        row_num += 1
                    purchase = next_purchase(purchases)
                    offer_item_save = purchase.offer_item if purchase is not None else None
            row_num += 1
            c = ws.cell(row=row_num, column=4)
            c.value = group_label
            c.style.number_format.format_code = NumberFormat.FORMAT_TEXT
            c.style.font.bold = True
            c = ws.cell(row=row_num, column=8)
            c.value = "%s %s" % (_("Total Price"), customer_save.long_basket_name)
            c.style.number_format.format_code = NumberFormat.FORMAT_TEXT
            c.style.font.bold = True
            c.style.alignment.horizontal = c.style.alignment.HORIZONTAL_RIGHT
            c = ws.cell(row=row_num, column=9)
            if xlsx_formula:
                c.value = '=SUM(J%s:J%s)' % (row_start_customer, row_num)
            else:
                c.value = total_price
            c.style.number_format.format_code = repanier.apps.REPANIER_SETTINGS_CURRENCY_XLSX
            c.style.font.bold = True
            # Display a separator line between customers
            row_num += 1
            for col_num in range(11):
                c = ws.cell(row=row_num, column=col_num)
                c.style.borders.bottom.border_style = Border.BORDER_MEDIUMDASHED
            row_num += 2

        ws.column_dimensions[get_column_letter(1)].visible = False
        ws.column_dimensions[get_column_letter(2)].visible = False
        if hide_column_placement:
            ws.column_dimensions[get_column_letter(3)].visible = False
1328 1329
        if hide_column_producer:
            ws.column_dimensions[get_column_letter(4)].visible = False
Patrick's avatar
Patrick committed
1330 1331 1332 1333 1334 1335 1336 1337
    translation.activate(language_code)
    return wb


def admin_customer_export(permanence, deliveries_id=None):
    response = None
    wb = export_abstract(permanence=permanence, deliveries_id=deliveries_id, wb=None)
    if wb is not None:
1338 1339 1340
        wb = export_customer_label(
            permanence=permanence, deliveries_id=deliveries_id, wb=wb
        )
Patrick's avatar
Patrick committed
1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 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
        wb = export_preparation(permanence=permanence, deliveries_id=deliveries_id, wb=wb)
        if wb is not None:
            ws_preparation_title = cap("%s" % (_("Preparation")), 31)
            wb = export_customer(
                permanence=permanence, deliveries_id=deliveries_id, wb=wb, ws_preparation_title=ws_preparation_title
            )
            ws_customer_title = cap("%s" % (_('Customer check')), 31)
            wb = export_customer(permanence=permanence, deliveries_id=deliveries_id, deposit=True, wb=wb)
        else:
            ws_customer_title = None
        wb = export_permanence_stock(permanence=permanence, deliveries_id=deliveries_id, wb=wb,
                                     ws_customer_title=ws_customer_title)

    if wb is not None:
        response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
        response['Content-Disposition'] = "attachment; filename={0}-{1}.xlsx".format(
            slugify(_("Customers")),
            slugify(permanence)
        )
        wb.save(response)
    return response


def admin_producer_export(permanence):
    wb = None
    producer_set = Producer.objects.filter(permanence=permanence).order_by("short_profile_name")
    for producer in producer_set:
        wb = export_producer_by_product(
            permanence=permanence, producer=producer, wb=wb
        )
        if not producer.manage_replenishment:
            wb = export_producer_by_customer(
                permanence=permanence, producer=producer, wb=wb
            )
    if wb is not None:
        response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
        response['Content-Disposition'] = "attachment; filename={0}-{1}.xlsx".format(
            slugify(_("Producers")),
            slugify(permanence)
        )
        wb.save(response)
        return response
    else:
        return None