Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added ability to invite user as owner #938

Merged
merged 28 commits into from
Nov 28, 2024
Merged
Show file tree
Hide file tree
Changes from 19 commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
9eabf14
Add dummy buttons to ownerships page
Anahkiasen Oct 19, 2024
89fbcf5
Merge branch 'main' into feature/III-6358
Anahkiasen Oct 19, 2024
5b1d248
Add modal skeleton
Anahkiasen Oct 19, 2024
74eac94
Add translations block
Anahkiasen Oct 19, 2024
c72a684
Get organizer from server side
Anahkiasen Oct 19, 2024
e40a1b9
Work on mutation logic
Anahkiasen Oct 19, 2024
550a715
Add approval
Anahkiasen Oct 19, 2024
7b73765
Linting
Anahkiasen Oct 21, 2024
2198c8e
Merge branch 'main' into feature/III-6358
Anahkiasen Oct 23, 2024
7394fc7
Use new ownerEmail parameter
Anahkiasen Oct 23, 2024
506a202
Merge branch 'main' into feature/III-6358
Anahkiasen Oct 31, 2024
ca1d229
Work on centralizing logic
Anahkiasen Oct 31, 2024
0cd81f0
Work on centralizing logic from actions
Anahkiasen Oct 31, 2024
0dc3f49
Fixed unparsed @id
Anahkiasen Oct 31, 2024
5e5da88
Merge branch 'main' into feature/III-6358
Anahkiasen Nov 14, 2024
a61d891
Work on ownership request flow
Anahkiasen Nov 15, 2024
c41c7b8
Remove leftover prop
Anahkiasen Nov 15, 2024
8a9fdf1
Add types
Anahkiasen Nov 18, 2024
63c93c3
Linting
Anahkiasen Nov 18, 2024
b1bfa87
Add translations
Anahkiasen Nov 18, 2024
5bd45a1
Add start of ownership test
Anahkiasen Nov 20, 2024
cf18752
Work on requesting ownership
Anahkiasen Nov 20, 2024
c9106ec
Use correct organizer name
Anahkiasen Nov 20, 2024
df7d517
Merge branch 'feature/III-6358' into feature/III-6417
Anahkiasen Nov 21, 2024
c6671f3
Add E2E test to add and remove ownership
Anahkiasen Nov 21, 2024
8cf6a0d
No braces I know
Anahkiasen Nov 21, 2024
0b20501
Merge pull request #958 from cultuurnet/feature/III-6417
Anahkiasen Nov 28, 2024
65464b2
Merge branch 'main' into feature/III-6358
Anahkiasen Nov 28, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions src/hooks/api/ownerships.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,27 @@ export const RequestState = {

type RequestState = Values<typeof RequestState>;

const requestOwnership = async ({ headers, itemId, itemType, ownerEmail }) =>
fetchFromApi({
path: `/ownerships`,
options: {
method: 'POST',
headers,
body: JSON.stringify({
ownerEmail,
itemId,
itemType,
}),
},
});

const useRequestOwnershipMutation = (configuration: UseQueryOptions = {}) =>
useAuthenticatedMutation({
mutationFn: requestOwnership,
mutationKey: 'ownerships-request-ownership',
...configuration,
});

const getOwnershipRequests = async ({ headers, organizerId }) => {
const res = await fetchFromApi({
path: '/ownerships/',
Expand Down Expand Up @@ -113,4 +134,5 @@ export {
useDeleteOwnershipRequestMutation,
useGetOwnershipRequestsQuery,
useRejectOwnershipRequestMutation,
useRequestOwnershipMutation,
};
10 changes: 10 additions & 0 deletions src/i18n/nl.json
Original file line number Diff line number Diff line change
Expand Up @@ -1034,6 +1034,16 @@
},
"pending": "Openstaande aanvragen tot beheer",
"close": "Sluiten",
"request_modal": {
"title": "Beheerder toevoegen aan {{name}}",
"email": "E-mailadres",
"email_error": "Geen geldig e-mailadres",
"success": "{{ownerEmail}} is nu beheerder van {{organizerName}} en kan voortaan de organisatiepagina en evenementen van {{organizerName}} bewerken.",
"actions": {
"confirm": "Beheerder toevoegen",
"cancel": "Annuleren"
}
},
"confirm_modal": {
"title": "Aanvraag tot beheer goedkeuren",
"body": "Ben je zeker dat je de aanvraag van {{ownerEmail}} wilt goedkeuren? <br/><br/> Van zodra je de aanvraag goedkeurt zal {{ownerEmail}} de organisatiepagina en de evenementen van {{organizerName}} kunnen bewerken.",
Expand Down
113 changes: 90 additions & 23 deletions src/pages/organizers/[organizerId]/ownerships/index.page.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import groupBy from 'lodash/groupBy';
import { useRouter } from 'next/router';
import { useMemo, useState } from 'react';
import { useForm } from 'react-hook-form';
import { Trans, useTranslation } from 'react-i18next';
import { dehydrate, useQueryClient } from 'react-query';

Expand All @@ -12,26 +13,31 @@ import {
useDeleteOwnershipRequestMutation,
useGetOwnershipRequestsQuery,
useRejectOwnershipRequestMutation,
useRequestOwnershipMutation,
} from '@/hooks/api/ownerships';
import { Organizer } from '@/types/Organizer';
import { Values } from '@/types/Values';
import { Alert, AlertVariants } from '@/ui/Alert';
import { Box } from '@/ui/Box';
import { Button, ButtonVariants } from '@/ui/Button';
import { Icon } from '@/ui/Icon';
import { FormElement } from '@/ui/FormElement';
import { Icons } from '@/ui/Icon';
import { Inline } from '@/ui/Inline';
import { Input } from '@/ui/Input';
import { Modal, ModalSizes, ModalVariants } from '@/ui/Modal';
import { Page } from '@/ui/Page';
import { Stack } from '@/ui/Stack';
import { Title } from '@/ui/Title';
import { ErrorBody, FetchError } from '@/utils/fetchFromApi';
import { getApplicationServerSideProps } from '@/utils/getApplicationServerSideProps';
import { parseOfferId } from '@/utils/parseOfferId';

import { OwnershipsTable } from './OwnershipsTable';

const ActionType = {
APPROVE: 'approve',
APPROVE: 'confirm',
REJECT: 'reject',
REQUEST: 'request',
} as const;

type ActionType = Values<typeof ActionType>;
Expand All @@ -40,32 +46,33 @@ const Ownership = () => {
const router = useRouter();
const { t, i18n } = useTranslation();
const queryClient = useQueryClient();
const [selectedRequest, setSelectedRequest] = useState<OwnershipRequest>();
const [requestToBeDeleted, setRequestToBeDeleted] =
useState<OwnershipRequest>();
const [isQuestionModalVisible, setIsQuestionModalVisible] = useState(false);
const [actionType, setActionType] = useState<ActionType>();
const [isOpen, setIsOpen] = useState(false);
const [isQuestionModalVisible, setIsQuestionModalVisible] = useState(false);
const [isSuccessAlertVisible, setIsSuccessAlertVisible] = useState(false);
const isApproveAction = actionType === ActionType.APPROVE;
const translationsPath = `organizers.ownerships.${
isApproveAction ? 'confirm' : 'reject'
}_modal`;
const [requestToBeDeleted, setRequestToBeDeleted] =
useState<OwnershipRequest>();
const [selectedRequest, setSelectedRequest] = useState<OwnershipRequest>();
const translationsPath = `organizers.ownerships.${actionType}_modal`;
const { register, formState, getValues, setError } = useForm();

const organizerId = useMemo(
() => router.query.organizerId as string,
[router.query.organizerId],
);

const getOrganizerByIdQuery = useGetOrganizerByIdQuery({
id: organizerId,
});

// @ts-expect-error
const organizer: Organizer = getOrganizerByIdQuery?.data;
const organizerName =
organizer?.name?.[i18n.language] ??
organizer?.name?.[organizer.mainLanguage];

const getOwnershipRequestsQuery = useGetOwnershipRequestsQuery({
organizerId: organizerId,
organizerId,
});

const requestsByState: { [key: string]: OwnershipRequest[] } = useMemo(
Expand All @@ -90,6 +97,25 @@ const Ownership = () => {
},
});

const approveRequestedOwnership = async (ownershipId: string) => {
setIsSuccessAlertVisible(true);
setIsOpen(false);

return approveOwnershipRequestMutation.mutateAsync({ ownershipId });
};

const requestOwnership = useRequestOwnershipMutation({
onError: async (error: FetchError<ErrorBody>) => {
if (error.body.status === 409) {
const ownershipId = error.body.detail.split('with id ')[1];
await approveRequestedOwnership(ownershipId);
} else {
setError('email', { message: error.body.detail || error.title });
Copy link
Contributor Author

@Anahkiasen Anahkiasen Nov 18, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@simon-debruijn I did this originally to cascade the email errors back to the user UI, but ended up reverting it to a generic since but it allowed users to probe for existing emails in the system, but now it's sometimes cryptic why an email is rejected. Do you think we should show the actual errors?

}
},
onSuccess: (data: { id: string }) => approveRequestedOwnership(data.id),
});

const rejectOwnershipRequestMutation = useRejectOwnershipRequestMutation({
onSuccess: async () => {
await queryClient.invalidateQueries('ownership-requests');
Expand All @@ -106,14 +132,21 @@ const Ownership = () => {
});

const handleConfirm = () => {
if (isApproveAction) {
approveOwnershipRequestMutation.mutate({
ownershipId: selectedRequest.id,
});
} else {
rejectOwnershipRequestMutation.mutate({
ownershipId: selectedRequest.id,
});
switch (actionType) {
case ActionType.APPROVE:
return approveOwnershipRequestMutation.mutate({
ownershipId: selectedRequest.id,
});
case ActionType.REJECT:
return rejectOwnershipRequestMutation.mutate({
ownershipId: selectedRequest.id,
});
case ActionType.REQUEST:
return requestOwnership.mutate({
ownerEmail: getValues('email'),
itemType: 'organizer',
itemId: parseOfferId(organizer['@id']),
});
}
};

Expand Down Expand Up @@ -144,8 +177,9 @@ const Ownership = () => {
<Trans
i18nKey={`${translationsPath}.success`}
values={{
ownerEmail: selectedRequest?.ownerEmail,
organizerName: organizerName,
ownerEmail:
selectedRequest?.ownerEmail ?? getValues('email'),
organizerName,
}}
/>
</Alert>
Expand Down Expand Up @@ -235,7 +269,7 @@ const Ownership = () => {
i18nKey={`${translationsPath}.body`}
values={{
ownerEmail: selectedRequest?.ownerEmail,
organizerName: organizerName,
organizerName,
}}
/>
</Box>
Expand All @@ -244,7 +278,14 @@ const Ownership = () => {
)}
</Stack>
<Stack spacing={3.5} flex={1}>
<Button variant={ButtonVariants.PRIMARY}>
<Button
variant={ButtonVariants.PRIMARY}
onClick={() => {
setIsSuccessAlertVisible(false);
setActionType(ActionType.REQUEST);
setIsOpen(true);
}}
>
{t('organizers.ownerships.actions.add')}
</Button>
<Button
Expand All @@ -257,6 +298,32 @@ const Ownership = () => {
</Button>
</Stack>
</Inline>
<Modal
visible={isOpen}
variant={ModalVariants.QUESTION}
size={ModalSizes.MD}
title={t('organizers.ownerships.request_modal.title', {
name: organizer.name,
})}
confirmTitle={t(
'organizers.ownerships.request_modal.actions.confirm',
)}
cancelTitle={t('organizers.ownerships.request_modal.actions.cancel')}
onConfirm={handleConfirm}
onClose={() => setIsOpen(false)}
>
<Stack padding={4}>
<FormElement
id={'email'}
Component={<Input type={'email'} {...register('email')} />}
label={t('organizers.ownerships.request_modal.email')}
error={
formState.errors.email &&
t(`organizers.ownerships.request_modal.email_error`)
}
/>
</Stack>
</Modal>
</Page.Content>
</Page>
);
Expand Down
14 changes: 9 additions & 5 deletions src/utils/fetchFromApi.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import omit from 'lodash/omit';
import getConfig from 'next/config';

class FetchError extends Error {
class FetchError<TBody = any> extends Error {
title?: string;
status: number;
body?: any;
body?: TBody;

constructor(status: number, message: string, body?: any) {
super(message);
Expand All @@ -18,15 +19,18 @@ type ErrorObject = {
message: string;
};

export type DuplicatePlaceErrorBody = {
export type ErrorBody = {
detail: string;
query?: string;
duplicatePlaceUri?: string;
status: number;
title: string;
type: string;
};

export type DuplicatePlaceErrorBody = ErrorBody & {
query?: string;
duplicatePlaceUri?: string;
};

const isErrorObject = (value: any): value is ErrorObject => {
return (
value.type === 'ERROR' &&
Expand Down
Loading