__init__.py 16 KB

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