All files / app/(dynamic)/last-will/editor/succession page.tsx

90.38% Statements 47/52
56.25% Branches 9/16
96.42% Functions 27/28
88.63% Lines 39/44

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                                            21x 14x   14x 14x     20x 20x 20x 20x 20x   14x     14x 14x     14x   24x   24x                   14x 2x   2x 2x                       14x                                 14x 8x     14x           1x     31x                               58x         116x   2x 2x                     1x                   2x                                                   6x               12x 12x       3x                                 21x                             21x   9x         1x                                            
'use client'
import { FieldArray, Form, Formik, FormikProps } from 'formik'
import { useRouter } from 'next/navigation'
import { useEffect, useState } from 'react'
import { ObjectSchema, array, number, object, string } from 'yup'
import { Route } from '../../../../../components/ButtonsAndLinks/Route/Route'
import { FormStepsButtons } from '../../../../../components/Form/FormStepsButtons/FormStepsButtons'
import { TextInput } from '../../../../../components/Form/TextInput/TextInput'
import { Headline } from '../../../../../components/Headline/Headline'
import { Icon } from '../../../../../components/Icon/Icon'
import { Modal } from '../../../../../components/Modal/ModalBase/Modal'
import { SuccessionHeir } from '../../../../../components/SuccessionHeir/SuccessionHeir'
import { getPercentageLeftPerHeir } from '../../../../../services/heirs'
import { routes } from '../../../../../services/routes/routes'
import { useAppDispatch, useAppSelector } from '../../../../../store/hooks'
import { sendLastWillState, setProgressKeys, setSuccession } from '../../../../../store/lastwill/lastwill'
import { HeirSuccesion, HeirsTypes, SuccessionFormPayload } from '../../../../../types/lastWill'
import { SidebarPages } from '../../../../../types/sidebar'
 
/**
 * Succession Page
 */
const Succession = () => {
	const router = useRouter()
 
	const [isModalOpen, setIsModalOpen] = useState(false)
	const [selectedHeirIndex, setSelectedHeirIndex] = useState<number>()
 
	// Global State
	const _id = useAppSelector((state) => state.lastWill.data._id)
	const isAuthenticated = useAppSelector((state) => state.auth.isAuthenticated)
	const heirs = useAppSelector((state) => state.lastWill.data.heirs)
	const items = useAppSelector((state) => state.lastWill.data.items)
	const isLoading = useAppSelector((state) => state.lastWill.isLoading)
 
	const dispatch = useAppDispatch()
 
	// Prepare links
	const PREVIOUS_LINK = routes.lastWill.inheritance(_id)
	const NEXT_LINK = isAuthenticated ? routes.lastWill.final(_id) : routes.lastWill.plans(_id) // TODO checken, ob für Testament schon bezahlt wurde
 
	// Formik
	const initialFormValues: SuccessionFormPayload = {
		heirs: heirs.map((heir) => {
			const percentageLeftPerHeir = getPercentageLeftPerHeir(heirs)
 
			return {
				id: heir.id,
				type: heir.type,
				name: heir.name ?? '',
				percentage: heir.percentage ?? percentageLeftPerHeir,
				itemIds: heir.itemIds ?? [],
			}
		}),
	}
 
	const onSubmit = async (values: SuccessionFormPayload, href: string) => {
		try {
			// Update store
			dispatch(setSuccession(values))
			const response = await dispatch(sendLastWillState())
			if (response.meta.requestStatus === 'rejected') {
				return
				// TODO: Add error handling here
			}
 
			router.push(href)
		} catch (error) {
			console.error('An error occured while submitting the form: ', error)
		}
	}
 
	const validationSchema: ObjectSchema<SuccessionFormPayload> = object().shape({
		heirs: array()
			.of(
				object<HeirSuccesion>()
					.shape({
						id: string().required(),
						type: string<HeirsTypes>().required(),
						name: string().required(),
						percentage: number().min(0).max(100).required(),
						itemIds: array().of(string().required()).required(),
					})
					.required()
			)
			.required(),
	})
 
	// Use to handle sidebar display state and progress
	useEffect(() => {
		dispatch(setProgressKeys(SidebarPages.SUCCESSION))
	}, [dispatch])
 
	return (
		<div className="container my-5 flex flex-1 flex-col">
			<Headline className="hidden lg:block">Erbfolge</Headline>
			<Formik
				initialValues={initialFormValues}
				validationSchema={validationSchema}
				onSubmit={(values) => onSubmit(values, NEXT_LINK)}
			>
				{({ values, dirty }: FormikProps<SuccessionFormPayload>) => (
					<Form>
						{/* heirs */}
						{values.heirs.length === 0 ? (
							<div datacy="succession-empty-state">
								<Headline level={3}>Erstellen Sie zuerst Erben</Headline>
 
								<p className="mb-2 text-gray-600 md:mb-4">
									Später können Sie Ihren Erben die gewünschte Erbschaft zuordnen.
								</p>
								<Route kind="secondary" href={routes.lastWill.heirs(_id)}>
									Erben anlegen
								</Route>
							</div>
						) : (
							<div className="mt-5 grid grid-cols-1 gap-6 md:mt-6 md:grid-cols-2 2xl:grid-cols-3">
								{values.heirs.map((heir, index) => (
									<SuccessionHeir
										datacy={`heir-${heir.id}`}
										key={`heir-${heir.id}`}
										name={heir.name}
										inputFieldName={`heirs.${index}.percentage`}
										items={items.filter((item) => heir.itemIds?.includes(item.id))}
										onClick={() => {
											setSelectedHeirIndex(values.heirs.findIndex((inner) => inner.id === heir.id))
											setIsModalOpen(true)
										}}
									/>
								))}
							</div>
						)}
 
						{/* Form Steps Buttons */}
						<FormStepsButtons
							loading={isLoading}
							dirty={dirty}
							previousOnClick={() => onSubmit(values, PREVIOUS_LINK)}
							previousHref={PREVIOUS_LINK}
							nextHref={NEXT_LINK}
						/>
 
						{/* Active Heir Modal to select Items */}
						{selectedHeirIndex !== undefined && (
							<Modal
								open={isModalOpen}
								headline={values.heirs[selectedHeirIndex].name}
								onClose={() => setIsModalOpen(false)}
							>
								<div className="mt-4 w-44 md:w-96">
									{/* Percentage */}
									<div className="mb-6 flex items-center justify-between">
										<Headline level={5} hasMargin={false}>
											Anteil
										</Headline>
										<div className="flex items-center">
											<TextInput
												datacy={`textinput-modal-${selectedHeirIndex}`}
												className="pr-6 text-right"
												type="number"
												min={0}
												max={100}
												width="w-24"
												hasBottomMargin={false}
												name={`heirs.${selectedHeirIndex}.percentage`}
											/>
											<p className="z-10 -ml-6">%</p>
										</div>
									</div>
 
									<FieldArray
										name={`heirs.${selectedHeirIndex}.itemIds`}
										render={(arrayHelpers) => (
											<>
												{/* Assigned Items List */}
												<Headline className="mb-2" level={5} hasMargin={false}>
													Gegenstände
												</Headline>
												<div className="mb-6">
													{items
														.filter((item) =>
															values.heirs
																.find((heir) => heir.id === values.heirs[selectedHeirIndex].id)
																?.itemIds?.includes(item.id)
														)
														.map((item, index) => (
															<div
																datacy={`assigned-item-${item.id}`}
																key={item.id}
																className="group -ml-2 flex cursor-pointer justify-between rounded-md p-0.5 px-2 hover:bg-gray-100"
																onClick={() => {
																	arrayHelpers.remove(index)
																}}
															>
																<p className="truncate text-gray-500">{item.name}</p>
																<Icon className="invisible text-gray-500 group-hover:visible" icon="expand_more" />
															</div>
														))}
												</div>
 
												<hr className="my-2" />
 
												{/* Unassigned Items List */}
												{items.filter((item) => !values.heirs.find((heir) => heir.itemIds?.includes(item.id)))
													.length !== 0 ? (
													<>
														<Headline className="" level={5} hasMargin={false}>
															Noch nicht zugeordnete Gegenstände:
														</Headline>
														<p className="mb-2">(durch Anklicken der Person zuweisen)</p>{' '}
													</>
												) : (
													<Headline className="font-normal" level={5} hasMargin={false}>
														Alle Gegenstände zugeordnet
													</Headline>
												)}
												<div>
													{items
														.filter((item) => !values.heirs.find((heir) => heir.itemIds?.includes(item.id)))
														.map((item) => (
															<div
																datacy={`unassigned-item-${item.id}`}
																key={item.id}
																className="group -ml-2 flex cursor-pointer justify-between rounded-md p-0.5 px-2 hover:bg-gray-100"
																onClick={() => {
																	arrayHelpers.push(item.id)
																}}
															>
																<p className="truncate text-gray-500">{item.name}</p>
																<Icon className="invisible text-gray-500 group-hover:visible" icon="expand_less" />
															</div>
														))}
												</div>
											</>
										)}
									/>
								</div>
							</Modal>
						)}
					</Form>
				)}
			</Formik>
		</div>
	)
}
 
export default Succession