1
0

__init__.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. # -*- coding: utf-8 -*-
  2. import copy
  3. import datetime
  4. import ioex.datetimeex
  5. import pytz
  6. import re
  7. import yaml
  8. import yaml.representer
  9. yaml.Dumper.add_representer(unicode, yaml.representer.SafeRepresenter.represent_unicode)
  10. yaml.Loader.add_constructor(
  11. u'tag:yaml.org,2002:str',
  12. lambda loader, node: unicode(loader.construct_scalar(node)),
  13. )
  14. ioex.datetimeex.register_yaml_timestamp_constructor(yaml.Loader)
  15. ioex.datetimeex.Duration.register_yaml_constructor(yaml.Loader)
  16. ioex.datetimeex.Duration.register_yaml_representer(yaml.Dumper)
  17. ioex.datetimeex.Period.register_yaml_constructor(yaml.Loader)
  18. ioex.datetimeex.Period.register_yaml_representer(yaml.Dumper)
  19. class _Object(object):
  20. def __eq__(self, other):
  21. return type(self) == type(other) and vars(self) == vars(other)
  22. def __ne__(self, other):
  23. return not (self == other)
  24. class _YamlInitConstructor(_Object, yaml.YAMLObject):
  25. @classmethod
  26. def from_yaml(cls, loader, node):
  27. return cls(**loader.construct_mapping(node, deep = True))
  28. # return cls(**{
  29. # k: unicode(v) if isinstance(v, str) else v
  30. # for (k, v) in loader.construct_mapping(node, deep = True).items()
  31. # })
  32. def __eq__(self, other):
  33. return (type(self) == type(other)
  34. and vars(self) == vars(other))
  35. def __ne__(self, other):
  36. return not (self == other)
  37. class Figure(_YamlInitConstructor):
  38. yaml_tag = u"!figure"
  39. def __init__(self, value, unit):
  40. self.value = value
  41. self.unit = unit
  42. def get_value(self):
  43. return self._value
  44. def set_value(self, value):
  45. self._value = value
  46. """ use property() instead of decorator to enable overriding """
  47. value = property(get_value, set_value)
  48. def get_unit(self):
  49. return self._unit
  50. def set_unit(self, unit):
  51. assert type(unit) is unicode
  52. self._unit = unit
  53. """ use property() instead of decorator to enable overriding """
  54. unit = property(get_unit, set_unit)
  55. @classmethod
  56. def to_yaml(cls, dumper, figure):
  57. return dumper.represent_mapping(
  58. cls.yaml_tag,
  59. {'unit': figure.get_unit(), 'value': figure.get_value()},
  60. )
  61. def __sub__(self, other):
  62. assert type(self) == type(other)
  63. assert self.unit == other.unit
  64. result = copy.deepcopy(self)
  65. result.value -= other.value
  66. return result
  67. class ScalarFigure(Figure):
  68. yaml_tag = u'!scalar'
  69. def get_value(self):
  70. return super(ScalarFigure, self).get_value()
  71. def set_value(self, value):
  72. assert type(value) is float
  73. super(ScalarFigure, self).set_value(value)
  74. """ use property() instead of decorator to enable overriding """
  75. value = property(get_value, set_value)
  76. @classmethod
  77. def from_yaml(cls, loader, node):
  78. attr = loader.construct_scalar(node).split(' ')
  79. return cls(
  80. value = float(attr[0]),
  81. unit = attr[1],
  82. )
  83. @classmethod
  84. def to_yaml(cls, dumper, s):
  85. return dumper.represent_scalar(
  86. cls.yaml_tag,
  87. '%s %s' % (repr(s.value), s.unit),
  88. )
  89. class Distance(ScalarFigure):
  90. yaml_tag = u'!distance'
  91. @property
  92. def metres(self):
  93. if self.unit == 'km':
  94. return self.value * 1000
  95. else:
  96. raise Exception()
  97. class Sum(ScalarFigure):
  98. yaml_tag = u'!sum'
  99. def __init__(self, value, currency):
  100. super(Sum, self).__init__(value, currency)
  101. @property
  102. def currency(self):
  103. return self.unit
  104. def get_unit(self):
  105. return super(Sum, self).get_unit()
  106. def set_unit(self, currency):
  107. if currency == u'€':
  108. currency = u'EUR'
  109. if currency == u'US$':
  110. currency = u'USD'
  111. assert type(currency) is unicode
  112. assert currency in [u'EUR', u'USD']
  113. super(Sum, self).set_unit(currency)
  114. """ use property() instead of decorator to enable overriding """
  115. unit = property(get_unit, set_unit)
  116. @classmethod
  117. def from_yaml(cls, loader, node):
  118. attr = loader.construct_scalar(node).split(' ')
  119. return cls(
  120. value = float(attr[0]),
  121. currency = attr[1],
  122. )
  123. @staticmethod
  124. def parse_text(text):
  125. match = re.search(
  126. ur'^(?P<curr_pre>[\$])(?P<value>\d+([\.,]\d{2})?)( (?P<currency>USD))?$',
  127. text,
  128. re.UNICODE,
  129. )
  130. assert not match is None, text
  131. attr = match.groupdict()
  132. currency = attr['currency'] if attr['currency'] else attr['curr_pre']
  133. if currency == u'$':
  134. currency = u'USD'
  135. return Sum(
  136. value = float(attr['value'].replace(',', '.')),
  137. currency = currency,
  138. )
  139. class Discount(_YamlInitConstructor):
  140. yaml_tag = u'!discount'
  141. def __init__(
  142. self,
  143. name = None,
  144. amount = None,
  145. ):
  146. assert type(name) is unicode
  147. self.name = name
  148. assert type(amount) is Sum
  149. assert amount.value >= 0
  150. self.amount = amount
  151. class Order(_YamlInitConstructor):
  152. yaml_tag = u'!order'
  153. def __init__(self, platform, order_id, order_date,
  154. customer_id = None,
  155. items = None,
  156. discounts = None,
  157. ):
  158. assert type(platform) is unicode
  159. self.platform = platform
  160. if type(order_id) in [int]:
  161. order_id = unicode(order_id)
  162. assert type(order_id) is unicode
  163. self.order_id = order_id
  164. assert type(order_date) in [datetime.date, datetime.datetime]
  165. if type(order_date) is datetime.datetime and order_date.tzinfo:
  166. order_date = order_date.astimezone(pytz.utc)
  167. self.order_date = order_date
  168. if customer_id is not None:
  169. assert type(customer_id) is unicode
  170. self.customer_id = customer_id
  171. if items is None:
  172. self.items = []
  173. else:
  174. assert type(items) is list
  175. assert all([isinstance(i, Item) for i in items])
  176. self.items = items
  177. if discounts is None:
  178. self.discounts = []
  179. else:
  180. assert type(discounts) is list
  181. assert all([isinstance(d, Discount) for d in discounts])
  182. self.discounts = discounts
  183. class Item(_YamlInitConstructor):
  184. yaml_tag = u'!item'
  185. def __init__(
  186. self,
  187. name = None,
  188. price_brutto = None,
  189. ):
  190. if not name is None:
  191. assert type(name) is unicode
  192. self.name = name
  193. assert type(price_brutto) is Sum
  194. self.price_brutto = price_brutto
  195. class Campaign(_YamlInitConstructor):
  196. yaml_tag = u'!campaign'
  197. def __init__(self,
  198. end = None,
  199. founder = None,
  200. name = None,
  201. website_url = None,
  202. ):
  203. assert type(name) is unicode
  204. self.name = name
  205. assert type(founder) is unicode
  206. self.founder = founder
  207. if not end is None:
  208. assert type(end) is datetime.datetime
  209. assert not end.tzinfo is None, '%r' % end
  210. self.end = end
  211. if not website_url is None:
  212. assert type(website_url) is unicode
  213. self.website_url = website_url
  214. class Pledge(Item):
  215. yaml_tag = u'!pledge'
  216. def __init__(self,
  217. campaign = None,
  218. reward = None,
  219. **kwargs
  220. ):
  221. super(Pledge, self).__init__(**kwargs)
  222. assert type(campaign) is Campaign
  223. self.campaign = campaign
  224. if not reward is None:
  225. assert type(reward) is unicode
  226. self.reward = reward
  227. class Contribution(Item):
  228. yaml_tag = u'!contribution'
  229. def __init__(self,
  230. campaign = None,
  231. reward = None,
  232. **kwargs
  233. ):
  234. super(Contribution, self).__init__(**kwargs)
  235. assert type(campaign) is Campaign
  236. self.campaign = campaign
  237. if not reward is None:
  238. assert type(reward) is unicode
  239. self.reward = reward
  240. class Article(Item):
  241. yaml_tag = u'!article'
  242. def __init__(
  243. self,
  244. authors = None,
  245. color = None,
  246. delivery_date = None,
  247. depth = None,
  248. features = None,
  249. height = None,
  250. maximum_load = None,
  251. option = None,
  252. product_id = None,
  253. quantity = None,
  254. reseller = None,
  255. shipper = None,
  256. size = None,
  257. state = None,
  258. width = None,
  259. **kwargs
  260. ):
  261. super(Article, self).__init__(**kwargs)
  262. assert not self.name is None
  263. assert type(quantity) is int
  264. self.quantity = quantity
  265. if authors is not None:
  266. assert type(authors) is list
  267. self.authors = authors
  268. if state is not None:
  269. assert type(state) is unicode
  270. self.state = state
  271. if reseller is not None:
  272. assert type(reseller) is unicode
  273. self.reseller = reseller
  274. if shipper is not None:
  275. assert type(shipper) is unicode
  276. self.shipper = shipper
  277. if product_id is not None:
  278. if type(product_id) in [int]:
  279. product_id = unicode(product_id)
  280. assert type(product_id) is unicode
  281. self.product_id = product_id
  282. if option is not None:
  283. assert type(option) is unicode
  284. self.option = option
  285. if color is not None:
  286. assert type(color) is unicode
  287. self.color = color
  288. if size is not None:
  289. assert type(size) is unicode
  290. self.size = size
  291. if width is not None:
  292. assert type(width) is ScalarFigure
  293. self.width = width
  294. if depth is not None:
  295. assert type(depth) is ScalarFigure
  296. self.depth = depth
  297. if height is not None:
  298. assert type(height) is ScalarFigure
  299. self.height = height
  300. if maximum_load is not None:
  301. assert type(maximum_load) is ScalarFigure
  302. self.maximum_load = maximum_load
  303. if features is not None:
  304. assert type(features) is unicode
  305. self.features = features
  306. assert delivery_date is None or type(delivery_date) is datetime.date
  307. self.delivery_date = delivery_date
  308. class Service(Item):
  309. yaml_tag = u'!service'
  310. def __init__(
  311. self,
  312. duration = None,
  313. **kwargs
  314. ):
  315. super(Service, self).__init__(**kwargs)
  316. if duration is not None:
  317. assert type(duration) is ioex.datetimeex.Duration
  318. self.duration = duration
  319. class Transportation(Item):
  320. yaml_tag = u'!transportation'
  321. def __init__(
  322. self,
  323. departure_point = None,
  324. destination_point = None,
  325. distance = None,
  326. estimated_arrival_time = None,
  327. passenger = None,
  328. route_map = None,
  329. ticket_url = None,
  330. valid_from = None,
  331. valid_until = None,
  332. **kwargs
  333. ):
  334. super(Transportation, self).__init__(**kwargs)
  335. if departure_point is not None:
  336. assert type(departure_point) is unicode
  337. self.departure_point = departure_point
  338. if destination_point is not None:
  339. assert type(destination_point) is unicode
  340. self.destination_point = destination_point
  341. if distance is not None:
  342. assert type(distance) is Distance
  343. self.distance = distance
  344. if route_map is not None:
  345. assert type(route_map) is str
  346. self.route_map = route_map
  347. if passenger is not None:
  348. assert type(passenger) is Person
  349. self.passenger = passenger
  350. if valid_from is not None:
  351. assert type(valid_from) is datetime.datetime
  352. assert not valid_from.tzinfo is None
  353. self.valid_from = valid_from
  354. if valid_until is not None:
  355. assert type(valid_until) is datetime.datetime
  356. assert not valid_until.tzinfo is None
  357. self.valid_until = valid_until
  358. if ticket_url is not None:
  359. assert type(ticket_url) is unicode
  360. self.ticket_url = ticket_url
  361. if estimated_arrival_time is not None:
  362. assert type(estimated_arrival_time) is ioex.datetimeex.Period
  363. assert not estimated_arrival_time.start.tzinfo is None
  364. assert not estimated_arrival_time.end.tzinfo is None
  365. self.estimated_arrival_time = estimated_arrival_time
  366. class Shipping(Transportation):
  367. yaml_tag = u'!shipping'
  368. def __init__(
  369. self,
  370. **kwargs
  371. ):
  372. super(Shipping, self).__init__(**kwargs)
  373. class TaxiRide(Transportation):
  374. yaml_tag = u'!taxi-ride'
  375. def __init__(
  376. self,
  377. arrival_time = None,
  378. departure_time = None,
  379. driver = None,
  380. name = None,
  381. **kwargs
  382. ):
  383. if name is None:
  384. name = u'Taxi Ride'
  385. super(TaxiRide, self).__init__(name = name, **kwargs)
  386. assert type(driver) is unicode
  387. self.driver = driver
  388. assert arrival_time is None or type(arrival_time) is datetime.datetime
  389. self.arrival_time = arrival_time
  390. assert departure_time is None or type(departure_time) is datetime.datetime
  391. self.departure_time = departure_time
  392. class OrderRegistry(_Object, yaml.YAMLObject):
  393. yaml_tag = u'!order-registry'
  394. def __init__(self):
  395. self.registry = {}
  396. def register(self, order):
  397. assert isinstance(order, Order)
  398. if not order.platform in self.registry:
  399. self.registry[order.platform] = {}
  400. self.registry[order.platform][order.order_id] = order
  401. @classmethod
  402. def to_yaml(cls, dumper, self):
  403. return dumper.represent_mapping(cls.yaml_tag, self.registry)
  404. @classmethod
  405. def from_yaml(cls, loader, node):
  406. self = cls()
  407. self.registry = loader.construct_mapping(node)
  408. return self
  409. class Person(_YamlInitConstructor):
  410. yaml_tag = u'!person'
  411. def __init__(self, first_name = None, last_name = None):
  412. self.first_name = first_name
  413. self.last_name = last_name
  414. @property
  415. def first_name(self):
  416. return self._first_name
  417. @first_name.setter
  418. def first_name(self, first_name):
  419. assert first_name is None or type(first_name) is unicode
  420. self._first_name = first_name
  421. @property
  422. def last_name(self):
  423. return self._last_name
  424. @last_name.setter
  425. def last_name(self, last_name):
  426. assert last_name is None or type(last_name) is unicode
  427. self._last_name = last_name
  428. @classmethod
  429. def to_yaml(cls, dumper, person):
  430. return dumper.represent_mapping(cls.yaml_tag, {
  431. 'first_name': person.first_name,
  432. 'last_name': person.last_name,
  433. })
  434. def __repr__(self):
  435. return self.__class__.__name__ + '(%s)' % ', '.join([
  436. '%s=%r' % (k, v) for k, v in vars(self).items()
  437. ])