From a3f536d65ebc261a775bf2a394e5b0e5c5ec152a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mat=C3=BA=C5=A1=20Hlav=C3=A1=C4=8Dik?= Date: Sat, 11 Nov 2023 13:39:03 +0100 Subject: [PATCH] Profil - Uprava udajov (#160) * Add edit profile buttons * Move School subform into own component * `yarn add usehooks-ts` * Add ProfileForm and improve SchoolSubForm * Fix typescript errror and cyclic imports * remove async/await where wasn't neccesary --- package.json | 3 +- .../PageLayout/LoginForm/LoginForm.tsx | 4 +- src/components/Profile/ProfileDetail.tsx | 29 ++++- src/components/Profile/ProfileForm.tsx | 121 ++++++++++++++++++ src/components/RegisterForm/RegisterForm.tsx | 108 ++-------------- .../SchoolSubForm/SchoolSubForm.tsx | 118 +++++++++++++++++ src/pages/strom/profil/uprava.tsx | 12 ++ yarn.lock | 11 ++ 8 files changed, 299 insertions(+), 107 deletions(-) create mode 100644 src/components/Profile/ProfileForm.tsx create mode 100644 src/components/SchoolSubForm/SchoolSubForm.tsx create mode 100644 src/pages/strom/profil/uprava.tsx diff --git a/package.json b/package.json index 51b787d0..4cde8223 100644 --- a/package.json +++ b/package.json @@ -43,7 +43,8 @@ "remark-gfm": "^3.0.1", "remark-math": "^5.1.1", "typescript": "^5.0.4", - "unstated-next": "^1.1.0" + "unstated-next": "^1.1.0", + "usehooks-ts": "^2.9.1" }, "devDependencies": { "@svgr/webpack": "^8.0.1", diff --git a/src/components/PageLayout/LoginForm/LoginForm.tsx b/src/components/PageLayout/LoginForm/LoginForm.tsx index 2bed7b6c..12e67c3e 100644 --- a/src/components/PageLayout/LoginForm/LoginForm.tsx +++ b/src/components/PageLayout/LoginForm/LoginForm.tsx @@ -24,8 +24,8 @@ export const LoginForm: FC = ({closeOverlay}) => { const {login} = AuthContainer.useContainer() const {handleSubmit, control} = useForm({defaultValues}) - const onSubmit: SubmitHandler = async (data) => { - await login({data, onSuccess: closeOverlay}) + const onSubmit: SubmitHandler = (data) => { + login({data, onSuccess: closeOverlay}) } const requiredRule = {required: '* Toto pole nemôže byť prázdne.'} diff --git a/src/components/Profile/ProfileDetail.tsx b/src/components/Profile/ProfileDetail.tsx index 31cf4547..f2985763 100644 --- a/src/components/Profile/ProfileDetail.tsx +++ b/src/components/Profile/ProfileDetail.tsx @@ -5,7 +5,9 @@ import {FC} from 'react' import {Profile} from '@/types/api/personal' import {AuthContainer} from '@/utils/AuthContainer' +import {useSeminarInfo} from '@/utils/useSeminarInfo' +import {Button, Link} from '../Clickable/Clickable' import styles from './ProfileDetail.module.scss' type ProfileLineInput = { @@ -25,6 +27,7 @@ const ProfileLine: FC = ({label, value}) => { export const ProfileDetail: FC = () => { const {isAuthed} = AuthContainer.useContainer() + const {seminar} = useSeminarInfo() const {data} = useQuery({ queryKey: ['personal', 'profiles', 'myprofile'], @@ -34,13 +37,25 @@ export const ProfileDetail: FC = () => { const profile = data?.data return ( - - - - - - - + + + + + + + + + + + upraviť údaje + + ) } diff --git a/src/components/Profile/ProfileForm.tsx b/src/components/Profile/ProfileForm.tsx new file mode 100644 index 00000000..73e78afb --- /dev/null +++ b/src/components/Profile/ProfileForm.tsx @@ -0,0 +1,121 @@ +import {useMutation, useQuery} from '@tanstack/react-query' +import axios from 'axios' +import {useRouter} from 'next/router' +import {FC} from 'react' +import {SubmitHandler, useForm} from 'react-hook-form' + +import styles from '@/components/FormItems/Form.module.scss' +import {FormInput} from '@/components/FormItems/FormInput/FormInput' +import {SelectOption} from '@/components/FormItems/FormSelect/FormSelect' +import {IGeneralPostResponse} from '@/types/api/general' +import {Profile} from '@/types/api/personal' +import {AuthContainer} from '@/utils/AuthContainer' +import {useSeminarInfo} from '@/utils/useSeminarInfo' + +import {Button} from '../Clickable/Clickable' +import {SchoolSubForm, SchoolSubFormValues} from '../SchoolSubForm/SchoolSubForm' + +interface ProfileFormValues extends SchoolSubFormValues { + first_name?: string + last_name?: string + phone?: string + parent_phone?: string +} + +const defaultValues: ProfileFormValues = { + first_name: '', + last_name: '', + phone: '', + parent_phone: '', + new_school_description: '', + without_school: false, + school: null, + school_not_found: false, + grade: '', +} + +export const ProfileForm: FC = () => { + const {isAuthed} = AuthContainer.useContainer() + + const {data} = useQuery({ + queryKey: ['personal', 'profiles', 'myprofile'], + queryFn: () => axios.get(`/api/personal/profiles/myprofile`), + enabled: isAuthed, + }) + const profile = data?.data + const profileValues: ProfileFormValues = { + first_name: profile?.first_name, + last_name: profile?.last_name, + phone: profile?.phone ?? '', + parent_phone: profile?.parent_phone ?? '', + new_school_description: '', + without_school: profile?.school_id === 1, + school: ({id: profile?.school.code, label: profile?.school.verbose_name} as SelectOption) ?? null, + school_not_found: profile?.school_id === 0, + grade: profile?.grade ?? '', + } + + const {handleSubmit, control, watch, setValue} = useForm({ + defaultValues, + values: profileValues, + }) + + watch(['first_name']) + + const scrollToTop = () => { + window.scrollTo({ + top: 0, + behavior: 'smooth', + }) + } + + const router = useRouter() + + const {seminar} = useSeminarInfo() + + const transformFormData = (data: ProfileFormValues) => ({ + profile: { + first_name: data.first_name, + last_name: data.last_name, + school: data.school?.id, + phone: data.phone, + parent_phone: data.parent_phone, + grade: data.grade, + }, + new_school_description: data.new_school_description || '', + }) + + const {mutate: submitFormData} = useMutation({ + mutationFn: (data: ProfileFormValues) => { + return axios.put(`/api/user/user`, transformFormData(data)) + }, + onSuccess: () => router.push(`/${seminar}/profil`), + }) + + const onSubmit: SubmitHandler = (data) => { + submitFormData(data) + } + + const requiredRule = {required: '* Toto pole nemôže byť prázdne.'} + const phoneRule = { + validate: (val?: string) => { + if (val && !/^(\+\d{10,12})$/u.test(val.replaceAll(/\s+/gu, ''))) + return '* Zadaj telefónne číslo vo formáte validnom formáte +421 123 456 789 alebo +421123456789.' + }, + } + return ( +
+
+ + + + + +

* takto označéné polia sú povinné

+ + +
+ ) +} diff --git a/src/components/RegisterForm/RegisterForm.tsx b/src/components/RegisterForm/RegisterForm.tsx index 4ca310d4..90bdc2fc 100644 --- a/src/components/RegisterForm/RegisterForm.tsx +++ b/src/components/RegisterForm/RegisterForm.tsx @@ -1,22 +1,19 @@ -import {useMutation, useQuery} from '@tanstack/react-query' +import {useMutation} from '@tanstack/react-query' import axios from 'axios' import {useRouter} from 'next/router' -import {FC, useEffect, useRef} from 'react' +import {FC} from 'react' import {SubmitHandler, useForm} from 'react-hook-form' import styles from '@/components/FormItems/Form.module.scss' -import {FormAutocomplete} from '@/components/FormItems/FormAutocomplete/FormAutocomplete' import {FormCheckbox} from '@/components/FormItems/FormCheckbox/FormCheckbox' import {FormInput} from '@/components/FormItems/FormInput/FormInput' -import {FormSelect, SelectOption} from '@/components/FormItems/FormSelect/FormSelect' -import {IGrade} from '@/types/api/competition' import {IGeneralPostResponse} from '@/types/api/general' -import {ISchool} from '@/types/api/personal' import {useSeminarInfo} from '@/utils/useSeminarInfo' import {Button} from '../Clickable/Clickable' +import {SchoolSubForm, SchoolSubFormValues} from '../SchoolSubForm/SchoolSubForm' -type RegisterFormValues = { +interface RegisterFormValues extends SchoolSubFormValues { email?: string password1?: string password2?: string @@ -24,12 +21,7 @@ type RegisterFormValues = { last_name?: string phone?: string parent_phone?: string - new_school_description?: string - without_school: boolean - school?: SelectOption | null - school_not_found: boolean - grade: number | '' - gdpr: boolean + gdpr?: boolean } const defaultValues: RegisterFormValues = { @@ -49,8 +41,10 @@ const defaultValues: RegisterFormValues = { } export const RegisterForm: FC = () => { - const {handleSubmit, control, watch, setValue, getValues} = useForm({defaultValues}) - const [school_not_found, without_school] = watch(['school_not_found', 'without_school']) + const {handleSubmit, control, watch, setValue, getValues} = useForm({ + defaultValues, + values: defaultValues, + }) const scrollToTop = () => { window.scrollTo({ @@ -59,58 +53,8 @@ export const RegisterForm: FC = () => { }) } - const otherSchoolItem = useRef() - const withoutSchoolItem = useRef() - const router = useRouter() - // načítanie ročníkov z BE, ktorými vyplníme FormSelect s ročníkmi - const {data: gradesData} = useQuery({ - queryKey: ['competition', 'grade'], - queryFn: () => axios.get(`/api/competition/grade`), - }) - const grades = gradesData?.data ?? [] - const gradeItems: SelectOption[] = grades.map(({id, name}) => ({id, label: name})) - - // načítanie škôl z BE, ktorými vyplníme FormAutocomplete so školami - const {data: schoolsData} = useQuery({ - queryKey: ['personal', 'schools'], - queryFn: () => axios.get(`/api/personal/schools`), - }) - const schools = schoolsData?.data ?? [] - const allSchoolItems: SelectOption[] = schools.map(({code, city, name, street}) => ({ - id: code, - label: city ? `${name} ${street}, ${city}` : name, - })) - const emptySchoolItems = allSchoolItems.filter(({id}) => [0, 1].includes(id)) - otherSchoolItem.current = emptySchoolItems.find(({id}) => id === 0) - withoutSchoolItem.current = emptySchoolItems.find(({id}) => id === 1) - const schoolItems = allSchoolItems.filter(({id}) => ![0, 1].includes(id)) - - // predvyplnenie/zmazania hodnôt pri zakliknutí checkboxu pre užívateľa po škole - useEffect(() => { - if (without_school) { - setValue('school', withoutSchoolItem.current) - setValue('grade', 13) - setValue('school_not_found', false) - } else { - setValue('school', null) - setValue('grade', '') - } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [without_school]) - - // predvyplnenie/zmazania hodnôt pri zakliknutí checkboxu pre neznámu školu - useEffect(() => { - if (school_not_found) { - setValue('school', otherSchoolItem.current) - } else if (!without_school) { - setValue('school', null) - setValue('grade', '') - } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [school_not_found]) - const {seminar} = useSeminarInfo() const transformFormData = (data: RegisterFormValues) => ({ @@ -136,7 +80,7 @@ export const RegisterForm: FC = () => { onSuccess: () => router.push(`${router.asPath}/../verifikacia`), }) - const onSubmit: SubmitHandler = async (data) => { + const onSubmit: SubmitHandler = (data) => { submitFormData(data) } @@ -189,37 +133,7 @@ export const RegisterForm: FC = () => { /> - - - - {school_not_found && ( - - )} - id !== 13 || without_school)} - disabled={!gradeItems.length || without_school} - rules={requiredRule} - /> + = { + control: Control + watch: UseFormWatch + setValue: UseFormSetValue +} + +export const SchoolSubForm = ({control, watch, setValue}: SchoolSubFormProps) => { + const [school_not_found, without_school] = watch(['school_not_found', 'without_school']) + + const otherSchoolItem = useRef() + const withoutSchoolItem = useRef() + + // načítanie ročníkov z BE, ktorými vyplníme FormSelect s ročníkmi + const {data: gradesData} = useQuery({ + queryKey: ['competition', 'grade'], + queryFn: () => axios.get(`/api/competition/grade`), + }) + const grades = gradesData?.data ?? [] + const gradeItems: SelectOption[] = grades.map(({id, name}) => ({id, label: name})) + + // načítanie škôl z BE, ktorými vyplníme FormAutocomplete so školami + const {data: schoolsData} = useQuery({ + queryKey: ['personal', 'schools'], + queryFn: () => axios.get(`/api/personal/schools`), + }) + const schools = schoolsData?.data ?? [] + const allSchoolItems: SelectOption[] = schools.map(({code, city, name, street}) => ({ + id: code, + label: city ? `${name} ${street}, ${city}` : name, + })) + const emptySchoolItems = allSchoolItems.filter(({id}) => [0, 1].includes(id)) + otherSchoolItem.current = emptySchoolItems.find(({id}) => id === 0) + withoutSchoolItem.current = emptySchoolItems.find(({id}) => id === 1) + const schoolItems = allSchoolItems.filter(({id}) => ![0, 1].includes(id)) + + // predvyplnenie/zmazania hodnôt pri zakliknutí checkboxu pre užívateľa po škole + useUpdateEffect(() => { + if (without_school) { + setValue('school', withoutSchoolItem.current) + setValue('grade', 13) + setValue('school_not_found', false) + } else { + setValue('school', null) + setValue('grade', '') + } + }, [without_school]) + + // predvyplnenie/zmazania hodnôt pri zakliknutí checkboxu pre neznámu školu + useUpdateEffect(() => { + if (school_not_found) { + setValue('school', otherSchoolItem.current) + } else if (!without_school) { + setValue('school', null) + setValue('grade', '') + } + }, [school_not_found]) + + const requiredRule = {required: '* Toto pole nemôže byť prázdne.'} + return ( +
+ + + + {school_not_found && ( + + )} + id !== 13 || without_school)} + disabled={!gradeItems.length || without_school} + rules={requiredRule} + /> +
+ ) +} diff --git a/src/pages/strom/profil/uprava.tsx b/src/pages/strom/profil/uprava.tsx new file mode 100644 index 00000000..fd1f514e --- /dev/null +++ b/src/pages/strom/profil/uprava.tsx @@ -0,0 +1,12 @@ +import {NextPage} from 'next' + +import {PageLayout} from '@/components/PageLayout/PageLayout' +import {ProfileForm} from '@/components/Profile/ProfileForm' + +const Profil: NextPage = () => ( + + + +) + +export default Profil diff --git a/yarn.lock b/yarn.lock index 1e0ca0a7..5ad9f273 100644 --- a/yarn.lock +++ b/yarn.lock @@ -10703,6 +10703,16 @@ __metadata: languageName: node linkType: hard +"usehooks-ts@npm:^2.9.1": + version: 2.9.1 + resolution: "usehooks-ts@npm:2.9.1" + peerDependencies: + react: ^16.8.0 || ^17.0.0 || ^18.0.0 + react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 + checksum: 36f1e4142ce23bc019b81d2e93aefd7f2c350abcf255598c21627114a69a2f2f116b35dc3a353375f09c6e4c9b704a04f104e3d10e98280545c097feca66c30a + languageName: node + linkType: hard + "util-deprecate@npm:^1.0.1": version: 1.0.2 resolution: "util-deprecate@npm:1.0.2" @@ -10853,6 +10863,7 @@ __metadata: typed-scss-modules: ^7.1.0 typescript: ^5.0.4 unstated-next: ^1.1.0 + usehooks-ts: ^2.9.1 languageName: unknown linkType: soft