feat: Интеграция DePay для криптовалютных платежей (USDT/Polygon)
- Добавлены endpoints для DePay: callback, success, rate, history - Заменена система проверки чеков на CryptoPayment - Переименована модель Check в CryptoPayment в Prisma схеме - Обновлен billing.tsx для работы с DePay виджетом - Все секреты вынесены в .env файлы - Интеграция с CoinGecko API для курса USDT/RUB - Добавлена RSA верификация webhook от DePay
This commit is contained in:
@@ -6,3 +6,6 @@ VITE_TURNSTILE_SITE_KEY=0x4AAAAAAB7306voAK0Pjx8O
|
||||
# API URLs
|
||||
VITE_API_URL=https://api.ospab.host
|
||||
VITE_SOCKET_URL=wss://api.ospab.host
|
||||
|
||||
# DePay Crypto Payment
|
||||
VITE_DEPAY_INTEGRATION_ID=60f35b39-15e6-4900-9c6d-eb4e4213d5b9
|
||||
|
||||
3840
ospabhost/frontend/package-lock.json
generated
3840
ospabhost/frontend/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -10,6 +10,7 @@
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@depay/widgets": "^13.0.40",
|
||||
"@marsidev/react-turnstile": "^1.3.1",
|
||||
"axios": "^1.12.2",
|
||||
"qrcode.react": "^4.2.0",
|
||||
|
||||
@@ -1,51 +1,102 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useState, useEffect, useContext } from 'react';
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
import apiClient from '../../utils/apiClient';
|
||||
import QRCode from 'react-qr-code';
|
||||
import { API_URL } from '../../config/api';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import AuthContext from '../../context/authcontext';
|
||||
|
||||
const sbpUrl = import.meta.env.VITE_SBP_QR_URL;
|
||||
const cardNumber = import.meta.env.VITE_CARD_NUMBER;
|
||||
const DEPAY_INTEGRATION_ID = import.meta.env.VITE_DEPAY_INTEGRATION_ID;
|
||||
|
||||
interface Check {
|
||||
// Declare DePayWidgets on window
|
||||
declare global {
|
||||
interface Window {
|
||||
DePayWidgets?: {
|
||||
Payment: (config: any) => void;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
interface CryptoPayment {
|
||||
id: number;
|
||||
amount: number;
|
||||
status: 'pending' | 'approved' | 'rejected';
|
||||
fileUrl: string;
|
||||
cryptoAmount: number | null;
|
||||
exchangeRate: number | null;
|
||||
status: 'pending' | 'completed' | 'failed';
|
||||
transactionHash: string | null;
|
||||
blockchain: string;
|
||||
token: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
const Billing = () => {
|
||||
const { locale } = useTranslation();
|
||||
const { userData } = useContext(AuthContext);
|
||||
const isEn = locale === 'en';
|
||||
const [searchParams] = useSearchParams();
|
||||
|
||||
const [amount, setAmount] = useState<number>(0);
|
||||
const [balance, setBalance] = useState<number>(0);
|
||||
const [checks, setChecks] = useState<Check[]>([]);
|
||||
const [checkFile, setCheckFile] = useState<File | null>(null);
|
||||
const [uploadLoading, setUploadLoading] = useState(false);
|
||||
const [payments, setPayments] = useState<CryptoPayment[]>([]);
|
||||
const [exchangeRate, setExchangeRate] = useState<number>(95);
|
||||
const [message, setMessage] = useState('');
|
||||
const [messageType, setMessageType] = useState<'success' | 'error'>('success');
|
||||
const [isPaymentGenerated, setIsPaymentGenerated] = useState(false);
|
||||
|
||||
const quickAmounts = [100, 500, 1000, 3000, 5000];
|
||||
|
||||
useEffect(() => {
|
||||
// Load DePay script
|
||||
loadDePayScript();
|
||||
|
||||
fetchBalance();
|
||||
fetchChecks();
|
||||
}, []);
|
||||
fetchPayments();
|
||||
fetchExchangeRate();
|
||||
|
||||
// Получить защищённый URL для файла чека
|
||||
const getCheckFileUrl = (fileUrl: string): string => {
|
||||
const filename = fileUrl.split('/').pop();
|
||||
return `${API_URL}/api/check/file/${filename}`;
|
||||
// Check for payment success/error from redirect
|
||||
const paymentStatus = searchParams.get('payment');
|
||||
const txHash = searchParams.get('tx');
|
||||
|
||||
if (paymentStatus === 'success') {
|
||||
showMessage(
|
||||
isEn
|
||||
? `✅ Payment successful! Transaction: ${txHash}`
|
||||
: `✅ Оплата успешна! Транзакция: ${txHash}`,
|
||||
'success'
|
||||
);
|
||||
// Refresh data
|
||||
setTimeout(() => {
|
||||
fetchBalance();
|
||||
fetchPayments();
|
||||
}, 2000);
|
||||
} else if (paymentStatus === 'error') {
|
||||
showMessage(
|
||||
isEn
|
||||
? '❌ Payment failed. Please try again.'
|
||||
: '❌ Ошибка оплаты. Попробуйте снова.',
|
||||
'error'
|
||||
);
|
||||
}
|
||||
}, [searchParams, isEn]);
|
||||
|
||||
const loadDePayScript = () => {
|
||||
if (window.DePayWidgets) return;
|
||||
|
||||
const script = document.createElement('script');
|
||||
script.src = 'https://integrate.depay.com/widgets/v12.js';
|
||||
script.async = true;
|
||||
script.onload = () => {
|
||||
console.log('[DePay] Widget script loaded');
|
||||
};
|
||||
script.onerror = () => {
|
||||
console.error('[DePay] Failed to load widget script');
|
||||
showMessage(
|
||||
isEn ? 'Failed to load payment widget' : 'Не удалось загрузить платёжный виджет',
|
||||
'error'
|
||||
);
|
||||
};
|
||||
document.body.appendChild(script);
|
||||
};
|
||||
|
||||
const fetchBalance = async () => {
|
||||
try {
|
||||
console.log('[Billing] Загрузка баланса...');
|
||||
const res = await apiClient.get(`${API_URL}/api/user/balance`);
|
||||
console.log('[Billing] Ответ от сервера:', res.data);
|
||||
const balanceValue = res.data.balance || 0;
|
||||
setBalance(balanceValue);
|
||||
console.log('[Billing] Баланс загружен:', balanceValue);
|
||||
@@ -54,114 +105,162 @@ const Billing = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const fetchChecks = async () => {
|
||||
const fetchPayments = async () => {
|
||||
try {
|
||||
console.log('[Billing] Загрузка истории чеков...');
|
||||
const res = await apiClient.get(`${API_URL}/api/check/my`);
|
||||
const checksData = res.data.data || [];
|
||||
setChecks(checksData);
|
||||
console.log('[Billing] История чеков загружена:', checksData.length, 'чеков');
|
||||
console.log('[Billing] Загрузка истории платежей...');
|
||||
const res = await apiClient.get(`${API_URL}/api/payment/depay/history`);
|
||||
const paymentsData = res.data.payments || [];
|
||||
setPayments(paymentsData);
|
||||
console.log('[Billing] История загружена:', paymentsData.length, 'платежей');
|
||||
} catch (error) {
|
||||
console.error('[Billing] Ошибка загрузки истории чеков:', error);
|
||||
console.error('[Billing] Ошибка загрузки истории:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const fetchExchangeRate = async () => {
|
||||
try {
|
||||
const res = await apiClient.get(`${API_URL}/api/payment/depay/rate`);
|
||||
const rate = res.data.rate || 95;
|
||||
setExchangeRate(rate);
|
||||
console.log('[Billing] Курс USDT/RUB:', rate);
|
||||
} catch (error) {
|
||||
console.error('[Billing] Ошибка получения курса:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const showMessage = (msg: string, type: 'success' | 'error' = 'success') => {
|
||||
setMessage(msg);
|
||||
setMessageType(type);
|
||||
setTimeout(() => setMessage(''), 5000);
|
||||
setTimeout(() => setMessage(''), 8000);
|
||||
};
|
||||
|
||||
const handleCopyCard = () => {
|
||||
if (cardNumber) {
|
||||
navigator.clipboard.writeText(cardNumber);
|
||||
showMessage('Номер карты скопирован!', 'success');
|
||||
}
|
||||
};
|
||||
|
||||
const handleGeneratePayment = () => {
|
||||
if (amount > 0) {
|
||||
setIsPaymentGenerated(true);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCheckUpload = async () => {
|
||||
if (!checkFile || amount <= 0) {
|
||||
console.error('[Billing] Ошибка валидации:', { checkFile: !!checkFile, amount });
|
||||
showMessage('Укажите сумму и выберите файл', 'error');
|
||||
const handleOpenPaymentWidget = () => {
|
||||
if (!window.DePayWidgets) {
|
||||
showMessage(
|
||||
isEn ? 'Payment widget not loaded yet. Please wait...' : 'Виджет оплаты ещё загружается. Подождите...',
|
||||
'error'
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('[Billing] Начало загрузки чека:', {
|
||||
fileName: checkFile.name,
|
||||
fileSize: checkFile.size,
|
||||
amount
|
||||
});
|
||||
if (!userData?.user?.id) {
|
||||
showMessage(
|
||||
isEn ? 'Please log in to make a payment' : 'Войдите для оплаты',
|
||||
'error'
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
setUploadLoading(true);
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append('file', checkFile);
|
||||
formData.append('amount', String(amount));
|
||||
// Open DePay payment widget
|
||||
window.DePayWidgets.Payment({
|
||||
integration: DEPAY_INTEGRATION_ID,
|
||||
|
||||
// User identifier for callback
|
||||
user: {
|
||||
id: String(userData.user.id),
|
||||
},
|
||||
|
||||
console.log('[Billing] Отправка запроса на /api/check/upload...');
|
||||
const response = await apiClient.post(`${API_URL}/api/check/upload`, formData, {
|
||||
headers: {
|
||||
'Content-Type': 'multipart/form-data',
|
||||
// Callback URLs
|
||||
callback: {
|
||||
url: `${API_URL}/api/payment/depay/callback`,
|
||||
},
|
||||
|
||||
// Success redirect
|
||||
success: {
|
||||
url: `${API_URL}/payment/depay/success`,
|
||||
},
|
||||
|
||||
// Styling
|
||||
style: {
|
||||
colors: {
|
||||
primary: '#6366f1', // ospab primary color
|
||||
},
|
||||
},
|
||||
|
||||
// Event handlers
|
||||
sent: (transaction: any) => {
|
||||
console.log('[DePay] Payment sent:', transaction);
|
||||
showMessage(
|
||||
isEn
|
||||
? 'Payment sent! Waiting for confirmation...'
|
||||
: 'Оплата отправлена! Ожидаем подтверждение...',
|
||||
'success'
|
||||
);
|
||||
},
|
||||
|
||||
confirmed: (transaction: any) => {
|
||||
console.log('[DePay] Payment confirmed:', transaction);
|
||||
showMessage(
|
||||
isEn
|
||||
? '✅ Payment confirmed! Your balance will be updated shortly.'
|
||||
: '✅ Оплата подтверждена! Баланс будет обновлён.',
|
||||
'success'
|
||||
);
|
||||
|
||||
// Refresh balance and payments after 3 seconds
|
||||
setTimeout(() => {
|
||||
fetchBalance();
|
||||
fetchPayments();
|
||||
}, 3000);
|
||||
},
|
||||
|
||||
failed: (error: any) => {
|
||||
console.error('[DePay] Payment failed:', error);
|
||||
showMessage(
|
||||
isEn
|
||||
? '❌ Payment failed. Please try again.'
|
||||
: '❌ Ошибка оплаты. Попробуйте снова.',
|
||||
'error'
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
console.log('[Billing] ✅ Чек успешно загружен:', response.data);
|
||||
showMessage('✅ Чек успешно отправлен! Ожидайте проверки оператором (обычно до 24 часов)', 'success');
|
||||
|
||||
setCheckFile(null);
|
||||
setAmount(0);
|
||||
setIsPaymentGenerated(false);
|
||||
|
||||
// Обновляем список чеков
|
||||
await fetchChecks();
|
||||
console.log('[Billing] История чеков обновлена');
|
||||
} catch (error) {
|
||||
const err = error as { response?: { data?: { error?: string; message?: string }; status?: number }; message?: string };
|
||||
console.error('[Billing] Ошибка загрузки чека:', {
|
||||
message: err.message,
|
||||
response: err.response?.data,
|
||||
status: err.response?.status,
|
||||
});
|
||||
|
||||
const errorMessage = err.response?.data?.error ||
|
||||
err.response?.data?.message ||
|
||||
'Ошибка загрузки чека. Попробуйте снова';
|
||||
showMessage(`${errorMessage}`, 'error');
|
||||
console.error('[DePay] Error opening widget:', error);
|
||||
showMessage(
|
||||
isEn
|
||||
? 'Failed to open payment widget'
|
||||
: 'Не удалось открыть виджет оплаты',
|
||||
'error'
|
||||
);
|
||||
}
|
||||
setUploadLoading(false);
|
||||
};
|
||||
|
||||
const getStatusText = (status: string) => {
|
||||
switch (status) {
|
||||
case 'approved':
|
||||
return isEn ? 'Approved' : 'Зачислено';
|
||||
case 'rejected':
|
||||
return isEn ? 'Rejected' : 'Отклонено';
|
||||
case 'completed':
|
||||
return isEn ? 'Completed' : 'Завершён';
|
||||
case 'failed':
|
||||
return isEn ? 'Failed' : 'Не удался';
|
||||
default:
|
||||
return isEn ? 'Pending' : 'На проверке';
|
||||
return isEn ? 'Pending' : 'В обработке';
|
||||
}
|
||||
};
|
||||
|
||||
const getStatusColor = (status: string) => {
|
||||
switch (status) {
|
||||
case 'approved':
|
||||
return 'text-green-600';
|
||||
case 'rejected':
|
||||
return 'text-red-600';
|
||||
case 'completed':
|
||||
return 'text-green-600 dark:text-green-400';
|
||||
case 'failed':
|
||||
return 'text-red-600 dark:text-red-400';
|
||||
default:
|
||||
return 'text-yellow-600';
|
||||
return 'text-yellow-600 dark:text-yellow-400';
|
||||
}
|
||||
};
|
||||
|
||||
const formatDate = (dateString: string) => {
|
||||
return new Date(dateString).toLocaleString(isEn ? 'en-US' : 'ru-RU', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="p-4 lg:p-8 bg-white rounded-2xl lg:rounded-3xl shadow-xl max-w-4xl mx-auto">
|
||||
<h2 className="text-2xl lg:text-3xl font-bold text-gray-800 mb-4 lg:mb-6">
|
||||
<div className="p-4 lg:p-8 bg-white dark:bg-gray-800 rounded-2xl lg:rounded-3xl shadow-xl max-w-4xl mx-auto transition-colors duration-200">
|
||||
<h2 className="text-2xl lg:text-3xl font-bold text-gray-800 dark:text-white mb-4 lg:mb-6">
|
||||
{isEn ? 'Top Up Balance' : 'Пополнение баланса'}
|
||||
</h2>
|
||||
|
||||
@@ -169,217 +268,165 @@ const Billing = () => {
|
||||
{message && (
|
||||
<div className={`mb-4 p-3 border rounded-xl text-sm font-medium ${
|
||||
messageType === 'success'
|
||||
? 'bg-green-50 border-green-200 text-green-700'
|
||||
: 'bg-red-50 border-red-200 text-red-700'
|
||||
? 'bg-green-50 dark:bg-green-900/20 border-green-200 dark:border-green-800 text-green-700 dark:text-green-300'
|
||||
: 'bg-red-50 dark:bg-red-900/20 border-red-200 dark:border-red-800 text-red-700 dark:text-red-300'
|
||||
}`}>
|
||||
{message}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Текущий баланс */}
|
||||
<div className="bg-gray-100 p-4 lg:p-6 rounded-xl lg:rounded-2xl mb-6">
|
||||
<p className="text-sm text-gray-600 mb-1">{isEn ? 'Current Balance' : 'Текущий баланс'}</p>
|
||||
<p className="text-3xl lg:text-4xl font-extrabold text-ospab-primary">{balance.toFixed(2)} ₽</p>
|
||||
<div className="bg-gradient-to-br from-indigo-500 to-purple-600 dark:from-indigo-600 dark:to-purple-700 p-6 lg:p-8 rounded-xl lg:rounded-2xl mb-6 text-white shadow-lg">
|
||||
<p className="text-sm opacity-90 mb-2">{isEn ? 'Current Balance' : 'Текущий баланс'}</p>
|
||||
<p className="text-4xl lg:text-5xl font-extrabold">{balance.toFixed(2)} ₽</p>
|
||||
<p className="text-xs opacity-75 mt-2">
|
||||
≈ ${(balance / exchangeRate).toFixed(2)} USDT
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{!isPaymentGenerated ? (
|
||||
<div>
|
||||
{/* Ввод суммы */}
|
||||
<div className="mb-4">
|
||||
<label htmlFor="amount" className="block text-gray-700 font-semibold mb-2">
|
||||
{isEn ? 'Top-up amount (₽)' : 'Сумма пополнения (₽)'}
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
id="amount"
|
||||
value={amount || ''}
|
||||
onChange={(e) => setAmount(Number(e.target.value))}
|
||||
className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-ospab-primary"
|
||||
min="1"
|
||||
placeholder={isEn ? 'Enter amount' : 'Введите сумму'}
|
||||
/>
|
||||
{/* Курс обмена */}
|
||||
<div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-xl p-4 mb-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm font-semibold text-blue-800 dark:text-blue-300">
|
||||
{isEn ? 'Exchange Rate' : 'Курс обмена'}
|
||||
</p>
|
||||
<p className="text-2xl font-bold text-blue-900 dark:text-blue-200">
|
||||
1 USDT = {exchangeRate.toFixed(2)} ₽
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Быстрые суммы */}
|
||||
<div className="mb-6">
|
||||
<p className="text-sm text-gray-600 mb-2">{isEn ? 'Quick select:' : 'Быстрый выбор:'}</p>
|
||||
<div className="grid grid-cols-3 md:grid-cols-5 gap-2">
|
||||
{quickAmounts.map((quickAmount) => (
|
||||
<button
|
||||
key={quickAmount}
|
||||
onClick={() => setAmount(quickAmount)}
|
||||
className={`px-3 py-2 rounded-lg text-sm font-medium transition ${
|
||||
amount === quickAmount
|
||||
? 'bg-ospab-primary text-white'
|
||||
: 'bg-gray-100 text-gray-700 hover:bg-gray-200'
|
||||
}`}
|
||||
>
|
||||
{quickAmount} ₽
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<p className="text-xs text-blue-600 dark:text-blue-400">
|
||||
{isEn ? 'Updated every minute' : 'Обновляется каждую минуту'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={handleGeneratePayment}
|
||||
disabled={amount <= 0}
|
||||
className="w-full px-5 py-3 rounded-xl text-white font-bold transition-colors bg-ospab-primary hover:bg-ospab-accent disabled:bg-gray-300 disabled:cursor-not-allowed"
|
||||
>
|
||||
{isEn ? 'Proceed to Payment' : 'Перейти к оплате'}
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
{/* Инструкция */}
|
||||
<div className="bg-blue-50 border border-blue-200 rounded-xl p-4 mb-6">
|
||||
<p className="font-bold text-blue-800 mb-2">{isEn ? 'Payment Instructions' : 'Инструкция по оплате'}</p>
|
||||
<ol className="text-sm text-blue-700 space-y-1 list-decimal list-inside">
|
||||
<li>{isEn ? <>Transfer <strong>₽{amount}</strong> via SBP or to card</> : <>Переведите <strong>₽{amount}</strong> по СБП или на карту</>}</li>
|
||||
<li>{isEn ? 'Save the payment receipt' : 'Сохраните чек об оплате'}</li>
|
||||
<li>{isEn ? 'Upload the receipt below for verification' : 'Загрузите чек ниже для проверки'}</li>
|
||||
</ol>
|
||||
</div>
|
||||
|
||||
{/* Кнопка оплаты через DePay */}
|
||||
<div className="mb-8">
|
||||
<button
|
||||
onClick={handleOpenPaymentWidget}
|
||||
className="w-full px-6 py-4 rounded-xl text-white font-bold text-lg transition-all duration-200 bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-700 hover:to-purple-700 shadow-lg hover:shadow-xl transform hover:scale-[1.02] active:scale-[0.98]"
|
||||
>
|
||||
<span className="flex items-center justify-center gap-3">
|
||||
<svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
|
||||
</svg>
|
||||
{isEn ? 'Top Up with Crypto (USDT)' : 'Пополнить криптовалютой (USDT)'}
|
||||
</span>
|
||||
</button>
|
||||
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400 text-center mt-3">
|
||||
{isEn
|
||||
? 'Pay with USDT on Polygon network. Fast and secure.'
|
||||
: 'Оплата USDT в сети Polygon. Быстро и безопасно.'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Преимущества */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-8 pb-8 border-b border-gray-200 dark:border-gray-700">
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="w-10 h-10 rounded-lg bg-green-100 dark:bg-green-900/30 flex items-center justify-center flex-shrink-0">
|
||||
<svg className="w-5 h-5 text-green-600 dark:text-green-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
{/* QR-код и карта */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
|
||||
{/* QR СБП */}
|
||||
<div className="bg-gray-100 p-4 rounded-xl">
|
||||
<h3 className="text-lg font-bold text-gray-800 mb-3">{isEn ? 'Pay via SBP' : 'Оплата по СБП'}</h3>
|
||||
<div className="flex justify-center p-4 bg-white rounded-lg">
|
||||
<QRCode value={sbpUrl || 'https://qr.nspk.ru/FAKE'} size={200} />
|
||||
</div>
|
||||
<p className="mt-3 text-xs text-gray-600 text-center">
|
||||
{isEn ? 'Scan QR code in your bank app' : 'Отсканируйте QR-код в приложении банка'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Номер карты */}
|
||||
<div className="bg-gray-100 p-4 rounded-xl">
|
||||
<h3 className="text-lg font-bold text-gray-800 mb-3">{isEn ? 'Card Number' : 'Номер карты'}</h3>
|
||||
<p className="text-xl font-mono font-bold text-gray-800 break-all mb-3 bg-white p-4 rounded-lg">
|
||||
{cardNumber || '0000 0000 0000 0000'}
|
||||
</p>
|
||||
<button
|
||||
onClick={handleCopyCard}
|
||||
className="w-full px-4 py-2 rounded-lg text-white font-semibold bg-gray-700 hover:bg-gray-800 transition"
|
||||
>
|
||||
{isEn ? 'Copy card number' : 'Скопировать номер карты'}
|
||||
</button>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold text-gray-800 dark:text-white text-sm">{isEn ? 'Instant' : 'Мгновенно'}</p>
|
||||
<p className="text-xs text-gray-600 dark:text-gray-400">
|
||||
{isEn ? 'Balance updates in seconds' : 'Баланс обновляется за секунды'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="w-10 h-10 rounded-lg bg-blue-100 dark:bg-blue-900/30 flex items-center justify-center flex-shrink-0">
|
||||
<svg className="w-5 h-5 text-blue-600 dark:text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
|
||||
</svg>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold text-gray-800 dark:text-white text-sm">{isEn ? 'Secure' : 'Безопасно'}</p>
|
||||
<p className="text-xs text-gray-600 dark:text-gray-400">
|
||||
{isEn ? 'Blockchain verified' : 'Проверено блокчейном'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Загрузка чека */}
|
||||
<div className="bg-gray-50 border-2 border-dashed border-gray-300 rounded-xl p-6 mb-4">
|
||||
<h3 className="text-lg font-bold text-gray-800 mb-3">{isEn ? 'Upload Receipt' : 'Загрузка чека'}</h3>
|
||||
{checkFile ? (
|
||||
<div>
|
||||
<p className="text-gray-700 mb-2">
|
||||
<strong>{isEn ? 'Selected file:' : 'Выбран файл:'}</strong> <span className="break-all" title={checkFile.name}>{checkFile.name}</span>
|
||||
</p>
|
||||
<p className="text-sm text-gray-500 mb-3">
|
||||
{isEn ? 'Size:' : 'Размер:'} {(checkFile.size / 1024 / 1024).toFixed(2)} {isEn ? 'MB' : 'МБ'}
|
||||
</p>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={() => setCheckFile(null)}
|
||||
className="px-4 py-2 bg-gray-300 rounded-lg hover:bg-gray-400 transition"
|
||||
>
|
||||
{isEn ? 'Remove' : 'Удалить'}
|
||||
</button>
|
||||
<button
|
||||
onClick={handleCheckUpload}
|
||||
disabled={uploadLoading}
|
||||
className="flex-1 px-4 py-2 bg-ospab-primary text-white rounded-lg hover:bg-ospab-accent transition disabled:bg-gray-400"
|
||||
>
|
||||
{uploadLoading ? (isEn ? 'Uploading...' : 'Загрузка...') : (isEn ? 'Submit receipt' : 'Отправить чек')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-center">
|
||||
<p className="text-gray-600 mb-2">
|
||||
<label className="text-ospab-primary cursor-pointer hover:underline font-semibold">
|
||||
{isEn ? 'Click to select a file' : 'Нажмите, чтобы выбрать файл'}
|
||||
<input
|
||||
type="file"
|
||||
accept="image/*,application/pdf"
|
||||
onChange={(e) => e.target.files && setCheckFile(e.target.files[0])}
|
||||
className="hidden"
|
||||
/>
|
||||
</label>
|
||||
</p>
|
||||
<p className="text-sm text-gray-500">{isEn ? 'JPG, PNG, PDF (up to 10 MB)' : 'JPG, PNG, PDF (до 10 МБ)'}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={() => {
|
||||
setIsPaymentGenerated(false);
|
||||
setAmount(0);
|
||||
}}
|
||||
className="w-full px-4 py-2 bg-gray-200 text-gray-700 rounded-xl hover:bg-gray-300 transition"
|
||||
>
|
||||
{isEn ? 'Change amount' : 'Изменить сумму'}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* История чеков */}
|
||||
<div className="mt-8 pt-8 border-t border-gray-200">
|
||||
<h3 className="text-xl font-bold text-gray-800 mb-4">{isEn ? 'Receipt History' : 'История чеков'}</h3>
|
||||
{checks.length > 0 ? (
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="w-10 h-10 rounded-lg bg-purple-100 dark:bg-purple-900/30 flex items-center justify-center flex-shrink-0">
|
||||
<svg className="w-5 h-5 text-purple-600 dark:text-purple-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold text-gray-800 dark:text-white text-sm">{isEn ? 'Low Fees' : 'Низкие комиссии'}</p>
|
||||
<p className="text-xs text-gray-600 dark:text-gray-400">
|
||||
{isEn ? 'Minimal network fees' : 'Минимальные комиссии сети'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* История платежей */}
|
||||
<div>
|
||||
<h3 className="text-xl font-bold text-gray-800 dark:text-white mb-4">
|
||||
{isEn ? 'Payment History' : 'История платежей'}
|
||||
</h3>
|
||||
{payments.length > 0 ? (
|
||||
<div className="space-y-3">
|
||||
{checks.map((check) => (
|
||||
{payments.map((payment) => (
|
||||
<div
|
||||
key={check.id}
|
||||
className="bg-gray-50 p-4 rounded-xl flex items-center justify-between"
|
||||
key={payment.id}
|
||||
className="bg-gray-50 dark:bg-gray-700/50 p-4 rounded-xl flex flex-col md:flex-row md:items-center justify-between gap-3 transition-colors duration-200"
|
||||
>
|
||||
<div>
|
||||
<p className="font-semibold text-gray-800">{check.amount} ₽</p>
|
||||
<p className="text-sm text-gray-500">
|
||||
{new Date(check.createdAt).toLocaleString(isEn ? 'en-US' : 'ru-RU')}
|
||||
<div className="flex-1">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<p className="font-bold text-gray-800 dark:text-white text-lg">
|
||||
+{payment.amount.toFixed(2)} ₽
|
||||
</p>
|
||||
<span className={`text-xs font-semibold ${getStatusColor(payment.status)}`}>
|
||||
{getStatusText(payment.status)}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400">
|
||||
{payment.cryptoAmount?.toFixed(4)} {payment.token}
|
||||
{payment.exchangeRate && (
|
||||
<span className="ml-2 text-xs">
|
||||
(@ {payment.exchangeRate.toFixed(2)} ₽)
|
||||
</span>
|
||||
)}
|
||||
</p>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-500 mt-1">
|
||||
{formatDate(payment.createdAt)}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<span className={`font-semibold ${getStatusColor(check.status)}`}>
|
||||
{getStatusText(check.status)}
|
||||
</span>
|
||||
{payment.transactionHash && (
|
||||
<a
|
||||
href={getCheckFileUrl(check.fileUrl)}
|
||||
href={`https://polygonscan.com/tx/${payment.transactionHash}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-ospab-primary hover:underline text-sm"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
const token = localStorage.getItem('access_token');
|
||||
const url = getCheckFileUrl(check.fileUrl);
|
||||
|
||||
// Открываем в новом окне с токеном в заголовке через fetch
|
||||
fetch(url, {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${token}`
|
||||
}
|
||||
})
|
||||
.then(res => res.blob())
|
||||
.then(blob => {
|
||||
const objectUrl = URL.createObjectURL(blob);
|
||||
window.open(objectUrl, '_blank');
|
||||
})
|
||||
.catch(err => {
|
||||
console.error('Ошибка загрузки чека:', err);
|
||||
showMessage(isEn ? 'Failed to load receipt' : 'Не удалось загрузить чек', 'error');
|
||||
});
|
||||
}}
|
||||
className="text-sm text-indigo-600 dark:text-indigo-400 hover:underline flex items-center gap-1"
|
||||
>
|
||||
{isEn ? 'Receipt' : 'Чек'}
|
||||
{isEn ? 'View on Explorer' : 'Посмотреть в Explorer'}
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
|
||||
</svg>
|
||||
</a>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-gray-500 text-center py-4">{isEn ? 'No receipts yet' : 'История чеков пуста'}</p>
|
||||
<div className="text-center py-12 bg-gray-50 dark:bg-gray-700/30 rounded-xl">
|
||||
<svg className="w-16 h-16 mx-auto text-gray-400 dark:text-gray-600 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
<p className="text-gray-500 dark:text-gray-400">
|
||||
{isEn ? 'No payment history yet' : 'История платежей пуста'}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user