route handlers for account/main

This commit is contained in:
2025-05-19 16:56:30 +03:00
parent edd380d78a
commit c0da94f3dc
22 changed files with 601 additions and 150 deletions

View File

@@ -0,0 +1,7 @@
import React from 'react'
const page = () => {
return <div>page</div>
}
export default page

View File

@@ -0,0 +1,7 @@
import React from 'react'
const page = () => {
return <div>page</div>
}
export default page

View File

@@ -1,7 +1,115 @@
import React from 'react'
'use client'
const page = () => {
return <div>page</div>
import React from 'react'
import { useForm } from '@/app/hooks/useForm'
import Button from '@/components/ui/Button'
import showToast from '@/components/ui/Toast'
import useUserStore from '@/app/store/userStore'
import ContactUs from '@/components/ContactUs'
import TextInput from '@/components/ui/TextInput'
import PhoneInput from '@/components/ui/PhoneInput'
const validationRules = {
firstName: { required: true },
lastName: { required: false },
phone_number: { required: true },
email: { required: true },
}
export default page
const AccountPage = () => {
const { user } = useUserStore()
const { values, handleChange, handleSubmit } = useForm(
{
firstName: user?.name || '',
lastName: user?.surname || '',
phone_number: user?.phone_number || '',
email: user?.email || '',
country: user?.country || '',
city: user?.city || '',
},
validationRules,
async (values) => {
try {
// await updateMainTab(values)
showToast({ type: 'success', message: 'Данные успешно обновлены!' })
} catch {
showToast({ type: 'error', message: 'Ой, что то пошло не так..' })
}
}
)
if (!user) {
return null
}
return (
<div className="space-y-3">
<div className="rounded-2xl shadow overflow-hidden">
<div className="p-6 bg-white sm:p-8">
<div className="space-y-4">
<h1 className="text-2xl">Личные данные</h1>
<form className="space-y-4" onSubmit={handleSubmit}>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<TextInput
name="firstName"
value={values.firstName}
handleChange={handleChange}
label="Имя"
placeholder="Ваше имя"
style="register"
/>
<TextInput
name="lastName"
value={values.lastName}
handleChange={handleChange}
label="Фамилия"
placeholder="Ваша фамилия"
style="register"
/>
<TextInput
name="email"
value={values.email}
handleChange={handleChange}
label="Email"
placeholder="Ваш email"
style="register"
/>
<PhoneInput
value={values.phone_number}
handleChange={handleChange}
operatorsInfo={false}
/>
<TextInput
name="country"
value={values.country}
handleChange={handleChange}
label="Страна"
placeholder="Ваша страна проживания"
style="register"
/>
<TextInput
name="city"
value={values.city}
handleChange={handleChange}
label="Город"
placeholder="Ваш город проживания"
style="register"
/>
</div>
<Button
text="Сохранить изменения"
className="text-sm font-semibold py-4 px-6 bg-orange text-white flex items-center rounded-2xl whitespace-nowrap"
type="submit"
/>
</form>
</div>
</div>
</div>
<ContactUs />
</div>
)
}
export default AccountPage

View File

@@ -0,0 +1,7 @@
import React from 'react'
const page = () => {
return <div>page</div>
}
export default page

View File

@@ -0,0 +1,7 @@
import React from 'react'
const page = () => {
return <div>page</div>
}
export default page

View File

@@ -2,10 +2,10 @@ import React from 'react'
import { useForm } from '@/app/hooks/useForm'
import Button from '@/components/ui/Button'
// import LoginButton from '@/app/components/ui/LoginButton'
import { HiOutlineEye, HiOutlineEyeOff } from 'react-icons/hi'
import showToast from '@/components/ui/Toast'
import { useRouter } from 'next/navigation'
import { signIn } from 'next-auth/react'
import TextInput from '@/components/ui/TextInput'
// import PasswordRecovery from '@/app/components/ui/PasswordRecovery'
const validationRules = {
@@ -52,50 +52,32 @@ const ClientView = () => {
return (
<>
<form className="flex flex-col gap-1" onSubmit={handleSubmit}>
<div className="mb-2">
<label className="block mb-2 text-gray-700" htmlFor="email">
Ваш email:
</label>
<input
type="email"
id="email"
placeholder="my_email@gmail.com"
value={values.email}
onChange={handleChange}
className="w-full px-3 py-2 border text-black rounded-xl focus:outline-none focus:ring-2 focus:ring-mainblocks"
autoComplete="true"
/>
</div>
<TextInput
value={values.email}
name="email"
handleChange={handleChange}
placeholder="my_email@gmail.com"
style="register"
label="Ваш еmail"
/>
<div className="mb-4">
<label className="block mb-2 text-gray-700" htmlFor="email">
Ваш пароль:
</label>
<div className="relative">
<input
type={isVisible ? 'text' : 'password'}
id="password"
placeholder="Пароль"
value={values.password}
onChange={handleChange}
className="w-full px-3 py-2 border text-black rounded-xl focus:outline-none focus:ring-2 focus:ring-mainblocks"
autoComplete="true"
/>
<button
type="button"
onClick={() => togglePasswordVisibility()}
className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700"
>
{isVisible ? <HiOutlineEye /> : <HiOutlineEyeOff />}
</button>
</div>
</div>
<TextInput
value={values.password}
name="password"
handleChange={handleChange}
placeholder="Не менее 8 символов"
style="register"
label="Ваш пароль"
isPassword={true}
isVisible={isVisible}
togglePasswordVisibility={togglePasswordVisibility}
/>
{/* <div className="flex flex-row-reverse text-sm justify-between pb-2">
<PasswordRecovery />
</div> */}
<Button
text="Войти"
className="flex items-center justify-center bg-black rounded-2xl text-white text-base font-semibold py-3"
className="flex items-center justify-center bg-orange rounded-2xl text-white text-base font-semibold py-3 mt-3"
type="submit"
/>
</form>

View File

@@ -0,0 +1,5 @@
import { NextRequest } from 'next/server'
export async function PUT(req: NextRequest) {
// обновляем данные в аккаунте
}

View File

@@ -0,0 +1,17 @@
import { NextRequest } from 'next/server'
export async function GET(req: NextRequest) {
// получить список маршрутов/локаций пользователя
}
export async function POST(req: NextRequest) {
// добавить новый маршрут
}
export async function PUT(req: NextRequest) {
// обновить маршрут
}
export async function DELETE(req: NextRequest) {
// удалить маршрут
}

View File

@@ -75,14 +75,6 @@ const authOptions: NextAuthOptions = {
throw new Error('Все поля обязательны для заполнения')
}
// console.log('Registration data:', {
// email: credentials.email,
// name: credentials.name,
// surname: credentials.surname,
// phone_number: credentials.phone_number,
// privacy_accepted: credentials.privacy_accepted,
// })
const res = await fetch(
`${process.env.BACKEND_URL}/register/clients/`,
{
@@ -125,54 +117,7 @@ const authOptions: NextAuthOptions = {
},
}),
//регистрация менеджера
CredentialsProvider({
id: 'register-credentials-manager',
name: 'RegisterManager',
credentials: {
email: { label: 'Email', type: 'email' },
password: { label: 'Password', type: 'password' },
username: { label: 'Username', type: 'text' },
},
async authorize(credentials) {
try {
const res = await fetch(
`${process.env.BACKEND_URL}/register/business/`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: credentials?.email,
password: credentials?.password,
username: credentials?.username,
}),
}
)
if (!res.ok) {
const text = await res.text()
console.error('Backend error response:', text)
throw new Error('Registration failed: ' + text)
}
const data = await res.json()
return {
id: data.user.id.toString(),
email: data.user.email,
name: data.user.firstName,
accessToken: data.access,
refreshToken: data.refresh,
userType: data.user.userType || 'manager',
}
} catch (error) {
console.error('Registration error:', error)
return null
}
},
}),
//логин обычный
//логин
CredentialsProvider({
name: 'Credentials',
credentials: {
@@ -212,50 +157,6 @@ const authOptions: NextAuthOptions = {
}
},
}),
//логин для менеджеров
CredentialsProvider({
id: 'login-credentials-manager',
name: 'Credentials',
credentials: {
email: { label: 'Email', type: 'email' },
password: { label: 'Password', type: 'password' },
},
async authorize(credentials) {
try {
const res = await fetch(
`${process.env.BACKEND_URL}/auth/login/business/`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: credentials?.email,
password: credentials?.password,
}),
}
)
const data = await res.json()
// console.log('Business login response:', data)
if (!res.ok) {
throw new Error(data.error || 'Authentication failed')
}
return {
id: data.user.id.toString(),
email: data.user.email || `${data.user.phone_number}@example.com`,
name: data.user.username || data.user.title,
accessToken: data.access,
refreshToken: data.refresh,
userType: data.user.userType || 'manager',
}
} catch (error) {
console.error('Login error:', error)
return null
}
},
}),
],
callbacks: {
async jwt({ token, user, account }) {

View File

@@ -135,3 +135,21 @@ export interface AccountSidebarProps {
user: User
navigation: NavigationItem[]
}
export interface TelegramMessage {
source: string
name: string
phone_number: string
message: string
}
export type SourceType = 'account' | 'contact-us'
export interface TextAreaProps {
value: string
handleChange: (e: React.ChangeEvent<HTMLTextAreaElement>) => void
label: string
name: string
placeholder: string
height?: string | number
}

View File

@@ -85,7 +85,7 @@ const AccountSidebar: React.FC<AccountSidebarProps> = ({
href={item.href}
className={`${
isActive
? 'bg-orange/80 text-white'
? 'bg-orange text-white'
: 'text-gray-600 hover:bg-gray-100'
} flex items-center p-4 text-sm font-medium rounded-lg transition-colors`}
>

View File

@@ -0,0 +1,94 @@
'use client'
import React from 'react'
import { useForm } from '@/app/hooks/useForm'
import { getSourceFromPath } from '@/lib/utils/pathMapper'
import { usePathname } from 'next/navigation'
import TextInput from './ui/TextInput'
import TextAreaInput from './ui/TextAreaInput'
import PhoneInput from './ui/PhoneInput'
import showToast from './ui/Toast'
import Button from './ui/Button'
import { sendMessage } from '@/lib/telegram/sendMessage'
import useUserStore from '@/app/store/userStore'
const validationRules = {
source: { required: true },
name: { required: true },
phone_number: { required: true },
message: { required: true },
}
const ContactUs = () => {
const pathname = usePathname()
const source = getSourceFromPath(pathname)
const { user } = useUserStore()
const { values, handleChange, handleSubmit, resetField } = useForm(
{
source: source,
name: user?.name || '',
phone_number: user?.phone_number || '',
message: '',
},
validationRules,
async (values) => {
try {
await sendMessage(values)
showToast({
type: 'success',
message: 'Ваше сообщение отправлено!',
})
resetField('message')
} catch {
showToast({ type: 'error', message: 'Ой, что то пошло не так..' })
}
}
)
return (
<div className="rounded-2xl shadow overflow-hidden">
<div className="p-6 bg-white sm:p-8">
<div className="space-y-4">
<h2 className="text-2xl">Хотели бы связаться с нами?</h2>
<form className="space-y-4" onSubmit={handleSubmit}>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 h-full">
<div className="space-y-4 h-full flex flex-col">
<TextInput
label="Ваше имя"
value={values.name}
handleChange={handleChange}
placeholder="Имя"
name="name"
style="register"
/>
<PhoneInput
value={values.phone_number}
handleChange={handleChange}
operatorsInfo={false}
/>
</div>
<TextAreaInput
value={values.message}
handleChange={handleChange}
height={145}
label="Чем бы Вы хотели с нами поделиться?"
name="message"
placeholder="Что угодно - от предложений до жалоб, мы всегда рады!"
/>
</div>
<Button
text="Отправить"
className="text-sm font-semibold py-4 px-6 bg-black text-white flex items-center justify-center w-full rounded-2xl whitespace-nowrap"
type="submit"
/>
</form>
</div>
</div>
</div>
)
}
export default ContactUs

View File

@@ -0,0 +1,33 @@
import React from 'react'
import { TextAreaProps } from '@/app/types'
const TextAreaInput = ({
value,
handleChange,
label,
name,
placeholder,
height,
}: TextAreaProps) => {
return (
<div>
<label
className="block mb-2 font-medium text-sm text-gray-500"
htmlFor={name}
>
{label}
</label>
<textarea
id={name}
placeholder={placeholder}
value={value}
onChange={handleChange}
style={{ minHeight: height ? `${height}px` : '160px' }}
className="w-full px-3 py-2 border border-gray-300 text-black rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-400 focus:bg-white"
autoComplete={name}
/>
</div>
)
}
export default TextAreaInput

View File

@@ -0,0 +1,41 @@
import { TelegramMessage } from '@/app/types'
export const sendMessage = async (data: TelegramMessage) => {
const API_URL = process.env.NEXT_PUBLIC_API_URL
const headers: Record<string, string> = {
'Content-Type': 'application/json',
Accept: 'application/json',
}
try {
const response = await fetch(`${API_URL}/send-message/`, {
method: 'POST',
headers,
body: JSON.stringify({
source: data.source,
name: data.name,
phone_number: data.phone_number,
message: data.message,
}),
})
if (!response.ok) {
let errorMessage = `Failed to send form data: ${response.status} ${response.statusText}`
try {
const errorData = await response.text()
if (errorData) {
errorMessage += ` - ${errorData}`
}
} catch (e) {
console.error('Error parsing error response:', e)
}
throw new Error(errorMessage)
}
const text = await response.text()
return text ? JSON.parse(text) : null
} catch (error) {
console.error('Error sending form data:', error)
throw error
}
}

View File

@@ -0,0 +1,15 @@
import { SourceType } from '@/app/types'
const pathToSourceMap: Record<string, SourceType> = {
techSupport: 'contact-us', // берем в кавычки значение с дефисом
account: 'account',
}
export const getSourceFromPath = (pathname: string): SourceType => {
const cleanPath = pathname.replace(/^\//, '')
const source = pathToSourceMap[cleanPath] || 'contact-us' // дефолтное значение
// console.log('Final source:', source)
return source
}