Commit 62ad9f2c authored by Patrick's avatar Patrick

WIP

parent 8975f63a
...@@ -19,7 +19,7 @@ class ProductFilterByProducer(SimpleListFilter): ...@@ -19,7 +19,7 @@ class ProductFilterByProducer(SimpleListFilter):
# right admin sidebar. # right admin sidebar.
title = _("producers") title = _("producers")
# Parameter for the filter that will be used in the URL query. # Parameter for the filter that will be used in the URL query.
parameter_name = 'producer_id' parameter_name = 'producer'
template = 'admin/producer_filter.html' template = 'admin/producer_filter.html'
def lookups(self, request, model_admin): def lookups(self, request, model_admin):
...@@ -157,23 +157,20 @@ class PurchaseFilterByCustomer(SimpleListFilter): ...@@ -157,23 +157,20 @@ class PurchaseFilterByCustomer(SimpleListFilter):
class PurchaseFilterByProducerForThisPermanence(SimpleListFilter): class PurchaseFilterByProducerForThisPermanence(SimpleListFilter):
title = _("producer") title = _("producers")
parameter_name = 'producer' parameter_name = 'producer'
template = 'admin/producer_filter.html' template = 'admin/producer_filter.html'
def lookups(self, request, model_admin): def lookups(self, request, model_admin):
permanence_id = request.GET.get('permanence', None) permanence_id = request.GET.get('permanence', None)
if permanence_id is not None: list_filter = []
list_filter = [] for p in Producer.objects.filter(permanence=permanence_id):
for p in Producer.objects.filter(permanence=permanence_id): pi = ProducerInvoice.objects.filter(permanence=permanence_id, producer_id=p.id).order_by('?').first()
pi = ProducerInvoice.objects.filter(permanence=permanence_id, producer_id=p.id).order_by('?').first() if pi is not None:
if pi is not None: list_filter.append((p.id, "%s (%s)" % (p.short_profile_name, pi.total_price_with_tax,)))
list_filter.append((p.id, "%s (%s)" % (p.short_profile_name, pi.total_price_with_tax,))) else:
else: list_filter.append((p.id, p.short_profile_name))
list_filter.append((p.id, p.short_profile_name)) return list_filter
return list_filter
else:
return []
def queryset(self, request, queryset): def queryset(self, request, queryset):
if self.value(): if self.value():
......
...@@ -49,10 +49,10 @@ class OfferItemClosedAdmin(admin.ModelAdmin): ...@@ -49,10 +49,10 @@ class OfferItemClosedAdmin(admin.ModelAdmin):
ordering = ('translations__long_name',) ordering = ('translations__long_name',)
def get_queryset(self, request): def get_queryset(self, request):
queryset = super(OfferItemClosedAdmin, self).get_queryset(request).filter( qs = super(OfferItemClosedAdmin, self).get_queryset(request)
return qs.filter(
translations__language_code=translation.get_language() translations__language_code=translation.get_language()
).distinct() ).distinct()
return queryset
def get_list_display(self, request): def get_list_display(self, request):
producer_id = sint(request.GET.get('producer', 0)) producer_id = sint(request.GET.get('producer', 0))
......
...@@ -362,7 +362,7 @@ class ProductAdmin(ImportExportMixin, TranslatableAdmin): ...@@ -362,7 +362,7 @@ class ProductAdmin(ImportExportMixin, TranslatableAdmin):
duplicate_product.short_description = _('duplicate product') duplicate_product.short_description = _('duplicate product')
def get_list_display(self, request): def get_list_display(self, request):
producer_id = sint(request.GET.get('producer_id', 0)) producer_id = sint(request.GET.get('producer', 0))
if producer_id != 0: if producer_id != 0:
producer_queryset = Producer.objects.filter(id=producer_id).order_by('?') producer_queryset = Producer.objects.filter(id=producer_id).order_by('?')
producer = producer_queryset.first() producer = producer_queryset.first()
...@@ -425,8 +425,8 @@ class ProductAdmin(ImportExportMixin, TranslatableAdmin): ...@@ -425,8 +425,8 @@ class ProductAdmin(ImportExportMixin, TranslatableAdmin):
preserved_filters = request.GET.get('_changelist_filters', None) preserved_filters = request.GET.get('_changelist_filters', None)
if preserved_filters: if preserved_filters:
param = dict(parse_qsl(preserved_filters)) param = dict(parse_qsl(preserved_filters))
if 'producer_id' in param: if 'producer' in param:
producer_id = param['producer_id'] producer_id = param['producer']
if producer_id: if producer_id:
producer_queryset = Producer.objects.filter(id=producer_id).order_by('?') producer_queryset = Producer.objects.filter(id=producer_id).order_by('?')
if 'department_for_customer' in param: if 'department_for_customer' in param:
......
...@@ -208,7 +208,7 @@ class OfferItemSendAdmin(admin.ModelAdmin): ...@@ -208,7 +208,7 @@ class OfferItemSendAdmin(admin.ModelAdmin):
qs = super(OfferItemSendAdmin, self).get_queryset(request) qs = super(OfferItemSendAdmin, self).get_queryset(request)
return qs.filter( return qs.filter(
translations__language_code=translation.get_language() translations__language_code=translation.get_language()
) ).distinct()
def get_form(self, request, obj=None, **kwargs): def get_form(self, request, obj=None, **kwargs):
if obj.is_resale_price_fixed: if obj.is_resale_price_fixed:
......
...@@ -68,7 +68,7 @@ class RepanierSettings(AppConfig): ...@@ -68,7 +68,7 @@ class RepanierSettings(AppConfig):
db_started = connection.cursor() is not None db_started = connection.cursor() is not None
except: except:
time.sleep(1) time.sleep(1)
from models import Configuration, LUT_DepartmentForCustomer, Staff, Purchase from models import Configuration, LUT_DepartmentForCustomer, Staff, Purchase, CustomerInvoice
from const import DECIMAL_ONE, PERMANENCE_NAME_PERMANENCE, CURRENCY_EUR, ORDER_GROUP, \ from const import DECIMAL_ONE, PERMANENCE_NAME_PERMANENCE, CURRENCY_EUR, ORDER_GROUP, \
INVOICE_GROUP, CONTRIBUTOR_GROUP, COORDINATION_GROUP, WEBMASTER_GROUP INVOICE_GROUP, CONTRIBUTOR_GROUP, COORDINATION_GROUP, WEBMASTER_GROUP
try: try:
...@@ -92,10 +92,14 @@ class RepanierSettings(AppConfig): ...@@ -92,10 +92,14 @@ class RepanierSettings(AppConfig):
# Purchase.objects.filter(customer_charged__isnull=True).update( # Purchase.objects.filter(customer_charged__isnull=True).update(
# customer_charged=F('customer_invoice__customer_charged') # customer_charged=F('customer_invoice__customer_charged')
# ) # )
for purchase in Purchase.objects.filter( # for purchase in Purchase.objects.filter(
customer_charged__isnull=True).select_related("customer_invoice").order_by('?'): # customer_charged__isnull=True).select_related("customer_invoice").order_by('?'):
purchase.customer_charged = purchase.customer_invoice.customer_charged # purchase.customer_charged = purchase.customer_invoice.customer_charged
purchase.save(update_fields=["customer_charged",]) # purchase.save(update_fields=["customer_charged",])
CustomerInvoice.objects.filter(
customer__is_group=True,
customer_id=F('customer_charged_id')
).update(is_group=True)
Staff.objects.rebuild() Staff.objects.rebuild()
# Create groups with correct rights # Create groups with correct rights
order_group = Group.objects.filter(name=ORDER_GROUP).only('id').order_by('?').first() order_group = Group.objects.filter(name=ORDER_GROUP).only('id').order_by('?').first()
......
...@@ -74,21 +74,21 @@ class PermanenceMenu(Menu): ...@@ -74,21 +74,21 @@ class PermanenceMenu(Menu):
submenu_id = self.append_permanence(is_anonymous, permanence, nodes, master_id, submenu_id) submenu_id = self.append_permanence(is_anonymous, permanence, nodes, master_id, submenu_id)
if displayed_permanence_counter > 4: if displayed_permanence_counter > 4:
break break
if displayed_permanence_counter < 4: # if displayed_permanence_counter < 4:
max_counter = 4 - displayed_permanence_counter # max_counter = 4 - displayed_permanence_counter
for permanence in Permanence.objects.filter(status__in=[PERMANENCE_INVOICED, PERMANENCE_ARCHIVED]) \ # for permanence in Permanence.objects.filter(status__in=[PERMANENCE_INVOICED, PERMANENCE_ARCHIVED]) \
.only("id", "permanence_date") \ # .only("id", "permanence_date") \
.order_by('-permanence_date'): # .order_by('-permanence_date'):
if permanence.permanence_date >= ( # if permanence.permanence_date >= (
timezone.now() - datetime.timedelta(weeks=LIMIT_DISPLAYED_PERMANENCE)).date(): # timezone.now() - datetime.timedelta(weeks=LIMIT_DISPLAYED_PERMANENCE)).date():
if first_pass and closed_separator: # if first_pass and closed_separator:
submenu_id = self.append_separator(nodes, master_id, submenu_id) # submenu_id = self.append_separator(nodes, master_id, submenu_id)
first_pass = False # first_pass = False
separator = True # separator = True
submenu_id = self.append_permanence(is_anonymous, permanence, nodes, master_id, submenu_id) # submenu_id = self.append_permanence(is_anonymous, permanence, nodes, master_id, submenu_id)
max_counter -= 1 # max_counter -= 1
if max_counter <= 0: # if max_counter <= 0:
break # break
# if REPANIER_SETTINGS_INVOICE and not request.user.is_staff: # if REPANIER_SETTINGS_INVOICE and not request.user.is_staff:
# if separator: # if separator:
......
...@@ -87,7 +87,8 @@ def send_invoice(permanence_id): ...@@ -87,7 +87,8 @@ def send_invoice(permanence_id):
).order_by('?'): ).order_by('?'):
long_basket_name = customer.long_basket_name if customer.long_basket_name is not None else customer.short_basket_name long_basket_name = customer.long_basket_name if customer.long_basket_name is not None else customer.short_basket_name
if Purchase.objects.filter( if Purchase.objects.filter(
permanence_id=permanence.id, customer_charged_id=customer.id permanence_id=permanence.id,
customer_invoice__customer_charged_id=customer.id
).order_by('?').exists(): ).order_by('?').exists():
to_email_customer = [customer.user.email] to_email_customer = [customer.user.email]
if customer.email2 is not None and len(customer.email2.strip()) > 0: if customer.email2 is not None and len(customer.email2.strip()) > 0:
......
This diff is collapsed.
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from django.core.management.base import BaseCommand from django.core.management.base import BaseCommand
from django.db.models import Sum from repanier.const import PERMANENCE_CLOSED
from repanier.models import BankAccount
from repanier.models import LUT_DeliveryPoint, DeliveryBoard
from repanier.models import CustomerInvoice, ProducerInvoice
from repanier.const import PERMANENCE_CLOSED, \
PERMANENCE_INVOICED, PERMANENCE_ARCHIVED, PERMANENCE_SEND, DECIMAL_ZERO
from repanier.models import Permanence from repanier.models import Permanence
from repanier.tools import reorder_offer_items, recalculate_order_amount from repanier.tools import recalculate_order_amount
from repanier.task import task_invoice
class Command(BaseCommand): class Command(BaseCommand):
...@@ -18,8 +10,15 @@ class Command(BaseCommand): ...@@ -18,8 +10,15 @@ class Command(BaseCommand):
help = 'Recalculate permanence profit' help = 'Recalculate permanence profit'
def handle(self, *args, **options): def handle(self, *args, **options):
for permanence in Permanence.objects.filter(status__gte=PERMANENCE_CLOSED).order_by('?'): for permanence in Permanence.objects.filter(
# id__in=[59, 58],
status__gte=PERMANENCE_CLOSED
).order_by('?'):
print ("%s %s" % (permanence.permanence_date, permanence.get_status_display())) print ("%s %s" % (permanence.permanence_date, permanence.get_status_display()))
# recalculate_order_amount(
# permanence_id=permanence.id,
# re_init=True
# )
permanence.recalculate_profit() permanence.recalculate_profit()
permanence.save() permanence.save()
...@@ -104,7 +104,7 @@ class Customer(models.Model): ...@@ -104,7 +104,7 @@ class Customer(models.Model):
verbose_name=_("delivery point"), verbose_name=_("delivery point"),
blank=True, null=True, default=None) blank=True, null=True, default=None)
is_active = models.BooleanField(_("is_active"), default=True) is_active = models.BooleanField(_("is_active"), default=True)
is_group = models.BooleanField(_("is_group"), default=False) is_group = models.BooleanField(_("is a group"), default=False)
may_order = models.BooleanField(_("may_order"), default=True) may_order = models.BooleanField(_("may_order"), default=True)
valid_email = models.NullBooleanField(_("valid_email"), default=None) valid_email = models.NullBooleanField(_("valid_email"), default=None)
subscribe_to_email = models.BooleanField(_("subscribe to email"), default=True) subscribe_to_email = models.BooleanField(_("subscribe to email"), default=True)
......
...@@ -120,6 +120,7 @@ class CustomerInvoice(models.Model): ...@@ -120,6 +120,7 @@ class CustomerInvoice(models.Model):
related_name='child_customer_invoice', related_name='child_customer_invoice',
blank=True, null=True, default=None, blank=True, null=True, default=None,
on_delete=models.PROTECT, db_index=True) on_delete=models.PROTECT, db_index=True)
is_group = models.BooleanField(_("is a group"), default=False)
def get_delta_price_with_tax(self): def get_delta_price_with_tax(self):
return self.delta_price_with_tax.amount return self.delta_price_with_tax.amount
...@@ -149,6 +150,14 @@ class CustomerInvoice(models.Model): ...@@ -149,6 +150,14 @@ class CustomerInvoice(models.Model):
@transaction.atomic @transaction.atomic
def set_delivery(self, delivery): def set_delivery(self, delivery):
# May not use delivery_id because it won't reload customer_invoice.delivery # May not use delivery_id because it won't reload customer_invoice.delivery
# Important
# Si c'est une facture du membre d'un groupe :
# self.customer_charged_id != self.customer_id
# self.customer_charged_id == owner of the group
# price_list_multiplier = DECIMAL_ONE
# Si c'est une facture lambda ou d'un groupe :
# self.customer_charged_id = self.customer_id
# price_list_multiplier may vary
from repanier.apps import REPANIER_SETTINGS_TRANSPORT, REPANIER_SETTINGS_MIN_TRANSPORT from repanier.apps import REPANIER_SETTINGS_TRANSPORT, REPANIER_SETTINGS_MIN_TRANSPORT
self.delivery = delivery self.delivery = delivery
if delivery is None: if delivery is None:
...@@ -190,7 +199,8 @@ class CustomerInvoice(models.Model): ...@@ -190,7 +199,8 @@ class CustomerInvoice(models.Model):
price_list_multiplier=delivery_point.price_list_multiplier, price_list_multiplier=delivery_point.price_list_multiplier,
transport=delivery_point.transport, transport=delivery_point.transport,
min_transport=delivery_point.min_transport, min_transport=delivery_point.min_transport,
is_order_confirm_send=True is_order_confirm_send=True,
is_group=True
) )
@transaction.atomic @transaction.atomic
...@@ -232,11 +242,58 @@ class CustomerInvoice(models.Model): ...@@ -232,11 +242,58 @@ class CustomerInvoice(models.Model):
def calculate_delta_price(self, confirm_order=False): def calculate_delta_price(self, confirm_order=False):
getcontext().rounding = ROUND_HALF_UP getcontext().rounding = ROUND_HALF_UP
if self.customer_charged is None or confirm_order: self.delta_price_with_tax.amount = DECIMAL_ZERO
# confirm_order : the customer confirm his/her order self.delta_vat.amount = DECIMAL_ZERO
# Important
# Si c'est une facture du membre d'un groupe :
# self.customer_charged_id == purchase.customer_charged_id != self.customer_id
# self.customer_charged_id == purchase.customer_charged_id == owner of the group
# self.price_list_multiplier = DECIMAL_ONE
# Si c'est une facture lambda ou d'un groupe :
# self.customer_charged_id == purchase.customer_charged_id = self.customer_id
# self.price_list_multiplier may vary
if self.customer_id == self.customer_charged_id:
if self.price_list_multiplier != DECIMAL_ONE:
result_set = purchase.Purchase.objects.filter(
permanence_id=self.permanence_id,
customer_invoice__customer_charged_id=self.customer_id,
is_resale_price_fixed=False
).order_by('?').aggregate(
Sum('customer_vat'),
Sum('deposit'),
Sum('selling_price')
)
if result_set["customer_vat__sum"] is not None:
total_vat = result_set["customer_vat__sum"]
else:
total_vat = DECIMAL_ZERO
if result_set["deposit__sum"] is not None:
total_deposit = result_set["deposit__sum"]
else:
total_deposit = DECIMAL_ZERO
if result_set["selling_price__sum"] is not None:
total_price_with_tax = result_set["selling_price__sum"]
else:
total_price_with_tax = DECIMAL_ZERO
total_price_with_tax_wo_deposit = total_price_with_tax - total_deposit
self.delta_price_with_tax.amount = -(
total_price_with_tax_wo_deposit - (
total_price_with_tax_wo_deposit * self.price_list_multiplier
).quantize(TWO_DECIMALS)
)
self.delta_vat.amount = -(
total_vat - (
total_vat * self.price_list_multiplier
).quantize(FOUR_DECIMALS)
)
result_set = purchase.Purchase.objects.filter( result_set = purchase.Purchase.objects.filter(
permanence_id=self.permanence_id, permanence_id=self.permanence_id,
customer_id=self.customer_id, customer_invoice__customer_charged_id=self.customer_id,
).order_by('?').aggregate( ).order_by('?').aggregate(
Sum('customer_vat'), Sum('customer_vat'),
Sum('deposit'), Sum('deposit'),
...@@ -245,7 +302,7 @@ class CustomerInvoice(models.Model): ...@@ -245,7 +302,7 @@ class CustomerInvoice(models.Model):
else: else:
result_set = purchase.Purchase.objects.filter( result_set = purchase.Purchase.objects.filter(
permanence_id=self.permanence_id, permanence_id=self.permanence_id,
customer_charged_id=self.customer_id, customer_id=self.customer_id,
).order_by('?').aggregate( ).order_by('?').aggregate(
Sum('customer_vat'), Sum('customer_vat'),
Sum('deposit'), Sum('deposit'),
...@@ -264,45 +321,6 @@ class CustomerInvoice(models.Model): ...@@ -264,45 +321,6 @@ class CustomerInvoice(models.Model):
else: else:
self.total_price_with_tax.amount = DECIMAL_ZERO self.total_price_with_tax.amount = DECIMAL_ZERO
if self.price_list_multiplier != DECIMAL_ONE:
result_set = purchase.Purchase.objects.filter(
permanence_id=self.permanence_id,
customer_id=self.customer_id,
is_resale_price_fixed=True
).order_by('?').aggregate(
Sum('customer_vat'),
Sum('deposit'),
Sum('selling_price')
)
if result_set["customer_vat__sum"] is not None:
total_vat = result_set["customer_vat__sum"]
else:
total_vat = DECIMAL_ZERO
if result_set["deposit__sum"] is not None:
total_deposit = result_set["deposit__sum"]
else:
total_deposit = DECIMAL_ZERO
if result_set["selling_price__sum"] is not None:
total_price_with_tax = result_set["selling_price__sum"]
else:
total_price_with_tax = DECIMAL_ZERO
total_price_with_tax_wo_deposit = total_price_with_tax - total_deposit
self.delta_price_with_tax.amount = -(
total_price_with_tax_wo_deposit - (
total_price_with_tax_wo_deposit * self.price_list_multiplier
).quantize(TWO_DECIMALS)
)
self.delta_vat.amount = -(
total_vat - (
total_vat * self.price_list_multiplier
).quantize(FOUR_DECIMALS)
)
else:
self.delta_price_with_tax.amount = DECIMAL_ZERO
self.delta_vat.amount = DECIMAL_ZERO
def calculate_delta_transport(self): def calculate_delta_transport(self):
self.delta_transport.amount = DECIMAL_ZERO self.delta_transport.amount = DECIMAL_ZERO
...@@ -310,7 +328,7 @@ class CustomerInvoice(models.Model): ...@@ -310,7 +328,7 @@ class CustomerInvoice(models.Model):
# Calculate transport only on master customer invoice # Calculate transport only on master customer invoice
# But take into account the children customer invoices # But take into account the children customer invoices
result_set = CustomerInvoice.objects.filter( result_set = CustomerInvoice.objects.filter(
master_permanence=self.permanence master_permanence_id=self.permanence_id
).order_by('?').aggregate( ).order_by('?').aggregate(
Sum('total_price_with_tax'), Sum('total_price_with_tax'),
Sum('delta_price_with_tax') Sum('delta_price_with_tax')
...@@ -347,11 +365,26 @@ class CustomerInvoice(models.Model): ...@@ -347,11 +365,26 @@ class CustomerInvoice(models.Model):
return False return False
def create_child(self, new_permanence): def create_child(self, new_permanence):
if self.customer_id != self.customer_charged_id:
# TODO : Créer la customer invoice du groupe
customer_invoice = CustomerInvoice.objects.filter(
permanence_id=self.permanence_id,
customer_id=self.customer_charged_id
).only("id").order_by('?')
if not customer_invoice.exists():
customer_invoice = CustomerInvoice.objects.create(
permanence_id=self.permanence_id,
customer_id=self.customer_charged_id,
customer_charged_id=self.customer_charged_id,
status=self.status
)
customer_invoice.set_delivery(delivery=None)
customer_invoice.save()
return CustomerInvoice.objects.create( return CustomerInvoice.objects.create(
permanence_id=new_permanence.id, permanence_id=new_permanence.id,
customer_id=self.customer_id, customer_id=self.customer_id,
master_permanence_id=self.permanence_id, master_permanence_id=self.permanence_id,
customer_charged_id=self.customer_id, customer_charged_id=self.customer_charged_id,
status=self.status status=self.status
) )
...@@ -396,6 +429,7 @@ class CustomerInvoice(models.Model): ...@@ -396,6 +429,7 @@ class CustomerInvoice(models.Model):
class ProducerInvoice(models.Model): class ProducerInvoice(models.Model):
producer = models.ForeignKey( producer = models.ForeignKey(
'Producer', verbose_name=_("producer"), 'Producer', verbose_name=_("producer"),
related_name='producer_invoice',
on_delete=models.PROTECT) on_delete=models.PROTECT)
permanence = models.ForeignKey( permanence = models.ForeignKey(
'Permanence', verbose_name=permanence_verbose_name(), 'Permanence', verbose_name=permanence_verbose_name(),
......
This diff is collapsed.
...@@ -109,7 +109,7 @@ class Producer(models.Model): ...@@ -109,7 +109,7 @@ class Producer(models.Model):
changeproductslist_url = urlresolvers.reverse( changeproductslist_url = urlresolvers.reverse(
'admin:repanier_product_changelist', 'admin:repanier_product_changelist',
) )
link = '<a href="%s?is_active__exact=1&producer_id=%s" class="btn addlink">&nbsp;%s</a>' \ link = '<a href="%s?is_active__exact=1&producer=%s" class="btn addlink">&nbsp;%s</a>' \
% (changeproductslist_url, str(self.id), _("his_products")) % (changeproductslist_url, str(self.id), _("his_products"))
return link return link
return EMPTY_STRING return EMPTY_STRING
......
...@@ -39,9 +39,9 @@ class Purchase(models.Model): ...@@ -39,9 +39,9 @@ class Purchase(models.Model):
producer.Producer, verbose_name=_("producer"), on_delete=models.PROTECT) producer.Producer, verbose_name=_("producer"), on_delete=models.PROTECT)
customer = models.ForeignKey( customer = models.ForeignKey(
'Customer', verbose_name=_("customer"), on_delete=models.PROTECT, db_index=True) 'Customer', verbose_name=_("customer"), on_delete=models.PROTECT, db_index=True)
customer_charged = models.ForeignKey( # customer_charged = models.ForeignKey(
'Customer', verbose_name=_("customer"), related_name='purchase_paid', blank=True, null=True, # 'Customer', verbose_name=_("customer"), related_name='purchase_paid', blank=True, null=True,
on_delete=models.PROTECT, db_index=True) # on_delete=models.PROTECT, db_index=True)
customer_producer_invoice = models.ForeignKey( customer_producer_invoice = models.ForeignKey(
'CustomerProducerInvoice', verbose_name=_("customer_producer_invoice"), 'CustomerProducerInvoice', verbose_name=_("customer_producer_invoice"),
# related_name = 'purchase_invoiced', # related_name = 'purchase_invoiced',
...@@ -416,13 +416,20 @@ def purchase_pre_save(sender, **kwargs): ...@@ -416,13 +416,20 @@ def purchase_pre_save(sender, **kwargs):
total_vat=F('total_vat') + delta_purchase_vat, total_vat=F('total_vat') + delta_purchase_vat,
total_deposit=F('total_deposit') + delta_deposit total_deposit=F('total_deposit') + delta_deposit
) )
delta_profit = delta_selling_price - delta_purchase_price - delta_selling_vat + delta_purchase_vat if purchase.offer_item.price_list_multiplier < DECIMAL_ONE or purchase.price_list_multiplier < DECIMAL_ONE:
permanence.Permanence.objects.filter(id=purchase.permanence_id).update( permanence.Permanence.objects.filter(id=purchase.permanence_id).update(
invoiced_with_tax=F('invoiced_with_tax') + delta_selling_price, total_purchase_with_tax=F('total_purchase_with_tax') + delta_selling_price,
vat=F('vat') + delta_selling_vat, total_selling_with_tax=F('total_selling_with_tax') + delta_selling_price,
deposit=F('deposit') + delta_deposit, total_purchase_vat=F('total_purchase_vat') + delta_selling_vat,
profit=F('profit') + delta_profit total_selling_vat=F('total_selling_vat') + delta_selling_vat,
) )
else:
permanence.Permanence.objects.filter(id=purchase.permanence_id).update(
total_purchase_with_tax=F('total_purchase_with_tax') + delta_purchase_price,
total_selling_with_tax=F('total_selling_with_tax') + delta_selling_price,
total_purchase_vat=F('total_purchase_vat') + delta_purchase_vat,
total_selling_vat=F('total_selling_vat') + delta_selling_vat,
)
# Do not do it twice # Do not do it twice
purchase.previous_quantity_ordered = purchase.quantity_ordered purchase.previous_quantity_ordered = purchase.quantity_ordered
purchase.previous_quantity_invoiced = purchase.quantity_invoiced purchase.previous_quantity_invoiced = purchase.quantity_invoiced
......
...@@ -17,6 +17,7 @@ from repanier.models import Producer ...@@ -17,6 +17,7 @@ from repanier.models import Producer
from repanier.models import ProducerInvoice from repanier.models import ProducerInvoice
from repanier.models import Product from repanier.models import Product
from repanier.models import Purchase from repanier.models import Purchase
from repanier.models import LUT_DeliveryPoint
from repanier.task import task_producer from repanier.task import task_producer
from repanier.tools import * from repanier.tools import *
...@@ -56,14 +57,18 @@ def generate_invoice(permanence, payment_date): ...@@ -56,14 +57,18 @@ def generate_invoice(permanence, payment_date):
).order_by('?').exists() ).order_by('?').exists()
if permanence_partially_invoiced: if permanence_partially_invoiced:
# Move the producers not invoiced into a new permanence # Move the producers not invoiced into a new permanence
producers_to_move = list(ProducerInvoice.objects.filter( producers_to_keep = list(Producer.objects.filter(
permanence_id=permanence.id, producer_invoice__permanence_id=permanence.id,
invoice_sort_order__isnull=True, producer_invoice__invoice_sort_order__isnull=True,
to_be_paid=False producer_invoice__to_be_paid=True).only('id').order_by('?'))
).values_list('producer_id', flat=True).order_by("producer_id")) permanence.producers.clear()
permanence.producers.add(*producers_to_keep)
producers_to_move = list(Producer.objects.filter(
producer_invoice__permanence_id=permanence.id,
producer_invoice__invoice_sort_order__isnull=True,
producer_invoice__to_be_paid=False).only('id').order_by('?'))
new_permanence = permanence.create_child(PERMANENCE_SEND) new_permanence = permanence.create_child(PERMANENCE_SEND)
new_permanence.producers.add(*producers_to_move)
ProducerInvoice.objects.filter( ProducerInvoice.objects.filter(
permanence_id=permanence.id, permanence_id=permanence.id,
producer_id__in=producers_to_move producer_id__in=producers_to_move
...@@ -91,41 +96,38 @@ def generate_invoice(permanence, payment_date): ...@@ -91,41 +96,38 @@ def generate_invoice(permanence, payment_date):
id=purchase.customer_invoice_id id=purchase.customer_invoice_id
).order_by('?').first() ).order_by('?').first()
new_customer_invoice = customer_invoice.create_child(new_permanence=new_permanence) new_customer_invoice = customer_invoice.create_child(new_permanence=new_permanence)
# Important : The customer_charged is null. This is required for calculate_and_save_delta_buyinggroup
new_customer_invoice.calculate_and_save_delta_buyinggroup()
new_customer_invoice.set_delivery(customer_invoice.delivery) new_customer_invoice.set_delivery(customer_invoice.delivery)
new_customer_invoice.save() # Important : The purchase customer charged must be calculated before calculate_and_save_delta_buyinggroup
Purchase.objects.filter( Purchase.objects.filter(
customer_invoice_id=customer_invoice.id, customer_invoice_id=customer_invoice.id,
producer_id__in=producers_to_move producer_id__in=producers_to_move
).order_by('?').update( ).order_by('?').update(
permanence_id=new_permanence.id, permanence_id=new_permanence.id,
customer_invoice_id=new_customer_invoice.id, customer_invoice_id=new_customer_invoice.id,
customer_charged_id=new_customer_invoice.customer_charged_id
) )
new_customer_invoice.calculate_and_save_delta_buyinggroup()
new_customer_invoice.save()
recalculate_order_amount( recalculate_order_amount(
permanence_id=new_permanence.id, permanence_id=new_permanence.id,
re_init=True re_init=True
) )
# Important : linked to task_invoice.cancel
# First pass, set customer_charged
for customer_invoice in CustomerInvoice.objects.filter(