order-confirmation-mail-parser 19 KB

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