Browse Source

use class properties

Fabian Peter Hammerle 8 years ago
parent
commit
2d0653ccd0
2 changed files with 81 additions and 41 deletions
  1. 64 1
      dingguo/__init__.py
  2. 17 40
      scripts/order-confirmation-mail-parser

+ 64 - 1
dingguo/__init__.py

@@ -1,9 +1,72 @@
+# -*- coding: utf-8 -*-
 import yaml
 
 class Figure(object):
 
     def __init__(self, value, unit):
         self.value = value
-        assert type(unit) is unicode
         self.unit = unit
 
+    def get_value(self):
+        return self._value
+
+    def set_value(self, value):
+        self._value = value
+
+    """ use property() instead of decorator to enable overriding """
+    value = property(get_value, set_value)
+
+    def get_unit(self):
+        return self._unit
+
+    def set_unit(self, unit):
+        assert type(unit) is unicode
+        self._unit = unit
+
+    """ use property() instead of decorator to enable overriding """
+    unit = property(get_unit, set_unit)
+
+class Distance(Figure):
+
+    def __init__(self, value, unit):
+        assert type(value) is float
+        super(Distance, self).__init__(value, unit)
+
+    @property
+    def metres(self):
+        if self.unit == 'km':
+            return self.value * 1000
+        else:
+            raise Exception()
+
+class Sum(Figure):
+
+    def __init__(self, value, currency):
+        super(Sum, self).__init__(value, currency)
+
+    def get_value(self):
+        return super(Sum, self).get_value()
+
+    def set_value(self, value):
+        assert type(value) is float
+        super(Sum, self).set_value(value)
+
+    """ use property() instead of decorator to enable overriding """
+    value = property(get_value, set_value)
+
+    @property
+    def currency(self):
+        return self.unit
+
+    def get_unit(self):
+        return super(Sum, self).get_unit()
+
+    def set_unit(self, currency):
+        if currency == u'€':
+            currency = u'EUR'
+        assert type(currency) is unicode
+        assert currency in [u'EUR']
+        super(Sum, self).set_unit(currency)
+
+    """ use property() instead of decorator to enable overriding """
+    unit = property(get_unit, set_unit)

+ 17 - 40
scripts/order-confirmation-mail-parser

@@ -48,29 +48,6 @@ class Order(object):
 
 yaml.SafeDumper.add_representer(Order, lambda dumper, order: dumper.represent_dict(order.dict_repr()))
 
-class Distance(dingguo.Figure):
-
-    def __init__(self, value, unit):
-        assert type(value) is float
-        super(Distance, self).__init__(value, unit)
-
-    def metres(self):
-        if self.unit == 'km':
-            return self.value * 1000
-        else:
-            raise Exception()
-
-class Sum(object):
-
-    def __init__(self, value, currency):
-        assert type(value) is float
-        self.value = value
-        if currency == u'€':
-            currency = u'EUR'
-        assert type(currency) is unicode
-        assert currency in [u'EUR']
-        self.currency = currency
-
 class Discount(object):
 
     def __init__(
@@ -80,7 +57,7 @@ class Discount(object):
             ):
         assert type(name) is unicode
         self.name = name
-        assert type(amount) is Sum
+        assert type(amount) is dingguo.Sum
         assert amount.value >= 0
         self.amount = amount
 
@@ -102,7 +79,7 @@ class Item(object):
             ):
         assert type(name) is unicode
         self.name = name
-        assert type(price_brutto) is Sum
+        assert type(price_brutto) is dingguo.Sum
         self.price_brutto = price_brutto
 
     def dict_repr(self):
@@ -168,7 +145,7 @@ class Transportation(Item):
         self.departure_point = departure_point
         assert type(destination_point) is unicode
         self.destination_point = destination_point
-        assert distance is None or type(distance) is Distance
+        assert distance is None or type(distance) is dingguo.Distance
         self.distance = distance
         assert route_map is None or type(route_map) is str
         self.route_map = route_map
@@ -178,7 +155,7 @@ class Transportation(Item):
         attr.update({
             'departure_point': self.departure_point,
             'destination_point': self.destination_point,
-            'distance_metres': self.distance.metres() if self.distance else None,
+            'distance_metres': self.distance.metres if self.distance else None,
             'route_map': self.route_map,
             })
         return attr
@@ -250,7 +227,7 @@ def parse_amazon(msg):
             article = article_match.groupdict()
             order.items.append(Article(
                 name = article['name'],
-                price_brutto = Sum(
+                price_brutto = dingguo.Sum(
                     float(article['price_brutto'].replace(',', '.')),
                     article['price_brutto_currency']
                     ),
@@ -308,7 +285,7 @@ def parse_oebb(msg):
     item = item_match.groupdict()
     order.items.append(Transportation(
         name = u'Train Ticket',
-        price_brutto = Sum(
+        price_brutto = dingguo.Sum(
             float(item['price_brutto']),
             item['price_brutto_currency'],
             ),
@@ -374,7 +351,7 @@ def parse_mytaxi(msg):
         )
     locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
     order.items.append(TaxiRide(
-        price_brutto = Sum(
+        price_brutto = dingguo.Sum(
             float(ride_match_groups['price_brutto'].replace(',', '.')),
             # why 0x80 ?
             u'EUR' if (ride_match_groups['price_brutto_currency'] == u'\x80')
@@ -432,7 +409,7 @@ def parse_uber(msg):
         '%I:%M%p',
         ).time()
 
-    distance = Distance(
+    distance = dingguo.Distance(
         float(doc.find(text = 'kilometers').parent.parent.find(attrs = {'class': 'data'}).text),
         u'km',
         )
@@ -441,7 +418,7 @@ def parse_uber(msg):
 
     order.items.append(TaxiRide(
         name = doc.find(text = 'CAR').parent.parent.find(attrs = {'class': 'data'}).text + ' Ride',
-        price_brutto = Sum(float(fare[1:]), fare[0]),
+        price_brutto = dingguo.Sum(float(fare[1:]), fare[0]),
         arrival_time = datetime.datetime.combine(order.order_date, arrival_time),
         departure_time = datetime.datetime.combine(order.order_date, departure_time),
         departure_point = departure_time_tag.parent.find(attrs = {'class': 'address'}).text,
@@ -489,7 +466,7 @@ def parse_yipbee(msg):
         quantity = int(article_match_groups['quantity'])
         order.items.append(Article(
             name = article_match_groups['name'],
-            price_brutto = Sum(round(total_price / quantity, 2), u'EUR'),
+            price_brutto = dingguo.Sum(round(total_price / quantity, 2), u'EUR'),
             quantity = quantity,
             reseller = u'yipbee',
             shipper = u'yipbee',
@@ -507,14 +484,14 @@ def parse_yipbee(msg):
         value, currency = value_tag.text.split(' ')
         order.discounts.append(Discount(
             name = name_tag.text,
-            amount = Sum(float(value.replace(',', '.')) * -1, currency),
+            amount = dingguo.Sum(float(value.replace(',', '.')) * -1, currency),
             ))
 
     delivery_price = order_match_groups['summary_text'].split('VERSAND')[1].split('STEUERN')[0].strip()
     delivery_price_value, delivery_price_currency = delivery_price.split(' ')
     order.items.append(Item(
         name = u'Delivery',
-        price_brutto = Sum(float(delivery_price_value.replace(',', '.')), delivery_price_currency),
+        price_brutto = dingguo.Sum(float(delivery_price_value.replace(',', '.')), delivery_price_currency),
         ))
 
     return [order]
@@ -547,7 +524,7 @@ def parse_yipbee_html(msg):
         (price, currency) = re.sub(ur'\s+', ' ', article_columns[2].text.replace(u',', u'.')).split(' ')
         order.items.append(Article(
             name = article_columns[1].text,
-            price_brutto = Sum(float(price), currency),
+            price_brutto = dingguo.Sum(float(price), currency),
             quantity = int(article_columns[3].text),
             reseller = u'yipbee',
             shipper = u'yipbee',
@@ -558,14 +535,14 @@ def parse_yipbee_html(msg):
     (discount_value, discount_currency) = discount_value_with_currency.split(' ')
     order.discounts.append(Discount(
         name = discount_name,
-        amount = Sum(float(discount_value.replace(',', '.')) * -1, discount_currency)
+        amount = dingguo.Sum(float(discount_value.replace(',', '.')) * -1, discount_currency)
         ))
 
     shipping_costs_table = content_table.find('tbody').findAll('tr', recursive = False)[3].findAll('table')[1]
     (shipping_price, shipping_currency) = shipping_costs_table.text.replace(',', '.').split(' ')
     order.items.append(Item(
         name = u'Delivery',
-        price_brutto = Sum(float(shipping_price), shipping_currency),
+        price_brutto = dingguo.Sum(float(shipping_price), shipping_currency),
         ))
 
     return [order]
@@ -614,7 +591,7 @@ def parse_lieferservice(msg):
         quantity = int(article_match_groups['quantity'])
         assert quantity == 1
         name = re.sub(ur' +', ' ', article_match_groups['name'])
-        price = Sum(
+        price = dingguo.Sum(
             float(article_match_groups['price'].replace(',', '.')),
             article_match_groups['currency'],
             )
@@ -637,7 +614,7 @@ def parse_lieferservice(msg):
     assert delivery_costs == 'FREE'
     order.items.append(Item(
         name = u'Delivery',
-        price_brutto = Sum(float('0'.replace(',', '.')), u'EUR'),
+        price_brutto = dingguo.Sum(float('0'.replace(',', '.')), u'EUR'),
         ))
 
     return [order]