__init__.py 18 KB

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