admin.py 116 KB
Newer Older
Patrick's avatar
Patrick committed
1 2 3
# -*- coding: utf-8
from __future__ import unicode_literals
from collections import OrderedDict
Patrick Colmant's avatar
Patrick Colmant committed
4
from os import sep as os_sep
pi's avatar
pi committed
5
import uuid
6
from django.contrib.auth.models import User
Patrick's avatar
Patrick committed
7
from django.forms import Textarea
8 9 10
from import_export import resources, fields
from import_export.admin import ImportExportMixin, ExportMixin
from import_export.widgets import DateWidget, ForeignKeyWidget
Patrick's avatar
Patrick committed
11 12
import parler
from fkey_choice_cache_mixin import ForeignKeyCacheMixin
13
from repanier.email.email_alert import send_sms
Patrick's avatar
Patrick committed
14
from widget import SelectAdminOrderUnitWidget, PreviewProductOrderWidget
15 16 17
from xlsx.widget import TwoDecimalsWidget, TranslatedForeignKeyWidget, ThreeDecimalsWidget, OneToOneWidget, \
    DecimalBooleanWidget, FourDecimalsWidget, ZeroDecimalsWidget, IdWidget
from xlsx.widget import ChoiceWidget
18

Patrick's avatar
Patrick committed
19 20 21 22
try:
    from urllib.parse import parse_qsl
except ImportError:
    from urlparse import parse_qsl
23

Patrick's avatar
Patrick committed
24
from re import compile
pi's avatar
pi committed
25
from tools import *
26
from admin_filter import *
Patrick Colmant's avatar
Patrick Colmant committed
27
from django.contrib import admin
Patrick's avatar
Patrick committed
28
from django.contrib import messages
Patrick Colmant's avatar
Patrick Colmant committed
29
from django.contrib.auth import get_user_model
Patrick's avatar
Patrick committed
30
import datetime
Patrick Colmant's avatar
Patrick Colmant committed
31
from django.utils.translation import ugettext_lazy as _
32
from django.utils import translation
33
from django.utils import timezone
34
from django.core import validators
35
from django.db.models import Q, F
36
from django import forms
37
from django.db import transaction
38 39 40
from django_mptt_admin.admin import DjangoMpttAdmin

from parler.admin import TranslatableAdmin, TranslatableModelForm
Patrick Colmant's avatar
Patrick Colmant committed
41

Patrick Colmant's avatar
Patrick Colmant committed
42
from models import LUT_ProductionMode, OfferItemSend, PurchaseSendForUpdate, \
43
    PurchaseOpenedOrClosedForUpdate, CustomerSend, OfferItemClosed, CustomerInvoice, ProducerInvoice, PurchaseInvoiced
Patrick's avatar
Patrick committed
44
from models import Configuration
Patrick's avatar
Patrick committed
45 46
from models import LUT_DepartmentForCustomer
from models import LUT_PermanenceRole
Patrick's avatar
Patrick committed
47
from models import LUT_DeliveryPoint
Patrick's avatar
Patrick committed
48 49 50 51 52 53 54 55 56 57 58 59 60 61

from models import Producer
from models import Permanence
from models import Customer
from models import Staff
from models import Product
from models import PermanenceBoard
from models import OfferItem
from models import PermanenceInPreparation
from models import PermanenceDone
from models import Purchase
from models import BankAccount
from views import render_response

62 63 64 65 66 67
from xlsx import xslx_offer
from xlsx import xslx_order
from xlsx import xslx_product
from xlsx import xslx_invoice
from xlsx import xslx_purchase
from xlsx import xslx_stock
pi's avatar
pi committed
68

Patrick's avatar
Patrick committed
69 70 71 72 73
from task import task_invoice
from task import task_order
from task import task_product
from task import task_purchase

Patrick Colmant's avatar
Patrick Colmant committed
74 75

# LUT
76
class LUTProductionModeAdmin(TranslatableAdmin, DjangoMpttAdmin):
77 78 79 80
    list_display = ('short_name', 'is_active')
    list_display_links = ('short_name',)
    list_per_page = 17
    list_max_show_all = 17
Patrick Colmant's avatar
Patrick Colmant committed
81
    exclude = ('picture',)
82

Patrick Colmant's avatar
Patrick Colmant committed
83

Patrick's avatar
Patrick committed
84
admin.site.register(LUT_ProductionMode, LUTProductionModeAdmin)
Patrick Colmant's avatar
Patrick Colmant committed
85

86

Patrick's avatar
Patrick committed
87 88 89 90 91 92 93 94 95 96
class LUTDeliveryPointAdmin(TranslatableAdmin, DjangoMpttAdmin):
    list_display = ('short_name', 'is_active')
    list_display_links = ('short_name',)
    list_per_page = 17
    list_max_show_all = 17


admin.site.register(LUT_DeliveryPoint, LUTDeliveryPointAdmin)


97
class LUTDepartmentForCustomerAdmin(TranslatableAdmin, DjangoMpttAdmin):
98 99 100 101 102
    list_display = ('short_name', 'is_active')
    list_display_links = ('short_name',)
    list_per_page = 17
    list_max_show_all = 17

Patrick Colmant's avatar
Patrick Colmant committed
103

Patrick's avatar
Patrick committed
104
admin.site.register(LUT_DepartmentForCustomer, LUTDepartmentForCustomerAdmin)
Patrick Colmant's avatar
Patrick Colmant committed
105

106

107
class LUTPermanenceRoleAdmin(TranslatableAdmin, DjangoMpttAdmin):
108 109 110 111 112
    list_display = ('short_name', 'is_active')
    list_display_links = ('short_name',)
    list_per_page = 17
    list_max_show_all = 17

113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
    def get_fields(self, request, obj=None):
        if apps.REPANIER_SETTINGS_DELIVERY_POINT:
            return [
                ('parent',),
                ('delivery_points'),
                ('is_active'),
                ('short_name'),
                ('description',)
            ]
        else:
            return [
                ('parent',),
                ('is_active'),
                ('short_name'),
                ('description',)
            ]

Patrick Colmant's avatar
Patrick Colmant committed
130

Patrick's avatar
Patrick committed
131
admin.site.register(LUT_PermanenceRole, LUTPermanenceRoleAdmin)
Patrick Colmant's avatar
Patrick Colmant committed
132

133

134 135
class ConfigurationDataForm(TranslatableModelForm):
    # preview_product_order = forms.CharField(label="", widget=PreviewProductOrderWidget)
Patrick's avatar
Patrick committed
136

137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
    def __init__(self, *args, **kwargs):
        super(ConfigurationDataForm, self).__init__(*args, **kwargs)

    def clean(self):
        cleaned_data = super(ConfigurationDataForm, self).clean()
        send_order_mail_to_customer = self.cleaned_data["send_order_mail_to_customer"]
        send_abstract_order_mail_to_customer = self.cleaned_data["send_abstract_order_mail_to_customer"]
        if send_abstract_order_mail_to_customer and not send_order_mail_to_customer:
            self.add_error(
                'send_abstract_order_mail_to_customer',
                _('The abstract can only be send if the order is also send to customer'))
        send_order_mail_to_producer = self.cleaned_data["send_order_mail_to_producer"]
        send_abstract_order_mail_to_producer = self.cleaned_data["send_abstract_order_mail_to_producer"]
        if send_abstract_order_mail_to_producer and not send_order_mail_to_producer:
            self.add_error(
                'send_abstract_order_mail_to_customer',
                _('The abstract can only be send if the order is also send to producer'))

        return cleaned_data
Patrick's avatar
Patrick committed
156 157 158


class ConfigurationAdmin(TranslatableAdmin):
159
    form = ConfigurationDataForm
Patrick's avatar
Patrick committed
160 161 162 163 164 165
    fieldsets = [
        (None, {
            'fields':
                (('test_mode', 'group_name', 'name'),
                'display_anonymous_order_form',
                ('display_producer_on_order_form', 'max_week_wo_participation'),
166
                ('invoice', 'bank_account', 'vat_id')),
Patrick's avatar
Patrick committed
167 168 169 170 171 172 173 174 175 176 177 178
        }),
        (_('Opening mails'), {
            'classes': ('collapse',),
            'fields':
                (
                    'send_opening_mail_to_customer', 'offer_customer_mail',
                ),
        }),
        (_('Ordering mails'), {
            'classes': ('collapse',),
            'fields':
                (
179 180
                    'send_order_mail_to_customer', 'send_abstract_order_mail_to_customer', 'order_customer_mail',
                    'send_order_mail_to_producer', 'send_abstract_order_mail_to_producer', 'order_producer_mail',
Patrick's avatar
Patrick committed
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
                    'send_order_mail_to_board', 'order_staff_mail',
                ),
        }),
        (_('Invoicing mails'), {
            'classes': ('collapse',),
            'fields':
                (
                    'send_invoice_mail_to_customer', 'invoice_customer_mail',
                    'send_invoice_mail_to_producer', 'invoice_producer_mail',
                    # 'invoice_staff_mail',
                ),
        }),
        (_('Advanced options'), {
            'classes': ('collapse',),
            'fields':
196 197 198 199 200
                # (('accept_child_group', 'delivery_point'),
                ('delivery_point',
                ('page_break_on_customer_check', 'display_vat'),
                # ('stock', 'producer_order_rounded',),
                'offer_producer_mail'),
Patrick's avatar
Patrick committed
201 202 203
        }),
        ]

204 205 206 207 208 209
    def has_add_permission(self, request):
        return False

    def has_delete_permission(self, request, obj=None):
        return False

Patrick's avatar
Patrick committed
210
    def get_readonly_fields(self, request, configuration=None):
211 212 213 214 215 216
        permanence = Permanence.objects.all().order_by()
        is_coordinator = request.user.is_superuser or Staff.objects.filter(
            id=request.user.staff.id, is_coordinator=True, is_active=True
        ).order_by().first() is not None

        if is_coordinator or permanence.first() is None:
Patrick's avatar
Patrick committed
217 218 219 220 221 222 223 224
            return []
        else:
            return ['bank_account']


admin.site.register(Configuration, ConfigurationAdmin)


225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
# Custom Producer
class ProducerResource(resources.ModelResource):
    id = fields.Field(attribute='id', widget=IdWidget(), readonly=True)
    price_list_multiplier = fields.Field(attribute='price_list_multiplier', widget=TwoDecimalsWidget())
    vat_level = fields.Field(attribute='vat_level', widget=ChoiceWidget(LUT_VAT, LUT_VAT_REVERSE))
    date_balance = fields.Field(attribute='date_balance', widget=DateWidget(format='%d-%m-%Y'), readonly=True)
    balance = fields.Field(attribute='balance', widget=TwoDecimalsWidget(), readonly=True)
    invoice_by_basket = fields.Field(attribute='invoice_by_basket', widget=DecimalBooleanWidget())
    manage_stock = fields.Field(attribute='manage_stock', widget=DecimalBooleanWidget())
    is_resale_price_fixed = fields.Field(attribute='is_resale_price_fixed', widget=DecimalBooleanWidget())
    represent_this_buyinggroup = fields.Field(attribute='represent_this_buyinggroup', widget=DecimalBooleanWidget())
    is_active = fields.Field(attribute='is_active', widget=DecimalBooleanWidget())

    def before_save_instance(self, instance, dry_run):
        """
        Override to add additional logic.
        """
        if instance.id is not None:
            producer = Producer.objects.filter(short_profile_name=instance.short_profile_name).exclude(id=instance.id).order_by().only('id')
            if producer.exists():
                raise ValueError(_("The short_basket_name %s is already used by another producer.") % instance.short_profile_name)

    class Meta:
        model = Producer
        fields = (
            'id', 'short_profile_name', 'long_profile_name',
            'email', 'language', 'phone1', 'phone2',
            'fax', 'address', 'invoice_by_basket', 'manage_stock',
            'producer_pre_opening', 'producer_price_are_wo_vat', 'vat_level',
            'price_list_multiplier', 'is_resale_price_fixed',
            'date_balance', 'balance', 'represent_this_buyinggroup', 'is_active'
        )
        export_order = fields
        import_id_fields = ('id',)
        skip_unchanged = True
        report_skipped = False
        use_transactions = False

Patrick's avatar
Patrick committed
263

264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
def create__producer_action(year):
    def action(modeladmin, request, queryset):
        queryset = queryset.order_by()
        return xslx_purchase.admin_export_in(year, queryset)

    name = "export_producer_%d" % (year,)
    return (name, (action, name, _("Export purchases of %s") % (year,)))


class ProducerDataForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(ProducerDataForm, self).__init__(*args, **kwargs)

    def clean(self):
        cleaned_data = super(ProducerDataForm, self).clean()
        if 'producer_pre_opening' in self.cleaned_data:
            producer_pre_opening = self.cleaned_data["producer_pre_opening"]
        else:
            producer_pre_opening = False
        manage_stock = self.cleaned_data["manage_stock"]
        if manage_stock and producer_pre_opening:
            # The producer set his stock -> no possibility to manage stock
            self.add_error('producer_pre_opening', _("Either 'manage stock' or 'producer pre opening' may be set. Not both."))
            self.add_error('manage_stock', _("Either 'manage stock' or 'producer pre opening' may be set. Not both."))
        invoice_by_basket = self.cleaned_data["invoice_by_basket"]
        if manage_stock and invoice_by_basket:
            # The group manage the stock -> no possibility for the producer to prepare basket
            self.add_error('invoice_by_basket', _("Either 'manage stock' or 'invoice by basket' may be set. Not both."))
            self.add_error('manage_stock', _("Either 'manage stock' or 'invoice by basket' may be set. Not both."))
        is_resale_price_fixed = self.cleaned_data["is_resale_price_fixed"]
        if is_resale_price_fixed and producer_pre_opening:
            # The producer set his price -> no possibility to fix the resale price
            self.add_error('producer_pre_opening', _("Either 'is resale price fixed' or 'producer pre opening' may be set. Not both."))
            self.add_error('is_resale_price_fixed', _("Either 'is resale price fixed' or 'producer pre opening' may be set. Not both."))
        return cleaned_data


class ProducerAdmin(ImportExportMixin, admin.ModelAdmin):

    form=ProducerDataForm
    resource_class = ProducerResource
306
    search_fields = ('short_profile_name', 'email')
307
    # list_display = ('short_profile_name', 'get_products', 'get_balance', 'phone1', 'email', 'manage_stock', 'is_active')
308 309
    list_per_page = 17
    list_max_show_all = 17
Patrick's avatar
Patrick committed
310
    list_filter = ('is_active', 'invoice_by_basket', 'manage_stock', 'is_resale_price_fixed')
311 312
    # actions = ['export_xlsx_producer_prices', 'export_xlsx_customer_prices', 'import_xlsx', 'recalculate_prices']
    actions = ['recalculate_prices']
313

Patrick Colmant's avatar
Patrick Colmant committed
314 315 316 317 318 319 320 321
    def export_xlsx_producer_prices(self, request, queryset):
        return xslx_product.admin_export(request, queryset, producer_prices=True)

    export_xlsx_producer_prices.short_description = _(
        "Export products of selected producer(s) as XSLX file at procuder's pices")

    def export_xlsx_customer_prices(self, request, queryset):
        return xslx_product.admin_export(request, queryset, producer_prices=False)
322

Patrick Colmant's avatar
Patrick Colmant committed
323 324
    export_xlsx_customer_prices.short_description = _(
        "Export products of selected producer(s) as XSLX file at customer's prices")
325 326

    def import_xlsx(self, request, queryset):
Patrick's avatar
Patrick committed
327
        return xslx_product.admin_import(self, admin, request, queryset, action='import_xlsx')
328 329 330

    import_xlsx.short_description = _("Import products of selected producer(s) from a XLSX file")

Patrick's avatar
Patrick committed
331 332 333 334 335 336 337
    def recalculate_prices(self, request, queryset):
        for producer in queryset:
            for product in Product.objects.filter(producer_id=producer.id).order_by():
                product.save()
                for permanence in Permanence.objects.filter(
                        status__in=[PERMANENCE_CLOSED, PERMANENCE_SEND]
                ):
338 339 340 341 342
                    offer_item_queryset = OfferItem.objects.filter(
                        permanence_id=permanence.id,
                        product_id=product.id,
                        is_active=True
                    ).order_by()
Patrick's avatar
Patrick committed
343 344 345 346 347 348 349 350 351 352 353 354
                    clean_offer_item(permanence, offer_item_queryset, reorder=False)
                    recalculate_order_amount(permanence_id=permanence.id,
                                             permanence_status=permanence.status,
                                             offer_item_queryset=offer_item_queryset,
                                             send_to_producer=False)

        self.message_user(request, _("The prices have been recalculated."), level=messages.INFO)

    recalculate_prices.short_description = _('recalculate prices')

    def get_actions(self, request):
        actions = super(ProducerAdmin, self).get_actions(request)
355
        this_year = timezone.now().year
Patrick's avatar
Patrick committed
356 357 358 359
        actions.update(OrderedDict(create__producer_action(y) for y in [this_year, this_year-1, this_year-2]))
        return actions

    def get_list_display(self, request):
360
        return ('short_profile_name', 'get_products', 'get_balance', 'phone1', 'email', 'producer_pre_opening', 'manage_stock')
Patrick's avatar
Patrick committed
361 362 363 364 365 366 367

    def get_fields(self, request, producer=None):
        fields = [
            ('short_profile_name', 'long_profile_name', 'language'),
            ('email', 'fax'),
            ('phone1', 'phone2',)
        ]
368
        if apps.REPANIER_SETTINGS_DISPLAY_VAT:
Patrick's avatar
Patrick committed
369 370
            fields += [
                ('price_list_multiplier', 'is_resale_price_fixed'),
371
                ('producer_price_are_wo_vat', 'vat_level', 'vat_id'),
Patrick's avatar
Patrick committed
372 373 374
            ]
        else:
            fields += [
375
                ('price_list_multiplier', 'is_resale_price_fixed'),
Patrick's avatar
Patrick committed
376
            ]
377 378 379
        fields += [
            ('invoice_by_basket', 'manage_stock', 'producer_pre_opening'),
        ]
Patrick's avatar
Patrick committed
380 381 382
        fields += [
            ('address', 'memo'),
        ]
383
        if apps.REPANIER_SETTINGS_INVOICE:
Patrick's avatar
Patrick committed
384 385 386 387 388 389 390 391 392
            fields += [
                ('initial_balance', 'date_balance', 'balance', 'represent_this_buyinggroup'),
            ]
        fields += [
            ('is_active', 'uuid')
        ]
        return fields

    def get_readonly_fields(self, request, producer=None):
393
        if apps.REPANIER_SETTINGS_INVOICE:
Patrick's avatar
Patrick committed
394 395 396 397 398 399 400 401 402 403 404 405
            if producer is not None:
                producer_invoice = ProducerInvoice.objects.filter(producer_id=producer.id).order_by().first()
                if producer_invoice is not None:
                    # Do not modify the initial balance, an invoice already exist
                    return ['represent_this_buyinggroup', 'date_balance', 'balance', 'uuid', 'initial_balance']
                else:
                    return ['represent_this_buyinggroup', 'date_balance', 'balance', 'uuid']
            else:
                return ['uuid',]
        else:
            return ['represent_this_buyinggroup', 'uuid',]

pi's avatar
pi committed
406 407 408

admin.site.register(Producer, ProducerAdmin)

Patrick's avatar
Patrick committed
409

410 411
# Custom User
class UserDataForm(forms.ModelForm):
412 413 414 415 416
    username = forms.CharField(label=_('Username'), max_length=30,
                               help_text=_(
                                   'Required. 30 characters or fewer. Letters, numbers and @/./+/-/_ characters'
                               ),
                               validators=[
Patrick's avatar
Patrick committed
417
                                   validators.RegexValidator(compile('^[\w.@+-]+$'), _('Enter a valid username.'),
418 419 420 421 422 423 424 425
                                                             'invalid')
                               ])
    email = forms.EmailField(label=_('Email'))
    user = None

    def __init__(self, *args, **kwargs):
        super(UserDataForm, self).__init__(*args, **kwargs)

Patrick's avatar
Patrick committed
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
    def clean_phone1(self):
        i = 0
        k = 0
        phone1 = self.cleaned_data['phone1']
        while i < len(phone1):
            if '0' <= phone1[i] <= '9':
                k += 1
            if k == 4:
                break
            i += 1
        if k < 4:
            self.add_error(
                'phone1',
                _('The phone number must ends with 4 digits, eventually separated'))
        return phone1

    def clean(self):
        cleaned_data = super(UserDataForm, self).clean()
444
        # The Staff has no first_name or last_name because it's a function with login/pwd.
Patrick's avatar
Patrick committed
445
        # A Customer with a first_name and last_name is responsible of this function.
Patrick's avatar
Patrick committed
446 447
        is_customer_form = 'short_basket_name' in self.fields
        is_staff_form = not is_customer_form
448 449 450 451 452 453
        username_field_name = 'username'
        initial_username = None
        try:
            initial_username = self.instance.user.username
        except:
            pass
Patrick's avatar
Patrick committed
454
        if is_customer_form:
455 456 457 458 459
            # Customer
            username_field_name = 'short_basket_name'
        username = self.cleaned_data.get(username_field_name)
        user_error1 = _('The given username must be set')
        user_error2 = _('The given username is used by another user')
Patrick's avatar
Patrick committed
460
        if is_customer_form:
461 462 463 464 465 466
            user_error1 = _('The given short_basket_name must be set')
            user_error2 = _('The given short_basket_name is used by another user')
            if 'username' in self._errors:
                del self._errors['username']
            self.data['username'] = username
        if not username:
Patrick's avatar
Patrick committed
467
            self.add_error(username_field_name, user_error1)
468
        # Check that the email is set
Patrick's avatar
Patrick committed
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
        if not "email" in self.cleaned_data:
            self.add_error('email', _('The given email must be set'))
        else:
            email = self.cleaned_data["email"]
            if is_staff_form:
                is_reply_to_order_email = self.cleaned_data["is_reply_to_order_email"]
                is_reply_to_invoice_email = self.cleaned_data["is_reply_to_invoice_email"]
                if is_reply_to_order_email or is_reply_to_invoice_email:
                    allowed_mail_extension = get_allowed_mail_extension()
                    if not email.endswith(allowed_mail_extension):
                        self.add_error(
                            'email',
                            _('The given email must end with %(allowed_extension)s') %
                                 {'allowed_extension': allowed_mail_extension}
                        )
            user_model = get_user_model()
            user = user_model.objects.filter(email=email).order_by("id").first()
            # Check that the username is not already used
            if user is not None:
                if initial_username != user.username:
                    self.add_error('email', _('The given email is used by another user'))
            user = user_model.objects.filter(username=username).order_by("id").first()
            if user is not None:
                if initial_username != user.username:
                    self.add_error(username_field_name, user_error2)
494 495 496 497
        return cleaned_data

    def save(self, *args, **kwargs):
        super(UserDataForm, self).save(*args, **kwargs)
Patrick's avatar
Patrick committed
498
        change = (self.instance.id is not None)
499
        username = self.data['username']
Patrick's avatar
Patrick committed
500 501 502 503 504
        email = self.data['email'].lower()
        user_model = get_user_model()
        if change:
            user = user_model.objects.get(id=self.instance.user_id)
            user.username = username
505 506
            user.first_name = ""
            user.last_name = username
Patrick's avatar
Patrick committed
507 508 509 510 511 512
            user.email = email
            user.save()
        else:
            user = user_model.objects.create_user(
                username=username, email=email, password=uuid.uuid1().hex,
                first_name="", last_name=username)
513 514
        self.user = user
        return self.instance
515

Patrick Colmant's avatar
Patrick Colmant committed
516 517

# Customer
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576
class CustomerResource(resources.ModelResource):
    id = fields.Field(attribute='id', widget=IdWidget(), readonly=True)
    email = fields.Field(attribute='user', widget=OneToOneWidget(User, 'email'), readonly=False)
    delivery_point = fields.Field(attribute='delivery_point', widget=TranslatedForeignKeyWidget(LUT_DeliveryPoint, 'short_name'))
    date_balance = fields.Field(attribute='date_balance', widget=DateWidget(format='%d-%m-%Y'), readonly=True)
    balance = fields.Field(attribute='balance', widget=TwoDecimalsWidget(), readonly=True)
    may_order = fields.Field(attribute='may_order', widget=DecimalBooleanWidget())
    is_active = fields.Field(attribute='is_active', widget=DecimalBooleanWidget())
    purchase = fields.Field(attribute='get_purchase', widget=ZeroDecimalsWidget(), readonly=True)
    participation = fields.Field(attribute='get_participation', widget=ZeroDecimalsWidget(), readonly=True)

    def before_save_instance(self, instance, dry_run):
        """
        Override to add additional logic.
        """
        user_model = get_user_model()
        if instance.id is not None:
            customer = Customer.objects.filter(id=instance.id).order_by().only('id', 'user_id').first()
            user = user_model.objects.filter(email=instance.user.email).exclude(id=customer.user_id).order_by().only('id')
        else:
            user = user_model.objects.filter(email=instance.user.email).order_by().only('id')
        if user.exists():
            raise ValueError(_("The email %s is already used by another user.") % instance.user.email)
        if instance.id is not None:
            user = user_model.objects.filter(username=instance.short_basket_name).exclude(id=customer.user_id).order_by().only('id')
        else:
            user = user_model.objects.filter(username=instance.short_basket_name).order_by().only('id')
        if user.exists():
            raise ValueError(_("The short_basket_name %s is already used by another user.") % instance.short_basket_name)
        if not dry_run:
            if instance.id is not None:
                email = instance.user.email
                instance.user = user_model.objects.get(id=customer.user_id)
                instance.user.username = instance.short_basket_name
                instance.user.first_name = ""
                instance.user.last_name = instance.short_basket_name
                instance.user.email = email
                instance.user.save()
            else:
                instance.user = user_model.objects.create_user(
                    username=instance.short_basket_name, email=instance.user.email, password=uuid.uuid1().hex,
                    first_name="", last_name=instance.short_basket_name)
                instance.user_id = instance.user.id

    class Meta:
        model = Customer
        fields = (
            'id', 'short_basket_name', 'long_basket_name', 'email',
            'email2', 'language', 'delivery_point',
            'phone1', 'phone2', 'address', 'city',
            'date_balance', 'balance', 'may_order', 'is_active', 'participation', 'purchase'
        )
        export_order = fields
        import_id_fields = ('id',)
        skip_unchanged = True
        report_skipped = False
        use_transactions = False


577
class CustomerWithUserDataForm(UserDataForm):
Patrick's avatar
Patrick committed
578

579
    class Meta:
Patrick's avatar
Patrick committed
580
        widgets = {
581 582
            'address': Textarea(attrs={'rows': 4, 'cols': 80, 'style': 'height: 5em; width: 30em;'}),
            'memo': Textarea(attrs={'rows': 4, 'cols': 160, 'style': 'height: 5em; width: 60em;'}),
Patrick's avatar
Patrick committed
583
        }
584
        model = Customer
Patrick's avatar
Patrick committed
585
        fields = "__all__"
586 587


588 589 590 591 592
class CustomerWithUserDataAdmin(ImportExportMixin, admin.ModelAdmin):
    # http://stackoverflow.com/questions/17919361/how-can-i-add-a-button-into-django-admin-change-list-view-page
    # class Media:
    #     js = ('js/adminfix.js', )

593
    form = CustomerWithUserDataForm
594
    resource_class = CustomerResource
595
    list_display = (
Patrick's avatar
Patrick committed
596 597 598
        'short_basket_name', 'get_balance', 'may_order', 'long_basket_name', 'phone1', 'get_email',
        'get_last_login')
    search_fields = ('short_basket_name', 'long_basket_name', 'user__email', 'email2')
599 600
    list_per_page = 17
    list_max_show_all = 17
601
    list_filter = ('is_active', 'may_order', 'delivery_point')
602

Patrick's avatar
Patrick committed
603 604 605
    def get_email(self, customer):
        if customer.user is not None:
            return customer.user.email
606 607 608 609
        else:
            return ''

    get_email.short_description = _("email")
Patrick's avatar
Patrick committed
610
    get_email.admin_order_field = 'user__email'
611

Patrick's avatar
Patrick committed
612 613 614 615 616 617 618 619 620
    def get_date_joined(self, customer):
        if customer.user is not None:
            return customer.user.date_joined.strftime('%d-%m-%Y')
        else:
            return ''

    get_date_joined.short_description = _("date joined")

    def get_last_login(self, customer):
621
        if customer.user is not None and customer.user.last_login is not None:
Patrick's avatar
Patrick committed
622 623 624 625 626 627 628 629 630 631 632 633 634
            return customer.user.last_login.strftime('%d-%m-%Y')
        else:
            return ''

    get_last_login.short_description = _("last login")
    get_last_login.admin_order_field = 'user__last_login'

    def get_fields(self, request, customer=None):
        fields = [
            ('short_basket_name', 'long_basket_name', 'language'),
            ('email', 'email2', 'accept_mails_from_members'),
            ('phone1', 'phone2', 'accept_phone_call_from_members'),
        ]
635
        if apps.REPANIER_SETTINGS_DELIVERY_POINT:
Patrick's avatar
Patrick committed
636 637 638
            fields += [
                ('delivery_point',),
            ]
639 640 641
        fields += [
            ('vat_id',),
        ]
Patrick Colmant's avatar
Patrick Colmant committed
642 643 644 645 646 647 648 649 650 651 652 653
        if customer is not None:
            fields += [
                ('address', 'city', 'picture'),
                'memo',
            ]
        else:
            # Do not accept the picture because there is no customer.id for the "upload_to"
            fields += [
                ('address', 'city'),
                'memo',
            ]

654
        if apps.REPANIER_SETTINGS_INVOICE:
Patrick's avatar
Patrick committed
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671
            if customer is not None:
                customer_invoice = CustomerInvoice.objects.filter(customer_id=customer.id).order_by().first()
                if customer_invoice is not None:
                    # Do not modify the initial balance, an invoice already exist
                    fields += [
                        ('date_balance', 'balance', 'represent_this_buyinggroup'),
                    ]
                else:
                    fields += [
                        ('initial_balance', 'represent_this_buyinggroup'),
                    ]
            else:
                fields += [
                    ('initial_balance',),
                ]
        fields += [
            ('may_order', 'is_active'),
672
            ('get_last_login', 'get_date_joined', 'get_participation', 'get_purchase')
Patrick's avatar
Patrick committed
673 674 675 676
        ]
        return fields

    def get_readonly_fields(self, request, customer=None):
677
        if apps.REPANIER_SETTINGS_INVOICE:
Patrick's avatar
Patrick committed
678 679 680 681 682
            if customer is not None:
                customer_invoice = CustomerInvoice.objects.filter(customer_id=customer.id).order_by().first()
                if customer_invoice is not None:
                    # Do not modify the initial balance, an invoice already exist
                    return ['represent_this_buyinggroup', 'date_balance', 'balance', 'get_last_login',
683
                            'get_date_joined', 'get_participation', 'get_purchase']
Patrick's avatar
Patrick committed
684
                else:
685
                    return ['represent_this_buyinggroup', 'get_last_login', 'get_date_joined', 'get_participation', 'get_purchase']
Patrick's avatar
Patrick committed
686
            else:
687 688
                return ['represent_this_buyinggroup', 'get_last_login', 'get_date_joined', 'get_participation', 'get_purchase']
        return ['get_last_login', 'get_date_joined', 'get_participation', 'get_purchase']
Patrick's avatar
Patrick committed
689 690 691

    def get_form(self, request, customer=None, **kwargs):
        form = super(CustomerWithUserDataAdmin, self).get_form(request, customer, **kwargs)
Patrick Colmant's avatar
Patrick Colmant committed
692 693 694
        username_field = form.base_fields['username']
        email_field = form.base_fields['email']

695
        if apps.REPANIER_SETTINGS_DELIVERY_POINT:
Patrick Colmant's avatar
Patrick Colmant committed
696 697 698
            delivery_point_field = form.base_fields["delivery_point"]
            delivery_point_field.empty_label = None
            delivery_point_field.queryset = LUT_DeliveryPoint.objects.filter(
Patrick's avatar
Patrick committed
699 700
                rght=F('lft')+1, is_active=True, translations__language_code=translation.get_language()
            ).order_by('translations__short_name')
Patrick Colmant's avatar
Patrick Colmant committed
701 702
            delivery_point_field.widget.can_add_related = False
        if customer is not None:
703
            user_model = get_user_model()
Patrick's avatar
Patrick committed
704
            user = user_model.objects.get(id=customer.user_id)
Patrick Colmant's avatar
Patrick Colmant committed
705 706 707 708 709 710
            username_field.initial = getattr(user, user_model.USERNAME_FIELD)
            email_field.initial = user.email
            # One folder by customer to avoid picture names conflicts
            picture_field = form.base_fields["picture"]
            if hasattr(picture_field.widget, 'upload_to'):
                picture_field.widget.upload_to = "customer" + os_sep + str(customer.id)
711 712
        else:
            # Clean data displayed
Patrick Colmant's avatar
Patrick Colmant committed
713 714
            username_field.initial = ''
            email_field.initial = ''
715 716 717
        return form

    def save_model(self, request, customer, form, change):
Patrick's avatar
Patrick committed
718 719 720 721 722 723
        customer.user = form.user
        form.user.is_staff = False
        form.user.is_active = customer.is_active
        form.user.save()
        super(CustomerWithUserDataAdmin, self).save_model(
            request, customer, form, change)
724

725

726
admin.site.register(Customer, CustomerWithUserDataAdmin)
Patrick Colmant's avatar
Patrick Colmant committed
727

Patrick's avatar
Patrick committed
728

pi's avatar
pi committed
729 730
# Staff
class StaffWithUserDataForm(UserDataForm):
731 732
    class Meta:
        model = Staff
Patrick's avatar
Patrick committed
733
        fields = "__all__"
734 735


Patrick's avatar
Patrick committed
736
class StaffWithUserDataAdmin(admin.ModelAdmin):
737
    form = StaffWithUserDataForm
Patrick's avatar
Patrick committed
738
    fields = ['username',
739
              'email', 'is_reply_to_order_email', 'is_reply_to_invoice_email',
Patrick's avatar
Patrick committed
740 741 742
              'is_coordinator', 'is_webmaster',
              'customer_responsible', 'long_name', 'function_description',
              'is_active']
743 744
    list_display = ('user', 'long_name', 'customer_responsible', 'get_customer_phone1')
    list_filter = ('is_active',)
745 746 747 748 749 750
    list_select_related = ('customer_responsible',)
    list_per_page = 17
    list_max_show_all = 17

    def get_form(self, request, obj=None, **kwargs):
        form = super(StaffWithUserDataAdmin, self).get_form(request, obj, **kwargs)
Patrick Colmant's avatar
Patrick Colmant committed
751 752
        username_field = form.base_fields['username']
        email_field = form.base_fields['email']
753
        if "customer_responsible" in form.base_fields:
Patrick Colmant's avatar
Patrick Colmant committed
754 755
            customer_responsible_field = form.base_fields["customer_responsible"]
            customer_responsible_field.widget.can_add_related = False
756
            if obj:
Patrick Colmant's avatar
Patrick Colmant committed
757 758
                customer_responsible_field.empty_label = None
                customer_responsible_field.initial = obj.customer_responsible
759
            else:
Patrick Colmant's avatar
Patrick Colmant committed
760
                customer_responsible_field.queryset = Customer.objects.filter(is_active=True).order_by(
761 762 763 764 765
                    "short_basket_name")

        if obj:
            user_model = get_user_model()
            user = user_model.objects.get(id=obj.user_id)
Patrick Colmant's avatar
Patrick Colmant committed
766
            username_field.initial = getattr(user, user_model.USERNAME_FIELD)
767
            # username.widget.attrs['readonly'] = True
Patrick Colmant's avatar
Patrick Colmant committed
768
            email_field.initial = user.email
769 770
        else:
            # Clean data displayed
Patrick Colmant's avatar
Patrick Colmant committed
771
            username_field.initial = ''
772
            # username.widget.attrs['readonly'] = False
Patrick Colmant's avatar
Patrick Colmant committed
773
            email_field.initial = ''
774 775 776 777 778
        return form

    def save_model(self, request, staff, form, change):
        # TODO Check there is not more that one is_reply_to_order_email set to True
        # TODO Check there is not more that one is_reply_to_invoice_email set to True
Patrick's avatar
Patrick committed
779 780 781 782 783
        staff.user = form.user
        form.user.is_staff = True
        form.user.is_active = staff.is_active
        form.user.save()
        super(StaffWithUserDataAdmin, self).save_model(request, staff, form, change)
784

Patrick Colmant's avatar
Patrick Colmant committed
785

pi's avatar
pi committed
786
admin.site.register(Staff, StaffWithUserDataAdmin)
Patrick Colmant's avatar
Patrick Colmant committed
787

Patrick's avatar
Patrick committed
788

789
# Custom Product
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
class ProductResource(resources.ModelResource):
    id = fields.Field(attribute='id', widget=IdWidget(), readonly=True)
    producer_name = fields.Field(attribute='producer', widget=ForeignKeyWidget(Producer, 'short_profile_name'))
    long_name = fields.Field(attribute='long_name')
    department_for_customer = fields.Field(attribute='department_for_customer', widget=TranslatedForeignKeyWidget(LUT_DepartmentForCustomer, 'short_name'))
    order_unit = fields.Field(attribute='order_unit', widget=ChoiceWidget(LUT_PRODUCT_ORDER_UNIT, LUT_PRODUCT_ORDER_UNIT_REVERSE))
    order_average_weight = fields.Field(attribute='order_average_weight', widget=ThreeDecimalsWidget())
    producer_unit_price = fields.Field(attribute='producer_unit_price', widget=TwoDecimalsWidget())
    customer_unit_price = fields.Field(attribute='customer_unit_price', widget=TwoDecimalsWidget())
    unit_deposit = fields.Field(attribute='unit_deposit', widget=TwoDecimalsWidget())
    vat_level = fields.Field(attribute='vat_level', widget=ChoiceWidget(LUT_VAT, LUT_VAT_REVERSE))
    customer_minimum_order_quantity = fields.Field(attribute='customer_minimum_order_quantity', widget=ThreeDecimalsWidget())
    customer_increment_order_quantity = fields.Field(attribute='customer_increment_order_quantity', widget=ThreeDecimalsWidget())
    customer_alert_order_quantity = fields.Field(attribute='customer_alert_order_quantity', widget=ThreeDecimalsWidget())
    wrapped = fields.Field(attribute='wrapped', widget=DecimalBooleanWidget())

    class Meta:
        model = Product
        fields = (
            'id',
            'producer_name', 'reference', 'department_for_customer',
            'long_name',
            'order_unit',
            'wrapped', 'order_average_weight', 'producer_unit_price', 'customer_unit_price',
            'unit_deposit', 'vat_level', 'customer_minimum_order_quantity',
            'customer_increment_order_quantity', 'customer_alert_order_quantity'
        )
        export_order = fields
        import_id_fields = ('id',)
        skip_unchanged = True
        report_skipped = False
        use_transactions = False

823
class ProductDataForm(TranslatableModelForm):
Patrick Colmant's avatar
Patrick Colmant committed
824
    # preview_product_order = forms.CharField(label="", widget=PreviewProductOrderWidget)
825 826 827 828

    def __init__(self, *args, **kwargs):
        super(ProductDataForm, self).__init__(*args, **kwargs)

Patrick's avatar
Patrick committed
829 830
    def clean(self):
        cleaned_data = super(ProductDataForm, self).clean()
831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854
        customer_minimum_order_quantity = self.cleaned_data["customer_minimum_order_quantity"]
        customer_increment_order_quantity = self.cleaned_data["customer_increment_order_quantity"]
        customer_alert_order_quantity = self.cleaned_data["customer_alert_order_quantity"]
        if "limit_order_quantity_to_stock" in self.cleaned_data:
            limit_order_quantity_to_stock = self.cleaned_data["limit_order_quantity_to_stock"]
        else:
            limit_order_quantity_to_stock = False

        if customer_increment_order_quantity <= DECIMAL_ZERO:
            customer_increment_order_quantity = DECIMAL_ONE
        if customer_minimum_order_quantity <= DECIMAL_ZERO:
            customer_minimum_order_quantity = customer_increment_order_quantity
        # if customer_alert_order_quantity <= customer_minimum_order_quantity:
        #     customer_alert_order_quantity = customer_minimum_order_quantity
        if customer_alert_order_quantity > DECIMAL_ZERO:
            limit_order_qty_item = customer_alert_order_quantity / customer_increment_order_quantity
            if customer_increment_order_quantity > customer_minimum_order_quantity:
                limit_order_qty_item += 1

            if not limit_order_quantity_to_stock and limit_order_qty_item > LIMIT_ORDER_QTY_ITEM:
                self.add_error(
                    'customer_alert_order_quantity',
                    _('This alert quantity will generate more than %(qty_item)d choices for the customer into the order form') % {'qty_item': LIMIT_ORDER_QTY_ITEM,})

855 856 857 858
        return cleaned_data

    class Meta:
        model = Product
Patrick's avatar
Patrick committed
859 860 861 862 863 864 865 866 867
        fields = "__all__"
        widgets = {
          'order_unit': SelectAdminOrderUnitWidget(),
        }


def create_product_action(permanence):
    def action(modeladmin, request, queryset):
        queryset = queryset.order_by()
868 869 870 871 872
        offer_item_queryset = OfferItem.objects.filter(
            permanence_id=permanence.id,
            product__in=queryset,
            is_active=True
        ).order_by()
Patrick's avatar
Patrick committed
873 874 875 876 877 878 879 880 881 882 883
        clean_offer_item(permanence, offer_item_queryset, reorder=False)
        recalculate_order_amount(permanence_id=permanence.id,
                                 permanence_status=permanence.status,
                                 offer_item_queryset=offer_item_queryset,
                                 send_to_producer=False)
        user_message = _("Action performed.")
        user_message_level = messages.INFO
        modeladmin.message_user(request, user_message, user_message_level)

    name = "apply_to_%d" % (permanence.id,)
    return (name, (action, name, _("Apply to %s") % (permanence,)))
884 885


886
class ProductAdmin(ImportExportMixin, TranslatableAdmin):
887
    form = ProductDataForm
888 889 890
    resource_class = ProductResource
    list_display = ('is_into_offer', 'producer','department_for_customer', 'get_long_name', 'producer_unit_price',
                'unit_deposit', 'customer_alert_order_quantity', 'stock')
Patrick's avatar
Patrick committed
891
    list_display_links = ('get_long_name',)
892
    list_editable = ('producer_unit_price', 'stock')
893 894 895
    readonly_fields = ('is_created_on',
                       'is_updated_on')
    list_select_related = ('producer', 'department_for_customer')
896 897
    list_per_page = 17
    list_max_show_all = 17
898
    filter_horizontal = ('production_mode',)
899
    ordering = ('producer',
900 901
                'translations__long_name',)
    search_fields = ('translations__long_name',)
902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919
    list_filter = ('is_active',
                   'is_into_offer',
                   ProductFilterByDepartmentForThisProducer,
                   ProductFilterByProducer,)
    actions = ['flip_flop_select_for_offer_status', 'duplicate_product']

    def flip_flop_select_for_offer_status(self, request, queryset):
        task_product.flip_flop_is_into_offer(queryset)

    flip_flop_select_for_offer_status.short_description = _(
        'flip_flop_select_for_offer_status for offer')

    def duplicate_product(self, request, queryset):
        user_message, user_message_level = task_product.admin_duplicate(queryset)
        self.message_user(request, user_message, user_message_level)

    duplicate_product.short_description = _('duplicate product')

Patrick's avatar
Patrick committed
920
    def get_list_display(self, request):
921 922 923 924 925 926 927 928 929 930 931 932 933 934
        producer_id = sint(request.GET.get('producer', 0))
        if producer_id != 0:
            producer_queryset = Producer.objects.filter(id=producer_id).order_by()
            producer = producer_queryset.first()
        else:
            producer = None
        if producer is not None:
            if producer.manage_stock:
                return ('is_into_offer', 'producer','department_for_customer', 'get_long_name', 'all_languages_column', 'producer_unit_price',
                    'unit_deposit', 'customer_alert_order_quantity', 'stock')
            elif producer.producer_pre_opening:
                return ('is_into_offer', 'producer','department_for_customer', 'get_long_name', 'all_languages_column', 'producer_unit_price',
                    'unit_deposit', 'stock')
            else:
935
                self.list_editable = ('producer_unit_price',)
936 937
                return ('is_into_offer', 'producer','department_for_customer', 'get_long_name', 'all_languages_column', 'producer_unit_price',
                    'unit_deposit', 'customer_alert_order_quantity')
Patrick's avatar
Patrick committed
938
        else:
939 940
            return ('is_into_offer', 'producer','department_for_customer', 'get_long_name', 'all_languages_column', 'producer_unit_price',
                'unit_deposit', 'customer_alert_order_quantity', 'stock')
Patrick's avatar
Patrick committed
941

942
    def get_form(self, request, product=None, **kwargs):
Patrick's avatar
Patrick committed
943 944 945 946
        department_for_customer_id = None
        is_active_value = None
        is_into_offer_value = None
        producer_queryset = Producer.objects.none()
947
        if product is not None:
Patrick's avatar
Patrick committed
948 949 950 951 952 953 954 955 956 957 958 959 960 961 962
            producer_queryset = Producer.objects.filter(id=product.producer_id).order_by()
        else:
            preserved_filters = request.GET.get('_changelist_filters', None)
            if preserved_filters:
                param = dict(parse_qsl(preserved_filters))
                if 'producer' in param:
                    producer_id = param['producer']
                    if producer_id:
                        producer_queryset = Producer.objects.filter(id=producer_id).order_by()
                if 'department_for_customer' in param:
                    department_for_customer_id = param['department_for_customer']
                if 'is_active__exact' in param:
                    is_active_value = param['is_active__exact']
                if 'is_into_offer__exact' in param:
                    is_into_offer_value = param['is_into_offer__exact']
963
        producer = producer_queryset.first()
Patrick's avatar
Patrick committed
964
        self.fields = [
Patrick Colmant's avatar
Patrick Colmant committed
965
            ('producer', 'long_name', 'picture2'),
Patrick's avatar
Patrick committed
966 967 968
            # 'preview_product_order',
            ('order_unit', 'wrapped'),
        ]
Patrick Colmant's avatar
Patrick Colmant committed
969
        if producer is not None and producer.is_resale_price_fixed:
Patrick's avatar
Patrick committed
970 971 972 973 974 975 976 977 978 979 980
            self.fields += [
                ('producer_unit_price', 'customer_unit_price',),
                ('unit_deposit', 'order_average_weight',),
            ]
        else:
            self.fields += [
                ('producer_unit_price', 'unit_deposit', 'order_average_weight'),
            ]
        self.fields += [
            ('customer_minimum_order_quantity', 'customer_increment_order_quantity', 'customer_alert_order_quantity'),
            ('department_for_customer', 'placement'),
981 982 983 984 985 986
        ]
        if producer is not None and (producer.manage_stock or producer.producer_pre_opening):
            self.fields += [
                ('stock', 'limit_order_quantity_to_stock', 'producer_order_by_quantity'),
            ]
        self.fields += [
Patrick's avatar
Patrick committed
987 988 989
            'production_mode',
            'offer_description',
        ]
990
        if apps.REPANIER_SETTINGS_DISPLAY_VAT or (producer is not None and producer.producer_pre_opening):
Patrick's avatar
Patrick committed
991 992 993 994 995 996 997 998 999 1000
            self.fields += [
            ('reference', 'vat_level'),
            ]
        else:
            self.fields += [
            ('reference',),
            ]
        self.fields += [
            ('is_into_offer', 'is_active', 'is_created_on', 'is_updated_on')
        ]
Patrick Colmant's avatar
Patrick Colmant committed
1001

1002
        form = super(ProductAdmin, self).get_form(request, product, **kwargs)
Patrick Colmant's avatar
Patrick Colmant committed
1003 1004 1005 1006 1007 1008

        producer_field = form.base_fields["producer"]
        department_for_customer_field = form.base_fields["department_for_customer"]
        production_mode_field = form.base_fields["production_mode"]
        picture_field = form.base_fields["picture2"]

1009 1010 1011 1012 1013 1014 1015 1016 1017
        # producer_field.widget.can_add_related = False
        # department_for_customer_field.widget.can_add_related = False
        # production_mode_field.widget.can_add_related = False

        if producer is not None:
            # One folder by producer for clarity
            if hasattr(picture_field.widget, 'upload_to'):
                # picture_field.widget.upload_to += os_sep + str(producer.id)
                picture_field.widget.upload_to = "product" + os_sep + str(producer.id)
Patrick Colmant's avatar
Patrick Colmant committed
1018

1019
        if product is not None:
Patrick Colmant's avatar
Patrick Colmant committed
1020 1021 1022 1023 1024 1025 1026 1027 1028
            producer_field.empty_label = None
            producer_field.queryset = producer_queryset
            # department_for_customer_field.empty_label = None
            department_for_customer_field.queryset = LUT_DepartmentForCustomer.objects.filter(
                rght=F('lft') + 1, is_active=True, translations__language_code=translation.get_language()).order_by(
                'translations__short_name')
            production_mode_field.empty_label = None
        else:
            if producer is not None:
1029
                if "vat_level" in form.base_fields:
Patrick Colmant's avatar
Patrick Colmant committed
1030 1031 1032 1033
                    vat_level_field = form.base_fields["vat_level"]
                    vat_level_field.initial = producer.vat_level
                producer_field.empty_label = None
                producer_field.queryset = producer_queryset
1034 1035 1036 1037 1038
                if producer.producer_pre_opening:
                    order_unit_field = form.base_fields["order_unit"]
                    order_unit_field.choices = LUT_PRODUCER_PRODUCT_ORDER_UNIT
                    limit_order_quantity_to_stock_field = form.base_fields["limit_order_quantity_to_stock"]
                    limit_order_quantity_to_stock_field.initial = True
Patrick Colmant's avatar
Patrick Colmant committed
1039 1040 1041 1042 1043 1044 1045
            else:
                producer_field.choices = [('-1', _("Please select first a producer in the filter of previous screen"))]
            if department_for_customer_id is not None:
                # department_for_customer_field.empty_label = None
                department_for_customer_field.queryset = LUT_DepartmentForCustomer.objects.filter(
                    id=department_for_customer_id
                )
1046
            else:
Patrick Colmant's avatar
Patrick Colmant committed
1047 1048 1049 1050 1051 1052 1053
                department_for_customer_field.queryset = LUT_DepartmentForCustomer.objects.filter(
                    rght=F('lft') + 1, is_active=True, translations__language_code=translation.get_language()).order_by(
                    'translations__short_name')
            if is_active_value:
                is_active_field = form.base_fields["is_active"]
                if is_active_value == '0':
                    is_active_field.initial = False
1054
                else:
Patrick Colmant's avatar
Patrick Colmant committed
1055 1056 1057 1058 1059
                    is_active_field.initial = True
            if is_into_offer_value:
                is_into_offer_field = form.base_fields["is_into_offer"]
                if is_into_offer_value == '0':
                    is_into_offer_field.initial = False
1060
                else:
Patrick Colmant's avatar
Patrick Colmant committed
1061 1062 1063 1064
                    is_into_offer_field.initial = True
        production_mode_field.queryset = LUT_ProductionMode.objects.filter(
            rght=F('lft') + 1, is_active=True, translations__language_code=translation.get_language()).order_by(
            'translations__short_name')
1065 1066
        return form

Patrick's avatar
Patrick committed
1067 1068 1069 1070 1071 1072
    def save_model(self, request, product, form, change):
        super(ProductAdmin, self).save_model(
            request, product, form, change)
        for permanence in Permanence.objects.filter(
                status__in=[PERMANENCE_CLOSED, PERMANENCE_SEND]
        ):
1073 1074 1075 1076 1077
            offer_item_queryset = OfferItem.objects.filter(
                permanence_id=permanence.id,
                product_id=product.id,
                is_active=True
            ).order_by()
Patrick's avatar
Patrick committed
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
            clean_offer_item(permanence, offer_item_queryset, reorder=False)
            recalculate_order_amount(permanence_id=permanence.id,
                                     permanence_status=permanence.status,
                                     offer_item_queryset=offer_item_queryset,
                                     send_to_producer=False)

    def get_queryset(self, request):
        queryset = super(ProductAdmin, self).get_queryset(request)
        return queryset.filter(translations__language_code=translation.get_language())

    def get_actions(self, request):
        actions = super(ProductAdmin, self).get_actions(request)
        actions.update(OrderedDict(create_product_action(p) for p in
            Permanence.objects.filter(status__in=[PERMANENCE_PRE_OPEN, PERMANENCE_OPENED])
                .order_by('-permanence_date')))
        return actions
Patrick Colmant's avatar
Patrick Colmant committed
1094

1095
admin.site.register(Product, ProductAdmin)