order-confirmation-mail-parser 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # PYTHON_ARGCOMPLETE_OK
  4. import dingguo
  5. import re
  6. import os
  7. import sys
  8. import yaml
  9. import email
  10. import pprint
  11. import random
  12. import locale
  13. import argparse
  14. import datetime
  15. import traceback
  16. import subprocess
  17. import HTMLParser
  18. import argcomplete
  19. import BeautifulSoup
  20. class Order(object):
  21. def __init__(self, platform, order_id, order_date, customer_id = None):
  22. assert type(platform) is unicode
  23. self.platform = platform
  24. assert type(order_id) is unicode
  25. self.order_id = order_id
  26. if type(order_date) is datetime.datetime:
  27. order_date = order_date.date()
  28. assert type(order_date) is datetime.date
  29. self.order_date = order_date
  30. assert customer_id is None or type(customer_id) is unicode
  31. self.customer_id = customer_id
  32. self.items = []
  33. self.discounts = []
  34. def dict_repr(self):
  35. return {k: v for (k, v) in {
  36. 'articles': self.items,
  37. 'customer_id': self.customer_id,
  38. 'discounts': self.discounts,
  39. 'order_date': self.order_date.strftime('%Y-%m-%d'),
  40. 'order_id': self.order_id,
  41. 'platform': self.platform,
  42. }.items() if v is not None}
  43. yaml.SafeDumper.add_representer(Order, lambda dumper, order: dumper.represent_dict(order.dict_repr()))
  44. class Discount(object):
  45. def __init__(
  46. self,
  47. name = None,
  48. amount = None,
  49. ):
  50. assert type(name) is unicode
  51. self.name = name
  52. assert type(amount) is dingguo.Sum
  53. assert amount.value >= 0
  54. self.amount = amount
  55. def dict_repr(self):
  56. return {
  57. 'name': self.name,
  58. 'value': self.amount.value,
  59. 'value_currency': self.amount.currency,
  60. }
  61. yaml.SafeDumper.add_representer(Discount, lambda dumper, discount: dumper.represent_dict(discount.dict_repr()))
  62. class Item(object):
  63. def __init__(
  64. self,
  65. name = None,
  66. price_brutto = None,
  67. ):
  68. assert type(name) is unicode
  69. self.name = name
  70. assert type(price_brutto) is dingguo.Sum
  71. self.price_brutto = price_brutto
  72. def dict_repr(self):
  73. return {
  74. 'name': self.name,
  75. 'price_brutto': self.price_brutto.value,
  76. 'price_brutto_currency': self.price_brutto.currency,
  77. }
  78. yaml.SafeDumper.add_representer(Item, lambda dumper, item: dumper.represent_dict(item.dict_repr()))
  79. class Article(Item):
  80. def __init__(
  81. self,
  82. quantity = None,
  83. authors = [],
  84. state = None,
  85. reseller = None,
  86. shipper = None,
  87. **kwargs
  88. ):
  89. super(Article, self).__init__(**kwargs)
  90. assert type(quantity) is int
  91. self.quantity = quantity
  92. assert type(authors) is list
  93. self.authors = authors
  94. assert state is None or type(state) is unicode
  95. self.state = state
  96. assert reseller is None or type(reseller) is unicode
  97. self.reseller = reseller
  98. assert shipper is None or type(shipper) is unicode
  99. self.shipper = shipper
  100. self.delivery_date = None
  101. def dict_repr(self):
  102. attr = Item.dict_repr(self)
  103. attr.update({
  104. 'delivery_date': self.delivery_date,
  105. 'quantity': self.quantity,
  106. 'reseller': self.reseller,
  107. 'shipper': self.shipper,
  108. 'state': self.state,
  109. })
  110. if len(self.authors) > 0:
  111. attr['authors'] = self.authors
  112. return attr
  113. yaml.SafeDumper.add_representer(Article, lambda dumper, article: dumper.represent_dict(article.dict_repr()))
  114. class Transportation(Item):
  115. def __init__(
  116. self,
  117. departure_point = None,
  118. destination_point = None,
  119. distance = None,
  120. route_map = None,
  121. **kwargs
  122. ):
  123. super(Transportation, self).__init__(**kwargs)
  124. assert type(departure_point) is unicode
  125. self.departure_point = departure_point
  126. assert type(destination_point) is unicode
  127. self.destination_point = destination_point
  128. assert distance is None or type(distance) is dingguo.Distance
  129. self.distance = distance
  130. assert route_map is None or type(route_map) is str
  131. self.route_map = route_map
  132. def dict_repr(self):
  133. attr = Item.dict_repr(self)
  134. attr.update({
  135. 'departure_point': self.departure_point,
  136. 'destination_point': self.destination_point,
  137. 'distance_metres': self.distance.metres if self.distance else None,
  138. 'route_map': self.route_map,
  139. })
  140. return attr
  141. yaml.SafeDumper.add_representer(Transportation, lambda dumper, transportation: dumper.represent_dict(transportation.dict_repr()))
  142. class TaxiRide(Transportation):
  143. def __init__(self, name = None, driver = None, arrival_time = None, departure_time = None, **kwargs):
  144. if name is None:
  145. name = u'Taxi Ride'
  146. super(TaxiRide, self).__init__(name = name, **kwargs)
  147. assert type(driver) is unicode
  148. self.driver = driver
  149. assert arrival_time is None or type(arrival_time) is datetime.datetime
  150. self.arrival_time = arrival_time
  151. assert departure_time is None or type(departure_time) is datetime.datetime
  152. self.departure_time = departure_time
  153. def dict_repr(self):
  154. attr = Transportation.dict_repr(self)
  155. attr.update({
  156. 'arrival_time': self.arrival_time.strftime('%Y-%m-%d %H:%M') if self.arrival_time else None,
  157. 'departure_time': self.departure_time.strftime('%Y-%m-%d %H:%M') if self.departure_time else None,
  158. 'driver': self.driver,
  159. })
  160. return attr
  161. yaml.SafeDumper.add_representer(TaxiRide, lambda dumper, taxi_ride: dumper.represent_dict(taxi_ride.dict_repr()))
  162. def parse_amazon(msg):
  163. msg_text = msg.get_payload()[0].get_payload(decode = True).decode('utf-8')
  164. if not u'Amazon.de Bestellbestätigung' in msg_text:
  165. raise Exception('no amazon order confirmation')
  166. orders = []
  167. for order_text in re.split(ur'={32,}', msg_text)[1:-1]:
  168. order_id = re.search(r'Bestellnummer #(.+)', order_text).group(1)
  169. order_date_formatted = re.search(ur'Aufgegeben am (.+)', order_text, re.UNICODE).group(1)
  170. locale.setlocale(locale.LC_ALL, 'de_DE.UTF-8')
  171. order_date = datetime.datetime.strptime(order_date_formatted.encode('utf-8'), '%d. %B %Y')
  172. order = Order(
  173. u'amazon.de',
  174. order_id,
  175. order_date
  176. )
  177. articles_text = order_text.split('Bestellte(r) Artikel:')[1].split('_' * 10)[0].strip()
  178. for article_text in re.split(ur'\n\t*\n', articles_text):
  179. article_match = re.match(
  180. ur' *((?P<quantity>\d+) x )?(?P<name>.*)\n'
  181. + ur'( *von (?P<authors>.*)\n)?'
  182. + ur' *(?P<price_brutto_currency>[A-Z]+) (?P<price_brutto>\d+,\d+)\n'
  183. + ur'( *Zustand: (?P<state>.*)\n)?'
  184. + ur' *Verkauft von: (?P<reseller>.*)'
  185. + ur'(\n *Versand durch (?P<shipper>.*))?',
  186. article_text,
  187. re.MULTILINE | re.UNICODE
  188. )
  189. if article_match is None:
  190. sys.stderr.write(repr(article_text) + '\n')
  191. raise Exception('could not match article')
  192. article = article_match.groupdict()
  193. order.items.append(Article(
  194. name = article['name'],
  195. price_brutto = dingguo.Sum(
  196. float(article['price_brutto'].replace(',', '.')),
  197. article['price_brutto_currency']
  198. ),
  199. quantity = int(article['quantity']) if article['quantity'] else 1,
  200. authors = article['authors'].split(',') if article['authors'] else [],
  201. state = article['state'],
  202. reseller = article['reseller'],
  203. shipper = article['shipper'],
  204. ))
  205. orders.append(order)
  206. return orders
  207. def parse_oebb(msg):
  208. msg_text = msg.get_payload()[0].get_payload(decode = True).decode('utf8')
  209. # msg_text = re.sub(
  210. # r'<[^>]+>',
  211. # '',
  212. # HTMLParser.HTMLParser().unescape(msg.get_payload(decode = True).decode('utf8'))
  213. # )
  214. order_match = re.search(
  215. ur'Booking code:\s+(?P<order_id>[\d ]+)\s+'
  216. + ur'Customer number:\s+(?P<customer_id>PV\d+)\s+'
  217. + ur'Booking date:\s+(?P<order_date>.* \d{4})\s',
  218. msg_text,
  219. re.MULTILINE | re.UNICODE
  220. )
  221. order_match_groups = order_match.groupdict()
  222. locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
  223. order_date = datetime.datetime.strptime(
  224. order_match_groups['order_date'],
  225. '%b %d, %Y'
  226. )
  227. order = Order(
  228. u'oebb',
  229. order_match_groups['order_id'],
  230. order_date,
  231. customer_id = order_match_groups['customer_id'],
  232. )
  233. item_match = re.search(
  234. ur'(?P<price_brutto_currency>.)(?P<price_brutto>\d+\.\d+)'
  235. + ur'[\W\w]+'
  236. + ur'Your Booking\s+'
  237. + ur'(?P<departure_point>.*)\s+>\s+(?P<destination_point>.*)',
  238. msg_text,
  239. re.MULTILINE | re.UNICODE
  240. )
  241. item = item_match.groupdict()
  242. order.items.append(Transportation(
  243. name = u'Train Ticket',
  244. price_brutto = dingguo.Sum(
  245. float(item['price_brutto']),
  246. item['price_brutto_currency'],
  247. ),
  248. departure_point = item['departure_point'],
  249. destination_point = item['destination_point'],
  250. ))
  251. return [order]
  252. def parse_mytaxi(msg):
  253. if not 'mytaxi' in msg.get_payload()[0].get_payload()[0].get_payload(decode = True):
  254. raise Exception('no mytaxi mail')
  255. pdf_compressed = msg.get_payload()[1].get_payload(decode = True)
  256. pdftk = subprocess.Popen(
  257. ['pdftk - output - uncompress'],
  258. shell = True,
  259. stdin = subprocess.PIPE,
  260. stdout = subprocess.PIPE,
  261. )
  262. pdf_uncompressed = pdftk.communicate(
  263. input = pdf_compressed,
  264. )[0].decode('latin-1')
  265. assert type(pdf_uncompressed) is unicode
  266. order_match = re.search(
  267. ur'Rechnungsnummer:[^\(]+\((?P<order_id>\w+)\)',
  268. pdf_uncompressed,
  269. re.MULTILINE | re.UNICODE
  270. )
  271. order_id = order_match.groupdict()['order_id']
  272. ride_match_groups = re.search(
  273. ur'\(Bruttobetrag\)'
  274. + ur'[^\(]+'
  275. + ur'\((?P<price_brutto>\d+,\d+) (?P<price_brutto_currency>.+)\)'
  276. + ur'[\w\W]+'
  277. + ur'\((?P<driver>[^\(]+)\)'
  278. + ur'[^\(]+'
  279. + ur'\(\d+,\d+ .\)'
  280. + ur'[^\(]+'
  281. + ur'\((?P<name>Taxifahrt)'
  282. + ur'[^\(]+'
  283. + ur'\(von: (?P<departure_point>[^\)]+)'
  284. + ur'[^\(]+'
  285. + ur'\(nach: (?P<destination_point>[^\)]+)'
  286. + ur'[\w\W]+'
  287. + ur'Belegdatum \\\(Leistungszeitpunkt\\\):[^\(]+\((?P<arrival_time>\d\d.\d\d.\d\d \d\d:\d\d)\)',
  288. pdf_uncompressed,
  289. re.MULTILINE | re.UNICODE
  290. ).groupdict()
  291. arrival_time = datetime.datetime.strptime(
  292. ride_match_groups['arrival_time'],
  293. '%d.%m.%y %H:%M'
  294. )
  295. order = Order(
  296. u'mytaxi',
  297. order_id,
  298. arrival_time,
  299. )
  300. locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
  301. order.items.append(TaxiRide(
  302. price_brutto = dingguo.Sum(
  303. float(ride_match_groups['price_brutto'].replace(',', '.')),
  304. # why 0x80 ?
  305. u'EUR' if (ride_match_groups['price_brutto_currency'] == u'\x80')
  306. else ride_match_groups['price_brutto_currency'],
  307. ),
  308. departure_point = ride_match_groups['departure_point'],
  309. destination_point = ride_match_groups['destination_point'],
  310. driver = ride_match_groups['driver'],
  311. arrival_time = arrival_time,
  312. ))
  313. return [order]
  314. def parse_uber(msg):
  315. html = msg.get_payload()[0].get_payload(decode = True)
  316. """ document in html2 has the same structure as the one in html.
  317. only difference is that hyperlink urls in html2 have been
  318. replaced by 'email.uber.com/wf/click?upn=.*' urls.
  319. """
  320. html2 = msg.get_payload()[1].get_payload()[0].get_payload(decode = True)
  321. route_map = msg.get_payload()[1].get_payload()[1].get_payload(decode = True)
  322. doc = BeautifulSoup.BeautifulSoup(
  323. html,
  324. convertEntities = BeautifulSoup.BeautifulSoup.HTML_ENTITIES,
  325. )
  326. # strptime
  327. locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
  328. trip_id = re.search(
  329. ur'[\da-f\-]{36}',
  330. doc.find(text = 'Visit the trip page').parent['href'],
  331. ).group(0)
  332. order = Order(
  333. u'uber',
  334. trip_id,
  335. datetime.datetime.strptime(
  336. doc.find(attrs = {'class': 'date'}).text,
  337. '%B %d, %Y',
  338. ),
  339. )
  340. departure_time_tag = doc.find(attrs = {'class': 'from time'})
  341. departure_time = datetime.datetime.strptime(
  342. departure_time_tag.text,
  343. '%I:%M%p',
  344. ).time()
  345. arrival_time_tag = doc.find(attrs = {'class': 'to time'})
  346. arrival_time = datetime.datetime.strptime(
  347. arrival_time_tag.text,
  348. '%I:%M%p',
  349. ).time()
  350. distance = dingguo.Distance(
  351. float(doc.find(text = 'kilometers').parent.parent.find(attrs = {'class': 'data'}).text),
  352. u'km',
  353. )
  354. fare = doc.find(attrs = {'class': 'header-price'}).find(attrs = {'class': 'header-fare text-pad'}).text
  355. order.items.append(TaxiRide(
  356. name = doc.find(text = 'CAR').parent.parent.find(attrs = {'class': 'data'}).text + ' Ride',
  357. price_brutto = dingguo.Sum(float(fare[1:]), fare[0]),
  358. arrival_time = datetime.datetime.combine(order.order_date, arrival_time),
  359. departure_time = datetime.datetime.combine(order.order_date, departure_time),
  360. departure_point = departure_time_tag.parent.find(attrs = {'class': 'address'}).text,
  361. destination_point = arrival_time_tag.parent.find(attrs = {'class': 'address'}).text,
  362. distance = distance,
  363. driver = doc.find(attrs = {'class': 'driver-info'}).text[len('You rode with '):],
  364. route_map = route_map,
  365. ))
  366. return [order]
  367. def parse_yipbee(msg):
  368. text = msg.get_payload()[0].get_payload()[0].get_payload(decode = True).decode('utf-8')
  369. if not u'Vielen Dank für deine Bestellung bei yipbee' in text:
  370. raise Exception('no yipbee confirmation')
  371. order_match_groups = re.search(
  372. ur'[\W\w]+'
  373. + ur'BESTELLUNG: (?P<order_id>\w+) vom (?P<order_time>\d\d.\d\d.\d{4} \d\d:\d\d:\d\d)'
  374. + ur'[\W\w]+'
  375. + ur'GESAMTPREIS\s+'
  376. + ur'(?P<articles_and_discount_text>[\W\w]+)'
  377. + ur'(?P<summary_text>ARTIKEL [\W\w]+)',
  378. text,
  379. re.UNICODE
  380. ).groupdict()
  381. order = Order(
  382. u'yipbee',
  383. order_match_groups['order_id'],
  384. datetime.datetime.strptime(order_match_groups['order_time'], '%d.%m.%Y %H:%M:%S'),
  385. )
  386. for article_match in re.finditer(
  387. ur'(?P<name>[\w\-\.\:,%\(\) ]+ (Klasse \d|[\w\-\. ]+[^\d ]))'
  388. + ur'(?P<total_price>\d+,\d\d) €(?P<quantity>\d)(?P<total_price_2>\d+,\d\d) €',
  389. order_match_groups['articles_and_discount_text'].replace('\n', ' '),
  390. re.UNICODE,
  391. ):
  392. article_match_groups = article_match.groupdict()
  393. total_price = float(article_match_groups['total_price'].replace(',', '.'))
  394. total_price_2 = float(article_match_groups['total_price_2'].replace(',', '.'))
  395. assert abs(total_price - total_price_2) < 0.01, 'expected %f, received %f' % (total_price, total_price_2)
  396. quantity = int(article_match_groups['quantity'])
  397. order.items.append(Article(
  398. name = article_match_groups['name'],
  399. price_brutto = dingguo.Sum(round(total_price / quantity, 2), u'EUR'),
  400. quantity = quantity,
  401. reseller = u'yipbee',
  402. shipper = u'yipbee',
  403. ))
  404. articles_price = float(text.split('RABATTE')[0].split('ARTIKEL')[-1].strip().split(' ')[0].replace(',', '.'))
  405. assert abs(articles_price - sum([a.price_brutto.value * a.quantity for a in order.items])) < 0.01
  406. discount_tag = BeautifulSoup.BeautifulSoup(
  407. order_match_groups['articles_and_discount_text'],
  408. convertEntities = BeautifulSoup.BeautifulSoup.HTML_ENTITIES,
  409. ).find('tr')
  410. if discount_tag:
  411. name_tag, value_tag = discount_tag.findAll('td', recursive = False)
  412. value, currency = value_tag.text.split(' ')
  413. order.discounts.append(Discount(
  414. name = name_tag.text,
  415. amount = dingguo.Sum(float(value.replace(',', '.')) * -1, currency),
  416. ))
  417. delivery_price = order_match_groups['summary_text'].split('VERSAND')[1].split('STEUERN')[0].strip()
  418. delivery_price_value, delivery_price_currency = delivery_price.split(' ')
  419. order.items.append(Item(
  420. name = u'Delivery',
  421. price_brutto = dingguo.Sum(float(delivery_price_value.replace(',', '.')), delivery_price_currency),
  422. ))
  423. return [order]
  424. def parse_yipbee_html(msg):
  425. html = msg.get_payload()[0].get_payload()[1].get_payload(decode = True)
  426. if not 'yipbee' in html:
  427. raise Exception('no yipbee confirmation')
  428. doc = BeautifulSoup.BeautifulSoup(html, convertEntities = BeautifulSoup.BeautifulSoup.HTML_ENTITIES)
  429. content_table = doc.find('table')
  430. order_match_groups = re.search(
  431. ur'Bestellung:(?P<order_id>\w+) vom (?P<order_time>\d\d.\d\d.\d{4} \d\d:\d\d:\d\d)',
  432. content_table.find('table').findAll('tr')[3].text,
  433. re.UNICODE
  434. ).groupdict()
  435. order = Order(
  436. u'yipbee',
  437. order_match_groups['order_id'],
  438. datetime.datetime.strptime(order_match_groups['order_time'], '%d.%m.%Y %H:%M:%S'),
  439. )
  440. articles_table = content_table.find('table').find('tbody').findAll('tr', recursive = False)[4].find('table')
  441. for article_row in articles_table.find('tbody').findAll('tr', recursive = False)[1:]:
  442. article_columns = article_row.findAll('td', recursive = False)
  443. (price, currency) = re.sub(ur'\s+', ' ', article_columns[2].text.replace(u',', u'.')).split(' ')
  444. order.items.append(Article(
  445. name = article_columns[1].text,
  446. price_brutto = dingguo.Sum(float(price), currency),
  447. quantity = int(article_columns[3].text),
  448. reseller = u'yipbee',
  449. shipper = u'yipbee',
  450. ))
  451. discount_row = content_table.find('table').find('tbody').findAll('tr', recursive = False)[6]
  452. (discount_name, discount_value_with_currency) = [c.text for c in discount_row.findAll('td', recursive = False)]
  453. (discount_value, discount_currency) = discount_value_with_currency.split(' ')
  454. order.discounts.append(Discount(
  455. name = discount_name,
  456. amount = dingguo.Sum(float(discount_value.replace(',', '.')) * -1, discount_currency)
  457. ))
  458. shipping_costs_table = content_table.find('tbody').findAll('tr', recursive = False)[3].findAll('table')[1]
  459. (shipping_price, shipping_currency) = shipping_costs_table.text.replace(',', '.').split(' ')
  460. order.items.append(Item(
  461. name = u'Delivery',
  462. price_brutto = dingguo.Sum(float(shipping_price), shipping_currency),
  463. ))
  464. return [order]
  465. def parse_lieferservice(msg):
  466. text = msg.get_payload()[0].get_payload(decode = True).decode('utf-8').replace('\r\n', '\n')
  467. assert type(text) is unicode
  468. if not 'Lieferservice.at' in text:
  469. raise Exception('no lieferservice.at confirmation')
  470. order_match = re.search(
  471. ur'Your order \(.+\) at (?P<restaurant>.*)\s+'
  472. + ur'Your order reference is: (?P<order_id>.*)\s+'
  473. + ur'[\W\w]+'
  474. + ur'Your order\s+'
  475. + ur'(?P<orders_text>[\W\w]+)'
  476. + ur'Delivery costs:\s+(?P<delivery_costs>.*)\s+',
  477. text,
  478. re.UNICODE,
  479. )
  480. order_match_groups = order_match.groupdict()
  481. import time
  482. import email.utils
  483. order_date = datetime.datetime.fromtimestamp(
  484. time.mktime(email.utils.parsedate(msg['Date']))
  485. )
  486. order = Order(
  487. u'lieferservice.at',
  488. order_match_groups['order_id'].strip(),
  489. order_date
  490. )
  491. for article_match in re.finditer(
  492. ur'(?P<quantity>\d+)x\s'
  493. + ur'(?P<name>.*)\s'
  494. + ur'(?P<currency>.) (?P<price>-?\d+,\d+)\s',
  495. order_match_groups['orders_text'],
  496. re.UNICODE,
  497. ):
  498. article_match_groups = article_match.groupdict()
  499. quantity = int(article_match_groups['quantity'])
  500. assert quantity == 1
  501. name = re.sub(ur' +', ' ', article_match_groups['name'])
  502. price = dingguo.Sum(
  503. float(article_match_groups['price'].replace(',', '.')),
  504. article_match_groups['currency'],
  505. )
  506. if price.value < 0:
  507. price.value *= -1
  508. order.discounts.append(Discount(
  509. name = name,
  510. amount = price,
  511. ))
  512. else:
  513. order.items.append(Article(
  514. name = name,
  515. quantity = 1,
  516. price_brutto = price,
  517. reseller = order_match_groups['restaurant'],
  518. shipper = order_match_groups['restaurant'],
  519. ))
  520. delivery_costs = order_match_groups['delivery_costs'].strip()
  521. assert delivery_costs == 'FREE'
  522. order.items.append(Item(
  523. name = u'Delivery',
  524. price_brutto = dingguo.Sum(float('0'.replace(',', '.')), u'EUR'),
  525. ))
  526. return [order]
  527. def parse(msg):
  528. tracebacks = {}
  529. try:
  530. return parse_amazon(msg)
  531. except:
  532. tracebacks['amazon'] = traceback.format_exc()
  533. try:
  534. return parse_oebb(msg)
  535. except:
  536. tracebacks['oebb'] = traceback.format_exc()
  537. try:
  538. return parse_lieferservice(msg)
  539. except:
  540. tracebacks['lieferservice'] = traceback.format_exc()
  541. try:
  542. return parse_mytaxi(msg)
  543. except:
  544. tracebacks['mytaxi'] = traceback.format_exc()
  545. try:
  546. return parse_uber(msg)
  547. except:
  548. tracebacks['uber'] = traceback.format_exc()
  549. try:
  550. return parse_yipbee(msg)
  551. except:
  552. tracebacks['yipbee'] = traceback.format_exc()
  553. for parser_name in tracebacks:
  554. sys.stderr.write('%s parser: \n%s\n' % (parser_name, tracebacks[parser_name]))
  555. raise Exception('failed to parse')
  556. def compute(register_path):
  557. msg = email.message_from_string(sys.stdin.read())
  558. orders = parse(msg)
  559. if register_path:
  560. with open(register_path, 'r') as register:
  561. registered_orders = yaml.load(register.read().decode('utf-8'))
  562. if not registered_orders:
  563. registered_orders = {}
  564. for order in orders:
  565. if order.platform not in registered_orders:
  566. registered_orders[order.platform] = {}
  567. if order.order_id in registered_orders[order.platform]:
  568. raise Exception('already registered')
  569. registered_orders[order.platform][order.order_id] = order
  570. with open(register_path, 'w') as register:
  571. register.write(yaml.safe_dump(registered_orders, default_flow_style = False))
  572. else:
  573. print(yaml.safe_dump(orders, default_flow_style = False))
  574. def _init_argparser():
  575. argparser = argparse.ArgumentParser(description = None)
  576. argparser.add_argument('--register', metavar = 'path', dest = 'register_path')
  577. return argparser
  578. def main(argv):
  579. argparser = _init_argparser()
  580. argcomplete.autocomplete(argparser)
  581. args = argparser.parse_args(argv)
  582. compute(**vars(args))
  583. return 0
  584. if __name__ == "__main__":
  585. sys.exit(main(sys.argv[1:]))