Browse Source

Add Service.compare() method

To be able to show figure variations between two documents.
Jocelyn Delalande 7 years ago
parent
commit
83c2d5edcd
2 changed files with 48 additions and 0 deletions
  1. 31 0
      costs/models.py
  2. 17 0
      costs/tests/test_models.py

+ 31 - 0
costs/models.py

@@ -91,6 +91,37 @@ class Document(models.Model):
     def get_total_goods(self):
         return self.good_set.aggregate(sum=Sum('price'))['sum'] or 0
 
+    def compare(self, other_doc):
+        """ Compare this document to another one
+
+        :type other_doc: Document
+        :rtype: dict
+        """
+        service_records = []
+        for service in self.service_set.subscribables():
+            other_service = Service.objects.similar_to(service).filter(
+                document=other_doc).first()
+
+            if other_service:
+                deltas  = service.compare(other_service)
+            else:
+                deltas = {}
+
+            service_records.append({
+                'service': service,
+                'other_service': other_service,
+                'deltas': deltas,
+            })
+
+        comparison = {
+            'services': service_records,
+            'total_recuring_costs': self.get_total_recuring_costs() - other_doc.get_total_recuring_costs(),
+            'total_goods': self.get_total_goods() - other_doc.get_total_goods(),
+        }
+
+        return comparison
+
+
 class AbstractItem(models.Model):
     name = models.CharField('Nom', max_length=130)
     description = models.TextField('description', blank=True)

+ 17 - 0
costs/tests/test_models.py

@@ -412,3 +412,20 @@ class TestDocuments(TestCase):
         self.assertEqual(self._count(), [i*2 for i in initial_counts])
         old_doc.delete()
         self.assertEqual(self._count(), initial_counts)
+
+    def test_compare(self):
+        doc1 = Document.objects.create(name='a budget')
+        doc2 = Document.objects.create(name='a budget')
+
+        Service.objects.create(
+            name='Foo', document=doc2, subscriptions_count=3)
+        Service.objects.create(
+            name='Bar', document=doc2, subscriptions_count=3)
+        Service.objects.create(
+            name='Bar', document=doc1, subscriptions_count=3)
+
+        comparison = doc2.compare(doc1)
+
+        self.assertEqual(len(comparison['services']), 2)
+        self.assertIsNone(comparison['services'][0]['other_service'])
+        self.assertIsNotNone(comparison['services'][1]['other_service'])