Beispiel #1
0
def format_data(data, format_iso_dates=False, format_money_values=False):
    if data is None:
        return ""

    elif isinstance(data, Money):
        if format_money_values:
            return format_money(data)
        return float(data.as_rounded().value)

    elif isinstance(data, Decimal):
        exponent = abs(data.normalize().as_tuple().exponent)
        # Limit the amount of decimals to 10
        return floatformat(data, min(exponent, 10))

    elif callable(data):
        return force_text(data())

    elif isinstance(data, Promise):
        return force_text(data)

    elif isinstance(data, models.Model):
        return force_text(data)

    elif isinstance(data, datetime):
        if format_iso_dates:
            return data.isoformat()
        return get_locally_formatted_datetime(data)

    return data
Beispiel #2
0
    def get_display_value(self, context, object):
        display_callable = maybe_callable(self.display, context=context)
        if display_callable:
            return display_callable(object)

        value = object
        for bit in self.display.split("__"):
            value = getattr(value, bit, None)

        if isinstance(value, ProductMedia):
            return "<img src='/media/%s'>" % value.get_thumbnail()

        if isinstance(value, Image):
            thumbnailer = get_thumbnailer(value)
            options = {"size": (64, 64)}
            thumbnail = thumbnailer.get_thumbnail(options, generate=True)
            return "<img src='%s'>" % thumbnail.url

        if isinstance(value, bool):
            value = yesno(value)

        if isinstance(value, Manager):
            value = ", ".join("%s" % x for x in value.all())

        if isinstance(value, datetime.datetime):
            return get_locally_formatted_datetime(value)

        if not value:
            value = ""

        return force_text(value)
Beispiel #3
0
    def post(self, request, *args, **kwargs):
        shop_ids = Shop.objects.get_for_user(self.request.user).values_list(
            "id", flat=True)
        order = Order.objects.filter(pk=kwargs["pk"],
                                     shop_id__in=shop_ids).first()
        if not order:
            raise Http404()

        message = request.POST["message"]
        entry = OrderLogEntry.objects.create(
            target=order,
            message=message,
            kind=LogEntryKind.NOTE,
            user=request.user,
        )

        return JsonResponse({
            "message":
            entry.message,
            "kind":
            force_text(entry.kind.label),
            "created_on":
            get_locally_formatted_datetime(entry.created_on),
            "user":
            force_text(getattr(entry.user,
                               get_user_model().USERNAME_FIELD)),
        })
Beispiel #4
0
    def get_display_value(self, context, object):
        display_callable = maybe_callable(self.display, context=context)
        if display_callable:
            return display_callable(object)

        value = object
        for bit in self.display.split("__"):
            value = getattr(value, bit, None)

        if isinstance(value, ProductMedia):
            return "<img src='/media/%s'>" % value.get_thumbnail()

        if isinstance(value, Image):
            thumbnailer = get_thumbnailer(value)
            options = {"size": (64, 64)}
            thumbnail = thumbnailer.get_thumbnail(options, generate=True)
            return "<img src='%s'>" % thumbnail.url

        if isinstance(value, bool):
            value = yesno(value)

        if isinstance(value, Manager):
            value = ", ".join("%s" % x for x in value.all())

        if isinstance(value, datetime.datetime):
            return get_locally_formatted_datetime(value)

        if isinstance(value, Money):
            return escape(format_money(value))

        if not value:
            value = ""

        return force_text(value)
Beispiel #5
0
    def handle_customer_details(self, request):
        customer_id = request.GET["id"]
        customer = Contact.objects.get(pk=customer_id)
        companies = []
        if isinstance(customer, PersonContact):
            companies = sorted(customer.company_memberships.all(),
                               key=(lambda x: force_text(x)))
        recent_orders = customer.customer_orders.valid().order_by('-id')[:10]

        order_summary = []
        for dt in customer.customer_orders.valid().datetimes(
                'order_date', 'year'):
            summary = customer.customer_orders.filter(
                order_date__year=dt.year).aggregate(
                    total=Sum('taxful_total_price_value'))
            order_summary.append({
                'year':
                dt.year,
                'total':
                format_currency(summary['total'],
                                currency=recent_orders[0].currency,
                                locale=get_current_babel_locale())
            })

        return {
            "customer_info": {
                "name":
                customer.full_name,
                "phone_no":
                customer.phone,
                "email":
                customer.email,
                "tax_number":
                getattr(customer, "tax_number", ""),
                "companies":
                [force_text(company)
                 for company in companies] if len(companies) else None,
                "groups":
                [force_text(group) for group in customer.groups.all()],
                "merchant_notes":
                customer.merchant_notes
            },
            "order_summary":
            order_summary,
            "recent_orders": [{
                "order_date":
                get_locally_formatted_datetime(order.order_date),
                "total":
                format_money(order.taxful_total_price),
                "status":
                order.get_status_display(),
                "payment_status":
                force_text(order.payment_status.label),
                "shipment_status":
                force_text(order.shipping_status.label)
            } for order in recent_orders]
        }
Beispiel #6
0
    def post(self, request, *args, **kwargs):
        order = Order.objects.get(pk=kwargs["pk"])
        message = request.POST["message"]
        entry = OrderLogEntry.objects.create(target=order, message=message, kind=LogEntryKind.NOTE, user=request.user)

        return JsonResponse(
            {
                "message": entry.message,
                "kind": force_text(entry.kind.label),
                "created_on": get_locally_formatted_datetime(entry.created_on),
                "user": force_text(getattr(entry.user, get_user_model().USERNAME_FIELD)),
            }
        )
Beispiel #7
0
    def post(self, request, *args, **kwargs):
        order = Order.objects.get(pk=kwargs["pk"])
        message = request.POST["message"]
        entry = OrderLogEntry.objects.create(
            target=order,
            message=message,
            kind=LogEntryKind.NOTE,
            user=request.user,
        )

        return JsonResponse({
            "message": entry.message,
            "kind": force_text(entry.kind.label),
            "created_on": get_locally_formatted_datetime(entry.created_on),
            "user": force_text(getattr(entry.user, get_user_model().USERNAME_FIELD)),
        })
Beispiel #8
0
    def handle_customer_details(self, request):
        customer_id = request.GET["id"]
        customer = Contact.objects.get(pk=customer_id)
        companies = []
        if isinstance(customer, PersonContact):
            companies = sorted(customer.company_memberships.all(), key=(lambda x: force_text(x)))
        recent_orders = customer.customer_orders.valid().order_by('-id')[:10]

        order_summary = []
        for dt in customer.customer_orders.valid().datetimes('order_date', 'year'):
            summary = customer.customer_orders.filter(order_date__year=dt.year).aggregate(
                total=Sum('taxful_total_price_value')
            )
            order_summary.append({
                'year': dt.year,
                'total': format_currency(
                    summary['total'], currency=recent_orders[0].currency, locale=get_current_babel_locale()
                )
            })

        return {
            "customer_info": {
                "name": customer.full_name,
                "phone_no": customer.phone,
                "email": customer.email,
                "tax_number": getattr(customer, "tax_number", ""),
                "companies": [force_text(company) for company in companies] if len(companies) else None,
                "groups": [force_text(group) for group in customer.groups.all()],
                "merchant_notes": customer.merchant_notes
            },
            "order_summary": order_summary,
            "recent_orders": [
                {
                    "order_date": get_locally_formatted_datetime(order.order_date),
                    "total": format_money(order.taxful_total_price),
                    "status": order.get_status_display(),
                    "payment_status": force_text(order.payment_status.label),
                    "shipment_status": force_text(order.shipping_status.label)
                } for order in recent_orders
            ]
        }
Beispiel #9
0
    def check_different_types(self, value):
        if isinstance(value, ProductMedia):
            return "<img src='/media/%s'>" % value.get_thumbnail()

        if isinstance(value, Image):
            thumbnailer = get_thumbnailer(value)
            options = {"size": (64, 64)}
            thumbnail = thumbnailer.get_thumbnail(options, generate=True)
            return "<img src='%s'>" % thumbnail.url

        if isinstance(value, bool):
            value = yesno(value)

        if isinstance(value, Manager):
            value = ", ".join("%s" % x for x in value.all())

        if isinstance(value, datetime.datetime):
            return get_locally_formatted_datetime(value)

        if isinstance(value, Money):
            return escape(format_money(value))
Beispiel #10
0
    def check_different_types(self, value):
        if isinstance(value, ProductMedia):
            return "<img src='/media/%s'>" % value.get_thumbnail()

        if isinstance(value, Image):
            thumbnailer = get_thumbnailer(value)
            options = {"size": (64, 64)}
            thumbnail = thumbnailer.get_thumbnail(options, generate=True)
            return "<img src='%s'>" % thumbnail.url

        if isinstance(value, bool):
            value = yesno(value)

        if isinstance(value, Manager):
            value = ", ".join("%s" % x for x in value.all())
            return value

        if isinstance(value, datetime.datetime):
            return get_locally_formatted_datetime(value)

        if isinstance(value, Money):
            return escape(format_money(value))
Beispiel #11
0
 def get_data(self):
     data = []
     order_lines = self.get_objects()[:self.queryset_row_limit]
     for line in order_lines:
         data.append({
             "order_line_sku":
             line.sku,
             "order_line_text":
             line.text,
             "order_line_quantity":
             line.quantity,
             "taxless_unit_price":
             format_money(line.taxless_base_unit_price),
             "taxful_unit_price":
             format_money(line.taxful_base_unit_price),
             "taxful_price":
             format_money(line.taxful_price),
             "type":
             line.type.name.capitalize(),
             "created_on":
             get_locally_formatted_datetime(line.created_on),
         })
     return self.get_return_data(data, has_totals=False)
Beispiel #12
0
    def get_data(self):
        data = []
        orders = self.get_objects(paid=False)

        for order in orders:
            data.append({
                "order_num":
                order.identifier,
                "order_date":
                get_locally_formatted_datetime(order.order_date),
                "status":
                order.status,
                "order_line_quantity":
                order.lines.filter(type=OrderLineType.PRODUCT).count(),
                "order_total_amount":
                format_money(order.taxful_total_price),
                "payment_status":
                order.get_payment_status_display(),
                "shipment_status":
                order.get_shipping_status_display(),
                "customer":
                order.get_customer_name()
            })
        return self.get_return_data(data, has_totals=False)
Beispiel #13
0
 def format_start_date(self, instance, *args, **kwargs):
     if instance.start_date:
         return get_locally_formatted_datetime(instance.start_date)
Beispiel #14
0
 def format_updated_date(self, instance, *args, **kwargs):
     return get_locally_formatted_datetime(instance.updated_on)
Beispiel #15
0
 def format_order_date(self, instance, *args, **kwargs):
     return get_locally_formatted_datetime(instance.order_date)
Beispiel #16
0
 def format_order_date(self, instance, *args, **kwargs):
     return get_locally_formatted_datetime(instance.order_date)
Beispiel #17
0
 def format_end_datetime(self, instance, *args, **kwargs):
     return get_locally_formatted_datetime(
         instance.end_datetime) if instance.end_datetime else ""
Beispiel #18
0
 def format_updated_date(self, instance, *args, **kwargs):
     return get_locally_formatted_datetime(instance.updated_on)
Beispiel #19
0
 def format_end_datetime(self, instance, *args, **kwargs):
     return get_locally_formatted_datetime(instance.end_datetime) if instance.end_datetime else ""