first backend integration

This commit is contained in:
idittrich-valueon 2025-05-14 12:39:45 +02:00
parent b5f1d8afa9
commit 59018ece4e
78 changed files with 1274 additions and 4026 deletions

View file

@ -1,15 +1,11 @@
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import { ProtectedRoute } from "./auth/ProtectedRoute";
import Login from './pages/Login';
import Register from './pages/Register';
import { AuthProvider } from './auth/auth-provider';
import { ProtectedRoute } from './auth/ProtectedRoute';
import Home from './pages/Home';
import Dashboard from './pages/Home/Dashboard/Dashboard';
import { AuthProvider } from './auth/Hooks/auth-provider';
import RegisterOrganisation from './pages/Register/RegisterOrganisation';
import RegisterPricing from './pages/Register/RegisterPricing';
import RegisterSummary from './pages/Register/RegisterSummary';
import Mitglieder from './pages/Home/Mitglieder/Mitglieder';
import Organisation from './pages/Home/Organisation/Organisation';
import Dateien from './pages/Home/Dateien/Dateien';
function App() {
return (
@ -18,22 +14,12 @@ function App() {
<Routes>
{/* Public route */}
<Route path="/login" element={<Login />} />
<Route path="/register-organisation" element={<RegisterOrganisation />} />
<Route path="/register-pricing" element={<RegisterPricing />} />
<Route path="/register-summary" element={<RegisterSummary />} />
{/* Protected routes */}
<Route path="/register" element={<Register />} />
<Route path="/" element={
<ProtectedRoute>
<Home />
</ProtectedRoute>
}>
{/* Child route of Home - note the relative path */}
<Route path="dashboard" element={<Dashboard />} />
<Route path="dateien" element={<Dateien />} />
<Route path="mitglieder" element={<Mitglieder />} />
<Route path="organisation" element={<Organisation />} />
</Route>
}></Route>
</Routes>
</Router>
</AuthProvider>

View file

@ -1,126 +1,44 @@
// api.ts
import axios from 'axios';
const API_URL = import.meta.env?.VITE_API_URL || 'http://127.0.0.1:8000';
const api = axios.create({
baseURL: API_URL,
headers: {
'Content-Type': 'application/json',
},
baseURL: 'http://127.0.0.1:8000',
withCredentials: true
});
export async function authorizedGet(endpoint: string, getToken: () => Promise<string>) {
try {
const token = await getToken();
// Ensure that token is not null or undefined
if (!token) {
throw new Error("No token found");
// Add a request interceptor to add the auth token
api.interceptors.request.use(
(config) => {
const authData = localStorage.getItem('auth_data');
if (authData) {
try {
const { accessToken, tokenType } = JSON.parse(authData);
if (accessToken) {
config.headers.Authorization = `${tokenType} ${accessToken}`;
}
} catch (error) {
console.error('Error parsing auth data:', error);
}
}
const response = await api.get(endpoint, {
headers: {
Authorization: `Bearer ${token}`,
},
});
return response; // Axios already wraps the response, no need to call .data here
} catch (err) {
console.error("API request failed:", err);
throw err;
return config;
},
(error) => {
return Promise.reject(error);
}
}
);
export async function authorizedDelete(endpoint: string, getToken: () => Promise<string>) {
try {
const token = await getToken();
// Ensure that token is not null or undefined
if (!token) {
throw new Error("No token found");
// Add a response interceptor to handle token expiration
api.interceptors.response.use(
(response) => response,
async (error) => {
if (error.response?.status === 401) {
// Clear invalid token
localStorage.removeItem('auth_data');
// Redirect to login
window.location.href = '/login';
}
const response = await api.delete(endpoint, {
headers: {
Authorization: `Bearer ${token}`,
},
});
return response; // Axios already wraps the response, no need to call .data here
} catch (err) {
console.error("API request failed:", err);
throw err;
return Promise.reject(error);
}
}
export async function authorizedPut(endpoint: string, data: any, getToken: () => Promise<string>) {
try {
const token = await getToken();
// Ensure that token is not null or undefined
if (!token) {
throw new Error("No token found");
}
const response = await api.put(endpoint, data, {
headers: {
Authorization: `Bearer ${token}`,
},
});
return response;
} catch (err) {
console.error("API request failed:", err);
throw err;
}
}
export async function authorizedPost(endpoint: string, getToken: () => Promise<string>, data: any) {
try {
const token = await getToken();
// Ensure that token is not null or undefined
if (!token) {
throw new Error("No token found");
}
const response = await api.post(endpoint, data, {
headers: {
Authorization: `Bearer ${token}`,
},
});
return response;
} catch (err) {
console.error("API request failed:", err);
throw err;
}
}
export async function downloadFile(fileId: number, getToken: () => Promise<string>) {
try {
const token = await getToken();
if (!token) {
throw new Error("No token found");
}
const response = await api.get(`/api/user/files/${fileId}/download`, {
headers: {
Authorization: `Bearer ${token}`,
},
responseType: 'blob', // Important for file downloads
});
// Create a blob URL and trigger download
const blob = new Blob([response.data]);
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = response.headers['content-disposition']?.split('filename=')[1] || 'download';
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
return response;
} catch (err) {
console.error("File download failed:", err);
throw err;
}
}
);
export default api;

View file

@ -1,14 +0,0 @@
import { authorizedDelete } from "../../api";
async function deleteUser(userId: string, token: string): Promise<void> {
try {
const response = await authorizedDelete(`/api/user/${userId}`, async () => token);
// You can add additional handling here if needed
console.log("User deleted successfully:", response.status);
} catch (error) {
console.error("Failed to delete user:", error);
throw error;
}
}
export default deleteUser;

View file

@ -1,42 +0,0 @@
import { useEffect, useState } from 'react';
import { authorizedGet } from '../../api';
import { useAuthToken } from './use-auth-token';
type User = {
id: string;
name: string;
azure_id: string;
created_at: string;
role: string;
email: string;
phone: string;
position: string;
};
export const useOrgUsers = () => {
const [users, setUsers] = useState<User[]>([]);
const [loading, setLoading] = useState<boolean>(true);
const [error, setError] = useState<string | null>(null);
const { getToken } = useAuthToken();
const fetchUsers = async () => {
setLoading(true);
setError(null);
try {
const response = await authorizedGet("/api/organisation/users", getToken);
console.log(response)
setUsers(response.data)
} catch (err) {
setError("Failed to fetch users");
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchUsers();
}, []);
return { users, loading, error, refetch: fetchUsers };
};

View file

@ -1,39 +0,0 @@
// src/hooks/useAuthToken.ts
import { useMsal } from "@azure/msal-react";
import { useCallback } from "react";
import { InteractionRequiredAuthError } from "@azure/msal-browser";
const tokenRequest = {
scopes: ["api://24cd6c8a-b592-4905-a5ba-d5fa9f911154/user_impersonation"], // Adjust scopes as needed
};
export function useAuthToken() {
const { instance, accounts } = useMsal();
const getToken = useCallback(async () => {
if (accounts.length === 0) throw new Error("No signed-in account found");
try {
const response = await instance.acquireTokenSilent({
...tokenRequest,
account: accounts[0],
});
return response.accessToken;
} catch (err: any) {
if (err instanceof InteractionRequiredAuthError) {
console.warn("Silent token failed, redirecting for interactive login...");
// Trigger full-page redirect to login
instance.acquireTokenRedirect({
...tokenRequest,
account: accounts[0], // you might omit this if it's undefined
});
return ""; // won't reach this anyway
}
console.error("Token acquisition failed unexpectedly:", err);
throw err;
}
}, [instance, accounts]);
return { getToken };
}

View file

@ -1,30 +0,0 @@
import { useMsal } from "@azure/msal-react";
import { useState } from "react";
import { loginRequest } from "../auth-config";
export const useMsalLogin = () => {
const { instance } = useMsal();
const [isLoggingIn, setIsLoggingIn] = useState(false);
const [error, setError] = useState<null | string>(null);
const login = async () => {
setIsLoggingIn(true);
setError(null);
try {
console.log("Starting login process...");
await instance.loginPopup(loginRequest); // or loginRedirect
console.log("Login successful");
} catch (err: any) {
console.error("Login failed:", err);
setError(err?.message || "Login failed");
} finally {
setIsLoggingIn(false);
}
};
return {
login,
isLoggingIn,
error,
};
};

View file

@ -1,41 +0,0 @@
import { useEffect, useState } from 'react';
import { authorizedGet } from '../../api';
import { useAuthToken } from './use-auth-token';
type File = {
id: number;
file_name: string;
action: string;
user_id: number;
prompt_id: number;
meta_data: Record<string, any> | null;
created_at: string;
};
export const useUserFiles = () => {
const [files, setFiles] = useState<File[]>([]);
const [loading, setLoading] = useState<boolean>(true);
const [error, setError] = useState<string | null>(null);
const { getToken } = useAuthToken();
const fetchFiles = async () => {
setLoading(true);
setError(null);
try {
const response = await authorizedGet("/api/user/files", getToken);
setFiles(response.data);
} catch (err) {
setError("Failed to fetch files");
console.error("Error fetching files:", err);
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchFiles();
}, []);
return { files, loading, error, refetch: fetchFiles };
};

View file

@ -1,33 +0,0 @@
import { useMsal } from "@azure/msal-react";
interface UserInfo {
name?: string;
email?: string;
oid?: string;
tenantId?: string;
rawClaims?: Record<string, any>;
}
export const useUserInfo = (): UserInfo => {
const { instance } = useMsal();
const account = instance.getActiveAccount();
if (!account) return {};
const idTokenClaims = account.idTokenClaims as {
name?: string;
preferred_username?: string;
email?: string;
oid?: string;
tid?: string;
[key: string]: any;
};
return {
name: idTokenClaims?.name,
email: idTokenClaims?.email || idTokenClaims?.preferred_username,
oid: idTokenClaims?.oid,
tenantId: idTokenClaims?.tid,
rawClaims: idTokenClaims,
};
};

View file

@ -1,41 +0,0 @@
import { useEffect, useState } from 'react';
import { authorizedGet } from '../../api';
import { useAuthToken } from './use-auth-token';
type Prompt = {
id: string;
user_id: string;
prompt_title: string;
workflow_manager_plan: string;
result: string;
created_at: string;
user_prompt: string;
};
export const useUserPrompts = () => {
const [prompts, setPrompts] = useState<Prompt[]>([]);
const [loading, setLoading] = useState<boolean>(true);
const [error, setError] = useState<string | null>(null);
const { getToken } = useAuthToken();
const fetchPrompts = async () => {
setLoading(true);
setError(null);
try {
const response = await authorizedGet("/api/user/prompts", getToken);
setPrompts(response.data);
} catch (err) {
setError("Failed to fetch prompts");
console.error("Error fetching prompts:", err);
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchPrompts();
}, []);
return { prompts, loading, error, refetch: fetchPrompts };
};

View file

@ -14,24 +14,59 @@ export const ProtectedRoute = ({
const { accounts } = useMsal();
const location = useLocation();
const [isChecking, setIsChecking] = useState(true);
const [isAuthenticated, setIsAuthenticated] = useState(false);
useEffect(() => {
// Give a small delay to ensure MSAL is fully initialized
const checkAuthentication = async () => {
try {
// Check for MSAL authentication
const hasMsalAccount = accounts.length > 0;
// Check for backend token
const authData = localStorage.getItem('auth_data');
let hasBackendToken = false;
if (authData) {
try {
const parsedAuthData = JSON.parse(authData);
hasBackendToken = !!parsedAuthData.accessToken;
} catch (e) {
console.error('Error parsing auth data:', e);
}
}
// User is authenticated if either method is valid
setIsAuthenticated(hasMsalAccount || hasBackendToken);
if (hasBackendToken) {
console.log('Authenticated with backend token');
} else if (hasMsalAccount) {
console.log('Authenticated with MSAL');
}
} catch (error) {
console.error('Error checking authentication:', error);
setIsAuthenticated(false);
} finally {
setIsChecking(false);
}
};
// Small delay to ensure MSAL is initialized
const timer = setTimeout(() => {
setIsChecking(false);
checkAuthentication();
}, 100);
return () => clearTimeout(timer);
}, []);
}, [accounts]);
// If still checking, show loading
if (isChecking) {
return <div>Checking authentication...</div>;
}
// Check if user is authenticated
if (accounts.length === 0) {
console.log("No accounts found, redirecting to login");
// Check if user is authenticated through either method
if (!isAuthenticated) {
console.log("No valid authentication found, redirecting to login");
return <Navigate to={redirectPath} state={{ from: location }} replace />;
}

View file

@ -4,7 +4,7 @@ import {
PublicClientApplication,
InteractionStatus
} from "@azure/msal-browser";
import { msalConfig } from "../auth-config";
import { msalConfig } from "./auth-config";
import { MsalProvider } from "@azure/msal-react";
import { ReactNode, useEffect, useState } from "react";

View file

@ -1,51 +0,0 @@
.dashboard_prompt {
display: flex;
padding: 20px;
flex-direction: column;
align-self: stretch;
border-radius: 30px;
border: 1px solid var(--f-1-f-1-f-1, #F1F1F1);
background: var(--Grayscale-True-White, #FFF);
position: relative;
box-shadow: 0px 2px 6px 0px rgba(194, 194, 194, 0.10);
height: 100%;
}
.prompt_button_div {
display: flex;
align-self: stretch;
gap: 30px;
}
.prompt_button {
text-align: center;
font-size: 14px;
font-style: normal;
font-weight: 500;
line-height: normal;
border: none;
background: none;
outline: none;
color: var(--Grayscale-Black, #24262B);
}
.prompt_button_inactive {
opacity: 50%;
}
.horizontalLine {
width: 100%;
background-color: black;
height: 2px;
margin-top: 19px;
}
.horizontalLineLight {
width: calc(100%);
background-color: #F1F1F1;
height: 2px;
margin-top: 39px;
margin-left: -20px;
position: absolute;
}

View file

@ -1,48 +0,0 @@
import React, { useState, useEffect } from "react";
import { useSearchParams } from "react-router-dom";
import DashboardPromptArea from './DashboardPromptArea/DashboardPromptArea';
import DashboardPromptSet from './DashboardPromptSet/DashboardPromptSet';
import styles from './DashboardPrompt.module.css';
const DashboardPrompt: React.FC = () => {
const [activeTab, setActiveTab] = useState("Prompt Area");
const [searchParams] = useSearchParams();
useEffect(() => {
// If there's an expandedPrompt parameter, switch to the Prompt Set tab
const expandedPrompt = searchParams.get('expandedPrompt');
const promptId = searchParams.get('promptId');
if (expandedPrompt) {
setActiveTab("Prompt Set");
} else if (promptId) {
setActiveTab("Prompt Area");
}
}, [searchParams]);
return (
<div className={ styles.dashboard_prompt }>
<div className={ styles.prompt_button_div }>
{["Prompt Area", "Prompt Set"].map((tab) => (
<div key={tab} className={styles.buttonWrapper}>
<button
key={tab}
className={`${styles.prompt_button} ${activeTab === tab ? styles.prompt_button_active : styles.prompt_button_inactive}`}
onClick={()=> setActiveTab(tab)} >
{ tab }
</button>
{activeTab === tab && <div className={styles.horizontalLine}></div>}
</div>
))}
</div>
<div className={styles.horizontalLineLight}></div>
<div>
{activeTab === "Prompt Area" ? <DashboardPromptArea /> : <DashboardPromptSet />}
</div>
</div>
)
}
export default DashboardPrompt;

View file

@ -1,37 +0,0 @@
.promptArea {
display: flex;
flex-direction: column;
height: 100%;
position: relative;
}
.cancelContainer {
position: absolute;
top: 10px;
right: 10px;
z-index: 10;
}
.cancelButton {
display: flex;
align-items: center;
gap: 4px;
padding: 8px 16px;
background: white;
border: 1px solid #ddd;
border-radius: 20px;
color: #666;
font-size: 14px;
cursor: pointer;
transition: all 0.2s;
font-family: Arial, Helvetica, sans-serif;
}
.cancelButton:hover {
background-color: #f5f5f5;
border-color: #ccc;
}
.cancelIcon {
font-size: 16px;
}

View file

@ -1,69 +0,0 @@
import { useState, useRef } from "react";
import { useSearchParams, useNavigate } from "react-router-dom";
import DashboardPromptAreaMessage from './DashboardPromptAreaMessage';
import DashboardPromptAreaChat from './DashboardPromptAreaChat';
import { useAuthToken } from "../../../auth/Hooks/use-auth-token";
import { authorizedGet } from "../../../api";
import styles from './DashboardPromptArea.module.css';
import { IoClose } from 'react-icons/io5';
function DashboardPromptArea() {
const [messages, setMessages] = useState<any[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [searchParams] = useSearchParams();
const navigate = useNavigate();
const messagesEndRef = useRef<HTMLDivElement | null>(null);
const { getToken } = useAuthToken();
const handleCancel = () => {
navigate('/dashboard');
};
const fetchMessages = async () => {
setLoading(true);
setError(null);
try {
const response = await authorizedGet("/api/messages/", getToken);
setMessages(response.data);
} catch (err) {
console.error("Error fetching messages:", err);
setError("Failed to fetch messages");
} finally {
setLoading(false);
}
};
const addMessage = (newMessage: any) => {
setMessages((prevMessages) => [...prevMessages, newMessage]);
};
return (
<div className={styles.promptArea}>
{searchParams.get('promptId') && (
<div className={styles.cancelContainer}>
<button
className={styles.cancelButton}
onClick={handleCancel}
title="Cancel prompt"
>
<IoClose className={styles.cancelIcon} />
Cancel
</button>
</div>
)}
<DashboardPromptAreaChat
messages={messages}
loading={loading}
error={error}
fetchMessages={fetchMessages}
/>
<DashboardPromptAreaMessage
addMessage={addMessage}
/>
<div ref={messagesEndRef} />
</div>
);
}
export default DashboardPromptArea;

View file

@ -1,29 +0,0 @@
.messages_container {
display: flex;
flex-direction: column;
align-items: flex-start; /* Align messages to the left */
width: 100%;
padding: 10px;
width: calc(100% - 40px);
height: calc(100% - 100px);
overflow-y: auto;
margin-bottom: 12px;
}
.message_item {
margin-bottom: 10px;
}
.message_content {
display: inline-block; /* Ensures the div is only as wide as the message content */
background-color: var(--Grayscale-Light-Gray, #F9F9F9); /* Background color for the message */
padding: 9px 14px;
border-radius: 10px; /* Optional: for rounded corners */
color: #000;
font-family: Arial, Helvetica, sans-serif;
font-size: 12px;
font-style: normal;
font-weight: 400;
line-height: normal;
}

View file

@ -1,169 +0,0 @@
import React, { useEffect, useState } from "react";
import { useSearchParams } from "react-router-dom";
import { useAuthToken } from "../../../auth/Hooks/use-auth-token";
import styles from "./DashboardPromptAreaChat.module.css";
function DashboardPromptAreaChat({ messages: propMessages, loading: propLoading, error: propError }: any) {
const [messages, setMessages] = useState<any[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [searchParams] = useSearchParams();
const { getToken } = useAuthToken();
const promptId = searchParams.get('promptId');
const promptText = searchParams.get('promptText');
useEffect(() => {
const fetchResponse = async () => {
if (promptId && promptText) {
setLoading(true);
setError(null);
// Initialize with the user's prompt
setMessages([{
id: promptId,
content: promptText,
created_at: new Date().toISOString(),
type: 'user'
}]);
try {
const token = await getToken();
if (!token) {
throw new Error('No authentication token available');
}
console.log('Making request with token:', token);
const response = await fetch(
`http://localhost:8000/api/prompts/?promptText=${encodeURIComponent(promptText)}`,
{
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`,
'Accept': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
}
}
);
console.log('Response status:', response.status);
console.log('Response headers:', Object.fromEntries(response.headers.entries()));
if (!response.ok) {
const errorText = await response.text();
console.error('Error response:', errorText);
throw new Error(`HTTP error! status: ${response.status}, message: ${errorText}`);
}
const reader = response.body?.getReader();
if (!reader) {
throw new Error('No reader available');
}
let fullContent = '';
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
// Convert the Uint8Array to a string
const chunk = new TextDecoder().decode(value);
console.log('Received chunk:', chunk);
buffer += chunk;
// Process complete SSE messages
const lines = buffer.split('\n\n');
buffer = lines.pop() || ''; // Keep the last incomplete chunk in the buffer
for (const line of lines) {
if (line.startsWith('data: ')) {
try {
const jsonStr = line.slice(6); // Remove 'data: ' prefix
console.log('Processing SSE data:', jsonStr);
const data = JSON.parse(jsonStr);
if (data.content) {
fullContent += data.content;
// Update the message with the accumulated content
setMessages(prevMessages => {
const lastMessage = prevMessages[prevMessages.length - 1];
if (lastMessage && lastMessage.type === 'assistant') {
return [
...prevMessages.slice(0, -1),
{
...lastMessage,
content: fullContent
}
];
} else {
return [
...prevMessages,
{
id: `${promptId}-response`,
content: fullContent,
created_at: new Date().toISOString(),
type: 'assistant'
}
];
}
});
}
} catch (err) {
console.error('Error parsing SSE data:', err, 'Raw line:', line);
}
}
}
}
} catch (err) {
console.error('Error in fetchResponse:', err);
setError(err instanceof Error ? err.message : 'Failed to connect to server');
} finally {
setLoading(false);
}
} else if (propMessages) {
// Use messages from props if no prompt is being processed
setMessages(propMessages);
setLoading(propLoading);
setError(propError);
} else {
setLoading(false);
}
};
fetchResponse();
}, [promptId, promptText, propMessages, propLoading, propError]);
return (
<div className={styles.messages_container}>
{loading ? (
<div className="loading-indicator">
<p>Loading messages...</p>
</div>
) : error ? (
<div className="error-message">
<p>Error: {error}</p>
</div>
) : (
<>
{messages && messages.length > 0 ? (
<div className={styles.message_list}>
{messages.map((message: any) => (
<div key={message.id} className={styles.message_item}>
<div className={styles.message_content}>
{message.content}
</div>
</div>
))}
</div>
) : (
<p className="no-messages">No messages found.</p>
)}
</>
)}
</div>
);
}
export default DashboardPromptAreaChat;

View file

@ -1,27 +0,0 @@
.messageField {
display: flex;
height: 70px;
width: 100%;
border-radius: 12px;
border: 1px solid var(--f-1-f-1-f-1, #F1F1F1);
}
.inputField {
height: 70px;
padding: 15px 24px 0 15px;
width: calc(100% - 40px);
color: #000;
font-size: 12px;
font-style: normal;
font-weight: 400;
opacity: 0.4;
resize: none;
overflow: hidden;
font-family: Helvetica;
border: none;
}
.inputButton {
height: 40px;
width: 40px;
}

View file

@ -1,71 +0,0 @@
import React, { useState } from "react";
import { useAuthToken } from "../../../auth/Hooks/use-auth-token";
import api from "../../../api";
import styles from "./DashboardPromptAreaMessage.module.css";
interface DashboardPromptAreaMessageProps {
addMessage: (newMessage: any) => void;
}
function DashboardPromptAreaMessage({ addMessage }: DashboardPromptAreaMessageProps) {
const [message, setMessage] = useState("");
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const { getToken } = useAuthToken();
const sendMessage = async () => {
if (!message.trim()) return;
setLoading(true);
setError("");
try {
const token = await getToken();
const response = await api.post(
'/api/messages/create',
{ content: message.trim() },
{
headers: {
Authorization: `Bearer ${token}`,
},
}
);
addMessage(response.data);
setMessage("");
} catch (error: unknown) {
console.error("Error sending message:", error);
if (error instanceof Error) {
setError(`Error: ${error.message}`);
} else {
setError("An unexpected error occurred");
}
} finally {
setLoading(false);
}
};
return (
<div className={styles.messageField}>
<textarea
placeholder="Ask a question or make a request..."
value={message}
onChange={(e) => setMessage(e.target.value)}
disabled={loading}
className={styles.inputField}
/>
<button
onClick={sendMessage}
disabled={loading || !message.trim()}
className={styles.inputButton}
>
{loading ? "Sending message..." : "Send"}
</button>
{error && <div className="error">{error}</div>}
</div>
);
}
export default DashboardPromptAreaMessage;

View file

@ -1,218 +0,0 @@
.container {
width: 100%;
padding-top: 20px;
position: relative;
}
.promptList {
width: 100%;
max-width: 100%;
}
.promptCard {
background: white;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
margin-bottom: 12px;
overflow: hidden;
width: 100%;
will-change: transform, opacity;
}
.promptHeader {
display: flex;
align-items: center;
padding: 10px;
background: #f8f9fa;
gap: 8px;
width: 100%;
box-sizing: border-box;
}
.expandButton {
background: none;
border: none;
cursor: pointer;
padding: 4px;
color: #666;
display: flex;
align-items: center;
justify-content: center;
min-width: 24px;
flex-shrink: 0;
outline: none;
}
.expandButton:hover {
color: #333;
}
.promptTitle {
margin: 0;
flex-grow: 1;
font-size: 12pt;
font-weight: 550;
color: var(--Grayscale-Black, #24262B);
font-family: Arial, Helvetica, sans-serif;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.actionButtons {
display: flex;
gap: 4px;
margin-left: auto;
flex-shrink: 0;
}
.iconButton {
background: none;
border: none;
cursor: pointer;
padding: 6px;
color: #666;
border-radius: 4px;
transition: all 0.2s;
display: flex;
align-items: center;
justify-content: center;
min-width: 28px;
height: 28px;
outline: none;
}
.iconButton:hover {
background: rgba(0, 0, 0, 0.05);
color: #333;
}
.promptContentWrapper {
border-top: 1px solid #eee;
overflow: hidden;
}
.promptContent {
padding-top: 10px;
padding-bottom: 10px;
padding-left: 16px;
padding-right: 16px;
color: #666;
line-height: 0.7;
font-family: Arial, Helvetica, sans-serif;
font-size: 10pt;
}
.promptContent p {
margin: 0;
padding: 4px 0;
}
.filesContainer {
display: flex;
gap: 2rem;
padding: 1rem;
border-top: 1px solid var(--border-color, #e0e0e0);
margin-top: 1rem;
}
.filesColumn {
flex: 1;
min-width: 0;
}
.filesColumn h3 {
display: flex;
align-items: center;
gap: 0.5rem;
font-size: 1rem;
margin-bottom: 1rem;
color: var(--text-color-secondary, #666);
}
.filesList {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.fileItem {
display: flex;
align-items: center;
padding: 8px 12px;
background-color: var(--background-color-light, #f5f5f5);
border-radius: 4px;
cursor: pointer;
transition: all 0.2s ease;
gap: 8px;
position: relative;
overflow: hidden;
}
.fileItem:hover {
background-color: var(--background-color-hover, #e8e8e8);
}
.fileItem.downloading {
background-color: var(--background-color-hover, #e8e8e8);
cursor: default;
opacity: 0.8;
}
.fileIcon {
color: var(--text-color-secondary, #666);
font-size: 1rem;
flex-shrink: 0;
}
.fileName {
flex: 1;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
font-size: 0.9rem;
}
.fileDate {
color: var(--text-color-secondary, #666);
font-size: 0.8rem;
white-space: nowrap;
margin-left: auto;
}
.downloadingText {
position: absolute;
right: 12px;
font-size: 0.8rem;
color: var(--text-color-secondary, #666);
animation: pulse 1.5s infinite;
}
@keyframes pulse {
0% {
opacity: 0.6;
}
50% {
opacity: 1;
}
100% {
opacity: 0.6;
}
}
.errorMessage {
margin: 1rem;
padding: 0.75rem;
background-color: #fee2e2;
border: 1px solid #fecaca;
border-radius: 4px;
color: #dc2626;
font-size: 0.9rem;
}
.noFiles {
color: var(--text-color-disabled, #999);
font-style: italic;
font-size: 0.9rem;
}

View file

@ -1,183 +0,0 @@
import { useState, useEffect } from 'react';
import styles from './DashboardPromptSet.module.css';
import { useUserPrompts } from '../../../auth/Hooks/use-user-prompts';
import { useUserFiles } from '../../../auth/Hooks/use-user-files';
import { FaEdit, FaRedo, FaChevronRight } from 'react-icons/fa';
import PromptItemDelete from './PromptItemDelete';
import PromptItemShare from './PromptItemShare';
import NewPromptButton from './NewPromptButton';
import { motion, AnimatePresence } from 'framer-motion';
import { useSearchParams } from 'react-router-dom';
import { useFileOperations } from '../../../hooks/use-file-operations';
import { FileList } from './FileList';
const formatPromptText = (text: string) => {
// Split text at 5 or more consecutive spaces
const parts = text.split(/\s{4,}/g);
// Join with line breaks
return parts.join('\n');
};
function DashboardPromptSet() {
const { prompts, loading, error, refetch } = useUserPrompts();
const { files, loading: filesLoading } = useUserFiles();
const [expandedPrompts, setExpandedPrompts] = useState<Set<string>>(new Set());
const [searchParams] = useSearchParams();
const { downloadingFiles, downloadError, handleFileDownload } = useFileOperations();
useEffect(() => {
if (!loading && prompts.length > 0) {
const expandedPrompt = searchParams.get('expandedPrompt');
console.log('URL Parameter expandedPrompt:', expandedPrompt);
console.log('Available prompts:', prompts.map(p => ({ id: p.id, title: p.prompt_title })));
console.log('Current expandedPrompts:', Array.from(expandedPrompts));
if (expandedPrompt) {
const matchingPrompt = prompts.find(p => p.id.toString() === expandedPrompt.toString());
console.log('Matching prompt:', matchingPrompt);
if (matchingPrompt) {
console.log('Setting expanded prompt:', matchingPrompt.id);
setExpandedPrompts(new Set([matchingPrompt.id]));
}
}
}
}, [searchParams, prompts, loading]);
const toggleExpand = (promptId: string) => {
console.log('Toggling prompt:', promptId);
setExpandedPrompts(prev => {
const newSet = new Set(prev);
if (newSet.has(promptId)) {
newSet.delete(promptId);
} else {
newSet.add(promptId);
}
return newSet;
});
};
const handleDelete = async () => {
try {
await refetch(); // Refetch prompts after successful deletion
} catch (error) {
console.error('Error deleting prompt:', error);
}
};
const getPromptFiles = (promptId: string | null) => {
if (!files || !promptId) return { uploadedFiles: [], downloadFiles: [] };
const promptFiles = files.filter(file => {
// Check if either file.prompt_id or promptId is null
if (file.prompt_id === null || promptId === null) return false;
return file.prompt_id.toString() === promptId.toString();
});
return {
uploadedFiles: promptFiles.filter(file => file.action === 'upload'),
downloadFiles: promptFiles.filter(file => file.action === 'download')
};
};
return (
<div className={styles.container}>
<NewPromptButton />
{loading || filesLoading ? (
<div>Loading...</div>
) : error ? (
<div>Error: {error}</div>
) : (
<div className={styles.promptList}>
{prompts.map(prompt => (
<motion.div
key={prompt.id}
className={styles.promptCard}
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -20 }}
transition={{ duration: 0.3 }}
>
<div className={styles.promptHeader}>
<motion.button
className={styles.expandButton}
onClick={() => toggleExpand(prompt.id)}
animate={{
rotate: expandedPrompts.has(prompt.id) ? 90 : 0
}}
transition={{ duration: 0.2 }}
>
<FaChevronRight />
</motion.button>
<h2 className={styles.promptTitle}>{prompt.prompt_title}</h2>
<div className={styles.actionButtons}>
<button className={styles.iconButton} title="Edit">
<FaEdit />
</button>
<PromptItemDelete
promptId={prompt.id}
promptTitle={prompt.prompt_title}
onDelete={handleDelete}
/>
<button className={styles.iconButton} title="Repeat">
<FaRedo />
</button>
<PromptItemShare
promptId={prompt.id}
promptTitle={prompt.prompt_title}
/>
</div>
</div>
<AnimatePresence initial={false}>
{expandedPrompts.has(prompt.id) && (
<motion.div
className={styles.promptContentWrapper}
initial={{ height: 0, opacity: 0, borderTopWidth: 0 }}
animate={{
height: "auto",
opacity: 1,
borderTopWidth: 1,
transition: {
height: { duration: 0.3, ease: "easeOut" },
opacity: { duration: 0.2, delay: 0.1 },
borderTopWidth: { duration: 0.2, delay: 0.1 }
}
}}
exit={{
height: 0,
opacity: 0,
borderTopWidth: 0,
transition: {
height: { duration: 0.3, ease: "easeIn" },
opacity: { duration: 0.2 },
borderTopWidth: { duration: 0.1 }
}
}}
>
<div className={styles.promptContent}>
{formatPromptText(prompt.user_prompt).split('\n').map((line, index) => (
<p key={index}>{line}</p>
))}
</div>
<FileList
{...getPromptFiles(prompt.id)}
downloadingFiles={downloadingFiles}
onFileClick={handleFileDownload}
/>
{downloadError && (
<div className={styles.errorMessage}>
{downloadError}
</div>
)}
</motion.div>
)}
</AnimatePresence>
</motion.div>
))}
</div>
)}
</div>
);
}
export default DashboardPromptSet;

View file

@ -1,34 +0,0 @@
import { FaFile } from 'react-icons/fa';
import styles from './DashboardPromptSet.module.css';
type FileItemProps = {
id: number;
fileName: string;
createdAt: string;
isDownloading: boolean;
onFileClick: (fileId: number, fileName: string) => void;
};
export const FileItem = ({
id,
fileName,
createdAt,
isDownloading,
onFileClick
}: FileItemProps) => {
return (
<div
className={`${styles.fileItem} ${isDownloading ? styles.downloading : ''}`}
onClick={() => onFileClick(id, fileName)}
>
<FaFile className={styles.fileIcon} />
<span className={styles.fileName}>{fileName}</span>
<span className={styles.fileDate}>
{new Date(createdAt).toLocaleDateString()}
</span>
{isDownloading && (
<span className={styles.downloadingText}>Downloading...</span>
)}
</div>
);
};

View file

@ -1,64 +0,0 @@
import { FaUpload, FaDownload } from 'react-icons/fa';
import styles from './DashboardPromptSet.module.css';
import { FileItem } from './FileItem';
type File = {
id: number;
file_name: string;
created_at: string;
};
type FileListProps = {
uploadedFiles: File[];
downloadFiles: File[];
downloadingFiles: Set<number>;
onFileClick: (fileId: number, fileName: string) => void;
};
export const FileList = ({
uploadedFiles,
downloadFiles,
downloadingFiles,
onFileClick
}: FileListProps) => {
return (
<div className={styles.filesContainer}>
<div className={styles.filesColumn}>
<h3><FaUpload /> Uploaded Files</h3>
<div className={styles.filesList}>
{uploadedFiles.map(file => (
<FileItem
key={file.id}
id={file.id}
fileName={file.file_name}
createdAt={file.created_at}
isDownloading={downloadingFiles.has(file.id)}
onFileClick={onFileClick}
/>
))}
{uploadedFiles.length === 0 && (
<p className={styles.noFiles}>No uploaded files</p>
)}
</div>
</div>
<div className={styles.filesColumn}>
<h3><FaDownload /> Files for Download</h3>
<div className={styles.filesList}>
{downloadFiles.map(file => (
<FileItem
key={file.id}
id={file.id}
fileName={file.file_name}
createdAt={file.created_at}
isDownloading={downloadingFiles.has(file.id)}
onFileClick={onFileClick}
/>
))}
{downloadFiles.length === 0 && (
<p className={styles.noFiles}>No files for download</p>
)}
</div>
</div>
</div>
);
};

View file

@ -1,144 +0,0 @@
.container {
margin-bottom: 20px;
}
.newPromptButton {
background-color: var(--Brand-Purple-Purple, #5F59D4);;
color: white;
border: none;
padding: 10px 20px;
border-radius: 30px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: background-color 0.2s;
font-family: Arial, Helvetica, sans-serif;
}
.newPromptButton:hover {
background-color: var(--Brand-Purple-Purple, #5F59D4);
}
.overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
z-index: 1000;
}
.popup {
display: flex;
flex-direction: column;
gap: 25px;
background: white;
padding: 24px;
border-radius: 30px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
width: 100%;
max-width: 400px;
margin: 20px;
}
.popupHeader {
display: flex;
justify-content: space-between;
align-items: center;
height: 35px;
}
.popup h2 {
display: flex;
justify-content: center;
align-items: center;
font-size: 18px;
color: #24262B;
font-family: Arial, Helvetica, sans-serif;
font-weight: 550;
height: 80%;
}
.cancelButton {
display: flex;
justify-content: center;
align-items: center;
height: 80%;
border: none;
background: none;
color: #666;
transition: all 0.2s;
}
.cancelButton:hover {
cursor: pointer;
}
.cancelButtonIcon {
display: flex;
justify-content: center;
align-items: center;
height: 100%;
width: 100%;
}
.inputGroup {
margin-bottom: 20px;
}
.inputGroup label {
display: block;
margin-bottom: 8px;
font-size: 14px;
color: #666;
font-family: Arial, Helvetica, sans-serif;
}
.inputGroup textarea {
display: flex;
width: 100%;
padding: 10px;
border: 1px solid #ddd;
border-radius: 5px;
font-size: 14px;
font-family: Arial, Helvetica, sans-serif;
box-sizing: border-box;
height: 100px;
resize: none;
vertical-align: top;
line-height: 1.5;
}
.inputGroup textarea:focus {
outline: none;
border-color: var(--Brand-Purple-Purple, #5F59D4);
box-shadow: 0 0 0 2px rgba(95, 89, 212, 0.25);
}
.buttonGroup {
display: flex;
justify-content: flex-end;
gap: 12px;
}
.submitButton {
padding: 8px 16px;
border: none;
border-radius: 30px;
background: var(--Brand-Purple-Purple, #5F59D4);
color: white;
font-size: 14px;
cursor: pointer;
font-family: Arial, Helvetica, sans-serif;
transition: background-color 0.2s;
}
.submitButton:hover {
background-color: var(--Brand-Purple-Purple, #5F59D4);
}

View file

@ -1,109 +0,0 @@
import { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import styles from './NewPromptButton.module.css';
import { IoClose } from 'react-icons/io5';
import { authorizedGet } from '../../../api';
import { useAuthToken } from '../../../auth/Hooks/use-auth-token';
import { useNavigate } from 'react-router-dom';
function NewPromptButton() {
const [isOpen, setIsOpen] = useState(false);
const [promptText, setPromptText] = useState('');
const [isSubmitting, setIsSubmitting] = useState(false);
const { getToken } = useAuthToken();
const navigate = useNavigate();
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setIsSubmitting(true);
try {
console.log('Submitting prompt:', promptText);
// Make the API call to start the streaming
const response = await authorizedGet(
`/api/prompts/?promptText=${encodeURIComponent(promptText)}`,
getToken
);
console.log('API response:', response);
// Close the popup and reset the form
setIsOpen(false);
setPromptText('');
// Navigate to dashboard with both the prompt ID and text
navigate(`/dashboard?promptId=${Date.now()}&promptText=${encodeURIComponent(promptText)}`);
} catch (error) {
console.error('Error creating prompt:', error);
// You might want to show an error message to the user here
} finally {
setIsSubmitting(false);
}
};
return (
<div className={styles.container}>
<motion.button
className={styles.newPromptButton}
onClick={() => setIsOpen(true)}
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
>
New Prompt
</motion.button>
<AnimatePresence>
{isOpen && (
<motion.div
className={styles.overlay}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
onClick={() => setIsOpen(false)}
>
<motion.div
className={styles.popup}
initial={{ scale: 0.9, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
exit={{ scale: 0.9, opacity: 0 }}
onClick={e => e.stopPropagation()}
>
<div className={styles.popupHeader}>
<h2>Create New Prompt</h2>
<button
type="button"
className={styles.cancelButton}
onClick={() => setIsOpen(false)}
>
<IoClose className={styles.cancelButtonIcon}/>
</button>
</div>
<form onSubmit={handleSubmit}>
<div className={styles.inputGroup}>
<label htmlFor="promptText">Please enter your prompt here.</label>
<textarea
id="promptText"
value={promptText}
onChange={(e) => setPromptText(e.target.value)}
placeholder="Enter prompt."
required
/>
</div>
<div className={styles.buttonGroup}>
<button
type="submit"
className={styles.submitButton}
disabled={isSubmitting}
>
{isSubmitting ? 'Processing...' : 'Prompt starten'}
</button>
</div>
</form>
</motion.div>
</motion.div>
)}
</AnimatePresence>
</div>
);
}
export default NewPromptButton;

View file

@ -1,132 +0,0 @@
.deleteButton {
background: none;
border: none;
cursor: pointer;
padding: 6px;
color: #666;
border-radius: 4px;
transition: all 0.2s;
display: flex;
align-items: center;
justify-content: center;
}
.deleteButton:hover {
background: rgba(0, 0, 0, 0.05);
color: #333;
}
.modalOverlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
z-index: 9999;
backdrop-filter: blur(2px);
}
.modalContent {
background: white;
padding: 24px;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
max-width: 400px;
width: 90%;
text-align: center;
position: relative;
z-index: 10000;
animation: modalAppear 0.3s ease-out;
}
@keyframes modalAppear {
from {
opacity: 0;
transform: scale(0.95) translateY(10px);
}
to {
opacity: 1;
transform: scale(1) translateY(0);
}
}
.modalContent h2 {
margin: 0 0 16px;
color: var(--Grayscale-Black, #24262B);
font-size: 1.5rem;
font-weight: 600;
font-family: Arial, Helvetica, sans-serif;
}
.modalContent p {
margin: 8px 0;
color: #666;
font-size: 1rem;
line-height: 1.2;
font-family: Arial, Helvetica, sans-serif;
}
.deletePromptTitle {
font-weight: 600;
color: var(--Grayscale-Black, #24262B);
margin: 16px 0;
font-family: Arial, Helvetica, sans-serif;
}
.modalButtons {
display: flex;
justify-content: center;
gap: 16px;
margin-top: 15px;
}
.modalButton {
padding: 8px 24px;
border: none;
border-radius: 8px;
font-weight: 500;
cursor: pointer;
transition: all 0.2s;
font-size: 0.95rem;
min-width: 100px;
}
.cancelButton {
background-color: #f8f9fa;
color: #495057;
border: 1px solid #e9ecef;
}
.cancelButton:hover {
background-color: #e9ecef;
}
.confirmButton {
background-color: #dc3545;
color: white;
}
.confirmButton:hover {
background-color: #c82333;
}
/* Responsive adjustments */
@media (max-width: 480px) {
.modalContent {
width: calc(100% - 32px);
padding: 24px;
}
.modalButtons {
flex-direction: column;
gap: 12px;
}
.modalButton {
width: 100%;
}
}

View file

@ -1,74 +0,0 @@
import { useState } from 'react';
import { FaTrash } from 'react-icons/fa';
import { createPortal } from 'react-dom';
import styles from './PromptItemDelete.module.css';
import { useAuthToken } from '../../../auth/Hooks/use-auth-token';
import { authorizedDelete } from '../../../api';
interface PromptItemDeleteProps {
promptId: string;
promptTitle: string;
onDelete: (promptId: string) => Promise<void>;
}
export const PromptItemDelete: React.FC<PromptItemDeleteProps> = ({ promptId, promptTitle, onDelete }) => {
const [showConfirmation, setShowConfirmation] = useState(false);
const { getToken } = useAuthToken();
const handleDeleteClick = () => {
setShowConfirmation(true);
};
const handleConfirm = async () => {
try {
await authorizedDelete(`/api/user/prompts/${promptId}`, getToken);
setShowConfirmation(false);
await onDelete(promptId);
} catch (error) {
console.error('Error deleting prompt:', error);
}
};
const handleCancel = () => {
setShowConfirmation(false);
};
return (
<>
<button
className={styles.deleteButton}
title="Delete"
onClick={handleDeleteClick}
>
<FaTrash />
</button>
{showConfirmation && createPortal(
<div className={styles.modalOverlay}>
<div className={styles.modalContent}>
<h2>Delete Prompt</h2>
<p>Are you sure you want to delete the prompt:</p>
<p className={styles.deletePromptTitle}>{promptTitle}?</p>
<div className={styles.modalButtons}>
<button
className={`${styles.modalButton} ${styles.cancelButton}`}
onClick={handleCancel}
>
Cancel
</button>
<button
className={`${styles.modalButton} ${styles.confirmButton}`}
onClick={handleConfirm}
>
Delete
</button>
</div>
</div>
</div>,
document.body
)}
</>
);
};
export default PromptItemDelete;

View file

@ -1,169 +0,0 @@
.shareButton {
background: none;
border: none;
cursor: pointer;
color: #666;
border-radius: 30px;
transition: all 0.2s;
display: flex;
align-items: center;
justify-content: center;
}
.shareButton:hover {
background: rgba(0, 0, 0, 0.05);
color: #333;
}
.modalOverlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
z-index: 9999;
backdrop-filter: blur(2px);
}
.modalContent {
background: white;
padding: 24px;
border-radius: 30px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
max-width: 400px;
width: 90%;
position: relative;
z-index: 10000;
animation: modalAppear 0.3s ease-out;
}
@keyframes modalAppear {
from {
opacity: 0;
transform: scale(0.95) translateY(10px);
}
to {
opacity: 1;
transform: scale(1) translateY(0);
}
}
.modalContent h2 {
margin: 0 0 16px;
color: var(--Grayscale-Black, #24262B);
font-size: 1.5rem;
font-weight: 600;
font-family: Arial, Helvetica, sans-serif;
}
.modalContent p {
margin: 8px 0;
color: #666;
font-size: 1rem;
line-height: 1.2;
font-family: Arial, Helvetica, sans-serif;
}
.userList {
max-height: 300px;
overflow-y: auto;
margin: 10px 0;
border: 1px solid #eee;
border-radius: 4px;
padding-left: 8px;
padding-right: 8px;
padding-top: 0px;
padding-bottom: 0px;
font-family: Arial, Helvetica, sans-serif;
font-size: 10px;
line-height: 0.5;
}
.userItem {
display: flex;
align-items: center;
padding: 8px;
cursor: pointer;
transition: background-color 0.2s;
border-radius: 4px;
height: 18px;
}
.userItem:hover {
background-color: #f8f9fa;
}
.userItem input[type="checkbox"] {
margin-right: 10px;
}
.userName {
font-size: 14px;
color: #333;
line-height: 1;
display: flex;
align-items: center;
gap: 8px;
}
.userEmail {
color: #666;
font-size: 12px;
}
.loading {
text-align: center;
padding: 20px;
color: #666;
}
.error {
text-align: center;
padding: 20px;
color: #dc3545;
}
.modalButtons {
display: flex;
justify-content: flex-end;
gap: 16px;
margin-top: 24px;
}
.modalButton {
padding: 8px 24px;
border: none;
border-radius: 8px;
font-weight: 500;
cursor: pointer;
transition: all 0.2s;
font-size: 0.95rem;
}
.modalButton:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.cancelButton {
background-color: #f8f9fa;
color: #495057;
border: 1px solid #e9ecef;
}
.cancelButton:hover:not(:disabled) {
background-color: #e9ecef;
}
.modalButton.shareButton {
background-color: var(--Brand-Purple-Purple, #5F59D4);
color: white;
}
.modalButton.shareButton:hover:not(:disabled) {
background-color: var(--Brand-Purple-Purple, #5F59D4);
}

View file

@ -1,112 +0,0 @@
import { useState } from 'react';
import { FaShare } from 'react-icons/fa';
import { createPortal } from 'react-dom';
import styles from './PromptItemShare.module.css';
import { useAuthToken } from '../../../auth/Hooks/use-auth-token';
import { useOrgUsers } from '../../../auth/Hooks/get-all-users';
import { authorizedPost } from '../../../api';
interface PromptItemShareProps {
promptId: string;
promptTitle: string;
}
export const PromptItemShare: React.FC<PromptItemShareProps> = ({ promptId, promptTitle }) => {
const [showModal, setShowModal] = useState(false);
const [selectedUsers, setSelectedUsers] = useState<Set<string>>(new Set());
const { getToken } = useAuthToken();
const { users, loading, error } = useOrgUsers();
const handleShareClick = () => {
setShowModal(true);
};
const handleUserToggle = (userId: string) => {
setSelectedUsers(prev => {
const newSet = new Set(prev);
if (newSet.has(userId)) {
newSet.delete(userId);
} else {
newSet.add(userId);
}
return newSet;
});
};
const handleShare = async () => {
try {
console.log(Array.from(selectedUsers));
await authorizedPost(`/api/user/prompts/${promptId}/share`, getToken, {
user_ids: Array.from(selectedUsers)
});
setShowModal(false);
setSelectedUsers(new Set());
} catch (error) {
console.error('Error sharing prompt:', error);
}
};
const handleCancel = () => {
setShowModal(false);
setSelectedUsers(new Set());
};
return (
<>
<button
className={styles.shareButton}
title="Share"
onClick={handleShareClick}
>
<FaShare />
</button>
{showModal && createPortal(
<div className={styles.modalOverlay}>
<div className={styles.modalContent}>
<h2>Share Prompt</h2>
<p>Share "{promptTitle}" with:</p>
{loading && <div className={styles.loading}>Loading users...</div>}
{error && <div className={styles.error}>{error}</div>}
<div className={styles.userList}>
{users.map(user => (
<label key={user.id} className={styles.userItem}>
<input
type="checkbox"
checked={selectedUsers.has(user.id)}
onChange={() => handleUserToggle(user.id)}
/>
<span className={styles.userName}>
{user.name}
<span className={styles.userEmail}>({user.email})</span>
</span>
</label>
))}
</div>
<div className={styles.modalButtons}>
<button
className={`${styles.modalButton} ${styles.cancelButton}`}
onClick={handleCancel}
>
Cancel
</button>
<button
className={`${styles.modalButton} ${styles.shareButton}`}
onClick={handleShare}
disabled={selectedUsers.size === 0}
>
Share
</button>
</div>
</div>
</div>,
document.body
)}
</>
);
};
export default PromptItemShare;

View file

@ -1,120 +0,0 @@
.fileItem {
display: flex;
align-items: center;
height: 70px;
padding: 0px 16px;
justify-content: space-between;
color: var(--Grayscale-Black, #24262B);
}
.fileIcon {
margin-right: 12px;
}
.icon {
font-size: 24px;
color: var(--Grayscale-Gray, #E9E9E9);
}
.fileInfo {
display: grid;
grid-template-columns: 400px 250px 100px;
gap: 16px;
flex-grow: 1;
align-items: center;
}
.fileName {
margin: 0;
font-size: 14px;
font-weight: 500;
}
.fileAction,
.fileDate {
margin: 0;
font-size: 12px;
color: #666;
font-weight: light;
}
.actionButtons {
display: flex;
gap: 8px;
margin-left: 16px;
}
.downloadButton,
.deleteButton {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 12px;
border: none;
border-radius: 4px;
background-color: transparent;
color: var(--text-color-secondary, #666);
cursor: pointer;
transition: all 0.2s ease;
min-width: 40px;
justify-content: center;
}
.downloadButton:hover:not(:disabled),
.deleteButton:hover:not(:disabled) {
background-color: var(--background-color-hover, #e8e8e8);
color: var(--text-color-primary, #333);
}
.deleteButton:hover:not(:disabled) {
color: #dc2626;
}
.deleteButton.confirm {
background-color: #fee2e2;
color: #dc2626;
}
.deleteButton.confirm:hover:not(:disabled) {
background-color: #fecaca;
}
.downloadButton:disabled,
.deleteButton:disabled {
cursor: not-allowed;
opacity: 0.7;
}
.actionIcon {
font-size: 16px;
flex-shrink: 0;
}
.downloadButton.downloading,
.deleteButton.deleting {
background-color: var(--background-color-light, #f5f5f5);
}
.actionText {
font-size: 12px;
color: var(--text-color-secondary, #666);
animation: pulse 1.5s infinite;
white-space: nowrap;
}
.deleteButton.confirm .actionText {
color: #dc2626;
animation: none;
}
@keyframes pulse {
0% {
opacity: 0.6;
}
50% {
opacity: 1;
}
100% {
opacity: 0.6;
}
}

View file

@ -1,76 +0,0 @@
import { FaFile, FaDownload, FaTrash } from "react-icons/fa";
import styles from "./DateienItem.module.css";
import { useFileOperations } from "../../hooks/use-file-operations";
import { useState } from "react";
type DateienItemProps = {
file: {
id: number;
file_name: string;
action: string;
created_at: string;
};
onDelete?: () => void;
};
const DateienItem = ({ file, onDelete }: DateienItemProps) => {
const { downloadingFiles, deletingFiles, handleFileDownload, handleFileDelete } = useFileOperations();
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
const isDownloading = downloadingFiles.has(file.id);
const isDeleting = deletingFiles.has(file.id);
const handleDeleteClick = async () => {
if (showDeleteConfirm) {
const success = await handleFileDelete(file.id);
if (success && onDelete) {
onDelete();
}
setShowDeleteConfirm(false);
} else {
setShowDeleteConfirm(true);
}
};
const handleCancelDelete = () => {
setShowDeleteConfirm(false);
};
return (
<li className={styles.fileItem}>
<div className={styles.fileIcon}>
<FaFile className={styles.icon} />
</div>
<div className={styles.fileInfo}>
<span className={styles.fileName}>{file.file_name}</span>
<span className={styles.fileAction}>{file.action}</span>
<span className={styles.fileDate}>
{new Date(file.created_at).toLocaleDateString()}
</span>
</div>
<div className={styles.actionButtons}>
<button
className={`${styles.downloadButton} ${isDownloading ? styles.downloading : ''}`}
onClick={() => handleFileDownload(file.id, file.file_name)}
disabled={isDownloading || isDeleting}
title="Download file"
>
<FaDownload className={styles.actionIcon} />
{isDownloading && <span className={styles.actionText}>Downloading...</span>}
</button>
<button
className={`${styles.deleteButton} ${isDeleting ? styles.deleting : ''} ${showDeleteConfirm ? styles.confirm : ''}`}
onClick={handleDeleteClick}
disabled={isDownloading || isDeleting}
title={showDeleteConfirm ? "Click again to confirm deletion" : "Delete file"}
onBlur={handleCancelDelete}
>
<FaTrash className={styles.actionIcon} />
{isDeleting && <span className={styles.actionText}>Deleting...</span>}
{showDeleteConfirm && <span className={styles.actionText}>Click to confirm</span>}
</button>
</div>
</li>
);
};
export default DateienItem;

View file

@ -1,53 +0,0 @@
.memberItem {
display: flex;
align-items: center;
height: 70px;
padding: 0px 16px;
justify-content: space-between;
color: var(--Grayscale-Black, #24262B);
}
.userProfile {
margin-right: 12px;
}
.profileIcon {
font-size: 36px;
color: var(--Grayscale-Gray, #E9E9E9);
}
.userInfo {
display: grid;
grid-template-columns: 200px 250px 100px;
gap: 16px;
flex-grow: 1;
align-items: center;
}
.userName {
margin: 0;
font-size: 14px;
}
.userEmail,
.userRole {
margin: 0;
font-size: 12px;
font-weight: light;
}
.actions {
display: flex;
align-items: center;
justify-content: center;
}
.editBtn:hover {
color: var(--Brand-Green-Green, #3A8088);
}
.deleteBtn:hover {
color: var(--Brand-Green-Green, #3A8088);
}

View file

@ -1,38 +0,0 @@
import { FaUserCircle } from "react-icons/fa";
import styles from "./MitgliederItem.module.css";
import MitgliederItemDelete from "./MitgliederItemDelete/MitgliederItemDelete";
import MitgliederItemEdit from "./MitgliederItemEdit/MitgliederItemEdit";
type MitgliederItemProps = {
user: {
id: string;
name: string;
email: string;
role: string;
position: string;
azure_id: string;
};
refetchUsers: () => Promise<void>;
totalUsers: number;
};
const MitgliederItem = ({ user, refetchUsers, totalUsers }: MitgliederItemProps) => {
return (
<li className={styles.memberItem}>
<div className={styles.userProfile}>
<FaUserCircle className={styles.profileIcon} />
</div>
<div className={styles.userInfo}>
<span className={styles.userName}>{user.name}</span>
<span className={styles.userEmail}>{user.email}</span>
<span className={styles.userRole}>{user.role}</span>
</div>
<div className={styles.actions}>
<MitgliederItemEdit user={user} refetchUsers={refetchUsers} />
<MitgliederItemDelete user={user} refetchUsers={refetchUsers} isDisabled={totalUsers <= 1} />
</div>
</li>
);
};
export default MitgliederItem;

View file

@ -1,92 +0,0 @@
.popupHeader {
display: flex;
justify-content: space-between;
align-items: center;
margin-top:10px;
margin-left: 10px;
margin-right: 10px;
margin-bottom: 5px;
width: 300px;
height: 20px;
color: gray;
font-size: 10px;
}
.closeButton {
display: flex;
align-items: center;
background: none;
border: none;
cursor: pointer;
width: 20px; /* Increased button size */
height: 20px;
line-height: 0;
padding: 0;
margin:0;
}
.closeIcon {
width: 100%; /* Make the icon fill the button's width */
height: 100%;
padding: 0;
margin:0;
display: block;
}
.horizontalLineLight {
width: 100%;
background-color: #F1F1F1;
height: 1px;
}
.userInfo {
display: grid;
grid-column: 1;
padding: none;
margin: none;
align-items: center;
justify-content: center; /* Center horizontally */
}
.userInfoParagraph{
display: flex;
color: gray;
font-size: 10px;
margin:0px;
justify-content: center;
gap: 10px;
}
.userInfo h2{
display: flex;
justify-content: center;
margin: 0;
margin-top:10px;
justify-content: center;
}
.submitButtonDiv {
margin: 10px;
display: flex; /* Use Flexbox */
justify-content: center; /* Center horizontally */
align-items: center;
}
.submitButton {
background: none;
border: 1px solid black;
border-radius: 5px;
padding: 5px 20px; /* Optional: Adds some padding for better button size */
cursor: pointer;
width: 80%
}
.submitButton:hover {
background: rgb(168, 18, 18);
border: 1px solid rgb(168, 18, 18);
border-radius: 5px;
padding: 5px 20px; /* Optional: Adds some padding for better button size */
cursor: pointer;
color: white;
transition: 0.2s;
}

View file

@ -1,86 +0,0 @@
import { IoCloseOutline } from "react-icons/io5";
import styles from "./DeletePopUp.module.css";
import deleteUser from "../../../auth/Hooks/delete-user";
import { useAuthToken } from "../../../auth/Hooks/use-auth-token";
type DeletePopUpProps = {
closePopup: () => void;
refetchUsers: () => Promise<void>;
user: {
name: string;
email: string;
role: string;
position: string;
azure_id: string;
};
};
const DeletePopUp = ({ closePopup, refetchUsers, user }: DeletePopUpProps) => {
const { getToken } = useAuthToken();
const handleDelete = async () => {
try {
const token = await getToken();
await deleteUser(user.azure_id, token);
await refetchUsers();
closePopup();
} catch (error) {
console.error("Failed to delete user:", error);
}
};
return (
<div style={popupStyles.overlay}>
<div style={popupStyles.popup}>
<div className={styles.popupHeader}>
<p>Delete User...</p>
<button
className={styles.closeButton}
onClick={closePopup}><IoCloseOutline className={styles.closeIcon}/>
</button>
</div>
<div className={styles.horizontalLineLight}></div>
<div className={styles.userInfo}>
<h2>{user.name}</h2>
<div className={styles.userInfoParagraph}>
<p>Email: {user.email}</p>
<p>Role: {user.role}</p>
</div>
</div>
<div className={styles.horizontalLineLight}></div>
<div className={styles.submitButtonDiv}>
<button
className={styles.submitButton}
onClick={handleDelete}>
Delete
</button>
</div>
</div>
</div>
)
}
const popupStyles: { overlay: React.CSSProperties; popup: React.CSSProperties } = {
overlay: {
position: "fixed",
top: 0,
left: 0,
right: 0,
bottom: 0,
backgroundColor: "rgba(0,0,0,0.5)",
display: "flex",
justifyContent: "center",
alignItems: "center",
},
popup: {
backgroundColor: "#fff",
borderRadius: "8px",
boxShadow: "0 5px 15px rgba(0,0,0,0.3)",
position: "relative"
}
};
export default DeletePopUp;

View file

@ -1,33 +0,0 @@
.deleteBtn {
background: none;
border: none;
cursor: pointer;
font-size: 18px;
color: #444;
height: 100;
}
.deleteBtn:hover {
color: var(--Brand-Green-Green, #3A8088);
}
.deleteBtn.disabled {
cursor: not-allowed;
opacity: 0.5;
background: none;
border: none;
cursor: pointer;
font-size: 18px;
color: #444;
}
.deleteBtn.disabled:hover {
color: #444;
}
.deleteBtnContainer {
display: flex;
align-items: center;
justify-content: center;
}

View file

@ -1,43 +0,0 @@
import { FaTrash } from "react-icons/fa";
import styles from "./MitgliederItemDelete.module.css";
import { useState } from "react";
import DeletePopUp from "./DeletePopUp";
type MitgliederItemDeleteProps = {
user: {
id: string;
name: string;
email: string;
role: string;
position: string;
azure_id: string;
};
refetchUsers: () => Promise<void>;
isDisabled?: boolean;
};
const MitgliederItemDelete = ({ user, refetchUsers, isDisabled = false }: MitgliederItemDeleteProps) => {
const [deleteWindow, setDeleteWindow] = useState(false);
return (
<div className={styles.deleteBtnContainer}>
<button
onClick={() => !isDisabled && setDeleteWindow(true)}
className={`${styles.deleteBtn} ${isDisabled ? styles.disabled : ''}`}
disabled={isDisabled}
title={isDisabled ? "Cannot delete the only remaining user" : "Delete user"}>
<FaTrash />
</button>
{deleteWindow && (
<DeletePopUp
user={user}
closePopup={() => setDeleteWindow(false)}
refetchUsers={refetchUsers}
/>
)}
</div>
);
};
export default MitgliederItemDelete;

View file

@ -1,89 +0,0 @@
.popupHeader {
display: flex;
justify-content: space-between;
align-items: center;
padding: 15px 20px;
}
.popupHeader p {
font-size: 1.2rem;
font-weight: 600;
margin: 0;
}
.closeButton {
background: none;
border: none;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
}
.closeIcon {
font-size: 1.5rem;
color: #666;
}
.horizontalLineLight {
height: 1px;
background-color: #e0e0e0;
width: 100%;
margin: 0;
}
.form {
box-sizing: border-box;
max-width: 100%;
padding: 20px;
}
.formGroup {
margin-bottom: 15px;
box-sizing: border-box;
}
.formGroup label {
display: block;
margin-bottom: 5px;
font-weight: 500;
}
.formGroup input,
.formGroup select {
width: 100%;
padding: 8px 12px;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 1rem;
box-sizing: border-box;
}
.submitButtonDiv {
display: flex;
justify-content: flex-end;
padding: 15px 0 10px;
}
.submitButton {
background-color: #4c9aff;
color: white;
border: none;
border-radius: 4px;
padding: 8px 16px;
font-size: 1rem;
cursor: pointer;
transition: background-color 0.2s;
}
.submitButton:hover {
background-color: #3d8df5;
}
.userInfo h2 {
margin-top: 0;
margin-bottom: 10px;
}

View file

@ -1,143 +0,0 @@
import { IoCloseOutline } from "react-icons/io5";
import { useState } from "react";
import styles from "./EditPopUp.module.css";
import updateUser from "./update-user";
import { useAuthToken } from "../../../auth/Hooks/use-auth-token";
type EditPopUpProps = {
closePopup: () => void;
refetchUsers: () => Promise<void>;
user: {
id: string;
name: string;
email: string;
role: string;
position: string;
azure_id: string;
};
};
const EditPopUp = ({ closePopup, refetchUsers, user }: EditPopUpProps) => {
const { getToken } = useAuthToken();
const [formData, setFormData] = useState({
name: user.name,
email: user.email,
role: user.role,
position: user.position || ""
});
const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
const { name, value } = e.target;
setFormData(prev => ({
...prev,
[name]: value
}));
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
try {
const token = await getToken();
await updateUser(user.azure_id, formData, token);
await refetchUsers();
closePopup();
} catch (error) {
console.error("Failed to update user:", error);
}
};
return (
<div style={popupStyles.overlay}>
<div style={popupStyles.popup}>
<div className={styles.popupHeader}>
<p>Edit User</p>
<button
className={styles.closeButton}
onClick={closePopup}><IoCloseOutline className={styles.closeIcon}/>
</button>
</div>
<div className={styles.horizontalLineLight}></div>
<form onSubmit={handleSubmit} className={styles.form}>
<div className={styles.formGroup}>
<label htmlFor="name">Name:</label>
<input
type="text"
id="name"
name="name"
value={formData.name}
onChange={handleChange}
required
/>
</div>
<div className={styles.formGroup}>
<label htmlFor="email">Email:</label>
<input
type="email"
id="email"
name="email"
value={formData.email}
onChange={handleChange}
required
/>
</div>
<div className={styles.formGroup}>
<label htmlFor="role">Role:</label>
<select
id="role"
name="role"
value={formData.role}
onChange={handleChange}
required
>
<option value="admin">admin</option>
<option value="member">member</option>
</select>
</div>
<div className={styles.formGroup}>
<label htmlFor="position">Position:</label>
<input
type="text"
id="position"
name="position"
value={formData.position}
onChange={handleChange}
/>
</div>
<div className={styles.horizontalLineLight}></div>
<div className={styles.submitButtonDiv}>
<button
type="submit"
className={styles.submitButton}>
Update
</button>
</div>
</form>
</div>
</div>
);
};
const popupStyles: { overlay: React.CSSProperties; popup: React.CSSProperties } = {
overlay: {
position: "fixed",
top: 0,
left: 0,
right: 0,
bottom: 0,
backgroundColor: "rgba(0,0,0,0.5)",
display: "flex",
justifyContent: "center",
alignItems: "center",
},
popup: {
backgroundColor: "#fff",
borderRadius: "8px",
boxShadow: "0 5px 15px rgba(0,0,0,0.3)",
position: "relative",
width: "400px",
maxWidth: "90%"
}
};
export default EditPopUp;

View file

@ -1,12 +0,0 @@
.editBtn {
background: none;
border: none;
cursor: pointer;
font-size: 18px;
color: #444;
height: 100;
}
.editBtn:hover {
color: #3d8df5;
}

View file

@ -1,42 +0,0 @@
import { FaEdit } from "react-icons/fa";
import { useState } from "react";
import styles from "./MitgliederItemEdit.module.css";
import EditPopUp from "./EditPopUp";
type MitgliederItemEditProps = {
user: {
id: string;
name: string;
email: string;
role: string;
position: string;
azure_id: string;
};
refetchUsers: () => Promise<void>;
};
const MitgliederItemEdit = ({ user, refetchUsers }: MitgliederItemEditProps) => {
const [editWindow, setEditWindow] = useState(false);
return (
<div>
<button
onClick={() => setEditWindow(true)}
className={styles.editBtn}
title="Edit user"
>
<FaEdit />
</button>
{editWindow && (
<EditPopUp
user={user}
closePopup={() => setEditWindow(false)}
refetchUsers={refetchUsers}
/>
)}
</div>
);
};
export default MitgliederItemEdit;

View file

@ -1,20 +0,0 @@
import { authorizedPut } from "../../../api";
type UserUpdateData = {
name?: string;
email?: string;
role?: string;
position?: string;
};
async function updateUser(userId: string, userData: UserUpdateData, token: string): Promise<void> {
try {
const response = await authorizedPut(`/api/user/${userId}`, userData, async () => token);
console.log("User updated successfully:", response.status);
} catch (error) {
console.error("Failed to update user:", error);
throw error;
}
}
export default updateUser;

View file

@ -1,69 +1,40 @@
import React, { useEffect, useState } from 'react'
import React from 'react'
import styles from './Sidebar.module.css'
import SidebarItem from './SidebarItem';
import { useAuthToken } from '../../auth/Hooks/use-auth-token';
import { authorizedGet } from '../../api';
import useSidebarData from './sidebarData';
import SidebarUser from './SidebarUser';
import { useCurrentUser } from '../../hooks/useCurrentUser';
interface SidebarItemType {
id: string;
name: string;
link?: string;
submenu?: SidebarItemType[];
}
}
interface SidebarProps {
data: SidebarItemType[];
}
interface User {
id: number,
name: string,
role: string,
}
//frontend\frontend\src\components\Sidebar\Sidebar.tsx
const Sidebar: React.FC<SidebarProps> = ({ data }) => {
const [user, setUser] = useState<User>({id: 0, name: '', role: ''});
const [_loading, setLoading] = useState(true);
const [_error, setError] = useState<string | null>(null);
const { getToken } = useAuthToken();
useEffect(() => {
fetchUser();
}, []);
const fetchUser = async () => {
setLoading(true);
setError(null);
try {
const response = await authorizedGet("/api/user/", getToken);
console.log(response)
setUser(response.data[0]);
} catch (err) {
console.error("Error fetching messages:", err);
setError("Failed to fetch messages");
} finally {
setLoading(false);
}
};
const Sidebar: React.FC<SidebarProps> = ({ data }) => {
const { user, isLoading, error } = useCurrentUser();
return (
<div className={styles.sidebarContainer}>
<div className={styles.logoContainer}>
<img src="..\..\..\src\assets\LogoPowerOn.png" alt="Logo" className={styles.logo} />
</div>
<div>
<SidebarUser user={user} />
<SidebarUser
user={{
id: user?.id || 0,
name: user?.fullName || user?.username || '',
role: user?.privilege || ''
}}
isLoading={isLoading}
error={error}
/>
</div>
<div className={styles.sidebar}>
@ -71,13 +42,12 @@ interface User {
return <SidebarItem key={item.id} item={item} />;
})}
</div>
</div>
)
}
}
const SidebarWithData: React.FC = () => {
return <Sidebar data={useSidebarData()} />;
};
return <Sidebar data={useSidebarData()} />;
};
export default SidebarWithData;

View file

@ -3,15 +3,19 @@ import { useMsal } from '@azure/msal-react'
import { FaUserCircle } from 'react-icons/fa'
import styles from './SidebarUser.module.css'
interface SidebarUserProps {
user: {
id: number,
name: string,
role: string,
}
interface User {
id: number;
name: string;
role: string;
}
const SidebarUser: React.FC<SidebarUserProps> = ({ user }) => {
interface SidebarUserProps {
user: User;
isLoading?: boolean;
error?: string | null;
}
const SidebarUser: React.FC<SidebarUserProps> = ({ user, isLoading, error }) => {
const { instance } = useMsal();
const handleLogout = async () => {
@ -29,6 +33,14 @@ const SidebarUser: React.FC<SidebarUserProps> = ({ user }) => {
}
};
if (isLoading) {
return <div className={styles.userContainer}>Lädt...</div>;
}
if (error) {
return <div className={styles.userContainer}>Fehler beim Laden des Benutzerprofils</div>;
}
return (
<div className={styles.user_section}>
<div className={styles.user_info}>

View file

@ -6,11 +6,11 @@ import { BiInfoSquare } from "react-icons/bi";
import { GoGear } from "react-icons/go";
import { FaRegFileAlt } from "react-icons/fa";
import { TbLogs } from "react-icons/tb";
import { useUserPrompts } from '../../auth/Hooks/use-user-prompts';
import { useMemo } from 'react';
export const useSidebarData = () => {
const { prompts, loading } = useUserPrompts();
return useMemo(() => [
{
@ -23,11 +23,7 @@ export const useSidebarData = () => {
id: '2',
name: 'Prompts',
icon: BsChatDots,
submenu: loading ? [] : prompts.map(prompt => ({
id: `prompt-${prompt.id}`,
name: prompt.prompt_title.substring(0, 100),
link: `/dashboard?expandedPrompt=${prompt.id}`,
})),
submenu: [],
},
{
id: '3',
@ -71,7 +67,7 @@ export const useSidebarData = () => {
link: '',
icon: BiInfoSquare,
},
], [prompts, loading]);
], []);
}
export default useSidebarData;

View file

@ -1,71 +0,0 @@
import { useState } from 'react';
import { useAuthToken } from '../auth/Hooks/use-auth-token';
import { downloadFile } from '../api';
import { authorizedDelete } from '../api';
export type FileOperationState = {
downloadingFiles: Set<number>;
downloadError: string | null;
deletingFiles: Set<number>;
deleteError: string | null;
};
export const useFileOperations = () => {
const [downloadingFiles, setDownloadingFiles] = useState<Set<number>>(new Set());
const [downloadError, setDownloadError] = useState<string | null>(null);
const [deletingFiles, setDeletingFiles] = useState<Set<number>>(new Set());
const [deleteError, setDeleteError] = useState<string | null>(null);
const { getToken } = useAuthToken();
const handleFileDownload = async (fileId: number, fileName: string) => {
try {
setDownloadError(null);
setDownloadingFiles(prev => new Set(prev).add(fileId));
await downloadFile(fileId, getToken);
} catch (error) {
console.error('Error downloading file:', error);
setDownloadError('Failed to download file. Please try again.');
} finally {
setDownloadingFiles(prev => {
const newSet = new Set(prev);
newSet.delete(fileId);
return newSet;
});
}
};
const handleFileDelete = async (fileId: number) => {
try {
setDeleteError(null);
setDeletingFiles(prev => new Set(prev).add(fileId));
await authorizedDelete(`/api/user/files/${fileId}`, getToken);
// Return true to indicate successful deletion
return true;
} catch (error) {
console.error('Error deleting file:', error);
setDeleteError('Failed to delete file. Please try again.');
return false;
} finally {
setDeletingFiles(prev => {
const newSet = new Set(prev);
newSet.delete(fileId);
return newSet;
});
}
};
return {
downloadingFiles,
downloadError,
deletingFiles,
deleteError,
handleFileDownload,
handleFileDelete,
clearDownloadError: () => setDownloadError(null),
clearDeleteError: () => setDeleteError(null)
};
};

92
src/hooks/useAuth.ts Normal file
View file

@ -0,0 +1,92 @@
import { useState } from 'react';
import axios from 'axios';
interface LoginResponse {
accessToken: string;
tokenType: string;
label?: any;
fieldLabels?: any;
}
interface UseAuthReturn {
login: (username: string, password: string) => Promise<LoginResponse>;
error: string | null;
isLoading: boolean;
}
export function useAuth(): UseAuthReturn {
const [error, setError] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(false);
const login = async (username: string, password: string): Promise<LoginResponse> => {
setIsLoading(true);
setError(null);
try {
// Create the form data in the exact format FastAPI expects
const params = new URLSearchParams();
params.append('username', username);
params.append('password', password);
params.append('grant_type', 'password');
params.append('scope', '');
params.append('client_id', '');
params.append('client_secret', '');
// Create a custom axios instance for this request
const instance = axios.create({
baseURL: 'http://127.0.0.1:8000',
withCredentials: true,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
const response = await instance.post('/api/token', params);
console.log('Login response:', response.data);
// Store the entire auth response
if (response.data.accessToken) {
localStorage.setItem('auth_data', JSON.stringify(response.data));
}
return response.data;
} catch (error: any) {
let errorMessage = 'An error occurred during login';
if (error.response) {
// Log the complete error details including the request that was sent
console.error('Login error details:', {
status: error.response.status,
statusText: error.response.statusText,
data: error.response.data,
headers: error.response.headers,
request: {
url: error.config?.url,
method: error.config?.method,
data: error.config?.data,
params: error.config?.params
}
});
errorMessage = error.response.data?.detail || 'Invalid username or password';
} else if (error.request) {
console.error('No response received:', error.request);
errorMessage = 'No response received from server';
} else {
console.error('Error:', error.message);
errorMessage = error.message;
}
setError(errorMessage);
throw error;
} finally {
setIsLoading(false);
}
};
return {
login,
error,
isLoading
};
}

View file

@ -0,0 +1,60 @@
import { useState, useEffect } from 'react';
import api from '../api';
interface CurrentUser {
id: number;
username: string;
fullName: string;
email: string;
privilege: string;
mandateId: number;
}
interface UseCurrentUserReturn {
user: CurrentUser | null;
error: string | null;
isLoading: boolean;
refetch: () => Promise<void>;
}
export function useCurrentUser(): UseCurrentUserReturn {
const [user, setUser] = useState<CurrentUser | null>(null);
const [error, setError] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(false);
const fetchCurrentUser = async () => {
setIsLoading(true);
setError(null);
try {
const response = await api.get('/api/user/me');
setUser(response.data);
} catch (error: any) {
let errorMessage = 'Fehler beim Abrufen des Benutzerprofils';
if (error.response) {
errorMessage = error.response.data?.detail || error.response.data?.message || errorMessage;
} else if (error.request) {
errorMessage = 'Keine Antwort vom Server erhalten';
} else {
errorMessage = error.message || errorMessage;
}
setError(errorMessage);
setUser(null);
} finally {
setIsLoading(false);
}
};
useEffect(() => {
fetchCurrentUser();
}, []);
return {
user,
error,
isLoading,
refetch: fetchCurrentUser
};
}

102
src/hooks/useMsalAuth.ts Normal file
View file

@ -0,0 +1,102 @@
import { useState } from 'react';
import { useMsal } from '@azure/msal-react';
import api from '../api';
interface MsalAuthResponse {
accessToken: string;
tokenType: string;
user: {
username: string;
email: string;
fullName: string;
mandateId: number;
};
}
interface UseMsalAuthReturn {
loginWithMsal: () => Promise<MsalAuthResponse>;
error: string | null;
isLoading: boolean;
}
export function useMsalAuth(): UseMsalAuthReturn {
const { instance, accounts } = useMsal();
const [error, setError] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(false);
const loginWithMsal = async (): Promise<MsalAuthResponse> => {
setIsLoading(true);
setError(null);
try {
let msalToken;
// If we have an account, try to get the token silently
if (accounts.length > 0) {
const silentRequest = {
scopes: ['user.read'],
account: accounts[0]
};
try {
const response = await instance.acquireTokenSilent(silentRequest);
msalToken = response.accessToken;
} catch (e) {
// If silent token acquisition fails, fall back to popup
const response = await instance.acquireTokenPopup(silentRequest);
msalToken = response.accessToken;
}
} else {
// No account, do popup login
const response = await instance.loginPopup({
scopes: ['user.read']
});
if (response.account) {
const tokenResponse = await instance.acquireTokenSilent({
scopes: ['user.read'],
account: response.account
});
msalToken = tokenResponse.accessToken;
} else {
throw new Error('Failed to get account after login');
}
}
// Exchange MSAL token for backend token
const response = await api.post('/api/msft/token', null, {
headers: {
'Authorization': `Bearer ${msalToken}`
}
});
// Store the backend token
if (response.data.accessToken) {
localStorage.setItem('auth_data', JSON.stringify(response.data));
}
return response.data;
} catch (error: any) {
let errorMessage = 'MSAL Login fehlgeschlagen';
if (error.response) {
errorMessage = error.response.data?.detail || error.response.data?.message || errorMessage;
} else if (error.request) {
errorMessage = 'Keine Antwort vom Server erhalten';
} else {
errorMessage = error.message || errorMessage;
}
setError(errorMessage);
throw new Error(errorMessage);
} finally {
setIsLoading(false);
}
};
return {
loginWithMsal,
error,
isLoading
};
}

View file

@ -0,0 +1,94 @@
import { useState } from 'react';
import { useMsal } from '@azure/msal-react';
import api from '../api';
interface MsalRegisterData {
username: string;
email: string;
fullName: string;
language?: string;
}
interface MsalRegisterResponse {
success: boolean;
message?: string;
user?: {
username: string;
email: string;
fullName: string;
};
}
interface UseMsalRegisterReturn {
registerWithMsal: () => Promise<MsalRegisterResponse>;
error: string | null;
isLoading: boolean;
}
export function useMsalRegister(): UseMsalRegisterReturn {
const { instance, accounts } = useMsal();
const [error, setError] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(false);
const registerWithMsal = async (): Promise<MsalRegisterResponse> => {
setIsLoading(true);
setError(null);
try {
if (!accounts || accounts.length === 0) {
// If not signed in with Microsoft, sign in first
await instance.loginPopup({
scopes: ['user.read']
});
}
// Get the current account
const currentAccount = instance.getAllAccounts()[0];
if (!currentAccount) {
throw new Error('No Microsoft account found');
}
// Prepare user data from Microsoft account
const userData: MsalRegisterData = {
username: currentAccount.username,
email: currentAccount.username,
fullName: currentAccount.name || currentAccount.username,
language: 'de'
};
// Register the user through our backend
const response = await api.post('/api/users/register-with-msal', userData, {
headers: {
'Content-Type': 'application/json'
}
});
return {
success: true,
message: 'Registration successful',
user: response.data
};
} catch (error: any) {
let errorMessage = 'MSAL Registrierung fehlgeschlagen';
if (error.response) {
errorMessage = error.response.data?.detail || error.response.data?.message || errorMessage;
} else if (error.request) {
errorMessage = 'Keine Antwort vom Server erhalten';
} else {
errorMessage = error.message || errorMessage;
}
setError(errorMessage);
throw new Error(errorMessage);
} finally {
setIsLoading(false);
}
};
return {
registerWithMsal,
error,
isLoading
};
}

82
src/hooks/useRegister.ts Normal file
View file

@ -0,0 +1,82 @@
import { useState } from 'react';
import api from '../api';
interface RegisterData {
username: string;
password: string;
email: string;
fullName: string;
language?: string;
}
interface RegisterResponse {
success: boolean;
message?: string;
user?: {
username: string;
email: string;
fullName: string;
};
}
interface UseRegisterReturn {
register: (data: RegisterData) => Promise<RegisterResponse>;
error: string | null;
isLoading: boolean;
}
export function useRegister(): UseRegisterReturn {
const [error, setError] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(false);
const register = async (userData: RegisterData): Promise<RegisterResponse> => {
setIsLoading(true);
setError(null);
try {
// Add default language if not provided
const dataToSend = {
...userData,
language: userData.language || 'de'
};
const response = await api.post('/api/users/register', dataToSend, {
headers: {
'Content-Type': 'application/json'
}
});
return {
success: true,
message: 'Registration successful',
user: response.data
};
} catch (error: any) {
let errorMessage = 'Registrierung fehlgeschlagen';
// Handle different types of errors
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
errorMessage = error.response.data?.detail || error.response.data?.message || errorMessage;
} else if (error.request) {
// The request was made but no response was received
errorMessage = 'Keine Antwort vom Server erhalten';
} else {
// Something happened in setting up the request
errorMessage = error.message || errorMessage;
}
setError(errorMessage);
throw new Error(errorMessage);
} finally {
setIsLoading(false);
}
};
return {
register,
error,
isLoading
};
}

105
src/hooks/useUser.ts Normal file
View file

@ -0,0 +1,105 @@
import { useState } from 'react';
import api from '../api';
interface User {
id: number;
username: string;
email: string;
fullName: string;
mandateId: number;
}
interface UseUserReturn {
deleteUser: (userId: number) => Promise<void>;
updateUser: (userId: number, userData: Partial<User>) => Promise<User>;
getUser: (userId: number) => Promise<User>;
error: string | null;
isLoading: boolean;
}
export function useUser(): UseUserReturn {
const [error, setError] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(false);
const deleteUser = async (userId: number): Promise<void> => {
setIsLoading(true);
setError(null);
try {
await api.delete(`/api/users/${userId}`);
} catch (error: any) {
let errorMessage = 'Fehler beim Löschen des Benutzers';
if (error.response) {
errorMessage = error.response.data?.detail || error.response.data?.message || errorMessage;
} else if (error.request) {
errorMessage = 'Keine Antwort vom Server erhalten';
} else {
errorMessage = error.message || errorMessage;
}
setError(errorMessage);
throw new Error(errorMessage);
} finally {
setIsLoading(false);
}
};
const updateUser = async (userId: number, userData: Partial<User>): Promise<User> => {
setIsLoading(true);
setError(null);
try {
const response = await api.put(`/api/users/${userId}`, userData);
return response.data;
} catch (error: any) {
let errorMessage = 'Fehler beim Aktualisieren des Benutzers';
if (error.response) {
errorMessage = error.response.data?.detail || error.response.data?.message || errorMessage;
} else if (error.request) {
errorMessage = 'Keine Antwort vom Server erhalten';
} else {
errorMessage = error.message || errorMessage;
}
setError(errorMessage);
throw new Error(errorMessage);
} finally {
setIsLoading(false);
}
};
const getUser = async (userId: number): Promise<User> => {
setIsLoading(true);
setError(null);
try {
const response = await api.get(`/api/users/${userId}`);
return response.data;
} catch (error: any) {
let errorMessage = 'Fehler beim Abrufen des Benutzers';
if (error.response) {
errorMessage = error.response.data?.detail || error.response.data?.message || errorMessage;
} else if (error.request) {
errorMessage = 'Keine Antwort vom Server erhalten';
} else {
errorMessage = error.message || errorMessage;
}
setError(errorMessage);
throw new Error(errorMessage);
} finally {
setIsLoading(false);
}
};
return {
deleteUser,
updateUser,
getUser,
error,
isLoading
};
}

View file

@ -1,7 +1,7 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import App from './App.tsx'
import { AuthProvider } from './auth/Hooks/auth-provider.tsx';
import { AuthProvider } from './auth/auth-provider.tsx';
createRoot(document.getElementById('root')!).render(
<StrictMode>

View file

@ -3,7 +3,7 @@ import { Outlet, useLocation } from 'react-router-dom';
import styles from './Home.module.css'
import Sidebar from '../../components/Sidebar';
import Sidebar from '../components/Sidebar';
import { AnimatePresence, motion } from "framer-motion";

View file

@ -1,4 +0,0 @@
.dashboardContainer {
margin: 51px 49px 0 36px;
}

View file

@ -1,13 +0,0 @@
import DashboardPrompt from '../../../components/DashboardPrompts/DashboardPrompt';
import styles from './Dashboard.module.css'
function Dashboard () {
return (
<div className={styles.dashboardContainer}>
<DashboardPrompt />
</div>
);
}
export default Dashboard;

View file

@ -1,90 +0,0 @@
.dateienContainer {
margin: 51px 49px 0 36px;
display: flex;
padding: 0px 30px 30px 30px;
flex-direction: column;
align-self: stretch;
border-radius: 30px;
border: 1px solid var(--f-1-f-1-f-1, #F1F1F1);
background: var(--Grayscale-True-White, #FFF);
position: relative;
box-shadow: 0px 2px 6px 0px rgba(194, 194, 194, 0.10);
max-height: calc(100vh - 100px);
overflow: hidden;
}
.horizontalLineLight {
width: 100%;
background-color: #F1F1F1;
height: 1px;
margin-top: 90px;
margin-left: -30px;
position: absolute;
}
.header {
display: flex;
gap: 30px;
align-items: flex-start;
height: 62px;
color: var(--Grayscale-Black, #24262B);
padding-top: 30px;
}
.datei_hinzufügen_button {
border-radius: 30px;
background: var(--Grayscale-Gray, #E9E9E9);
border: none;
outline: none;
text-align: left;
padding-left: 20px;
padding-right: 20px;
padding-top: 10px;
padding-bottom: 10px;
display: flex;
gap: 10px;
align-items: center;
}
.datei_hinzufügen_button:hover {
cursor: pointer;
}
.add_icon {
font-size: 16px;
}
.filesList {
list-style: none;
padding: 0;
margin: 0;
width: 100%;
overflow-y: auto;
}
.filesList li {
display: flex;
align-items: center;
height: 60px; /* Specific height for each item */
padding: 0 16px;
border-bottom: 1px solid #F1F1F1;
font-size: 16px;
transition: background-color 0.2s ease;
}
.actions {
display: flex;
gap: 10px;
align-items: center;
justify-content: center;
}
.error {
color: #d32f2f;
margin: 1rem 0;
padding: 0.5rem;
background-color: #ffebee;
border-radius: 4px;
text-align: center;
}

View file

@ -1,94 +0,0 @@
import styles from './Dateien.module.css'
import { useUserFiles } from '../../../auth/Hooks/use-user-files';
import { IoAddCircleOutline } from "react-icons/io5";
import DateienItem from '../../../components/Dateien/DateienItem';
import DateienUpload from './DateienHinzufügen/DateienUpload';
import { useState } from 'react';
import { useAuthToken } from '../../../auth/Hooks/use-auth-token';
import { useFileOperations } from '../../../hooks/use-file-operations';
import axios from 'axios';
function Dateien() {
const { files, loading, error, refetch } = useUserFiles();
const [isUploadOpen, setIsUploadOpen] = useState(false);
const [uploadError, setUploadError] = useState<string | null>(null);
const { getToken } = useAuthToken();
const { downloadError, deleteError } = useFileOperations();
const handleFileUpload = async (file: File) => {
try {
setUploadError(null);
console.log('Starting file upload for:', file.name);
const token = await getToken();
console.log('Got authentication token');
const formData = new FormData();
formData.append('file', file);
console.log('Sending request to backend...');
const response = await axios.post('http://localhost:8000/api/user/files/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data',
'Authorization': `Bearer ${token}`
}
});
console.log('Upload successful:', response.data);
await refetch();
} catch (error: any) {
console.error('Error uploading file:', error);
console.error('Error response:', error.response?.data);
setUploadError(error.response?.data?.detail || 'Failed to upload file. Please try again.');
}
};
const handleFileDeleted = () => {
refetch();
};
return (
<div className={styles.dateienContainer}>
<div className={styles.header}>
<button
className={styles.datei_hinzufügen_button}
onClick={() => setIsUploadOpen(true)}
>
<IoAddCircleOutline className={styles.add_icon}/>
Datei hinzufügen
</button>
</div>
<div className={styles.horizontalLineLight}></div>
<DateienUpload
isOpen={isUploadOpen}
onClose={() => setIsUploadOpen(false)}
onFileUpload={handleFileUpload}
/>
{(uploadError || downloadError || deleteError) && (
<p className={styles.error}>
{uploadError || downloadError || deleteError}
</p>
)}
{loading && <p>Loading files...</p>}
{error && <p>Error: {error}</p>}
{!loading && !error && files.length === 0 ? (
<p>No files found.</p>
) : (
<ul className={styles.filesList}>
{files.map(file => (
<DateienItem
key={file.id}
file={file}
onDelete={handleFileDeleted}
/>
))}
</ul>
)}
</div>
);
}
export default Dateien;

View file

@ -1,101 +0,0 @@
.overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
z-index: 1000;
}
.modal {
background: white;
padding: 2rem;
border-radius: 8px;
width: 90%;
max-width: 500px;
position: relative;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
.closeButton {
position: absolute;
top: 1rem;
right: 1rem;
background: none;
border: none;
font-size: 1.5rem;
cursor: pointer;
color: #666;
}
.closeButton:hover {
color: #333;
}
.dropzone {
border: 2px dashed #ccc;
border-radius: 4px;
padding: 2rem;
text-align: center;
cursor: pointer;
margin: 1rem 0;
transition: all 0.3s ease;
}
.dropzone.active {
border-color: #2196f3;
background-color: rgba(33, 150, 243, 0.1);
}
.uploadIcon {
font-size: 3rem;
color: #666;
margin-bottom: 1rem;
}
.dropzoneText {
color: #666;
}
.dropzoneText p {
margin: 0.5rem 0;
}
.browseButton {
background-color: #2196f3;
color: white;
border: none;
padding: 0.5rem 1rem;
border-radius: 4px;
cursor: pointer;
margin-top: 0.5rem;
}
.browseButton:hover {
background-color: #1976d2;
}
.selectedFile {
margin-top: 1rem;
padding: 1rem;
background-color: #f5f5f5;
border-radius: 4px;
}
.uploadButton {
background-color: #4caf50;
color: white;
border: none;
padding: 0.5rem 1rem;
border-radius: 4px;
cursor: pointer;
margin-top: 0.5rem;
}
.uploadButton:hover {
background-color: #388e3c;
}

View file

@ -1,80 +0,0 @@
import React, { useCallback, useState } from 'react';
import { useDropzone } from 'react-dropzone';
import styles from './DateienUpload.module.css';
import { IoCloudUploadOutline } from "react-icons/io5";
import { IoClose } from "react-icons/io5";
interface DateienUploadProps {
isOpen: boolean;
onClose: () => void;
onFileUpload: (file: File) => void;
}
function DateienUpload({ isOpen, onClose, onFileUpload }: DateienUploadProps) {
const [selectedFile, setSelectedFile] = useState<File | null>(null);
const onDrop = useCallback((acceptedFiles: File[]) => {
if (acceptedFiles.length > 0) {
setSelectedFile(acceptedFiles[0]);
}
}, []);
const { getRootProps, getInputProps, isDragActive } = useDropzone({
onDrop,
multiple: false
});
const handleUpload = () => {
if (selectedFile) {
onFileUpload(selectedFile);
setSelectedFile(null);
onClose();
}
};
if (!isOpen) return null;
return (
<div className={styles.overlay}>
<div className={styles.modal}>
<button className={styles.closeButton} onClick={onClose}>
<IoClose />
</button>
<h2>Datei hochladen</h2>
<div
{...getRootProps()}
className={`${styles.dropzone} ${isDragActive ? styles.active : ''}`}
>
<input {...getInputProps()} />
<IoCloudUploadOutline className={styles.uploadIcon} />
{isDragActive ? (
<p>Datei hier ablegen...</p>
) : (
<div className={styles.dropzoneText}>
<p>Dateien hierher ziehen</p>
<p>oder</p>
<button className={styles.browseButton}>
Durchsuchen
</button>
</div>
)}
</div>
{selectedFile && (
<div className={styles.selectedFile}>
<p>Ausgewählte Datei: {selectedFile.name}</p>
<button
className={styles.uploadButton}
onClick={handleUpload}
>
Hochladen
</button>
</div>
)}
</div>
</div>
);
}
export default DateienUpload;

View file

@ -1,85 +0,0 @@
.mitgliederContainer {
margin: 51px 49px 0 36px;
display: flex;
padding: 0px 30px 30px 30px;
flex-direction: column;
align-self: stretch;
border-radius: 30px;
border: 1px solid var(--f-1-f-1-f-1, #F1F1F1);
background: var(--Grayscale-True-White, #FFF);
position: relative;
box-shadow: 0px 2px 6px 0px rgba(194, 194, 194, 0.10);
max-height: calc(100vh - 100px);
overflow: hidden;
}
.horizontalLineLight {
width: 100%;
background-color: #F1F1F1;
height: 1px;
margin-top: 90px;
margin-left: -30px;
position: absolute;
}
.header{
display: flex;
gap: 30px;
align-items: flex-start;
height: 62px;
color: var(--Grayscale-Black, #24262B);
padding-top: 30px;
padding-bottom: 30px;
}
.mitglieder_hinzufügen_button {
border-radius: 30px;
background: var(--Grayscale-Gray, #E9E9E9);
border: none;
outline: none;
text-align: left;
padding-left: 20px;
padding-right: 20px;
padding-top: 10px;
padding-bottom: 10px;
display: flex;
gap: 10px;
align-items: center;
}
.mitglieder_hinzufügen_button:hover {
cursor: pointer;
}
.add_icon {
font-size: 16px;
}
.membersList {
list-style: none;
padding: 0;
margin: 0;
width: 100%;
overflow-y: auto; /* Enable vertical scrolling */
/* Space for the header line */
}
.membersList li {
display: flex;
align-items: center;
height: 60px; /* Specific height for each item */
padding: 0 16px;
border-bottom: 1px solid #F1F1F1;
font-size: 16px;
transition: background-color 0.2s ease;
}
.actions {
display: flex;
gap: 10px;
align-items: center;
justify-content: center;
}

View file

@ -1,39 +0,0 @@
import styles from './Mitglieder.module.css'
import { useOrgUsers } from '../../../auth/Hooks/get-all-users';
import MitgliederItem from '../../../components/Mitglieder/MitgliederItem';
import { IoPersonAddSharp } from "react-icons/io5";
function Mitglieder () {
const { users, loading, error, refetch } = useOrgUsers();
return (
<div className={styles.mitgliederContainer}>
<div className={styles.header}>
<button className={styles.mitglieder_hinzufügen_button}>
<IoPersonAddSharp className={styles.add_icon}/>
Mitglied hinzufügen
</button>
</div>
<div className={styles.horizontalLineLight}></div>
{users.length === 0 ? (
<p>No users found.</p>
) : (
<ul className={styles.membersList}>
{users.map(user => (
<MitgliederItem
key={user.azure_id}
user={user}
refetchUsers={refetch}
totalUsers={users.length}
/>
))}
</ul>
)}
</div>
);
}
export default Mitglieder;

View file

@ -1,16 +0,0 @@
function Organisation () {
return(
<div>
<h1>Organisation</h1>
<p>Hier sind die Infos über deine Organisation:</p>
</div>
)
}
export default Organisation;

View file

@ -1,3 +0,0 @@
import Home from "./Home";
export default Home;

View file

@ -1,108 +1,172 @@
.container {
display: flex;
min-height: calc(100vh - 20pt);
max-height: calc(100vh - 20pt);
background: var(--Grayscale-True-White, #FFF);
padding: 20pt;
box-sizing: border-box;
min-height: 100vh;
background-color: #ffffff;
}
.leftPanel {
flex: 1;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
padding: 2rem;
background-color: white;
border-radius: 8px;
margin-right: 20pt;
padding: 3rem;
background-color: #ffffff;
}
.rightPanel {
flex: 1;
background-color: #ffffff;
display: flex;
justify-content: flex-end;
align-items: center;
justify-content: center;
}
.logo {
margin-bottom: 2rem;
display: flex;
justify-content: center;
align-items: center;
}
.logo img {
height: 40px;
width: auto;
}
.loginBox {
width: 100%;
max-width: 400px;
text-align: center;
margin: auto;
width: 100%;
}
.title {
font-size: 2rem;
margin-bottom: 1.5rem;
color: var(--Grayscale-Black, #24262B);
font-family: Avenir, Helvetica, Arial, sans-serif;
font-weight: 600;
margin-bottom: 2rem;
color: #1a1a1a;
}
.loginForm {
display: flex;
flex-direction: column;
gap: 1rem;
}
.input {
width: 100%;
padding: 12px 16px;
border: 1px solid #e0e0e0;
border-radius: 8px;
font-size: 1rem;
transition: all 0.2s ease;
background-color: #ffffff;
}
.input:focus {
outline: none;
border-color: #0078d4;
box-shadow: 0 0 0 2px rgba(0, 120, 212, 0.1);
}
.input::placeholder {
color: #757575;
}
.button {
width: 100%;
padding: 0.8rem;
margin: 0.5rem 0;
border: none;
border-radius: 4px;
padding: 12px 20px;
border-radius: 8px;
font-size: 1rem;
font-weight: 500;
cursor: pointer;
transition: all 0.3s ease;
transition: all 0.2s ease;
border: none;
text-align: center;
}
.primaryButton {
background: var(--Brand-Purple-Purple, #5F59D4);
background-color: #0078d4;
color: white;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.primaryButton:hover {
background-color: #006cbd;
}
.microsoftButton {
background-color: #2f2f2f;
color: white;
}
.microsoftButton:hover {
background-color: #1f1f1f;
}
.divider {
display: flex;
align-items: center;
text-align: center;
margin: 1rem 0;
}
.divider::before,
.divider::after {
content: '';
flex: 1;
border-bottom: 1px solid #e0e0e0;
}
.divider span {
padding: 0 1rem;
color: #757575;
font-size: 0.9rem;
}
.registerLink {
display: flex;
align-items: center;
justify-content: center;
gap: 0.5rem;
margin-top: 1rem;
}
.registerLink span {
color: #757575;
font-size: 0.9rem;
}
.textButton {
background: none;
border: none;
color: #0078d4;
font-weight: 500;
cursor: pointer;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
transform: translateY(-1px);
padding: 0;
font-size: 0.9rem;
}
.secondaryButton {
background-color: #f0f0f0;
color: #333;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
.textButton:hover {
text-decoration: underline;
}
.secondaryButton:hover {
background-color: #e0e0e0;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
transform: translateY(-1px);
}
.button:disabled {
background-color: #cccccc;
button:disabled {
opacity: 0.7;
cursor: not-allowed;
}
.rightContent {
max-width: 100%;
height: 100%;
display: flex;
justify-content: flex-end;
align-items: center;
max-width: 80%;
padding: 2rem;
}
.rightContent img {
max-width: 100%;
max-height: 100%;
object-fit: contain;
width: 100%;
height: auto;
max-width: 500px;
}
.error {
color: #dc3545;
background-color: #f8d7da;
border: 1px solid #f5c6cb;
border-radius: 8px;
padding: 12px;
margin-bottom: 1rem;
font-size: 0.9rem;
text-align: center;
}

View file

@ -5,37 +5,44 @@ import { useState, useEffect } from 'react';
import styles from './Login.module.css';
import agentDiagram from '../assets/Frame 43.png';
import logo from '../assets/LogoPowerOn.png';
import { useAuth } from '../hooks/useAuth';
import { useMsalAuth } from '../hooks/useMsalAuth';
function Login() {
const { instance, accounts, inProgress } = useMsal();
const navigate = useNavigate();
const location = useLocation();
const [isLoggingIn, setIsLoggingIn] = useState(false);
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const { login, error: loginError, isLoading: isLoginLoading } = useAuth();
const { loginWithMsal, error: msalError, isLoading: isMsalLoading } = useMsalAuth();
// Get the page the user was trying to visit
const from = location.state?.from?.pathname || "/";
useEffect(() => {
if (accounts.length > 0 && inProgress === "none") {
console.log("User is already logged in, redirecting to:", from);
setTimeout(() => {
navigate(from, { replace: true });
}, 300);
handleMsalLogin();
} else {
console.log("User not logged in or auth in progress:", inProgress);
}
}, [accounts, inProgress, navigate, from]);
}, [accounts, inProgress]);
const handleLoginRedirect = async () => {
setIsLoggingIn(true);
const handleMsalLogin = async () => {
try {
console.log("Starting login process...");
// Use popup instead of redirect for easier debugging
await instance.loginPopup(loginRequest);
console.log("Login successful, auth should redirect shortly");
await loginWithMsal();
navigate(from, { replace: true });
} catch (error) {
console.error("MSAL login failed:", error);
}
};
const handleCredentialLogin = async () => {
try {
await login(username, password);
navigate(from, { replace: true });
} catch (error) {
console.error("Login failed:", error);
setIsLoggingIn(false);
}
};
@ -47,19 +54,55 @@ function Login() {
</div>
<div className={styles.loginBox}>
<h1 className={styles.title}>Sign In or Register Your Organisation</h1>
<button
className={`${styles.button} ${styles.primaryButton}`}
onClick={handleLoginRedirect}
disabled={isLoggingIn || inProgress !== "none"}
>
{isLoggingIn ? "Signing in..." : "Sign in with Microsoft"}
</button>
<button
className={`${styles.button} ${styles.secondaryButton}`}
onClick={() => navigate("/register-organisation")}
>
Register Organisation
</button>
<div className={styles.loginForm}>
{(loginError || msalError) && (
<div className={styles.error}>{loginError || msalError}</div>
)}
<input
type="text"
placeholder="Username"
value={username}
onChange={(e) => setUsername(e.target.value)}
className={styles.input}
/>
<input
type="password"
placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
className={styles.input}
/>
<button
className={`${styles.button} ${styles.primaryButton}`}
onClick={handleCredentialLogin}
disabled={isLoginLoading}
>
{isLoginLoading ? "Signing in..." : "Sign In"}
</button>
<div className={styles.divider}>
<span>or continue with</span>
</div>
<button
className={`${styles.button} ${styles.microsoftButton}`}
onClick={() => instance.loginPopup(loginRequest)}
disabled={isMsalLoading || inProgress !== "none"}
>
{isMsalLoading ? "Signing in..." : "Sign in with Microsoft"}
</button>
<div className={styles.registerLink}>
<span>Don't have an account?</span>
<button
className={styles.textButton}
onClick={() => navigate("/register")}
>
Register
</button>
</div>
</div>
</div>
</div>
<div className={styles.rightPanel}>

View file

@ -0,0 +1,213 @@
.container {
display: flex;
min-height: 100vh;
background-color: #ffffff;
}
.leftPanel {
flex: 1;
display: flex;
flex-direction: column;
padding: 3rem;
background-color: #ffffff;
}
.rightPanel {
flex: 1;
background-color: #ffffff;
display: flex;
align-items: center;
justify-content: center;
}
.logo {
margin-bottom: 2rem;
}
.logo img {
height: 40px;
}
.registerBox {
max-width: 500px;
margin: auto;
width: 100%;
}
.title {
font-size: 2rem;
font-weight: 600;
margin-bottom: 2rem;
color: #1a1a1a;
}
.registerForm {
display: flex;
flex-direction: column;
gap: 1.25rem;
}
.inputGroup {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.inputGroup label {
font-size: 0.9rem;
font-weight: 500;
color: #1a1a1a;
}
.input {
width: 100%;
padding: 12px 16px;
border: 1px solid #e0e0e0;
border-radius: 8px;
font-size: 1rem;
transition: all 0.2s ease;
background-color: #ffffff;
}
.input:focus {
outline: none;
border-color: #0078d4;
box-shadow: 0 0 0 2px rgba(0, 120, 212, 0.1);
}
.input::placeholder {
color: #757575;
}
.button {
width: 100%;
padding: 12px 20px;
border-radius: 8px;
font-size: 1rem;
font-weight: 500;
cursor: pointer;
transition: all 0.2s ease;
border: none;
text-align: center;
margin-top: 1rem;
}
.primaryButton {
background-color: #0078d4;
color: white;
}
.primaryButton:hover {
background-color: #006cbd;
}
.primaryButton:disabled {
background-color: #cccccc;
cursor: not-allowed;
}
.error {
color: #dc3545;
background-color: #f8d7da;
border: 1px solid #f5c6cb;
border-radius: 8px;
padding: 12px;
font-size: 0.9rem;
text-align: center;
}
.loginLink {
display: flex;
align-items: center;
justify-content: center;
gap: 0.5rem;
margin-top: 1.5rem;
padding-top: 1.5rem;
border-top: 1px solid #e0e0e0;
}
.loginLink span {
color: #757575;
font-size: 0.9rem;
}
.textButton {
background: none;
border: none;
color: #0078d4;
font-weight: 500;
cursor: pointer;
padding: 0;
font-size: 0.9rem;
}
.textButton:hover {
text-decoration: underline;
}
.rightContent {
max-width: 80%;
padding: 2rem;
}
.rightContent img {
width: 100%;
height: auto;
max-width: 500px;
}
/* Required field indicator */
label[htmlFor]::after {
content: ' *';
color: #dc3545;
}
.msalButton {
display: flex;
align-items: center;
justify-content: center;
gap: 10px;
width: 100%;
padding: 10px;
background-color: #fff;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 16px;
cursor: pointer;
transition: background-color 0.2s;
margin-bottom: 20px;
}
.msalButton:hover {
background-color: #f5f5f5;
}
.msalButton:disabled {
background-color: #f5f5f5;
cursor: not-allowed;
}
.msalLogo {
width: 20px;
height: 20px;
}
.divider {
display: flex;
align-items: center;
text-align: center;
margin: 20px 0;
}
.divider::before,
.divider::after {
content: '';
flex: 1;
border-bottom: 1px solid #ccc;
}
.divider span {
padding: 0 10px;
color: #666;
font-size: 14px;
}

220
src/pages/Register.tsx Normal file
View file

@ -0,0 +1,220 @@
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import styles from './Register.module.css';
import logo from '../assets/LogoPowerOn.png';
import agentDiagram from '../assets/Frame 43.png';
import { useRegister } from '../hooks/useRegister';
import { useMsalRegister } from '../hooks/useMsalRegister';
interface RegisterFormData {
username: string;
password: string;
confirmPassword: string;
email: string;
fullName: string;
}
function Register() {
const navigate = useNavigate();
const { register, error: registerError, isLoading } = useRegister();
const { registerWithMsal, error: msalError, isLoading: msalLoading } = useMsalRegister();
const [formData, setFormData] = useState<RegisterFormData>({
username: '',
password: '',
confirmPassword: '',
email: '',
fullName: ''
});
const [validationError, setValidationError] = useState<string | null>(null);
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const { name, value } = e.target;
setFormData(prev => ({
...prev,
[name]: value
}));
setValidationError(null);
};
const validateForm = (): boolean => {
if (!formData.username || !formData.password || !formData.confirmPassword || !formData.email || !formData.fullName) {
setValidationError('Bitte füllen Sie alle Pflichtfelder aus.');
return false;
}
if (formData.password !== formData.confirmPassword) {
setValidationError('Die Passwörter stimmen nicht überein.');
return false;
}
if (!formData.email.includes('@')) {
setValidationError('Bitte geben Sie eine gültige E-Mail-Adresse ein.');
return false;
}
return true;
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!validateForm()) {
return;
}
try {
const { confirmPassword, ...registrationData } = formData;
await register(registrationData);
navigate('/login', {
state: {
registered: true,
message: 'Registration erfolgreich. Bitte melden Sie sich an.'
}
});
} catch (err) {
console.error('Registration failed:', err);
}
};
const handleMsalRegister = async () => {
try {
await registerWithMsal();
navigate('/login', {
state: {
registered: true,
message: 'Microsoft Registration erfolgreich. Bitte melden Sie sich an.'
}
});
} catch (err) {
console.error('Microsoft registration failed:', err);
}
};
return (
<div className={styles.container}>
<div className={styles.leftPanel}>
<div className={styles.logo}>
<img src={logo} alt="PowerOn Logo" onClick={() => navigate('/')} style={{ cursor: 'pointer' }} />
</div>
<div className={styles.registerBox}>
<h1 className={styles.title}>Organisation registrieren</h1>
{/* Microsoft Register Button */}
<button
type="button"
className={`${styles.button} ${styles.msalButton}`}
onClick={handleMsalRegister}
disabled={msalLoading}
>
{msalLoading ? "Registrierung läuft..." : "Mit Microsoft registrieren"}
</button>
<div className={styles.divider}>
<span>oder</span>
</div>
<form className={styles.registerForm} onSubmit={handleSubmit}>
{(validationError || registerError || msalError) && (
<div className={styles.error}>
{validationError || registerError || msalError}
</div>
)}
<div className={styles.inputGroup}>
<label htmlFor="username">Benutzername *</label>
<input
id="username"
type="text"
name="username"
value={formData.username}
onChange={handleInputChange}
className={styles.input}
placeholder="Geben Sie Ihren Benutzernamen ein"
/>
</div>
<div className={styles.inputGroup}>
<label htmlFor="password">Passwort *</label>
<input
id="password"
type="password"
name="password"
value={formData.password}
onChange={handleInputChange}
className={styles.input}
placeholder="Geben Sie Ihr Passwort ein"
/>
</div>
<div className={styles.inputGroup}>
<label htmlFor="confirmPassword">Passwort bestätigen *</label>
<input
id="confirmPassword"
type="password"
name="confirmPassword"
value={formData.confirmPassword}
onChange={handleInputChange}
className={styles.input}
placeholder="Bestätigen Sie Ihr Passwort"
/>
</div>
<div className={styles.inputGroup}>
<label htmlFor="email">E-Mail *</label>
<input
id="email"
type="email"
name="email"
value={formData.email}
onChange={handleInputChange}
className={styles.input}
placeholder="Geben Sie Ihre E-Mail-Adresse ein"
/>
</div>
<div className={styles.inputGroup}>
<label htmlFor="fullName">Vollständiger Name *</label>
<input
id="fullName"
type="text"
name="fullName"
value={formData.fullName}
onChange={handleInputChange}
className={styles.input}
placeholder="Geben Sie Ihren vollständigen Namen ein"
/>
</div>
<button
type="submit"
className={`${styles.button} ${styles.primaryButton}`}
disabled={isLoading}
>
{isLoading ? "Registrierung läuft..." : "Registrieren"}
</button>
<div className={styles.loginLink}>
<span>Bereits registriert?</span>
<button
type="button"
className={styles.textButton}
onClick={() => navigate('/login')}
>
Jetzt anmelden
</button>
</div>
</form>
</div>
</div>
<div className={styles.rightPanel}>
<div className={styles.rightContent}>
<img src={agentDiagram} alt="Agent Diagram" />
</div>
</div>
</div>
);
}
export default Register;

View file

@ -1,152 +0,0 @@
import { useEffect, useState } from 'react';
import { useMsalLogin } from '../../auth/Hooks/use-msal-login';
import { useUserInfo } from '../../auth/Hooks/use-user-info';
import { useNavigate } from 'react-router-dom'; // Use useNavigate instead of useHistory
function RegisterOrganisation() {
const { login, isLoggingIn, error } = useMsalLogin();
const user = useUserInfo();
console.log(user);
const navigate = useNavigate(); // Initialize useNavigate hook
const [userName, setUserName] = useState("");
const [userEmail, setUserEmail] = useState("");
const [userAzureID, setUserAzureID] = useState("");
const [tenantID, setTenantID] = useState("");
const [organisationName, setOrganisationName] = useState("");
const [userPosition, setUserPosition] = useState("");
const [organisationSize, setOrganisationSize] = useState("");
const [country, setCountry] = useState("");
const [phoneNumber, setPhoneNumber] = useState("");
useEffect(() => {
if (user?.name) {setUserName(user.name);}
if (user?.email) {setUserEmail(user.email);}
if (user?.oid) {setUserAzureID(user.oid);}
if (user?.tenantId) {setTenantID(user.tenantId);}
}, [user]);
const handleRedirectToPricingSetup = () => {
// Use navigate to redirect to the pricing setup page
navigate('/register-pricing', {
state: {
user: {
userName,
userEmail,
userAzureID,
userPosition,
phoneNumber
},
organisation: {
organisationName,
organisationSize,
country,
tenantID,
}
}
});
};
return (
<div className="register-form">
<h1>Register Your Organisation</h1>
{!user?.name && (
<div className="login-section">
<p>Great! Please log in with MSAL:</p>
<button onClick={login} disabled={isLoggingIn} className="login-button">
{isLoggingIn ? "Logging in..." : "Login with Microsoft"}
</button>
{error && <p style={{ color: "red" }}>Login error: {error}</p>}
</div>
)}
{user?.name && (
<div className="user-info-section">
<p>Hello {user.name}</p>
<p>These are your information:</p>
<ul>
<li>Name: {user.name}</li>
<li>Email: {user.email}</li>
<li>Azure ID: {user.oid}</li>
<li>Tenant ID: {user.tenantId}</li>
</ul>
<p>Now, please enter your organisation's information:</p>
<form className="organisation-form">
<div className="form-group">
<label htmlFor="organisationName">Organisation Name:</label>
<input
type="text"
id="organisationName"
value={organisationName}
onChange={(e) => setOrganisationName(e.target.value)}
placeholder="Enter your organisation's name"
required
/>
</div>
<div className="form-group">
<label htmlFor="userPosition">Your Position:</label>
<input
type="text"
id="userPosition"
value={userPosition}
onChange={(e) => setUserPosition(e.target.value)}
placeholder="Enter your position"
required
/>
</div>
<div className="form-group">
<label htmlFor="organisationSize">Organisation Size:</label>
<input
type="text"
id="organisationSize"
value={organisationSize}
onChange={(e) => setOrganisationSize(e.target.value)}
placeholder="Enter your organisation's size"
required
/>
</div>
<div className="form-group">
<label htmlFor="country">Country:</label>
<input
type="text"
id="country"
value={country}
onChange={(e) => setCountry(e.target.value)}
placeholder="Enter your country"
required
/>
</div>
<div className="form-group">
<label htmlFor="phoneNumber">Phone Number:</label>
<input
type="tel"
id="phoneNumber"
value={phoneNumber}
onChange={(e) => setPhoneNumber(e.target.value)}
placeholder="Enter your phone number"
required
/>
</div>
{/* Button to navigate to pricing setup page */}
<button
type="button"
onClick={handleRedirectToPricingSetup}
className="redirect-button"
>
Go to Pricing Setup
</button>
</form>
</div>
)}
</div>
);
}
export default RegisterOrganisation;

View file

@ -1,52 +0,0 @@
// Example of PricingSetup component
import { useState } from 'react';
import { useLocation } from 'react-router-dom';
import { useNavigate } from 'react-router-dom';
function RegisterPricing() {
const [ price, setPrice ] = useState("");
const location = useLocation();
const navigate = useNavigate();
const organisationData = location.state?.organisation;
const organisationUser = location.state?.user;
const handleRedirectToSummary = () => {
// Use navigate to redirect to the pricing setup page
navigate('/register-summary', {
state: {
organisation: organisationData,
user: organisationUser,
price,
}
});
};
return (
<div>
<h1>Pricing Setup</h1>
<p>Here you can set up your pricing options!</p>
<input
type="text"
id="price"
value={price}
onChange={(e) => setPrice(e.target.value)}
placeholder="Enter your price"
required
/>
<button
type="button"
onClick={handleRedirectToSummary}
className="redirect-button"
>
Go to Summary
</button>
</div>
);
}
export default RegisterPricing;

View file

@ -1,117 +0,0 @@
import { useEffect, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import api from '../../api';
import { useAuthToken } from '../../auth/Hooks/use-auth-token';
function RegisterSummary() {
const navigate = useNavigate();
const location = useLocation();
const user = location.state?.user;
const organisation = location.state?.organisation;
const pricing = location.state?.price;
const [isSubmitting, setIsSubmitting] = useState(false);
const [submitSuccess, setSubmitSuccess] = useState(false);
const [submitError, setSubmitError] = useState<string | null>(null);
const [responseMessageUser, setResponseMessageUser] = useState<string | null>(null);
const [responseMessageOrganisation, setResponseMessageOrganisation] = useState<string | null>(null);
const { getToken } = useAuthToken();
const handleSubmit = async () => {
setIsSubmitting(true);
setSubmitError(null);
setResponseMessageUser(null);
setResponseMessageOrganisation(null);
const payload = {
organisation: {
name: organisation.organisationName,
size: organisation.organisationSize,
country: organisation.country,
tenant_id: organisation.tenantID
},
user: {
name: user.userName,
email: user.userEmail,
azure_id: user.userAzureID,
position: user.userPosition,
phone: user.phoneNumber,
role: "admin"
}
};
try {
const token = await getToken();
const response = await api.post(
'http://localhost:8000/api/organisation/register',
payload,
{
headers: {
Authorization: `Bearer ${token}`,
},
}
);
const message = response.data[0]?.message;
setResponseMessageOrganisation(message);
setSubmitSuccess(true);
} catch (error: any) {
const detailMessage = error?.response?.data?.detail;
setSubmitError(detailMessage || 'Something went wrong');
} finally {
setIsSubmitting(false);
};
};
useEffect(() => {
if (submitSuccess) {
setTimeout(() => {
navigate('/');
}, 2000); // 2-second delay
}
}, [submitSuccess]);
return (
<div>
<h1>Summary of Your Registration</h1>
<h2>Your Information</h2>
<ul>
<li>Name: {user.userName}</li>
<li>Email: {user.userEmail}</li>
<li>Your Position: {user.userPosition}</li>
<li>Phone Number: {user.phoneNumber}</li>
</ul>
{/* Display Organisation Data */}
<h2>Organisation Information</h2>
<ul>
<li>Tenant ID: {organisation.tenantID}</li>
<li>Organisation Name: {organisation.organisationName}</li>
<li>Organisation Size: {organisation.organisationSize}</li>
<li>Country: {organisation.country}</li>
</ul>
{/* Display Pricing Data */}
<h2>Pricing Information</h2>
<ul>
<li>Price: {pricing}</li>
</ul>
<button onClick={handleSubmit} disabled={isSubmitting}>
{isSubmitting ? 'Submitting...' : 'Submit Registration'}
</button>
{submitSuccess && <div><p style={{ color: 'green' }}>{responseMessageUser}</p><p style={{ color: 'green' }}>{responseMessageOrganisation}</p></div>}
{submitError && <p style={{ color: 'red' }}>Error: {submitError}</p>}
</div>
);
}
export default RegisterSummary;