Skip to content

Commit

Permalink
add new endpoints for users to groups
Browse files Browse the repository at this point in the history
  • Loading branch information
diegoalzate committed May 13, 2024
1 parent ab16af3 commit e99b59a
Show file tree
Hide file tree
Showing 16 changed files with 147 additions and 97 deletions.
24 changes: 0 additions & 24 deletions packages/api/src/fetchUserGroups.ts

This file was deleted.

27 changes: 27 additions & 0 deletions packages/api/src/fetchUsersToGroups.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { GetUsersToGroupsResponse } from './types';

async function fetchUsersToGroups(userId: string): Promise<GetUsersToGroupsResponse | null> {
try {
const response = await fetch(
`${import.meta.env.VITE_SERVER_URL}/api/users/${userId}/users-to-groups`,
{
credentials: 'include',
headers: {
'Content-Type': 'application/json',
},
},
);

if (!response.ok) {
throw new Error(`HTTP Error! Status: ${response.status}`);
}

const userGroups = (await response.json()) as { data: GetUsersToGroupsResponse };
return userGroups.data;
} catch (error) {
console.error('Error fetching user groups:', error);
return null;
}
}

export default fetchUsersToGroups;
7 changes: 4 additions & 3 deletions packages/api/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export { default as fetchRegistrationFields } from './fetchRegistrationFields';
export { default as fetchRegistrations } from './fetchRegistrations';
export { default as fetchUserAttributes } from './fetchUserAttributes';
export { default as fetchUser } from './fetchUser';
export { default as fetchUserGroups } from './fetchUserGroups';
export { default as fetchUsersToGroups } from './fetchUsersToGroups';
export { default as fetchUserRegistrations } from './fetchUserRegistrations';
export { default as fetchUserVotes } from './fetchUserVotes';
export { default as logout } from './logout';
Expand All @@ -26,8 +26,9 @@ export { default as postGroup } from './postGroup';
export { default as postLike } from './postLike';
export { default as postPcdStr } from './postVerify';
export { default as postRegistration } from './postRegistration';
export { default as postUserToGroups } from './postUserToGroups';
export { default as postUsersToGroups } from './postUsersToGroups';
export { default as postVotes } from './postVotes';
export { default as putRegistration } from './putRegistration';
export { default as updateUser } from './putUser';
export { default as putUser } from './putUser';
export { default as putUsersToGroups } from './putUsersToGroups';
export * from './types';
File renamed without changes.
6 changes: 3 additions & 3 deletions packages/api/src/putUsersToGroups.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { PostUsersToGroupsResponse, PutUsersToGroupsRequest } from './types';

async function postUserToGroups({
async function postUsersToGroups({
groupId,
userToGroupId,
}: PutUsersToGroupsRequest): Promise<PostUsersToGroupsResponse | null> {
try {
const response = await fetch(
`${import.meta.env.VITE_SERVER_URL}/api/users-to-groups/${userToGroupId}`,
{
method: 'POST',
method: 'PUT',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
Expand All @@ -32,4 +32,4 @@ async function postUserToGroups({
}
}

export default postUserToGroups;
export default postUsersToGroups;
21 changes: 0 additions & 21 deletions packages/api/src/types/UserToGroupsType.ts

This file was deleted.

46 changes: 46 additions & 0 deletions packages/api/src/types/UsersToGroupsType.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
type UsersToGroups = {
id: string;
createdAt: Date;
updatedAt: Date;
userId: string;
groupCategoryId: string | null;
groupId: string;
};

export type GetUsersToGroupsResponse = {
id: string;
createdAt: string;
updatedAt: string;
userId: string;
groupCategoryId: string | null;
groupId: string;
group: {
id: string;
name: string;
createdAt: Date;
updatedAt: Date;
description: string | null;
secret: string | null;
groupCategoryId: string | null;
groupCategory?: {
createdAt: string;
eventId: string;
id: string;
name: string;
updatedAt: string;
};
};
}[];

export type PostUsersToGroupsRequest = {
groupId?: string;
secret?: string;
};

export type PutUsersToGroupsRequest = {
userToGroupId: string;
groupId: string;
};

export type PostUsersToGroupsResponse = UsersToGroups;
export type PutUsersToGroupsResponse = UsersToGroups;
2 changes: 1 addition & 1 deletion packages/api/src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,6 @@ export * from './RegistrationFieldOptionType';
export * from './RegistrationFieldType';
export * from './RegistrationType';
export * from './UserAttributesType';
export * from './UserToGroupsType';
export * from './UsersToGroupsType';
export * from './UserType';
export * from './UserVotesType';
8 changes: 4 additions & 4 deletions packages/berlin/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { QueryClient } from '@tanstack/react-query';
import { useAppStore } from './store';

// API
import { fetchEvents, fetchUserData, fetchCycle, fetchRegistrations } from 'api';
import { fetchEvents, fetchUser, fetchCycle, fetchRegistrations } from 'api';

// Pages
import { default as BerlinLayout } from './layout/index.ts';
Expand All @@ -31,7 +31,7 @@ import SecretGroupRegistration from './pages/SecretGroupRegistration.tsx';
async function redirectToLandingLoader(queryClient: QueryClient) {
const user = await queryClient.fetchQuery({
queryKey: ['user'],
queryFn: fetchUserData,
queryFn: fetchUser,
staleTime: 10000,
});

Expand All @@ -47,7 +47,7 @@ async function redirectToLandingLoader(queryClient: QueryClient) {
async function redirectToAccount(queryClient: QueryClient) {
const user = await queryClient.fetchQuery({
queryKey: ['user'],
queryFn: fetchUserData,
queryFn: fetchUser,
});

if (user?.username) {
Expand All @@ -65,7 +65,7 @@ async function redirectToAccount(queryClient: QueryClient) {
async function redirectOnLandingLoader(queryClient: QueryClient) {
const user = await queryClient.fetchQuery({
queryKey: ['user'],
queryFn: fetchUserData,
queryFn: fetchUser,
});

if (!user) {
Expand Down
4 changes: 2 additions & 2 deletions packages/berlin/src/hooks/useUser.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useQuery } from '@tanstack/react-query';
import { fetchUserData } from 'api';
import { fetchUser } from 'api';

function useUser() {
const {
Expand All @@ -8,7 +8,7 @@ function useUser() {
isError,
} = useQuery({
queryKey: ['user'],
queryFn: fetchUserData,
queryFn: fetchUser,
});

return { user, isLoading, isError };
Expand Down
50 changes: 33 additions & 17 deletions packages/berlin/src/pages/Account.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,14 @@ import toast from 'react-hot-toast';

// API Calls
import {
GetUserResponse,
type GetUserResponse,
fetchEvents,
fetchGroups,
fetchUserAttributes,
fetchUserGroups,
updateUserData,
fetchUsersToGroups,
putUser,
putUsersToGroups,
postUsersToGroups,
} from 'api';

// Components
Expand Down Expand Up @@ -59,7 +61,8 @@ type InitialUser = {
firstName: string;
lastName: string;
email: string;
group: string;
userToGroupId?: string;
groupId: string;
telegram: string | null;
userAttributes: UserAttributes | undefined;
};
Expand All @@ -73,9 +76,9 @@ function Account() {
enabled: !!user?.id,
});

const { data: userGroups, isLoading: userGroupsIsLoading } = useQuery({
const { data: usersToGroups, isLoading: userGroupsIsLoading } = useQuery({
queryKey: ['user', user?.id, 'groups'],
queryFn: () => fetchUserGroups(user?.id || ''),
queryFn: () => fetchUsersToGroups(user?.id || ''),
enabled: !!user?.id,
});

Expand All @@ -98,7 +101,9 @@ function Account() {
lastName: user?.lastName || '',
email: user?.email || '',
telegram: user?.telegram || null,
group: (userGroups && userGroups[0]?.id) || '',
userToGroupId: usersToGroups?.find((g) => g.group.groupCategory?.name === 'affiliation')?.id,
groupId:
usersToGroups?.find((g) => g.group.groupCategory?.name === 'affiliation')?.group.id || '',
userAttributes: userAttributes?.reduce(
(acc, curr) => {
if (curr.attributeKey === 'credentialsGroup') {
Expand Down Expand Up @@ -136,7 +141,7 @@ function Account() {
} as UserAttributes,
),
};
}, [user, userGroups, userAttributes]);
}, [user, usersToGroups, userAttributes]);

if (userIsLoading || userGroupsIsLoading || userAttributesIsLoading) {
return <Title>Loading...</Title>;
Expand All @@ -161,7 +166,7 @@ function AccountForm({
const queryClient = useQueryClient();

const { mutate: mutateUserData } = useMutation({
mutationFn: updateUserData,
mutationFn: putUser,
onSuccess: async (body) => {
console.log({ body });
if (!body) {
Expand Down Expand Up @@ -231,29 +236,40 @@ function AccountForm({
control,
});

const watchedGroupInputId = useWatch({ control, name: 'group' });
const watchedGroupInputId = useWatch({ control, name: 'groupId' });
const customGroupName = 'Custom Affiliation';
const customGroup = groups?.find(
(group) => group.name.toLocaleLowerCase() === customGroupName.toLocaleLowerCase(),
);

const onSubmit = (value: typeof initialUser) => {
const onSubmit = async (value: typeof initialUser) => {
if (isValid && user && user.id) {
mutateUserData({
await mutateUserData({
userId: user.id,
username: value.username,
email: value.email,
firstName: value.firstName,
lastName: value.lastName,
telegram: value.telegram?.trim() !== '' ? value.telegram?.trim() : null,
groupIds: [value.group],
userAttributes: {
...value.userAttributes,
credentialsGroup: JSON.stringify(value.userAttributes?.credentialsGroup),
publications: JSON.stringify(value.userAttributes?.publications),
contributions: JSON.stringify(value.userAttributes?.contributions),
},
});

// Create user to group if it doesn't exist
if (!value.userToGroupId) {
await postUsersToGroups({
groupId: value.groupId,
});
} else {
await putUsersToGroups({
groupId: value.groupId,
userToGroupId: value.userToGroupId,
});
}
}
};

Expand All @@ -278,8 +294,8 @@ function AccountForm({

if (customGroup) {
// set group to custom group id
setValue('group', customGroup?.id);
trigger('group');
setValue('groupId', customGroup?.id);
trigger('groupId');
}
// set otherGroupName to value
setValue('userAttributes.customGroupName', value);
Expand Down Expand Up @@ -323,7 +339,7 @@ function AccountForm({
{...register('telegram')}
/>
<Controller
name="group"
name="groupId"
control={control}
rules={{ required: 'Affiliation is required' }}
render={({ field }) => (
Expand All @@ -340,7 +356,7 @@ function AccountForm({
onBlur={field.onBlur}
onOptionCreate={(value) => groupOnCreate(groups, customGroupName, value)}
value={field.value}
errors={[errors.group?.message ?? '']}
errors={[errors.groupId?.message ?? '']}
/>
{watchedGroupInputId === customGroup?.id &&
initialUser.userAttributes?.customGroupName && (
Expand Down
8 changes: 4 additions & 4 deletions packages/berlin/src/pages/PublicGroupRegistration.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import toast from 'react-hot-toast';
import useUser from '../hooks/useUser';

// API
import { fetchGroups, postUserToGroups } from 'api';
import { fetchGroups, postUsersToGroups } from 'api';

// Data
import publicGroups from '../data/publicGroups';
Expand Down Expand Up @@ -50,8 +50,8 @@ function PublicGroupRegistration() {

const selectData = groups?.map((group) => ({ id: group.id, name: group.name })) ?? [];

const { mutate: postUserToGroupsMutation } = useMutation({
mutationFn: postUserToGroups,
const { mutate: postUsersToGroupsMutation } = useMutation({
mutationFn: postUsersToGroups,
onSuccess: (body) => {
if (!body) {
return;
Expand All @@ -66,7 +66,7 @@ function PublicGroupRegistration() {

const onSubmit = () => {
if (isValid) {
postUserToGroupsMutation({ groupId: getValues('group') });
postUsersToGroupsMutation({ groupId: getValues('group') });
setValue('group', '');
reset();
}
Expand Down
Loading

0 comments on commit e99b59a

Please sign in to comment.