__init__.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  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. assert not end.tzinfo is None, '%r' % end
  212. self.end = end
  213. if not website_url is None:
  214. assert type(website_url) is str
  215. self.website_url = website_url
  216. class Pledge(Item):
  217. yaml_tag = u'!pledge'
  218. def __init__(self,
  219. campaign=None,
  220. reward=None,
  221. **kwargs
  222. ):
  223. super(Pledge, self).__init__(**kwargs)
  224. assert type(campaign) is Campaign
  225. self.campaign = campaign
  226. if not reward is None:
  227. assert type(reward) is str
  228. self.reward = reward
  229. class Contribution(Item):
  230. yaml_tag = u'!contribution'
  231. def __init__(self,
  232. campaign=None,
  233. reward=None,
  234. **kwargs
  235. ):
  236. super(Contribution, self).__init__(**kwargs)
  237. assert type(campaign) is Campaign
  238. self.campaign = campaign
  239. if not reward is None:
  240. assert type(reward) is str
  241. self.reward = reward
  242. class Article(Item):
  243. yaml_tag = u'!article'
  244. def __init__(self,
  245. authors=None,
  246. color=None,
  247. delivery_date=None,
  248. depth=None,
  249. features=None,
  250. height=None,
  251. maximum_load=None,
  252. option=None,
  253. product_id=None,
  254. quantity=None,
  255. reseller=None,
  256. shipper=None,
  257. size=None,
  258. state=None,
  259. width=None,
  260. **kwargs
  261. ):
  262. super(Article, self).__init__(**kwargs)
  263. assert not self.name is None
  264. assert type(quantity) is int
  265. self.quantity = quantity
  266. if authors is not None:
  267. assert type(authors) is list
  268. self.authors = authors
  269. if state is not None:
  270. assert type(state) is str
  271. self.state = state
  272. if reseller is not None:
  273. assert type(reseller) is str
  274. self.reseller = reseller
  275. if shipper is not None:
  276. assert type(shipper) is str
  277. self.shipper = shipper
  278. if product_id is not None:
  279. if type(product_id) in [int]:
  280. product_id = str(product_id)
  281. assert type(product_id) is str
  282. self.product_id = product_id
  283. if option is not None:
  284. assert type(option) is str
  285. self.option = option
  286. if color is not None:
  287. assert type(color) is str
  288. self.color = color
  289. if size is not None:
  290. assert type(size) is str
  291. self.size = size
  292. if width is not None:
  293. assert type(width) is Distance
  294. self.width = width
  295. if depth is not None:
  296. assert type(depth) is Distance
  297. self.depth = depth
  298. if height is not None:
  299. assert type(height) is Distance
  300. self.height = height
  301. if maximum_load is not None:
  302. assert type(maximum_load) is ioex.calcex.Figure, type(maximum_load)
  303. self.maximum_load = maximum_load
  304. if features is not None:
  305. assert type(features) is str
  306. self.features = features
  307. if delivery_date is not None:
  308. assert type(delivery_date) is datetime.date
  309. self.delivery_date = delivery_date
  310. class Service(Item):
  311. yaml_tag = u'!service'
  312. def __init__(self,
  313. duration=None,
  314. ip_addresses=None,
  315. location=None,
  316. period=None,
  317. state=None,
  318. **kwargs
  319. ):
  320. super(Service, self).__init__(**kwargs)
  321. assert not (duration and period)
  322. if duration:
  323. assert isinstance(duration, ioex.datetimeex.Duration)
  324. self.duration = duration
  325. if ip_addresses:
  326. assert isinstance(ip_addresses, list)
  327. assert all([isinstance(a, str) for a in ip_addresses])
  328. self.ip_addresses = ip_addresses
  329. if location:
  330. assert isinstance(location, str)
  331. self.location = location
  332. if period:
  333. assert isinstance(period, ioex.datetimeex.Period)
  334. self.period = period
  335. if state:
  336. assert isinstance(state, str)
  337. self.state = state
  338. class HostingService(Service):
  339. yaml_tag = u'!hosting-service'
  340. def __init__(self,
  341. operating_system=None,
  342. **kwargs
  343. ):
  344. super(HostingService, self).__init__(**kwargs)
  345. if operating_system:
  346. assert isinstance(operating_system, str)
  347. self.operating_system = operating_system
  348. class CloudMining(Service):
  349. yaml_tag = u'!cloud-mining'
  350. def __init__(self,
  351. hashrate=None,
  352. **kwargs
  353. ):
  354. super(CloudMining, self).__init__(**kwargs)
  355. if hashrate:
  356. assert isinstance(hashrate, ioex.calcex.Figure)
  357. self.hashrate = hashrate
  358. class Transportation(Item):
  359. yaml_tag = u'!transportation'
  360. def __init__(self,
  361. departure_point=None,
  362. destination_point=None,
  363. distance=None,
  364. estimated_arrival_time=None,
  365. passenger=None,
  366. route_map=None,
  367. ticket_url=None,
  368. valid_from=None,
  369. valid_until=None,
  370. **kwargs
  371. ):
  372. super(Transportation, self).__init__(**kwargs)
  373. if departure_point is not None:
  374. assert type(departure_point) is str
  375. self.departure_point = departure_point
  376. if destination_point is not None:
  377. assert type(destination_point) is str
  378. self.destination_point = destination_point
  379. if distance is not None:
  380. assert type(distance) is Distance
  381. self.distance = distance
  382. if route_map is not None:
  383. assert type(route_map) is bytes
  384. self.route_map = route_map
  385. if passenger is not None:
  386. assert type(passenger) is Person
  387. self.passenger = passenger
  388. if valid_from is not None:
  389. assert type(valid_from) is datetime.datetime
  390. assert not valid_from.tzinfo is None
  391. self.valid_from = valid_from
  392. if valid_until is not None:
  393. assert type(valid_until) is datetime.datetime
  394. assert not valid_until.tzinfo is None
  395. self.valid_until = valid_until
  396. if ticket_url is not None:
  397. assert type(ticket_url) is str
  398. self.ticket_url = ticket_url
  399. if estimated_arrival_time is not None:
  400. assert type(estimated_arrival_time) is ioex.datetimeex.Period
  401. assert not estimated_arrival_time.start.tzinfo is None
  402. assert not estimated_arrival_time.end.tzinfo is None
  403. self.estimated_arrival_time = estimated_arrival_time
  404. class Shipping(Transportation):
  405. yaml_tag = u'!shipping'
  406. def __init__(self,
  407. tracking_number=None,
  408. **kwargs
  409. ):
  410. super(Shipping, self).__init__(**kwargs)
  411. if tracking_number:
  412. assert isinstance(tracking_number, str)
  413. self.tracking_number = tracking_number
  414. class TaxiRide(Transportation):
  415. yaml_tag = u'!taxi-ride'
  416. def __init__(self,
  417. arrival_time=None,
  418. departure_time=None,
  419. driver=None,
  420. name=None,
  421. **kwargs
  422. ):
  423. if name is None:
  424. name = u'Taxi Ride'
  425. super(TaxiRide, self).__init__(name=name, **kwargs)
  426. assert type(driver) is str
  427. self.driver = driver
  428. assert arrival_time is None or type(arrival_time) is datetime.datetime
  429. self.arrival_time = arrival_time
  430. assert departure_time is None or type(
  431. departure_time) is datetime.datetime
  432. self.departure_time = departure_time
  433. class Person(_Object, _YamlInitConstructor):
  434. yaml_tag = u'!person'
  435. def __init__(self, first_name=None, last_name=None):
  436. self.first_name = first_name
  437. self.last_name = last_name
  438. @property
  439. def first_name(self):
  440. return self._first_name
  441. @first_name.setter
  442. def first_name(self, first_name):
  443. assert first_name is None or type(first_name) is str
  444. self._first_name = first_name
  445. @property
  446. def last_name(self):
  447. return self._last_name
  448. @last_name.setter
  449. def last_name(self, last_name):
  450. assert last_name is None or type(last_name) is str
  451. self._last_name = last_name
  452. @classmethod
  453. def to_yaml(cls, dumper, person):
  454. return dumper.represent_mapping(cls.yaml_tag, {
  455. 'first_name': person.first_name,
  456. 'last_name': person.last_name,
  457. })
  458. def __repr__(self):
  459. return self.__class__.__name__ + '(%s)' % ', '.join([
  460. '%s=%r' % (k, v) for k, v in vars(self).items()
  461. ])