__init__.py 16 KB

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