#69 refactor(ReconciliationJar): extract to method.
This commit is contained in:
		| @@ -58,18 +58,14 @@ class ReconciliateJarView(APIView): | ||||
|         cash_purchases_id = data.get('cash_purchases') | ||||
|         serializer = ReconciliationJarSerializer(data=data) | ||||
|         if serializer.is_valid(): | ||||
|             purchases = Sale.objects.filter(pk__in=cash_purchases_id) | ||||
|             total_cash_purchases = sum(p.get_total() for p in purchases) | ||||
|             if total_cash_purchases != Decimal(data.get('total_cash_purchases')): | ||||
|             cash_purchases = Sale.objects.filter(pk__in=cash_purchases_id) | ||||
|             if not self._is_valid_total(cash_purchases, data.get('total_cash_purchases')): | ||||
|                 return Response( | ||||
|                     {'error': 'total_cash_purchases not equal to sum of all purchases.'}, | ||||
|                     status=HTTP_400_BAD_REQUEST | ||||
|                 ) | ||||
|             reconciliation = serializer.save() | ||||
|             for purchase in purchases: | ||||
|                 purchase.reconciliation = reconciliation | ||||
|                 purchase.clean() | ||||
|                 purchase.save() | ||||
|             self._link_purchases(reconciliation, cash_purchases) | ||||
|             return Response({'id': reconciliation.id}) | ||||
|         return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) | ||||
|  | ||||
| @@ -77,3 +73,13 @@ class ReconciliateJarView(APIView): | ||||
|         reconciliations = ReconciliationJar.objects.all() | ||||
|         serializer = ReconciliationJarSerializer(reconciliations, many=True) | ||||
|         return Response(serializer.data) | ||||
|  | ||||
|     def _is_valid_total(self, purchases, total): | ||||
|         calculated_total = sum(p.get_total() for p in purchases) | ||||
|         return calculated_total == Decimal(total) | ||||
|  | ||||
|     def _link_purchases(self, reconciliation, purchases): | ||||
|         for purchase in purchases: | ||||
|             purchase.reconciliation = reconciliation | ||||
|             purchase.clean() | ||||
|             purchase.save() | ||||
|   | ||||
		Reference in New Issue
	
	Block a user