change Payment.from_toml to private
[utils.git] / src / budget_sync / budget_graph.py
index 1ebcd509a9ec3dd07d0259535436aa6e75626dfa..dd59fd4ac2222d9def9556777ac2f55b1267a4b2 100644 (file)
@@ -1,12 +1,14 @@
 from bugzilla.bug import Bug
 from bugzilla import Bugzilla
-from typing import Set, Dict, Iterable, Optional, List
+from typing import Set, Dict, Iterable, Optional, List, Union, Any
 from budget_sync.util import all_bugs
 from budget_sync.money import Money
 from functools import cached_property
 import toml
 import sys
+import enum
 from collections import deque
+from datetime import date, time, datetime
 
 
 class BudgetGraphBaseError(Exception):
@@ -49,6 +51,140 @@ class _NodeSimpleReprWrapper:
         return self.node.bug.id < other.node.bug.id
 
 
+class PayeeState(enum.Enum):
+    NotYetSubmitted = "not yet submitted"
+    Submitted = "submitted"
+    Paid = "paid"
+
+
+_Date = Union[date, datetime]
+
+
+def _parse_money_from_toml(value: Any) -> Money:
+    if not isinstance(value, (int, str)):
+        msg = f"monetary amount is not a string or integer " \
+            f"(to use fractional amounts such as 123.45, write " \
+            f"\"123.45\"): {value!r}"
+        raise ValueError(msg)
+    return Money(value)
+
+
+def _parse_date_time_or_none_from_toml(value: Any) -> Optional[_Date]:
+    if value is None or isinstance(value, (date, datetime)):
+        return value
+    elif isinstance(value, time):
+        msg = f"just a time of day by itself is not enough," \
+            f" a date must be included: {str(value)}"
+        raise ValueError(msg)
+    elif isinstance(value, bool):
+        msg = f"invalid date: {str(value).lower()}"
+        raise ValueError(msg)
+    elif isinstance(value, (str, int, float)):
+        msg = f"invalid date: {value!r}"
+        raise ValueError(msg)
+    else:
+        msg = f"invalid date"
+        raise ValueError(msg)
+
+
+class Payment:
+    def __init__(self,
+                 node: "Node",
+                 payee_key: str,
+                 amount: Money,
+                 paid: Optional[_Date],
+                 submitted: Optional[_Date]):
+        self.node = node
+        self.payee_key = payee_key
+        self.amount = amount
+        self.paid = paid
+        self.submitted = submitted
+
+    @property
+    def state(self):
+        if self.paid is not None:
+            return PayeeState.Paid
+        if self.submitted is not None:
+            return PayeeState.Submitted
+        return PayeeState.NotYetSubmitted
+
+    @staticmethod
+    def _from_toml(node: "Node", payee_key: str, toml_value: Any) -> "Payment":
+        paid = None
+        submitted = None
+        known_keys = ("paid", "submitted", "amount")
+        if isinstance(toml_value, dict):
+            try:
+                amount = toml_value['amount']
+            except KeyError:
+                msg = f"value for key {payee_key!r} is missing the " \
+                    f"`amount` field which is required"
+                raise BudgetGraphPayeesParseError(node.bug.id, msg) \
+                    .with_traceback(sys.exc_info()[2])
+            for k, v in toml_value.items():
+                if k in ("paid", "submitted"):
+                    try:
+                        parsed_value = _parse_date_time_or_none_from_toml(v)
+                    except ValueError as e:
+                        msg = f"failed to parse `{k}` field for" \
+                            f" key {payee_key!r}: {e}"
+                        raise BudgetGraphPayeesParseError(
+                            node.bug.id, msg) \
+                            .with_traceback(sys.exc_info()[2])
+                    if k == "paid":
+                        paid = parsed_value
+                    else:
+                        assert k == "submitted"
+                        submitted = parsed_value
+                if k not in known_keys:
+                    msg = f"value for key {payee_key!r} has an unknown" \
+                        f" field: `{k}`"
+                    raise BudgetGraphPayeesParseError(node.bug.id, msg) \
+                        .with_traceback(sys.exc_info()[2])
+            try:
+                paid = _parse_date_time_or_none_from_toml(
+                    toml_value.get('paid'))
+            except ValueError as e:
+                msg = f"failed to parse `paid` field for" \
+                    f" key {payee_key!r}: {e}"
+                raise BudgetGraphPayeesParseError(
+                    node.bug.id, msg) \
+                    .with_traceback(sys.exc_info()[2])
+            try:
+                submitted = _parse_date_time_or_none_from_toml(
+                    toml_value.get('submitted'))
+            except ValueError as e:
+                msg = f"failed to parse `submitted` field for" \
+                    f" key {payee_key!r}: {e}"
+                raise BudgetGraphPayeesParseError(
+                    node.bug.id, msg) \
+                    .with_traceback(sys.exc_info()[2])
+        elif isinstance(toml_value, (int, str, float)):
+            # float included for better error messages
+            amount = toml_value
+        else:
+            msg = f"value for key {payee_key!r} is invalid -- it should " \
+                f"either be a monetary value or a table"
+            raise BudgetGraphPayeesParseError(node.bug.id, msg)
+        try:
+            amount = _parse_money_from_toml(amount)
+        except ValueError as e:
+            msg = f"failed to parse monetary amount for key {payee_key!r}: {e}"
+            raise BudgetGraphPayeesParseError(
+                node.bug.id, msg) \
+                .with_traceback(sys.exc_info()[2])
+        return Payment(node=node, payee_key=payee_key, amount=amount,
+                       paid=paid, submitted=submitted)
+
+    def __repr__(self):
+        return (f"Payment(node={_NodeSimpleReprWrapper(self.node)}, "
+                f"payee_key={self.payee_key!r}, "
+                f"amount={self.amount}, "
+                f"state={self.state.name}, "
+                f"paid={str(self.paid)}, "
+                f"submitted={str(self.submitted)})")
+
+
 class Node:
     graph: "BudgetGraph"
     bug: Bug
@@ -74,7 +210,7 @@ class Node:
             self.nlnet_milestone = None
 
     @cached_property
-    def payees(self) -> Dict[str, Money]:
+    def payments(self) -> Dict[str, Payment]:
         try:
             parsed = toml.loads(self.bug.cf_payees_list)
         except toml.TomlDecodeError as e:
@@ -86,19 +222,7 @@ class Node:
             if not isinstance(key, str):
                 raise BudgetGraphPayeesParseError(
                     self.bug.id, f"key is not a string: {key!r}")
-            if not isinstance(value, (int, str)):
-                msg = f"value for key {key!r} is not a string or integer " \
-                    f"(to use fractional values such as 123.45, write " \
-                    f"\"123.45\"): {value!r}"
-                raise BudgetGraphPayeesParseError(self.bug.id, msg)
-            try:
-                money_value = Money(value)
-            except ValueError as e:
-                msg = f"failed to parse Money value for key {key!r}: {e}"
-                raise BudgetGraphPayeesParseError(
-                    self.bug.id, msg) \
-                    .with_traceback(sys.exc_info()[2])
-            retval[key] = money_value
+            retval[key] = Payment._from_toml(self, key, value)
         return retval
 
     @property
@@ -151,9 +275,6 @@ class Node:
     def __eq__(self, other):
         return self.bug.id == other.bug.id
 
-    def __ne__(self, other):
-        return self.bug.id != other.bug.id
-
     def __hash__(self):
         return self.bug.id
 
@@ -167,6 +288,7 @@ class Node:
             immediate_children.append(_NodeSimpleReprWrapper(i))
         immediate_children.sort()
         parent = f"#{self.parent_id}" if self.parent_id is not None else None
+        payments = list(self.payments.values())
         return (f"Node(graph=..., "
                 f"id={_NodeSimpleReprWrapper(self)}, "
                 f"root={root}, "
@@ -177,7 +299,7 @@ class Node:
                 f"fixed_budget_including_subtasks={self.fixed_budget_including_subtasks}, "
                 f"nlnet_milestone={self.nlnet_milestone!r}, "
                 f"immediate_children={immediate_children!r}, "
-                f"payees={self.payees!r}")
+                f"payments={payments!r}")
 
 
 class BudgetGraphError(BudgetGraphBaseError):
@@ -301,11 +423,11 @@ class BudgetGraph:
             subtasks_total += child.fixed_budget_including_subtasks
 
         payees_total = Money(0)
-        for payee_key, payee_value in node.payees.items():
-            if payee_value < 0:
+        for payment in node.payments.values():
+            if payment.amount < 0:
                 errors.append(BudgetGraphNegativePayeeMoney(
-                    node.bug.id, root.bug.id, payee_key))
-            payees_total += payee_value
+                    node.bug.id, root.bug.id, payment.payee_key))
+            payees_total += payment.amount
 
         def set_including_from_excluding_and_error():
             node.fixed_budget_including_subtasks = \
@@ -367,7 +489,7 @@ class BudgetGraph:
             # can't have 2 match without all 3 matching
             assert not payees_matches_excluding
             assert not including_matches_excluding
-            if node.budget_including_subtasks == 0 and len(node.payees) == 0:
+            if node.budget_including_subtasks == 0 and len(node.payments) == 0:
                 set_including_from_excluding_and_error()
             else:
                 set_excluding_from_including_and_error()
@@ -375,7 +497,7 @@ class BudgetGraph:
             # can't have 2 match without all 3 matching
             assert not payees_matches_including
             assert not including_matches_excluding
-            if node.budget_excluding_subtasks == 0 and len(node.payees) == 0:
+            if node.budget_excluding_subtasks == 0 and len(node.payments) == 0:
                 if node.budget_including_subtasks == 0:
                     set_including_from_excluding_and_error()
                 else:
@@ -386,7 +508,7 @@ class BudgetGraph:
             # can't have 2 match without all 3 matching
             assert not payees_matches_including
             assert not payees_matches_excluding
-            if len(node.payees) == 0:
+            if len(node.payments) == 0:
                 pass  # no error -- payees is just not set
             elif node.budget_excluding_subtasks == 0 \
                     and node.budget_including_subtasks == 0:
@@ -396,7 +518,7 @@ class BudgetGraph:
                 set_payees_from_excluding_and_error()
         else:
             # nothing matches
-            if len(node.payees) == 0:
+            if len(node.payments) == 0:
                 # payees unset -- don't need to set payees
                 if node.budget_including_subtasks == 0:
                     set_including_from_excluding_and_error()
@@ -440,6 +562,6 @@ class BudgetGraph:
     def payee_keys(self) -> Set[str]:
         retval = set()
         for node in self.nodes.values():
-            for payee_key in node.payees.keys():
+            for payee_key in node.payments.keys():
                 retval.add(payee_key)
         return retval