oebb.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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 = mail.get_payload()[0]
  10. if type(msg.get_payload()) is list:
  11. msg = msg.get_payload()[0]
  12. msg_text = msg.get_payload(decode = True).decode('utf8')
  13. # msg_text = re.sub(
  14. # r'<[^>]+>',
  15. # '',
  16. # HTMLParser.HTMLParser().unescape(msg.get_payload(decode = True).decode('utf8'))
  17. # )
  18. order_match = re.search(
  19. ur'(?P<order_id_label>Booking code|Buchungscode):\s+(?P<order_id>[\d ]+)\s+'
  20. + ur'(Customer number|Kundennummer):\s+(?P<customer_id>PV\d+)\s+'
  21. + ur'(Booking date|Buchungsdatum):\s+(?P<order_date>.* \d{4})\s',
  22. msg_text,
  23. re.MULTILINE | re.UNICODE
  24. )
  25. order_match_groups = order_match.groupdict()
  26. if order_match_groups['order_id_label'] == 'Buchungscode':
  27. with ioex.setlocale('de_AT.UTF-8'):
  28. order_date = datetime.datetime.strptime(
  29. order_match_groups['order_date'],
  30. '%d. %b %Y',
  31. )
  32. else:
  33. with ioex.setlocale('en_US.UTF-8'):
  34. order_date = datetime.datetime.strptime(
  35. order_match_groups['order_date'],
  36. '%b %d, %Y',
  37. )
  38. order = dingguo.Order(
  39. u'oebb',
  40. order_match_groups['order_id'],
  41. order_date.date(),
  42. customer_id = order_match_groups['customer_id'],
  43. )
  44. item_match = re.search(
  45. ur'(?P<price_brutto_currency>.) ?(?P<price_brutto>\d+(\.|,)\d+)'
  46. + ur'[\W\w]+'
  47. + ur'(Your Bookings?|Ihre Buchung)\s+'
  48. + ur'(?P<departure_point>.*)\s+>\s+(?P<destination_point>.*)',
  49. msg_text,
  50. re.MULTILINE | re.UNICODE
  51. )
  52. item = item_match.groupdict()
  53. order.items.append(dingguo.Transportation(
  54. name = u'Train Ticket',
  55. price_brutto = dingguo.Sum(
  56. float(item['price_brutto'].replace(',', '.')),
  57. item['price_brutto_currency'],
  58. ),
  59. departure_point = item['departure_point'],
  60. destination_point = item['destination_point'],
  61. ))
  62. return [order]