# -*- coding: utf-8 -*- import datetime import dingguo import email import ioex import re def parse_order_confirmation_mail(mail): assert isinstance(mail, email.message.Message) msg_text = mail.get_payload()[0].get_payload(decode = True).decode('utf-8') if not u'Amazon.de Bestellbestätigung' in msg_text: raise Exception('no amazon order confirmation') orders = [] for order_text in re.split(ur'={32,}', msg_text)[1:-1]: order_id = re.search(r'Bestellnummer #(.+)', order_text).group(1) order_date_formatted = re.search(ur'Aufgegeben am (.+)', order_text, re.UNICODE).group(1) with ioex.setlocale('de_DE.UTF-8'): order_date = datetime.datetime.strptime( order_date_formatted.encode('utf-8'), '%d. %B %Y', ) order = dingguo.Order( u'amazon.de', order_id, order_date ) articles_text = order_text.split('Bestellte(r) Artikel:')[1].split('_' * 10)[0].strip() for article_text in re.split(ur'\n\t*\n', articles_text): article_match = re.match( ur' *((?P\d+) x )?(?P.*)\n' + ur'( *von (?P.*)\n)?' + ur' *(?P[A-Z]+) (?P\d+,\d+)\n' + ur'( *Zustand: (?P.*)\n)?' + ur' *Verkauft von: (?P.*)' + ur'(\n *Versand durch (?P.*))?', article_text, re.MULTILINE | re.UNICODE ) assert article_match is not None, repr(article_text) article = article_match.groupdict() order.items.append(dingguo.Article( name = article['name'], price_brutto = dingguo.Sum( float(article['price_brutto'].replace(',', '.')), article['price_brutto_currency'] ), quantity = int(article['quantity']) if article['quantity'] else 1, authors = article['authors'].split(',') if article['authors'] else None, state = article['state'], reseller = article['reseller'], shipper = article['shipper'], )) orders.append(order) return orders