Skip to content

Commit

Permalink
Organization screen (#431)
Browse files Browse the repository at this point in the history
* First approach for organization screen

* First approach showing list of organizations

* Adding and updating organizations

* Deleting organizations from UI
  • Loading branch information
javipacheco authored Sep 18, 2023
1 parent c32fb67 commit 44d9ad7
Show file tree
Hide file tree
Showing 14 changed files with 516 additions and 119 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import io.ktor.client.engine.cio.*
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation as ClientContentNegotiation
import io.ktor.client.plugins.auth.*
import io.ktor.client.plugins.logging.*
import io.ktor.http.*
import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.application.*
import io.ktor.server.auth.*
Expand Down Expand Up @@ -66,6 +67,7 @@ object Server {
server(factory = Netty, port = 8081, host = "0.0.0.0") {
install(CORS) {
allowNonSimpleContentTypes = true
HttpMethod.DefaultMethods.forEach { allowMethod(it) }
allowHeaders { true }
anyHost()
}
Expand Down
4 changes: 2 additions & 2 deletions server/web/src/components/Login/Login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ import { useContext, useState } from 'react';
import { Navigate, useLocation, useNavigate } from 'react-router-dom';
import styles from './Login.module.css';
import { LoadingContext } from '@/state/Loading';
import { postLogin } from '@/utils/api/login';
import { postLogin } from '@/utils/api/users';
import { FormLogin } from './FormLogin';
import { FormRegister } from './FormRegister';
import { isValidEmail } from '@/utils/validate';
import { postRegister } from '@/utils/api/register';
import { postRegister } from '@/utils/api/users';

export function RequireAuth({ children }: { children: JSX.Element }) {
let auth = useAuth();
Expand Down
3 changes: 0 additions & 3 deletions server/web/src/components/Pages/FeatureOne/FeatureOne.tsx

This file was deleted.

1 change: 0 additions & 1 deletion server/web/src/components/Pages/FeatureOne/index.ts

This file was deleted.

229 changes: 229 additions & 0 deletions server/web/src/components/Pages/Organizations/Organizations.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,229 @@
import { useAuth } from "@/state/Auth";
import { LoadingContext } from "@/state/Loading";
import { PostOrganizationProps, deleteOrganizations, getOrganizations, postOrganizations, putOrganizations } from "@/utils/api/organizations";
import {
Box,
Button,
Dialog,
DialogActions,
DialogContent,
DialogContentText,
DialogTitle,
Grid,
Paper,
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
TextField,
Typography
} from "@mui/material";
import { ChangeEvent, useContext, useEffect, useState } from "react";

export function Organizations() {

const auth = useAuth();

// functions to open/close the add/edit organization dialog

const [openAddEditOrganization, setOpenAddEditOrganization] = useState(false);

const [organizationforUpdating, setOrganizationForUpdating] = useState<OrganizationResponse | undefined>(undefined); // when adding is undefined and updating has the organization

const [organizationDataInDialog, setOrganizationDataInDialog] = useState<PostOrganizationProps | undefined>(undefined);

const handleClickAddOrganization = () => {
setOpenAddEditOrganization(true);
setOrganizationForUpdating(undefined);
setOrganizationDataInDialog(undefined);
};

const handleClickEditOrganization = (org: OrganizationResponse) => {
setOpenAddEditOrganization(true);
setOrganizationForUpdating(org);
setOrganizationDataInDialog({ name: org.name })
};

const handleCloseAddEditOrganization = () => {
setOpenAddEditOrganization(false);
};

const handleSaveAddEditOrganization = async () => {
if (organizationDataInDialog != undefined) {
if (organizationforUpdating == undefined)
await postOrganizations(auth.authToken, organizationDataInDialog);
else
await putOrganizations(auth.authToken, organizationforUpdating.id, organizationDataInDialog);

loadOrganizations();
}
setOpenAddEditOrganization(false);
};

const nameEditingHandleChange = (event: ChangeEvent<HTMLInputElement>) => {
setOrganizationDataInDialog({ name: event.target.value })
};

// functions to open/close the delete organization dialog

const [openDeleteOrganization, setOpenDeleteOrganization] = useState(false);

const [organizationforDeleting, setOrganizationForDeleting] = useState<OrganizationResponse | undefined>(undefined);

const handleClickDeleteOrganization = (org: OrganizationResponse) => {
setOpenDeleteOrganization(true);
setOrganizationForDeleting(org);
};

const handleCloseDeleteOrganzation = () => {
setOpenDeleteOrganization(false);
};

const handleDeleteOrganization = async () => {
if (organizationforDeleting != undefined)
await deleteOrganizations(auth.authToken, organizationforDeleting.id);

loadOrganizations();

setOpenDeleteOrganization(false);
};

// function to load organizations

const [loading, setLoading] = useContext(LoadingContext);

const [organizations, setOrganizations] = useState<OrganizationResponse[]>([]);

async function loadOrganizations() {
setLoading(true);
const response = await getOrganizations(auth.authToken);
setOrganizations(response);
setLoading(false);
}

useEffect(() => {
loadOrganizations()
}, []);

return <>
{/* List of organizations */}
{loading ?
<>
<Typography >
Loading...
</Typography>
</> :
<>
<Box sx={{ m: 2 }} />
<Grid container>
<Typography variant="h4" gutterBottom>
Organizations
</Typography>
<Button
onClick={handleClickAddOrganization}
variant="text"
disableElevation>
<Typography variant="button">Add</Typography>
</Button>
</Grid>
<Box sx={{ m: 2 }} />
<TableContainer component={Paper}>
<Table sx={{ minWidth: 650 }} aria-label="simple table">
<TableHead>
<TableRow>
<TableCell>Users</TableCell>
<TableCell>Name</TableCell>
<TableCell></TableCell>
<TableCell></TableCell>
</TableRow>
</TableHead>
<TableBody>
{organizations.map((organization) => (
<TableRow
key={organization.name}
sx={{ '&:last-child td, &:last-child th': { border: 0 } }}
>
<TableCell component="th" scope="row">
{organization.users}
</TableCell>
<TableCell component="th" scope="row" style={{ width: "90%" }}>
{organization.name}
</TableCell>
<TableCell align="right">
<Button
onClick={() => handleClickEditOrganization(organization)}
variant="text"
disableElevation>
<Typography variant="button">Edit</Typography>
</Button>
</TableCell>
<TableCell align="right">
<Button
onClick={() => handleClickDeleteOrganization(organization)}
variant="text"
disableElevation>
<Typography variant="button">Delete</Typography>
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
</>
}

{/* Add/Edit Organization Dialog */}

<Dialog open={openAddEditOrganization} onClose={handleCloseAddEditOrganization}>
<DialogTitle>{organizationforUpdating == undefined ? "New Organization" : "Update Organization"}</DialogTitle>
<DialogContent>
<TextField
autoFocus
margin="dense"
id="name"
label="Name"
fullWidth
variant="standard"
value={organizationDataInDialog?.name}
onChange={nameEditingHandleChange}
sx={{
width: { xs: '100%', sm: 550 },
}}
/>
</DialogContent>
<DialogActions>
<Button onClick={handleCloseAddEditOrganization}>Cancel</Button>
<Button onClick={handleSaveAddEditOrganization}>{organizationforUpdating == undefined ? "Create" : "Update"}</Button>
</DialogActions>
</Dialog>

{/* Delete Organization Dialog */}

<div>
<Dialog
open={openDeleteOrganization}
onClose={handleCloseDeleteOrganzation}
aria-labelledby="alert-dialog-title"
aria-describedby="alert-dialog-description"
>
<DialogTitle>
{"Delete Organizaction?"}
</DialogTitle>
<DialogContent>
<DialogContentText id="alert-dialog-description">
Are you sure you want to delete this organization?
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={handleCloseDeleteOrganzation}>No</Button>
<Button onClick={handleDeleteOrganization} autoFocus>
Yes
</Button>
</DialogActions>
</Dialog>
</div>
</>;
}
1 change: 1 addition & 0 deletions server/web/src/components/Pages/Organizations/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './Organizations';
4 changes: 2 additions & 2 deletions server/web/src/components/Sidebar/Sidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ export function Sidebar({ drawerWidth, open }: SidebarProps) {
</ListItemButton>
</ListItem>
<ListItem disablePadding>
<ListItemButton component={RouterLink} to="1">
<ListItemText primary="Feature One" />
<ListItemButton component={RouterLink} to="organizations">
<ListItemText primary="Organizations" />
</ListItemButton>
</ListItem>
<ListItem disablePadding>
Expand Down
6 changes: 3 additions & 3 deletions server/web/src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { ThemeProvider } from '@emotion/react';
import { App } from '@/components/App';
import { Root } from '@/components/Pages/Root';
import { ErrorPage } from '@/components/Pages/ErrorPage';
import { FeatureOne } from '@/components/Pages/FeatureOne';
import { Organizations } from '@/components/Pages/Organizations';
import { Chat } from '@/components/Pages/Chat';
import { GenericQuestion } from '@/components/Pages/GenericQuestion';
import { SettingsPage } from '@/components/Pages/SettingsPage';
Expand Down Expand Up @@ -46,10 +46,10 @@ const router = createBrowserRouter([
),
},
{
path: '1',
path: 'organizations',
element: (
<RequireAuth>
<FeatureOne />
<Organizations />
</RequireAuth>
),
},
Expand Down
23 changes: 20 additions & 3 deletions server/web/src/utils/api/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export type ApiOptions = {
export enum EndpointsEnum {
login = 'login',
register = 'register',
organization = 'v1/settings/org',
}

export type EndpointsTypes = {
Expand Down Expand Up @@ -89,9 +90,14 @@ const isErrorResponse = (b: unknown): b is ErrorResponse => {
return (b as ErrorResponse).error !== undefined;
};

export type ResponseData<T> = {
status: number;
data?: T;
};

export async function apiFetch<T = Record<string, unknown>>(
userApiConfig: ApiConfig,
): Promise<T> {
): Promise<ResponseData<T>> {
const apiConfig = {
...userApiConfig,
options: {
Expand All @@ -100,14 +106,25 @@ export async function apiFetch<T = Record<string, unknown>>(
},
};

let response: Response | undefined = undefined

try {
const response = await fetchWithTimeout(apiConfig.url, apiConfig.options);
response = await fetchWithTimeout(apiConfig.url, apiConfig.options);
const responseData: T | ErrorResponse = await response.json();

if (isErrorResponse(responseData)) throw responseData.error.message;

return responseData;
return {
status: response.status,
data: responseData,
};
} catch (error) {
if (response != undefined) {
return {
status: response.status,
data: undefined,
};
}
const errorMessage = `💢 Error: ${error}`;
console.error(errorMessage);
throw errorMessage;
Expand Down
Loading

0 comments on commit 44d9ad7

Please sign in to comment.