|
1 | 1 | from typing import Dict, Any |
2 | 2 | from django.db import transaction |
3 | 3 | from .models import Entity |
| 4 | +from decimal import Decimal, InvalidOperation, ROUND_DOWN |
4 | 5 |
|
5 | 6 | def list_entities( |
6 | 7 | name: str = None, |
@@ -35,11 +36,32 @@ def get_entity(entity_id: int) -> Entity: |
35 | 36 | return Entity.objects.get(pk=entity_id) |
36 | 37 |
|
37 | 38 | def create_entity(data: Dict[str, Any]) -> Entity: |
| 39 | + # accept `unit_price` (e.g. 50.99) and store as Decimal with 4 decimal places |
| 40 | + unit = data.pop('unit_price', None) |
| 41 | + if unit is not None: |
| 42 | + # accept both 50.99 and '50,99' by normalizing comma to dot |
| 43 | + unit_str = str(unit).replace(',', '.') |
| 44 | + try: |
| 45 | + d = Decimal(unit_str) |
| 46 | + except (InvalidOperation, ValueError): |
| 47 | + d = Decimal(float(unit_str)) |
| 48 | + # store with 4 decimal places to preserve measurement precision, truncate (ROUND_DOWN) |
| 49 | + data['unit_price'] = d.quantize(Decimal('0.0001'), rounding=ROUND_DOWN) |
38 | 50 | with transaction.atomic(): |
39 | 51 | return Entity.objects.create(**data) |
40 | 52 |
|
41 | 53 | def update_entity(entity_id: int, data: Dict[str, Any]) -> Entity: |
42 | 54 | with transaction.atomic(): |
| 55 | + # support updating via `unit_price` as well |
| 56 | + unit = data.pop('unit_price', None) |
| 57 | + if unit is not None: |
| 58 | + unit_str = str(unit).replace(',', '.') |
| 59 | + try: |
| 60 | + d = Decimal(unit_str) |
| 61 | + except (InvalidOperation, ValueError): |
| 62 | + d = Decimal(float(unit_str)) |
| 63 | + data['unit_price'] = d.quantize(Decimal('0.0001'), rounding=ROUND_DOWN) |
| 64 | + |
43 | 65 | obj = Entity.objects.get(pk=entity_id) |
44 | 66 | for k, v in data.items(): |
45 | 67 | setattr(obj, k, v) |
|
0 commit comments