__init__.py 13 KB

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