__init__.py 16 KB

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