Beispiel #1
0
 def _handle_source_data(self, request):
     state = json.loads(request.body.decode("utf-8"))["state"]
     source = create_source_from_state(
         state,
         creator=request.user,
         ip_address=request.META.get("REMOTE_ADDR"),
     )
     # Calculate final lines for confirmation
     source.calculate_taxes(force_recalculate=True)
     return {
         "taxfulTotal":
         format_money(source.taxful_total_price.amount),
         "taxlessTotal":
         format_money(source.taxless_total_price.amount),
         "totalDiscountAmount":
         format_money(source.total_discount.amount),
         "orderLines": [
             encode_line(line)
             for line in source.get_final_lines(with_taxes=True)
         ],
         "billingAddress":
         source.billing_address.as_string_list()
         if source.billing_address else None,
         "shippingAddress":
         source.shipping_address.as_string_list()
         if source.shipping_address else None,
     }
Beispiel #2
0
def encode_line(line):
    return {
        "sku": line.sku,
        "text": line.text,
        "quantity": format_decimal(line.quantity, locale=get_current_babel_locale()),
        "unitPrice": format_money(line.base_unit_price.amount),
        "discountAmount": format_money(line.discount_amount.amount),
        "taxlessTotal": format_money(line.taxless_price.amount),
        "taxPercentage": format_percent(line.tax_rate, 2),
        "taxfulTotal": format_money(line.taxful_price.amount)
    }
Beispiel #3
0
def encode_line(line):
    return {
        "sku": line.sku,
        "text": line.text,
        "quantity": format_decimal(line.quantity, locale=get_current_babel_locale()),
        "unitPrice": format_money(line.base_unit_price.amount),
        "discountAmount": format_money(line.discount_amount.amount),
        "taxlessTotal": format_money(line.taxless_price.amount),
        "taxPercentage": format_percent(line.tax_rate, 2),
        "taxfulTotal": format_money(line.taxful_price.amount)
    }
Beispiel #4
0
 def _handle_source_data(self, request):
     state = json.loads(request.body.decode("utf-8"))["state"]
     source = create_source_from_state(state, creator=request.user)
     # Calculate final lines for confirmation
     source.calculate_taxes(force_recalculate=True)
     return {
         "taxfulTotal": format_money(source.taxful_total_price.amount),
         "taxlessTotal": format_money(source.taxless_total_price.amount),
         "totalDiscountAmount": format_money(source.total_discount.amount),
         "orderLines": [encode_line(line) for line in source.get_final_lines(with_taxes=True)],
         "billingAddress": source.billing_address.as_string_list() if source.billing_address else None,
         "shippingAddress": source.shipping_address.as_string_list() if source.shipping_address else None,
     }
Beispiel #5
0
 def __str__(self):
     text = super(Tax, self).__str__()
     if self.rate is not None:
         text += " ({})".format(format_percent(self.rate, digits=3))
     if self.amount is not None:
         text += " ({})".format(format_money(self.amount))
     return text
Beispiel #6
0
 def __str__(self):
     text = super(Tax, self).__str__()
     if self.rate is not None:
         text += " ({})".format(format_percent(self.rate, digits=3))
     if self.amount is not None:
         text += " ({})".format(format_money(self.amount))
     return text
Beispiel #7
0
 def get(self, request, *args, **kwargs):
     reservable_id = request.GET.get("reservable_id", None)
     start_date, end_date = get_start_and_end_from_request(request)
     if not start_date or not end_date:
         return http.HttpResponseBadRequest("Need start and end dates.")
     if not reservable_id:
         return http.HttpResponseBadRequest("Need reservable id.")
     reservable = ReservableProduct.objects.get(id=reservable_id)
     is_free = reservable.is_period_days_free(start_date, end_date)
     total_days = (end_date - start_date).days
     if is_free:
         price_info = reservable.product.get_price_info(request, quantity=total_days)
         has_extra_info = price_info.period_modifiers > 0 or price_info.per_person_modifiers > 0
         price = {
             "total": format_money(price_info.price),
             "has_extra_info": has_extra_info,
         }
         if has_extra_info:
             price.update({
                 "period_modifiers": price_info.period_modifiers.quantize(Decimal("1.00")),
                 "per_person_modifiers": price_info.per_person_modifiers.quantize(Decimal("1.00")),
                 "special_period_str": ugettext("Special period"),
                 "persons_count_str": ugettext("Person count"),
             })
     else:
         price = None
     return JsonResponse({
         "result": is_free,
         "price": price,
     })
 def test_free_period_should_return_period_is_free_and_extra_info(self):
     request = RequestFactory().get("/")
     request.GET = {"persons": 3}
     request.shop = self.shop
     self.reservable.pricing_per_person = True
     self.reservable.pricing_per_person_included = 2
     self.reservable.pricing_per_person_price = Decimal("10.00")
     self.reservable.save()
     response = self.client.get(
         "%s?reservable_id=%s&start=%s&end=%s&persons=3" % (
             reverse('reservations:check_period'),
             self.reservable.id,
             self.next.strftime("%Y-%m-%d"),
             (self.next + datetime.timedelta(days=3)).strftime("%Y-%m-%d")
         )
     )
     price_info = self.reservable.product.get_price_info(request, quantity=3)
     self.assertJSONEqual(response.content.decode("utf-8"), {
         "result": True,
         "price": {
             "total": format_money(price_info.price),
             "period_modifiers": str(price_info.period_modifiers.quantize(Decimal("1.00"))),
             "per_person_modifiers": str(price_info.per_person_modifiers.quantize(Decimal("1.00"))),
             "has_extra_info": True,
             "special_period_str": "Special period",
             "persons_count_str": "Person count",
         }
     })
Beispiel #9
0
    def label_from_instance(self, obj):
        label = force_text(obj.get_effective_name(self.basket))

        price_info = (
            obj.get_effective_price_info(self.basket)
            if self.basket and self.show_prices else None)
        price_text = (
            format_money(price_info.price)
            if price_info and price_info.price else None)

        return ("{} ({})".format(label, price_text) if price_text else label)
Beispiel #10
0
    def label_from_instance(self, obj):
        label = force_text(obj.get_effective_name(self.basket))

        price_info = (
            obj.get_effective_price_info(self.basket)
            if self.basket and self.show_prices else None)
        price_text = (
            format_money(price_info.price)
            if price_info and price_info.price else None)

        return ("{} ({})".format(label, price_text) if price_text else label)
Beispiel #11
0
 def handle_source_data(self, request):
     try:
         state = json.loads(request.body.decode("utf-8"))["state"]
         source = create_source_from_state(state, creator=request.user)
         # Calculate final lines for confirmation
         source.calculate_taxes(force_recalculate=True)
         return {
             "customerId": source.customer.id,
             "taxfulTotal": format_money(source.taxful_total_price.amount),
             "taxlessTotal": format_money(source.taxless_total_price.amount),
             "totalDiscountAmount": format_money(source.total_discount.amount),
             "orderLines": [encode_line(line) for line in source.get_final_lines(with_taxes=True)],
             "billingAddress": source.billing_address.as_string_list() if source.billing_address else None,
             "shippingAddress": source.shipping_address.as_string_list() if source.shipping_address else None,
         }
     except Exception as exc:
         message = _("Could not proceed with order:")
         if isinstance(exc, ValidationError):  # pragma: no branch
             message += "\n" + "\n".join(force_text(err) for err in exc.messages)
         else:  # pragma: no branch
             message += " " + str(exc)
         return JsonResponse({"success": False, "errorMessage": message}, status=400)
Beispiel #12
0
 def handle_source_data(self, request):
     try:
         state = json.loads(request.body.decode("utf-8"))["state"]
         source = create_source_from_state(state, creator=request.user)
         # Calculate final lines for confirmation
         source.calculate_taxes(force_recalculate=True)
         return {
             "customerId":
             source.customer.id,
             "taxfulTotal":
             format_money(source.taxful_total_price.amount),
             "taxlessTotal":
             format_money(source.taxless_total_price.amount),
             "totalDiscountAmount":
             format_money(source.total_discount.amount),
             "orderLines": [
                 encode_line(line)
                 for line in source.get_final_lines(with_taxes=True)
             ],
             "billingAddress":
             source.billing_address.as_string_list()
             if source.billing_address else None,
             "shippingAddress":
             source.shipping_address.as_string_list()
             if source.shipping_address else None,
         }
     except Exception as exc:
         message = _("Could not proceed with order:")
         if isinstance(exc, ValidationError):  # pragma: no branch
             message += "\n" + "\n".join(
                 force_text(err) for err in exc.messages)
         else:  # pragma: no branch
             message += " " + str(exc)
         return JsonResponse({
             "success": False,
             "errorMessage": message
         },
                             status=400)
Beispiel #13
0
def money(amount, digits=None, widen=0):
    """
    Format money amount according to current locale settings.

    :param amount: Money or Price object to format
    :type amount: shoop.utils.money.Money
    :param digits: Number of digits to use, by default use locale's default
    :type digits: int|None
    :param widen: Number of extra digits to add; for formatting with
      additional precision, e.g. `widen`=3 will use 5 digits instead of 2
    :type widen: int
    :return: Formatted string representing the given amount
    :rtype: str
    """
    return format_money(amount, digits, widen)
Beispiel #14
0
def money(amount, digits=None, widen=0):
    """
    Format money amount according to current locale settings.

    :param amount: Money or Price object to format
    :type amount: shoop.utils.money.Money
    :param digits: Number of digits to use, by default use locale's default
    :type digits: int|None
    :param widen: Number of extra digits to add; for formatting with
      additional precision, e.g. `widen`=3 will use 5 digits instead of 2
    :type widen: int
    :return: Formatted string representing the given amount
    :rtype: str
    """
    return format_money(amount, digits, widen)
 def test_free_period_should_return_period_is_free(self):
     request = RequestFactory().get("/")
     request.shop = self.shop
     response = self.client.get(
         "%s?reservable_id=%s&start=%s&end=%s" % (
             reverse('reservations:check_period'),
             self.reservable.id,
             self.next.strftime("%Y-%m-%d"),
             (self.next + datetime.timedelta(days=3)).strftime("%Y-%m-%d")
         )
     )
     price_info = self.reservable.product.get_price_info(request, quantity=3)
     self.assertJSONEqual(response.content.decode("utf-8"), {
         "result": True,
         "price": {
             "total": format_money(price_info.price),
             "has_extra_info": False,
         }
     })
Beispiel #16
0
def test_format_money():
    assert format_money(Money("3.6", "EUR"), locale="fi") == "3,60\xa0\u20ac"
    assert format_money(Money("3.6", "EUR"), widen=2, locale="fi") == "3,6000\xa0\u20ac"
    assert format_money(Money("3.6", "EUR"), digits=0, locale="fi") == "4\xa0\u20ac"
Beispiel #17
0
 def format_taxful_total_price(self, instance, *args, **kwargs):
     return escape(format_money(instance.taxful_total_price))
Beispiel #18
0
def test_format_money():
    assert format_money(Money("3.6", "EUR"), locale="fi") == "3,60\xa0\u20ac"
    assert format_money(Money("3.6", "EUR"), widen=2, locale="fi") == "3,6000\xa0\u20ac"
    assert format_money(Money("3.6", "EUR"), digits=0, locale="fi") == "4\xa0\u20ac"
Beispiel #19
0
 def format_taxful_total_price(self, instance, *args, **kwargs):
     return escape(format_money(instance.taxful_total_price))