__init__.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. # -*- coding: utf-8 -*-
  2. import yaml
  3. import yaml.representer
  4. import datetime
  5. yaml.Dumper.add_representer(unicode, yaml.representer.SafeRepresenter.represent_unicode)
  6. class _YamlUnicodeConstruct(yaml.YAMLObject):
  7. @classmethod
  8. def from_yaml(cls, loader, node):
  9. return cls(**{
  10. k: unicode(v) if isinstance(v, str) else v
  11. for (k, v) in loader.construct_mapping(node, deep = True).items()
  12. })
  13. class Figure(_YamlUnicodeConstruct):
  14. yaml_tag = u"!figure"
  15. def __init__(self, value, unit):
  16. self.value = value
  17. self.unit = unit
  18. def get_value(self):
  19. return self._value
  20. def set_value(self, value):
  21. self._value = value
  22. """ use property() instead of decorator to enable overriding """
  23. value = property(get_value, set_value)
  24. def get_unit(self):
  25. return self._unit
  26. def set_unit(self, unit):
  27. assert type(unit) is unicode
  28. self._unit = unit
  29. """ use property() instead of decorator to enable overriding """
  30. unit = property(get_unit, set_unit)
  31. def __eq__(self, other):
  32. return type(self) == type(other) and self.value == other.value and self.unit == other.unit
  33. def __ne__(self, other):
  34. return not (self == other)
  35. @classmethod
  36. def to_yaml(cls, dumper, figure):
  37. return dumper.represent_mapping(
  38. cls.yaml_tag,
  39. {'unit': figure.get_unit(), 'value': figure.get_value()},
  40. )
  41. class Distance(Figure):
  42. def __init__(self, value, unit):
  43. assert type(value) is float
  44. super(Distance, self).__init__(value, unit)
  45. @property
  46. def metres(self):
  47. if self.unit == 'km':
  48. return self.value * 1000
  49. else:
  50. raise Exception()
  51. class Sum(Figure):
  52. yaml_tag = u'!sum'
  53. def __init__(self, value, currency):
  54. super(Sum, self).__init__(value, currency)
  55. def get_value(self):
  56. return super(Sum, self).get_value()
  57. def set_value(self, value):
  58. assert type(value) is float
  59. super(Sum, self).set_value(value)
  60. """ use property() instead of decorator to enable overriding """
  61. value = property(get_value, set_value)
  62. @property
  63. def currency(self):
  64. return self.unit
  65. def get_unit(self):
  66. return super(Sum, self).get_unit()
  67. def set_unit(self, currency):
  68. if currency == u'€':
  69. currency = u'EUR'
  70. assert type(currency) is unicode
  71. assert currency in [u'EUR']
  72. super(Sum, self).set_unit(currency)
  73. """ use property() instead of decorator to enable overriding """
  74. unit = property(get_unit, set_unit)
  75. @classmethod
  76. def from_yaml(cls, loader, node):
  77. attr = loader.construct_scalar(node).split(' ')
  78. return cls(
  79. currency = attr[0],
  80. value = float(attr[1]),
  81. )
  82. @classmethod
  83. def to_yaml(cls, dumper, s):
  84. return dumper.represent_scalar(
  85. cls.yaml_tag,
  86. '%s %s' % (s.currency, repr(s.value)),
  87. )
  88. class Discount(yaml.YAMLObject):
  89. yaml_tag = u'!discount'
  90. def __init__(
  91. self,
  92. name = None,
  93. amount = None,
  94. ):
  95. assert type(name) is unicode
  96. self.name = name
  97. assert type(amount) is Sum
  98. assert amount.value >= 0
  99. self.amount = amount
  100. def dict_repr(self):
  101. return {
  102. 'name': self.name,
  103. 'value': self.amount.value,
  104. 'value_currency': self.amount.currency,
  105. }
  106. @staticmethod
  107. def from_dict(attr):
  108. return Discount(
  109. name = attr['name'],
  110. amount = Sum(attr['value'], attr['value_currency']),
  111. )
  112. def __eq__(self, other):
  113. return type(self) == type(other) and self.name == other.name and self.amount == other.amount
  114. def __ne__(self, other):
  115. return not (self == other)
  116. yaml.SafeDumper.add_representer(Discount, lambda dumper, discount: dumper.represent_dict(discount.dict_repr()))
  117. class Order(_YamlUnicodeConstruct):
  118. yaml_tag = u'!order'
  119. def __init__(self, platform, order_id, order_date,
  120. customer_id = None,
  121. items = None,
  122. discounts = None,
  123. ):
  124. assert type(platform) is unicode
  125. self.platform = platform
  126. assert type(order_id) is unicode
  127. self.order_id = order_id
  128. if type(order_date) is datetime.datetime:
  129. order_date = order_date.date()
  130. assert type(order_date) is datetime.date
  131. self.order_date = order_date
  132. assert customer_id is None or type(customer_id) is unicode
  133. self.customer_id = customer_id
  134. if items is None:
  135. items = []
  136. assert type(items) is list
  137. self.items = items
  138. if discounts is None:
  139. discounts = []
  140. assert type(discounts) is list
  141. self.discounts = discounts
  142. def dict_repr(self):
  143. return {k: v for (k, v) in {
  144. 'articles': self.items,
  145. 'customer_id': self.customer_id,
  146. 'discounts': self.discounts,
  147. 'order_date': self.order_date.strftime('%Y-%m-%d'),
  148. 'order_id': self.order_id,
  149. 'platform': self.platform,
  150. }.items() if v is not None}
  151. @staticmethod
  152. def from_dict(attr):
  153. order = Order(
  154. platform = attr['platform'],
  155. order_id = attr['order_id'],
  156. order_date = datetime.datetime.strptime(attr['order_date'], '%Y-%m-%d'),
  157. )
  158. if 'customer_id' in attr:
  159. order.customer_id = attr['customer_id']
  160. for item in attr['articles']:
  161. if type(item) is dict:
  162. item = Item.from_dict(item)
  163. assert isinstance(item, Item)
  164. order.items.append(item)
  165. for discount in attr['discounts']:
  166. if type(discount) is dict:
  167. discount = Discount.from_dict(discount)
  168. assert isinstance(discount, Discount)
  169. order.discounts.append(discount)
  170. return order
  171. def __eq__(self, other):
  172. return (type(self) == type(other)
  173. and vars(self) == vars(other))
  174. def __ne__(self, other):
  175. return not (self == other)
  176. yaml.SafeDumper.add_representer(Order, lambda dumper, order: dumper.represent_dict(order.dict_repr()))
  177. class Item(_YamlUnicodeConstruct):
  178. yaml_tag = u'!item'
  179. def __init__(
  180. self,
  181. name = None,
  182. price_brutto = None,
  183. ):
  184. assert type(name) is unicode
  185. self.name = name
  186. assert type(price_brutto) is Sum
  187. self.price_brutto = price_brutto
  188. def dict_repr(self):
  189. return {
  190. 'name': self.name,
  191. 'price_brutto': self.price_brutto.value,
  192. 'price_brutto_currency': self.price_brutto.currency,
  193. }
  194. @staticmethod
  195. def from_dict(attr):
  196. return Item(
  197. name = attr['name'],
  198. price_brutto = Sum(attr['price_brutto'], attr['price_brutto_currency']),
  199. )
  200. def __eq__(self, other):
  201. return type(self) == type(other) and self.name == other.name and self.price_brutto == other.price_brutto
  202. def __ne__(self, other):
  203. return not (self == other)
  204. yaml.SafeDumper.add_representer(Item, lambda dumper, item: dumper.represent_dict(item.dict_repr()))
  205. class Article(Item):
  206. def __init__(
  207. self,
  208. quantity = None,
  209. authors = [],
  210. state = None,
  211. reseller = None,
  212. shipper = None,
  213. **kwargs
  214. ):
  215. super(Article, self).__init__(**kwargs)
  216. assert type(quantity) is int
  217. self.quantity = quantity
  218. assert type(authors) is list
  219. self.authors = authors
  220. assert state is None or type(state) is unicode
  221. self.state = state
  222. assert reseller is None or type(reseller) is unicode
  223. self.reseller = reseller
  224. assert shipper is None or type(shipper) is unicode
  225. self.shipper = shipper
  226. self.delivery_date = None
  227. def dict_repr(self):
  228. attr = super(Article, self).dict_repr()
  229. attr.update({
  230. 'delivery_date': self.delivery_date,
  231. 'quantity': self.quantity,
  232. 'reseller': self.reseller,
  233. 'shipper': self.shipper,
  234. 'state': self.state,
  235. })
  236. if len(self.authors) > 0:
  237. attr['authors'] = self.authors
  238. return attr
  239. yaml.SafeDumper.add_representer(Article, lambda dumper, article: dumper.represent_dict(article.dict_repr()))
  240. class Transportation(Item):
  241. def __init__(
  242. self,
  243. departure_point = None,
  244. destination_point = None,
  245. distance = None,
  246. route_map = None,
  247. **kwargs
  248. ):
  249. super(Transportation, self).__init__(**kwargs)
  250. assert type(departure_point) is unicode
  251. self.departure_point = departure_point
  252. assert type(destination_point) is unicode
  253. self.destination_point = destination_point
  254. assert distance is None or type(distance) is Distance
  255. self.distance = distance
  256. assert route_map is None or type(route_map) is str
  257. self.route_map = route_map
  258. def dict_repr(self):
  259. attr = super(Transportation, self).dict_repr()
  260. attr.update({
  261. 'departure_point': self.departure_point,
  262. 'destination_point': self.destination_point,
  263. 'distance_metres': self.distance.metres if self.distance else None,
  264. 'route_map': self.route_map,
  265. })
  266. return attr
  267. yaml.SafeDumper.add_representer(Transportation, lambda dumper, transportation: dumper.represent_dict(transportation.dict_repr()))
  268. class TaxiRide(Transportation):
  269. def __init__(self, name = None, driver = None, arrival_time = None, departure_time = None, **kwargs):
  270. if name is None:
  271. name = u'Taxi Ride'
  272. super(TaxiRide, self).__init__(name = name, **kwargs)
  273. assert type(driver) is unicode
  274. self.driver = driver
  275. assert arrival_time is None or type(arrival_time) is datetime.datetime
  276. self.arrival_time = arrival_time
  277. assert departure_time is None or type(departure_time) is datetime.datetime
  278. self.departure_time = departure_time
  279. def dict_repr(self):
  280. attr = super(TaxiRide, self).dict_repr()
  281. attr.update({
  282. 'arrival_time': self.arrival_time.strftime('%Y-%m-%d %H:%M') if self.arrival_time else None,
  283. 'departure_time': self.departure_time.strftime('%Y-%m-%d %H:%M') if self.departure_time else None,
  284. 'driver': self.driver,
  285. })
  286. return attr
  287. yaml.SafeDumper.add_representer(TaxiRide, lambda dumper, taxi_ride: dumper.represent_dict(taxi_ride.dict_repr()))