Ejemplo n.º 1
0
async def post_dialogflow(username: str, request: dict):
    text = request["text"]
    name = request["name"]

    session_client = dialogflow.SessionsClient()
    session = session_client.session_path('gitrich-9txq', str(uuid.uuid4()))

    text_input = dialogflow.TextInput(text=text, language_code='en')
    query_input = dialogflow.QueryInput(text=text_input)

    response = session_client.detect_intent(request={
        "session": session,
        "query_input": query_input
    })

    params = response.query_result.parameters

    try:
        price = params["unit-currency"]["amount"]
        price = f"{price:.2f}"
    except TypeError:
        return ErrorResponseModel("Price not found within text", 400,
                                  "Please provide the price of the item")

    if params["foods"] != "":
        category = "Food & Drinks"
    else:
        category = "Entertainment"

    receipt = {
        "name":
        name,
        "amount":
        price,
        "items": {},
        "category":
        category,
        "image":
        "",
        "date":
        datetime.now(
            pytz.timezone('Asia/Singapore')).strftime('%d/%m/%Y %H:%M:%S')
    }

    success, receipt = await add_receipt(username, receipt)

    if not (success):
        return ErrorResponseModel("Unexpected Error Occured", 400,
                                  "Please check request body again")

    return ResponseModel(receipt, 201, "Successfully uploaded adhoc receipt")
Ejemplo n.º 2
0
async def login_user(username: str, request: dict):
    password = request.get("password", False)

    # never send password
    if not (password):
        return ErrorResponseModel('Request body incomplete', 400,
                                  'Please send the correct request')

    exist, user = await check_user_existence(username, password)

    if not (exist):
        return ErrorResponseModel('User not found', 400,
                                  'Please enter the correct username')

    return ResponseModel(user, 200, "User logged in.")
Ejemplo n.º 3
0
async def get_category_expense_analytics(username: str):
    result = defaultdict(dict)
    # Everything is monthly for now
    receipts = await retrieve_user_receipts(username)
    if receipts:
        for receipt in receipts:
            receipt_date = receipt["date"]
            category = receipt["category"]
            amount = receipt["amount"]
            date_time_obj = datetime.strptime(receipt_date,
                                              '%d/%m/%Y %H:%M:%S')
            month_and_year = date_time_obj.strftime('%b %Y')

            if category not in result[month_and_year]:
                result[month_and_year][category] = 0.0

            try:
                result[month_and_year][category] += float(amount)
            except ValueError:
                result[month_and_year][category] += 0

        result = OrderedDict(
            sorted(result.items(),
                   key=lambda t: datetime.strptime(t[0], '%b %Y'),
                   reverse=True))
        return ResponseModel(result, 200,
                             "Receipts data retrieved successfully")
    return ErrorResponseModel([], 400, "No Receipts")


# NOTE: For sample response
# receipt = Receipt("Pasta Express\t\r\nSMU, 40 Stamford\t23 February 2021\t\r\nRoad S(178908)\t1:42 pm\t\r\nSMUCONNEXION\t\r\n+65 9711 9906\t\r\nReceipt: ZThw\t\r\nTicket: 85\t\r\n2 Vegetable + 1 Meat+\tS$5.80\t\r\nSpaghetti\t\r\nSMU Staff\tSS0.58\t\r\n(10% off)\t\r\nSubtotal\tS$5.22\t\r\nRounding\t-S$0.02\t\r\nTotal\tS$5.20\t\r\nCash\tS$5.20\t\r\nChange\tSSO.00\t\r\nThank you!\t\r\n")
# print(receipt)
Ejemplo n.º 4
0
async def get_expense_analytics(username: str):
    result = defaultdict(float)

    # Initialise past 6 months
    this_month = date.today().replace(day=1)
    for i in range(6):
        if i == 0:
            result[this_month.strftime('%b %Y')] = 0.0
        else:
            this_month = (this_month - timedelta(days=1)).replace(day=1)
            result[this_month.strftime('%b %Y')] = 0.0

    # Everything is monthly for now
    receipts = await retrieve_user_receipts(username)
    if receipts:
        for receipt in receipts:
            receipt_date = receipt["date"]
            date_time_obj = datetime.strptime(receipt_date,
                                              '%d/%m/%Y %H:%M:%S')
            month_and_year = date_time_obj.strftime('%b %Y')

            if month_and_year in result:
                result[month_and_year] += float(receipt["amount"])
            else:
                continue

        result = OrderedDict(
            sorted(result.items(),
                   key=lambda t: datetime.strptime(t[0], '%b %Y')))
        return ResponseModel(result, 200,
                             "Receipts data retrieved successfully")
    return ErrorResponseModel([], 400, "No Receipts")
Ejemplo n.º 5
0
async def delete_receipt_data(username: str, receipt_id: str):
    deleted_receipt = await delete_receipt(username, receipt_id)
    if deleted_receipt:
        return ResponseModel("Receipt with ID: {} removed".format(receipt_id),
                             200, "Receipt deleted successfully")
    return ErrorResponseModel(
        "An error occurred", 400,
        "Receipt with id {} doesn't exist".format(receipt_id))
Ejemplo n.º 6
0
async def create_user(username: str, request: dict):
    # initialise empty receipt ids
    request["receipt_ids"] = []
    request["username"] = username
    created, user = await add_user(request)

    if not (created):
        return ErrorResponseModel('Username already exists', 400,
                                  'Please choose another username')

    return ResponseModel(user, 201, "User successfully created.")
Ejemplo n.º 7
0
async def get_receipt(username: str, receipt_id: str):
    receipt = await retrieve_user_receipt(receipt_id)

    if receipt:
        return ResponseModel(
            receipt,
            200,
            "Success",
        )

    return ErrorResponseModel(None, 400,
                              "There was an error updating the receipt data")
Ejemplo n.º 8
0
async def upload_qrreceipt(
        username: str, request: dict
):  # if never specify, its gonna be request body from call

    # add Hours minutes and seconds to date
    request["date"] += " 00:00:00"
    success, receipt = await add_receipt(username, request)

    if success:
        return ResponseModel(receipt, 201, "Receipt Successfully Uploaded")

    return ErrorResponseModel("An error occurred.", 400,
                              "There was an error uploading the receipt data")
Ejemplo n.º 9
0
async def update_receipt_data(username: str,
                              receipt_id: str,
                              req: UpdateReceiptModel = Body(...)):
    req = {k: v for k, v in req.dict().items() if v is not None}
    if " " not in req["date"]:
        req["date"] += " 00:00:00"

    updated_receipts = await update_receipt(receipt_id, req)
    if updated_receipts:
        return ResponseModel(
            "Receipt with ID: {} update is successful".format(receipt_id),
            200,
            "Success",
        )
    return ErrorResponseModel("An error occurred.", 400,
                              "There was an error updating the receipt data")
Ejemplo n.º 10
0
async def bootstrap_receipts_endpoint(username: str):
    status = await bootstrap_receipts(username)

    if status:
        return ResponseModel(None, 200, "Receipts data bootstraped")
    return ErrorResponseModel(None, 400, "Error")