__init__.py 15 KB

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