All files / app/(dynamic)/(pages)/profile/settings page.tsx

97.5% Statements 39/40
94.44% Branches 17/18
100% Functions 8/8
97.43% Lines 38/39

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256                                                                                                    18x       18x           18x       18x       18x                             18x   22x 22x   22x 22x   22x 22x     24x 22x   22x 3x 3x 3x 3x 1x   2x     22x 3x 3x 3x 3x 1x   2x     22x 1x 1x 1x 1x     1x     22x                             109x                                                                         287x                                                                                     25x                                                                
'use client'
import { Form, Formik, FormikProps } from 'formik'
import { useState } from 'react'
import { ObjectSchema, object, ref, string } from 'yup'
import {
	alertContentChangeEmail,
	alertContentChangePassword,
	alertContentDeleteAccount,
} from '../../../../../../content/profileSettings'
import {
	EMAIL_REQUIRED_ERROR,
	PASSWORD_ACTUAL_INSERT_ERROR,
	PASSWORD_CONFIRM_REQUIRED_ERROR,
	PASSWORD_MATCH_ERROR,
	PASSWORD_MIN_LENGTH_ERROR,
	PASSWORD_NOT_OLD_ERROR,
	PASSWORD_REQUIRED_ERROR,
} from '../../../../../../content/validation'
import { validateMail } from '../../../../../../utils/validateMail'
import { Alert } from '../../../../../components/Alert/Alert'
import { Button } from '../../../../../components/ButtonsAndLinks/Button/Button'
import { Checkbox } from '../../../../../components/Form/Checkbox/Checkbox'
import { PasswordInput } from '../../../../../components/Form/PasswordInput/PasswordInput'
import { TextInput } from '../../../../../components/Form/TextInput/TextInput'
import { Headline } from '../../../../../components/Headline/Headline'
import {
	ChangeEmailResponse,
	ChangePasswordResponse,
	DeleteAccountResponse,
	changeEmail,
	changePassword,
	deleteAccount,
} from '../../../../../services/api/profile/settings'
import { logout, refreshToken } from '../../../../../store/auth/auth'
import { useAppDispatch, useAppSelector } from '../../../../../store/hooks'
 
type EmailChange = {
	newEmail: string
}
 
type PasswordChange = {
	oldPassword: string
	newPassword: string
	newPasswordConfirm: string
}
 
type AccountDelete = {
	delete: [boolean?]
}
 
const initialEmailChangeValues: EmailChange = {
	newEmail: '',
}
 
const initialPasswordChangeValues: PasswordChange = {
	oldPassword: '',
	newPassword: '',
	newPasswordConfirm: '',
}
 
const initialAccountDeleteValues: AccountDelete = {
	delete: [],
}
 
const validationSchemaEmailChange: ObjectSchema<EmailChange> = object().shape({
	newEmail: string().matches(validateMail.regex, validateMail.message).required(EMAIL_REQUIRED_ERROR),
})
 
const validationSchemaPasswordChange: ObjectSchema<PasswordChange> = object().shape({
	oldPassword: string().required(PASSWORD_ACTUAL_INSERT_ERROR),
	newPassword: string()
		.notOneOf([ref('oldPassword')], PASSWORD_NOT_OLD_ERROR)
		.min(8, PASSWORD_MIN_LENGTH_ERROR)
		.required(PASSWORD_REQUIRED_ERROR),
	newPasswordConfirm: string()
		.notOneOf([ref('oldPassword')], PASSWORD_NOT_OLD_ERROR)
		.oneOf([ref('newPassword')], PASSWORD_MATCH_ERROR)
		.required(PASSWORD_CONFIRM_REQUIRED_ERROR),
})
 
/**
 * Account Settings Page
 */
const AccountSettings = () => {
	// Local State
	const [isLoadingChangeMail, setIsLoadingChangeMail] = useState(false)
	const [changeMailStatus, setChangeMailStatus] = useState<ChangeEmailResponse | null>(null)
 
	const [isLoadingChangePassword, setIsLoadingChangePassword] = useState(false)
	const [changePasswordStatus, setChangePasswordStatus] = useState<ChangePasswordResponse | null>(null)
 
	const [isLoadingDeleteAccount, setIsLoadingDeleteAccount] = useState(false)
	const [deleteAccountStatus, setDeleteAccountStatus] = useState<DeleteAccountResponse | null>(null)
 
	// Global State
	const email = useAppSelector((state) => state.auth.sessionData?.decodedAccessToken.email)
	const dispatch = useAppDispatch()
 
	const onSubmitEmailChange = async (values: EmailChange) => {
		setIsLoadingChangeMail(true)
		const response = await changeEmail(values.newEmail)
		setChangeMailStatus(response)
		if (response === 'OK') {
			await dispatch(refreshToken({ ignoreExpireCheck: true }))
		}
		setIsLoadingChangeMail(false)
	}
 
	const onSubmitPasswordChange = async (values: PasswordChange) => {
		setIsLoadingChangePassword(true)
		const response = await changePassword(values.oldPassword, values.newPassword)
		setChangePasswordStatus(response)
		if (response === 'OK') {
			await dispatch(refreshToken({ ignoreExpireCheck: true }))
		}
		setIsLoadingChangePassword(false)
	}
 
	const onSubmitAccountDelete = async () => {
		setIsLoadingDeleteAccount(true)
		const response = await deleteAccount()
		setDeleteAccountStatus(response)
		Iif (response === 'OK') {
			dispatch(logout())
		}
		setIsLoadingDeleteAccount(false)
	}
 
	return (
		<div>
			{/* Change Mail */}
			<div className="rounded-xl border-2 border-gray-200 p-6">
				<Headline level={4}>E-Mail Adresse ändern</Headline>
				<p className="mb-4">
					Ihre aktuelle E-Mail ist <span className="select-all text-red">{email}</span>
				</p>
 
				<Formik
					initialValues={initialEmailChangeValues}
					validationSchema={validationSchemaEmailChange}
					onSubmit={onSubmitEmailChange}
				>
					{({ dirty, isValid }: FormikProps<EmailChange>) => (
						<Form className="mb-2 md:mb-4">
							<div className="lg:w-2/3">
								<TextInput
									name="newEmail"
									labelText="Neue E-Mail Adresse"
									placeholder="Gebe eine neue E-Mail Adresse ein"
									autoComplete="email"
								/>
							</div>
							<div className="flex justify-end">
								<Button
									datacy="change-email-button"
									type="submit"
									kind="secondary"
									icon="mail"
									loading={isLoadingChangeMail}
									disabled={!(dirty && isValid)}
								>
									E-Mail ändern
								</Button>
							</div>
						</Form>
					)}
				</Formik>
				{changeMailStatus && <Alert {...alertContentChangeEmail[changeMailStatus]} />}
			</div>
 
			{/* Change password */}
			<div className="mt-6 rounded-xl border-2 border-gray-200 p-6">
				<Headline level={4}>Passwort ändern</Headline>
 
				<Formik
					initialValues={initialPasswordChangeValues}
					validationSchema={validationSchemaPasswordChange}
					onSubmit={onSubmitPasswordChange}
				>
					{({ dirty, isValid }: FormikProps<PasswordChange>) => (
						<Form className="mb-2 md:mb-4">
							<div className="lg:w-2/3">
								<PasswordInput
									name="oldPassword"
									labelText="Aktuelles Passwort"
									placeholder="Gebe das alte Passwort ein"
								/>
								<PasswordInput name="newPassword" labelText="Neues Passwort" placeholder="Gebe das neue Passwort ein" />
								<PasswordInput
									name="newPasswordConfirm"
									labelText="Neues Passwort bestätigen"
									placeholder="Bestätige das neue Passwort"
								/>
							</div>
							<div className="flex justify-end">
								<Button
									datacy="change-password-button"
									type="submit"
									icon="lock_reset"
									loading={isLoadingChangePassword}
									kind="secondary"
									disabled={!(dirty && isValid)}
								>
									Passwort ändern
								</Button>
							</div>
						</Form>
					)}
				</Formik>
				{changePasswordStatus && <Alert {...alertContentChangePassword[changePasswordStatus]} />}
			</div>
 
			{/* Delete Account */}
			<div className="mt-6 rounded-xl border-2 border-gray-200 p-6">
				<Headline level={4}>Account löschen</Headline>
 
				<p className="mb-4">
					Sind Sie sich sicher Ihren Account zu löschen? Wenn Sie Ihren Account löschen, werden alle Ihre Daten
					unwiderruflich gelöscht.
				</p>
 
				<Formik initialValues={initialAccountDeleteValues} onSubmit={onSubmitAccountDelete}>
					{({ dirty, isValid }: FormikProps<AccountDelete>) => (
						<Form className="mb-2 md:mb-4">
							<Checkbox
								name="delete"
								options={[
									{
										value: true,
										label: 'Ja, ich möchte meinen Account löschen',
									},
								]}
							/>
							<div className="flex justify-end">
								<Button
									datacy="delete-account-button"
									type="submit"
									icon="delete"
									loading={isLoadingDeleteAccount}
									kind="secondary"
									disabled={!(dirty && isValid)}
								>
									Account löschen
								</Button>
							</div>
						</Form>
					)}
				</Formik>
				{deleteAccountStatus && <Alert {...alertContentDeleteAccount[deleteAccountStatus]} />}
			</div>
		</div>
	)
}
 
export default AccountSettings