__init__.py 18 KB

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