__init__.py 16 KB

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