Skip to content

Commit

Permalink
Release/uat 1.0.2 (#38)
Browse files Browse the repository at this point in the history
* Updated dev 4 9 24 (#36)

* update reply show only changed data and logtime deco func add

* consist of update response change gghnbackgroundtask and rean login once change

* removed some comments and rectified set reminder resp msg

* changed filename to logtime

* changed date format to resolve issue of when date (#37)
  • Loading branch information
nisha-inflectionzone authored Sep 10, 2024
1 parent e945251 commit 8a062c3
Show file tree
Hide file tree
Showing 16 changed files with 175 additions and 166 deletions.
57 changes: 29 additions & 28 deletions app/api/appointment/handler.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# ############gghn############
from datetime import datetime
import json
import os
import shutil
Expand Down Expand Up @@ -54,18 +55,17 @@ async def handle_s3_event(message: Request,storage_service):

file_path = await download(message)

# 1. Login as tenant-admin or tenant-user
login = ReanCareLogin()
await login.login()

# 2. Extract the date from the PDF file
reader = GMUPdfReader()
reminder_date = await reader.extract_reminder_date(file_path)
if not reminder_date:
date_extracted = await reader.extract_reminder_date(file_path)
if not date_extracted:
return ('Unable to find or unable to parse the date')

# Compare file date with the todays date
is_valid_date = await is_date_valid(reminder_date);
is_valid_date = await is_date_valid(date_extracted);
formatted_date = datetime.strptime(date_extracted, '%Y-%m-%d').strftime('%Y-%m-%d')
print("formatted_date:",formatted_date)
reminder_date = formatted_date
# 3. Extract the PDF file
if is_valid_date:
print('Extracting pdf data')
Expand Down Expand Up @@ -127,17 +127,16 @@ async def handle(storage_service,file: UploadFile = File(...)):

file_path = await store_uploaded_file(file)

# 1. Login as tenant-admin or tenant-user
login = ReanCareLogin()
await login.login()

# 2. Extract the date from the PDF file
reader = GMUPdfReader()
reminder_date = await reader.extract_reminder_date(file_path)
if not reminder_date:
date_extracted = await reader.extract_reminder_date(file_path)
if not date_extracted:
return ('Unable to find or unable to parse the date')
# Compare file date with the todays date
is_valid_date = await is_date_valid(reminder_date);
is_valid_date = await is_date_valid(date_extracted);
formatted_date = datetime.strptime(date_extracted, '%Y-%m-%d').strftime('%Y-%m-%d')
print("formatted_date:",formatted_date)
reminder_date = formatted_date
# 3. Extract the PDF file
if is_valid_date:
# 3. Extract the PDF file
Expand Down Expand Up @@ -175,37 +174,38 @@ async def store_uploaded_file(file: UploadFile):
###########################other routes#######################################
async def readfile_content(date, storage_service):
try:
in_date = date
date_str = await format_date_(in_date)
formatted_date = datetime.strptime(date, '%Y-%m-%d').strftime('%Y-%m-%d')
print("formatted_date:",formatted_date)
date_str = formatted_date
if(date_str == 'None'):
print("date returned null")
print("formated_date...",date_str)

login = ReanCareLogin()
await login.login()
patientextraction = GGHNAppointmentReminder()
appointmentcontent = await patientextraction.read_content(date_str,storage_service)
return(appointmentcontent)
print(appointmentcontent)
# return()
except Exception as e:
raise e


async def update_reply_by_ph(client_bot_name,date_str, phone_number, content,storage_service):
try:
in_date = date_str
formatted_date = datetime.strptime(date_str, '%Y-%m-%d').strftime('%Y-%m-%d')
print("formatted_date:",formatted_date)

client_name = await get_client_name(client_bot_name)
client = (client_name).lower()
print("client name--",client)
date_str = await format_date_(in_date)
if(date_str == 'None'):
# date_str = await format_date_(in_date)
if(formatted_date == 'None'):
print("date returned null")

print("formated_date...",date_str)
print("date...",formatted_date)
number = await format_phone_number(phone_number)
if(number == 'None'):
print("number returned null")
filename = await form_file_name(client,date_str)
filename = await form_file_name(client,formatted_date)
if(filename == 'None'):
print("filename returned null")
updatefile = UpdateReply()
Expand All @@ -231,17 +231,18 @@ async def read_appointment_file(filename,storage_service):
except Exception as e:
raise e

async def readfile_content_by_phone(client_bot_name, phone_number,date_string,storage_service):
async def readfile_content_by_phone(client_bot_name, phone_number,date_str,storage_service):
try:
client_name = await get_client_name(client_bot_name)
client = (client_name).lower()
date_str = await format_date_(date_string)
if(date_str == 'None'):
formatted_date = datetime.strptime(date_str, '%Y-%m-%d').strftime('%Y-%m-%d')
print("formatted_date:",formatted_date)
if(formatted_date == 'None'):
print("date returned null")
number = await format_phone_number(phone_number)
if(number == 'None'):
print("number returned null")
filename = await form_file_name(client,date_str)
filename = await form_file_name(client,formatted_date)
if(filename == 'None'):
print("filename returned null")
reportfile = ReadReport()
Expand Down
28 changes: 11 additions & 17 deletions app/api/appointment/route.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from datetime import datetime
import os
from fastapi import APIRouter, HTTPException, status
from fastapi import Request
Expand All @@ -12,7 +13,7 @@
from app.dependency import get_storage_service
from app.interfaces.appointment_storage_interface import IStorageService
from fastapi import APIRouter, Depends, HTTPException, Path, status, File, UploadFile

from fastapi import BackgroundTasks
##################################################################################
router = APIRouter(

Expand All @@ -23,29 +24,20 @@
)
#################################################################################
@router.post("/{client}/set-reminders/date/{date_string}", status_code=status.HTTP_201_CREATED,response_model=ResponseModel[BaseResponseModel|None])
async def read_file(client: str, date_string: str,storage_service: IStorageService = Depends(get_storage_service)):
async def read_file(background_tasks: BackgroundTasks, client: str, date_string: str,storage_service: IStorageService = Depends(get_storage_service)):
try:
response = await readfile_content(date_string,storage_service)
if(response == None):
return{
"Message":"No Appointments available",
"Data":response
}
background_tasks.add_task(readfile_content, date_string,storage_service)

return {
"Message" : "Reminders created successfully",
"Data" : response
}
"Message" : "Your Followup reminders are being scheduled",
}
except Exception as e:
print(e)
return JSONResponse(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, content={
"Status": "failure",
"Message": "Internal Server Error",
"Data": None
})
# return {
# "Message" : "Internal Server Error",
# "Data" : None
# }


@router.post("/tests/upload", status_code=status.HTTP_201_CREATED, response_model=ResponseModel[BaseResponseModel|None])
async def test(file: UploadFile = File(...),storage_service: IStorageService = Depends(get_storage_service)):
Expand Down Expand Up @@ -104,7 +96,9 @@ async def read_recent_file(client: str,storage_service: IStorageService = Depend

@router.get("/{client}/status-report/{date_str}", status_code=status.HTTP_200_OK)
async def status_for_date_file(client: str,date_str: str,storage_service: IStorageService = Depends(get_storage_service)):
date_string = await format_date_(date_str)
formatted_date = datetime.strptime(date_str, '%Y-%m-%d').strftime('%Y-%m-%d')
print("formatted_date:",formatted_date)
date_string = formatted_date
if(date_string == 'None'):
print("date returned null")
filename = await form_file_name(client,date_string)
Expand Down
3 changes: 3 additions & 0 deletions app/common/appointment_api/appointment_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
import urllib.parse
import requests

from app.common.logtime import log_execution_time

# from app.services.common_service.db_service import DatabaseService


Expand Down Expand Up @@ -98,6 +100,7 @@ async def has_patient_replied_infile(prefix_string, mobile, reminder_date):
return True
return False

@log_execution_time
async def has_patient_replied(prefix_string, mobile, reminder_date,storage_service):
# initial = prefix_string
# ini_prefix = initial.split('_')
Expand Down
1 change: 1 addition & 0 deletions app/common/base_response.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@
class BaseResponseModel(BaseModel):
Message : str
Data : dict[str,int] | None


28 changes: 28 additions & 0 deletions app/common/logtime.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import asyncio
import time
import logging
import functools



def log_execution_time(func):
if asyncio.iscoroutinefunction(func): # Check if the function is async
@functools.wraps(func)
async def async_wrapper(*args, **kwargs):
start_time = time.perf_counter() # Start time
result = await func(*args, **kwargs)
end_time = time.perf_counter() # End time
execution_time = end_time - start_time
logging.info(f"Executed {func.__name__} in {execution_time:.4f} seconds")
return result
return async_wrapper
else:
@functools.wraps(func)
def sync_wrapper(*args, **kwargs):
start_time = time.perf_counter() # Start time
result = func(*args, **kwargs)
end_time = time.perf_counter() # End time
execution_time = end_time - start_time
logging.info(f"Executed {func.__name__} in {execution_time:.4f} seconds")
return result
return sync_wrapper
29 changes: 22 additions & 7 deletions app/common/reancare_api/reancare_login_service.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
from ast import Dict
from datetime import datetime
import json
import os
import requests
from app.common.cache import cache
from app.common.logtime import log_execution_time

###############################################################

Expand All @@ -17,11 +19,13 @@ def __init__(self):
self.username = os.getenv("USER_NAME")
self.password = os.getenv("PASSWORD")
self.API_KEY = os.getenv("REANCARE_API_KEY")
self.access_token = ''
# self.access_token
self.url = str(reancare_base_url)

@log_execution_time
async def login(self):
base_url = self.url
token_validtill = ''
reancare_access_token = ''
health_check_resp = requests.get(base_url)
print("health check resp", health_check_resp)
headers = {
Expand All @@ -38,12 +42,23 @@ async def login(self):
result = response.json()
if result['Status'] == 'failure':
raise Exception(result['Message'])
self.access_token = result['Data']['AccessToken']

cache.set('access_token', self.access_token)
reancare_access_token = result['Data']['AccessToken']
token_validtill = result['Data']['SessionValidTill']
print("validtill..",token_validtill)
cache.set('Valid_rc_token_date', token_validtill)
cache.set('access_token', reancare_access_token)
print('Login successful')
return (result)

def get_access_token(self):
return self.access_token

async def get_access_token(self):
token = cache.get('access_token')
validtill_date = cache.get('Valid_rc_token_date')
date = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
if(token == None or validtill_date < date or validtill_date == None):
print('need to login')
await self.login()
# print('token valid no need to login')
access_token = cache.get('access_token')
return access_token

13 changes: 10 additions & 3 deletions app/common/reancare_api/reancare_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,17 @@
from app.common.cache import cache
import urllib.parse
import requests

from app.common.reancare_api.reancare_login_service import ReanCareLogin
###############################################################################

from app.common.logtime import log_execution_time
###############################################################################
@log_execution_time
async def find_patient_by_mobile(mobile):
reancare_base_url = os.getenv("REANCARE_BASE_URL")
url = str(reancare_base_url + "/patients/")
headers = get_headers()
headers = await get_headers()
formatted = urllib.parse.quote(mobile)
search_url = url + "search?phone={}".format(formatted)
response = requests.get(search_url, headers=headers)
Expand All @@ -24,14 +29,16 @@ async def find_patient_by_mobile(mobile):
else:
return search_result['Data']['Patients']['Items'][0]['UserId']

def get_headers(create_user = False):
async def get_headers(create_user = False):
login = ReanCareLogin()
access_token = await login.get_access_token()
if create_user:
return {
'x-api-key': os.getenv("REANCARE_API_KEY"),
'Content-Type': 'application/json'
}
return {
'Authorization': "Bearer " + cache.get('access_token'),
'Authorization': "Bearer " + access_token,
'x-api-key': os.getenv("REANCARE_API_KEY"),
'Content-Type': 'application/json'
}
Loading

0 comments on commit 8a062c3

Please sign in to comment.