xlsx_purchase.py 42.1 KB
Newer Older
Patrick's avatar
Patrick committed
1 2 3 4 5 6 7 8 9 10
# -*- coding: utf-8
from __future__ import unicode_literals

from django.db import transaction
from django.utils import translation
from django.utils.translation import ugettext_lazy as _
from openpyxl import load_workbook
from openpyxl.style import Fill
from openpyxl.styles import Color

chris's avatar
chris committed
11 12
from repanier.xlsx.export_tools import *
from repanier.xlsx.import_tools import *
Patrick's avatar
Patrick committed
13 14
from repanier.apps import REPANIER_SETTINGS_CURRENCY_XLSX
from repanier.const import *
Patrick's avatar
Patrick committed
15 16 17
from repanier.models.offeritem import OfferItem
from repanier.models.producer import Producer
from repanier.models.purchase import Purchase
Patrick's avatar
Patrick committed
18
from repanier.tools import cap, next_row
Patrick's avatar
Patrick committed
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50


def next_purchase(purchases):
    purchase = next_row(purchases)
    while purchase is not None \
            and purchase.quantity_invoiced <= DECIMAL_ZERO \
            and purchase.offer_item.order_unit < PRODUCT_ORDER_UNIT_DEPOSIT:
        purchase = next_row(purchases)
    return purchase


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

    header = [
        (_("Format"), 5),
        (_("Id"), 10),
        (_("Date"), 15),
        (_("producer"), 15),
        (_("product"), 60),
        (_("customer"), 15),
        (_("quantity invoiced"), 10),
        (_("producer unit price"), 10),
        (_("deposit"), 10),
        (_("purchase price"), 10),
        (_("tax"), 10),
        (_("rule of 3"), 10),
        (_("comment"), 30),
        (_("vat level"), 10),
Patrick's avatar
Patrick committed
51
        (_("CustId_01"), 10),
Patrick's avatar
Patrick committed
52 53 54 55
    ]

    if producer is None:
        if permanence is not None:
Patrick's avatar
Patrick committed
56 57 58 59 60 61 62 63 64 65
            if customer is not None:
                producers = Producer.objects.filter(
                    producerinvoice__permanence_id=permanence.id
                ).distinct().iterator()
                title1 = "%s-%s" % (customer.short_basket_name, permanence)
            else:
                producers = Producer.objects.filter(
                    producerinvoice__permanence_id=permanence.id
                ).distinct().iterator()
                title1 = "%s" % permanence
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 88 89 90 91
        else:
            producers = Producer.objects.filter(
                producerinvoice__permanence__permanence_date__year=year
            ).distinct().iterator()
            title1 = "%s-%d" % (customer.short_basket_name, year)
    else:
        producers = Producer.objects.filter(id=producer.id).iterator()
        title1 = "%s-%d" % (producer.short_profile_name, year)
    producer = next_row(producers)
    if producer is not None:
        wb, ws = new_landscape_a4_sheet(
            wb,
            title1,
            _('invoices'),
            header
        )
        row_num = 1
        count_all_purchase = 0
        purchase_price_all_purchase = []
        tax_all_purchase = []
        while producer is not None:
            producer_save = producer
            # count_producer_purchase = 0
            producer_price = DECIMAL_ZERO
            if producer.invoice_by_basket:
                if year is None:
Patrick's avatar
Patrick committed
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
                    if customer is None:
                        purchases = 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"
                        ).iterator()
                    else:
                        purchases = Purchase.objects.filter(
                            permanence_id=permanence.id,
                            customer_id=customer.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"
                        ).iterator()
Patrick's avatar
Patrick committed
111 112 113
                else:
                    if customer is None:
                        purchases = Purchase.objects.filter(
Patrick's avatar
Patrick committed
114
                            permanence__status__gte=PERMANENCE_INVOICED,
Patrick's avatar
Patrick committed
115 116 117 118 119 120 121 122 123 124 125
                            permanence_date__year=year,
                            producer_id=producer.id,
                            offer_item__translations__language_code=translation.get_language()
                        ).order_by(
                            "permanence_date",
                            "permanence_id",
                            "customer__short_basket_name",
                            "offer_item__translations__preparation_sort_order"
                        ).iterator()
                    else:
                        purchases = Purchase.objects.filter(
Patrick's avatar
Patrick committed
126
                            permanence__status__gte=PERMANENCE_INVOICED,
Patrick's avatar
Patrick committed
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 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
                            permanence_date__year=year,
                            customer_id=customer.id,
                            producer_id=producer.id,
                            offer_item__translations__language_code=translation.get_language()
                        ).order_by(
                            "permanence_date",
                            "permanence_id",
                            "offer_item__translations__preparation_sort_order"
                        ).iterator()
                purchase = next_purchase(purchases)
                while purchase is not None:
                    permanence_save = purchase.permanence
                    count_permanence_purchase = 0
                    row_start_permanence = 0
                    row_num += 1
                    while purchase is not None and permanence_save.id == purchase.permanence_id:
                        customer_save = purchase.customer
                        count_purchase = 0
                        row_start_purchase = 0
                        purchases_price = DECIMAL_ZERO
                        while purchase is not None and permanence_save.id == purchase.permanence_id \
                                and customer_save.id == purchase.customer_id:
                            offer_item_save = purchase.offer_item
                            department_for_customer_save = offer_item_save.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 permanence_save.id == purchase.permanence_id \
                                    and customer_save.id == purchase.customer_id \
                                    and department_for_customer_save == purchase.offer_item.department_for_customer:
                                c = ws.cell(row=row_num, column=1)
                                c.value = purchase.id
                                c = ws.cell(row=row_num, column=2)
                                c.value = permanence_save.permanence_date
                                c.style.number_format.format_code = NumberFormat.FORMAT_DATE_DDMMYYYY
                                c = ws.cell(row=row_num, column=3)
                                c.value = producer_save.short_profile_name
                                c.style.number_format.format_code = NumberFormat.FORMAT_TEXT
                                if count_purchase == 0:
                                    row_start_purchase = row_num + 1
                                    if count_permanence_purchase == 0:
                                        c.style.font.bold = True
                                        row_start_permanence = row_start_purchase
                                    c = ws.cell(row=row_num, column=0)
                                    c.value = "A"
                                else:
                                    c = ws.cell(row=row_num, column=0)
                                    c.value = "B"
                                count_purchase += 1
                                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 = ws.cell(row=row_num, column=5)
                                c.value = customer_save.short_basket_name
                                c.style.number_format.format_code = NumberFormat.FORMAT_TEXT
                                if count_purchase == 0 and customer is None:
                                    c.style.font.bold = True
                                c = ws.cell(row=row_num, column=6)
                                c.value = purchase.quantity_invoiced
                                c.style.number_format.format_code = '#,##0.????'
                                if year is None:
                                    c.style.font.color = Color(Color.BLUE)
                                    ws.conditional_formatting.addCellIs(
                                        get_column_letter(7) + str(row_num + 1), 'notEqual',
                                        [str(purchase.quantity_invoiced)], True, wb,
                                        None, None, yellowFill
                                    )
                                c = ws.cell(row=row_num, column=7)
                                c.value = purchase.get_producer_unit_price()
                                c.style.number_format.format_code = REPANIER_SETTINGS_CURRENCY_XLSX
Patrick's avatar
Patrick committed
201 202
                                # if year is None:
                                #     c.style.font.color = Color(Color.BLUE)
Patrick's avatar
Patrick committed
203 204 205 206 207 208 209 210 211 212
                                c = ws.cell(row=row_num, column=8)
                                c.value = purchase.offer_item.unit_deposit.amount
                                c.style.number_format.format_code = REPANIER_SETTINGS_CURRENCY_XLSX
                                c = ws.cell(row=row_num, column=9)
                                c.value = '=ROUND(G%s*(H%s+I%s),2)' % (row_num + 1, row_num + 1, row_num + 1)
                                if year is None:
                                    purchase_price = (purchase.quantity_invoiced *
                                                      (purchase.get_producer_unit_price() +
                                                       purchase.get_unit_deposit())).quantize(TWO_DECIMALS)
                                    purchases_price += purchase_price
Patrick's avatar
Patrick committed
213 214 215 216 217 218
                                    # Asked by GAC HAMOIS : sell broken products...
                                    # if offer_item_save.order_unit in [
                                    #     PRODUCT_ORDER_UNIT_KG, PRODUCT_ORDER_UNIT_PC_KG,
                                    #     PRODUCT_ORDER_UNIT_LT
                                    # ]:
                                    c.style.font.color = Color(Color.BLUE)
Patrick's avatar
Patrick committed
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
                                    ws.conditional_formatting.addCellIs(
                                        get_column_letter(10) + str(row_num + 1), 'notEqual',
                                        [str(purchase_price)], True, wb,
                                        None, None, yellowFill
                                    )
                                c.style.number_format.format_code = REPANIER_SETTINGS_CURRENCY_XLSX
                                c = ws.cell(row=row_num, column=10)
                                c.value = '=G%s*%s' % (row_num + 1, purchase.offer_item.customer_vat.amount)
                                c.style.number_format.format_code = REPANIER_SETTINGS_CURRENCY_XLSX
                                c = ws.cell(row=row_num, column=12)
                                c.value = cap(purchase.comment, 100)
                                c.style.number_format.format_code = NumberFormat.FORMAT_TEXT
                                c = ws.cell(row=row_num, column=13)
                                c.value = purchase.offer_item.get_vat_level_display()
                                c.style.number_format.format_code = NumberFormat.FORMAT_TEXT
Patrick's avatar
Patrick committed
234 235 236
                                c = ws.cell(row=row_num, column=14)
                                c.value = purchase.customer.user.email
                                c.style.number_format.format_code = NumberFormat.FORMAT_TEXT
Patrick's avatar
Patrick committed
237 238 239
                                delta = 5
                                for col_num in range(5):
                                    c = ws.cell(row=row_num, column=delta + col_num)
Patrick's avatar
Patrick committed
240
                                    c.style.borders.top.border_style = Border.BORDER_THIN
Patrick's avatar
Patrick committed
241 242 243 244 245
                                row_num += 1
                                purchase = next_purchase(purchases)

                        count_permanence_purchase += count_purchase
                        if year is None and count_purchase > 1:
Patrick's avatar
Patrick committed
246
                            c = ws.cell(row=row_num -1, column=11)
Patrick's avatar
Patrick committed
247 248 249 250
                            c.value = '=SUM(J%s:J%s)' % (row_start_purchase, row_num)
                            c.style.number_format.format_code = REPANIER_SETTINGS_CURRENCY_XLSX
                            c.style.font.color = Color(Color.BLUE)
                            ws.conditional_formatting.addCellIs(
Patrick's avatar
Patrick committed
251
                                get_column_letter(12) + str(row_num), 'notEqual',
Patrick's avatar
Patrick committed
252 253 254
                                [str(purchases_price)], True, wb,
                                None, None, yellowFill
                            )
Patrick's avatar
Patrick committed
255
                            c = ws.cell(row=row_num -1, column=0)
Patrick's avatar
Patrick committed
256
                            c.value = "C"
Patrick's avatar
Patrick committed
257
                            # row_num += 1
Patrick's avatar
Patrick committed
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288

                        producer_price += purchases_price
                    if count_permanence_purchase > 0:
                        count_all_purchase += count_permanence_purchase
                        purchase_price_producer_purchase = 'ROUND(SUM(J%s:J%s),2)' % (row_start_permanence, row_num)
                        purchase_price_all_purchase.append(purchase_price_producer_purchase)
                        tax_producer_purchase = 'SUM(K%s:K%s)' % (row_start_permanence, row_num)
                        tax_all_purchase.append(tax_producer_purchase)

                        row_num += 1
                        c = ws.cell(row=row_num, column=8)
                        c.value = "%s : %s %s" % (_("Total"), producer_save.short_profile_name, permanence_save)
                        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)
                        c.value = '=%s' % purchase_price_producer_purchase
                        c.style.number_format.format_code = REPANIER_SETTINGS_CURRENCY_XLSX
                        c.style.font.bold = True
                        if year is None:
                            ws.conditional_formatting.addCellIs(
                                get_column_letter(10) + str(row_num + 1), 'notEqual',
                                [str(producer_price)], True, wb,
                                None, None, yellowFill
                            )
                        c = ws.cell(row=row_num, column=10)
                        c.value = '=%s' % tax_producer_purchase
                        c.style.number_format.format_code = REPANIER_SETTINGS_CURRENCY_XLSX
                        row_num += 1
                        for col_num in range(14):
                            c = ws.cell(row=row_num, column=col_num)
Patrick's avatar
Patrick committed
289
                            c.style.borders.top.border_style = Border.BORDER_MEDIUMDASHED
Patrick's avatar
Patrick committed
290 291 292 293 294
                        row_num += 1
            else:
                if year is None:
                    # 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.
Patrick's avatar
Patrick committed
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
                    if customer is None:
                        purchases = Purchase.objects.filter(
                            permanence_id=permanence.id,
                            producer_id=producer.id,
                            offer_item__translations__language_code=translation.get_language()
                        ).order_by(  # "product__placement",
                            "offer_item__translations__preparation_sort_order",
                            "quantity_for_preparation_sort_order",
                            "customer__short_basket_name"
                        ).iterator()
                    else:
                        purchases = Purchase.objects.filter(
                            permanence_id=permanence.id,
                            customer_id=customer.id,
                            producer_id=producer.id,
                            offer_item__translations__language_code=translation.get_language()
                        ).order_by(  # "product__placement",
                            "offer_item__translations__preparation_sort_order",
                            "quantity_for_preparation_sort_order",
                            "customer__short_basket_name"
                        ).iterator()
Patrick's avatar
Patrick committed
316 317 318
                else:
                    if customer is None:
                        purchases = Purchase.objects.filter(
Patrick's avatar
Patrick committed
319
                            permanence__status__gte=PERMANENCE_INVOICED,
Patrick's avatar
Patrick committed
320 321 322 323 324 325 326 327 328 329 330 331
                            permanence_date__year=year,
                            producer_id=producer.id,
                            offer_item__translations__language_code=translation.get_language()
                        ).order_by(
                            "permanence_date",
                            "permanence_id",
                            "offer_item__translations__preparation_sort_order",
                            "quantity_for_preparation_sort_order",
                            "customer__short_basket_name"
                        ).iterator()
                    else:
                        purchases = Purchase.objects.filter(
Patrick's avatar
Patrick committed
332
                            permanence__status__gte=PERMANENCE_INVOICED,
Patrick's avatar
Patrick committed
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
                            permanence_date__year=year,
                            customer_id=customer.id,
                            producer_id=producer.id,
                            offer_item__translations__language_code=translation.get_language()
                        ).order_by(
                            "permanence_date",
                            "permanence_id",
                            "offer_item__translations__preparation_sort_order",
                            "quantity_for_preparation_sort_order"
                        ).iterator()
                purchase = next_purchase(purchases)
                while purchase is not None:
                    permanence_save = purchase.permanence
                    count_permanence_purchase = 0
                    row_start_permanence = 0
                    row_num += 1
                    while purchase is not None and permanence_save.id == purchase.permanence_id:
                        producer_save = purchase.producer
                        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 permanence_save.id == purchase.permanence_id \
                                and producer_save == purchase.producer \
                                and department_for_customer_save == purchase.offer_item.department_for_customer:
                            offer_item_save = purchase.offer_item
                            count_offer_item = 0
                            row_first_offer_item = row_num
                            offer_items_price = DECIMAL_ZERO
                            for col_num in range(14):
                                c = ws.cell(row=row_num, column=col_num)
Patrick's avatar
Patrick committed
363
                                c.style.borders.top.border_style = Border.BORDER_THIN
Patrick's avatar
Patrick committed
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 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
                            row_start_offer_item = 0
                            while purchase is not None and offer_item_save == purchase.offer_item:
                                c = ws.cell(row=row_num, column=1)
                                c.value = purchase.id
                                c = ws.cell(row=row_num, column=2)
                                c.value = permanence_save.permanence_date
                                c.style.number_format.format_code = NumberFormat.FORMAT_DATE_DDMMYYYY
                                c = ws.cell(row=row_num, column=3)
                                c.value = producer_save.short_profile_name
                                c.style.number_format.format_code = NumberFormat.FORMAT_TEXT
                                if count_offer_item == 0:
                                    row_start_offer_item = row_num + 1
                                    if count_permanence_purchase == 0:
                                        c.style.font.bold = True
                                        row_start_permanence = row_start_offer_item
                                    c = ws.cell(row=row_num, column=0)
                                    c.value = "A"
                                else:
                                    c = ws.cell(row=row_num, column=0)
                                    c.value = "B"
                                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
                                if count_offer_item != 0:
                                    c.style.font.color.index = 'FF939393'
                                c = ws.cell(row=row_num, column=5)
                                c.value = purchase.customer.short_basket_name
                                c.style.number_format.format_code = NumberFormat.FORMAT_TEXT
                                c = ws.cell(row=row_num, column=6)
                                c.value = purchase.quantity_invoiced
                                c.style.number_format.format_code = '#,##0.????'
                                if year is None:
                                    c.style.font.color = Color(Color.BLUE)
                                    ws.conditional_formatting.addCellIs(
                                        get_column_letter(7) + str(row_num + 1), 'notEqual',
                                        [str(purchase.quantity_invoiced)], True, wb,
                                        None, None, yellowFill
                                    )
                                c = ws.cell(row=row_num, column=7)
                                if count_offer_item == 0:
                                    producer_unit_price = purchase.get_producer_unit_price()
                                    c.value = producer_unit_price
                                    c.style.font.color = Color(Color.BLUE)
                                    ws.conditional_formatting.addCellIs(
                                        get_column_letter(8) + str(row_num + 1), 'notEqual',
                                        [str(producer_unit_price)], True, wb,
                                        None, None, yellowFill
                                    )
                                else:
                                    c.value = '=H%s' % (row_first_offer_item + 1)
                                c.style.number_format.format_code = REPANIER_SETTINGS_CURRENCY_XLSX
                                c = ws.cell(row=row_num, column=8)
                                c.value = purchase.offer_item.unit_deposit.amount
                                c.style.number_format.format_code = REPANIER_SETTINGS_CURRENCY_XLSX
                                c = ws.cell(row=row_num, column=9)
                                c.value = '=ROUND(G%s*(H%s+I%s),2)' % (row_num + 1, row_first_offer_item + 1, row_num + 1)
                                c.style.number_format.format_code = REPANIER_SETTINGS_CURRENCY_XLSX
                                if year is None:
                                    offer_item_price = (purchase.quantity_invoiced *
                                                        (purchase.get_producer_unit_price() +
                                                         purchase.get_unit_deposit())).quantize(
                                        TWO_DECIMALS)
                                    offer_items_price += offer_item_price
                                    if offer_item_save.order_unit in [
                                        PRODUCT_ORDER_UNIT_KG, PRODUCT_ORDER_UNIT_PC_KG,
                                        PRODUCT_ORDER_UNIT_LT
                                    ]:
                                        c.style.font.color = Color(Color.BLUE)
                                    ws.conditional_formatting.addCellIs(
                                        get_column_letter(10) + str(row_num + 1), 'notEqual',
                                        [str(offer_item_price)], True, wb,
                                        None, None, yellowFill
                                    )
                                c = ws.cell(row=row_num, column=10)
                                c.value = '=G%s*%s' % (row_num + 1, purchase.offer_item.customer_vat.amount)
                                c.style.number_format.format_code = REPANIER_SETTINGS_CURRENCY_XLSX
                                c = ws.cell(row=row_num, column=12)
                                c.value = cap(purchase.comment, 100)
                                c.style.number_format.format_code = NumberFormat.FORMAT_TEXT
                                c = ws.cell(row=row_num, column=13)
                                c.value = purchase.offer_item.get_vat_level_display()
                                c.style.number_format.format_code = NumberFormat.FORMAT_TEXT
Patrick's avatar
Patrick committed
450 451 452
                                c = ws.cell(row=row_num, column=14)
                                c.value = purchase.customer.user.email
                                c.style.number_format.format_code = NumberFormat.FORMAT_TEXT
Patrick's avatar
Patrick committed
453 454 455
                                delta = 5
                                for col_num in range(5):
                                    c = ws.cell(row=row_num, column=delta + col_num)
Patrick's avatar
Patrick committed
456
                                    c.style.borders.top.border_style = Border.BORDER_THIN
Patrick's avatar
Patrick committed
457 458 459 460 461 462 463 464 465 466 467

                                purchase = next_purchase(purchases)
                                row_num += 1
                                count_offer_item += 1

                            count_permanence_purchase += count_offer_item
                            if year is None and count_offer_item > 1:
                                if not offer_item_save.wrapped and offer_item_save.order_unit in [
                                    PRODUCT_ORDER_UNIT_KG, PRODUCT_ORDER_UNIT_PC_KG,
                                    PRODUCT_ORDER_UNIT_LT
                                ]:
Patrick's avatar
Patrick committed
468
                                    c = ws.cell(row=row_num - 1, column=11)
Patrick's avatar
Patrick committed
469 470 471 472
                                    c.value = '=SUM(J%s:J%s)' % (row_start_offer_item, row_num)
                                    c.style.number_format.format_code = REPANIER_SETTINGS_CURRENCY_XLSX
                                    c.style.font.color = Color(Color.BLUE)
                                    ws.conditional_formatting.addCellIs(
Patrick's avatar
Patrick committed
473
                                        get_column_letter(12) + str(row_num), 'notEqual',
Patrick's avatar
Patrick committed
474 475 476
                                        [str(offer_items_price)], True, wb,
                                        None, None, yellowFill
                                    )
Patrick's avatar
Patrick committed
477
                                    c = ws.cell(row=row_num - 1, column=0)
Patrick's avatar
Patrick committed
478
                                    c.value = "D"
Patrick's avatar
Patrick committed
479
                                    # row_num += 1
Patrick's avatar
Patrick committed
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

                            producer_price += offer_items_price

                    if count_permanence_purchase > 0:
                        count_all_purchase += count_permanence_purchase
                        purchase_price_producer_purchase = 'ROUND(SUM(J%s:J%s),2)' % (row_start_permanence, row_num)
                        purchase_price_all_purchase.append(purchase_price_producer_purchase)
                        tax_producer_purchase = 'SUM(K%s:K%s)' % (row_start_permanence, row_num)
                        tax_all_purchase.append(tax_producer_purchase)

                        row_num += 1
                        c = ws.cell(row=row_num, column=8)
                        c.value = "%s : %s %s" % (_("Total"), producer_save.short_profile_name, permanence_save)
                        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)
                        c.value = '=%s' % purchase_price_producer_purchase
                        c.style.number_format.format_code = REPANIER_SETTINGS_CURRENCY_XLSX
                        c.style.font.bold = True
                        if year is None:
                            ws.conditional_formatting.addCellIs(
                                get_column_letter(10) + str(row_num + 1), 'notEqual',
                                [str(producer_price)], True, wb,
                                None, None, yellowFill
                            )
                        c = ws.cell(row=row_num, column=10)
                        c.value = '=%s' % tax_producer_purchase
                        c.style.number_format.format_code = REPANIER_SETTINGS_CURRENCY_XLSX
                        row_num += 1
                        for col_num in range(14):
                            c = ws.cell(row=row_num, column=col_num)
Patrick's avatar
Patrick committed
512
                            c.style.borders.top.border_style = Border.BORDER_MEDIUMDASHED
Patrick's avatar
Patrick committed
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
                        row_num += 1
            producer = next_row(producers)

        if count_all_purchase > 0:
            row_num += 1
            c = ws.cell(row=row_num, column=8)
            c.value = "%s : %s" % (_('Total'), title1)
            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)
            c.value = '=%s' % "+".join(purchase_price_all_purchase)
            c.style.number_format.format_code = REPANIER_SETTINGS_CURRENCY_XLSX
            c.style.font.bold = True
            c = ws.cell(row=row_num, column=10)
            c.value = '=%s' % "+".join(tax_all_purchase)
            c.style.number_format.format_code = REPANIER_SETTINGS_CURRENCY_XLSX
            row_num += 1
            for col_num in range(14):
                c = ws.cell(row=row_num, column=col_num)
Patrick's avatar
Patrick committed
533
                c.style.borders.top.border_style = Border.BORDER_MEDIUMDASHED
Patrick's avatar
Patrick committed
534 535 536 537 538 539 540

        if year is None:
            ws.column_dimensions[get_column_letter(3)].visible = False
            ws.column_dimensions[get_column_letter(11)].visible = False
        else:
            ws.column_dimensions[get_column_letter(12)].visible = False
        ws.column_dimensions[get_column_letter(1)].visible = False
Patrick's avatar
Patrick committed
541
        ws.column_dimensions[get_column_letter(15)].visible = False
Patrick's avatar
Patrick committed
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559

    return wb


@transaction.atomic
def import_purchase_sheet(worksheet, permanence=None,
                          customer_2_id_dict=None,
                          producer_2_id_dict=None
                          ):
    error = False
    error_msg = None
    import_counter = 0
    header = get_header(worksheet)
    if header:
        row_num = 1
        array_purchase = []
        rule_of_3_source = DECIMAL_ZERO
        row = get_row(worksheet, header, row_num)
Patrick's avatar
Patrick committed
560
        getcontext().rounding = ROUND_HALF_UP
Patrick's avatar
Patrick committed
561 562 563
        while row and not error:
            try:
                row_format = row[_('Format')]
Patrick's avatar
Patrick committed
564
                if row_format in ["A", "B", "C", "D"]:
Patrick's avatar
Patrick committed
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
                    import_counter += 1
                    if row[_('Id')] is None:
                        error = True
                        error_msg = _("Row %(row_num)d : No purchase id given.") % {'row_num': row_num + 1}
                        break
                    row_id = Decimal(row[_('Id')])
                    purchase = Purchase.objects.filter(id=row_id).order_by('?').first()
                    if purchase is None:
                        error = True
                        error_msg = _("Row %(row_num)d : No purchase corresponding to the given purchase id.") % {
                            'row_num': row_num + 1}
                        break
                    if purchase.permanence_id != permanence.id:
                        error = True
                        error_msg = _("Row %(row_num)d : The given permanence doesn't own the given purchase id.") % {
                            'row_num': row_num + 1}
                        break
Patrick's avatar
Patrick committed
582 583 584 585 586 587
                    offer_item = OfferItem.objects.filter(id=purchase.offer_item_id).order_by('?').first()
                    if offer_item is None:
                        error = True
                        error_msg = _("Row %(row_num)d : No offer_item corresponding to the given purchase id.") % {
                            'row_num': row_num + 1}
                        break
Patrick's avatar
Patrick committed
588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
                    producer_id = None
                    if row[_('producer')] in producer_2_id_dict:
                        producer_id = producer_2_id_dict[row[_('producer')]]
                    if producer_id != purchase.producer_id:
                        error = True
                        error_msg = _("Row %(row_num)d : No valid producer.") % {'row_num': row_num + 1}
                        break
                    customer_name = "%s" % row[_('customer')]
                    if customer_name in customer_2_id_dict:
                        customer_id = customer_2_id_dict[customer_name]
                        if customer_id != purchase.customer_id:
                            error = True
                            error_msg = _("Row %(row_num)d : No valid customer") % {'row_num': row_num + 1}
                            break
                    comment = cap(row[_('comment')], 100)
Patrick's avatar
Patrick committed
603

Patrick's avatar
Patrick committed
604
                    quantity_has_been_modified = False
Patrick's avatar
Patrick committed
605

Patrick's avatar
Patrick committed
606
                    producer_row_price = row[_('purchase price')]
Patrick's avatar
Patrick committed
607 608 609
                    if producer_row_price is not None:
                        producer_row_price = Decimal(producer_row_price).quantize(TWO_DECIMALS)
                        if purchase.purchase_price.amount != producer_row_price:
Patrick's avatar
Patrick committed
610 611 612 613 614 615 616 617 618 619 620 621 622
                            quantity_has_been_modified = True
                            # Asked by GAC HAMOIS : sell broken products...
                            # if purchase.offer_item.order_unit in [
                            #     PRODUCT_ORDER_UNIT_KG, PRODUCT_ORDER_UNIT_PC_KG,
                            #     PRODUCT_ORDER_UNIT_LT
                            # ]:
                            producer_unit_price = (purchase.offer_item.producer_unit_price.amount +
                                                   purchase.offer_item.unit_deposit.amount).quantize(TWO_DECIMALS)
                            if producer_unit_price != DECIMAL_ZERO:
                                purchase.quantity_invoiced = (producer_row_price /
                                                              producer_unit_price).quantize(FOUR_DECIMALS)
                            else:
                                purchase.quantity_invoiced = DECIMAL_ZERO
Patrick's avatar
Patrick committed
623

Patrick's avatar
Patrick committed
624 625 626 627 628
                    if not quantity_has_been_modified:
                        quantity_invoiced = DECIMAL_ZERO if row[_('quantity invoiced')] is None \
                            else Decimal(row[_('quantity invoiced')]).quantize(FOUR_DECIMALS)
                        if purchase.quantity_invoiced != quantity_invoiced:
                            purchase.quantity_invoiced = quantity_invoiced
Patrick's avatar
Patrick committed
629 630 631 632

                    if row_format == "A":
                        array_purchase = []
                        rule_of_3_source = DECIMAL_ZERO
Patrick's avatar
Patrick committed
633 634 635 636 637 638
                        producer_unit_price = row[_('producer unit price')]
                        if producer_unit_price is not None and not purchase.producer.invoice_by_basket:
                            previous_producer_unit_price = purchase.get_producer_unit_price()
                            if producer_unit_price != previous_producer_unit_price:
                                offer_item.producer_unit_price = producer_unit_price
                                offer_item.save()
Patrick's avatar
Patrick committed
639

Patrick's avatar
Patrick committed
640 641 642
                    purchase.comment = comment
                    purchase.save()
                    rule_of_3_source += purchase.purchase_price.amount
Patrick's avatar
Patrick committed
643
                    array_purchase.append(purchase)
Patrick's avatar
Patrick committed
644

Patrick's avatar
Patrick committed
645
                if row_format in ["C", "D"]:
Patrick's avatar
Patrick committed
646 647 648
                    rule_of_3_target = row[_('rule of 3')]
                    if rule_of_3_target is not None:
                        rule_of_3_target = Decimal(rule_of_3_target).quantize(TWO_DECIMALS)
649
                        # print(rule_of_3_target)
Patrick's avatar
Patrick committed
650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668
                        if rule_of_3_target != rule_of_3_source:
                            max_purchase_counter = len(array_purchase)
                            if max_purchase_counter <= 1:
                                error = True
                                error_msg = _("Row %(row_num)d : Rule of 3 target in wrong context.") % {
                                    'row_num': row_num + 1}
                                return error, error_msg
                            else:
                                if rule_of_3_source != DECIMAL_ZERO:
                                    ratio = rule_of_3_target / rule_of_3_source
                                else:
                                    if rule_of_3_target == DECIMAL_ZERO:
                                        ratio = DECIMAL_ZERO
                                    else:
                                        ratio = DECIMAL_ONE
                                # Rule of 3
                                if ratio != DECIMAL_ONE:
                                    adjusted_invoice = DECIMAL_ZERO
                                    for i, purchase in enumerate(array_purchase, start=1):
Patrick's avatar
Patrick committed
669
                                        producer_unit_price = purchase.offer_item.producer_unit_price.amount
Patrick's avatar
Patrick committed
670 671 672 673 674 675 676 677 678 679
                                        if i == max_purchase_counter:
                                            delta = rule_of_3_target - adjusted_invoice
                                            if producer_unit_price != DECIMAL_ZERO:
                                                purchase.quantity_invoiced = (delta / producer_unit_price).quantize(
                                                    FOUR_DECIMALS)
                                            else:
                                                purchase.quantity_invoiced = DECIMAL_ZERO
                                        else:
                                            purchase.quantity_invoiced = (purchase.quantity_invoiced * ratio).quantize(
                                                FOUR_DECIMALS)
Patrick's avatar
Patrick committed
680 681
                                            adjusted_invoice += (
                                                purchase.quantity_invoiced * producer_unit_price).quantize(TWO_DECIMALS)
Patrick's avatar
Patrick committed
682 683 684 685 686
                                        purchase.save()

                row_num += 1
                row = get_row(worksheet, header, row_num)

Patrick's avatar
Patrick committed
687
            except KeyError as e:
Patrick's avatar
Patrick committed
688 689 690 691
                # Missing field
                error = True
                error_msg = _("Row %(row_num)d : A required column is missing %(error_msg)s.") % {
                    'row_num': row_num + 1, 'error_msg': str(e)}
Patrick's avatar
Patrick committed
692
            except Exception as e:
Patrick's avatar
Patrick committed
693 694
                error = True
                error_msg = _("Row %(row_num)d : %(error_msg)s.") % {'row_num': row_num + 1, 'error_msg': str(e)}
Patrick's avatar
Patrick committed
695

Patrick's avatar
Patrick committed
696 697 698
    if import_counter == 0:
        error = True
        error_msg = "%s" % _("Nothing to import.")
Patrick's avatar
Patrick committed
699 700 701 702 703
    # if not error:
    #     recalculate_order_amount(
    #         permanence_id=permanence.id,
    #         re_init=True
    #     )
Patrick's avatar
Patrick committed
704 705 706
    return error, error_msg


Patrick's avatar
Patrick committed
707
def handle_uploaded_purchase(request, permanences, file_to_import, *args):
Patrick's avatar
Patrick committed
708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
    error = False
    error_msg = None
    wb = load_workbook(file_to_import)
    # dict for performance optimisation purpose : read the DB only once
    customer_buyinggroup_id, customer_2_id_dict = get_customer_2_id_dict()
    producer_buyinggroup_id, producer_2_id_dict = get_producer_2_id_dict()
    if customer_buyinggroup_id is None:
        error = True
        error_msg = _("At least one customer must represent the buying group.")
    else:
        if producer_buyinggroup_id is None:
            error = True
            error_msg = _("At least one producer must represent the buying group.")

    if not error:
        permanence = permanences.first()
        if permanence is not None:
            if permanence.status == PERMANENCE_SEND:
Patrick's avatar
Patrick committed
726
                ws = wb.get_sheet_by_name(cap(slugify("%s" % (permanence)), 31))
Patrick's avatar
Patrick committed
727 728 729 730 731 732
                error, error_msg = import_purchase_sheet(
                    ws, permanence=permanence,
                    customer_2_id_dict=customer_2_id_dict,
                    producer_2_id_dict=producer_2_id_dict
                )
                if error:
Patrick's avatar
Patrick committed
733
                    error_msg = cap(slugify("%s" % (permanence)), 31) + " > " + error_msg
Patrick's avatar
Patrick committed
734 735 736 737 738 739 740
            else:
                error = True
                error_msg = _("The permanence has already been invoiced.")
        else:
            error = True
            error_msg = _("The permanence doesn't exists.")
    return error, error_msg