All files / store/lastwill lastwill.ts

91.81% Statements 101/110
82.08% Branches 55/67
92.1% Functions 35/38
93.13% Lines 95/102

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 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333                                    127x                                                         127x         16x   16x   16x 12x       12x     127x         30x 1x   29x   27x         27x 27x     127x 73x   73x                         127x 119x             127x 21x             127x 188x                                   127x 44x                                     44x     127x 55x                         127x       43x                           43x     127x         49x 41x         108x 52x 26x       108x 108x     49x 49x     140x 140x     140x         21x 21x 21x 119x       119x 119x     140x     140x   140x 140x     69x 69x     14x 14x 14x 14x     55x 55x     24x 24x 24x 24x     16x 16x     54x 62x 58x 58x       2x 2x 2x   2x       127x 30x 30x   127x 27x 27x   27x   127x 1x 1x 1x     127x 16x 16x     127x 12x     127x               127x                         127x  
import { PayloadAction, createAsyncThunk, createSlice, nanoid } from '@reduxjs/toolkit'
import { getLastWillById } from '../../services/api/lastwill/getLastWillById'
import { updateLastWillById } from '../../services/api/lastwill/updateLastWillById'
import {
	InheritanceFormPayload,
	LastWillState,
	MarriageFormPayload,
	Organisation,
	OrganisationFormPayload,
	Person,
	PersonFormPayload,
	SuccessionFormPayload,
	Testator,
	TestatorFormPayload,
} from '../../types/lastWill'
import { SidebarPages } from '../../types/sidebar'
import { RootState } from '../store'
 
export const initialState: LastWillState = {
	isLoading: false,
	isInitialized: false,
	error: null,
 
	data: {
		_id: '',
		common: {},
		testator: {
			name: '',
			gender: undefined,
			birthDate: '',
			birthPlace: '',
			isHandicapped: false,
			isInsolvent: false,
			address: {
				city: '',
				houseNumber: '',
				zipCode: '',
				street: '',
			},
		},
		heirs: [],
		progressKeys: [],
		financialAssets: [],
		items: [],
	},
}
 
export const sendLastWillState = createAsyncThunk<
	LastWillState['data'],
	undefined,
	{ state: RootState; rejectValue: 'ERROR' }
>('lastWill/sendLastWillState', async (params, { getState, rejectWithValue }) => {
	const state = getState()
 
	const lastWillData = state.lastWill.data
 
	const response = await updateLastWillById(lastWillData._id, lastWillData)
	Iif (response === 'ERROR') {
		return rejectWithValue(response)
	}
 
	return response
})
 
export const fetchLastWillState = createAsyncThunk<
	LastWillState['data'],
	{ lastWillId?: string },
	{ rejectValue: 'NOT_FOUND' | 'ERROR' }
>('lastWill/fetchLastWillState', async ({ lastWillId }, { rejectWithValue }) => {
	if (!lastWillId) {
		return rejectWithValue('NOT_FOUND')
	}
	const apiLastWillResponse = await getLastWillById(lastWillId)
 
	Iif (apiLastWillResponse === 'NOT_FOUND' || apiLastWillResponse === 'ERROR') {
		return rejectWithValue(apiLastWillResponse)
	}
 
	// eslint-disable-next-line @typescript-eslint/no-unused-vars
	const { createdAt, updatedAt, accountId, ...lastWill } = apiLastWillResponse
	return lastWill
})
 
export const createTestator = (testatorPayload: TestatorFormPayload): Testator => {
	const { moreInfos, city, street, houseNumber, zipCode, ...formTestator } = testatorPayload
 
	return {
		...formTestator,
		address: {
			city,
			street,
			houseNumber,
			zipCode,
		},
		isHandicapped: moreInfos ? moreInfos.includes('isHandicapped') : false,
		isInsolvent: moreInfos ? moreInfos.includes('isInsolvent') : false,
	}
}
 
export const createMarriage = (marriagePayload: MarriageFormPayload): Person => {
	return createPerson({
		...(marriagePayload as PersonFormPayload),
		id: nanoid(),
		type: 'partner',
	})
}
 
export const patchMarriage = (marriage: Person, marriagePayload: Partial<MarriageFormPayload>): Person => {
	return patchPerson(marriage, {
		...marriagePayload,
		type: 'partner',
		id: marriage.id,
	})
}
 
export const createPerson = (personPayload: PersonFormPayload): Person => {
	return {
		id: personPayload.id,
		type: personPayload.type,
		name: personPayload.name,
		gender: personPayload.gender,
		birthDate: personPayload.birthDate,
		birthPlace: personPayload.birthPlace,
		isHandicapped: personPayload.moreInfos ? personPayload.moreInfos.includes('isHandicapped') : false,
		isInsolvent: personPayload.moreInfos ? personPayload.moreInfos.includes('isInsolvent') : false,
		address: {
			street: personPayload.street,
			houseNumber: personPayload.houseNumber,
			zipCode: personPayload.zipCode,
			city: personPayload.city,
		},
	}
}
 
export const patchPerson = (person: Person, personPayload: Partial<PersonFormPayload>): Person => {
	const newPerson: Person = {
		...person,
		id: person.id,
		type: personPayload.type || person.type,
		name: personPayload.name || person.name,
		gender: personPayload.gender || person.gender,
		birthDate: personPayload.birthDate || person.birthDate,
		birthPlace: personPayload.birthPlace || person.birthPlace,
		isHandicapped: personPayload.moreInfos ? personPayload.moreInfos.includes('isHandicapped') : person.isHandicapped,
		isInsolvent: personPayload.moreInfos ? personPayload.moreInfos.includes('isInsolvent') : person.isInsolvent,
		address: {
			...person.address,
			street: personPayload.street || person.address?.street,
			houseNumber: personPayload.houseNumber || person.address?.houseNumber,
			zipCode: personPayload.zipCode || person.address?.zipCode,
			city: personPayload.city || person.address?.city,
		},
	}
 
	return newPerson
}
 
export const createOrganisation = (organisationPayload: OrganisationFormPayload): Organisation => {
	return {
		id: organisationPayload.id,
		type: 'organisation',
		name: organisationPayload.name,
		address: {
			city: organisationPayload.city,
			houseNumber: organisationPayload.houseNumber,
			zipCode: organisationPayload.zipCode,
			street: organisationPayload.street,
		},
	}
}
 
export const patchOrganisation = (
	organisation: Organisation,
	organisationPayload: Partial<OrganisationFormPayload>
): Organisation => {
	const newOrganisation: Organisation = {
		...organisation,
		id: organisation.id,
		type: 'organisation',
		name: organisationPayload.name || organisation.name,
		address: {
			...organisation.address,
			street: organisationPayload.street || organisation.address?.street,
			houseNumber: organisationPayload.houseNumber || organisation.address?.houseNumber,
			zipCode: organisationPayload.zipCode || organisation.address?.zipCode,
			city: organisationPayload.city || organisation.address?.city,
		},
	}
 
	return newOrganisation
}
 
const lastWillSlice = createSlice({
	name: 'lastWill',
	initialState,
	reducers: {
		setProgressKeys: (state, action: PayloadAction<SidebarPages>) => {
			if (!state.data.progressKeys.includes(action.payload)) {
				state.data.progressKeys.push(action.payload)
			}
		},
		setInheritance: (state, action: PayloadAction<InheritanceFormPayload>) => {
			// Remove itemIds from heir if the item was removed
			state.data.heirs.forEach((heir) => {
				heir.itemIds = heir.itemIds
					? heir.itemIds.filter((itemId) => action.payload.items.find((item) => item.id === itemId))
					: []
			})
 
			state.data.financialAssets = action.payload.financialAssets
			state.data.items = action.payload.items
		},
		setTestator: (state, action: PayloadAction<TestatorFormPayload>) => {
			const testator = createTestator(action.payload)
			state.data.testator = testator
		},
		setMarriage: (state, action: PayloadAction<MarriageFormPayload>) => {
			const oldPartner = state.data.heirs.find((heir): heir is Person => heir.type === 'partner')
			const hasPartner = oldPartner !== undefined
 
			// Set state
			if (
				hasPartner &&
				action.payload.relationshipStatus !== undefined &&
				action.payload.relationshipStatus === 'married'
			) {
				const partner = patchMarriage(oldPartner, action.payload)
				const oldPartnerIndex = state.data.heirs.findIndex((heir): heir is Person => heir.type === 'partner')
				state.data.heirs[oldPartnerIndex] = partner
			} else Iif (hasPartner) {
				const oldPartnerIndex = state.data.heirs.findIndex((heir): heir is Person => heir.type === 'partner')
				state.data.heirs.splice(oldPartnerIndex, 1)
			} else {
				const partner = createMarriage(action.payload)
				state.data.heirs.push(partner)
			}
 
			state.data.common.isBerlinWill = action.payload.moreInfos
				? action.payload.moreInfos.includes('isBerlinWill')
				: false
			state.data.common.isPartnerGermanCitizenship =
				action.payload.isPartnerGermanCitizenship?.includes('isPartnerGermanCitizenship') ?? false
			state.data.common.matrimonialProperty = action.payload.matrimonialProperty
			state.data.testator.relationshipStatus = action.payload.relationshipStatus
		},
		addPersonHeir: (state, action: PayloadAction<PersonFormPayload>) => {
			const person = createPerson(action.payload)
			state.data.heirs.push(person)
		},
		updatePersonHeir: (state, action: PayloadAction<PersonFormPayload>) => {
			const heirIndex = state.data.heirs.findIndex((heir) => heir.id === action.payload.id)
			const oldPerson = state.data.heirs[heirIndex] as Person
			const patchedPerson = patchPerson(oldPerson, action.payload)
			state.data.heirs[heirIndex] = patchedPerson
		},
		addOrganisationHeir: (state, action: PayloadAction<OrganisationFormPayload>) => {
			const organisation = createOrganisation(action.payload)
			state.data.heirs.push(organisation)
		},
		updateOrganisationHeir: (state, action: PayloadAction<OrganisationFormPayload>) => {
			const heirIndex = state.data.heirs.findIndex((heir) => heir.id === action.payload.id)
			const oldOrganisation = state.data.heirs[heirIndex] as Organisation
			const patchedOrganisation = patchOrganisation(oldOrganisation, action.payload)
			state.data.heirs[heirIndex] = patchedOrganisation
		},
		removeHeir: (state, action: PayloadAction<string>) => {
			const heirIndex = state.data.heirs.findIndex((heir) => heir.id === action.payload)
			state.data.heirs.splice(heirIndex, 1)
		},
		setSuccession: (state, action: PayloadAction<SuccessionFormPayload>) => {
			action.payload.heirs.forEach((heir) => {
				const stateHeir = state.data.heirs.find((stateHeir) => stateHeir.id === heir.id)!
				stateHeir.percentage = heir.percentage
				stateHeir.itemIds = heir.itemIds
			})
		},
		resetLastWill: (state) => {
			state.isLoading = false
			state.isInitialized = false
			state.error = null
 
			state.data = initialState.data
		},
	},
	extraReducers(builder) {
		builder.addCase(fetchLastWillState.pending, (state) => {
			state.isLoading = true
			state.error = null
		})
		builder.addCase(fetchLastWillState.fulfilled, (state, action) => {
			state.isLoading = false
			state.isInitialized = true
 
			state.data = action.payload
		})
		builder.addCase(fetchLastWillState.rejected, (state, action) => {
			state.isLoading = false
			state.error = action.payload ?? null
			console.log(action.payload)
		})
 
		builder.addCase(sendLastWillState.pending, (state) => {
			state.isLoading = true
			state.error = null
		})
 
		builder.addCase(sendLastWillState.fulfilled, (state) => {
			state.isLoading = false
		})
 
		builder.addCase(sendLastWillState.rejected, (state, action) => {
			state.isLoading = false
			state.error = action.payload ?? null
			console.log(action.payload)
		})
	},
})
 
export const lastWillReducer = lastWillSlice.reducer
export const {
	setProgressKeys,
	resetLastWill,
	setInheritance,
	setTestator,
	setMarriage,
	addPersonHeir,
	updatePersonHeir,
	addOrganisationHeir,
	updateOrganisationHeir,
	setSuccession,
	removeHeir,
} = lastWillSlice.actions