__init__.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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. def __init__(
  90. self,
  91. name = None,
  92. amount = None,
  93. ):
  94. assert type(name) is unicode
  95. self.name = name
  96. assert type(amount) is Sum
  97. assert amount.value >= 0
  98. self.amount = amount
  99. def dict_repr(self):
  100. return {
  101. 'name': self.name,
  102. 'value': self.amount.value,
  103. 'value_currency': self.amount.currency,
  104. }
  105. @staticmethod
  106. def from_dict(attr):
  107. return Discount(
  108. name = attr['name'],
  109. amount = Sum(attr['value'], attr['value_currency']),
  110. )
  111. def __eq__(self, other):
  112. return type(self) == type(other) and self.name == other.name and self.amount == other.amount
  113. def __ne__(self, other):
  114. return not (self == other)
  115. yaml.SafeDumper.add_representer(Discount, lambda dumper, discount: dumper.represent_dict(discount.dict_repr()))
  116. class Order(_YamlUnicodeConstruct):
  117. yaml_tag = u'!order'
  118. def __init__(self, platform, order_id, order_date,
  119. customer_id = None,
  120. items = None,
  121. discounts = None,
  122. ):
  123. assert type(platform) is unicode
  124. self.platform = platform
  125. assert type(order_id) is unicode
  126. self.order_id = order_id
  127. if type(order_date) is datetime.datetime:
  128. order_date = order_date.date()
  129. assert type(order_date) is datetime.date
  130. self.order_date = order_date
  131. assert customer_id is None or type(customer_id) is unicode
  132. self.customer_id = customer_id
  133. if items is None:
  134. items = []
  135. assert type(items) is list
  136. self.items = items
  137. if discounts is None:
  138. discounts = []
  139. assert type(discounts) is list
  140. self.discounts = discounts
  141. def dict_repr(self):
  142. return {k: v for (k, v) in {
  143. 'articles': self.items,
  144. 'customer_id': self.customer_id,
  145. 'discounts': self.discounts,
  146. 'order_date': self.order_date.strftime('%Y-%m-%d'),
  147. 'order_id': self.order_id,
  148. 'platform': self.platform,
  149. }.items() if v is not None}
  150. @staticmethod
  151. def from_dict(attr):
  152. order = Order(
  153. platform = attr['platform'],
  154. order_id = attr['order_id'],
  155. order_date = datetime.datetime.strptime(attr['order_date'], '%Y-%m-%d'),
  156. )
  157. if 'customer_id' in attr:
  158. order.customer_id = attr['customer_id']
  159. for item in attr['articles']:
  160. if type(item) is dict:
  161. item = Item.from_dict(item)
  162. assert isinstance(item, Item)
  163. order.items.append(item)
  164. for discount in attr['discounts']:
  165. if type(discount) is dict:
  166. discount = Discount.from_dict(discount)
  167. assert isinstance(discount, Discount)
  168. order.discounts.append(discount)
  169. return order
  170. def __eq__(self, other):
  171. return (type(self) == type(other)
  172. and vars(self) == vars(other))
  173. def __ne__(self, other):
  174. return not (self == other)
  175. yaml.SafeDumper.add_representer(Order, lambda dumper, order: dumper.represent_dict(order.dict_repr()))
  176. class Item(_YamlUnicodeConstruct):
  177. yaml_tag = u'!item'
  178. def __init__(
  179. self,
  180. name = None,
  181. price_brutto = None,
  182. ):
  183. assert type(name) is unicode
  184. self.name = name
  185. assert type(price_brutto) is Sum
  186. self.price_brutto = price_brutto
  187. def dict_repr(self):
  188. return {
  189. 'name': self.name,
  190. 'price_brutto': self.price_brutto.value,
  191. 'price_brutto_currency': self.price_brutto.currency,
  192. }
  193. @staticmethod
  194. def from_dict(attr):
  195. return Item(
  196. name = attr['name'],
  197. price_brutto = Sum(attr['price_brutto'], attr['price_brutto_currency']),
  198. )
  199. def __eq__(self, other):
  200. return type(self) == type(other) and self.name == other.name and self.price_brutto == other.price_brutto
  201. def __ne__(self, other):
  202. return not (self == other)
  203. yaml.SafeDumper.add_representer(Item, lambda dumper, item: dumper.represent_dict(item.dict_repr()))
  204. class Article(Item):
  205. def __init__(
  206. self,
  207. quantity = None,
  208. authors = [],
  209. state = None,
  210. reseller = None,
  211. shipper = None,
  212. **kwargs
  213. ):
  214. super(Article, self).__init__(**kwargs)
  215. assert type(quantity) is int
  216. self.quantity = quantity
  217. assert type(authors) is list
  218. self.authors = authors
  219. assert state is None or type(state) is unicode
  220. self.state = state
  221. assert reseller is None or type(reseller) is unicode
  222. self.reseller = reseller
  223. assert shipper is None or type(shipper) is unicode
  224. self.shipper = shipper
  225. self.delivery_date = None
  226. def dict_repr(self):
  227. attr = super(Article, self).dict_repr()
  228. attr.update({
  229. 'delivery_date': self.delivery_date,
  230. 'quantity': self.quantity,
  231. 'reseller': self.reseller,
  232. 'shipper': self.shipper,
  233. 'state': self.state,
  234. })
  235. if len(self.authors) > 0:
  236. attr['authors'] = self.authors
  237. return attr
  238. yaml.SafeDumper.add_representer(Article, lambda dumper, article: dumper.represent_dict(article.dict_repr()))
  239. class Transportation(Item):
  240. def __init__(
  241. self,
  242. departure_point = None,
  243. destination_point = None,
  244. distance = None,
  245. route_map = None,
  246. **kwargs
  247. ):
  248. super(Transportation, self).__init__(**kwargs)
  249. assert type(departure_point) is unicode
  250. self.departure_point = departure_point
  251. assert type(destination_point) is unicode
  252. self.destination_point = destination_point
  253. assert distance is None or type(distance) is Distance
  254. self.distance = distance
  255. assert route_map is None or type(route_map) is str
  256. self.route_map = route_map
  257. def dict_repr(self):
  258. attr = super(Transportation, self).dict_repr()
  259. attr.update({
  260. 'departure_point': self.departure_point,
  261. 'destination_point': self.destination_point,
  262. 'distance_metres': self.distance.metres if self.distance else None,
  263. 'route_map': self.route_map,
  264. })
  265. return attr
  266. yaml.SafeDumper.add_representer(Transportation, lambda dumper, transportation: dumper.represent_dict(transportation.dict_repr()))
  267. class TaxiRide(Transportation):
  268. def __init__(self, name = None, driver = None, arrival_time = None, departure_time = None, **kwargs):
  269. if name is None:
  270. name = u'Taxi Ride'
  271. super(TaxiRide, self).__init__(name = name, **kwargs)
  272. assert type(driver) is unicode
  273. self.driver = driver
  274. assert arrival_time is None or type(arrival_time) is datetime.datetime
  275. self.arrival_time = arrival_time
  276. assert departure_time is None or type(departure_time) is datetime.datetime
  277. self.departure_time = departure_time
  278. def dict_repr(self):
  279. attr = super(TaxiRide, self).dict_repr()
  280. attr.update({
  281. 'arrival_time': self.arrival_time.strftime('%Y-%m-%d %H:%M') if self.arrival_time else None,
  282. 'departure_time': self.departure_time.strftime('%Y-%m-%d %H:%M') if self.departure_time else None,
  283. 'driver': self.driver,
  284. })
  285. return attr
  286. yaml.SafeDumper.add_representer(TaxiRide, lambda dumper, taxi_ride: dumper.represent_dict(taxi_ride.dict_repr()))