__init__.py 16 KB

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