__init__.py 17 KB

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