__init__.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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. yaml.Loader.add_constructor(
  7. u'tag:yaml.org,2002:str',
  8. lambda loader, node: unicode(loader.construct_scalar(node)),
  9. )
  10. class _YamlInitConstructor(yaml.YAMLObject):
  11. @classmethod
  12. def from_yaml(cls, loader, node):
  13. return cls(**loader.construct_mapping(node, deep = True))
  14. # return cls(**{
  15. # k: unicode(v) if isinstance(v, str) else v
  16. # for (k, v) in loader.construct_mapping(node, deep = True).items()
  17. # })
  18. class Figure(_YamlInitConstructor):
  19. yaml_tag = u"!figure"
  20. def __init__(self, value, unit):
  21. self.value = value
  22. self.unit = unit
  23. def get_value(self):
  24. return self._value
  25. def set_value(self, value):
  26. self._value = value
  27. """ use property() instead of decorator to enable overriding """
  28. value = property(get_value, set_value)
  29. def get_unit(self):
  30. return self._unit
  31. def set_unit(self, unit):
  32. assert type(unit) is unicode
  33. self._unit = unit
  34. """ use property() instead of decorator to enable overriding """
  35. unit = property(get_unit, set_unit)
  36. def __eq__(self, other):
  37. return type(self) == type(other) and self.value == other.value and self.unit == other.unit
  38. def __ne__(self, other):
  39. return not (self == other)
  40. @classmethod
  41. def to_yaml(cls, dumper, figure):
  42. return dumper.represent_mapping(
  43. cls.yaml_tag,
  44. {'unit': figure.get_unit(), 'value': figure.get_value()},
  45. )
  46. class ScalarFigure(Figure):
  47. yaml_tag = u'!scalar'
  48. def get_value(self):
  49. return super(ScalarFigure, self).get_value()
  50. def set_value(self, value):
  51. assert type(value) is float
  52. super(ScalarFigure, self).set_value(value)
  53. """ use property() instead of decorator to enable overriding """
  54. value = property(get_value, set_value)
  55. @classmethod
  56. def from_yaml(cls, loader, node):
  57. attr = loader.construct_scalar(node).split(' ')
  58. return cls(
  59. value = float(attr[0]),
  60. unit = attr[1],
  61. )
  62. @classmethod
  63. def to_yaml(cls, dumper, s):
  64. return dumper.represent_scalar(
  65. cls.yaml_tag,
  66. '%s %s' % (repr(s.value), s.unit),
  67. )
  68. class Distance(ScalarFigure):
  69. yaml_tag = u'!distance'
  70. @property
  71. def metres(self):
  72. if self.unit == 'km':
  73. return self.value * 1000
  74. else:
  75. raise Exception()
  76. class Sum(ScalarFigure):
  77. yaml_tag = u'!sum'
  78. def __init__(self, value, currency):
  79. super(Sum, self).__init__(value, currency)
  80. @property
  81. def currency(self):
  82. return self.unit
  83. def get_unit(self):
  84. return super(Sum, self).get_unit()
  85. def set_unit(self, currency):
  86. if currency == u'€':
  87. currency = u'EUR'
  88. if currency == u'US$':
  89. currency = u'USD'
  90. assert type(currency) is unicode
  91. assert currency in [u'EUR', u'USD']
  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. value = float(attr[0]),
  100. currency = attr[1],
  101. )
  102. class Discount(yaml.YAMLObject):
  103. yaml_tag = u'!discount'
  104. def __init__(
  105. self,
  106. name = None,
  107. amount = None,
  108. ):
  109. assert type(name) is unicode
  110. self.name = name
  111. assert type(amount) is Sum
  112. assert amount.value >= 0
  113. self.amount = amount
  114. def dict_repr(self):
  115. return {
  116. 'name': self.name,
  117. 'value': self.amount.value,
  118. 'value_currency': self.amount.currency,
  119. }
  120. @staticmethod
  121. def from_dict(attr):
  122. return Discount(
  123. name = attr['name'],
  124. amount = Sum(attr['value'], attr['value_currency']),
  125. )
  126. def __eq__(self, other):
  127. return (type(self) == type(other)
  128. and vars(self) == vars(other))
  129. def __ne__(self, other):
  130. return not (self == other)
  131. yaml.SafeDumper.add_representer(Discount, lambda dumper, discount: dumper.represent_dict(discount.dict_repr()))
  132. class Order(_YamlInitConstructor):
  133. yaml_tag = u'!order'
  134. def __init__(self, platform, order_id, order_date,
  135. customer_id = None,
  136. items = None,
  137. discounts = None,
  138. ):
  139. assert type(platform) is unicode
  140. self.platform = platform
  141. if type(order_id) in [int]:
  142. order_id = unicode(order_id)
  143. assert type(order_id) is unicode
  144. self.order_id = order_id
  145. if type(order_date) is datetime.datetime:
  146. order_date = order_date.date()
  147. assert type(order_date) is datetime.date
  148. self.order_date = order_date
  149. assert customer_id is None or type(customer_id) is unicode
  150. self.customer_id = customer_id
  151. if items is None:
  152. items = []
  153. assert type(items) is list
  154. self.items = items
  155. if discounts is None:
  156. discounts = []
  157. assert type(discounts) is list
  158. self.discounts = discounts
  159. def dict_repr(self):
  160. return {k: v for (k, v) in {
  161. 'articles': self.items,
  162. 'customer_id': self.customer_id,
  163. 'discounts': self.discounts,
  164. 'order_date': self.order_date.strftime('%Y-%m-%d'),
  165. 'order_id': self.order_id,
  166. 'platform': self.platform,
  167. }.items() if v is not None}
  168. @staticmethod
  169. def from_dict(attr):
  170. order = Order(
  171. platform = attr['platform'],
  172. order_id = attr['order_id'],
  173. order_date = datetime.datetime.strptime(attr['order_date'], '%Y-%m-%d'),
  174. )
  175. if 'customer_id' in attr:
  176. order.customer_id = attr['customer_id']
  177. for item in attr['articles']:
  178. if type(item) is dict:
  179. item = Item.from_dict(item)
  180. assert isinstance(item, Item)
  181. order.items.append(item)
  182. for discount in attr['discounts']:
  183. if type(discount) is dict:
  184. discount = Discount.from_dict(discount)
  185. assert isinstance(discount, Discount)
  186. order.discounts.append(discount)
  187. return order
  188. def __eq__(self, other):
  189. return (type(self) == type(other)
  190. and vars(self) == vars(other))
  191. def __ne__(self, other):
  192. return not (self == other)
  193. yaml.SafeDumper.add_representer(Order, lambda dumper, order: dumper.represent_dict(order.dict_repr()))
  194. class Item(_YamlInitConstructor):
  195. yaml_tag = u'!item'
  196. def __init__(
  197. self,
  198. name = None,
  199. price_brutto = None,
  200. ):
  201. assert type(name) is unicode
  202. self.name = name
  203. assert type(price_brutto) is Sum
  204. self.price_brutto = price_brutto
  205. def dict_repr(self):
  206. return {
  207. 'name': self.name,
  208. 'price_brutto': self.price_brutto.value,
  209. 'price_brutto_currency': self.price_brutto.currency,
  210. }
  211. @staticmethod
  212. def from_dict(attr):
  213. return Item(
  214. name = attr['name'],
  215. price_brutto = Sum(attr['price_brutto'], attr['price_brutto_currency']),
  216. )
  217. def __eq__(self, other):
  218. return (type(self) == type(other)
  219. and vars(self) == vars(other))
  220. def __ne__(self, other):
  221. return not (self == other)
  222. yaml.SafeDumper.add_representer(Item, lambda dumper, item: dumper.represent_dict(item.dict_repr()))
  223. class Article(Item):
  224. yaml_tag = u'!article'
  225. def __init__(
  226. self,
  227. authors = None,
  228. delivery_date = None,
  229. option = None,
  230. product_id = None,
  231. quantity = None,
  232. reseller = None,
  233. shipper = None,
  234. state = None,
  235. **kwargs
  236. ):
  237. super(Article, self).__init__(**kwargs)
  238. assert type(quantity) is int
  239. self.quantity = quantity
  240. if authors is not None:
  241. assert type(authors) is list
  242. self.authors = authors
  243. if state is not None:
  244. assert type(state) is unicode
  245. self.state = state
  246. if reseller is not None:
  247. assert type(reseller) is unicode
  248. self.reseller = reseller
  249. if shipper is not None:
  250. assert type(shipper) is unicode
  251. self.shipper = shipper
  252. if product_id is not None:
  253. if type(product_id) in [int]:
  254. product_id = unicode(product_id)
  255. assert type(product_id) is unicode
  256. self.product_id = product_id
  257. if option is not None:
  258. assert type(option) is unicode
  259. self.option = option
  260. assert delivery_date is None or type(delivery_date) is datetime.date
  261. self.delivery_date = delivery_date
  262. def dict_repr(self):
  263. attr = super(Article, self).dict_repr()
  264. attr.update({
  265. 'delivery_date': self.delivery_date,
  266. 'quantity': self.quantity,
  267. 'reseller': self.reseller if hasattr(self, 'reseller') else None,
  268. 'shipper': self.shipper if hasattr(self, 'shipper') else None,
  269. 'state': self.state if hasattr(self, 'state') else None,
  270. })
  271. if hasattr(self, 'authors') and len(self.authors) > 0:
  272. attr['authors'] = self.authors
  273. return attr
  274. yaml.SafeDumper.add_representer(Article, lambda dumper, article: dumper.represent_dict(article.dict_repr()))
  275. class Transportation(Item):
  276. yaml_tag = u'!transportation'
  277. def __init__(
  278. self,
  279. departure_point = None,
  280. destination_point = None,
  281. distance = None,
  282. route_map = None,
  283. **kwargs
  284. ):
  285. super(Transportation, self).__init__(**kwargs)
  286. assert type(departure_point) is unicode
  287. self.departure_point = departure_point
  288. assert type(destination_point) is unicode
  289. self.destination_point = destination_point
  290. assert distance is None or type(distance) is Distance
  291. self.distance = distance
  292. assert route_map is None or type(route_map) is str
  293. self.route_map = route_map
  294. def dict_repr(self):
  295. attr = super(Transportation, self).dict_repr()
  296. attr.update({
  297. 'departure_point': self.departure_point,
  298. 'destination_point': self.destination_point,
  299. 'distance_metres': self.distance.metres if self.distance else None,
  300. 'route_map': self.route_map,
  301. })
  302. return attr
  303. yaml.SafeDumper.add_representer(Transportation, lambda dumper, transportation: dumper.represent_dict(transportation.dict_repr()))
  304. class TaxiRide(Transportation):
  305. yaml_tag = u'!taxi-ride'
  306. def __init__(
  307. self,
  308. arrival_time = None,
  309. departure_time = None,
  310. driver = None,
  311. name = None,
  312. **kwargs
  313. ):
  314. if name is None:
  315. name = u'Taxi Ride'
  316. super(TaxiRide, self).__init__(name = name, **kwargs)
  317. assert type(driver) is unicode
  318. self.driver = driver
  319. assert arrival_time is None or type(arrival_time) is datetime.datetime
  320. self.arrival_time = arrival_time
  321. assert departure_time is None or type(departure_time) is datetime.datetime
  322. self.departure_time = departure_time
  323. def dict_repr(self):
  324. attr = super(TaxiRide, self).dict_repr()
  325. attr.update({
  326. 'arrival_time': self.arrival_time.strftime('%Y-%m-%d %H:%M') if self.arrival_time else None,
  327. 'departure_time': self.departure_time.strftime('%Y-%m-%d %H:%M') if self.departure_time else None,
  328. 'driver': self.driver,
  329. })
  330. return attr
  331. yaml.SafeDumper.add_representer(TaxiRide, lambda dumper, taxi_ride: dumper.represent_dict(taxi_ride.dict_repr()))
  332. class OrderRegistry(yaml.YAMLObject):
  333. yaml_tag = u'!order-registry'
  334. def __init__(self):
  335. self.registry = {}
  336. def register(self, order):
  337. assert isinstance(order, Order)
  338. if not order.platform in self.registry:
  339. self.registry[order.platform] = {}
  340. self.registry[order.platform][order.order_id] = order
  341. @classmethod
  342. def to_yaml(cls, dumper, self):
  343. return dumper.represent_mapping(cls.yaml_tag, self.registry)
  344. @classmethod
  345. def from_yaml(cls, loader, node):
  346. self = cls()
  347. self.registry = loader.construct_mapping(node)
  348. return self
  349. def __eq__(self, other):
  350. return type(self) == type(other) and vars(self) == vars(other)
  351. def __ne__(self, other):
  352. return not self == other