Exemple #1
0
 def archive(self, request, queryset):
     permanence = queryset.order_by("?").first()
     if permanence is None or permanence.status not in [PERMANENCE_CLOSED, PERMANENCE_SEND]:
         user_message = _("Action canceled by the system.")
         user_message_level = messages.ERROR
         self.message_user(request, user_message, user_message_level)
         return None
     if permanence.status == PERMANENCE_CLOSED:
         permanence.set_status(PERMANENCE_SEND)
     Producer.objects.all().order_by("?").update(to_be_paid=True)
     user_message, user_message_level = task_invoice.admin_generate(
         request, permanence=permanence, payment_date=timezone.now().date()
     )
     self.message_user(request, user_message, user_message_level)
     return None
Exemple #2
0
    def generate_invoices(self, request, queryset):
        if "done" in request.POST:
            user_message = _("Action performed.")
            user_message_level = messages.INFO
            self.message_user(request, user_message, user_message_level)
            return None
        elif "cancel" in request.POST:
            user_message = _("Action canceled by the user.")
            user_message_level = messages.INFO
            self.message_user(request, user_message, user_message_level)
            return None
        permanence = queryset.order_by("?").first()
        if permanence is None or permanence.status != PERMANENCE_SEND:
            user_message = _("Action canceled by the system.")
            user_message_level = messages.ERROR
            self.message_user(request, user_message, user_message_level)
            return None
        previous_permanence_not_invoiced = (
            Permanence.objects.filter(status=PERMANENCE_SEND, permanence_date__lt=permanence.permanence_date)
            .order_by("permanence_date")
            .first()
        )
        if previous_permanence_not_invoiced is not None:
            user_message = _("You must first invoice the %(permanence)s.") % {
                "permanence": previous_permanence_not_invoiced
            }
            user_message_level = messages.WARNING
            self.message_user(request, user_message, user_message_level)
            return None

        next_permanence_not_invoiced = (
            Permanence.objects.filter(status=PERMANENCE_SEND, permanence_date__gte=permanence.permanence_date)
            .exclude(id=permanence.id)
            .order_by("permanence_date")
            .first()
        )
        if next_permanence_not_invoiced is not None:
            max_payment_date = next_permanence_not_invoiced.permanence_date - datetime.timedelta(days=1)
        else:
            max_payment_date = timezone.now().date()
        bank_account = (
            BankAccount.objects.filter(operation_status=BANK_LATEST_TOTAL)
            .only("operation_date")
            .order_by("-id")
            .first()
        )
        if bank_account is not None:
            if bank_account.operation_date > max_payment_date:
                max_payment_date = bank_account.operation_date
            min_payment_date = bank_account.operation_date
        else:
            # This cas should never occur because of the first bank aoocunt record created at startup if none exists
            # via config.save() in apps.
            min_payment_date = timezone.now().date()

        if max_payment_date < min_payment_date:
            max_payment_date = min_payment_date
        if "apply" in request.POST and admin.ACTION_CHECKBOX_NAME in request.POST:
            permanence_form = PermanenceInvoicedForm(request.POST)
            producer_invoiced_formset = ProducerInvoicedFormSet(request.POST)
            if permanence_form.is_valid() and producer_invoiced_formset.is_valid():
                payment_date = permanence_form.cleaned_data.get("payment_date")
                if payment_date < min_payment_date or payment_date > max_payment_date:
                    permanence_form.add_error(
                        "payment_date",
                        _("The payment date must be between %(min_payment_date)s and %(max_payment_date)s.")
                        % {
                            "min_payment_date": min_payment_date.strftime(settings.DJANGO_SETTINGS_DATE),
                            "max_payment_date": max_payment_date.strftime(settings.DJANGO_SETTINGS_DATE),
                        },
                    )
                else:
                    Producer.objects.all().order_by("?").order_by("?").update(to_be_paid=False)
                    for producer_invoiced_form in producer_invoiced_formset:
                        if producer_invoiced_form.is_valid() and producer_invoiced_form.has_changed():
                            selected = producer_invoiced_form.cleaned_data.get("selected")
                            short_profile_name = producer_invoiced_form.cleaned_data.get("short_profile_name")
                            producer = (
                                Producer.objects.filter(short_profile_name=short_profile_name).order_by("?").first()
                            )
                            if selected:
                                producer.to_be_paid = True
                                producer.save(update_fields=["to_be_paid"])
                            producer_invoice = (
                                ProducerInvoice.objects.filter(producer=producer.id, permanence_id=permanence.id)
                                .order_by("?")
                                .first()
                            )
                            producer_invoice.to_be_invoiced_balance = producer_invoiced_form.cleaned_data.get(
                                "to_be_invoiced_balance"
                            )
                            producer_invoice.invoice_reference = producer_invoiced_form.cleaned_data.get(
                                "invoice_reference"
                            )
                            if not producer_invoice.invoice_reference:
                                producer_invoice.invoice_reference = None
                            producer_invoice.save(update_fields=["to_be_invoiced_balance", "invoice_reference"])

                    user_message, user_message_level = task_invoice.admin_generate(
                        request, payment_date=payment_date, permanence=permanence
                    )
                    if user_message_level == messages.INFO:
                        previous_latest_total = (
                            BankAccount.objects.filter(
                                operation_status=BANK_NOT_LATEST_TOTAL, producer__isnull=True, customer__isnull=True
                            )
                            .order_by("-id")
                            .first()
                        )
                        previous_latest_total_id = previous_latest_total.id if previous_latest_total is not None else 0
                        return render(
                            request,
                            "repanier/confirm_admin_bank_movement.html",
                            {
                                "sub_title": _(
                                    "Please make the following payments, whose bank movements have been generated"
                                ),
                                "action": "generate_invoices",
                                "permanence": permanence,
                                "bankaccounts": BankAccount.objects.filter(
                                    id__gt=previous_latest_total_id,
                                    producer__isnull=False,
                                    producer__represent_this_buyinggroup=False,
                                    customer__isnull=True,
                                    operation_status=BANK_CALCULATED_INVOICE,
                                ).order_by("producer", "-operation_date", "-id"),
                                "action_checkbox_name": admin.ACTION_CHECKBOX_NAME,
                            },
                        )
        else:
            Producer.objects.all().order_by("?").update(to_be_paid=False)
            ProducerInvoice.objects.filter(permanence_id=permanence.id).order_by("?").update(
                delta_vat=DECIMAL_ZERO, delta_deposit=DECIMAL_ZERO, delta_price_with_tax=DECIMAL_ZERO
            )
            for producer in (
                Producer.objects.filter(
                    Q(producerinvoice__permanence=permanence.id)
                    | Q(is_active=True, balance__gt=0)
                    | Q(is_active=True, balance__lt=0)
                    | Q(is_active=True, represent_this_buyinggroup=True)
                )
                .order_by()
                .distinct()
            ):
                producer_invoice = (
                    ProducerInvoice.objects.filter(permanence_id=permanence.id, producer_id=producer.id)
                    .order_by("?")
                    .first()
                )
                if producer_invoice is None:
                    producer_invoice = ProducerInvoice.objects.create(
                        producer_id=producer.id, permanence_id=permanence.id, status=permanence.status
                    )
                if not producer.manage_production:
                    producer.to_be_paid = True
                    producer.save(update_fields=["to_be_paid"])
                    # We have already pay to much (look at the bank movements).
                    # So we do not need to pay anything
                    producer_invoice.calculated_invoiced_balance.amount = producer.get_calculated_invoiced_balance(
                        permanence.id
                    )
                else:
                    producer_invoice.calculated_invoiced_balance.amount = producer_invoice.total_price_with_tax.amount
                if permanence.highest_status == PERMANENCE_SEND:
                    # First time invoiced ? Yes : propose the calculated invoiced balance as to be invoiced balance
                    producer_invoice.to_be_invoiced_balance = producer_invoice.calculated_invoiced_balance
                    producer_invoice.save(update_fields=["calculated_invoiced_balance", "to_be_invoiced_balance"])
                else:
                    producer_invoice.save(update_fields=["calculated_invoiced_balance"])

            permanence_form = PermanenceInvoicedForm(payment_date=max_payment_date)

            qs = ProducerInvoice.objects.filter(producer__to_be_paid=True, permanence_id=permanence.id).order_by(
                "producer"
            )
            producer_invoiced = [
                {
                    "selected": True,
                    "short_profile_name": pi.producer.short_profile_name,
                    "calculated_invoiced_balance": pi.calculated_invoiced_balance,
                    "to_be_invoiced_balance": pi.to_be_invoiced_balance,
                    "invoice_reference": pi.invoice_reference,
                }
                for pi in qs
            ]
            producer_invoiced_formset = ProducerInvoicedFormSet(initial=producer_invoiced)

        return render(
            request,
            "repanier/confirm_admin_invoice.html",
            {
                "sub_title": _("Please, confirm the action : generate the invoices"),
                "action": "generate_invoices",
                "permanence": permanence,
                "permanence_form": permanence_form,
                "producer_invoiced_formset": producer_invoiced_formset,
                "action_checkbox_name": admin.ACTION_CHECKBOX_NAME,
            },
        )