🚀 MVP: FastAPI + React форма с SMS верификацией

 Инфраструктура: PostgreSQL, Redis, RabbitMQ, S3
 Backend: SMS сервис + API endpoints
 Frontend: React форма (3 шага) + SMS верификация
This commit is contained in:
AI Assistant
2025-10-24 16:19:58 +03:00
parent 8af23e90fa
commit 0f82eef08d
42 changed files with 2902 additions and 241 deletions

View File

@@ -0,0 +1,199 @@
import { useState } from 'react';
import { Form, Input, Button, message, Space } from 'antd';
import { PhoneOutlined, SafetyOutlined, FileProtectOutlined } from '@ant-design/icons';
interface Props {
formData: any;
updateFormData: (data: any) => void;
onNext: () => void;
isPhoneVerified: boolean;
setIsPhoneVerified: (verified: boolean) => void;
}
export default function Step1Phone({ formData, updateFormData, onNext, isPhoneVerified, setIsPhoneVerified }: Props) {
const [form] = Form.useForm();
const [codeSent, setCodeSent] = useState(false);
const [loading, setLoading] = useState(false);
const [verifyLoading, setVerifyLoading] = useState(false);
const sendCode = async () => {
try {
const phone = form.getFieldValue('phone');
if (!phone) {
message.error('Введите номер телефона');
return;
}
setLoading(true);
const response = await fetch('http://147.45.146.17:8100/api/v1/sms/send', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ phone }),
});
const result = await response.json();
if (response.ok) {
message.success('Код отправлен на ваш телефон');
setCodeSent(true);
if (result.debug_code) {
message.info(`DEBUG: Код ${result.debug_code}`);
}
} else {
message.error(result.detail || 'Ошибка отправки кода');
}
} catch (error) {
message.error('Ошибка соединения с сервером');
} finally {
setLoading(false);
}
};
const verifyCode = async () => {
try {
const phone = form.getFieldValue('phone');
const code = form.getFieldValue('smsCode');
if (!code) {
message.error('Введите код из SMS');
return;
}
setVerifyLoading(true);
const response = await fetch('http://147.45.146.17:8100/api/v1/sms/verify', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ phone, code }),
});
const result = await response.json();
if (response.ok) {
message.success('Телефон подтвержден!');
setIsPhoneVerified(true);
} else {
message.error(result.detail || 'Неверный код');
}
} catch (error) {
message.error('Ошибка соединения с сервером');
} finally {
setVerifyLoading(false);
}
};
const handleNext = async () => {
try {
const values = await form.validateFields();
updateFormData(values);
onNext();
} catch (error) {
message.error('Заполните все обязательные поля');
}
};
return (
<Form
form={form}
layout="vertical"
initialValues={formData}
style={{ marginTop: 24 }}
>
<Form.Item
label="Номер телефона"
name="phone"
rules={[
{ required: true, message: 'Введите номер телефона' },
{ pattern: /^\+7\d{10}$/, message: 'Формат: +79001234567' }
]}
>
<Input
prefix={<PhoneOutlined />}
placeholder="+79001234567"
disabled={isPhoneVerified}
maxLength={12}
/>
</Form.Item>
{!isPhoneVerified && (
<>
<Form.Item>
<Button
type="primary"
onClick={sendCode}
loading={loading}
disabled={codeSent}
>
{codeSent ? 'Код отправлен' : 'Отправить код'}
</Button>
</Form.Item>
{codeSent && (
<Form.Item
label="Код из SMS"
name="smsCode"
rules={[{ required: true, message: 'Введите код' }, { len: 6, message: '6 цифр' }]}
>
<Space.Compact style={{ width: '100%' }}>
<Input
prefix={<SafetyOutlined />}
placeholder="123456"
maxLength={6}
style={{ width: '70%' }}
/>
<Button
type="primary"
onClick={verifyCode}
loading={verifyLoading}
style={{ width: '30%' }}
>
Проверить
</Button>
</Space.Compact>
</Form.Item>
)}
</>
)}
{isPhoneVerified && (
<>
<Form.Item
label="Email (необязательно)"
name="email"
rules={[{ type: 'email', message: 'Неверный формат email' }]}
>
<Input placeholder="example@mail.ru" />
</Form.Item>
<Form.Item
label="ИНН (необязательно)"
name="inn"
>
<Input placeholder="1234567890" maxLength={12} />
</Form.Item>
<Form.Item
label="Номер полиса"
name="policyNumber"
rules={[{ required: true, message: 'Введите номер полиса' }]}
>
<Input prefix={<FileProtectOutlined />} placeholder="123456789" />
</Form.Item>
<Form.Item
label="Серия полиса (необязательно)"
name="policySeries"
>
<Input placeholder="AB" />
</Form.Item>
<Form.Item>
<Button type="primary" onClick={handleNext} size="large" block>
Далее
</Button>
</Form.Item>
</>
)}
</Form>
);
}

View File

@@ -0,0 +1,122 @@
import { Form, Input, DatePicker, Select, Button, Upload, message } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import type { UploadFile } from 'antd/es/upload/interface';
import { useState } from 'react';
const { TextArea } = Input;
const { Option } = Select;
interface Props {
formData: any;
updateFormData: (data: any) => void;
onNext: () => void;
onPrev: () => void;
}
export default function Step2Details({ formData, updateFormData, onNext, onPrev }: Props) {
const [form] = Form.useForm();
const [fileList, setFileList] = useState<UploadFile[]>([]);
const handleNext = async () => {
try {
const values = await form.validateFields();
updateFormData({
...values,
incidentDate: values.incidentDate?.format('YYYY-MM-DD'),
uploadedFiles: fileList.map(f => f.uid),
});
onNext();
} catch (error) {
message.error('Заполните все обязательные поля');
}
};
const uploadProps = {
fileList,
beforeUpload: (file: File) => {
const isImage = file.type.startsWith('image/');
const isPDF = file.type === 'application/pdf';
if (!isImage && !isPDF) {
message.error('Можно загружать только изображения и PDF');
return false;
}
const isLt10M = file.size / 1024 / 1024 < 10;
if (!isLt10M) {
message.error('Файл должен быть меньше 10MB');
return false;
}
setFileList([...fileList, {
uid: Math.random().toString(),
name: file.name,
status: 'done',
url: URL.createObjectURL(file),
} as UploadFile]);
return false; // Отключаем автозагрузку
},
onRemove: (file: UploadFile) => {
setFileList(fileList.filter(f => f.uid !== file.uid));
},
};
return (
<Form
form={form}
layout="vertical"
initialValues={formData}
style={{ marginTop: 24 }}
>
<Form.Item
label="Дата происшествия"
name="incidentDate"
>
<DatePicker style={{ width: '100%' }} format="DD.MM.YYYY" />
</Form.Item>
<Form.Item
label="Тип транспорта"
name="transportType"
>
<Select placeholder="Выберите тип транспорта">
<Option value="air">Авиа</Option>
<Option value="train">Поезд</Option>
<Option value="bus">Автобус</Option>
<Option value="ship">Водный транспорт</Option>
<Option value="other">Другое</Option>
</Select>
</Form.Item>
<Form.Item
label="Описание происшествия"
name="incidentDescription"
>
<TextArea
rows={4}
placeholder="Опишите что произошло..."
maxLength={1000}
showCount
/>
</Form.Item>
<Form.Item label="Документы (билеты, справки, чеки)">
<Upload {...uploadProps} listType="picture">
<Button icon={<UploadOutlined />}>Загрузить файлы</Button>
</Upload>
<div style={{ marginTop: 8, color: '#999', fontSize: 12 }}>
Максимум 10 MB на файл. Форматы: JPG, PNG, PDF, HEIC
</div>
</Form.Item>
<Form.Item>
<div style={{ display: 'flex', gap: 8 }}>
<Button onClick={onPrev}>Назад</Button>
<Button type="primary" onClick={handleNext} style={{ flex: 1 }}>
Далее
</Button>
</div>
</Form.Item>
</Form>
);
}

View File

@@ -0,0 +1,131 @@
import { Form, Input, Radio, Button, Select, message } from 'antd';
import { BankOutlined, CreditCardOutlined, QrcodeOutlined } from '@ant-design/icons';
import { useState } from 'react';
const { Option } = Select;
interface Props {
formData: any;
updateFormData: (data: any) => void;
onPrev: () => void;
onSubmit: () => void;
}
export default function Step3Payment({ formData, updateFormData, onPrev, onSubmit }: Props) {
const [form] = Form.useForm();
const [paymentMethod, setPaymentMethod] = useState(formData.paymentMethod || 'sbp');
const [submitting, setSubmitting] = useState(false);
const handleSubmit = async () => {
try {
const values = await form.validateFields();
updateFormData(values);
setSubmitting(true);
await onSubmit();
} catch (error) {
message.error('Заполните все обязательные поля');
} finally {
setSubmitting(false);
}
};
return (
<Form
form={form}
layout="vertical"
initialValues={formData}
style={{ marginTop: 24 }}
>
<Form.Item
label="Способ выплаты"
name="paymentMethod"
rules={[{ required: true, message: 'Выберите способ выплаты' }]}
>
<Radio.Group onChange={(e) => setPaymentMethod(e.target.value)}>
<Radio.Button value="sbp">
<QrcodeOutlined /> СБП (Быстрые платежи)
</Radio.Button>
<Radio.Button value="card">
<CreditCardOutlined /> Карта
</Radio.Button>
<Radio.Button value="bank_transfer">
<BankOutlined /> Банковский счет
</Radio.Button>
</Radio.Group>
</Form.Item>
{paymentMethod === 'sbp' && (
<Form.Item
label="Банк для СБП"
name="bankName"
rules={[{ required: true, message: 'Выберите банк' }]}
>
<Select placeholder="Выберите ваш банк">
<Option value="sberbank">Сбербанк</Option>
<Option value="tinkoff">Тинькофф</Option>
<Option value="vtb">ВТБ</Option>
<Option value="alfabank">Альфа-Банк</Option>
<Option value="raiffeisen">Райффайзенбанк</Option>
<Option value="other">Другой</Option>
</Select>
</Form.Item>
)}
{paymentMethod === 'card' && (
<Form.Item
label="Номер карты"
name="cardNumber"
rules={[
{ required: true, message: 'Введите номер карты' },
{ pattern: /^\d{16}$/, message: '16 цифр без пробелов' }
]}
>
<Input
prefix={<CreditCardOutlined />}
placeholder="1234567890123456"
maxLength={16}
/>
</Form.Item>
)}
{paymentMethod === 'bank_transfer' && (
<>
<Form.Item
label="Название банка"
name="bankName"
rules={[{ required: true, message: 'Введите название банка' }]}
>
<Input prefix={<BankOutlined />} placeholder="Сбербанк" />
</Form.Item>
<Form.Item
label="Номер счета"
name="accountNumber"
rules={[
{ required: true, message: 'Введите номер счета' },
{ pattern: /^\d{20}$/, message: '20 цифр' }
]}
>
<Input placeholder="12345678901234567890" maxLength={20} />
</Form.Item>
</>
)}
<Form.Item>
<div style={{ display: 'flex', gap: 8, marginTop: 32 }}>
<Button onClick={onPrev}>Назад</Button>
<Button
type="primary"
onClick={handleSubmit}
loading={submitting}
style={{ flex: 1 }}
size="large"
>
Отправить заявку
</Button>
</div>
</Form.Item>
</Form>
);
}