コード例 #1
0
def deleteReceipt():
    # Get Receipt inputs
    
    auth_token=request.headers.get("auth_token")
    if not auth_token:    
        #data=receipt.objects(user_id=userid)
        responseObject = {
                'status': 'fail',
                'message': 'Something is wrong.'
            }
        return make_response(jsonify(responseObject)), 400
    else:
        auth=user.decode_auth_token(auth_token)
        userid=auth['user_id']
        receipt_id=request.get_json()['receipt_id']
        
        if not receipt.objects(user_id=userid,receipt_id=receipt_id):
            responseObject = {
                'status': 'fail',
                'message': 'Receipt not found.'
            }
            return make_response(jsonify(responseObject)), 400
        else:
            data=receipt.objects.get(user_id=userid,receipt_id=receipt_id)

            data.delete()
            print(data.title)
            responseObject = {
                    'status': 'success',
                    'message': 'Receipt deleted.'
                }
    return make_response(jsonify(responseObject)), 200
        

    
コード例 #2
0
def getReceipt():
    id = request.args.get('receipt_id')
    print(id)
    # Validating if receipt id present in database
    if not id:
        responseObject = {
            'status': 'fail',
            'message': 'Please enter required parameters'
        }
        return make_response(jsonify(responseObject)), 400
    else:
        auth_token = request.headers.get("auth_token")
        auth = user.decode_auth_token(auth_token)
        userid = auth['user_id']

    data = receipt.objects.get(user_id=userid)
    if data.receipt_id == id:
        responseObject = {
            'status': 'success',
            'receipt_id': data.receipt_id,
            'picture_url': [data.picture_url]
        }
        return make_response(jsonify(responseObject)), 201
    else:
        responseObject = {'status': 'fail', 'message': 'Invalid Receipt id'}
        return make_response(jsonify(responseObject)), 400
コード例 #3
0
def getReceipts():
    month = int(request.args.get('month'))
    year = int(request.args.get('year'))
    if month == None and year == None:
        responseObject = {
            'status': 'fail',
            'message': 'Please enter required parameters'
        }
        return make_response(jsonify(responseObject)), 400
    else:
        auth_token = request.headers.get("auth_token")
        auth = user.decode_auth_token(auth_token)
        userid = auth['user_id']

    data = receipt.objects(user_id=userid)
    response = []
    total_amt = 0
    date_str = ""
    for doc in data:

        if doc.receipt_date.month == month and doc.receipt_date.year == year:
            total_amt = total_amt + doc.amount
            date_str = str(doc.receipt_date.day) + '-' + str(
                doc.receipt_date.month) + '-' + str(doc.receipt_date.year)
            dic = {
                'receipt_id': doc.receipt_id,
                'title': doc.title,
                'amount': doc.amount,
                'category': doc.category,
                'receipt_date': date_str,
                'picture_url': doc.picture_url
            }
            response.append(dic)

        else:
            pass
    response.reverse()
    responseObject = {
        'status': 'success',
        'response': response,
        'total_amount': total_amt
    }
    return make_response(jsonify(responseObject)), 201
コード例 #4
0
def updateReceipt():
    # Get Receipt inputs
    auth_token = request.headers.get("auth_token")

    if not auth_token:
        #data=receipt.objects(user_id=userid)
        responseObject = {'status': 'fail', 'message': 'Something is wrong.'}
        return make_response(jsonify(responseObject)), 400
    else:
        auth = user.decode_auth_token(auth_token)
        userid = auth['user_id']
        data = receipt.objects(user_id=userid)
        data_len = len(list(data))

        if data_len == 0:
            responseObject = {
                'status': 'success',
                'message': 'Something is wrong.'
            }
            return make_response(jsonify(responseObject)), 200

        else:

            receipt_id = request.get_json()['receipt_id']
            title = request.get_json()['title']
            amount = request.get_json()['amount']
            category = request.get_json()['category']
            receipt_date = request.get_json()['receipt_date']
            create_date = request.get_json()['date_created']

            # Inserting into the database
            userid = receipt.objects(receipt_id=receipt_id).update_one(
                set__title=title,
                set__amount=amount,
                set__category=category,
                set__receipt_date=receipt_date,
                set__date_created=create_date)
            responseObject = {
                'status': 'success',
                'message': 'Receipt Updated Successfully.',
            }
            return make_response(jsonify(responseObject)), 201
コード例 #5
0
def viewAllReceipts():
    
    auth_token=request.headers.get("auth_token")
    
    if not auth_token:    
        #data=receipt.objects(user_id=userid)
        responseObject = {
                'status': 'fail',
                'message': 'Something is wrong.'
            }
        return make_response(jsonify(responseObject)), 400
    else:
        auth=user.decode_auth_token(auth_token)
        userid=auth['user_id']
        data=receipt.objects(user_id=userid)
        response=[]
        total_amt=0
        date_str=""
        for doc in data:
            
            total_amt=total_amt+doc.amount
            date_str=str(doc.receipt_date.day) +'-'+ str(doc.receipt_date.month)+'-'+str(doc.receipt_date.year)
            dic={
                    'receipt_id':doc.receipt_id,
                'title':doc.title,
                'amount':doc.amount,
                'category':doc.category,
                'receipt_date':date_str,
                'picture_url':doc.picture_url
            }
            response.append(dic)
        response.reverse()
        responseObject = {
            'status': 'success',
            'response':response,
            'total_amount':total_amt
            }
        return make_response(jsonify(responseObject)),201
        
コード例 #6
0
def createReceipt():
    # Get Receipt inputs

    try:
        auth_token = request.headers.get("auth_token")
        auth = user.decode_auth_token(auth_token)
        user_id = auth['user_id']
        id = uuid.uuid1()
        receipt_id = str(id).replace("-", "")
        title = request.get_json()['title']
        amount = request.get_json()['amount']
        category = request.get_json()['category']
        receipt_date = request.get_json()['receipt_date']
        create_date = request.get_json()['date_created']
        picture_url = request.get_json()['picture_url']

    except KeyError:
        responseObject = {
            'status': 'fail',
            'message': 'Some Key values Missing, Please enter all details.'
        }
        return make_response(jsonify(responseObject)), 400

    # Inserting into the database
    userid = receipt(receipt_id=receipt_id,
                     user_id=user_id,
                     title=title,
                     amount=amount,
                     category=category,
                     receipt_date=receipt_date,
                     date_created=create_date,
                     picture_url=picture_url).save()

    responseObject = {
        'status': 'success',
        'message': 'Receipt Created Successfully.',
    }
    return make_response(jsonify(responseObject)), 201
コード例 #7
0
def topCategories():

    auth_token = request.headers.get("auth_token")
    token = user.decode_auth_token(auth_token)
    userid = token['user_id']

    if not receipt.objects(user_id=userid):
        responseObject = {
            'status':
            'success',
            'topCategory': [{
                'name': 'Food and Drinks',
                'total': 0
            }, {
                'name': 'Shopping',
                'total': 0
            }, {
                'name': 'Grocery',
                'total': 0
            }]
        }
        return make_response(jsonify(responseObject)), 201
    else:
        data = receipt.objects(user_id=userid)
        current_year = datetime.date.today().year
        # filtering receipts by current year
        filtered_yearly = filter(
            lambda item: item.receipt_date.year == current_year, data)

        food_drinks_amt = 0
        food_count = 0
        travel_amt = 0
        travel_count = 0
        shopping_amt = 0
        shopping_count = 0
        services_amt = 0
        services_count = 0
        other_amt = 0
        other_count = 0
        grocery_amt = 0
        grocery_count = 0
        business_amt = 0
        business_count = 0

        for doc in filtered_yearly:

            if doc.category == "Food and Drinks":
                food_count += 1
                food_drinks_amt += doc.amount
            elif doc.category == "Travel":
                travel_count += 1
                travel_amt += doc.amount
            elif doc.category == "Shopping":
                shopping_count += 1
                shopping_amt += doc.amount
            elif doc.category == "Services":
                services_count += 1
                services_amt += doc.amount
            elif doc.category == "Other":
                other_count += 1
                other_amt += doc.amount
            elif doc.category == "Grocery":
                grocery_count += 1
                grocery_amt += doc.amount
            elif doc.category == "Business":
                business_count += 1
                business_amt += doc.amount
            else:
                pass

        class Category:
            def __init__(self, name, total, count):
                self.name = name
                self.total = total
                self.count = count

            def asdict(self):
                return {'name': self.name, 'total': self.total}

        c1 = Category('Food and Drinks', food_drinks_amt, food_count)
        c2 = Category('Travel', travel_amt, travel_count)
        c3 = Category('Shopping', shopping_amt, shopping_count)
        c4 = Category('Services', services_amt, services_count)
        c5 = Category('Other', other_amt, other_count)
        c6 = Category('Grocery', grocery_amt, grocery_count)
        c7 = Category('Business', business_amt, business_count)

        li = [c1, c2, c3, c4, c5, c6, c7]

        # key to sort the top three categories by most choosed category
        def e_sort(cat):
            return cat.count

        s_li = sorted(li, key=e_sort, reverse=True)
        top_3 = s_li[0:3]
        top_categories = [
            top_3[0].asdict(), top_3[1].asdict(), top_3[2].asdict()
        ]

        responseObject = {'status': 'success', 'topCategory': top_categories}
        return make_response(jsonify(responseObject)), 201
コード例 #8
0
def createReceiptVision():
    # Get Receipt inputs

    try:
        auth_token = request.headers.get("auth_token")
        auth = user.decode_auth_token(auth_token)
        user_id = auth['user_id']

        pict_file = request.files['picture_url']
        p = pict_file.filename

        # Storing the data in aws s3 buckets
        s3 = boto3.resource('s3',
                            aws_access_key_id=ACCESS_KEY_ID,
                            aws_secret_access_key=ACCESS_SECRET_KEY,
                            config=Config(signature_version='s3v4'))
        location = s3.Bucket(BUCKET_NAME).put_object(Key=p, Body=pict_file)
        # Url where we store our file
        picture_url = 'https://%s.s3.ca-central-1.amazonaws.com/%s' % (
            BUCKET_NAME, p)

        # Google cloud vision API for text detection in image receipts
        print("google credential--------")
        credi = os.getenv('GOOGLE_APPLICATION_CREDENTIALS')
        from google.oauth2 import service_account
        # Instantiates a client
        credentials = service_account.Credentials.from_service_account_file(
            credi)

        #person_dict = json.load(credi)
        with open(credi, "r") as read_file:
            data = json.load(read_file)
        print(data)
        print(os.getenv('GOOGLE_APPLICATION_CREDENTIALS'))

        print(type(os.getenv('GOOGLE_APPLICATION_CREDENTIALS')))
        client = vision.ImageAnnotatorClient(credentials=credentials)
        image = vision.types.Image()
        image.source.image_uri = picture_url

        response = client.text_detection(image=image)
        texts = response.text_annotations

        # Parse the text from receipts
        title = ""
        amount = 0
        texts_list = list(texts)
        for i in range(len(texts_list)):
            if "{}".format(texts_list[i].description).lower() in [
                    'fuel', 'gas', 'restaurant'
            ]:
                title = texts_list[i].description

        if title == None:
            title = ""

        for i in range(len(texts_list)):
            if "{}".format(texts_list[i].description).lower() in [
                    'total', 'total amount', 'sub-total'
            ]:
                new_lst = texts_list[i:]

                for j in range(len(new_lst)):
                    digit = "{}".format(new_lst[j].description)

                    dig = re.findall('\d*\.?\d+', digit)

                    if len(dig) != 0:
                        amount = dig[0]
                        break

                break
        if amount == None:
            amount = 0

        response = {
            'title': title,
            'amount': amount,
            'picture_url': picture_url
        }
        responseObject = {'status': 'success', 'response': response}
        return make_response(jsonify(responseObject)), 201

    except KeyError:
        responseObject = {
            'status': 'fail',
            'message': 'Some Key values Missing, Please enter all details.'
        }
        return make_response(jsonify(responseObject)), 400
コード例 #9
0
def sendEmail():
    month = int(request.args.get('month'))
    year = int(request.args.get('year'))
    if month == None and year == None:
        responseObject = {
            'status': 'fail',
            'message': 'Please enter required parameters'
        }
        return make_response(jsonify(responseObject)), 400
    else:
        auth_token = request.headers.get("auth_token")
        auth = user.decode_auth_token(auth_token)
        userid = auth['user_id']
        user_email = auth['email']
    data = receipt.objects(user_id=userid)
    response = filter(lambda item: item.receipt_date.month ==
                      month and item.receipt_date.year == year, data)
    new_data = []
    total = 0
    for doc in response:
        date_str = str(doc.receipt_date.year) + '-' + \
            str(doc.receipt_date.month) + \
            '-'+str(doc.receipt_date.day)
        total += doc.amount
        dic = {
            'receipt_date': date_str,
            'picture_url': doc.picture_url,
            'title': doc.title,
            'amount': doc.amount,
            'category': doc.category,
        }
        new_data.append(dic)
    headers = new_data[0].keys()
    message = Mail(
        from_email=SENDER_EMAIL,
        to_emails=user_email,
        subject='Report from Receipt Tracker',
        html_content='<p>Dear User,<br/><br/>This email has attached report for the requested month and year.<br/>We really appreciate your bussiness and always looking for your feedback to improove our service.<br/><br/>Have a great day!</p>'
    )
    with open('myFile.csv', 'w', newline="") as f:
        dict_writer = csv.DictWriter(f, headers)
        dict_writer.writeheader()
        for dic in new_data:
            dict_writer.writerow(dic)
        dict_writer.writerow(
            {'receipt_date': '', 'picture_url': '', 'title': '', 'amount': '', 'category': ''})
        dict_writer.writerow(
            {'receipt_date': '', 'picture_url': '', 'title': 'Total', 'amount': total, 'category': ''})
    with open('myFile.csv', 'r') as fi:
        generated_file = fi.read()
        x = generated_file.encode()
        fi.close()

    encoded = base64.b64encode(x).decode()
    attachment = Attachment()
    attachment.file_content = FileContent(encoded)
    attachment.file_type = FileType('text/csv')
    attachment.file_name = FileName('myFile.csv')
    attachment.disposition = Disposition('attachment')
    attachment.content_id = ContentId('Content ID')
    message.attachment = attachment

    try:
        sg = SendGridAPIClient(api_key=SENDGRID_API_KEY)
        response = sg.send(message)
        os.remove('myFile.csv')
        print(response.status_code)
        responseobj = {
            "status": "success",
            "message": "Email successfully sent"}
        return make_response(jsonify(responseobj)), 201
    except Exception as e:
        print(e)
        errResponse = {
            "status": "fail",
            "message": "Something went wrong, unable to send email"}
        return make_response(jsonify(errResponse)), 500