__init__.py 17 KB

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