__init__.py 14 KB

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