create sender fix

This commit is contained in:
2025-05-22 13:52:02 +03:00
parent 4182708db7
commit b0aef18c38
6 changed files with 115 additions and 57 deletions

View File

@@ -47,12 +47,13 @@ const validationRules = {
minLength: 11,
pattern: /^\+?[0-9]{11,}$/,
},
comment: { required: false, minLength: 10 },
comment: { required: false },
email_notification: { required: false },
}
const SenderPage = () => {
const { user, setUser } = useUserStore()
const today = formatDateToHTML(new Date())
const initialValues: SenderPageProps = {
@@ -73,38 +74,75 @@ const SenderPage = () => {
const cargoOptions: SelectOption[] = cargo_types.map((type, index) => ({
id: index + 1,
label: cargo_type_translations[type],
value: type,
label: cargo_type_translations[type],
}))
const transportOptions: SelectOption[] = transport_types.map((type, index) => ({
id: index + 1,
label: transport_translations[type],
value: type,
label: transport_translations[type],
}))
const { values, handleChange, handleSubmit } = useForm<SenderPageProps>(
const { values, handleChange, handleSubmit, resetField } = useForm<SenderPageProps>(
initialValues,
validationRules,
async values => {
try {
// находим выбранные опции
const selectedTransport = transportOptions.find(
opt => opt.id.toString() === values.transport
)
const selectedCargoType = cargoOptions.find(opt => opt.id.toString() === values.cargo_type)
if (!selectedTransport || !selectedCargoType) {
throw new Error('Некорректный тип транспорта или груза')
}
// подготавливаем данные для отправки
const requestData = {
...values,
owner_type: 'sender',
transport: selectedTransport.value,
cargo_type: selectedCargoType.value,
phone_number: values.phone_number,
}
const response = await fetch('/api/account/sender', {
method: 'PATCH',
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(values),
body: JSON.stringify(requestData),
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.error || 'Ошибка при обновлении данных')
console.error('Ошибка от сервера:', error)
throw new Error(error.error || 'Ошибка при создании маршрута')
}
const result = await response.json()
setUser(result.user)
showToast({ type: 'success', message: 'Данные успешно обновлены!' })
// Обновляем номер телефона в сторе, если он изменился
if (user && user.phone_number !== values.phone_number) {
setUser({
...user,
phone_number: values.phone_number,
})
}
showToast({
type: 'success',
message: 'Маршрут успешно создан!',
})
// сбрасываем все поля формы кроме телефона
Object.keys(initialValues).forEach(field => {
if (field !== 'phone_number') {
resetField(field)
}
})
} catch (error) {
console.error('Ошибка:', error)
showToast({
type: 'error',
message: error instanceof Error ? error.message : 'Ой, что то пошло не так..',

View File

@@ -34,18 +34,18 @@ export async function POST(req: NextRequest) {
Authorization: `Bearer ${session.accessToken}`,
},
body: JSON.stringify({
owner_type: 'sender',
transport,
country_from,
city_from,
country_to,
city_to,
cargo_type,
departure,
arrival,
phone_number,
comment,
email_notification,
owner_type: data.owner_type,
transport: data.transport,
country_from: data.country_from,
city_from: data.city_from,
country_to: data.country_to,
city_to: data.city_to,
cargo_type: data.cargo_type,
departure: data.departure,
arrival: data.arrival,
phone_number: data.phone_number,
comment: data.comment || '',
email_notification: data.email_notification,
}),
})

View File

@@ -68,6 +68,14 @@ export function useForm<T extends Record<string, FormValue>>(
phone_number: 'Номер телефона',
password: 'Пароль',
privacy_policy: 'Политика конфиденциальности',
arrival: 'Дата прибытия',
departure: 'Дата отправления',
cargo_type: 'Тип груза',
city_from: 'Город отправления',
country_to: 'Страна назначения',
city_to: 'Город назначения',
country_from_id: 'Страна отправления',
country_to_id: 'Страна отправления',
}
const validate = () => {

View File

@@ -171,6 +171,7 @@ export interface Route {
export interface SelectOption {
id: number
label: string
value: string | CargoType | TransportType
}
export interface MultiSelectProps {