File size: 2,478 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import { CALYPSO_CONTACT } from '@automattic/urls';
import { useMutation } from '@tanstack/react-query';
import { useTranslate } from 'i18n-calypso';
import wp from 'calypso/lib/wp';
import { useDispatch } from 'calypso/state';
import { errorNotice, successNotice } from 'calypso/state/notices/actions';
import type { AlterDestinationParams } from './types';
import type { UseMutationOptions } from '@tanstack/react-query';

const MUTATION_KEY = 'reverifyEmailForward';

/**
 * Manually trigger a new verification email to an email forward receiver
 * @param domainName The domain name of the mailbox
 * @param mutationOptions Mutation options passed on to `useMutation`
 * @returns Returns the result of the `useMutation` call
 */
export default function useResendVerifyEmailForwardMutation(
	domainName: string,
	mutationOptions: Omit<
		UseMutationOptions< any, unknown, AlterDestinationParams >,
		'mutationFn'
	> = {}
) {
	const dispatch = useDispatch();
	const translate = useTranslate();

	const suppliedOnError = mutationOptions.onError;
	const suppliedOnSuccess = mutationOptions.onSuccess;

	mutationOptions.mutationKey = [ MUTATION_KEY ];

	mutationOptions.onSuccess = ( data, emailForward, context ) => {
		suppliedOnSuccess?.( data, emailForward, context );

		const { destination } = emailForward;

		const successMessage = translate(
			'Successfully sent confirmation email for %(email)s to %(destination)s.',
			{
				args: {
					email: emailForward.mailbox + '@' + domainName,
					destination,
				},
			}
		);

		dispatch(
			successNotice( successMessage, {
				duration: 7000,
			} )
		);
	};

	mutationOptions.onError = ( error, variables, context ) => {
		suppliedOnError?.( error, variables, context );

		const failureMessage = translate(
			'Failed to resend verification email for email forwarding record %(email)s. ' +
				'Please try again or {{contactSupportLink}}contact support{{/contactSupportLink}}.',
			{
				args: {
					email: variables.mailbox + '@' + domainName,
				},
				components: {
					contactSupportLink: <a href={ CALYPSO_CONTACT } />,
				},
			}
		);

		dispatch( errorNotice( failureMessage ) );
	};

	return useMutation< any, unknown, AlterDestinationParams >( {
		mutationFn: ( { mailbox, destination } ) =>
			wp.req.post(
				`/domains/${ encodeURIComponent( domainName ) }/email/${ encodeURIComponent(
					mailbox
				) }/${ encodeURIComponent( destination ) }/resend-verification`
			),
		...mutationOptions,
	} );
}