From ac708d909da509983cc9282f4e26e42289fd1824 Mon Sep 17 00:00:00 2001
From: Dominik George <dominik.george@teckids.org>
Date: Sun, 6 Mar 2022 23:30:46 +0100
Subject: [PATCH] Add tables interface to invoice

---
 aleksis/apps/tezor/models/invoice.py | 28 ++++++++++++++++++++++++++++
 aleksis/apps/tezor/tables.py         | 16 ++++++++++++++++
 2 files changed, 44 insertions(+)
 create mode 100644 aleksis/apps/tezor/tables.py

diff --git a/aleksis/apps/tezor/models/invoice.py b/aleksis/apps/tezor/models/invoice.py
index 356aa4b..03f4fc9 100644
--- a/aleksis/apps/tezor/models/invoice.py
+++ b/aleksis/apps/tezor/models/invoice.py
@@ -10,6 +10,7 @@ from payments.models import BasePayment
 from aleksis.core.mixins import ExtensibleModel, PureDjangoModel
 
 from .base import Client
+from ..tables import PurchasedItemsTable, TotalsTable
 
 
 class InvoiceGroup(ExtensibleModel):
@@ -44,3 +45,30 @@ class Invoice(BasePayment, PureDjangoModel):
         constraints = [
             models.UniqueConstraint(fields=["transaction_id", "group"], name="number_uniq_per_group")
         ]
+
+    @property
+    def purchased_items_table(self):
+        items = [i._asdict() for i in self.get_purchased_items()]
+        return PurchasedItemsTable(items)
+
+    @property
+    def totals_table(self):
+        tax_amounts = {}
+        for item in self.get_purchased_items():
+            tax_amounts.setdefault(item.tax_rate, 0)
+            tax_amounts[item.tax_rate] += item.price / (item.tax_rate + 100) * item.tax_rate
+
+        values = []
+        for tax_rate, total in tax_amounts:
+            values.append({
+                "name": _("Included VAT {} %").format(tax_rate),
+                "value": total,
+                "currency": self.currency,
+            })
+        values.append({
+            "name": _("Gross total"),
+            "value": self.total,
+            "currency": self.currency,
+        })
+
+        return TotalsTable(values)
diff --git a/aleksis/apps/tezor/tables.py b/aleksis/apps/tezor/tables.py
new file mode 100644
index 0000000..5eff624
--- /dev/null
+++ b/aleksis/apps/tezor/tables.py
@@ -0,0 +1,16 @@
+import django_tables2 as tables
+
+
+class PurchasedItemsTable(tables.Table):
+    sku = tables.Column()
+    name = tables.Column()
+    tax_rate = tables.Column()
+    quantity = tables.Column()
+    price = tables.Column()
+    currency = tables.Column()
+
+
+class TotalsTable(tables.Table):
+    name = tables.Column()
+    value = tables.Column()
+    currency = tables.Column()
-- 
GitLab