1
0

__init__.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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. class Order(_YamlInitConstructor):
  132. yaml_tag = u'!order'
  133. def __init__(self, platform, order_id, order_date,
  134. customer_id = None,
  135. items = None,
  136. discounts = None,
  137. ):
  138. assert type(platform) is unicode
  139. self.platform = platform
  140. if type(order_id) in [int]:
  141. order_id = unicode(order_id)
  142. assert type(order_id) is unicode
  143. self.order_id = order_id
  144. if type(order_date) is datetime.datetime:
  145. order_date = order_date.date()
  146. assert type(order_date) is datetime.date
  147. self.order_date = order_date
  148. assert customer_id is None or type(customer_id) is unicode
  149. self.customer_id = customer_id
  150. if items is None:
  151. items = []
  152. assert type(items) is list
  153. self.items = items
  154. if discounts is None:
  155. discounts = []
  156. assert type(discounts) is list
  157. self.discounts = discounts
  158. def dict_repr(self):
  159. return {k: v for (k, v) in {
  160. 'articles': self.items,
  161. 'customer_id': self.customer_id,
  162. 'discounts': self.discounts,
  163. 'order_date': self.order_date.strftime('%Y-%m-%d'),
  164. 'order_id': self.order_id,
  165. 'platform': self.platform,
  166. }.items() if v is not None}
  167. @staticmethod
  168. def from_dict(attr):
  169. order = Order(
  170. platform = attr['platform'],
  171. order_id = attr['order_id'],
  172. order_date = datetime.datetime.strptime(attr['order_date'], '%Y-%m-%d'),
  173. )
  174. if 'customer_id' in attr:
  175. order.customer_id = attr['customer_id']
  176. for item in attr['articles']:
  177. if type(item) is dict:
  178. item = Item.from_dict(item)
  179. assert isinstance(item, Item)
  180. order.items.append(item)
  181. for discount in attr['discounts']:
  182. if type(discount) is dict:
  183. discount = Discount.from_dict(discount)
  184. assert isinstance(discount, Discount)
  185. order.discounts.append(discount)
  186. return order
  187. def __eq__(self, other):
  188. return (type(self) == type(other)
  189. and vars(self) == vars(other))
  190. def __ne__(self, other):
  191. return not (self == other)
  192. class Item(_YamlInitConstructor):
  193. yaml_tag = u'!item'
  194. def __init__(
  195. self,
  196. name = None,
  197. price_brutto = None,
  198. ):
  199. assert type(name) is unicode
  200. self.name = name
  201. assert type(price_brutto) is Sum
  202. self.price_brutto = price_brutto
  203. def dict_repr(self):
  204. return {
  205. 'name': self.name,
  206. 'price_brutto': self.price_brutto.value,
  207. 'price_brutto_currency': self.price_brutto.currency,
  208. }
  209. @staticmethod
  210. def from_dict(attr):
  211. return Item(
  212. name = attr['name'],
  213. price_brutto = Sum(attr['price_brutto'], attr['price_brutto_currency']),
  214. )
  215. def __eq__(self, other):
  216. return (type(self) == type(other)
  217. and vars(self) == vars(other))
  218. def __ne__(self, other):
  219. return not (self == other)
  220. class Article(Item):
  221. yaml_tag = u'!article'
  222. def __init__(
  223. self,
  224. authors = None,
  225. color = None,
  226. delivery_date = None,
  227. option = None,
  228. product_id = None,
  229. quantity = None,
  230. reseller = None,
  231. shipper = None,
  232. size = None,
  233. state = None,
  234. **kwargs
  235. ):
  236. super(Article, self).__init__(**kwargs)
  237. assert type(quantity) is int
  238. self.quantity = quantity
  239. if authors is not None:
  240. assert type(authors) is list
  241. self.authors = authors
  242. if state is not None:
  243. assert type(state) is unicode
  244. self.state = state
  245. if reseller is not None:
  246. assert type(reseller) is unicode
  247. self.reseller = reseller
  248. if shipper is not None:
  249. assert type(shipper) is unicode
  250. self.shipper = shipper
  251. if product_id is not None:
  252. if type(product_id) in [int]:
  253. product_id = unicode(product_id)
  254. assert type(product_id) is unicode
  255. self.product_id = product_id
  256. if option is not None:
  257. assert type(option) is unicode
  258. self.option = option
  259. if color is not None:
  260. assert type(color) is unicode
  261. self.color = color
  262. if size is not None:
  263. assert type(size) is unicode
  264. self.size = size
  265. assert delivery_date is None or type(delivery_date) is datetime.date
  266. self.delivery_date = delivery_date
  267. class Transportation(Item):
  268. yaml_tag = u'!transportation'
  269. def __init__(
  270. self,
  271. departure_point = None,
  272. destination_point = None,
  273. distance = None,
  274. route_map = None,
  275. **kwargs
  276. ):
  277. super(Transportation, self).__init__(**kwargs)
  278. assert type(departure_point) is unicode
  279. self.departure_point = departure_point
  280. assert type(destination_point) is unicode
  281. self.destination_point = destination_point
  282. assert distance is None or type(distance) is Distance
  283. self.distance = distance
  284. assert route_map is None or type(route_map) is str
  285. self.route_map = route_map
  286. def dict_repr(self):
  287. attr = super(Transportation, self).dict_repr()
  288. attr.update({
  289. 'departure_point': self.departure_point,
  290. 'destination_point': self.destination_point,
  291. 'distance_metres': self.distance.metres if self.distance else None,
  292. 'route_map': self.route_map,
  293. })
  294. return attr
  295. class TaxiRide(Transportation):
  296. yaml_tag = u'!taxi-ride'
  297. def __init__(
  298. self,
  299. arrival_time = None,
  300. departure_time = None,
  301. driver = None,
  302. name = None,
  303. **kwargs
  304. ):
  305. if name is None:
  306. name = u'Taxi Ride'
  307. super(TaxiRide, self).__init__(name = name, **kwargs)
  308. assert type(driver) is unicode
  309. self.driver = driver
  310. assert arrival_time is None or type(arrival_time) is datetime.datetime
  311. self.arrival_time = arrival_time
  312. assert departure_time is None or type(departure_time) is datetime.datetime
  313. self.departure_time = departure_time
  314. def dict_repr(self):
  315. attr = super(TaxiRide, self).dict_repr()
  316. attr.update({
  317. 'arrival_time': self.arrival_time.strftime('%Y-%m-%d %H:%M') if self.arrival_time else None,
  318. 'departure_time': self.departure_time.strftime('%Y-%m-%d %H:%M') if self.departure_time else None,
  319. 'driver': self.driver,
  320. })
  321. return attr
  322. class OrderRegistry(yaml.YAMLObject):
  323. yaml_tag = u'!order-registry'
  324. def __init__(self):
  325. self.registry = {}
  326. def register(self, order):
  327. assert isinstance(order, Order)
  328. if not order.platform in self.registry:
  329. self.registry[order.platform] = {}
  330. self.registry[order.platform][order.order_id] = order
  331. @classmethod
  332. def to_yaml(cls, dumper, self):
  333. return dumper.represent_mapping(cls.yaml_tag, self.registry)
  334. @classmethod
  335. def from_yaml(cls, loader, node):
  336. self = cls()
  337. self.registry = loader.construct_mapping(node)
  338. return self
  339. def __eq__(self, other):
  340. return type(self) == type(other) and vars(self) == vars(other)
  341. def __ne__(self, other):
  342. return not self == other