diff --git a/inventory-manager/src/components/myorg/MyOrganizations.jsx b/inventory-manager/src/components/myorg/MyOrganizations.jsx index 07a4b19e0c345da0bd8932cc99d5511382e95c06..0137ae98a73a31a99569792d82dd8a26507bf8a8 100644 --- a/inventory-manager/src/components/myorg/MyOrganizations.jsx +++ b/inventory-manager/src/components/myorg/MyOrganizations.jsx @@ -2,10 +2,18 @@ import React, { useState, useEffect } from 'react'; import Axios from 'axios'; import './MyOrganization.css' import PropTypes from "prop-types"; -import {Link} from "react-router-dom"; +import {Link, useLocation} from "react-router-dom"; const MyOrganizations = ({ token }) => { const [organizations, setOrganizations] = useState([]); - + // if (token == null || token == undefined) + // const {token2} = useLocation(); + // token = token2; + const {state} = useLocation(); + if (token == null || token == undefined) + { + console.log('updated token to be token2'); + token = state.token2; + } useEffect(() => { const fetchOrganizations = async () => { try { @@ -15,6 +23,7 @@ const MyOrganizations = ({ token }) => { }); if (response.data.result === 'success') { + setOrganizations(response.data.data); } else { console.error('Error fetching organizations'); diff --git a/inventory-manager/src/components/myorg/OrganizationDetails.jsx b/inventory-manager/src/components/myorg/OrganizationDetails.jsx index 6d681cc9d129166c79411d4949c6b8e9feec5132..ef3b6b97687a475e5a8e4c6d30ccae6e87b88a56 100644 --- a/inventory-manager/src/components/myorg/OrganizationDetails.jsx +++ b/inventory-manager/src/components/myorg/OrganizationDetails.jsx @@ -34,6 +34,30 @@ const OrganizationDetails = ({token}) => { // Redirect to the OrganizationMembers page navigate(`/organizations/${orgId}/members`); }; + const handleLeaveButtonClick = async () => { + if (window.confirm(`Are you sure you want to leave the organization: ${organization.name}?`)) { + try { + const response = await Axios.put('http://localhost:8080/myorg/user/update', { + orgId: orgId, + jwt: token.jwt, + newtype: "DELETE", + memberEmail: "self" + }); + if (response.data.result === 'success') { + // window.location.reload(false); //refresh the page, remount component and render based on new perms + navigate(`/myorganizations`, {state: {token2: token}}); + } else { + console.log(response); + } + } catch (error) { + console.error('Error fetching organization members:', error); + navigate('/404'); + } + } else { + console.log("user clicked no, doing nothing"); + } + + } if (!organization) { return <div>Loading...</div>; } @@ -53,6 +77,7 @@ const OrganizationDetails = ({token}) => { <button className="blue-button">Requests</button> <button className="blue-button">Items</button> <button className="blue-button">Listings</button> + <button className="blue-button" onClick={handleLeaveButtonClick}>Leave Organization</button> </div> </div> ); diff --git a/inventory-manager/src/components/user/AccountInformation.jsx b/inventory-manager/src/components/user/AccountInformation.jsx index 2bd5ab093d5453eff25d4f3042091fab1eab29e3..4438c3ad3852a862cbdbcd94a7177047a115c686 100644 --- a/inventory-manager/src/components/user/AccountInformation.jsx +++ b/inventory-manager/src/components/user/AccountInformation.jsx @@ -21,7 +21,7 @@ const AccountInformation = ({ token }) => { const getUserInfo = async () => { try { - console.log(token); + // console.log(token); const response = await Axios.post("http://localhost:8080/user/user", { jwt: token.jwt, }); diff --git a/phase 1.sql b/phase 1.sql index 502f917e459c61b3a296acfd3a8749fc722795aa..e9e4a0aa18df2de6f7b91d6558da44c8b177a9f2 100644 --- a/phase 1.sql +++ b/phase 1.sql @@ -15,10 +15,9 @@ INSERT INTO USER (email, lname, fname, password, phone_number) VALUES ('alicedoe@example.com', 'Doe', 'Alice', 'securepass', '987-654-3210'), ('emilyjohnson@example.com', 'Johnson', 'Emily', 'sciencePass', '8888888888'); -SELECT * FROM USER; +# SELECT * FROM USER; -- DELETE FROM USER; -DROP TABLE ORGANIZATION; CREATE TABLE IF NOT EXISTS ORGANIZATION ( organization_id INT AUTO_INCREMENT, name VARCHAR(256) NOT NULL, @@ -38,7 +37,6 @@ INSERT INTO ORGANIZATION (name, email, description, owner_email, category, membe ('Political Discussion Group', 'politics@example.com', 'Discussions on current political affairs', 'alicedoe@example.com', 'POLITICS', 25), ('Greek Life Association', 'greeklife@example.com', 'Promoting Greek culture and traditions', 'emilyjohnson@example.com', 'GREEKLIFE', 40); -DROP TABLE ORGANIZATION_ROSTER; CREATE TABLE IF NOT EXISTS ORGANIZATION_ROSTER ( roster_id INT AUTO_INCREMENT NOT NULL, user_email VARCHAR(128) NOT NULL, @@ -60,10 +58,10 @@ VALUES ('alicedoe@example.com', 5, 'MEMBER'), ('emilyjohnson@example.com', 2, 'MEMBER'); -INSERT INTO ORGANIZATION_ROSTER(user_email, organization_id, type) -VALUES - ('johnsmith@example.com', 2, 'MEMBER'), - ('emilyjohnson@example.com', 2, 'MANAGER'); +# INSERT INTO ORGANIZATION_ROSTER(user_email, organization_id, type) +# VALUES +# ('johnsmith@example.com', 2, 'MEMBER'), +# ('emilyjohnson@example.com', 2, 'MANAGER'); UPDATE ORGANIZATION o SET member_count = ( @@ -71,17 +69,17 @@ SET member_count = ( FROM ORGANIZATION_ROSTER WHERE organization_id = o.organization_id ) -WHERE member_count != o.member_count; +WHERE true; -SELECT * FROM ORGANIZATION_ROSTER WHERE ORGANIZATION_ROSTER.user_email LIKE 'emilyjohnson@example.com'; -SELECT DISTINCT o.* -FROM ORGANIZATION o - JOIN ORGANIZATION_ROSTER r ON o.organization_id = r.organization_id -WHERE r.user_email = 'emilyjohnson@example.com' - OR o.owner_email = 'emilyjohnson@example.com'; +# SELECT DISTINCT o.* +# FROM ORGANIZATION o +# JOIN ORGANIZATION_ROSTER r ON o.organization_id = r.organization_id +# WHERE r.user_email = 'emilyjohnson@example.com' +# OR o.owner_email = 'emilyjohnson@example.com'; +# DROP TABLE REQUEST; DROP TABLE FAVORITE; DROP TABLE LISTING; DROP TABLE ITEM; DROP TABLE LOCATION; CREATE TABLE IF NOT EXISTS REQUEST ( request_id INT AUTO_INCREMENT NOT NULL, user_email VARCHAR(128) NOT NULL, diff --git a/src/main/java/com/example/accessingdatamysql/myorg/MyOrgRosterRepository.java b/src/main/java/com/example/accessingdatamysql/myorg/MyOrgRosterRepository.java index 4e2921f0fe2fa4eb791811a24bc5ae332fb75e17..98df3043e093e8e81c196874bfc46d11b274e600 100644 --- a/src/main/java/com/example/accessingdatamysql/myorg/MyOrgRosterRepository.java +++ b/src/main/java/com/example/accessingdatamysql/myorg/MyOrgRosterRepository.java @@ -104,6 +104,75 @@ public class MyOrgRosterRepository implements OrgRosterRepository{ return result; } + @Transactional + public Map<String, Object> promoteRandom(Integer orgId) { + Map<String, Object> result = new HashMap<>(); + + try { + // Get the count of managers for the organization + Long managerCount = entityManager.createQuery( + "SELECT COUNT(*) FROM OrganizationRoster r WHERE r.organizationId = :orgId AND r.type = 'MANAGER'", + Long.class + ) + .setParameter("orgId", orgId) + .getSingleResult(); + + if (managerCount > 0) { + // Promote a random manager to owner + String promoteManagerQuery = "UPDATE organization_roster SET type = 'OWNER' WHERE organization_id = :orgId AND type = 'MANAGER' ORDER BY RAND() LIMIT 1"; + Query promoteManagerNativeQuery = entityManager.createNativeQuery(promoteManagerQuery); + promoteManagerNativeQuery.setParameter("orgId", orgId); + + int updatedRows = promoteManagerNativeQuery.executeUpdate(); + + if (updatedRows > 0) { + // Update owner_email in Organization table + String updateOwnerEmailQuery = "UPDATE organization SET owner_email = (SELECT user_email FROM organization_roster WHERE organization_id = :orgId AND type = 'OWNER') WHERE organization_id = :orgId"; + Query updateOwnerEmailNativeQuery = entityManager.createNativeQuery(updateOwnerEmailQuery); + updateOwnerEmailNativeQuery.setParameter("orgId", orgId); + + int updatedOwnerEmailRows = updateOwnerEmailNativeQuery.executeUpdate(); + + result.put("result", "success"); + result.put("message", "Random manager promoted to owner"); + result.put("updatedOwnerEmailRows", updatedOwnerEmailRows); + } else { + result.put("result", "failure"); + result.put("error", "No manager found to promote"); + } + } else { + // Promote a random member to owner + String promoteMemberQuery = "UPDATE organization_roster SET type = 'OWNER' WHERE organization_id = :orgId AND type = 'MEMBER' ORDER BY RAND() LIMIT 1"; + Query promoteMemberNativeQuery = entityManager.createNativeQuery(promoteMemberQuery); + promoteMemberNativeQuery.setParameter("orgId", orgId); + + int updatedRows = promoteMemberNativeQuery.executeUpdate(); + + if (updatedRows > 0) { + // Update owner_email in Organization table + String updateOwnerEmailQuery = "UPDATE organization SET owner_email = (SELECT user_email FROM organization_roster WHERE organization_id = :orgId AND type = 'OWNER') WHERE organization_id = :orgId"; + Query updateOwnerEmailNativeQuery = entityManager.createNativeQuery(updateOwnerEmailQuery); + updateOwnerEmailNativeQuery.setParameter("orgId", orgId); + + int updatedOwnerEmailRows = updateOwnerEmailNativeQuery.executeUpdate(); + + result.put("result", "success"); + result.put("message", "Random member promoted to owner"); + result.put("updatedOwnerEmailRows", updatedOwnerEmailRows); + } else { + result.put("result", "failure"); + result.put("error", "No member found to promote"); + } + } + } catch (Exception e) { + result.put("result", "failure"); + result.put("error", e.getMessage()); + } + + return result; + } + + @Transactional public Map<String, Object> deleteMember(Integer orgId, String memberEmail) { diff --git a/src/main/java/com/example/accessingdatamysql/myorg/OrgRosterController.java b/src/main/java/com/example/accessingdatamysql/myorg/OrgRosterController.java index 006a5e6b2d18c008299e8e7ae0e657a50cbf589c..025601fe513caabad99015e712e8deec0f37eb00 100644 --- a/src/main/java/com/example/accessingdatamysql/myorg/OrgRosterController.java +++ b/src/main/java/com/example/accessingdatamysql/myorg/OrgRosterController.java @@ -62,7 +62,7 @@ public class OrgRosterController { public @ResponseBody Map<String, Object> getUserOrg(@RequestBody Map<String, Object> json) { Map<String, Object> response = new HashMap<>(); - System.out.println(json.get("orgId")); +// System.out.println(json.get("orgId")); if (!json.containsKey("orgId")) { response.put("result", "failed = no orgId provided bad request"); @@ -98,7 +98,7 @@ public class OrgRosterController { result.put("result", "success"); result.put("type", map.get("type")); //tell the client what type this user is so they can render buttons for the roster result.put("userEmail", map.get("userEmail")); - System.out.println(map.get("orgId")); +// System.out.println(map.get("orgId")); if (json.get("orgId") instanceof Integer) result.put("roster", myOrgRosterRepository.getRoster((Integer) json.get("orgId"))); else @@ -113,7 +113,7 @@ public class OrgRosterController { public @ResponseBody Map<String, Object> updateUser(@RequestBody Map<String, Object> json) { Map<String, Object> result = new HashMap<>(); - System.out.println(json.entrySet()); +// System.out.println(json.entrySet()); if (!json.containsKey("orgId") || !json.containsKey("newtype") || !json.containsKey("jwt") || !json.containsKey("memberEmail")) { System.out.println("thought there were wrong headers"); @@ -133,9 +133,23 @@ public class OrgRosterController { { orgId = Integer.parseInt((String)json.get("orgId")); } - System.out.println(map.get("type")); - System.out.println(map.get("type").getClass()); - if (map.get("type") == OrganizationRoster.Type.OWNER) + String userEmail = (String)map.get("userEmail"); + System.out.println(json.entrySet()); + if ("self".equals((String)(json.get("memberEmail"))) && json.get("newtype").equals("DELETE")) + { + System.out.println("In the self removal case"); + //basically if the user tries to remove themselves from the organization + result.put("data", myOrgRosterRepository.deleteMember(orgId, userEmail)); + //above, remove the user + if (map.get("type") == OrganizationRoster.Type.OWNER) + { + //we need to promote an existing member to owner + result.put("data", myOrgRosterRepository.promoteRandom(orgId)); + } + result.put("result", "success"); + return result; + } + else if (map.get("type") == OrganizationRoster.Type.OWNER) { if (json.get("newtype").equals("MANAGER") || json.get("newtype").equals("MEMBER")) {