__init__.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. import datetime
  2. import ioex.calcex
  3. import locale
  4. import re
  5. import yaml
  6. class _Object(object):
  7. def __eq__(self, other):
  8. return type(self) == type(other) and vars(self) == vars(other)
  9. def __ne__(self, other):
  10. return not (self == other)
  11. class _YamlInitConstructor(yaml.YAMLObject):
  12. @classmethod
  13. def from_yaml(cls, loader, node):
  14. return cls(**loader.construct_mapping(node, deep=True))
  15. # return cls(**{
  16. # k: unicode(v) if isinstance(v, str) else v
  17. # for (k, v) in loader.construct_mapping(node, deep = True).items()
  18. # })
  19. @classmethod
  20. def register_yaml_constructor(cls, loader, tag=None):
  21. loader.add_constructor(
  22. cls.yaml_tag if tag is None else tag,
  23. cls.from_yaml,
  24. )
  25. class Sum(ioex.calcex.Figure):
  26. currency_symbol_map = {
  27. '€': 'EUR',
  28. 'US$': 'USD',
  29. '¥': 'CNY',
  30. }
  31. yaml_tag = u'!sum'
  32. def __init__(self, value=None, currency=None, unit=None):
  33. if not currency is None and not unit is None:
  34. raise ValueError('missing currency')
  35. else:
  36. unit = currency if currency else unit
  37. super(Sum, self).__init__(
  38. value=value,
  39. unit=currency if currency else unit,
  40. )
  41. def get_value(self):
  42. return super(Sum, self).get_value()
  43. def set_value(self, value):
  44. assert type(value) is float
  45. super(Sum, self).set_value(value)
  46. """ use property() instead of decorator to enable overriding """
  47. value = property(get_value, set_value)
  48. def get_unit(self):
  49. return super(Sum, self).get_unit()
  50. def set_unit(self, currency):
  51. currency = Sum.currency_symbol_map.get(currency, currency)
  52. assert type(currency) is str
  53. super(Sum, self).set_unit(currency)
  54. """ use property() instead of decorator to enable overriding """
  55. unit = property(get_unit, set_unit)
  56. currency = property(get_unit, set_unit)
  57. value_regex = r"-?\d+([\.,]\d{2})?"
  58. currency_regex = r"[^\d\s-]+"
  59. @staticmethod
  60. def parse_text(text):
  61. match = re.search(
  62. r'^\$?(?P<value>{}) (?P<curr>{})$'.format(
  63. Sum.value_regex, Sum.currency_regex),
  64. text,
  65. re.UNICODE,
  66. )
  67. if not match:
  68. match = re.search(
  69. r'^(?P<curr>{}) ?(?P<value>{})$'.format(
  70. Sum.currency_regex, Sum.value_regex),
  71. text,
  72. re.UNICODE,
  73. )
  74. assert not match is None, text
  75. attr = match.groupdict()
  76. return Sum(
  77. value=locale.atof(attr['value']),
  78. currency=attr['curr'],
  79. )
  80. class Order(_Object, _YamlInitConstructor):
  81. yaml_tag = u'!order'
  82. def __init__(self, platform, order_id, order_date,
  83. customer_id=None,
  84. items=None,
  85. discounts=None,
  86. ):
  87. assert type(platform) is str
  88. self.platform = platform
  89. if type(order_id) in [int]:
  90. order_id = str(order_id)
  91. assert type(order_id) is str
  92. self.order_id = order_id
  93. assert type(order_date) in [datetime.date, datetime.datetime]
  94. if type(order_date) is datetime.datetime and order_date.tzinfo:
  95. order_date = order_date.astimezone(pytz.utc)
  96. self.order_date = order_date
  97. if customer_id is not None:
  98. assert type(customer_id) is str
  99. self.customer_id = customer_id
  100. if items is None:
  101. self.items = []
  102. else:
  103. assert type(items) is list
  104. assert all([isinstance(i, Item) for i in items])
  105. self.items = items
  106. if discounts is None:
  107. self.discounts = []
  108. else:
  109. assert type(discounts) is list
  110. assert all([isinstance(d, Discount) for d in discounts])
  111. self.discounts = discounts
  112. class Distance(ioex.calcex.Figure):
  113. yaml_tag = u'!distance'
  114. def get_value(self):
  115. return super(Distance, self).get_value()
  116. def set_value(self, value):
  117. assert type(value) is float
  118. super(Distance, self).set_value(value)
  119. """ use property() instead of decorator to enable overriding """
  120. value = property(get_value, set_value)
  121. @property
  122. def metres(self):
  123. if self.unit == 'm':
  124. return Distance(self.value, 'm')
  125. elif self.unit == 'km':
  126. return Distance(self.value * 1000, 'm')
  127. else:
  128. raise Exception()
  129. class Discount(_Object, _YamlInitConstructor):
  130. yaml_tag = u'!discount'
  131. def __init__(self, name=None, amount=None):
  132. assert type(name) is str
  133. self.name = name
  134. assert type(amount) is Sum
  135. assert amount.value >= 0
  136. self.amount = amount
  137. class Item(_Object, _YamlInitConstructor):
  138. yaml_tag = u'!item'
  139. def __init__(self,
  140. name=None,
  141. price_brutto=None,
  142. ):
  143. if not name is None:
  144. assert type(name) is str
  145. self.name = name
  146. assert type(price_brutto) is Sum
  147. self.price_brutto = price_brutto
  148. class Campaign(_Object, _YamlInitConstructor):
  149. yaml_tag = u'!campaign'
  150. def __init__(self,
  151. end=None,
  152. founder=None,
  153. name=None,
  154. website_url=None,
  155. ):
  156. assert type(name) is str
  157. self.name = name
  158. assert type(founder) is str
  159. self.founder = founder
  160. if not end is None:
  161. assert type(end) is datetime.datetime
  162. assert not end.tzinfo is None, '%r' % end
  163. self.end = end
  164. if not website_url is None:
  165. assert type(website_url) is str
  166. self.website_url = website_url
  167. class Pledge(Item):
  168. yaml_tag = u'!pledge'
  169. def __init__(self,
  170. campaign=None,
  171. reward=None,
  172. **kwargs
  173. ):
  174. super(Pledge, self).__init__(**kwargs)
  175. assert type(campaign) is Campaign
  176. self.campaign = campaign
  177. if not reward is None:
  178. assert type(reward) is str
  179. self.reward = reward
  180. class Contribution(Item):
  181. yaml_tag = u'!contribution'
  182. def __init__(self,
  183. campaign=None,
  184. reward=None,
  185. **kwargs
  186. ):
  187. super(Contribution, self).__init__(**kwargs)
  188. assert type(campaign) is Campaign
  189. self.campaign = campaign
  190. if not reward is None:
  191. assert type(reward) is str
  192. self.reward = reward
  193. class Article(Item):
  194. yaml_tag = u'!article'
  195. def __init__(self,
  196. authors=None,
  197. color=None,
  198. delivery_date=None,
  199. depth=None,
  200. features=None,
  201. height=None,
  202. maximum_load=None,
  203. option=None,
  204. product_id=None,
  205. quantity=None,
  206. reseller=None,
  207. shipper=None,
  208. size=None,
  209. state=None,
  210. width=None,
  211. **kwargs
  212. ):
  213. super(Article, self).__init__(**kwargs)
  214. assert not self.name is None
  215. assert type(quantity) is int
  216. self.quantity = quantity
  217. if authors is not None:
  218. assert type(authors) is list
  219. self.authors = authors
  220. if state is not None:
  221. assert type(state) is str
  222. self.state = state
  223. if reseller is not None:
  224. assert type(reseller) is str
  225. self.reseller = reseller
  226. if shipper is not None:
  227. assert type(shipper) is str
  228. self.shipper = shipper
  229. if product_id is not None:
  230. if type(product_id) in [int]:
  231. product_id = str(product_id)
  232. assert type(product_id) is str
  233. self.product_id = product_id
  234. if option is not None:
  235. assert type(option) is str
  236. self.option = option
  237. if color is not None:
  238. assert type(color) is str
  239. self.color = color
  240. if size is not None:
  241. assert type(size) is str
  242. self.size = size
  243. if width is not None:
  244. assert type(width) is Distance
  245. self.width = width
  246. if depth is not None:
  247. assert type(depth) is Distance
  248. self.depth = depth
  249. if height is not None:
  250. assert type(height) is Distance
  251. self.height = height
  252. if maximum_load is not None:
  253. assert type(maximum_load) is ioex.calcex.Figure, type(maximum_load)
  254. self.maximum_load = maximum_load
  255. if features is not None:
  256. assert type(features) is str
  257. self.features = features
  258. assert delivery_date is None or type(delivery_date) is datetime.date
  259. self.delivery_date = delivery_date
  260. class Service(Item):
  261. yaml_tag = u'!service'
  262. def __init__(self,
  263. duration=None,
  264. **kwargs
  265. ):
  266. super(Service, self).__init__(**kwargs)
  267. if duration is not None:
  268. assert type(duration) is ioex.datetimeex.Duration
  269. self.duration = duration
  270. class Transportation(Item):
  271. yaml_tag = u'!transportation'
  272. def __init__(self,
  273. departure_point=None,
  274. destination_point=None,
  275. distance=None,
  276. estimated_arrival_time=None,
  277. passenger=None,
  278. route_map=None,
  279. ticket_url=None,
  280. valid_from=None,
  281. valid_until=None,
  282. **kwargs
  283. ):
  284. super(Transportation, self).__init__(**kwargs)
  285. if departure_point is not None:
  286. assert type(departure_point) is str
  287. self.departure_point = departure_point
  288. if destination_point is not None:
  289. assert type(destination_point) is str
  290. self.destination_point = destination_point
  291. if distance is not None:
  292. assert type(distance) is Distance
  293. self.distance = distance
  294. if route_map is not None:
  295. assert type(route_map) is str
  296. self.route_map = route_map
  297. if passenger is not None:
  298. assert type(passenger) is Person
  299. self.passenger = passenger
  300. if valid_from is not None:
  301. assert type(valid_from) is datetime.datetime
  302. assert not valid_from.tzinfo is None
  303. self.valid_from = valid_from
  304. if valid_until is not None:
  305. assert type(valid_until) is datetime.datetime
  306. assert not valid_until.tzinfo is None
  307. self.valid_until = valid_until
  308. if ticket_url is not None:
  309. assert type(ticket_url) is str
  310. self.ticket_url = ticket_url
  311. if estimated_arrival_time is not None:
  312. assert type(estimated_arrival_time) is ioex.datetimeex.Period
  313. assert not estimated_arrival_time.start.tzinfo is None
  314. assert not estimated_arrival_time.end.tzinfo is None
  315. self.estimated_arrival_time = estimated_arrival_time
  316. class Shipping(Transportation):
  317. yaml_tag = u'!shipping'
  318. def __init__(self,
  319. **kwargs
  320. ):
  321. super(Shipping, self).__init__(**kwargs)
  322. class TaxiRide(Transportation):
  323. yaml_tag = u'!taxi-ride'
  324. def __init__(self,
  325. arrival_time=None,
  326. departure_time=None,
  327. driver=None,
  328. name=None,
  329. **kwargs
  330. ):
  331. if name is None:
  332. name = u'Taxi Ride'
  333. super(TaxiRide, self).__init__(name=name, **kwargs)
  334. assert type(driver) is str
  335. self.driver = driver
  336. assert arrival_time is None or type(arrival_time) is datetime.datetime
  337. self.arrival_time = arrival_time
  338. assert departure_time is None or type(
  339. departure_time) is datetime.datetime
  340. self.departure_time = departure_time
  341. class Person(_Object, _YamlInitConstructor):
  342. yaml_tag = u'!person'
  343. def __init__(self, first_name=None, last_name=None):
  344. self.first_name = first_name
  345. self.last_name = last_name
  346. @property
  347. def first_name(self):
  348. return self._first_name
  349. @first_name.setter
  350. def first_name(self, first_name):
  351. assert first_name is None or type(first_name) is str
  352. self._first_name = first_name
  353. @property
  354. def last_name(self):
  355. return self._last_name
  356. @last_name.setter
  357. def last_name(self, last_name):
  358. assert last_name is None or type(last_name) is str
  359. self._last_name = last_name
  360. @classmethod
  361. def to_yaml(cls, dumper, person):
  362. return dumper.represent_mapping(cls.yaml_tag, {
  363. 'first_name': person.first_name,
  364. 'last_name': person.last_name,
  365. })
  366. def __repr__(self):
  367. return self.__class__.__name__ + '(%s)' % ', '.join([
  368. '%s=%r' % (k, v) for k, v in vars(self).items()
  369. ])