1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- import BeautifulSoup
- import datetime
- import dateutil.parser
- import dingguo
- import email.message
- import ioex
- import pytz
- import re
- def parse_order_confirmation_mail(mail):
- assert isinstance(mail, email.message.Message)
- html = mail.get_payload()[1].get_payload(decode = True).decode('utf-8')
- if not 'kickstarter' in html:
- raise Exception()
- email_recipient_address = mail['delivered-to'].decode('utf8')
- email_date = dateutil.parser.parse(mail['date'])
- order = dingguo.Order(
- platform = u'kickstarter',
- order_id = '%s-%sZ' % (
- email_recipient_address,
- email_date.astimezone(pytz.utc).replace(tzinfo = None).isoformat(),
- ),
- order_date = email_date,
- customer_id = email_recipient_address,
- )
- doc = BeautifulSoup.BeautifulSoup(html)
- def get_text(tag):
- return u''.join([c if type(c) is BeautifulSoup.NavigableString else get_text(c) for c in tag.contents])
- shipping_label_tag = doc.find(text = re.compile('Shipping'))
- if shipping_label_tag:
- shipping_attr = re.search(
- ur'^Shipping(?P<dest>.*)\((?P<price>.*)\)$',
- shipping_label_tag.parent.parent.text,
- ).groupdict()
- shipping = dingguo.Shipping(
- destination_point = shipping_attr['dest'].strip(),
- price_brutto = dingguo.Sum.parse_text(shipping_attr['price']),
- )
- else:
- shipping = None
- pledge_amount = dingguo.Sum.parse_text(
- doc.find(text = re.compile('Amount pledged')).parent.parent.text.replace('Amount pledged', '')
- )
- order.items.append(dingguo.Pledge(
- campaign = dingguo.Campaign(
- name = doc.find('h2').text,
- founder = doc.find('h2').findNext('p').text[len('By '):],
- end = dateutil.parser.parse(
- doc.find(text = re.compile('your card will be charged on')).findNext('time')['datetime']
- ),
- ),
- price_brutto = pledge_amount - shipping.price_brutto if shipping else pledge_amount,
- reward = get_text(doc.find(text = re.compile('Reward')).findPrevious('td'))
- .strip()[len('Reward'):].strip().replace('\r\n', '\n'),
- ))
- if shipping:
- order.items.append(shipping)
- return [order]
|