__init__.py 16 KB

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