__init__.py 17 KB

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