1
0
Pārlūkot izejas kodu

support oebb booking confirmations in text format

Fabian Peter Hammerle 8 gadi atpakaļ
vecāks
revīzija
269aabcb5e
2 mainītis faili ar 63 papildinājumiem un 11 dzēšanām
  1. 61 9
      order-confirmation-mail-parser
  2. 2 2
      tests/test_integration.py

+ 61 - 9
amazon-order-confirmation-mail-parser → order-confirmation-mail-parser

@@ -1,4 +1,5 @@
 #!/usr/bin/env python
+# -*- coding: utf-8 -*-
 # PYTHON_ARGCOMPLETE_OK
 
 import re
@@ -11,12 +12,13 @@ import random
 import locale
 import argparse
 import datetime
+import traceback
 import argcomplete
 
 # strptime
 locale.setlocale(locale.LC_ALL, 'de_DE.UTF-8')
 
-def parse(msg):
+def parse_amazon(msg):
 
     order = {
         'platform': 'amazon.de',
@@ -58,6 +60,64 @@ def parse(msg):
 
     return order
 
+def parse_oebb(msg):
+
+    msg_text = msg.get_payload(decode = True).decode('utf8')
+
+    order_match = re.search(
+        ur'Booking code: (?P<order_id>[\d ]+)\s+'
+            + ur'Customer number: (?P<customer_id>PV\d+)\s+'
+            + ur'Booking date: (?P<order_date>.* \d{4})\s',
+        msg_text,
+        re.MULTILINE | re.UNICODE
+        )
+    order = order_match.groupdict()
+    order['platform'] = 'oebb.at'
+    locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
+    order['order_date'] = datetime.datetime.strptime(
+        order['order_date'],
+        '%b %d, %Y'
+        ).strftime('%Y-%m-%d')
+
+    article_match = re.search(
+        ur'(?P<price_brutto_currency>.)(?P<price_brutto>\d+\.\d+)'
+            + ur'[\W\w]+'
+            + ur'Your Booking\s+'
+            + ur'(?P<departure_point>.*) > (?P<destination_point>.*)',
+        msg_text,
+        re.MULTILINE | re.UNICODE
+        )
+    article = article_match.groupdict()
+    article['name'] = 'Train Ticket'
+    article['price_brutto'] = float(article['price_brutto'])
+    if article['price_brutto_currency'] == u'€':
+        article['price_brutto_currency'] = 'EUR'
+    else:
+        raise Exception('currency %s is not supported' % article['price_brutto_currency'])
+    order['articles'] = [article]
+
+    return order
+
+def parse(msg):
+
+    tracebacks = {}
+
+    try:
+        return parse_amazon(msg)
+    except:
+        tracebacks['amazon'] = traceback.format_exc()
+
+    try:
+        return parse_oebb(msg)
+    except:
+        tracebacks['oebb'] = traceback.format_exc()
+
+    for parser_name in tracebacks:
+        print('%s parser: \n%s' % (parser_name, tracebacks[parser_name]))
+
+    print('failed')
+    # raise Exception('failed to parse')
+
 def compute():
 
     msg = email.message_from_string(sys.stdin.read())
@@ -75,14 +135,6 @@ def compute():
 def _init_argparser():
 
     argparser = argparse.ArgumentParser(description = None)
-    # argparser.add_argument('a', nargs = '*')
-    # argparser.add_argument('--b')
-    # argparser.add_argument('--flag', action='store_true')
-    # argparser.add_argument('file', type = argparse.FileType('r'))
-    # exclusive_group = argparser.add_mutually_exclusive_group(required = False)
-    # exclusive_group.add_argument('--exclusive-1', action='store_true')
-    # exclusive_group.add_argument('--exclusive-2', action='store_true')
-    # subparsers = argparser.add_subparsers(help = None, dest = 'command')
     return argparser
 
 def main(argv):

+ 2 - 2
tests/test_renames_script.py → tests/test_integration.py

@@ -6,11 +6,11 @@ import yaml
 import subprocess
 
 project_root_path = os.path.realpath(os.path.join(__file__, '..', '..'))
-script_path = os.path.join(project_root_path, 'amazon-order-confirmation-mail-parser')
+script_path = os.path.join(project_root_path, 'order-confirmation-mail-parser')
 test_data_path = os.path.join(project_root_path, 'tests', 'data')
 
 def test_integration():
-    for mail_path in glob.glob(os.path.join(test_data_path, 'mail_*.eml')):
+    for mail_path in glob.glob(os.path.join(test_data_path, '*', 'mail_*.eml')):
         with open(mail_path, 'r') as mail_file:
             process = subprocess.Popen([script_path], stdin = subprocess.PIPE, stdout = subprocess.PIPE)
             script_stdout, script_stderr = process.communicate(input = mail_file.read())