__init__.py 16 KB

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