Skip to content

Commit

Permalink
Improve to_decimal() implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
osantana committed Apr 25, 2017
1 parent 0ec90de commit cbf1a14
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 15 deletions.
9 changes: 2 additions & 7 deletions correios/models/posting.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@
MAX_CYLINDER_SIZE = 28
INSURANCE_VALUE_THRESHOLD = Decimal("50.00") # R$
INSURANCE_PERCENTUAL_COST = Decimal("0.007") # 0.7%
MONEY_QUANTIZATION = Decimal("0.00")


class EventStatus:
Expand Down Expand Up @@ -361,7 +360,7 @@ def calculate_insurance(cls,
per_unit_value = Decimal(per_unit_value)
if Service.get(service) == Service.get(SERVICE_PAC) and per_unit_value > INSURANCE_VALUE_THRESHOLD:
value = (per_unit_value - INSURANCE_VALUE_THRESHOLD) * INSURANCE_PERCENTUAL_COST
return Decimal(value * quantity).quantize(MONEY_QUANTIZATION)
return to_decimal(value * quantity)

@classmethod
def validate(cls,
Expand Down Expand Up @@ -695,10 +694,6 @@ def __init__(self,
service: Union[Service, int],
error_code: Union[str, int],
error_message: str) -> None:
super().__init__(
service=service,
value=Decimal("0.00"),
delivery_time=timedelta(days=0),
)
super().__init__(service, 0, Decimal("0.00"))
self.error_code = int(error_code)
self.error_message = error_message
18 changes: 10 additions & 8 deletions correios/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,13 +69,15 @@ def to_datetime(date: Union[datetime, str], fmt="%Y-%m-%d %H:%M:%S%z") -> dateti
return date


def to_decimal(value: Union[str, float], precision=2):
value = rreplace(str(value), ",", ".", 1)
if "." in value:
real, imag = value.rsplit(".", 1)
else:
real, imag = value, "0"
real = re.sub("[,._]", "", real)
def to_decimal(value: Union[Decimal, str, float], precision=2):
if not isinstance(value, Decimal):
value = rreplace(str(value), ",", ".", 1)
if "." in value:
real, imag = value.rsplit(".", 1)
else:
real, imag = value, "0"
real = re.sub("[,._]", "", real)
value = Decimal("{}.{}".format(real, imag))

quantize = Decimal("0." + "0" * precision)
return Decimal("{}.{}".format(real, imag)).quantize(quantize)
return value.quantize(quantize)

0 comments on commit cbf1a14

Please sign in to comment.