Files
AI_Pharmacy_Api/update_api.py
T

156 lines
5.9 KiB
Python

import os
import sys
import re
# Candidate paths for frontend api.ts
DEFAULT_PATHS = [
r"c:\Users\CSH12\Desktop\ai_pharma_frontend\src\services\api.ts",
r"c:\Users\Lenovo\Desktop\ai_pharma_frontend\src\services\api.ts",
os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "ai_pharma_frontend", "src", "services", "api.ts")),
os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "frontend", "src", "services", "api.ts")),
os.path.abspath(os.path.join(os.path.dirname(__file__), "src", "services", "api.ts")),
]
def find_target_file():
# 1. Command-line argument
if len(sys.argv) > 1 and os.path.exists(sys.argv[1]):
return sys.argv[1]
# 2. Environment variable
env_path = os.environ.get("API_TS_PATH")
if env_path and os.path.exists(env_path):
return env_path
# 3. Check direct known candidate paths
for p in DEFAULT_PATHS:
if os.path.exists(p):
return p
# 4. Check top-level directories on Desktop
user_desktop = os.path.expanduser(r"~\Desktop")
if os.path.exists(user_desktop):
try:
for item in os.listdir(user_desktop):
candidate = os.path.join(user_desktop, item, "src", "services", "api.ts")
if os.path.exists(candidate):
return candidate
except Exception:
pass
return None
def update_api_file(client_id="jayam_web_ai"):
filepath = find_target_file()
if not filepath:
print("ERROR: Target 'api.ts' file could not be found automatically.")
print("Usage: python update_api.py <path_to_api.ts>")
return False
print(f"Found target file: {filepath}")
with open(filepath, "r", encoding="utf-8") as f:
content = f.read()
original_content = content
replacements_made = 0
# Replacement 1: Add API_KEY to axios.create
old_axios_create = """export const api = axios.create({
baseURL: API_BASE_URL,
headers: {
'Content-Type': 'application/json',
},
});"""
new_axios_create = """export const api = axios.create({
baseURL: API_BASE_URL,
headers: {
'Content-Type': 'application/json',
'x-api-key': import.meta.env.VITE_API_KEY || '',
},
});"""
if old_axios_create in content:
content = content.replace(old_axios_create, new_axios_create)
replacements_made += 1
print(" - Updated axios.create headers with x-api-key")
elif "'x-api-key'" not in content and "axios.create" in content:
content = re.sub(
r"(headers:\s*\{[^}]*'Content-Type':\s*['\"]application/json['\"])(,?\s*\})",
r"\1,\n 'x-api-key': import.meta.env.VITE_API_KEY || ''\2",
content
)
if content != original_content:
replacements_made += 1
print(" - Inserted x-api-key into axios.create headers")
# Replacement 2: Update Hospital API client_credentials authentication (/auth/token)
# Using regex matching so ANY client_id (e.g. jayam_web_ai, telegaruda, etc.) is supported
token_pattern = r"(axios\.post\s*\(\s*`?\$\{?API_BASE_URL\}?/auth/token`?\s*,\s*\{[^}]*grant_type:\s*['\"]client_credentials['\"][^}]*\})\s*(;|\))"
if re.search(token_pattern, content) and "x-api-key" not in re.search(token_pattern, content).group(0):
content = re.sub(
token_pattern,
r"\1, { headers: { 'x-api-key': import.meta.env.VITE_API_KEY || '' } }\2",
content
)
replacements_made += 1
print(f" - Updated Hospital API client_credentials authentication (/auth/token) headers for client_id")
else:
# Fallback literal string replace for specific client_id
old_auth = f""" const response = await axios.post(`${{API_BASE_URL}}/auth/token`, {{
grant_type: 'client_credentials',
client_id: '{client_id}',
client_secret: 'my_secret_key'
}});"""
new_auth = f""" const response = await axios.post(`${{API_BASE_URL}}/auth/token`, {{
grant_type: 'client_credentials',
client_id: '{client_id}',
client_secret: 'my_secret_key'
}}, {{
headers: {{ 'x-api-key': import.meta.env.VITE_API_KEY || '' }}
}});"""
if old_auth in content:
content = content.replace(old_auth, new_auth)
replacements_made += 1
print(f" - Updated Hospital API client_credentials authentication headers ({client_id})")
# Replacement 3: Update loginPharmacist (/auth/login)
old_login = """ const response = await axios.post(`${API_BASE_URL}/auth/login`, credentials);"""
new_login = """ const response = await axios.post(`${API_BASE_URL}/auth/login`, credentials, {
headers: { 'x-api-key': import.meta.env.VITE_API_KEY || '' }
});"""
if old_login in content:
content = content.replace(old_login, new_login)
replacements_made += 1
print(" - Updated loginPharmacist endpoint headers")
# Replacement 4: Update logoutPharmacist (/auth/logout)
old_logout = """ const response = await axios.post(`${API_BASE_URL}/auth/logout`);"""
new_logout = """ const response = await axios.post(`${API_BASE_URL}/auth/logout`, {}, {
headers: { 'x-api-key': import.meta.env.VITE_API_KEY || '' }
});"""
if old_logout in content:
content = content.replace(old_logout, new_logout)
replacements_made += 1
print(" - Updated logoutPharmacist endpoint headers")
# Save modified file
if content != original_content:
with open(filepath, "w", encoding="utf-8") as f:
f.write(content)
print(f"SUCCESS: Applied {replacements_made} update(s) to {filepath}")
else:
print("INFO: File is already up to date or no matching patterns were found.")
return True
if __name__ == "__main__":
cid = sys.argv[2] if len(sys.argv) > 2 else "pharmacy-v1-staging"
update_api_file(client_id=cid)