Skip to content

Commit

Permalink
Merge pull request #69 from renathossain/fixed-admin-logs
Browse files Browse the repository at this point in the history
fixed admin logs to match other pages
  • Loading branch information
mjsflames authored Mar 31, 2024
2 parents 5d99c7e + bde723e commit 72a1493
Show file tree
Hide file tree
Showing 5 changed files with 131 additions and 86 deletions.
13 changes: 13 additions & 0 deletions backend/auth_service/database_Authentications.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,19 @@ def close_client_connection(mongoClient):
except Exception as e:
return jsonify({"error": str(e)}), 500

@app.route("/api/getUserID/<username>", methods=["GET"])
@cross_origin()
def getPatientPrescriptions(username):

try:
user = collection.find_one({"email": username})

return user, 200, {"Content-Type": "application/json"}

except Exception as e:
return jsonify({"error": str(e)}), 500



@app.route("/listUsers", methods=["GET"])
@cross_origin()
Expand Down
52 changes: 6 additions & 46 deletions backend/database_functions/database_Prescriptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@
COMPLETE = "Complete"
PR_LOGGED = "Pr Logged"
PA_LOGGED = "Pa Logged"
BOTH_LOGGED = "Both logged with Discovery Pass"
BOTH_LOGGED = "Both Logged with Discovery Pass"
COMPLETE_WITH_DP = "Complete with Discovery Pass"

# required_PAT_prescription_fields = [
Expand Down Expand Up @@ -236,57 +236,17 @@ def search_prescriptions():
def update_prescription(oid):
data = request.json

# Ensure incoming data fields are within the allowed list
if not set(data.keys()).issubset(template_PR):
invalid_fields = set(data.keys()) - set(template_PR)
return jsonify({"error": "Invalid fields in update request", "invalid_fields": list(invalid_fields)}), 400
elif "status" in data and data.get("status") != COMPLETE_WITH_DP:
return jsonify({"error": "Invalid status input in update request. Check if status input is automatically assigned only."}), 400

try:
result = collection.find_one({"_id": ObjectId(oid)})
if not result:
return jsonify({"message": "No prescription found matching the criteria"}), 404
elif "status" in data and result.get("status") != BOTH_LOGGED:
return jsonify({"message": "Status assigned automatically cannot be changed"}), 400

update_data = {k: v for k, v in data.items() if k in result and k in template_PR}

if result.get("status") == BOTH_LOGGED and "prescriber" in result and "patient" in result:
update_data["prescriber"] = {k: v for k, v in data.items() if k in result["prescriber"]}
update_data["patient"] = {k: v for k, v in data.items() if k in result["patient"]}
if "discoveryPass" in data and data.get("discoveryPass") == "No":
update_data["status"] = COMPLETE
update_data["prescriber"]["status"] = COMPLETE
update_data["patient"]["status"] = COMPLETE

elif result.get("status") == COMPLETE and "prescriber" in result and "patient" in result:
update_data["prescriber"] = {k: v for k, v in data.items() if k in result["prescriber"]}
update_data["patient"] = {k: v for k, v in data.items() if k in result["patient"]}
if "discoveryPass" in data and data.get("discoveryPass") == "Yes":
update_data["status"] = BOTH_LOGGED
update_data["prescriber"]["status"] = PA_LOGGED
update_data["patient"]["status"] = PR_LOGGED

elif result.get("status") == PA_NOT_LOGGED and "prescriber" in result:
# Start with a copy of the existing 'prescriber' fields from the result
update_data["prescriber"] = result["prescriber"].copy()
# Update/overwrite with fields from 'data' that exist in the 'prescriber' structure
update_data["prescriber"].update((k, v) for k, v in data.items() if k in result["prescriber"])

elif result.get("status") == PR_NOT_LOGGED and "patient" in result:
# Start with a copy of the existing 'patient' fields from the result
update_data["patient"] = result["patient"].copy()
# Update/overwrite with fields from 'data' that exist in the 'patient' structure
update_data["patient"].update((k, v) for k, v in data.items() if k in result["patient"])

update_operation = {"$set": update_data}
updated_result = collection.find_one_and_update({"_id": ObjectId(oid)}, update_operation, return_document=True)
if "_id" in data:
del data["_id"]
update_operation = {"$set": data}
updated_result = collection.find_one_and_update({"_id": ObjectId(oid)}, update_operation)

if updated_result:
return jsonify({"message": "Prescription updated successfully"}), 200

except Exception as e:
print("error", e)
return jsonify({"error": str(e)}), 500

return jsonify({"message": "An unexpected error occurred"}), 500
Expand Down
80 changes: 80 additions & 0 deletions frontend/src/components/AdminPrescription.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import React, { useEffect, useState } from "react";
import api from "../axiosConfig";

const AdminPrescription = ({ item }) => {
const [data, setData] = useState(item);

const fields = [
{ field: "Date", key: "date" },
{ field: "Patient Initials", key: "patient_initials" },
{ field: "Prescriber Code", key: "patient_email" },
{ field: "Comments", key: "comments" }
];

const handleChange = (e) => {
const newStatus = e.target.value;
data.status = newStatus;
data.patient.status = newStatus;
data.prescriber.status = newStatus;
setData(data);
console.log(data);
};

const updateLogStatus = async () => {
console.log("Trying:", data._id.$oid);
try {
const response = await api.post(`http://localhost:5001/api/update-prescription/${data._id.$oid}`, data);
console.log(response.data);

// const res = await fetch(`http://localhost:5001/`, {
// method: "POST",
// body: {
// targetUser: ,
// title: "Prescription Updated",
// message: "Your prescription was updated by admin"
// },
// });
// const resjson = response.json();
// if (resjson) {
// setTimeout(() => {
// window.location.reload();
// }, 50);
// }
} catch (error) {
console.error("UpdateError:",error);
}
};

return (
<>
<div></div>
<div className="flex left">
{data && (
<table id="patientPrescriptionTable" className="rounded-lg font-semibold w-5/6">
<tbody>
{fields.map(({ field, key }) => (
<tr key={key}>
<td className="w-1/2 px-1 align-top">{field}:</td>
<input defaultValue={data[key]} className="w-full px-2 rounded-sm bg-black/15" onChange={(e) => setData(prevData => ({ ...prevData, [key]: e.target.value }))}></input>
</tr>
))}
<tr>
<td>Status:</td>
<td>
{item.status && (item.status.includes("Complete") || item.status.includes("Both")) ? (<select value={item.status} className="w-full px-2 rounded-sm bg-black/15"
onChange={handleChange}>
<option value={data.status}>{data.status}</option>
{item.status !== "Complete with Discovery Pass"? <option value="Complete with Discovery Pass">Complete with Discovery Pass</option>:null}
{item.status !== "Both Logged With Discovery Pass"? <option value="Both Logged With Discovery Pass">Both Logged With Discovery Pass</option>:null}
</select>) : <div>{item.status}</div>} </td>
</tr>
</tbody>
</table>
)}
<div className="grid-cols-1 w-1/6"><button className="p-2 border-black border" onClick={() => updateLogStatus(item)}>Update</button></div>
</div>
</>
);
};

export default AdminPrescription;
71 changes: 31 additions & 40 deletions frontend/src/pages/AdminLogs.jsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import React, { useEffect, useState } from "react";
import PageHeader from "../components/PageHeader";
import pic from "../assets/prescribertable.jpg";
import api from "../axiosConfig";
import AdminPrescription from "../components/AdminPrescription";

const AdminLogs = () => {
const [data, setData] = useState(null);
const [shownData, setShownData] = useState(null);
const [searchInput, setSearchInput] = useState("");
const [notification, setNotification] = useState(null);
const [myItem, setItem] = useState(null);

// Other states and useEffects...
const [updatedItemDisplay, setUpdatedItemDisplay] = useState({});
Expand Down Expand Up @@ -46,6 +48,15 @@ const AdminLogs = () => {
fetchData();
}, [data, searchInput]);

const itemClick = (item) => {
if (myItem !== item) {
setItem(item);
}
else {
setItem(null);
}
};

async function filterData(data, filterString) {
if (!filterString) return data;

Expand Down Expand Up @@ -73,33 +84,6 @@ const AdminLogs = () => {
}));
};

const updateLogStatus = async (updatedItem) => {
const payload = {
date: updatedItem.date,
patient_initials: updatedItem.patient_initials,
prescriber_code: updatedItem.parx_code,
discoveryPass: updatedItem.discoveryPass,
};

// Filter out attributes with empty string values
const filteredPayload = Object.fromEntries(
Object.entries(payload).filter(([key, value]) => value !== '')
);

// Assuming this function does something with updatedItem, like sending it to an API
console.log("Updating item with the following details:", updatedItem);

// Update the state to display the updated item data
setUpdatedItemDisplay(payload);

try {
const response = await api.post(`http://localhost:5001/api/update-prescription/${updatedItem.oid.$oid}`, filteredPayload);
console.log(response.data);
} catch (error) {
console.error(error);
}
};


return (
<>
Expand Down Expand Up @@ -133,9 +117,9 @@ const AdminLogs = () => {
<>
<tr className="w-full text-left text-black border-t border-white odd:bg-white/60 even:text-white even:bg-[#0a0e1a]/40 hover: ">

<td><input data-key="date" type="text" id={`date-${index}`} className="px-2 py-3 bg-transparent placeholder:text-current" placeholder={item.date}></input></td>
<td><input data-key="patient_initials" type="text" id={`patient_initials-${index}`} className="px-2 py-3 placeholder:text-current bg-transparent" placeholder={item.patient_initials}></input></td>
<td><input data-key="parx_code" type="text" id={`parx_code-${index}`} className="px-2 py-3 placeholder:text-current bg-transparent" placeholder={item.prescriber_code}></input></td>
<td><div className="p-1">{item.date}</div></td>
<td><div className="p-1">{item.patient_initials}</div></td>
<td><div className="p-1">{item.prescriber_code}</div></td>

<td className="px-2 py-3 w-1/8">
<input
Expand All @@ -146,16 +130,16 @@ const AdminLogs = () => {
</td>
<select className="py-3 w-full truncate max-w-md text-current bg-transparent placeholder:text-gray-700">
<option selected value={item.status} disabled>{item.status}</option>
{item.status === "Both Logged With Discovery Pass" && (
<option value="Complete with Discovery Pass">Complete with Discovery Pass</option>
)}
{item.status === "Complete with Discovery Pass" && (
<option value="Both Logged With Discovery Pass">Both Logged With Discovery Pass</option>
)}

<option value="Complete with Discovery Pass">Complete with Discovery Pass</option>


<option value="Both Logged With Discovery Pass">Both Logged With Discovery Pass</option>

</select>
<td>
<button className="w-20 rounded hover:bg-slate-300 p-2 border border-opacity-30 border-black"
onClick={() => {
<button className="rounded hover:bg-slate-300 p-2 border border-opacity-30 border-black" onClick={() => itemClick(item)}>
{/* onClick={() => {
// Create an updated item object based on input values
const updatedItem = {
oid: item._id,
Expand All @@ -165,12 +149,19 @@ const AdminLogs = () => {
discoveryPass: checkboxStates[index] || false
};
updateLogStatus(updatedItem);

}}>
Update

</button>
</td>
</tr>
{/* Display the updated item data */}
{myItem === item && (<tr className="text-left text-black border-t border-white">
<td colSpan="6">
<AdminPrescription item={item} />
</td>
</tr>
)}
</>
))}
</tbody>
Expand Down
1 change: 1 addition & 0 deletions frontend/src/pages/PatientSettings.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import api from "../axiosConfig";

const PatientSettings = () => {
const [userData, setData] = useState(null);

const { user, updateUser } = useContext(UserContext);
const [newItem, setNewItem] = useState(user);

Expand Down

0 comments on commit 72a1493

Please sign in to comment.