コード例 #1
0
ファイル: forms.py プロジェクト: pcolmant/repanier
 def save(self, commit=True, use_https=False, request=None):
     super(AuthRepanierSetPasswordForm, self).save(commit)
     if commit:
         now = timezone.now()
         if self.user.is_superuser:
             Configuration.objects.filter(id=DECIMAL_ONE).update(
                 login_attempt_counter=DECIMAL_ZERO,
                 password_reset_on=now
             )
         else:
             customer = Customer.objects.filter(
                 user=self.user, is_active=True
             ).order_by('?').first()
             if customer is not None:
                 Customer.objects.filter(id=customer.id).update(
                     login_attempt_counter=DECIMAL_ZERO,
                     password_reset_on=now
                 )
         current_site = get_current_site(request)
         site_name = current_site.name
         domain = current_site.domain
         context = {
             'email': self.user.email,
             'domain': domain,
             'site_name': site_name,
             'user': self.user,
             'protocol': 'https' if use_https else 'http',
         }
         self.send_mail(get_repanier_template_name('registration/password_reset_done_subject.txt'),
                        get_repanier_template_name('registration/password_reset_done_email.html'),
                        context, self.user.email,
                        html_email_template_name=None)
     return self.user
コード例 #2
0
 def save(self, commit=True, use_https=False, request=None):
     super(AuthRepanierSetPasswordForm, self).save(commit)
     if commit:
         now = timezone.now()
         if self.user.is_superuser:
             Configuration.objects.filter(id=DECIMAL_ONE).update(
                 login_attempt_counter=DECIMAL_ZERO, password_reset_on=now)
         else:
             customer = Customer.objects.filter(
                 user=self.user, is_active=True).order_by('?').first()
             if customer is not None:
                 Customer.objects.filter(id=customer.id).update(
                     login_attempt_counter=DECIMAL_ZERO,
                     password_reset_on=now)
         current_site = get_current_site(request)
         site_name = current_site.name
         domain = current_site.domain
         context = {
             'email': self.user.email,
             'domain': domain,
             'site_name': site_name,
             'user': self.user,
             'protocol': 'https' if use_https else 'http',
         }
         self.send_mail(get_repanier_template_name(
             'registration/password_reset_done_subject.txt'),
                        get_repanier_template_name(
                            'registration/password_reset_done_email.html'),
                        context,
                        self.user.email,
                        html_email_template_name=None)
     return self.user
コード例 #3
0
ファイル: who_is_who_view.py プロジェクト: pcolmant/repanier
def who_is_who_view(request):
    from repanier.apps import REPANIER_SETTINGS_DISPLAY_WHO_IS_WHO
    if not REPANIER_SETTINGS_DISPLAY_WHO_IS_WHO:
        raise Http404
    q = request.POST.get('q', None)
    customer_list = Customer.objects.filter(may_order=True, represent_this_buyinggroup=False).order_by(
        "long_basket_name")
    if q is not None:
        customer_list = customer_list.filter(Q(long_basket_name__icontains=q) | Q(city__icontains=q))
    staff_list = Staff.objects.filter(
        is_active=True, can_be_contacted=True
    )
    try:
        is_repanier_admin = request.user.is_repanier_admin
    except AttributeError:
        is_repanier_admin = False
    template_name = get_repanier_template_name("who_is_who.html")
    return render(
        request,
        template_name,
        {
            'staff_list': staff_list,
            'customer_list': customer_list,
            'coordinator': is_repanier_admin,
            'q': q
        }
    )
コード例 #4
0
 def generate_permanence(self, request, queryset):
     if "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
     permanence = queryset.first()
     if permanence.status not in [
             PERMANENCE_PLANNED,
             PERMANENCE_OPENED,
             PERMANENCE_CLOSED,
             PERMANENCE_SEND,
     ]:
         user_message = _(
             "The status of %(permanence)s prohibit you to perform this action."
         ) % {
             "permanence": permanence
         }
         user_message_level = messages.ERROR
         self.message_user(request, user_message, user_message_level)
         return
     if "apply" in request.POST:
         form = GeneratePermanenceForm(request.POST)
         if form.is_valid():
             recurrences = form.cleaned_data["recurrences"]
             dates = get_recurrence_dates(permanence.permanence_date,
                                          recurrences)
             creation_counter = permanence.duplicate(dates)
             if creation_counter == 0:
                 user_message = _("Nothing to do.")
             elif creation_counter == 1:
                 user_message = _("{} duplicate created.").format(
                     creation_counter)
             else:
                 user_message = _("{} duplicates created.").format(
                     creation_counter)
             user_message_level = messages.INFO
             self.message_user(request, user_message, user_message_level)
         return HttpResponseRedirect(request.get_full_path())
     else:
         form = GeneratePermanenceForm()
     template_name = get_repanier_template_name(
         "confirm_admin_generate_permanence.html")
     return render(
         request,
         template_name,
         {
             "sub_title":
             _("How many weekly permanence(s) do you want to generate from this ?"
               ),
             "action":
             "generate_permanence",
             "permanence":
             permanence,
             "form":
             form,
             "action_checkbox_name":
             admin.ACTION_CHECKBOX_NAME,
         },
     )
コード例 #5
0
 def cancel_delivery(self, request, permanence_qs):
     if '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
     permanence = permanence_qs.first()
     if permanence is None or permanence.status not in [
             PERMANENCE_CLOSED, PERMANENCE_SEND
     ]:
         user_message = _(
             "The status of %(permanence)s prohibit you to perform this action."
         ) % {
             'permanence': permanence
         }
         user_message_level = messages.ERROR
         self.message_user(request, user_message, user_message_level)
         return
     if 'apply' in request.POST:
         permanence.cancel_delivery()
         user_message = _("Action performed.")
         user_message_level = messages.INFO
         self.message_user(request, user_message, user_message_level)
         return
     template_name = get_repanier_template_name("confirm_admin_action.html")
     return render(
         request, template_name, {
             'sub_title': _("Please, confirm the action : cancel delivery"),
             'action': 'cancel_delivery',
             'permanence': permanence,
             'action_checkbox_name': admin.ACTION_CHECKBOX_NAME,
         })
コード例 #6
0
 def back_to_scheduled(self, request, permanence_id, permanence=None):
     if "apply" in request.POST:
         task_order.back_to_scheduled(permanence)
         user_message = _('The permanence is back to "Scheduled".')
         user_message_level = messages.INFO
         self.message_user(request, user_message, user_message_level)
         return HttpResponseRedirect(self.get_redirect_to_change_list_url())
     template_name = get_repanier_template_name("admin/confirm_action.html")
     return render(
         request,
         template_name,
         {
             **self.admin_site.each_context(request),
             "model_verbose_name_plural":
             _("Offers in preparation"),
             "sub_title":
             _("Please, confirm the action : back to scheduled"),
             "action":
             "back_to_scheduled",
             "permanence":
             permanence,
             "action_checkbox_name":
             admin.ACTION_CHECKBOX_NAME,
         },
     )
コード例 #7
0
ファイル: product.py プロジェクト: ryanbagwell/repanier
    def duplicate_product(self, request, product_id, product):
        if "apply" in request.POST:
            if "producers" in request.POST:
                producers = request.POST.getlist("producers", [])
                if len(producers) == 1:
                    producer = (
                        Producer.objects.filter(id=producers[0]).order_by("?").first()
                    )
                    if producer is not None:
                        user_message, user_message_level = task_product.admin_duplicate(
                            product, producer
                        )
                        self.message_user(request, user_message, user_message_level)
                    return HttpResponseRedirect(self.get_redirect_to_change_list_url())
            user_message = _("You must select one and only one producer.")
            user_message_level = messages.ERROR
            self.message_user(request, user_message, user_message_level)
            return HttpResponseRedirect(self.get_redirect_to_change_list_url())
        template_name = get_repanier_template_name(
            "admin/confirm_duplicate_product.html"
        )

        return render(
            request,
            template_name,
            {
                **self.admin_site.each_context(request),
                "action_checkbox_name": admin.ACTION_CHECKBOX_NAME,
                "action": "duplicate_product",
                "product": product,
                "producers": Producer.objects.filter(is_active=True),
            },
        )
コード例 #8
0
ファイル: permanence_done.py プロジェクト: pcolmant/repanier
    def generate_archive(self, request, permanence_qs):
        if '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
        permanence = permanence_qs.first()

        if permanence is None or permanence.status not in [
            PERMANENCE_CLOSED, PERMANENCE_SEND
        ]:
            user_message = _("The status of %(permanence)s prohibit you to perform this action.") % {
                'permanence': permanence}
            user_message_level = messages.ERROR
            self.message_user(request, user_message, user_message_level)
            return

        if 'apply' in request.POST:
            permanence.archive()
            user_message = _("Action performed.")
            user_message_level = messages.INFO
            self.message_user(request, user_message, user_message_level)
            return
        template_name = get_repanier_template_name("confirm_admin_action.html")
        return render(request, template_name, {
            'sub_title': _("Please, confirm the action : generate archive"),
            'action': 'generate_archive',
            'permanence': permanence,
            'action_checkbox_name': admin.ACTION_CHECKBOX_NAME,
        })
コード例 #9
0
class RepanierPictureWidget(widgets.TextInput):
    template_name = get_repanier_template_name("widgets/picture.html")

    def __init__(self, *args, **kwargs):
        self.upload_to = kwargs.pop('upload_to', 'pictures')
        self.size = kwargs.pop('size', SIZE_M)
        self.bootstrap = kwargs.pop('bootstrap', False)
        super(RepanierPictureWidget, self).__init__(*args, **kwargs)

    def get_context(self, name, value, attrs):
        context = super(RepanierPictureWidget,
                        self).get_context(name, value, attrs)
        context['upload_url'] = reverse('ajax_picture',
                                        args=(self.upload_to, self.size))
        if value:
            context['repanier_file_path'] = file_path = str(value)
            context['repanier_display_picture'] = "inline"
            context['repanier_display_upload'] = "none"
            context['repanier_file_url'] = default_storage.url(file_path)
        else:
            context['repanier_file_path'] = EMPTY_STRING
            context['repanier_display_picture'] = "none"
            context['repanier_display_upload'] = "inline"
            context['repanier_file_url'] = EMPTY_STRING

        context['repanier_height'] = context['repanier_width'] = self.size
        context['bootstrap'] = self.bootstrap
        return context

    class Media:
        js = ("admin/js/jquery.init.js", )
コード例 #10
0
ファイル: product.py プロジェクト: pcolmant/repanier
 def duplicate_product(self, request, queryset):
     if '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
     product = queryset.first()
     if 'apply' in request.POST:
         if "producers" in request.POST:
             producers = request.POST.getlist("producers", [])
             if len(producers) == 1:
                 producer = Producer.objects.filter(id=producers[0]).order_by('?').first()
                 if producer is not None:
                     user_message, user_message_level = task_product.admin_duplicate(queryset, producer)
                     self.message_user(request, user_message, user_message_level)
                 return
         user_message = _("You must select one and only one producer.")
         user_message_level = messages.ERROR
         self.message_user(request, user_message, user_message_level)
         return
     template_name = get_repanier_template_name("confirm_admin_duplicate_product.html")
     return render(
         request,
         template_name, {
             'sub_title': _("Please, confirm the action : duplicate product"),
             'action_checkbox_name': admin.ACTION_CHECKBOX_NAME,
             'action': 'duplicate_product',
             'product': product,
             'producers': Producer.objects.filter(is_active=True)
         })
コード例 #11
0
def send_mail_to_coordinators_view(request):
    template_name = get_repanier_template_name(
        "send_mail_to_coordinators.html")
    if request.method == "POST":
        form = CoordinatorsContactForm(request.POST)
        if form.is_valid():
            to_email = [request.user.email]
            selected_staff_members = form.cleaned_data.get("staff")
            for staff in Staff.objects.filter(
                    is_active=True,
                    can_be_contacted=True,
                    id__in=selected_staff_members).order_by("?"):
                to_email = list(set(to_email + staff.get_to_email))

            email = RepanierEmail(
                strip_tags(form.cleaned_data.get("subject")),
                html_body=strip_tags(form.cleaned_data.get("message")),
                to=to_email,
                show_customer_may_unsubscribe=False,
                send_even_if_unsubscribed=True,
            )
            t = threading.Thread(target=email.send_email)
            t.start()
            email = form.fields["your_email"]
            email.initial = request.user.email
            email.widget.attrs["readonly"] = True
            return render(request, template_name, {"form": form, "send": True})
    else:
        form = CoordinatorsContactForm()

        email = form.fields["your_email"]
        email.initial = request.user.email
        email.widget.attrs["readonly"] = True

    return render(request, template_name, {"form": form, "send": None})
コード例 #12
0
 def archive(self, request, permanence_id, permanence=None):
     if "apply" in request.POST:
         permanence.archive()
         user_message = _("Action performed.")
         user_message_level = messages.INFO
         self.message_user(request, user_message, user_message_level)
         return HttpResponseRedirect(self.get_redirect_to_change_list_url())
     template_name = get_repanier_template_name("admin/confirm_action.html")
     return render(
         request,
         template_name,
         {
             **self.admin_site.each_context(request),
             "model_verbose_name_plural":
             _("Billing offers"),
             "sub_title":
             _("Please, confirm the action : generate archive."),
             "action":
             "archive",
             "permanence":
             permanence,
             "action_checkbox_name":
             admin.ACTION_CHECKBOX_NAME,
         },
     )
コード例 #13
0
class PermanenceView(ListView):
    template_name = get_repanier_template_name("task_form.html")
    success_url = '/'
    paginate_by = 50
    paginate_orphans = 5

    def get_context_data(self, **kwargs):
        context = super(PermanenceView, self).get_context_data(**kwargs)
        context[
            'DISPLAY_PRODUCER'] = settings.REPANIER_SETTINGS_SHOW_PRODUCER_ON_ORDER_FORM

        if self.request.user.is_anonymous:
            from repanier.apps import REPANIER_SETTINGS_CONFIG

            context[
                'how_to_register'] = REPANIER_SETTINGS_CONFIG.safe_translation_getter(
                    'how_to_register', any_language=True, default=EMPTY_STRING)
        else:
            context['how_to_register'] = EMPTY_STRING

        return context

    def get_queryset(self):
        qs = PermanenceBoard.objects.filter(
            permanence__status__lte=PERMANENCE_SEND,
            permanence__master_permanence__isnull=True,
            permanence_role__rght=F('permanence_role__lft') + 1,
            permanence_role__is_active=True).order_by(
                "permanence_date", "permanence_role__tree_id",
                "permanence_role__lft")
        return qs
コード例 #14
0
 def back_to_scheduled(self, request, queryset):
     if "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
     permanence = queryset.first()
     if permanence.status != PERMANENCE_OPENED:
         user_message = _(
             "The status of %(permanence)s prohibit you to perform this action."
         ) % {
             "permanence": permanence
         }
         user_message_level = messages.ERROR
         self.message_user(request, user_message, user_message_level)
         return
     if "apply" in request.POST:
         task_order.back_to_scheduled(permanence)
         user_message = _("The permanence is back to scheduled.")
         user_message_level = messages.INFO
         self.message_user(request, user_message, user_message_level)
         return
     template_name = get_repanier_template_name("confirm_admin_action.html")
     return render(
         request,
         template_name,
         {
             "sub_title":
             _("Please, confirm the action : back to scheduled"),
             "action": "back_to_scheduled",
             "permanence": permanence,
             "action_checkbox_name": admin.ACTION_CHECKBOX_NAME,
         },
     )
コード例 #15
0
 def back_to_scheduled(self, request, queryset):
     if '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
     permanence = queryset.first()
     if permanence.status != PERMANENCE_OPENED:
         user_message = _("The status of %(permanence)s prohibit you to perform this action.") % {
             'permanence': permanence}
         user_message_level = messages.ERROR
         self.message_user(request, user_message, user_message_level)
         return
     if 'apply' in request.POST:
         task_order.back_to_scheduled(permanence)
         user_message = _("The permanence is back to scheduled.")
         user_message_level = messages.INFO
         self.message_user(request, user_message, user_message_level)
         return
     template_name = get_repanier_template_name("confirm_admin_action.html")
     return render(request, template_name, {
         'sub_title': _("Please, confirm the action : back to scheduled"),
         'action': 'back_to_scheduled',
         'permanence': permanence,
         'action_checkbox_name': admin.ACTION_CHECKBOX_NAME,
     })
コード例 #16
0
class SelectAdminPermanenceWidget(forms.Select):
    template_name = get_repanier_template_name(
        "widgets/select_admin_purchase_qty.html")

    def get_context(self, name, value, attrs):
        context = super(SelectAdminPermanenceWidget,
                        self).get_context(name, value, attrs)
        case_show_show = "case \"0\": "
        case_show_hide = "case \"0\": "
        case_hide_show = "case \"0\": "
        for option_value, option_label in self.choices:
            permanence = Permanence.objects.filter(
                id=option_value).order_by('?').only('status').first()
            if permanence is not None:
                status = permanence.status
                if status in [
                        PERMANENCE_PLANNED, PERMANENCE_OPENED,
                        PERMANENCE_CLOSED
                ]:
                    case_show_hide += "case \"{}\": ".format(option_value)
                elif status == PERMANENCE_SEND:
                    case_hide_show += "case \"{}\": ".format(option_value)
                else:
                    case_show_show += "case \"{}\": ".format(option_value)
        context["case_show_show"] = mark_safe(case_show_show)
        context["case_show_hide"] = mark_safe(case_show_hide)
        context["case_hide_show"] = mark_safe(case_hide_show)
        return context
コード例 #17
0
def repanier_user_bs4(context, *args, **kwargs):
    from repanier.apps import REPANIER_SETTINGS_DISPLAY_WHO_IS_WHO

    request = context["request"]
    user = request.user
    producer = None
    my_balance = EMPTY_STRING

    if user.is_authenticated and user.customer_id is not None:

        if settings.REPANIER_SETTINGS_MANAGE_ACCOUNTING:
            last_customer_invoice = (CustomerInvoice.objects.filter(
                customer__user_id=request.user.id,
                invoice_sort_order__isnull=False).only(
                    "balance",
                    "date_balance").order_by("-invoice_sort_order").first())
            if (last_customer_invoice is not None
                    and last_customer_invoice.balance < DECIMAL_ZERO):
                my_balance = _(
                    'My balance : <font color="red">%(balance)s</font> at %(date)s'
                ) % {
                    "balance":
                    last_customer_invoice.balance,
                    "date":
                    last_customer_invoice.date_balance.strftime(
                        settings.DJANGO_SETTINGS_DATE),
                }
            elif last_customer_invoice:
                my_balance = _(
                    'My balance : <font color="green">%(balance)s</font> at %(date)s'
                ) % {
                    "balance":
                    last_customer_invoice.balance,
                    "date":
                    last_customer_invoice.date_balance.strftime(
                        settings.DJANGO_SETTINGS_DATE),
                }
            else:
                my_balance = _("My balance")

    else:
        p_offer_uuid = kwargs.get("offer_uuid", None)
        if len(p_offer_uuid) == 36:
            producer = (Producer.objects.filter(
                offer_uuid=p_offer_uuid).only("long_profile_name").first())

    return mark_safe(
        render_to_string(
            get_repanier_template_name("widgets/header_user_dropdown.html"),
            {
                "user": user,
                "my_balance": my_balance,
                "producer": producer,
                "display_who_is_who": REPANIER_SETTINGS_DISPLAY_WHO_IS_WHO,
                "manage_accounting":
                settings.REPANIER_SETTINGS_MANAGE_ACCOUNTING,
            },
        ))
コード例 #18
0
def order_description_view(request, permanence_id):
    user = request.user
    customer = Customer.objects.filter(
        user_id=user.id, may_order=True).order_by('?').first()
    if customer is None:
        raise Http404
    translation.activate(customer.language)
    permanence = Permanence.objects.filter(id=permanence_id).order_by('?').first()
    permanence_ok_or_404(permanence)
    is_basket = request.GET.get('is_basket', EMPTY_STRING)
    is_like = request.GET.get('is_like', EMPTY_STRING)
    if permanence.contract is not None:
        all_dates = permanence.contract.all_dates
        len_all_dates = len(all_dates)
        if len_all_dates < 2:
            date_id = 'all'
        else:
            date_id = sint(request.GET.get('date'), -1)
            if date_id < 0 or date_id >= len_all_dates:
                date_id = 'all'
    else:
        all_dates = []
        date_id = 'all'
    producer_id = request.GET.get('producer', 'all')
    department_id = request.GET.get('department', 'all')
    box_id = request.GET.get('box', 'all')
    if box_id != 'all':
        is_box = True
        # Do not display "all department" as selected
        department_id = None
    else:
        is_box = False
    q = request.GET.get('q', None)

    template_name = get_repanier_template_name("order_description.html")
    return render(
        request, template_name,
        {
            'is_like': is_like,
            'is_basket': is_basket,
            'is_box': is_box,
            'q': q,
            'all_dates': all_dates,

            'date_id': date_id,
            'producer_id': producer_id,
            'department_id': department_id,
            'box_id': box_id,
            'permanence_id': permanence_id,
            'may_order': True,

            'permanence': permanence,

            'is_description_view': 'active'
        }
    )
コード例 #19
0
class ButtonTestMailConfigWidget(Widget):
    template_name = get_repanier_template_name(
        "widgets/button_test_mail_config.html")

    def __init__(self, attrs=None):
        super(ButtonTestMailConfigWidget, self).__init__(attrs=attrs)

    def get_context(self, name, value, attrs):
        context = super(ButtonTestMailConfigWidget,
                        self).get_context(name, value, attrs)
        return context
コード例 #20
0
class ImportInvoiceForm(ImportXlsxForm):
    template = get_repanier_template_name('import_invoice_xlsx.html')
    # Important : Here, the length of invoice_reference must be the same as of permanence.short_name
    invoice_reference = forms.CharField(label=_("Invoice reference"),
                                        max_length=50,
                                        required=False)
    producer = forms.ModelChoiceField(
        label=_('Producer'),
        queryset=Producer.objects.filter(is_active=True).all(),
        required=False)

    def __init__(self, *args, **kwargs):
        super(ImportInvoiceForm, self).__init__(*args, **kwargs)
        self.fields["invoice_reference"].widget.attrs[
            'style'] = "width:450px !important"
コード例 #21
0
class RepanierCheckboxWidget(CheckboxInput):
    template_name = get_repanier_template_name("widgets/checkbox.html")

    def __init__(self, label, attrs=None, check_test=None):
        # the label is rendered by the Widget class rather than by BoundField.label_tag()
        self.repanier_label = label
        super(RepanierCheckboxWidget, self).__init__(attrs=attrs,
                                                     check_test=check_test)

    def get_context(self, name, value, attrs):
        context = super(RepanierCheckboxWidget,
                        self).get_context(name, value, attrs)
        context['repanier_label'] = self.repanier_label
        return context

    class Media:
        css = {'all': (get_repanier_static_name("css/widgets/checkbox.css"), )}
コード例 #22
0
ファイル: money.py プロジェクト: ryanbagwell/repanier
class MoneyWidget(NumberInput):
    template_name = get_repanier_template_name("widgets/money.html")

    def __init__(self, attrs=None):
        super(MoneyWidget, self).__init__(attrs=attrs)

    def get_context(self, name, value, attrs):
        context = super(MoneyWidget, self).get_context(name, value, attrs)
        context[
            "repanier_currency_after"
        ] = repanier.apps.REPANIER_SETTINGS_AFTER_AMOUNT
        context["repanier_currency_str"] = (
            '<i class="fas fa-euro-sign"></i>'
            if repanier.apps.REPANIER_SETTINGS_CURRENCY_DISPLAY == "€"
            else repanier.apps.REPANIER_SETTINGS_CURRENCY_DISPLAY
        )
        return context
コード例 #23
0
ファイル: forms.py プロジェクト: ryanbagwell/repanier
class ImportInvoiceForm(forms.Form):
    template = get_repanier_template_name("admin/import_invoice.html")
    file_to_import = forms.FileField(label=_("File to import"),
                                     allow_empty_file=False)
    # Important : Here, the length of invoice_reference must be the same as of permanence.short_name
    invoice_reference = forms.CharField(label=_("Invoice reference"),
                                        max_length=50,
                                        required=False)
    producer = forms.ModelChoiceField(
        label=_("Producer"),
        queryset=Producer.objects.filter(is_active=True).all(),
        required=False,
    )

    def __init__(self, *args, **kwargs):
        super(ImportInvoiceForm, self).__init__(*args, **kwargs)
        self.fields["invoice_reference"].widget.attrs[
            "style"] = "width:450px !important"
コード例 #24
0
def who_is_who_view(request):
    from repanier.apps import REPANIER_SETTINGS_DISPLAY_WHO_IS_WHO
    if not REPANIER_SETTINGS_DISPLAY_WHO_IS_WHO:
        raise Http404
    q = request.POST.get('q', None)
    customer_list = Customer.objects.filter(
        may_order=True,
        represent_this_buyinggroup=False).order_by("long_basket_name")
    if q is not None:
        customer_list = customer_list.filter(
            Q(long_basket_name__icontains=q) | Q(city__icontains=q))
    staff_list = Staff.objects.filter(is_active=True, can_be_contacted=True)
    template_name = get_repanier_template_name("who_is_who.html")
    return render(request, template_name, {
        'staff_list': staff_list,
        'customer_list': customer_list,
        'q': q
    })
コード例 #25
0
 def generate_permanence(self, request, permanence_id, permanence=None):
     if "apply" in request.POST:
         form = GeneratePermanenceForm(request.POST)
         if form.is_valid():
             recurrences = form.cleaned_data["recurrences"]
             dates = get_recurrence_dates(permanence.permanence_date,
                                          recurrences)
             creation_counter = permanence.duplicate(dates)
             if creation_counter == 0:
                 user_message = _("Nothing to do.")
             elif creation_counter == 1:
                 user_message = _("{} duplicate created.").format(
                     creation_counter)
             else:
                 user_message = _("{} duplicates created.").format(
                     creation_counter)
             user_message_level = messages.INFO
             self.message_user(request, user_message, user_message_level)
         return HttpResponseRedirect(self.get_redirect_to_change_list_url())
     else:
         form = GeneratePermanenceForm()
     template_name = get_repanier_template_name(
         "admin/confirm_generate_permanence.html")
     return render(
         request,
         template_name,
         {
             **self.admin_site.each_context(request),
             "action":
             "generate_permanence",
             "permanence":
             permanence,
             "permanenceboard":
             PermanenceBoard.objects.filter(
                 permanence=permanence_id).order_by("permanence_role"),
             "deliverypoint":
             DeliveryBoard.objects.filter(
                 permanence=permanence_id).order_by("delivery_point"),
             "form":
             form,
             "action_checkbox_name":
             admin.ACTION_CHECKBOX_NAME,
         },
     )
コード例 #26
0
class SelectBootstrapWidget(forms.Select):
    template_name = get_repanier_template_name("widgets/select_bootstrap.html")

    def get_context(self, name, value, attrs):
        context = super(SelectBootstrapWidget,
                        self).get_context(name, value, attrs)
        selected_label = EMPTY_STRING
        if value is None:
            # This is the "Empty Value" for ModelChoicesField
            value = EMPTY_STRING
        else:
            value = str(value)
        for choice in self.choices:
            if str(choice[0]) == value:
                selected_label = choice[1]
                break
        context['repanier_selected_label'] = selected_label
        context['repanier_selected_value'] = value
        return context
コード例 #27
0
ファイル: box.py プロジェクト: ryanbagwell/repanier
 def duplicate_box(self, request, queryset):
     if '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
     box = queryset.first()
     if 'apply' in request.POST:
         user_message, user_message_level = task_box.admin_duplicate(queryset)
         self.message_user(request, user_message, user_message_level)
         return
     template_name = get_repanier_template_name("admin/confirm_duplicate_box.html")
     return render(
         request,
         template_name, {
             'sub_title': _("Please, confirm the action : duplicate box."),
             'action_checkbox_name': admin.ACTION_CHECKBOX_NAME,
             'action': 'duplicate_box',
             'product': box,
         })
コード例 #28
0
ファイル: unsubscribe_view.py プロジェクト: jaliste/repanier
def unsubscribe_view(request, customer_id, token):
    """
    User is immediately unsubscribed
    if they came from an unexpired unsubscribe link.
    """

    customer = Customer.objects.filter(id=customer_id).order_by('?').first()

    if customer is not None and customer.check_token(token):
        # unsubscribe them
        # customer.save(update_fields=['subscribe_to_email'])
        # use vvvv because ^^^^^ will call "pre_save" function which reset valid_email to None
        if customer.subscribe_to_email:
            Customer.objects.filter(id=customer.id).order_by('?').update(
                subscribe_to_email=False)
        template_name = get_repanier_template_name(
            "registration/unsubscribe.html")
        return render(request, template_name)
    else:
        return HttpResponseRedirect("/")
コード例 #29
0
ファイル: box.py プロジェクト: pcolmant/repanier
 def duplicate_box(self, request, queryset):
     if '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
     box = queryset.first()
     if 'apply' in request.POST:
         user_message, user_message_level = task_box.admin_duplicate(queryset)
         self.message_user(request, user_message, user_message_level)
         return
     template_name = get_repanier_template_name("confirm_admin_duplicate_box.html")
     return render(
         request,
         template_name, {
             'sub_title': _("Please, confirm the action : duplicate box"),
             'action_checkbox_name': admin.ACTION_CHECKBOX_NAME,
             'action': 'duplicate_box',
             'product': box,
         })
コード例 #30
0
def order_description_view(request, permanence_id):
    user = request.user
    customer = Customer.objects.filter(
        user_id=user.id, may_order=True).first()
    if customer is None:
        raise Http404
    translation.activate(customer.language)
    permanence = Permanence.objects.filter(id=permanence_id).first()
    permanence_ok_or_404(permanence)
    is_basket = request.GET.get('is_basket', EMPTY_STRING)
    is_like = request.GET.get('is_like', EMPTY_STRING)
    producer_id = request.GET.get('producer', 'all')
    department_id = request.GET.get('department', 'all')
    box_id = request.GET.get('box', 'all')
    if box_id != 'all':
        is_box = True
        # Do not display "all department" as selected
        department_id = None
    else:
        is_box = False
    q = request.GET.get('q', None)

    template_name = get_repanier_template_name("order_description.html")
    return render(
        request, template_name,
        {
            'is_like': is_like,
            'is_basket': is_basket,
            'is_box': is_box,
            'q': q,
            'producer_id': producer_id,
            'department_id': department_id,
            'box_id': box_id,
            'permanence_id': permanence_id,
            'may_order': True,

            'permanence': permanence,

            'is_description_view': 'active'
        }
    )
コード例 #31
0
 def generate_permanence(self, request, queryset):
     if '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
     permanence = queryset.first()
     if permanence.status not in [
         PERMANENCE_PLANNED, PERMANENCE_PRE_OPEN, PERMANENCE_OPENED, PERMANENCE_CLOSED, PERMANENCE_SEND
     ]:
         user_message = _("The status of %(permanence)s prohibit you to perform this action.") % {
             'permanence': permanence}
         user_message_level = messages.ERROR
         self.message_user(request, user_message, user_message_level)
         return
     if 'apply' in request.POST:
         form = GeneratePermanenceForm(request.POST)
         if form.is_valid():
             recurrences = form.cleaned_data['recurrences']
             dates = get_recurrence_dates(permanence.permanence_date, recurrences)
             creation_counter = permanence.duplicate(dates)
             if creation_counter == 0:
                 user_message = _("Nothing to do.")
             elif creation_counter == 1:
                 user_message = _("{} duplicate created.").format(creation_counter)
             else:
                 user_message = _("{} duplicates created.").format(creation_counter)
             user_message_level = messages.INFO
             self.message_user(request, user_message, user_message_level)
         return HttpResponseRedirect(request.get_full_path())
     else:
         form = GeneratePermanenceForm()
     template_name = get_repanier_template_name("confirm_admin_generate_permanence.html")
     return render(request, template_name, {
         'sub_title': _("How many weekly permanence(s) do you want to generate from this ?"),
         'action': 'generate_permanence',
         'permanence': permanence,
         'form': form,
         'action_checkbox_name': admin.ACTION_CHECKBOX_NAME,
     })
コード例 #32
0
class SelectAdminDeliveryWidget(forms.Select):
    template_name = get_repanier_template_name("widgets/select_admin_purchase_qty.html")

    def get_context(self, name, value, attrs):
        context = super(SelectAdminDeliveryWidget, self).get_context(name, value, attrs)
        case_show_show = "case \"0\": "
        case_show_hide = "case \"0\": "
        case_hide_show = "case \"0\": "
        for option_value, option_label in self.choices:
            status = DeliveryBoard.objects.filter(id=option_value).order_by('?').only('status').first().status
            if status in [PERMANENCE_PLANNED, PERMANENCE_OPENED, PERMANENCE_CLOSED]:
                case_show_hide += "case \"{}\": ".format(option_value)
            elif status == PERMANENCE_SEND:
                case_hide_show += "case \"{}\": ".format(option_value)
            else:
                case_show_show += "case \"{}\": ".format(option_value)
        context["case_show_show"] = mark_safe(case_show_show)
        context["case_show_hide"] = mark_safe(case_show_hide)
        context["case_hide_show"] = mark_safe(case_hide_show)
        return context

    class Media:
        js = ("admin/js/jquery.init.js",)
コード例 #33
0
 def duplicate_product(self, request, queryset):
     if "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
     product = queryset.first()
     if "apply" in request.POST:
         if "producers" in request.POST:
             producers = request.POST.getlist("producers", [])
             if len(producers) == 1:
                 producer = (Producer.objects.filter(
                     id=producers[0]).order_by("?").first())
                 if producer is not None:
                     user_message, user_message_level = task_product.admin_duplicate(
                         queryset, producer)
                     self.message_user(request, user_message,
                                       user_message_level)
                 return
         user_message = _("You must select one and only one producer.")
         user_message_level = messages.ERROR
         self.message_user(request, user_message, user_message_level)
         return
     template_name = get_repanier_template_name(
         "confirm_admin_duplicate_product.html")
     return render(
         request,
         template_name,
         {
             "sub_title":
             _("Please, confirm the action : duplicate product"),
             "action_checkbox_name": admin.ACTION_CHECKBOX_NAME,
             "action": "duplicate_product",
             "product": product,
             "producers": Producer.objects.filter(is_active=True),
         },
     )
コード例 #34
0
def send_mail_to_coordinators_view(request):
    template_name = get_repanier_template_name("send_mail_to_coordinators.html")
    if request.method == 'POST':
        form = CoordinatorsContactForm(request.POST)
        if form.is_valid():
            to_email = [request.user.email]
            selected_staff_members = form.cleaned_data.get('staff')
            for staff in Staff.objects.filter(
                    is_active=True,
                    can_be_contacted=True,
                    id__in=selected_staff_members
            ).order_by('?'):
                to_email = list(set(to_email + staff.get_to_email))

            email = RepanierEmail(
                strip_tags(form.cleaned_data.get('subject')),
                html_body=strip_tags(form.cleaned_data.get('message')),
                to=to_email,
                show_customer_may_unsubscribe=False,
                send_even_if_unsubscribed=True
            )
            t = threading.Thread(target=email.send_email)
            t.start()
            email = form.fields["your_email"]
            email.initial = request.user.email
            email.widget.attrs['readonly'] = True
            return render(request, template_name,
                          {'form': form, 'send': True})
    else:
        form = CoordinatorsContactForm()

        email = form.fields["your_email"]
        email.initial = request.user.email
        email.widget.attrs['readonly'] = True

    return render(request, template_name, {'form': form, 'send': None})
コード例 #35
0
ファイル: order_ajax.py プロジェクト: pcolmant/repanier
def order_ajax(request):
    if not request.is_ajax():
        raise Http404
    user = request.user
    customer = Customer.objects.filter(
        user_id=user.id, may_order=True
    ).order_by('?').first()
    if customer is None:
        raise Http404
    offer_item_id = sint(request.GET.get('offer_item', 0))
    value_id = sint(request.GET.get('value', 0))
    is_basket = sboolean(request.GET.get('is_basket', False))
    qs = CustomerInvoice.objects.filter(
        permanence__offeritem=offer_item_id,
        customer_id=customer.id,
        status=PERMANENCE_OPENED).order_by('?')
    json_dict = {}
    if qs.exists():
        qs = ProducerInvoice.objects.filter(
            permanence__offeritem=offer_item_id,
            producer__offeritem=offer_item_id,
            status=PERMANENCE_OPENED
        ).order_by('?')
        if qs.exists():
            purchase, updated = create_or_update_one_cart_item(
                customer=customer,
                offer_item_id=offer_item_id,
                value_id=value_id,
                batch_job=False,
                comment=EMPTY_STRING
            )
            offer_item = OfferItemWoReceiver.objects.filter(
                id=offer_item_id
            ).order_by('?').first()
            if purchase is None:
                json_dict["#offer_item{}".format(offer_item.id)] = get_html_selected_value(offer_item, DECIMAL_ZERO,
                                                                                           is_open=True)
            else:
                json_dict["#offer_item{}".format(offer_item.id)] = get_html_selected_value(offer_item,
                                                                                           purchase.quantity_ordered,
                                                                                           is_open=True)
            if updated and offer_item.is_box:
                # update the content
                for content in BoxContent.objects.filter(
                        box=offer_item.product_id
                ).only(
                    "product_id"
                ).order_by('?'):
                    box_offer_item = OfferItemWoReceiver.objects.filter(
                        product_id=content.product_id,
                        permanence_id=offer_item.permanence_id
                    ).order_by('?').first()
                    if box_offer_item is not None:
                        # Select one purchase
                        purchase = PurchaseWoReceiver.objects.filter(
                            customer_id=customer.id,
                            offer_item_id=box_offer_item.id,
                            is_box_content=False
                        ).order_by('?').only('quantity_ordered').first()
                        if purchase is not None:
                            json_dict["#offer_item{}".format(box_offer_item.id)] = get_html_selected_value(
                                box_offer_item,
                                purchase.quantity_ordered,
                                is_open=True
                            )
                        box_purchase = PurchaseWoReceiver.objects.filter(
                            customer_id=customer.id,
                            offer_item_id=box_offer_item.id,
                            is_box_content=True
                        ).order_by('?').only('quantity_ordered').first()
                        if box_purchase is not None:
                            json_dict["#box_offer_item{}".format(box_offer_item.id)] = get_html_selected_box_value(
                                box_offer_item,
                                box_purchase.quantity_ordered
                            )

            if settings.REPANIER_SETTINGS_SHOW_PRODUCER_ON_ORDER_FORM:
                producer_invoice = ProducerInvoice.objects.filter(
                    producer_id=offer_item.producer_id, permanence_id=offer_item.permanence_id
                ).only("total_price_with_tax").order_by('?').first()
                json_dict.update(producer_invoice.get_order_json())

            customer_invoice = CustomerInvoice.objects.filter(
                permanence_id=offer_item.permanence_id,
                customer_id=customer.id
            ).order_by('?').first()
            invoice_confirm_status_is_changed = customer_invoice.cancel_confirm_order()
            if settings.REPANIER_SETTINGS_CUSTOMER_MUST_CONFIRM_ORDER and invoice_confirm_status_is_changed:
                template_name = get_repanier_template_name("communication_confirm_order.html")
                html = render_to_string(template_name)
                json_dict["#communicationModal"] = mark_safe(html)
                customer_invoice.save()

            json_dict.update(
                my_basket(customer_invoice.is_order_confirm_send, customer_invoice.get_total_price_with_tax()))
            permanence = Permanence.objects.filter(
                id=offer_item.permanence_id
            ).order_by('?').first()

            if is_basket:
                basket_message = get_html_basket_message(customer, permanence, PERMANENCE_OPENED)
            else:
                basket_message = EMPTY_STRING
            json_dict.update(customer_invoice.get_html_my_order_confirmation(
                permanence=permanence,
                is_basket=is_basket,
                basket_message=basket_message
            ))
    return JsonResponse(json_dict)
コード例 #36
0
ファイル: forms.py プロジェクト: pcolmant/repanier
from repanier.const import DECIMAL_ONE, DECIMAL_ZERO, LUT_PRODUCER_PRODUCT_ORDER_UNIT, EMPTY_STRING, LUT_VAT
from repanier.email.email import RepanierEmail
from repanier.models.configuration import Configuration
from repanier.models.customer import Customer
from repanier.models.lut import LUT_ProductionMode
from repanier.models.staff import Staff
from repanier.picture.const import SIZE_M
from repanier.tools import get_repanier_template_name
from repanier.widget.picture import RepanierPictureWidget
from repanier.widget.select_bootstrap import SelectBootstrapWidget
from repanier.widget.select_producer_order_unit import SelectProducerOrderUnitWidget

logger = logging.getLogger(__name__)

template_password_reset_email = get_repanier_template_name(
    os.path.join("registration", "password_reset_email.html")
)


class AuthRepanierPasswordResetForm(PasswordResetForm):
    def send_mail(self, subject_template_name, email_template_name,
                  context, from_email, to_email, html_email_template_name=None):
        """
        Sends a django.core.mail.EmailMultiAlternatives to `to_email`.
        """
        subject = loader.render_to_string(subject_template_name, context)
        html_body = loader.render_to_string(template_password_reset_email, context)

        if settings.REPANIER_SETTINGS_DEMO:
            to_email = settings.REPANIER_DEMO_EMAIL
        email = RepanierEmail(
コード例 #37
0
 def export_xlsx_customer_order(self, request, queryset):
     if '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
     permanence = queryset.first()
     if permanence.status not in [PERMANENCE_OPENED, PERMANENCE_CLOSED, PERMANENCE_SEND]:
         user_message = _("The status of %(permanence)s prohibit you to perform this action.") % {
             'permanence': permanence}
         user_message_level = messages.ERROR
         self.message_user(request, user_message, user_message_level)
         return
     if not permanence.with_delivery_point:
         # Perform the action directly. Do not ask to select any delivery point.
         response = None
         wb = generate_customer_xlsx(permanence=permanence)[0]
         if wb is not None:
             response = HttpResponse(
                 content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
             response['Content-Disposition'] = "attachment; filename={0}-{1}.xlsx".format(
                 _("Customers"),
                 permanence
             )
             wb.save(response)
         return response
     if 'apply' in request.POST:
         if admin.ACTION_CHECKBOX_NAME in request.POST:
             deliveries_to_be_exported = request.POST.getlist("deliveries", [])
             if len(deliveries_to_be_exported) == 0:
                 user_message = _("You must select at least one delivery point.")
                 user_message_level = messages.WARNING
                 self.message_user(request, user_message, user_message_level)
                 return
                 # Also display order without delivery point -> The customer has not selected it yet
                 # deliveries_to_be_exported.append(None)
         else:
             deliveries_to_be_exported = ()
         response = None
         wb = generate_customer_xlsx(permanence=permanence, deliveries_id=deliveries_to_be_exported)[0]
         if wb is not None:
             response = HttpResponse(
                 content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
             response['Content-Disposition'] = "attachment; filename={0}-{1}.xlsx".format(
                 _("Customers"),
                 permanence
             )
             wb.save(response)
         return response
     template_name = get_repanier_template_name("confirm_admin_export_customer_order.html")
     return render(
         request,
         template_name, {
             'sub_title': _("Please, confirm the action : Export customer orders"),
             'action_checkbox_name': admin.ACTION_CHECKBOX_NAME,
             'action': 'export_xlsx_customer_order',
             'permanence': permanence,
             'deliveries': DeliveryBoard.objects.filter(
                 permanence_id=permanence.id
             ),
         })
コード例 #38
0
ファイル: permanence_done.py プロジェクト: pcolmant/repanier
    def generate_invoices(self, request, permanence_qs):
        if 'done' in request.POST:
            user_message = _("Action performed.")
            user_message_level = messages.INFO
            self.message_user(request, user_message, user_message_level)
            return
        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
        permanence = permanence_qs.first()
        if permanence.status != PERMANENCE_SEND:
            user_message = _("The status of %(permanence)s prohibit you to perform this action.") % {
                'permanence': permanence}
            user_message_level = messages.ERROR
            self.message_user(request, user_message, user_message_level)
            return

        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:
                    at_least_one_selected = False
                    for producer_invoiced_form in producer_invoiced_formset:
                        if producer_invoiced_form.is_valid():
                            selected = producer_invoiced_form.cleaned_data.get('selected')
                            short_profile_name = producer_invoiced_form.cleaned_data.get('short_profile_name')
                            producer_invoice = ProducerInvoice.objects.filter(
                                permanence_id=permanence.id,
                                invoice_sort_order__isnull=True,
                                producer__short_profile_name=short_profile_name,
                            ).order_by(
                                '?'
                            ).first()
                            if selected:
                                at_least_one_selected = True
                                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', EMPTY_STRING)
                                producer_invoice.to_be_paid = True
                            else:
                                producer_invoice.to_be_invoiced_balance = DECIMAL_ZERO
                                producer_invoice.invoice_reference = EMPTY_STRING
                                producer_invoice.to_be_paid = False
                            producer_invoice.delta_vat = DECIMAL_ZERO
                            producer_invoice.delta_deposit = DECIMAL_ZERO
                            producer_invoice.delta_price_with_tax = DECIMAL_ZERO
                            producer_invoice.save(
                                update_fields=[
                                    'to_be_invoiced_balance', 'invoice_reference',
                                    'delta_vat', 'delta_deposit', 'delta_price_with_tax',
                                    'to_be_paid'
                                ]
                            )
                    if at_least_one_selected:
                        permanence.invoice(payment_date=payment_date)
                        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
                        template_name = get_repanier_template_name("confirm_admin_bank_movement.html")
                        return render(request, template_name, {
                            '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:
                        user_message = _("You must select at least one producer.")
                        user_message_level = messages.WARNING
                        self.message_user(request, user_message, user_message_level)
                        return
        else:
            producer_invoiced = []
            for producer_invoice in ProducerInvoice.objects.filter(
                    permanence_id=permanence.id,
                    invoice_sort_order__isnull=True,
            ).order_by("producer").select_related("producer"):
                producer = producer_invoice.producer
                if not producer.represent_this_buyinggroup:
                    # 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.get_total_price_with_tax().amount
                # 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'
                ])
                producer_invoiced.append({
                    'selected': True,
                    'short_profile_name': producer_invoice.producer.short_profile_name,
                    'calculated_invoiced_balance': producer_invoice.calculated_invoiced_balance,
                    'to_be_invoiced_balance': producer_invoice.to_be_invoiced_balance,
                    'invoice_reference': producer_invoice.invoice_reference
                })
            if permanence.payment_date is not None:
                # In this case we have also, permanence.status > PERMANENCE_SEND
                permanence_form = PermanenceInvoicedForm(payment_date=permanence.payment_date)
            else:
                permanence_form = PermanenceInvoicedForm(payment_date=max_payment_date)

            producer_invoiced_formset = ProducerInvoicedFormSet(initial=producer_invoiced)

        template_name = get_repanier_template_name("confirm_admin_invoice.html")
        return render(request, template_name, {
            '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,
        })
コード例 #39
0
ファイル: delivery_ajax.py プロジェクト: pcolmant/repanier
from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.http import Http404, JsonResponse
from django.template.loader import render_to_string
from django.utils.safestring import mark_safe
from django.views.decorators.cache import never_cache
from django.views.decorators.http import require_GET

from repanier.const import PERMANENCE_OPENED
from repanier.models.customer import Customer
from repanier.models.deliveryboard import DeliveryBoard
from repanier.models.invoice import CustomerInvoice
from repanier.models.permanence import Permanence
from repanier.tools import sint, sboolean, my_basket, get_repanier_template_name, get_html_basket_message

template_communication_confirm_order = get_repanier_template_name("communication_confirm_order.html")


@never_cache
@require_GET
@login_required
def delivery_ajax(request):
    if not request.is_ajax():
        raise Http404
    user = request.user
    permanence_id = sint(request.GET.get('permanence', 0))
    permanence = Permanence.objects.filter(
        id=permanence_id
    ).only("id", "status").order_by('?').first()
    if permanence is None:
        raise Http404
コード例 #40
0
ファイル: urls.py プロジェクト: pcolmant/repanier
from repanier.views.task_class import PermanenceView
from repanier.views.task_form_ajax import task_form_ajax
from repanier.views.test_mail_config_ajax import test_mail_config_ajax
from repanier.views.unsubscribe_view import unsubscribe_view
from repanier.views.who_is_who_view import who_is_who_view
from repanier.views.order_description_view import order_description_view

urlpatterns = [
    url(r'^go_repanier/$', login_view, name='login_form'),
    url(r'^leave_repanier/$', logout_view, name='logout'),
    url(r'^coordi/password_reset/$', auth_views.password_reset,
        {
            'post_reset_redirect': 'done/',
            # The form bellow is responsible of sending the recovery email
            'password_reset_form': AuthRepanierPasswordResetForm,
            'template_name': get_repanier_template_name('registration/password_reset_form.html')
        },
        name='admin_password_reset'),
    url(r'^coordi/password_reset/done/$', auth_views.password_reset_done,
        {
            'template_name': get_repanier_template_name('registration/password_reset_done.html')
        },
        name='password_reset_done'),
    url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>.+)/$', auth_views.password_reset_confirm,
        {
            'set_password_form': AuthRepanierSetPasswordForm,
            'template_name': get_repanier_template_name('registration/password_reset_confirm.html')
        },
        name='password_reset_confirm'),
    url(r'^reset/done/$', auth_views.password_reset_complete,
        {
コード例 #41
0
ファイル: order_init_ajax.py プロジェクト: pcolmant/repanier
def order_init_ajax(request):
    if not request.is_ajax():
        raise Http404
    permanence_id = sint(request.GET.get('pe', 0))
    permanence = Permanence.objects.filter(id=permanence_id).order_by('?').first()
    permanence_ok_or_404(permanence)
    user = request.user
    customer = Customer.objects.filter(
        user_id=user.id, may_order=True
    ).only(
        "id", "vat_id", "short_basket_name", "email2", "delivery_point",
        "balance", "date_balance", "may_order"
    ).order_by('?').first()
    if customer is None:
        raise Http404
    customer_invoice = CustomerInvoice.objects.filter(
        permanence_id=permanence.id,
        customer_id=customer.id
    ).order_by('?').first()
    if customer_invoice is None:
        customer_invoice = CustomerInvoice.objects.create(
            permanence_id=permanence.id,
            customer_id=customer.id,
            status=permanence.status,
            customer_charged_id=customer.id,
        )
        customer_invoice.set_order_delivery(delivery=None)
        customer_invoice.calculate_order_price()
        customer_invoice.save()

    if customer_invoice is None:
        raise Http404

    basket = sboolean(request.GET.get('ba', False))

    if customer_invoice.delivery is not None:
        status = customer_invoice.delivery.status
    else:
        status = customer_invoice.status
    if status <= PERMANENCE_OPENED:
        basket_message = get_html_basket_message(customer, permanence, status)
    else:
        if customer_invoice.delivery is not None:
            basket_message = EMPTY_STRING
        else:
            basket_message = "{}".format(
                _('The orders are closed.')
            )
    if settings.REPANIER_SETTINGS_TEMPLATE == "bs3":
        json_dict = customer_invoice.get_html_my_order_confirmation(
            permanence=permanence,
            is_basket=basket,
            basket_message=basket_message
        )
    else:
        json_dict = {}
    if customer.may_order:
        if settings.REPANIER_SETTINGS_SHOW_PRODUCER_ON_ORDER_FORM:
            for producer_invoice in ProducerInvoice.objects.filter(
                    permanence_id=permanence.id
            ).only(
                "total_price_with_tax", "status"
            ).order_by('?'):
                json_dict.update(producer_invoice.get_order_json())
        communication = sboolean(request.GET.get('co', False))
        if communication:
            now = timezone.now()
            permanence_boards = PermanenceBoard.objects.filter(
                customer_id=customer.id,
                permanence_date__gte=now,
                permanence__status__lte=PERMANENCE_WAIT_FOR_INVOICED
            ).order_by("permanence_date")[:2]
            from repanier.apps import REPANIER_SETTINGS_MAX_WEEK_WO_PARTICIPATION
            if REPANIER_SETTINGS_MAX_WEEK_WO_PARTICIPATION > DECIMAL_ZERO or len(permanence_boards) > 0:
                if len(permanence_boards) == 0:
                    count_activity = PermanenceBoard.objects.filter(
                        customer_id=customer.id, permanence_date__lt=now,
                        permanence_date__gte=now - datetime.timedelta(
                            days=float(REPANIER_SETTINGS_MAX_WEEK_WO_PARTICIPATION) * 7
                        )
                    ).count()
                else:
                    count_activity = None
                template_name = get_repanier_template_name("communication_permanence_board.html")
                html = render_to_string(
                    template_name,
                    {'permanence_boards': permanence_boards, 'count_activity': count_activity}
                )
                json_dict["#communicationModal"] = mark_safe(html)
    json_dict.update(my_basket(customer_invoice.is_order_confirm_send, customer_invoice.get_total_price_with_tax()))
    return JsonResponse(json_dict)
コード例 #42
0
class SelectProducerOrderUnitWidget(SelectBootstrapWidget):
    template_name = get_repanier_template_name(
        "widgets/select_producer_order_unit.html")
コード例 #43
0
def pre_order_create_product_ajax(request, permanence_id=None, offer_uuid=None):
    if permanence_id is None:
        raise Http404
    producer = Producer.objects.filter(offer_uuid=offer_uuid, is_active=True, producer_pre_opening=True).only(
        'id').order_by('?').first()
    if producer is None:
        template_name = get_repanier_template_name("pre_order_closed_form.html")
        return render(
            request,
            template_name,
        )

    permanence = get_object_or_404(Permanence, id=permanence_id)
    offer_item = None
    update = None
    if permanence.status == PERMANENCE_PRE_OPEN:
        if request.method == 'POST':  # If the form has been submitted...
            form = ProducerProductForm(request.POST)  # A form bound to the POST data
            if form.is_valid():
                long_name = form.cleaned_data.get('long_name')
                if long_name != _("Long name"):
                    order_unit = form.cleaned_data.get('order_unit')
                    producer_unit_price = form.cleaned_data.get('producer_unit_price')
                    stock = form.cleaned_data.get('stock')
                    if order_unit == PRODUCT_ORDER_UNIT_PC_KG:
                        customer_increment_order_quantity = form.cleaned_data.get(
                            'customer_increment_order_quantity').quantize(ONE_DECIMAL)
                        order_average_weight = form.cleaned_data.get('order_average_weight')
                        customer_alert_order_quantity = stock
                    else:
                        customer_increment_order_quantity = 1
                        order_average_weight = form.cleaned_data.get('customer_increment_order_quantity').quantize(
                            ONE_DECIMAL)
                        if order_average_weight <= DECIMAL_ZERO:
                            order_average_weight = DECIMAL_ONE
                        producer_unit_price = (producer_unit_price * order_average_weight).quantize(TWO_DECIMALS)
                        stock = customer_alert_order_quantity = stock / order_average_weight
                    unit_deposit = form.cleaned_data.get('unit_deposit')
                    vat_level = form.cleaned_data.get('vat_level')
                    offer_description = form.cleaned_data.get('offer_description')
                    customer_minimum_order_quantity = customer_increment_order_quantity
                    picture2 = form.cleaned_data.get('picture')
                    product = Product.objects.create(
                        producer_id=producer.id,
                        long_name=long_name,
                        order_unit=order_unit,
                        customer_increment_order_quantity=customer_increment_order_quantity,
                        customer_alert_order_quantity=customer_alert_order_quantity,
                        order_average_weight=order_average_weight,
                        producer_unit_price=producer_unit_price,
                        unit_deposit=unit_deposit,
                        stock=stock,
                        vat_level=vat_level,
                        offer_description=offer_description,
                        customer_minimum_order_quantity=customer_minimum_order_quantity,
                        picture2=picture2,
                        is_into_offer=True,
                        limit_order_quantity_to_stock=True,
                        is_active=True
                    )
                    production_mode = form.cleaned_data.get('production_mode', None)
                    if production_mode is not None:
                        product.production_mode.add(form.cleaned_data.get('production_mode'))
                    offer_item = product.get_or_create_offer_item(permanence, reset_add_2_stock=True)
                    update = True
                else:
                    update = False
        else:
            form = ProducerProductForm()  # An unbound form
            field = form.fields["long_name"]
            field.initial = _("Long name")
            field = form.fields["order_unit"]
            field.initial = PRODUCT_ORDER_UNIT_PC_PRICE_KG
            field = form.fields["order_average_weight"]
            field.initial = DECIMAL_ZERO
            field = form.fields["customer_increment_order_quantity"]
            field.initial = DECIMAL_ONE
            field = form.fields["producer_unit_price"]
            field.initial = DECIMAL_ZERO
            field = form.fields["unit_deposit"]
            field.initial = DECIMAL_ZERO
            field = form.fields["stock"]
            field.initial = DECIMAL_ZERO
            field = form.fields["vat_level"]
            field.initial = VAT_400
            field = form.fields["offer_description"]
            field.initial = EMPTY_STRING
            field = form.fields["picture"]
            field.widget.upload_to = "{}{}{}".format("product", os_sep, producer.id)
            update = None
        template_name = get_repanier_template_name('pre_order_create_product_form.html')
        return render(
            request,
            template_name,
            {'form': form, 'permanence_id': permanence_id, 'offer_uuid': offer_uuid, 'offer_item': offer_item,
             'producer': producer, 'update': update}
        )
    raise Http404
コード例 #44
0
    def close_and_send_order(self, request, queryset):
        if '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
        permanence = queryset.first()
        if permanence.status not in [PERMANENCE_OPENED, PERMANENCE_CLOSED]:
            user_message = _("The status of %(permanence)s prohibit you to perform this action.") % {
                'permanence': permanence}
            user_message_level = messages.ERROR
            self.message_user(request, user_message, user_message_level)
            return
        if 'apply' in request.POST:
            all_deliveries = True if request.POST.get("all-deliveries", True) else False
            deliveries_to_be_send = request.POST.getlist("deliveries", [])
            logger.debug("all_deliveries : {}".format(request.POST.get("all-deliveries")))
            logger.debug("all_deliveries : {}".format(all_deliveries))
            logger.debug("deliveries_to_be_send : {}".format(request.POST.getlist("deliveries", [])))
            if permanence.with_delivery_point and not all_deliveries and len(deliveries_to_be_send) == 0:
                user_message = _("You must select at least one delivery point.")
                user_message_level = messages.WARNING
                self.message_user(request, user_message, user_message_level)
                return
            # close_and_send_order(permanence.id, all_deliveries, deliveries_to_be_send)
            t = threading.Thread(target=close_and_send_order,
                                 args=(permanence.id, all_deliveries, deliveries_to_be_send))
            t.start()
            user_message = _("The orders are being send.")
            user_message_level = messages.INFO
            self.message_user(request, user_message, user_message_level)
            return

        template_order_customer_mail = []
        template_order_producer_mail = []
        template_order_staff_mail = []
        cur_language = translation.get_language()
        for language in settings.PARLER_LANGUAGES[settings.SITE_ID]:
            language_code = language["code"]
            translation.activate(language_code)

            template = Template(repanier.apps.REPANIER_SETTINGS_CONFIG.order_customer_mail)

            staff = Staff.get_or_create_order_responsible()

            customer_last_balance = \
                _('The balance of your account as of %(date)s is %(balance)s.') % {
                    'date': timezone.now().strftime(settings.DJANGO_SETTINGS_DATE),
                    'balance': RepanierMoney(123.45)
                }
            customer_on_hold_movement = \
                _(
                    'This balance does not take account of any unrecognized payments %(bank)s and any unbilled order %(other_order)s.') \
                % {
                    'bank': RepanierMoney(123.45),
                    'other_order': RepanierMoney(123.45)
                }

            bank_account_number = repanier.apps.REPANIER_SETTINGS_BANK_ACCOUNT
            if bank_account_number is not None:
                group_name = settings.REPANIER_SETTINGS_GROUP_NAME

                if permanence.short_name:
                    communication = "{} ({})".format(_('Short name'), permanence.short_name)
                else:
                    communication = _('Short name')
                customer_payment_needed = "<font color=\"#bd0926\">{}</font>".format(
                    _(
                        'Please pay a provision of %(payment)s to the bank account %(name)s %(number)s with communication %(communication)s.') % {
                        'payment': RepanierMoney(123.45),
                        'name': group_name,
                        'number': bank_account_number,
                        'communication': communication
                    }
                )
            else:
                customer_payment_needed = EMPTY_STRING
            context = TemplateContext({
                'name': _('Long name'),
                'long_basket_name': _('Long name'),
                'basket_name': _('Short name'),
                'short_basket_name': _('Short name'),
                'permanence_link': mark_safe("<a href=\"#\">{}</a>".format(permanence)),
                'last_balance': mark_safe("<a href=\"#\">{}</a>".format(customer_last_balance)),
                'order_amount': RepanierMoney(123.45),
                'on_hold_movement': mark_safe(customer_on_hold_movement),
                'payment_needed': mark_safe(customer_payment_needed),
                'delivery_point': _('Delivery point').upper(),
                'signature': staff.get_html_signature,
            })

            template_order_customer_mail.append(language_code)
            template_order_customer_mail.append(template.render(context))

            template = Template(repanier.apps.REPANIER_SETTINGS_CONFIG.order_producer_mail)
            context = TemplateContext({
                'name': _('Long name'),
                'long_profile_name': _('Long name'),
                'order_empty': False,
                'duplicate': True,
                'permanence_link': format_html("<a href=\"#\">{}</a>", permanence),
                'signature': staff.get_html_signature,
            })

            template_order_producer_mail.append(language_code)
            template_order_producer_mail.append(template.render(context))

            board_composition, board_composition_and_description = get_board_composition(permanence.id)
            template = Template(repanier.apps.REPANIER_SETTINGS_CONFIG.order_staff_mail)
            context = TemplateContext({
                'permanence_link': format_html("<a href=\"#\">{}</a>", permanence),
                'board_composition': mark_safe(board_composition),
                'board_composition_and_description': mark_safe(board_composition_and_description),
                'signature': staff.get_html_signature,
            })

            template_order_staff_mail.append(language_code)
            template_order_staff_mail.append(template.render(context))

        translation.activate(cur_language)

        order_customer_email_will_be_sent, order_customer_email_will_be_sent_to = RepanierEmail.send_email_to_who(
            is_email_send=True
        )
        order_producer_email_will_be_sent, order_producer_email_will_be_sent_to = RepanierEmail.send_email_to_who(
            is_email_send=True
        )
        order_board_email_will_be_sent, order_board_email_will_be_sent_to = RepanierEmail.send_email_to_who(
            is_email_send=repanier.apps.REPANIER_SETTINGS_SEND_ORDER_MAIL_TO_BOARD,
            board=True
        )

        form = CloseAndSendOrderForm(
            initial={
                'template_order_customer_mail': mark_safe(
                    "<br>==============<br>".join(template_order_customer_mail)),
                'template_order_producer_mail': mark_safe(
                    "<br>==============<br>".join(template_order_producer_mail)),
                'template_order_staff_mail': mark_safe("<br>==============<br>".join(template_order_staff_mail)),
            }
        )
        if permanence.with_delivery_point:
            deliveries = DeliveryBoard.objects.filter(
                permanence_id=permanence.id,
                status__in=[PERMANENCE_OPENED, PERMANENCE_CLOSED]
            )
        else:
            deliveries = DeliveryBoard.objects.none()
        template_name = get_repanier_template_name("confirm_admin_send_order.html")
        return render(
            request,
            template_name, {
                'sub_title': _("Please, confirm the action : send orders"),
                'action_checkbox_name': admin.ACTION_CHECKBOX_NAME,
                'action': 'close_and_send_order',
                'permanence': permanence,
                'with_delivery_point': permanence.with_delivery_point,
                'deliveries': deliveries,
                'form': form,
                'order_customer_email_will_be_sent': order_customer_email_will_be_sent,
                'order_customer_email_will_be_sent_to': order_customer_email_will_be_sent_to,
                'order_producer_email_will_be_sent': order_producer_email_will_be_sent,
                'order_producer_email_will_be_sent_to': order_producer_email_will_be_sent_to,
                'order_board_email_will_be_sent': order_board_email_will_be_sent,
                'order_board_email_will_be_sent_to': order_board_email_will_be_sent_to
            })
コード例 #45
0
ファイル: login_view.py プロジェクト: pcolmant/repanier
def login_view(request, template_name=EMPTY_STRING,
               redirect_field_name=REDIRECT_FIELD_NAME,
               authentication_form=AuthenticationForm,
               extra_context=None):
    """
    Displays the login form and handles the login action.
    """
    template_name = get_repanier_template_name('registration/login.html')
    redirect_to = request.POST.get(
        redirect_field_name,
        request.GET.get(redirect_field_name, EMPTY_STRING)
    )
    # Ensure the user-originating redirection url is safe.
    if not is_safe_url(url=redirect_to, allowed_hosts=request.get_host()):
        redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)

    staff_responsibilities = None
    user = request.user

    if request.method == "POST":
        form = authentication_form(request, data=request.POST)

        if form.is_valid():
            # Okay, security check complete. Log the user in.
            auth_login(request, form.get_user())

            # Now the logged in user is set in request.user
            user = request.user

            if user.is_authenticated:

                if user.is_staff:
                    return HttpResponseRedirect(
                        "{}?{}".format(redirect_to, get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON')))

                staff_qs = Staff.objects.filter(
                    customer_responsible_id=user.customer_id,
                    is_active=True
                ).order_by('?')
                may_become_a_staff_user = staff_qs.exists()

                if not may_become_a_staff_user:
                    return HttpResponseRedirect(redirect_to)

                # Ask the user to log in as a customer or as a staff member
                staff_responsibilities = staff_qs.all()

    else:
        if user.is_authenticated:
            as_staff_id = sint(request.GET.get('as_id', 0))

            if as_staff_id == 0:
                if user.is_superuser:
                    return HttpResponseRedirect(
                        "{}?{}".format(redirect_to, get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON')))
                else:
                    # The user want to be logged in as a customer
                    return HttpResponseRedirect(redirect_to)

            as_staff = Staff.objects.filter(
                id=as_staff_id,
                customer_responsible_id=user.customer_id,
                is_active=True
            ).order_by('?').first()

            if as_staff is None:
                # This should not occurs
                # But if ... then log the user as a customer
                return HttpResponseRedirect(redirect_to)

            RepanierAuthBackend.set_staff_right(
                request=request,
                user=user,
                as_staff=as_staff
            )
            return HttpResponseRedirect("{}?{}".format(redirect_to, get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON')))

    form = authentication_form(request)

    if user.is_anonymous:
        from repanier.apps import REPANIER_SETTINGS_CONFIG

        how_to_register = REPANIER_SETTINGS_CONFIG.safe_translation_getter(
            'how_to_register', any_language=True, default=EMPTY_STRING)
    else:
        how_to_register = EMPTY_STRING

    context = {
        'form': form,
        redirect_field_name: redirect_to,
        'how_to_register': how_to_register,
        'staff_responsibilities': staff_responsibilities,
    }
    if extra_context is not None:
        context.update(extra_context)
    return TemplateResponse(request, template_name, context)
コード例 #46
0
    def open_and_send_offer(self, request, queryset):
        if "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
        permanence = queryset.first()
        if permanence.status != PERMANENCE_PLANNED:
            user_message = _(
                "The status of %(permanence)s prohibit you to perform this action."
            ) % {
                "permanence": permanence
            }
            user_message_level = messages.ERROR
            self.message_user(request, user_message, user_message_level)
            return
        template_offer_mail = []
        template_cancel_order_mail = []
        cur_language = translation.get_language()
        for language in settings.PARLER_LANGUAGES[settings.SITE_ID]:
            language_code = language["code"]
            translation.activate(language_code)

            with switch_language(repanier.apps.REPANIER_SETTINGS_CONFIG,
                                 language_code):
                template = Template(
                    repanier.apps.REPANIER_SETTINGS_CONFIG.offer_customer_mail)

            staff = Staff.get_or_create_order_responsible()

            with switch_language(permanence, language_code):
                offer_description = permanence.safe_translation_getter(
                    "offer_description",
                    any_language=True,
                    default=EMPTY_STRING)
            offer_producer = ", ".join(
                [p.short_profile_name for p in permanence.producers.all()])
            qs = Product.objects.filter(
                producer=permanence.producers.first(),
                is_into_offer=True,
                order_unit__lt=
                PRODUCT_ORDER_UNIT_DEPOSIT,  # Don't display technical products.
            ).order_by("translations__long_name")[:5]
            offer_detail = "<ul>{}</ul>".format("".join(
                "<li>{}, {}</li>".format(p.get_long_name(),
                                         p.producer.short_profile_name)
                for p in qs))
            context = TemplateContext({
                "offer_description":
                mark_safe(offer_description),
                "offer_detail":
                offer_detail,
                "offer_recent_detail":
                offer_detail,
                "offer_producer":
                offer_producer,
                "permanence_link":
                mark_safe('<a href="#">{}</a>'.format(permanence)),
                "signature":
                staff.get_html_signature,
            })
            template_offer_mail.append(language_code)
            template_offer_mail.append(template.render(context))
            if settings.REPANIER_SETTINGS_CUSTOMER_MUST_CONFIRM_ORDER:
                context = TemplateContext({
                    "name":
                    _("Long name"),
                    "long_basket_name":
                    _("Long name"),
                    "basket_name":
                    _("Short name"),
                    "short_basket_name":
                    _("Short name"),
                    "permanence_link":
                    mark_safe('<a href="#">{}</a>'.format(permanence)),
                    "signature":
                    staff.get_html_signature,
                })
                template_cancel_order_mail.append(language_code)
                template_cancel_order_mail.append(template.render(context))
        translation.activate(cur_language)
        email_will_be_sent, email_will_be_sent_to = RepanierEmail.send_email_to_who(
        )
        if "apply" in request.POST or "apply-wo-mail" in request.POST:
            form = OpenAndSendOfferForm(request.POST)
            if form.is_valid():
                do_not_send_any_mail = "apply-wo-mail" in request.POST
                # open_order(permanence.id, do_not_send_any_mail)
                t = threading.Thread(target=open_order,
                                     args=(permanence.id,
                                           do_not_send_any_mail))
                t.start()
                user_message = _("The offers are being generated.")
                user_message_level = messages.INFO
                self.message_user(request, user_message, user_message_level)
            return HttpResponseRedirect(request.get_full_path())
        else:
            form = OpenAndSendOfferForm(
                initial={
                    "template_offer_customer_mail":
                    mark_safe("<br>==============<br>".join(
                        template_offer_mail)),
                    "template_cancel_order_customer_mail":
                    mark_safe("<br>==============<br>".join(
                        template_cancel_order_mail)),
                })
        template_name = get_repanier_template_name(
            "confirm_admin_open_and_send_offer.html")
        return render(
            request,
            template_name,
            {
                "sub_title":
                _("Please, confirm the action : open and send offers"),
                "action_checkbox_name": admin.ACTION_CHECKBOX_NAME,
                "action": "open_and_send_offer",
                "permanence": permanence,
                "form": form,
                "email_will_be_sent": email_will_be_sent,
                "email_will_be_sent_to": email_will_be_sent_to,
            },
        )
コード例 #47
0
def my_profile_view(request):
    user = request.user
    customer_is_active = (Customer.objects.filter(
        user_id=user.id, is_active=True).order_by("?").exists())
    if not customer_is_active:
        raise Http404
    customer = request.user.customer
    from repanier.apps import (
        REPANIER_SETTINGS_MEMBERSHIP_FEE,
        REPANIER_SETTINGS_DISPLAY_WHO_IS_WHO,
    )

    if REPANIER_SETTINGS_MEMBERSHIP_FEE > DECIMAL_ZERO:
        membership_fee_valid_until = customer.membership_fee_valid_until
    else:
        membership_fee_valid_until = None
    template_name = get_repanier_template_name("my_profile_form.html")
    if request.method == "POST":  # If the form has been submitted...
        form = CustomerForm(request.POST,
                            request=request)  # A form bound to the POST data
        if form.is_valid():  # All validation rules pass
            # Process the data in form.cleaned_data
            # ...
            if customer is not None:
                customer.long_basket_name = form.cleaned_data.get(
                    "long_basket_name")
                customer.phone1 = form.cleaned_data.get("phone1")
                customer.phone2 = form.cleaned_data.get("phone2")
                customer.email2 = form.cleaned_data.get("email2").lower()
                customer.subscribe_to_email = form.cleaned_data.get(
                    "subscribe_to_email")
                customer.city = form.cleaned_data.get("city")
                customer.address = form.cleaned_data.get("address")
                customer.picture = form.cleaned_data.get("picture")
                customer.about_me = form.cleaned_data.get("about_me")
                customer.zero_waste = form.cleaned_data.get("zero_waste")
                customer.save()
                # Important : place this code after because form = CustomerForm(data, request=request) delete form.cleaned_data
                email = form.cleaned_data.get("email1")
                user_model = get_user_model()
                user = user_model.objects.filter(
                    email=email).order_by("?").first()
                if user is None or user.email != email:
                    # user.email != email for case unsensitive SQL query
                    customer.user.username = customer.user.email = email.lower(
                    )
                    # customer.user.first_name = EMPTY_STRING
                    # customer.user.last_name = customer.short_basket_name
                    customer.user.save()
                # User feed back : Display email in lower case.
                data = form.data.copy()
                data["email1"] = customer.user.email
                data["email2"] = customer.email2
                form = CustomerForm(data, request=request)
            return render(
                request,
                template_name,
                {
                    "form": form,
                    "membership_fee_valid_until": membership_fee_valid_until,
                    "display_who_is_who": REPANIER_SETTINGS_DISPLAY_WHO_IS_WHO,
                    "update": True,
                },
            )
        return render(
            request,
            template_name,
            {
                "form": form,
                "membership_fee_valid_until": membership_fee_valid_until,
                "display_who_is_who": REPANIER_SETTINGS_DISPLAY_WHO_IS_WHO,
                "update": False,
            },
        )
    else:
        form = CustomerForm()  # An unbound form
        field = form.fields["long_basket_name"]
        field.initial = customer.long_basket_name
        field = form.fields["phone1"]
        field.initial = customer.phone1
        field = form.fields["phone2"]
        field.initial = customer.phone2
        field = form.fields["email1"]
        field.initial = request.user.email
        field = form.fields["email2"]
        field.initial = customer.email2
        field = form.fields["subscribe_to_email"]
        field.initial = customer.subscribe_to_email
        field = form.fields["city"]
        field.initial = customer.city
        field = form.fields["address"]
        field.initial = customer.address
        field = form.fields["picture"]
        field.initial = customer.picture
        if hasattr(field.widget, "upload_to"):
            field.widget.upload_to = "{}{}{}".format("customer", os_sep,
                                                     customer.id)
        field = form.fields["about_me"]
        field.initial = customer.about_me
        field = form.fields["zero_waste"]
        field.initial = customer.zero_waste

    return render(
        request,
        template_name,
        {
            "form": form,
            "membership_fee_valid_until": membership_fee_valid_until,
            "display_who_is_who": REPANIER_SETTINGS_DISPLAY_WHO_IS_WHO,
            "update": None,
        },
    )
コード例 #48
0
ファイル: permanence_done.py プロジェクト: pcolmant/repanier
    def cancel_invoice_or_archive_or_cancelled(self, request, permanence_qs, action):
        if '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
        permanence = permanence_qs.first()
        if permanence.status not in [PERMANENCE_INVOICED, PERMANENCE_ARCHIVED,
                                     PERMANENCE_CANCELLED]:
            user_message = _("The status of %(permanence)s prohibit you to perform this action.") % {
                'permanence': permanence}
            user_message_level = messages.ERROR
            self.message_user(request, user_message, user_message_level)
            return

        if 'apply' in request.POST:
            if permanence.status == PERMANENCE_INVOICED:
                last_bank_account_total = BankAccount.objects.filter(
                    operation_status=BANK_LATEST_TOTAL).only(
                    "permanence"
                ).first()
                if last_bank_account_total is not None:
                    last_permanence_invoiced_id = last_bank_account_total.permanence_id
                    if last_permanence_invoiced_id is not None:
                        if last_permanence_invoiced_id == permanence.id:
                            # This is well the latest closed permanence. The invoices can be cancelled without damages.
                            permanence.cancel_invoice(last_bank_account_total)
                            user_message = _("The selected invoice has been canceled.")
                            user_message_level = messages.INFO
                        else:
                            user_message = (
                                _("You mus first cancel the invoices of {} whose date is {}.").format(
                                    last_bank_account_total.permanence,
                                    last_bank_account_total.permanence.permanence_date.strftime(
                                        settings.DJANGO_SETTINGS_DATE))
                            )
                            user_message_level = messages.ERROR
                    else:
                        user_message = _("The selected invoice is not the latest invoice.")
                        user_message_level = messages.ERROR
                else:
                    user_message = _("The selected invoice has been canceled.")
                    user_message_level = messages.INFO
                    permanence.set_status(old_status=(PERMANENCE_INVOICED,), new_status=PERMANENCE_SEND)
            else:
                permanence.set_status(old_status=(PERMANENCE_ARCHIVED, PERMANENCE_CANCELLED,),
                                      new_status=PERMANENCE_SEND)
                user_message = _("The selected invoice has been restored.")
                user_message_level = messages.INFO
            self.message_user(request, user_message, user_message_level)
            return
        template_name = get_repanier_template_name("confirm_admin_action.html")
        return render(request, template_name, {
            'sub_title': _(
                "Please, confirm the action : cancel the invoices") if permanence.status == PERMANENCE_INVOICED else _(
                "Please, confirm the action : cancel the archiving") if permanence.status == PERMANENCE_ARCHIVED else _(
                "Please, confirm the action : restore the delivery"),
            'action': action,
            'permanence': permanence,
            'action_checkbox_name': admin.ACTION_CHECKBOX_NAME,
        })
コード例 #49
0
 def export_xlsx_customer_order(self, request, queryset):
     if "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
     permanence = queryset.first()
     if permanence.status not in [
             PERMANENCE_OPENED,
             PERMANENCE_CLOSED,
             PERMANENCE_SEND,
     ]:
         user_message = _(
             "The status of %(permanence)s prohibit you to perform this action."
         ) % {
             "permanence": permanence
         }
         user_message_level = messages.ERROR
         self.message_user(request, user_message, user_message_level)
         return
     if not permanence.with_delivery_point:
         # Perform the action directly. Do not ask to select any delivery point.
         response = None
         wb = generate_customer_xlsx(permanence=permanence)[0]
         if wb is not None:
             response = HttpResponse(
                 content_type=
                 "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
             )
             response[
                 "Content-Disposition"] = "attachment; filename={0}-{1}.xlsx".format(
                     _("Customers"), permanence)
             wb.save(response)
         return response
     if "apply" in request.POST:
         if admin.ACTION_CHECKBOX_NAME in request.POST:
             deliveries_to_be_exported = request.POST.getlist(
                 "deliveries", [])
             if len(deliveries_to_be_exported) == 0:
                 user_message = _(
                     "You must select at least one delivery point.")
                 user_message_level = messages.WARNING
                 self.message_user(request, user_message,
                                   user_message_level)
                 return
                 # Also display order without delivery point -> The customer has not selected it yet
                 # deliveries_to_be_exported.append(None)
         else:
             deliveries_to_be_exported = ()
         response = None
         wb = generate_customer_xlsx(
             permanence=permanence,
             deliveries_id=deliveries_to_be_exported)[0]
         if wb is not None:
             response = HttpResponse(
                 content_type=
                 "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
             )
             response[
                 "Content-Disposition"] = "attachment; filename={0}-{1}.xlsx".format(
                     _("Customers"), permanence)
             wb.save(response)
         return response
     template_name = get_repanier_template_name(
         "confirm_admin_export_customer_order.html")
     return render(
         request,
         template_name,
         {
             "sub_title":
             _("Please, confirm the action : Export customer orders"),
             "action_checkbox_name":
             admin.ACTION_CHECKBOX_NAME,
             "action":
             "export_xlsx_customer_order",
             "permanence":
             permanence,
             "deliveries":
             DeliveryBoard.objects.filter(permanence_id=permanence.id),
         },
     )
コード例 #50
0
ファイル: permanence_done.py プロジェクト: pcolmant/repanier
    def send_invoices(self, request, permanence_qs):
        if '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
        permanence = permanence_qs.first()
        if permanence.status != PERMANENCE_INVOICED:
            user_message = _("The status of %(permanence)s prohibit you to perform this action.") % {
                'permanence': permanence}
            user_message_level = messages.ERROR
            self.message_user(request, user_message, user_message_level)
            return
        template = Template(repanier.apps.REPANIER_SETTINGS_CONFIG.invoice_customer_mail)
        invoice_description = permanence.safe_translation_getter(
            'invoice_description', any_language=True, default=EMPTY_STRING
        )
        staff = Staff.get_or_create_invoice_responsible()

        # TODO : Align on tools.payment_message
        customer_order_amount = \
            _('The amount of your order is %(amount)s.') % {
                'amount': RepanierMoney(123.45)
            }
        customer_last_balance = \
            _('The balance of your account as of %(date)s is %(balance)s.') % {
                'date': timezone.now().strftime(settings.DJANGO_SETTINGS_DATE),
                'balance': RepanierMoney(123.45)
            }
        bank_account_number = repanier.apps.REPANIER_SETTINGS_BANK_ACCOUNT
        if bank_account_number is not None:
            group_name = settings.REPANIER_SETTINGS_GROUP_NAME
            if permanence.short_name:
                communication = "{} ({})".format(_('Short name'), permanence.short_name)
            else:
                communication = _('Short name')
            customer_payment_needed = "<font color=\"#bd0926\">{}</font>".format(
                _(
                    'Please pay a provision of %(payment)s to the bank account %(name)s %(number)s with communication %(communication)s.') % {
                    'payment': RepanierMoney(123.45),
                    'name': group_name,
                    'number': bank_account_number,
                    'communication': communication
                }
            )
        else:
            customer_payment_needed = EMPTY_STRING
        context = TemplateContext({
            'name': _('Long name'),
            'long_basket_name': _('Long name'),
            'basket_name': _('Short name'),
            'short_basket_name': _('Short name'),
            'permanence_link': mark_safe("<a href=\"#\">{}</a>".format(permanence)),
            'last_balance_link': mark_safe("<a href=\"#\">{}</a>".format(customer_last_balance)),
            'last_balance': customer_last_balance,
            'order_amount': mark_safe(customer_order_amount),
            'payment_needed': mark_safe(customer_payment_needed),
            'invoice_description': mark_safe(invoice_description),
            'signature': staff.get_html_signature,
        })
        template_invoice_customer_mail = template.render(context)

        invoice_customer_email_will_be_sent, invoice_customer_email_will_be_sent_to = RepanierEmail.send_email_to_who(
            is_email_send=repanier.apps.REPANIER_SETTINGS_SEND_INVOICE_MAIL_TO_CUSTOMER
        )

        template = Template(repanier.apps.REPANIER_SETTINGS_CONFIG.invoice_producer_mail)

        context = TemplateContext({
            'name': _('Long name'),
            'long_profile_name': _('Long name'),
            'permanence_link': mark_safe("<a href=\"#\">{}</a>".format(permanence)),
            'signature': staff.get_html_signature,
        })
        template_invoice_producer_mail = template.render(context)

        invoice_producer_email_will_be_sent, invoice_producer_email_will_be_sent_to = RepanierEmail.send_email_to_who(
            is_email_send=repanier.apps.REPANIER_SETTINGS_SEND_INVOICE_MAIL_TO_PRODUCER
        )
        if 'apply' in request.POST:
            form = InvoiceOrderForm(request.POST)
            if form.is_valid():
                t = threading.Thread(target=email_invoice.send_invoice, args=(permanence.id,))
                t.start()
                user_message = _("Emails containing the invoices will be send to the customers and the producers.")
                user_message_level = messages.INFO
                self.message_user(request, user_message, user_message_level)
            return HttpResponseRedirect(request.get_full_path())
        else:
            form = InvoiceOrderForm(
                initial={
                    'template_invoice_customer_mail': mark_safe(template_invoice_customer_mail),
                    'template_invoice_producer_mail': mark_safe(template_invoice_producer_mail),
                }
            )
        template_name = get_repanier_template_name(
            'repanier/confirm_admin_send_invoice.html'
        )
        return render(
            request,
            template_name, {
                'sub_title': _("Please, confirm the action : send invoices"),
                'action_checkbox_name': admin.ACTION_CHECKBOX_NAME,
                'action': 'send_invoices',
                'permanence': permanence,
                'form': form,
                'invoice_customer_email_will_be_sent': invoice_customer_email_will_be_sent,
                'invoice_customer_email_will_be_sent_to': invoice_customer_email_will_be_sent_to,
                'invoice_producer_email_will_be_sent': invoice_producer_email_will_be_sent,
                'invoice_producer_email_will_be_sent_to': invoice_producer_email_will_be_sent_to
            })
コード例 #51
0
    def close_and_send_order(self, request, queryset):
        if "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
        permanence = queryset.first()
        if permanence.status not in [PERMANENCE_OPENED, PERMANENCE_CLOSED]:
            user_message = _(
                "The status of %(permanence)s prohibit you to perform this action."
            ) % {
                "permanence": permanence
            }
            user_message_level = messages.ERROR
            self.message_user(request, user_message, user_message_level)
            return
        if "apply" in request.POST:
            all_deliveries = True if request.POST.get("all-deliveries",
                                                      True) else False
            deliveries_to_be_send = request.POST.getlist("deliveries", [])
            logger.debug("all_deliveries : {}".format(
                request.POST.get("all-deliveries")))
            logger.debug("all_deliveries : {}".format(all_deliveries))
            logger.debug("deliveries_to_be_send : {}".format(
                request.POST.getlist("deliveries", [])))
            if (permanence.with_delivery_point and not all_deliveries
                    and len(deliveries_to_be_send) == 0):
                user_message = _(
                    "You must select at least one delivery point.")
                user_message_level = messages.WARNING
                self.message_user(request, user_message, user_message_level)
                return
            # close_and_send_order(permanence.id, all_deliveries, deliveries_to_be_send)
            t = threading.Thread(
                target=close_and_send_order,
                args=(permanence.id, all_deliveries, deliveries_to_be_send),
            )
            t.start()
            user_message = _("The orders are being send.")
            user_message_level = messages.INFO
            self.message_user(request, user_message, user_message_level)
            return

        template_order_customer_mail = []
        template_order_producer_mail = []
        template_order_staff_mail = []
        cur_language = translation.get_language()
        for language in settings.PARLER_LANGUAGES[settings.SITE_ID]:
            language_code = language["code"]
            translation.activate(language_code)

            template = Template(
                repanier.apps.REPANIER_SETTINGS_CONFIG.order_customer_mail)

            staff = Staff.get_or_create_order_responsible()

            customer_last_balance = _(
                "The balance of your account as of %(date)s is %(balance)s."
            ) % {
                "date": timezone.now().strftime(settings.DJANGO_SETTINGS_DATE),
                "balance": RepanierMoney(123.45),
            }
            customer_on_hold_movement = _(
                "This balance does not take account of any unrecognized payments %(bank)s and any unbilled order %(other_order)s."
            ) % {
                "bank": RepanierMoney(123.45),
                "other_order": RepanierMoney(123.45)
            }

            bank_account_number = repanier.apps.REPANIER_SETTINGS_BANK_ACCOUNT
            if bank_account_number is not None:
                group_name = settings.REPANIER_SETTINGS_GROUP_NAME

                if permanence.short_name:
                    communication = "{} ({})".format(_("Short name"),
                                                     permanence.short_name)
                else:
                    communication = _("Short name")
                customer_payment_needed = '<font color="#bd0926">{}</font>'.format(
                    _("Please pay a provision of %(payment)s to the bank account %(name)s %(number)s with communication %(communication)s."
                      ) % {
                          "payment": RepanierMoney(123.45),
                          "name": group_name,
                          "number": bank_account_number,
                          "communication": communication,
                      })
            else:
                customer_payment_needed = EMPTY_STRING
            context = TemplateContext({
                "name":
                _("Long name"),
                "long_basket_name":
                _("Long name"),
                "basket_name":
                _("Short name"),
                "short_basket_name":
                _("Short name"),
                "permanence_link":
                mark_safe('<a href="#">{}</a>'.format(permanence)),
                "last_balance":
                mark_safe('<a href="#">{}</a>'.format(customer_last_balance)),
                "order_amount":
                RepanierMoney(123.45),
                "on_hold_movement":
                mark_safe(customer_on_hold_movement),
                "payment_needed":
                mark_safe(customer_payment_needed),
                "delivery_point":
                _("Delivery point").upper(),
                "signature":
                staff.get_html_signature,
            })

            template_order_customer_mail.append(language_code)
            template_order_customer_mail.append(template.render(context))

            template = Template(
                repanier.apps.REPANIER_SETTINGS_CONFIG.order_producer_mail)
            context = TemplateContext({
                "name":
                _("Long name"),
                "long_profile_name":
                _("Long name"),
                "order_empty":
                False,
                "duplicate":
                True,
                "permanence_link":
                format_html('<a href="#">{}</a>', permanence),
                "signature":
                staff.get_html_signature,
            })

            template_order_producer_mail.append(language_code)
            template_order_producer_mail.append(template.render(context))

            board_composition = permanence.get_html_board_composition()
            template = Template(
                repanier.apps.REPANIER_SETTINGS_CONFIG.order_staff_mail)
            context = TemplateContext({
                "permanence_link":
                format_html('<a href="#">{}</a>', permanence),
                "board_composition":
                board_composition,
                "board_composition_and_description":
                board_composition,
                "signature":
                staff.get_html_signature,
            })

            template_order_staff_mail.append(language_code)
            template_order_staff_mail.append(template.render(context))

        translation.activate(cur_language)

        order_customer_email_will_be_sent, order_customer_email_will_be_sent_to = RepanierEmail.send_email_to_who(
            is_email_send=True)
        order_producer_email_will_be_sent, order_producer_email_will_be_sent_to = RepanierEmail.send_email_to_who(
            is_email_send=True)
        order_board_email_will_be_sent, order_board_email_will_be_sent_to = RepanierEmail.send_email_to_who(
            is_email_send=repanier.apps.
            REPANIER_SETTINGS_SEND_ORDER_MAIL_TO_BOARD,
            board=True,
        )

        form = CloseAndSendOrderForm(
            initial={
                "template_order_customer_mail":
                mark_safe("<br>==============<br>".join(
                    template_order_customer_mail)),
                "template_order_producer_mail":
                mark_safe("<br>==============<br>".join(
                    template_order_producer_mail)),
                "template_order_staff_mail":
                mark_safe("<br>==============<br>".join(
                    template_order_staff_mail)),
            })
        if permanence.with_delivery_point:
            deliveries = DeliveryBoard.objects.filter(
                permanence_id=permanence.id,
                status__in=[PERMANENCE_OPENED, PERMANENCE_CLOSED],
            )
        else:
            deliveries = DeliveryBoard.objects.none()
        template_name = get_repanier_template_name(
            "confirm_admin_send_order.html")
        return render(
            request,
            template_name,
            {
                "sub_title":
                _("Please, confirm the action : send orders"),
                "action_checkbox_name":
                admin.ACTION_CHECKBOX_NAME,
                "action":
                "close_and_send_order",
                "permanence":
                permanence,
                "with_delivery_point":
                permanence.with_delivery_point,
                "deliveries":
                deliveries,
                "form":
                form,
                "order_customer_email_will_be_sent":
                order_customer_email_will_be_sent,
                "order_customer_email_will_be_sent_to":
                order_customer_email_will_be_sent_to,
                "order_producer_email_will_be_sent":
                order_producer_email_will_be_sent,
                "order_producer_email_will_be_sent_to":
                order_producer_email_will_be_sent_to,
                "order_board_email_will_be_sent":
                order_board_email_will_be_sent,
                "order_board_email_will_be_sent_to":
                order_board_email_will_be_sent_to,
            },
        )
コード例 #52
0
# -*- coding: utf-8

from django.conf import settings
from django.http import Http404, JsonResponse
from django.shortcuts import get_object_or_404
from django.template.loader import render_to_string
from django.utils.safestring import mark_safe
from django.views.decorators.http import require_GET

from repanier.const import PERMANENCE_OPENED, PERMANENCE_SEND
from repanier.models.offeritem import OfferItem
from repanier.tools import permanence_ok_or_404, sint, get_repanier_template_name

template_order_product_description = get_repanier_template_name("order_product_description.html")


@require_GET
def customer_product_description_ajax(request):
    if request.is_ajax():
        offer_item_id = sint(request.GET.get('offer_item', 0))
        offer_item = get_object_or_404(OfferItem, id=offer_item_id)
        permanence = offer_item.permanence
        permanence_ok_or_404(permanence)
        if PERMANENCE_OPENED <= permanence.status <= PERMANENCE_SEND:
            html = render_to_string(
                template_order_product_description,
                {'offer': offer_item, 'MEDIA_URL': settings.MEDIA_URL}
            )
            return JsonResponse({"#orderModal": mark_safe(html)})
    raise Http404
コード例 #53
0
ファイル: my_profile_view.py プロジェクト: pcolmant/repanier
def my_profile_view(request):
    user = request.user
    customer_is_active = Customer.objects.filter(user_id=user.id, is_active=True).order_by('?').exists()
    if not customer_is_active:
        raise Http404
    customer = request.user.customer
    from repanier.apps import REPANIER_SETTINGS_MEMBERSHIP_FEE, REPANIER_SETTINGS_DISPLAY_WHO_IS_WHO
    if REPANIER_SETTINGS_MEMBERSHIP_FEE > DECIMAL_ZERO:
        membership_fee_valid_until = customer.membership_fee_valid_until
    else:
        membership_fee_valid_until = None
    template_name = get_repanier_template_name("my_profile_form.html")
    if request.method == 'POST':  # If the form has been submitted...
        form = CustomerForm(request.POST, request=request)  # A form bound to the POST data
        if form.is_valid():  # All validation rules pass
            # Process the data in form.cleaned_data
            # ...
            if customer is not None:
                customer.long_basket_name = form.cleaned_data.get('long_basket_name')
                customer.phone1 = form.cleaned_data.get('phone1')
                customer.phone2 = form.cleaned_data.get('phone2')
                customer.email2 = form.cleaned_data.get('email2').lower()
                customer.show_phones_to_members = form.cleaned_data.get('show_phones_to_members')
                customer.show_mails_to_members = form.cleaned_data.get('show_mails_to_members')
                customer.subscribe_to_email = form.cleaned_data.get('subscribe_to_email')
                customer.city = form.cleaned_data.get('city')
                customer.address = form.cleaned_data.get('address')
                customer.picture = form.cleaned_data.get('picture')
                customer.about_me = form.cleaned_data.get('about_me')
                customer.zero_waste = form.cleaned_data.get('zero_waste')
                customer.save()
                # Important : place this code after because form = CustomerForm(data, request=request) delete form.cleaned_data
                email = form.cleaned_data.get('email1')
                user_model = get_user_model()
                user = user_model.objects.filter(email=email).order_by('?').first()
                if user is None or user.email != email:
                    # user.email != email for case unsensitive SQL query
                    customer.user.username = customer.user.email = email.lower()
                    # customer.user.first_name = EMPTY_STRING
                    # customer.user.last_name = customer.short_basket_name
                    customer.user.save()
                # User feed back : Display email in lower case.
                data = form.data.copy()
                data["email1"] = customer.user.email
                data["email2"] = customer.email2
                form = CustomerForm(data, request=request)
            return render(request, template_name,
                          {
                              'form': form,
                              'membership_fee_valid_until': membership_fee_valid_until,
                              'display_who_is_who': REPANIER_SETTINGS_DISPLAY_WHO_IS_WHO,
                              'update': True
                          })
        return render(request, template_name,
                      {
                          'form': form,
                          'membership_fee_valid_until': membership_fee_valid_until,
                          'display_who_is_who': REPANIER_SETTINGS_DISPLAY_WHO_IS_WHO,
                          'update': False
                      })
    else:
        form = CustomerForm()  # An unbound form
        field = form.fields["long_basket_name"]
        field.initial = customer.long_basket_name
        field = form.fields["phone1"]
        field.initial = customer.phone1
        field = form.fields["phone2"]
        field.initial = customer.phone2
        field = form.fields["email1"]
        field.initial = request.user.email
        field = form.fields["email2"]
        field.initial = customer.email2
        field = form.fields["show_phones_to_members"]
        field.initial = customer.show_phones_to_members
        field = form.fields["show_mails_to_members"]
        field.initial = customer.show_mails_to_members
        field = form.fields["subscribe_to_email"]
        field.initial = customer.subscribe_to_email
        field = form.fields["city"]
        field.initial = customer.city
        field = form.fields["address"]
        field.initial = customer.address
        field = form.fields["picture"]
        field.initial = customer.picture
        if hasattr(field.widget, 'upload_to'):
            field.widget.upload_to = "{}{}{}".format("customer", os_sep, customer.id)
        field = form.fields["about_me"]
        field.initial = customer.about_me
        field = form.fields["zero_waste"]
        field.initial = customer.zero_waste

    return render(request, template_name,
                  {
                      'form': form,
                      'membership_fee_valid_until': membership_fee_valid_until,
                      'display_who_is_who': REPANIER_SETTINGS_DISPLAY_WHO_IS_WHO,
                      'update': None})
コード例 #54
0
    def open_and_send_offer(self, request, queryset):
        if '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
        permanence = queryset.first()
        if permanence.status not in [PERMANENCE_PLANNED, PERMANENCE_PRE_OPEN]:
            user_message = _("The status of %(permanence)s prohibit you to perform this action.") % {
                'permanence': permanence}
            user_message_level = messages.ERROR
            self.message_user(request, user_message, user_message_level)
            return
        pre_open = (permanence.status == PERMANENCE_PLANNED) and Producer.objects.filter(
            permanence__id=permanence.id, is_active=True, producer_pre_opening=True
        ).order_by('?').exists()
        if pre_open:
            template_offer_mail = []
            template_cancel_order_mail = []
            cur_language = translation.get_language()
            for language in settings.PARLER_LANGUAGES[settings.SITE_ID]:
                language_code = language["code"]
                translation.activate(language_code)

                with switch_language(repanier.apps.REPANIER_SETTINGS_CONFIG, language_code):
                    template = Template(repanier.apps.REPANIER_SETTINGS_CONFIG.offer_producer_mail)

                staff = Staff.get_or_create_order_responsible()

                with switch_language(permanence, language_code):
                    offer_description = permanence.safe_translation_getter(
                        'offer_description', any_language=True, default=EMPTY_STRING
                    )
                context = TemplateContext({
                    'name': _('Long name'),
                    'long_profile_name': _('Long name'),
                    'permanence_link': mark_safe("<a href=\"#\">{}</a>".format(_("Offers"))),
                    'offer_description': mark_safe(offer_description),
                    'offer_link': mark_safe("<a href=\"#\">{}</a>".format(_("Offers"))),
                    'signature': staff.get_html_signature,
                })
                template_offer_mail.append(language_code)
                template_offer_mail.append(template.render(context))
            translation.activate(cur_language)
            email_will_be_sent, email_will_be_sent_to = RepanierEmail.send_email_to_who()
        else:
            template_offer_mail = []
            template_cancel_order_mail = []
            cur_language = translation.get_language()
            for language in settings.PARLER_LANGUAGES[settings.SITE_ID]:
                language_code = language["code"]
                translation.activate(language_code)

                with switch_language(repanier.apps.REPANIER_SETTINGS_CONFIG, language_code):
                    template = Template(repanier.apps.REPANIER_SETTINGS_CONFIG.offer_customer_mail)

                staff = Staff.get_or_create_order_responsible()

                with switch_language(permanence, language_code):
                    offer_description = permanence.safe_translation_getter(
                        'offer_description', any_language=True, default=EMPTY_STRING
                    )
                offer_producer = ', '.join([p.short_profile_name for p in permanence.producers.all()])
                qs = Product.objects.filter(
                    producer=permanence.producers.first(),
                    is_into_offer=True,
                    order_unit__lt=PRODUCT_ORDER_UNIT_DEPOSIT  # Don't display technical products.
                ).order_by(
                    "translations__long_name"
                )[:5]
                offer_detail = "<ul>{}</ul>".format("".join("<li>{}, {}</li>".format(
                    p.get_long_name(),
                    p.producer.short_profile_name
                )
                                                            for p in qs
                                                            ), )
                context = TemplateContext({
                    'offer_description': mark_safe(offer_description),
                    'offer_detail': offer_detail,
                    'offer_recent_detail': offer_detail,
                    'offer_producer': offer_producer,
                    'permanence_link': mark_safe("<a href=\"#\">{}</a>".format(permanence)),
                    'signature': staff.get_html_signature,
                })
                template_offer_mail.append(language_code)
                template_offer_mail.append(template.render(context))
                if settings.REPANIER_SETTINGS_CUSTOMER_MUST_CONFIRM_ORDER:
                    context = TemplateContext({
                        'name': _('Long name'),
                        'long_basket_name': _('Long name'),
                        'basket_name': _('Short name'),
                        'short_basket_name': _('Short name'),
                        'permanence_link': mark_safe("<a href=\"#\">{}</a>".format(permanence)),
                        'signature': staff.get_html_signature,
                    })
                    template_cancel_order_mail.append(language_code)
                    template_cancel_order_mail.append(template.render(context))
            translation.activate(cur_language)
            email_will_be_sent, email_will_be_sent_to = RepanierEmail.send_email_to_who()
        if 'apply' in request.POST or 'apply-wo-mail' in request.POST:
            form = OpenAndSendOfferForm(request.POST)
            if form.is_valid():
                do_not_send_any_mail = 'apply-wo-mail' in request.POST
                if pre_open:
                    permanence_already_pre_opened = Permanence.objects.filter(
                        status__in=[PERMANENCE_WAIT_FOR_PRE_OPEN, PERMANENCE_PRE_OPEN]
                    ).order_by("-is_updated_on").only("id").first()
                    if permanence_already_pre_opened is not None:
                        user_message = _("A maximum of one permanence may be pre opened.")
                        user_message_level = messages.ERROR
                    else:
                        # pre_open_order(permanence.id)
                        t = threading.Thread(target=pre_open_order, args=(permanence.id,))
                        t.start()
                        user_message = _("The offers are being generated.")
                        user_message_level = messages.INFO
                else:
                    # open_order(permanence.id, do_not_send_any_mail)
                    t = threading.Thread(target=open_order, args=(permanence.id, do_not_send_any_mail))
                    t.start()
                    user_message = _("The offers are being generated.")
                    user_message_level = messages.INFO
                self.message_user(request, user_message, user_message_level)
            return HttpResponseRedirect(request.get_full_path())
        else:
            form = OpenAndSendOfferForm(
                initial={
                    'template_offer_customer_mail': mark_safe(
                        "<br>==============<br>".join(template_offer_mail)),
                    'template_cancel_order_customer_mail': mark_safe(
                        "<br>==============<br>".join(template_cancel_order_mail)),
                }
            )
        template_name = get_repanier_template_name(
            'confirm_admin_open_and_send_offer.html'
        )
        return render(
            request,
            template_name, {
                'sub_title': _("Please, confirm the action : open and send offers"),
                'action_checkbox_name': admin.ACTION_CHECKBOX_NAME,
                'action': 'open_and_send_offer',
                'permanence': permanence,
                'pre_open': pre_open,
                'form': form,
                'email_will_be_sent': email_will_be_sent,
                'email_will_be_sent_to': email_will_be_sent_to
            })