__init__.py 11 KB

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