__init__.py 12 KB

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