amazon.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. # -*- coding: utf-8 -*-
  2. import datetime
  3. import dingguo
  4. import email
  5. import ioex
  6. import re
  7. def parse_order_confirmation_mail(mail):
  8. assert isinstance(mail, email.message.Message)
  9. msg_text = mail.get_payload()[0].get_payload(decode = True).decode('utf-8')
  10. if not u'Amazon.de Bestellbestätigung' in msg_text:
  11. raise Exception('no amazon order confirmation')
  12. orders = []
  13. for order_text in re.split(ur'={32,}', msg_text)[1:-1]:
  14. order_id = re.search(r'Bestellnummer #(.+)', order_text).group(1)
  15. order_date_formatted = re.search(ur'Aufgegeben am (.+)', order_text, re.UNICODE).group(1)
  16. with ioex.setlocale('de_DE.UTF-8'):
  17. order_date = datetime.datetime.strptime(
  18. order_date_formatted.encode('utf-8'),
  19. '%d. %B %Y',
  20. )
  21. order = dingguo.Order(
  22. u'amazon.de',
  23. order_id,
  24. order_date
  25. )
  26. articles_text = order_text.split('Bestellte(r) Artikel:')[1].split('_' * 10)[0].strip()
  27. for article_text in re.split(ur'\n\t*\n', articles_text):
  28. article_match = re.match(
  29. ur' *((?P<quantity>\d+) x )?(?P<name>.*)\n'
  30. + ur'( *von (?P<authors>.*)\n)?'
  31. + ur' *(?P<price_brutto_currency>[A-Z]+) (?P<price_brutto>\d+,\d+)\n'
  32. + ur'( *Zustand: (?P<state>.*)\n)?'
  33. + ur' *Verkauft von: (?P<reseller>.*)'
  34. + ur'(\n *Versand durch (?P<shipper>.*))?',
  35. article_text,
  36. re.MULTILINE | re.UNICODE
  37. )
  38. assert article_match is not None, repr(article_text)
  39. article = article_match.groupdict()
  40. order.items.append(dingguo.Article(
  41. name = article['name'],
  42. price_brutto = dingguo.Sum(
  43. float(article['price_brutto'].replace(',', '.')),
  44. article['price_brutto_currency']
  45. ),
  46. quantity = int(article['quantity']) if article['quantity'] else 1,
  47. authors = article['authors'].split(',') if article['authors'] else None,
  48. state = article['state'],
  49. reseller = article['reseller'],
  50. shipper = article['shipper'],
  51. ))
  52. orders.append(order)
  53. return orders