admin.py 37.5 KB
Newer Older
Patrick Colmant's avatar
Patrick Colmant committed
1
# -*- coding: utf-8 -*-
2
import re
pi's avatar
pi committed
3
import uuid
4

Patrick Colmant's avatar
Patrick Colmant committed
5
from const import *
pi's avatar
pi committed
6
from tools import *
Patrick Colmant's avatar
Patrick Colmant committed
7
from django.conf import settings
8
from django.conf.urls import patterns, url
Patrick Colmant's avatar
Patrick Colmant committed
9
from django.contrib import admin
Patrick Colmant's avatar
Patrick Colmant committed
10
from django.contrib.auth import get_user_model
11
from django.contrib.auth.models import User
12 13 14
from django.core import urlresolvers

from django.http import HttpResponse
Patrick Colmant's avatar
Patrick Colmant committed
15
from django.utils.translation import ugettext_lazy as _
16
from django.utils import timezone
17 18 19
from django.core import validators
from django.core.exceptions import ValidationError
from django.db import models
Patrick Colmant's avatar
Patrick Colmant committed
20
from django.db.models import Q, F
21
from django import forms
pi's avatar
pi committed
22
from django.contrib.sites.models import get_current_site
23

pi's avatar
pi committed
24 25
# from adminsortable.admin import SortableAdminMixin
from repanier.adminsortable import SortableAdminMixin
Patrick Colmant's avatar
Patrick Colmant committed
26 27 28 29 30

from repanier.models import LUT_ProductionMode
from repanier.models import LUT_DepartmentForCustomer
from repanier.models import LUT_DepartmentForProducer
from repanier.models import LUT_PermanenceRole
Patrick Colmant's avatar
Patrick Colmant committed
31 32

from repanier.models import Producer
33
from repanier.models import Permanence
Patrick Colmant's avatar
Patrick Colmant committed
34
from repanier.models import Customer
pi's avatar
pi committed
35
from repanier.models import Staff
Patrick Colmant's avatar
Patrick Colmant committed
36
from repanier.models import Product
Patrick Colmant's avatar
Patrick Colmant committed
37 38 39 40
from repanier.models import PermanenceBoard
from repanier.models import OfferItem
from repanier.models import PermanenceInPreparation
from repanier.models import PermanenceDone
Patrick Colmant's avatar
Patrick Colmant committed
41
from repanier.models import Purchase
Patrick Colmant's avatar
Patrick Colmant committed
42
from repanier.models import BankAccount
pi's avatar
pi committed
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
from repanier.models import CustomerInvoice
from repanier.models import ProducerInvoice

from repanier.admin_export_xlsx import export_permanence_planified_xlsx
from repanier.admin_export_xlsx import export_product_xlsx
from repanier.admin_export_xlsx import export_permanence_done_xlsx
from repanier.admin_import_xlsx import import_product_xlsx
from repanier.admin_import_xlsx import import_permanence_done_xlsx
from repanier.admin_export_docx import export_mymodel_docx
from repanier.admin_send_mail import send_test_email

from menus.base import Menu, NavigationNode
from menus.menu_pool import menu_pool

from datetime import datetime
from repanier.tasks import open_offers_async
from repanier.tasks import close_orders_async
from repanier.tasks import done_async
from repanier.tasks import email_invoices_async
Patrick Colmant's avatar
Patrick Colmant committed
62

63 64 65 66 67 68 69 70 71
# import django
# class LocalizedModelForm(forms.ModelForm):
#     def __new__(cls, *args, **kwargs):
#         new_class = super(LocalizedModelForm, cls).__new__(cls, *args, **kwargs)
#         for field in new_class.base_fields.values():
#             if isinstance(field, django.forms.DecimalField):
#                 field.localize = True
#                 field.widget.is_localized = True
#         return new_class
Patrick Colmant's avatar
Patrick Colmant committed
72 73 74 75 76

# Filters in the right sidebar of the change list page of the admin
from django.contrib.admin import SimpleListFilter


pi's avatar
pi committed
77
class ProductFilterByProducer(SimpleListFilter):
78 79
	# Human-readable title which will be displayed in the
	# right admin sidebar.
Patrick Colmant's avatar
Patrick Colmant committed
80
	title = _("producers")
81
	# Parameter for the filter that will be used in the URL query.
pi's avatar
pi committed
82
	parameter_name = 'producer'
Patrick Colmant's avatar
Patrick Colmant committed
83 84 85 86 87 88 89 90 91

	def lookups(self, request, model_admin):
		"""
		Returns a list of tuples. The first element in each
		tuple is the coded value for the option that will
		appear in the URL query. The second element is the
		human-readable name for the option that will appear
		in the right sidebar.
		"""
pi's avatar
pi committed
92
		# This list is a collection of producer.id, .name
Patrick Colmant's avatar
Patrick Colmant committed
93
		return [(c.id, c.short_profile_name) for c in 
pi's avatar
pi committed
94
			Producer.objects.all().active()
95
			]
Patrick Colmant's avatar
Patrick Colmant committed
96 97 98 99 100 101 102 103 104

	def queryset(self, request, queryset):
		"""
		Returns the filtered queryset based on the value
		provided in the query string and retrievable via
		`self.value()`.
		"""
		# This query set is a collection of products
		if self.value():
pi's avatar
pi committed
105
			return queryset.producer_is(self.value())
Patrick Colmant's avatar
Patrick Colmant committed
106 107 108 109 110 111 112 113 114
		else:
			return queryset


class ProductFilterByDepartmentForProducer(SimpleListFilter):
	title = _("departments for producer")
	parameter_name = 'department_for_producer'

	def lookups(self, request, model_admin):
pi's avatar
pi committed
115
		# This list is a collection of department.id, .name
Patrick Colmant's avatar
Patrick Colmant committed
116
		return [(c.id, c.short_name) for c in 
117
			LUT_DepartmentForProducer.objects.all().active()
118
			]
Patrick Colmant's avatar
Patrick Colmant committed
119 120 121 122 123 124 125 126

	def queryset(self, request, queryset):
		# This query set is a collection of products
		if self.value():
			return queryset.department_for_producer_is(self.value())
		else:
			return queryset

127 128 129 130 131
class ProductFilterByDepartmentForThisProducer(SimpleListFilter):
	title = _("departments for producer")
	parameter_name = 'department_for_this_producer'

	def lookups(self, request, model_admin):
pi's avatar
pi committed
132 133 134
		producer = request.GET.get('producer')
		inner_qs = Product.objects.all().active().producer_is(
			producer).order_by(
135 136 137 138 139
			'department_for_producer__id').distinct(
			'department_for_producer__id')
		# return []
		return [('all', _('All'))] + [(c.id, c.short_name) for c in 
			LUT_DepartmentForProducer.objects.all().active().filter(product__in=inner_qs)
140
			]
141 142 143 144 145 146 147 148 149 150 151 152 153 154

	def choices(self, cl):
		for lookup, title in self.lookup_choices:
			yield {
				'selected': self.value() == lookup,
				'query_string': cl.get_query_string({
					self.parameter_name: lookup,
				}, []),
				'display': title,
			}

	def queryset(self, request, queryset):
		# This query set is a collection of products
		if self.value()=='all':
pi's avatar
pi committed
155 156
			producer = request.GET.get('producer')
			return queryset.producer_is(producer)
157 158 159
		else:
			return queryset.department_for_producer_is(self.value())

Patrick Colmant's avatar
Patrick Colmant committed
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
# LUT
class LUT_ProductionModeAdmin(admin.ModelAdmin):
	list_display = ('short_name', 'is_active')
	list_display_links = ('short_name',)
	list_max_show_all = True

admin.site.register(LUT_ProductionMode, LUT_ProductionModeAdmin)

class LUT_DepartmentForCustomerAdmin(admin.ModelAdmin):
	list_display = ('short_name', 'is_active')
	list_display_links = ('short_name',)
	list_max_show_all = True

admin.site.register(LUT_DepartmentForCustomer, LUT_DepartmentForCustomerAdmin)

class LUT_DepartmentForProducerAdmin(admin.ModelAdmin):
	list_display = ('short_name', 'is_active')
	list_display_links = ('short_name',)
	list_max_show_all = True

admin.site.register(LUT_DepartmentForProducer, LUT_DepartmentForProducerAdmin)

class LUT_PermanenceRoleAdmin(admin.ModelAdmin):
	list_display = ('short_name', 'is_active')
	list_display_links = ('short_name',)
	list_max_show_all = True

admin.site.register(LUT_PermanenceRole, LUT_PermanenceRoleAdmin)

pi's avatar
pi committed
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
class ProducerAdmin(admin.ModelAdmin):
	fields = [ 
		'short_profile_name', 
		'long_profile_name',
		'email',
		'price_list_multiplier',
		'order_description',
		'invoice_description',
		'date_balance', 'balance',
		'represent_this_buyinggroup', 
		'phone1', 'phone2', 'fax', 'address',
		'vat_id',
		'bank_account', 'is_active']
	readonly_fields = (
		'date_balance', 
		'balance',
	)
	search_fields = ('short_profile_name',)
	list_display = ('short_profile_name', 'get_products', 'phone1', 'email', 'represent_this_buyinggroup',
		'is_active')
	list_max_show_all = True
	actions = [
		'export_xlsx',
		'import_xlsx',
	]

	def export_xlsx(self, request, queryset):
		return export_product_xlsx(request, queryset)
	export_xlsx.short_description = _("Export products of selected producer(s) as XSLX file")

	def import_xlsx(self, request, queryset):
		return import_product_xlsx(self, admin, request, queryset)
	import_xlsx.short_description = _("Import products of selected producer(s) from a XLSX file")

	# def get_producer_phone1(self, obj):
	# 	if obj.producer:
	# 		return '%s'%(obj.producer.phone1)
	# 	else:
	# 		return ''
	# get_producer_phone1.short_description = _("phone1") 

admin.site.register(Producer, ProducerAdmin)

232 233 234 235 236 237 238 239 240 241
# Custom User
class UserDataForm(forms.ModelForm):

	username = forms.CharField(label=_('Username'), max_length=30, 
			help_text=_(
				'Required. 30 characters or fewer. Letters, numbers and @/./+/-/_ characters'
			),
			validators=[
				validators.RegexValidator(re.compile('^[\w.@+-]+$'), _('Enter a valid username.'), 'invalid')
			])
pi's avatar
pi committed
242 243
	# password1 = forms.CharField(label=_('Password1'), max_length=128, required=False)
	# password2 = forms.CharField(label=_('Password2'), max_length=128, required=False)
244 245 246 247 248 249
	email = forms.EmailField(label=_('Email'))
	first_name = forms.CharField(label=_('First_name'), max_length=30)
	last_name = forms.CharField(label=_('Last_name'), max_length=30)

	def __init__(self, *args, **kwargs):
		super(UserDataForm, self).__init__(*args, **kwargs)
250
		self.user = None
251

252 253 254 255
	def error(self,field, msg):
		if field not in self._errors:
			self._errors[field]= self.error_class([msg])

256
	def clean(self, *args, **kwargs):
pi's avatar
pi committed
257 258 259 260
		# The Staff has no first_name or last_name because it's a function with login/pwd.
		# A Customer with a first_name and last_name is responsible of this funcition. 
		cleaned_data = super(UserDataForm, self).clean(*args, **kwargs)
		customer_form = 'short_basket_name' in self.fields
261
		if any(self.errors):
pi's avatar
pi committed
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
			if 'first_name' in self._errors:
				del self._errors['first_name']
			self.data['first_name'] = self.fields['first_name'].initial
			if 'last_name' in self._errors:
				del self._errors['last_name']
			self.data['last_name'] = self.fields['last_name'].initial
		username_field_name = 'username'
		initial_username  = self.instance.user.username
		if customer_form:
			# Customer
			username_field_name = 'short_basket_name'
		# initial_username = self.fields[username_field_name].initial
		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')
		if customer_form:
			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
283
		if not username:
pi's avatar
pi committed
284
			self.error(username_field_name ,user_error1)
285
		# Check that the email is set
286 287
		email = self.cleaned_data.get("email")
		if not email:
288 289
			self.error('email',_('The given email must be set'))
		# Check that the email is not already used
290 291
		user=None
		email = User.objects.normalize_email(email)
pi's avatar
pi committed
292 293
		if email:
			# Only if a email is given
294
			try:
pi's avatar
pi committed
295
				user = User.objects.get(email=email)
296 297
			except User.DoesNotExist:
				pass
pi's avatar
pi committed
298 299 300 301 302 303 304 305 306 307 308 309 310 311
		# Check that the username is not already used
		if user != None:
			if initial_username!=user.username:
				self.error('email',_('The given email is used by another user'))
		user=None
		try:
			user = User.objects.get(username=username)
		except User.DoesNotExist:
			pass
		if user != None:
			if initial_username!=user.username:
				self.error(username_field_name,user_error2)
		print self.errors
		return cleaned_data
312 313

	def save(self, *args, **kwargs):
314
		super(UserDataForm, self).save(*args, **kwargs)
315 316 317
		change = (self.instance.id != None)
		username = self.data['username']
		email = self.data['email']
pi's avatar
pi committed
318
		# password = self.data['password1']
319 320 321 322
		first_name = self.data['first_name']
		last_name = self.data['last_name']
		user = None
		if change:
323
			user=User.objects.get(id=self.instance.user_id)
324 325 326 327
			user.username = username
			user.email = email
			user.first_name = first_name
			user.last_name = last_name
pi's avatar
pi committed
328 329
			# if password:
			# 	user.set_password(password)
330 331
			user.save()
		else:
332
			user = User.objects.create_user(
pi's avatar
pi committed
333
				username=username, email=email, password=uuid.uuid1().hex,
334 335
				first_name=first_name, last_name=last_name)
		self.user = user
336 337
		return self.instance

Patrick Colmant's avatar
Patrick Colmant committed
338 339

# Customer
340
class CustomerWithUserDataForm(UserDataForm):
341 342 343 344 345 346

	class Meta:
		model = Customer

class CustomerWithUserDataAdmin(admin.ModelAdmin):
	form = CustomerWithUserDataForm
pi's avatar
pi committed
347 348 349 350 351 352 353
	fields = [
		('short_basket_name', 'long_basket_name',),
		'email', 
		'represent_this_buyinggroup',
		'phone1', 'phone2', 'address', 'vat_id',
		'date_balance', 'balance',
		'may_order',
354
		'is_active']
pi's avatar
pi committed
355 356 357 358 359 360
	readonly_fields = (
		'date_balance', 
		'balance',
	)
	search_fields = ('short_basket_name',)
	list_display = ('__unicode__', 'get_email', 'phone1', 'phone2', 'balance', 'may_order')
Patrick Colmant's avatar
Patrick Colmant committed
361 362
	list_max_show_all = True

pi's avatar
pi committed
363 364 365 366 367 368 369
	def get_email(self, obj):
		if obj.user:
			return '%s'%(obj.user.email)
		else:
			return ''
	get_email.short_description = _("email")

Patrick Colmant's avatar
Patrick Colmant committed
370
	def get_form(self,request, obj=None, **kwargs):
371 372 373 374 375
		form = super(CustomerWithUserDataAdmin,self).get_form(request, obj, **kwargs)
		username = form.base_fields['username']
		email = form.base_fields['email']
		first_name= form.base_fields['first_name']
		last_name= form.base_fields['last_name']
pi's avatar
pi committed
376

Patrick Colmant's avatar
Patrick Colmant committed
377
		if obj:
378
			user_model = get_user_model()
379
			user = user_model.objects.get(id=obj.user_id)
380
			username.initial = getattr(user, user_model.USERNAME_FIELD)
pi's avatar
pi committed
381
			# username.widget.attrs['readonly'] = True
382 383 384
			email.initial = user.email
			first_name.initial = user.first_name
			last_name.initial = user.last_name
385 386 387 388 389
		else:
			# Clean data displayed
			username.initial = ''
			# username.widget.attrs['readonly'] = False
			email.initial = ''
pi's avatar
pi committed
390 391
			first_name.initial = 'N/A'
			last_name.initial = 'N/A'
Patrick Colmant's avatar
Patrick Colmant committed
392 393
		return form

394 395
	def save_model(self, request, obj, form, change):
		obj.user = form.user
pi's avatar
pi committed
396 397 398
		form.user.is_staff = False
		form.user.is_active = obj.is_active
		form.user.save()
399 400
		super(CustomerWithUserDataAdmin,self).save_model(
			request, obj, form, change)
401

402
admin.site.register(Customer, CustomerWithUserDataAdmin)
Patrick Colmant's avatar
Patrick Colmant committed
403

pi's avatar
pi committed
404 405
# Staff
class StaffWithUserDataForm(UserDataForm):
406 407

	class Meta:
pi's avatar
pi committed
408 409 410 411 412 413 414 415 416 417
		model = Staff

class StaffWithUserDataAdmin(admin.ModelAdmin):
	form = StaffWithUserDataForm
	fields = ['username',
		# 'password1', 'password2',
		'email', 
		'is_reply_to_order_email', 'is_reply_to_invoice_email',
		'customer_responsible','long_name', 'function_description', 'is_active']
	list_display = ('__unicode__', 'customer_responsible', 'get_customer_phone1', 'is_active')
Patrick Colmant's avatar
Patrick Colmant committed
418 419 420
	list_max_show_all = True

	def get_form(self,request, obj=None, **kwargs):
pi's avatar
pi committed
421
		form = super(StaffWithUserDataAdmin,self).get_form(request, obj, **kwargs)
422 423 424 425
		username = form.base_fields['username']
		email = form.base_fields['email']
		first_name= form.base_fields['first_name']
		last_name= form.base_fields['last_name']
Patrick Colmant's avatar
Patrick Colmant committed
426 427 428 429
		customer_responsible = form.base_fields["customer_responsible"]
		customer_responsible.widget.can_add_related = False

		if obj:
430
			user_model = get_user_model()
431
			user = user_model.objects.get(id=obj.user_id)
432 433 434 435 436
			username.initial = getattr(user, user_model.USERNAME_FIELD)
			# username.widget.attrs['readonly'] = True
			email.initial = user.email
			first_name.initial = user.first_name
			last_name.initial = user.last_name
Patrick Colmant's avatar
Patrick Colmant committed
437 438 439
			customer_responsible.empty_label = None
			customer_responsible.initial = obj.customer_responsible
		else:
440 441 442 443 444 445
			# Clean data displayed
			username.initial = ''
			# username.widget.attrs['readonly'] = False
			email.initial = ''
			first_name.initial = 'N/A'
			last_name.initial = 'N/A'
pi's avatar
pi committed
446 447
		customer_responsible.queryset = Customer.objects.all(
			).active().order_by(
448
			"short_basket_name")
Patrick Colmant's avatar
Patrick Colmant committed
449 450
		return form

451
	def save_model(self, request, obj, form, change):
pi's avatar
pi committed
452 453
		# 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
454 455
		obj.user = form.user
		form.user.is_staff = True
pi's avatar
pi committed
456
		form.user.is_active = obj.is_active
457
		form.user.save()
pi's avatar
pi committed
458
		super(StaffWithUserDataAdmin,self).save_model(
459
			request, obj, form, change)
Patrick Colmant's avatar
Patrick Colmant committed
460

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

463
class ProductAdmin(SortableAdminMixin, admin.ModelAdmin):
pi's avatar
pi committed
464
	list_display = ('producer',
Patrick Colmant's avatar
Patrick Colmant committed
465 466
		'department_for_producer',
		'long_name',
467 468
		'is_into_offer',
		'producer_unit_price',
Patrick Colmant's avatar
Patrick Colmant committed
469 470 471
		'producer_must_give_order_detail_per_customer',
		'customer_minimum_order_quantity',
		'customer_increment_order_quantity',
472 473
		'customer_alert_order_quantity',
		'is_active')
Patrick Colmant's avatar
Patrick Colmant committed
474
	list_display_links = ('long_name',)
475 476 477
	# list_editable = ('is_active', 
	# 	'producer_unit_price',
	# 	'order_average_weight')
Patrick Colmant's avatar
Patrick Colmant committed
478 479
	readonly_fields = ('is_created_on', 
		'is_updated_on')
pi's avatar
pi committed
480 481 482 483 484 485 486 487 488 489 490 491
	fields = (
		('producer', 'long_name'),
		('producer_unit_price', 'order_average_weight'),
		('order_by_kg_pay_by_kg', 'order_by_piece_pay_by_piece', 'order_by_piece_pay_by_kg', 'producer_must_give_order_detail_per_customer'),
		('customer_minimum_order_quantity', 'customer_increment_order_quantity', 'customer_alert_order_quantity'),
		('production_mode', 'picture'),
		'offer_description', 
	 	'usage_description', 
	 	('department_for_producer', 'department_for_customer', 'placement'),
		('vat_level', 'automatically_added'),
		('is_into_offer', 'is_active', 'is_created_on', 'is_updated_on')
	)
Patrick Colmant's avatar
Patrick Colmant committed
492
	list_max_show_all = True
pi's avatar
pi committed
493
	# ordering = ('producer', 
494 495
	# 	'department_for_producer',
	# 	'long_name',)
Patrick Colmant's avatar
Patrick Colmant committed
496 497
	search_fields = ('long_name',)
	list_filter = ('is_active',
pi's avatar
pi committed
498
		ProductFilterByProducer, 
Patrick Colmant's avatar
Patrick Colmant committed
499
		ProductFilterByDepartmentForProducer,)
500
	actions = ['flip_flop_select_for_offer_status', 'duplicate_product'	]
501

502
	def flip_flop_select_for_offer_status(self, request, queryset):
pi's avatar
pi committed
503 504 505
		for product in queryset.order_by():
			product.is_into_offer = not product.is_into_offer
			product.save()
506 507 508

	flip_flop_select_for_offer_status.short_description = _(
		'flip_flop_select_for_offer_status for offer')
Patrick Colmant's avatar
Patrick Colmant committed
509 510 511

	def duplicate_product(self, request, queryset):
		for product in queryset:
512
			super(ProductAdmin,self).move_for_duplicate(product)
pi's avatar
pi committed
513
			long_name_prefix = _("COPY_OF_")
514 515 516 517 518
			length_long_name_prefix = len(long_name_prefix)
			max_length = Product._meta.get_field('long_name').max_length
			if len(product.long_name) + length_long_name_prefix > max_length:
				product.long_name = long_name_prefix + \
					product.long_name[:max_length-length_long_name_prefix ]
Patrick Colmant's avatar
Patrick Colmant committed
519
			else:
520
				product.long_name = long_name_prefix + product.long_name
Patrick Colmant's avatar
Patrick Colmant committed
521 522 523 524 525 526 527
			product.id = None
			product.save()

	duplicate_product.short_description = _('duplicate product')

	def get_form(self,request, obj=None, **kwargs):
		form = super(ProductAdmin,self).get_form(request, obj, **kwargs)
pi's avatar
pi committed
528
		producer = form.base_fields["producer"]
Patrick Colmant's avatar
Patrick Colmant committed
529 530 531
		department_for_producer = form.base_fields["department_for_producer"]
		department_for_customer = form.base_fields["department_for_customer"]
		production_mode = form.base_fields["production_mode"]
pi's avatar
pi committed
532
		producer.widget.can_add_related = False
Patrick Colmant's avatar
Patrick Colmant committed
533 534 535 536 537
		department_for_producer.widget.can_add_related = False
		department_for_customer.widget.can_add_related = False
		production_mode.widget.can_add_related = False

		if obj:
pi's avatar
pi committed
538
			producer.empty_label = None
Patrick Colmant's avatar
Patrick Colmant committed
539 540 541
			department_for_producer.empty_label = None
			department_for_customer.empty_label = None
			production_mode.empty_label = None
pi's avatar
pi committed
542 543
		producer.queryset = Producer.objects.all(
			).active()
544
		department_for_producer.queryset = LUT_DepartmentForProducer.objects.all(
Patrick Colmant's avatar
Patrick Colmant committed
545 546 547 548 549 550 551
			).active()
		department_for_customer.queryset = LUT_DepartmentForCustomer.objects.all(
			).active()
		production_mode.queryset = LUT_ProductionMode.objects.all(
			).active()
		return form

552
	def get_list_filter(self, request):
pi's avatar
pi committed
553 554
		producer = request.GET.get('department_for_this_producer')
		if producer:
555 556 557
			return ('is_active', ProductFilterByDepartmentForThisProducer,)
		else:
			return self.list_filter
Patrick Colmant's avatar
Patrick Colmant committed
558

pi's avatar
pi committed
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
	def save_model(self, request, product, form, change):
		if product.order_by_piece_pay_by_kg:
			product.order_by_kg_pay_by_kg = False
			product.order_by_piece_pay_by_piece = False
			if product.order_average_weight <= 0:
				product.order_average_weight = 1
		elif product.order_by_kg_pay_by_kg:
			product.order_by_piece_pay_by_kg = False
			product.order_by_piece_pay_by_piece = False
			product.order_average_weight = 0
		else:
			product.order_by_kg_pay_by_kg = False
			product.order_by_piece_pay_by_kg = False
			product.order_average_weight = 0
		product.save()

575 576 577
	# def queryset(self, request):
	# 	qs = super(ProductAdmin, self).queryset(request)
	#  	return qs.order_by('order',)
Patrick Colmant's avatar
Patrick Colmant committed
578

579
admin.site.register(Product, ProductAdmin)
Patrick Colmant's avatar
Patrick Colmant committed
580 581 582 583

# Permanence
class PermanenceBoardInline(admin.TabularInline):
	model = PermanenceBoard
pi's avatar
pi committed
584
	fields = ['permanence_role', 'customer']
Patrick Colmant's avatar
Patrick Colmant committed
585 586 587
	extra = 1

	def formfield_for_foreignkey(self, db_field, request, **kwargs):
pi's avatar
pi committed
588 589 590
		if db_field.name == "customer":
			kwargs["queryset"] = Customer.objects.all(
				).active()
Patrick Colmant's avatar
Patrick Colmant committed
591 592 593 594 595 596 597
		if db_field.name == "permanence_role":
			kwargs["queryset"] = LUT_PermanenceRole.objects.all(
				).active()
		return super(PermanenceBoardInline, self).formfield_for_foreignkey(db_field, request, **kwargs)

class OfferItemInline(admin.TabularInline):
	model = OfferItem
pi's avatar
pi committed
598 599
	fields = ['product', 'get_total_order_quantity', 'get_automatically_added_display', 'is_active']
	readonly_fields = ('product', 'get_total_order_quantity', 'get_automatically_added_display')
600 601
	extra = 0
	max_num = 0
Patrick Colmant's avatar
Patrick Colmant committed
602

pi's avatar
pi committed
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
	def has_delete_permission(self, request, obj=None):
		return False

class PermanenceDataForm(forms.ModelForm):
	def __init__(self, *args, **kwargs):
		super(PermanenceDataForm, self).__init__(*args, **kwargs)
		self.user = None

	def error(self,field, msg):
		if field not in self._errors:
			self._errors[field]= self.error_class([msg])

	def clean(self, *args, **kwargs):
		cleaned_data = super(PermanenceDataForm, self).clean(*args, **kwargs)
		initial_distribution_date = self.instance.distribution_date
		distribution_date = self.cleaned_data.get("distribution_date")
		initial_short_name = self.instance.short_name
		short_name = self.cleaned_data.get("short_name")
		if(initial_distribution_date != distribution_date or initial_short_name != short_name):
			permanence_already_exist = False
			try:
				Permanence.objects.get(distribution_date=distribution_date, short_name=short_name)
				permanence_already_exist = True
			except Permanence.DoesNotExist:
				pass
			if permanence_already_exist:
				self.error('short_name',_('A permanence with the same distribution date and the same short_name already exist. You must either change te distribution_date or the name.'))
		return cleaned_data

	class Meta:
		model = Permanence

Patrick Colmant's avatar
Patrick Colmant committed
635
class PermanenceInPreparationAdmin(admin.ModelAdmin):
pi's avatar
pi committed
636
	form = PermanenceDataForm
Patrick Colmant's avatar
Patrick Colmant committed
637 638
	fieldsets = [
		('Permanance', 
pi's avatar
pi committed
639 640 641 642 643
			{'fields': ['distribution_date', 'short_name', 
			('status', 'automaticaly_closed_on'), 
			'offer_description',
			'order_description', 
			'producers']}
Patrick Colmant's avatar
Patrick Colmant committed
644 645
		),
	]
646
	# readonly_fields = ('status', 'is_created_on', 'is_updated_on')
pi's avatar
pi committed
647
	exclude = ['invoice_description']
Patrick Colmant's avatar
Patrick Colmant committed
648
	list_max_show_all = True
649
	filter_horizontal = ('producers',)
Patrick Colmant's avatar
Patrick Colmant committed
650 651
	inlines = [PermanenceBoardInline, OfferItemInline]
	date_hierarchy = 'distribution_date'
pi's avatar
pi committed
652
	list_display = ('__unicode__', 'get_producers', 'get_customers', 'get_board', 'status')
Patrick Colmant's avatar
Patrick Colmant committed
653
	ordering = ('distribution_date',)
pi's avatar
pi committed
654 655 656 657 658 659 660 661
	actions = [
		'download_planified', 
		'open_and_send_offers',
		'close_and_send_orders',
		'delete_purchases', 
		'back_to_planified',
		'send_email',
		# 'export_docx',
Patrick Colmant's avatar
Patrick Colmant committed
662 663
	]

pi's avatar
pi committed
664 665 666
	# def export_docx(self, request, queryset):
	# 	return export_mymodel_docx(request, queryset)
	# export_docx.short_description = _("Export DOCX")
667 668

	def send_email(self, request, queryset):
pi's avatar
pi committed
669 670
		return send_test_email(request, queryset)
	send_email.short_description = _("Send test e-mail")
671

pi's avatar
pi committed
672 673 674
	def download_planified(self, request, queryset):
		return export_permanence_planified_xlsx(request, queryset)
	download_planified.short_description = _("Export planified XLSX")
675 676 677 678 679 680 681 682

	def get_readonly_fields(self, request, obj=None):
		if obj:
			status = obj.status
			if status>PERMANENCE_PLANIFIED:
				return('status', 'is_created_on', 'is_updated_on','producers')
		return ('status', 'is_created_on', 'is_updated_on')

pi's avatar
pi committed
683 684 685 686 687
	def open_and_send_offers(self, request, queryset):
		current_site = get_current_site(request)
		for permanence in queryset[:1]:
			if permanence.status==PERMANENCE_PLANIFIED:
				permanence.status = PERMANENCE_WAIT_FOR_OPEN
Patrick Colmant's avatar
Patrick Colmant committed
688
				permanence.save()
pi's avatar
pi committed
689 690 691 692 693 694 695 696 697 698 699
				open_offers_async.delay(permanence.id, current_site)
	
	open_and_send_offers.short_description = _('open and send offers')

	def close_and_send_orders(self, request, queryset):
		current_site = get_current_site(request)
		for permanence in queryset[:1]:
			if permanence.status==PERMANENCE_OPENED:
				permanence.status = PERMANENCE_WAIT_FOR_SEND
				permanence.save()
				close_orders_async.delay(permanence.id, current_site)
Patrick Colmant's avatar
Patrick Colmant committed
700

pi's avatar
pi committed
701
	close_and_send_orders.short_description = _('close and send orders')
Patrick Colmant's avatar
Patrick Colmant committed
702

pi's avatar
pi committed
703 704 705 706 707
	def back_to_planified(self, request, queryset):
		menu_pool.clear()
		for permanence in queryset[:1]:
			if PERMANENCE_OPENED <= permanence.status <= PERMANENCE_SEND:
				OfferItem.objects.all().permanence(permanence).update(is_active=False)
Patrick Colmant's avatar
Patrick Colmant committed
708 709 710
				permanence.status=PERMANENCE_PLANIFIED
				permanence.save()

pi's avatar
pi committed
711 712 713 714 715 716 717 718 719 720 721 722 723
	back_to_planified.short_description = _('back to planified')

	def delete_purchases(self, request, queryset):
		is_something_deleted = False
		for permanence in queryset.filter(status=PERMANENCE_SEND)[:1]:
			Purchase.objects.all().permanence(permanence).delete()
			is_something_deleted = True
		if is_something_deleted:
			self.message_user(request, _("Purchases successfully deleted."))
		else:
			self.message_user(request, _("You may only delete purchases of permanences whose orders are send."))

	delete_purchases.short_description = _('delete purchases')
Patrick Colmant's avatar
Patrick Colmant committed
724 725 726 727 728 729 730 731 732 733 734 735

	def get_actions(self, request):
		actions = super(PermanenceInPreparationAdmin, self).get_actions(request)
		if 'delete_selected' in actions:
			del actions['delete_selected']
		if not actions:
			try:
				self.list_display.remove('action_checkbox')
			except ValueError:
				pass
		return actions

pi's avatar
pi committed
736 737 738 739 740 741 742
	def formfield_for_manytomany(self, db_field, request, **kwargs):
		if db_field.name == "producers":
			kwargs["queryset"] = Producer.objects.all().active(
				)
		return super(PermanenceInPreparationAdmin, self).formfield_for_manytomany(
			db_field, request, **kwargs)

Patrick Colmant's avatar
Patrick Colmant committed
743 744
	def queryset(self, request):
		qs = super(PermanenceInPreparationAdmin, self).queryset(request)
pi's avatar
pi committed
745
		return qs.filter(status__lte=PERMANENCE_SEND)
Patrick Colmant's avatar
Patrick Colmant committed
746 747 748 749 750 751
admin.site.register(PermanenceInPreparation, PermanenceInPreparationAdmin)

class PermanenceDoneAdmin(admin.ModelAdmin):
	fieldsets = [
		('Permanance', 
			{'fields': ['distribution_date', 'short_name', 'status', 
pi's avatar
pi committed
752
			'invoice_description']}
Patrick Colmant's avatar
Patrick Colmant committed
753 754
		),
	]
pi's avatar
pi committed
755 756
	readonly_fields = ('status', 'is_created_on', 'is_updated_on', 'automaticaly_closed_on')
	exclude = ['offer_description', 'order_description']
Patrick Colmant's avatar
Patrick Colmant committed
757 758 759 760
	list_max_show_all = True
	# inlines = [PermanenceBoardInline, DeliveryBoardInline]
	inlines = [PermanenceBoardInline, OfferItemInline]
	date_hierarchy = 'distribution_date'
pi's avatar
pi committed
761
	list_display = ('__unicode__', 'get_producers', 'get_customers', 'get_board', 'status')
Patrick Colmant's avatar
Patrick Colmant committed
762
	ordering = ('distribution_date',)
pi's avatar
pi committed
763 764 765 766 767 768 769 770 771 772 773 774 775 776 777
	actions = [
		'export_xlsx',
		'import_xlsx',
		'close_and_send_invoices',
		're_send_invoices',
		'cancel_invoices',
	]

	def export_xlsx(self, request, queryset):
		return export_permanence_done_xlsx(request, queryset)
	export_xlsx.short_description = _("Export orders prepared as XSLX file")

	def import_xlsx(self, request, queryset):
		return import_permanence_done_xlsx(self, admin, request, queryset)
	import_xlsx.short_description = _("Import orders prepared from a XLSX file")
Patrick Colmant's avatar
Patrick Colmant committed
778

779 780 781 782 783 784 785 786 787
	# def get_urls(self):
	#         urls = super(PermanenceDoneAdmin, self).get_urls()
	#         my_urls = patterns('',
	#             (r'\d+/purchase/$', self.admin_site.admin_view(self.purchase)),
	#         )
	#         return my_urls + urls

	# def purchase(self, request, id):
	# 	print(id)
pi's avatar
pi committed
788 789 790 791 792 793 794 795
	# 	print(request.GET['customer'])

	
	def close_and_send_invoices(self, request, queryset):
		current_site = get_current_site(request)
		for permanence in queryset[:1]:
			if permanence.status==PERMANENCE_SEND:
				permanence.status = PERMANENCE_WAIT_FOR_DONE
Patrick Colmant's avatar
Patrick Colmant committed
796
				permanence.save()
pi's avatar
pi committed
797 798 799
				done_async.delay(permanence.id, current_site)
	
	close_and_send_invoices.short_description = _('orders prepared and done')
Patrick Colmant's avatar
Patrick Colmant committed
800

pi's avatar
pi committed
801 802 803 804 805
	def re_send_invoices(self, request, queryset):
		current_site = get_current_site(request)
		for permanence in queryset[:1]:
			if permanence.status==PERMANENCE_DONE:
				permanence.status = PERMANENCE_WAIT_FOR_DONE
Patrick Colmant's avatar
Patrick Colmant committed
806
				permanence.save()
pi's avatar
pi committed
807 808 809
				email_invoices_async.delay(permanence_id, current_site)
	
	re_send_invoices.short_description = _('re-send invoices')
Patrick Colmant's avatar
Patrick Colmant committed
810

pi's avatar
pi committed
811 812
	def cancel_invoices(self, request, queryset):
		self.cancel(request, queryset)
Patrick Colmant's avatar
Patrick Colmant committed
813

pi's avatar
pi committed
814 815 816
	cancel_invoices.short_description = _('cancel latest invoices')

	def cancel(self, request, queryset):
Patrick Colmant's avatar
Patrick Colmant committed
817 818
		for permanence in queryset:
			if permanence.status==PERMANENCE_DONE:
pi's avatar
pi committed
819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866
				latest_customer_invoice_set=CustomerInvoice.objects.order_by('-id')[:1]
				if latest_customer_invoice_set:
					if latest_customer_invoice_set[0].permanence.id == permanence.id:
						# This is well the latest closed permanence. The invoices can be cancelled without damages.

						for customer_invoice in CustomerInvoice.objects.filter(
							permanence_id=permanence.id).order_by().distinct():
							customer = Customer.objects.get(id=customer_invoice.customer_id)
							customer.balance = customer_invoice.previous_balance
							customer.date_balance = customer_invoice.date_previous_balance
							Purchase.objects.all().filter(
								is_recorded_on_customer_invoice_id=customer_invoice.id
								).update(
								is_recorded_on_customer_invoice=None
								)
							BankAccount.objects.all().filter(
								is_recorded_on_customer_invoice_id=customer_invoice.id
								).update(
								is_recorded_on_customer_invoice=None
								)
						for producer_invoice in ProducerInvoice.objects.filter(
							permanence_id=permanence.id).order_by().distinct():
							producer = Producer.objects.get(id=producer_invoice.producer_id)
							producer.balance = producer_invoice.previous_balance
							producer.date_balance = producer_invoice.date_previous_balance
							Purchase.objects.all().filter(
								is_recorded_on_producer_invoice_id=producer_invoice.id
								).update(
								is_recorded_on_producer_invoice=None
								)
							BankAccount.objects.all().filter(
								is_recorded_on_producer_invoice_id=producer_invoice.id
								).update(
								is_recorded_on_producer_invoice=None
								)
						CustomerInvoice.objects.filter(
							permanence_id=permanence.id).delete()
						ProducerInvoice.objects.filter(
							permanence_id=permanence.id).delete()
						permanence.status=PERMANENCE_SEND
						permanence.is_done_on = None
						permanence.save()
		menu_pool.clear()

	# back_to_order_send.short_description = _('back to send')

	def has_add_permission(self, request):
		return False
Patrick Colmant's avatar
Patrick Colmant committed
867 868 869 870 871 872 873 874 875 876 877 878 879 880

	def get_actions(self, request):
		actions = super(PermanenceDoneAdmin, self).get_actions(request)
		if 'delete_selected' in actions:
			del actions['delete_selected']
		if not actions:
			try:
				self.list_display.remove('action_checkbox')
			except ValueError:
				pass
		return actions

	def queryset(self, request):
		qs = super(PermanenceDoneAdmin, self).queryset(request)
pi's avatar
pi committed
881
		return qs.filter(status__gte=PERMANENCE_SEND)
Patrick Colmant's avatar
Patrick Colmant committed
882 883 884 885
admin.site.register(PermanenceDone, PermanenceDoneAdmin)

class PurchaseAdmin(admin.ModelAdmin):
	list_max_show_all = True
pi's avatar
pi committed
886 887 888 889
	exclude = ['offer_item']	
	list_display = ['distribution_date', 'product','customer', 'comment',
		'order_quantity', 'prepared_quantity', 'prepared_unit_price',
		'prepared_amount']
890 891
	date_hierarchy = 'distribution_date'
	list_filter = ('distribution_date',)
pi's avatar
pi committed
892 893
	list_display_links = ('product',)
	search_fields = ('customer__short_basket_name', 'product__long_name')
894
	fields = ('permanence',
pi's avatar
pi committed
895
		'customer',
896
		'product',
Patrick Colmant's avatar
Patrick Colmant committed
897
		'order_quantity',
pi's avatar
pi committed
898 899 900 901
		'prepared_quantity',
		('prepared_unit_price', 'vat_level'),
		'prepared_amount',
		'comment')
Patrick Colmant's avatar
Patrick Colmant committed
902 903 904 905 906
	actions = []

	def get_readonly_fields(self, request, obj=None):
		if obj:
			status = obj.permanence.status
pi's avatar
pi committed
907 908 909 910 911 912 913
			if status<PERMANENCE_SEND:
				return('prepared_quantity',
					'prepared_amount',
					'prepared_unit_price',
					'vat_level',
					'is_to_be_prepared')
			if PERMANENCE_SEND<=status<PERMANENCE_DONE:
Patrick Colmant's avatar
Patrick Colmant committed
914
				return('order_quantity',
pi's avatar
pi committed
915
					'is_to_be_prepared')
Patrick Colmant's avatar
Patrick Colmant committed
916
			return ('order_quantity',
pi's avatar
pi committed
917 918 919
				'prepared_quantity',
				'prepared_unit_price',
				'vat_level',
Patrick Colmant's avatar
Patrick Colmant committed
920
				'comment',
pi's avatar
pi committed
921 922
				'prepared_amount',
				'is_to_be_prepared')
Patrick Colmant's avatar
Patrick Colmant committed
923
		else:
pi's avatar
pi committed
924 925 926 927 928 929 930 931 932
			return ('prepared_quantity',
				'prepared_unit_price',
				'vat_level',
				'prepared_amount',
				'is_to_be_prepared')

	def queryset(self, request):
		queryset = super(PurchaseAdmin, self).queryset(request)
		return queryset.exclude(producer__isnull=True)
Patrick Colmant's avatar
Patrick Colmant committed
933 934 935

	def get_form(self,request, obj=None, **kwargs):
		form = super(PurchaseAdmin,self).get_form(request, obj, **kwargs)
936
		permanence = form.base_fields["permanence"]
pi's avatar
pi committed
937
		customer = form.base_fields["customer"]
938 939
		product = form.base_fields["product"]
		permanence.widget.can_add_related = False
pi's avatar
pi committed
940
		customer.widget.can_add_related = False
941
		product.widget.can_add_related = False
Patrick Colmant's avatar
Patrick Colmant committed
942 943

		if obj:
944 945 946
			permanence.empty_label = None
			permanence.queryset = Permanence.objects.filter(
				id = obj.permanence_id)
pi's avatar
pi committed
947 948 949
			customer.empty_label = None
			customer.queryset = Customer.objects.filter(
				id = obj.customer_id)
950 951 952
			product.empty_label = None
			product.queryset = Product.objects.filter(
				id = obj.product_id)
Patrick Colmant's avatar
Patrick Colmant committed
953
		else:
pi's avatar
pi committed
954 955
			permanence.queryset = Permanence.objects.all().is_opened()
			customer.queryset = Customer.objects.all().active()
956
			product.queryset = Product.objects.all().active()
Patrick Colmant's avatar
Patrick Colmant committed
957 958 959
		return form

	def save_model(self, request, purchase, form, change):
960 961
		# obj.preformed_by = request.user
		# obj.ip_address = utils.get_client_ip(request)
pi's avatar
pi committed
962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995
		if purchase == None:
			offer_item = None
			offer_item_set = OfferItem.objects.all().permanence(
				purchase.permanence).product(
				purchase.product).order_by()[:1]
			if offer_item_set:
				offer_item = offer_item_set[0]
			else:
				# Add the product to the OfferItem
				if purchase.product.is_active:
					offer_item = OfferItem.objects.create(
						permanence = purchase.permanence,
						product = purchase.product,
						automatically_added = ADD_PRODUCT_ADDED_WHEN_CREATING_A_PURCHASE_IN_ADMIN )
				else:
					offer_item = OfferItem.objects.create(
						permanence = purchase.permanence,
						product = purchase.product,
						automatically_added = ADD_PRODUCT_DEACTIVATED_ADDED_WHEN_CREATING_A_PURCHASE_IN_ADMIN )
			purchase.offert_item = offer_item
		if purchase.producer == None:
			purchase.producer = purchase.product.producer
		if purchase.distribution_date == None:
			purchase.distribution_date = purchase.permanence.distribution_date
		if purchase.is_to_be_prepared == None:
			purchase.is_to_be_prepared = (purchase.product.automatically_added == ADD_PORDUCT_MANUALY)
		if purchase.permanence.status<PERMANENCE_SEND:
			a_previous_order = purchase.order_amount
			if purchase.product.order_by_piece_pay_by_kg:
				purchase.order_amount = purchase.prepared_quantity * purchase.product.producer_unit_price * purchase.product.order_average_weight
			else:
				purchase.order_amount = purchase.prepared_quantity * purchase.product.producer_unit_price
			save_order_delta_amount(purchase.permanence, purchase.customer, a_previous_order, purchase.order_amount)
		purchase.permanence.producers.add(purchase.producer)
Patrick Colmant's avatar
Patrick Colmant committed
996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
		purchase.save()

	def get_actions(self, request):
		actions = super(PurchaseAdmin, self).get_actions(request)
		if 'delete_selected' in actions:
			del actions['delete_selected']
		if not actions:
			try:
				self.list_display.remove('action_checkbox')
			except ValueError:
				pass
		return actions

admin.site.register(Purchase, PurchaseAdmin)

# Accounting
class BankAccountAdmin(admin.ModelAdmin):
	list_max_show_all = True
pi's avatar
pi committed
1014
	list_display = ['operation_date', 'producer' , 'customer',
Patrick Colmant's avatar
Patrick Colmant committed
1015 1016 1017 1018
	 'bank_amount_in', 'bank_amount_out'] 
	date_hierarchy = 'operation_date'
	ordering = ('operation_date',)
	fields=('operation_date', 
pi's avatar
pi committed
1019
		('producer', 'customer'), 'operation_comment', 'bank_amount_in',
Patrick Colmant's avatar
Patrick Colmant committed
1020
		 'bank_amount_out', 
pi's avatar
pi committed
1021
		 ('is_recorded_on_customer_invoice', 'is_recorded_on_producer_invoice'), 
Patrick Colmant's avatar
Patrick Colmant committed
1022 1023 1024 1025 1026 1027 1028 1029 1030
		 ('is_created_on', 'is_updated_on') )
	actions = []

	def get_readonly_fields(self, request, obj=None):
		if obj:
			readonly = ['operation_date',
				'bank_amount_in',
				'bank_amount_out',
				'is_created_on', 'is_updated_on',
pi's avatar
pi committed
1031 1032 1033 1034 1035
				'is_recorded_on_customer_invoice', 'is_recorded_on_producer_invoice']
			if obj.customer==None:
				readonly.append('customer')
			if obj.producer==None:
				readonly.append('producer')
Patrick Colmant's avatar
Patrick Colmant committed
1036 1037
			return readonly
		return ('is_created_on', 'is_updated_on',
pi's avatar
pi committed
1038
			'is_recorded_on_customer_invoice', 'is_recorded_on_producer_invoice')
Patrick Colmant's avatar
Patrick Colmant committed
1039 1040 1041 1042

	def get_form(self,request, obj=None, **kwargs):
		form = super(BankAccountAdmin,self).get_form(request, obj, **kwargs)
		if obj:
pi's avatar
pi committed
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
			if obj.customer:
				customer = form.base_fields["customer"]
				customer.widget.can_add_related = False
				customer.empty_label = None
				customer.queryset = Customer.objects.id(
					obj.customer_id)
			if obj.producer:
				producer = form.base_fields["producer"]
				producer.widget.can_add_related = False
				producer.empty_label = None
				producer.queryset = Producer.objects.id(
					obj.producer_id)
Patrick Colmant's avatar
Patrick Colmant committed
1055
		else:
pi's avatar
pi committed
1056 1057 1058 1059 1060
			producer = form.base_fields["producer"]
			customer = form.base_fields["customer"]
			producer.widget.can_add_related = False
			customer.widget.can_add_related = False
			producer.queryset = Producer.objects.all(
Patrick Colmant's avatar
Patrick Colmant committed
1061
				).not_the_buyinggroup().active().order_by(
1062
				"short_profile_name")
pi's avatar
pi committed
1063
			customer.queryset = Customer.objects.all(
Patrick Colmant's avatar
Patrick Colmant committed
1064
				).not_the_buyinggroup().active().order_by(
1065 1066
				"short_basket_name")
		return form
Patrick Colmant's avatar
Patrick Colmant committed
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079

	def get_actions(self, request):
		actions = super(BankAccountAdmin, self).get_actions(request)
		if 'delete_selected' in actions:
			del actions['delete_selected']
		if not actions:
			try:
				self.list_display.remove('action_checkbox')
			except ValueError:
				pass
		return actions

admin.site.register(BankAccount, BankAccountAdmin)