Skip to content

Commit

Permalink
fix: admin edit accounts
Browse files Browse the repository at this point in the history
  • Loading branch information
daddygi committed Dec 15, 2023
1 parent b5c0848 commit dc5e603
Show file tree
Hide file tree
Showing 51 changed files with 12,358 additions and 209 deletions.
16 changes: 16 additions & 0 deletions backend/app/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ def get_all_users():
except mysql.connector.Error as err:
print(f"Error: {err}")


def get_user_by_id(user_id):
connection = get_db_connection(db_config)
if connection:
Expand All @@ -110,6 +111,9 @@ def get_user_by_id(user_id):
return result
except mysql.connector.Error as err:
print(f"Error fetching user by ID: {err}")
return None



def get_user_by_email_or_username(email_or_username):
connection = get_db_connection(db_config)
Expand Down Expand Up @@ -245,6 +249,18 @@ def get_reservations():
print(f"Error fetching reservations: {e}")
return jsonify(error='Error fetching reservations'), 500

@app.route('/api/get-all-users', methods=['GET'])
def get_all_users_route():
try:
all_users = get_all_users()
if all_users:
return jsonify({'accounts': all_users})
else:
return jsonify(error='No users found'), 404 # Change to 404 status code
except Exception as e:
print(f"Error in route: {e}")
return jsonify(error='Internal server error'), 500

@app.route('/api/sign-in', methods=['POST'])
def sign_in():
data = request.get_json()
Expand Down
168 changes: 168 additions & 0 deletions frontend/app/admin_accounts/[userId]/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
"use client";

import React, { useState, useEffect } from "react";
import Teste from "@/app/components/account";
import CloseIcon from "@mui/icons-material/Close";
import Image from "@/app/components/account_image";
import CircleIcon from "@mui/icons-material/Circle";
import TextInput from "@/app/components/text_input";
import Drop from "@/app/components/dropdown_button";
import Butt from "@/app/components/button";

import { useRouter } from "next/navigation";
function Page() {
const router = useRouter();

const handleBackButtonClick = () => {
router.back();
};

useEffect(() => {
document.title = "Edit Profile";
}, []);

const options = ["Male", "Female", "Others"];
const options1 = ["Student", "Worker"];

// Fetch user data from local storage
const storedUserData = localStorage.getItem("user");
const initialFormData = storedUserData ? JSON.parse(storedUserData) : null;

const [formData, setFormData] = useState<{
userName: string;
email: string;
phoneNumber: string;
gender: string;
occupation: string;
}>({
userName: initialFormData ? initialFormData.Username : "",
email: initialFormData ? initialFormData.Email : "",
phoneNumber: initialFormData ? initialFormData.PhoneNumber : "",
gender: initialFormData ? initialFormData.Gender : options[0],
occupation: initialFormData ? initialFormData.Occupation : options1[0],
});
const userId = initialFormData ? initialFormData.UserID : null; // Adjust this line based on your actual property name
console.log(userId);
const handleInputChange = (field: string, value: string) => {
setFormData({
...formData,
[field]: value,
});
};
console.log(formData);
const handleUpdateProfile = async () => {
try {
const response = await fetch(
`http://localhost:5000/api/update-account/${userId}`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(formData),
}
);

if (response.ok) {
const updatedUserData = await response.json();
localStorage.setItem("user", JSON.stringify(updatedUserData));
console.log("Profile updated successfully:", updatedUserData);
// Optionally, you can update the local state or perform other actions
} else {
console.error("Error updating profile:", await response.json());
}
} catch (error) {
console.error("Error updating profile:", error);
}
};

return (
<div className="flex min-h-full flex-col bg-backcolor">
<div className="flex items-center space-x-1">
<Teste
backButtonIcon={<CloseIcon style={{ fontSize: 24 }} />}
onBackButtonClick={handleBackButtonClick}
title=""
subTitle1=""
/>
<p className="text-xl text-textcolor font-extrabold">Edit Profile</p>
</div>

<div className="flex justify-center mt-5">
<Image
ImageIcon={<CircleIcon style={{ fontSize: 141, color: "#C7C7C7" }} />}
></Image>
</div>

<div>
<Butt
title="Edit"
Bgcolor="#E5E4E2"
width="100px"
height="28px"
borderRadius="50px"
/>
</div>

<div className="mt-6">
<TextInput
placeholder="Username"
width="335px"
height="35px"
value={formData.userName}
onInputChange={(value) => handleInputChange("userName", value)}
/>
<TextInput
placeholder="Email"
width="335px"
height="35px"
value={formData.email}
onInputChange={(value) => handleInputChange("email", value)}
/>
<TextInput
placeholder="Phone Number"
width="335px"
height="35px"
value={formData.phoneNumber}
onInputChange={(value) => handleInputChange("phoneNumber", value)}
/>

<div className="flex text-redwood text-xs ml-12 space-x-32 mt-2">
<p>Gender</p>
<p>Occupation</p>
</div>

<div className="flex justify-center space-x-3">
<Drop
options={options}
width="161px"
onSelect={(value) => handleInputChange("gender", value)}
/>
<Drop
options={options1}
width="161px"
onSelect={(value) => handleInputChange("occupation", value)}
/>
</div>
{/* <TextInput
placeholder="School/Company"
width="335px"
height="35px"
onInputChange={(value) => handleInputChange("school", value)}
/> */}
</div>

<div className="mt-16"></div>

<Butt
title="Update Profile"
Bgcolor="#FFF1E4"
width="325px"
height="34px"
onClick={handleUpdateProfile}
/>
</div>
);
}

export default Page;
61 changes: 38 additions & 23 deletions frontend/app/admin_accounts/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,43 +6,59 @@ import DateComponent from "../components/date";
import TimeComponent from "../components/time";
import SearchBar from "../components/search_bar";
import InfoTable from "../components/info_table";
import { useRouter } from "next/navigation";

type UserInfo = {
id: number;
name: string;
// Add more properties as needed
};
interface Accounts {
UserID: number;
Username: string;
}

function Page() {
const router = useRouter();
useEffect(() => {
// Set the title directly for the browser tab
document.title = "Admin Modify Accounts";
}, []);

const userData = [
{ id: 1, name: "John Doe" },
{ id: 2, name: "Jane Smith" },
{ id: 101, name: "Gian Limbaga" },
{ id: 102, name: "The Fourth" },
{ id: 103, name: "Melaissa Rioveros" },
{ id: 104, name: "Chen Leonor" },
{ id: 105, name: "Eric Ramos" },
// Add more user data as needed
];
const [accounts, setAccounts] = useState<Accounts[]>([]);
const [filteredData, setFilteredData] = useState<Accounts[]>(accounts);

const [data, setData] = useState<UserInfo[]>(userData);
const [filteredData, setFilteredData] = useState<UserInfo[]>(data);
useEffect(() => {
fetch("http://localhost:5000/api/get-all-users")
.then((response) => response.json())
.then((data: { accounts: Accounts[] }) => {
const simplifiedData = data.accounts.map(({ UserID, Username }) => ({
UserID,
Username,
}));
setAccounts(simplifiedData);
})
.catch((error) => {
console.error("Error fetching data:", error);
});
}, []);

useEffect(() => {
setFilteredData(accounts);
}, [accounts]);

// console.log(accounts);

const handleDataSearch = (searchQuery: string) => {
// Implement your filtering logic here
const filteredResults = data.filter(
const filteredResults = accounts.filter(
(item) =>
item.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
String(item.id).includes(searchQuery) // Convert id to string and check for inclusion
item.Username.toLowerCase().includes(searchQuery.toLowerCase()) ||
String(item.UserID).includes(searchQuery)
);

setFilteredData(filteredResults);
};
console.log(filteredData);
const handleEditClick = (userId: number) => {
// Navigate to the [id] folder
router.push(`/${userId}`);
};

return (
<div className="flex min-h-full flex-col bg-backcolor">
Expand Down Expand Up @@ -78,9 +94,8 @@ function Page() {
<Link href="/admin_sales">
<p>Sales Ledger</p>
</Link>
<Link href="/admin_accounts">
<p className="text-amber-500">Edit Accounts</p>
</Link>

<p className="text-amber-500">Edit Account</p>
</div>

<div className="container flex items-center justify-center space-x-8 text-xs text-black font-bold mb-2">
Expand Down
28 changes: 19 additions & 9 deletions frontend/app/components/info_table.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import Link from "next/link";
import React from "react";
import { useRouter } from "next/navigation";

type UserInfo = {
id: number;
name: string;
UserID: number;
Username: string;
// Add more properties as needed
};

Expand All @@ -12,6 +13,12 @@ type InfoProps = {
};

function InfoTable({ data }: InfoProps) {
const router = useRouter();

const handleEditClick = (userId: number) => {
// Navigate to the [id] folder
router.push(`/admin_accounts/${userId}`);
};
return (
<div className="overflow-x-auto">
<table className="min-w-full bg-white border border-gray-300">
Expand All @@ -25,14 +32,17 @@ function InfoTable({ data }: InfoProps) {
<tbody>
{data.map((item, index) => (
<tr key={index} className={index % 2 === 0 ? "bg-gray-100" : ""}>
<td className="py-2 px-4 border-b text-center">{item.id}</td>
<td className="py-2 px-4 border-b text-center">{item.name}</td>
<td className="py-2 px-4 border-b text-center">{item.UserID}</td>
<td className="py-2 px-4 border-b text-center">
{item.Username}
</td>
<td className="py-2 px-4 border-b text-center">
<Link href="/edit_profile">
<button className="bg-buttonpink text-parrot-pink py-1 px-2 rounded">
Modify
</button>
</Link>
<button
className="bg-buttonpink text-parrot-pink py-1 px-2 rounded"
onClick={() => handleEditClick(item.UserID)}
>
Modify
</button>
</td>
</tr>
))}
Expand Down
Loading

0 comments on commit dc5e603

Please sign in to comment.