amazon.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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.date(),
  25. )
  26. for articles_text in re.findall(
  27. ur'Bestellte\(r\) Artikel:\s+'
  28. + ur'([\W\w]+?)\s+'
  29. + ur'(Lieferung \d|_{10,})',
  30. order_text,
  31. re.UNICODE,
  32. ):
  33. for article_text in re.split(ur'\n\t*\n', articles_text[0]):
  34. article_match = re.match(
  35. ur' *((?P<quantity>\d+) x )?(?P<name>.*)\n'
  36. + ur'( *von (?P<authors>.*)\n)?'
  37. + ur' *(?P<price_brutto_currency>[A-Z]+) (?P<price_brutto>\d+,\d+)\n'
  38. + ur'( *Zustand: (?P<state>.*)\n)?'
  39. + ur' *Verkauft von: (?P<reseller>.*)'
  40. + ur'(\n *Versand durch (?P<shipper>.*))?',
  41. article_text,
  42. re.MULTILINE | re.UNICODE
  43. )
  44. assert article_match is not None, repr(article_text)
  45. article = article_match.groupdict()
  46. order.items.append(dingguo.Article(
  47. name = article['name'],
  48. price_brutto = dingguo.Sum(
  49. float(article['price_brutto'].replace(',', '.')),
  50. article['price_brutto_currency']
  51. ),
  52. quantity = int(article['quantity']) if article['quantity'] else 1,
  53. authors = article['authors'].split(',') if article['authors'] else None,
  54. state = article['state'],
  55. reseller = article['reseller'],
  56. shipper = article['shipper'],
  57. ))
  58. orders.append(order)
  59. return orders