initial commit (frontend)

This commit is contained in:
2026-09-20 15:08:32 +03:00
commit 04cc53e66d
84 changed files with 36264 additions and 0 deletions
+561
View File
@@ -0,0 +1,561 @@
import { useState, useEffect, useRef, useCallback } from 'react';
import { useLanguage } from '../i18n/LanguageContext';
import { fonts, radius } from '../styles/theme';
import {
sendSupportMessage,
getUserMessages,
deleteTicket,
getAdminTickets,
getAdminMessages,
adminReply,
translateMessage,
getUserTickets,
} from '../api';
import { getUserId } from '../telegram';
interface SupportChatModalProps {
isOpen: boolean;
onClose: () => void;
isAdmin: boolean;
/** Вызывается, когда счётчик непрочитанных мог измениться (прочитали / отправили / удалили) */
onUnreadChange?: () => void;
}
interface SupportMessage {
id: number;
sender_id: number;
message: string;
is_read: boolean;
created_at: string;
}
interface SupportTicket {
id: number;
user_id?: number;
status: string;
created_at?: string;
updated_at?: string;
username?: string | null;
app_language?: string;
unread_count?: number;
last_message?: string | null;
}
const SupportChatModal: React.FC<SupportChatModalProps> = ({ isOpen, onClose, isAdmin, onUnreadChange }) => {
const { language } = useLanguage();
const [messages, setMessages] = useState<SupportMessage[]>([]);
const [tickets, setTickets] = useState<SupportTicket[]>([]);
const [inputValue, setInputValue] = useState('');
const [isLoading, setIsLoading] = useState(false);
const [selectedTicket, setSelectedTicket] = useState<SupportTicket | null>(null);
const [showTicketList, setShowTicketList] = useState(isAdmin);
const [translatedText, setTranslatedText] = useState<Record<number, string>>({});
const [isTranslating, setIsTranslating] = useState<number | null>(null);
const [isDeleting, setIsDeleting] = useState(false);
const messagesEndRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLTextAreaElement>(null);
const userId = getUserId();
const supportColor = '#FF6B6B';
const textColor = '#1A1A2E';
const subColor = '#6B7280';
const cardBg = 'rgba(255,255,255,0.55)';
const glass = (extra: React.CSSProperties = {}): React.CSSProperties => ({
background: cardBg,
backdropFilter: 'blur(24px) saturate(180%)',
WebkitBackdropFilter: 'blur(24px) saturate(180%)',
border: '1px solid rgba(255,255,255,0.7)',
boxShadow: '0 8px 32px rgba(31,38,73,0.10), inset 0 1px 0 rgba(255,255,255,0.85)',
...extra,
});
const getLabel = (pl: string, ru: string, uk: string, en: string): string => {
const labels: Record<string, string> = { pl, ru, uk, en };
return labels[language] || labels.en;
};
const getBackLabel = () => getLabel('Powrót', 'Назад', 'Назад', 'Back');
const getPlaceholderLabel = () => getLabel('Napisz wiadomość...', 'Сообщение...', 'Повідомлення...', 'Message...');
const getSendLabel = () => getLabel('Wyślij', 'Отправить', 'Надіслати', 'Send');
const getNoTicketsLabel = () => getLabel('Brak zgłoszeń', 'Нет обращений', 'Немає звернень', 'No tickets');
const getLoadingLabel = () => getLabel('Ładowanie...', 'Загрузка...', 'Завантаження...', 'Loading...');
const getDescriptionLabel = () => getLabel(
'Masz pytanie lub znalazłeś błąd? Napisz do nas!',
'Есть вопрос или нашёл ошибку? Напиши нам!',
'Є питання або знайшов помилку? Напиши нам!',
'Have a question or found a bug? Write to us!'
);
const loadAdminTickets = useCallback(async () => {
setIsLoading(true);
try {
const data = await getAdminTickets();
setTickets(data.tickets || []);
} catch (e) {
console.error('Error loading tickets:', e);
} finally {
setIsLoading(false);
}
}, []);
const loadAdminMessages = useCallback(async (ticketId: number) => {
setIsLoading(true);
try {
const data = await getAdminMessages(ticketId);
setMessages(data.messages || []);
} catch (e) {
console.error('Error loading admin messages:', e);
} finally {
setIsLoading(false);
}
}, []);
const loadUserMessages = useCallback(async (ticketId: number) => {
setIsLoading(true);
try {
const data = await getUserMessages(ticketId);
setMessages(data.messages || []);
// 🔧 Бэк пометил ответы админа как прочитанные — сообщаем родителю
if (onUnreadChange) onUnreadChange();
} catch (e) {
console.error('Error loading messages:', e);
} finally {
setIsLoading(false);
}
}, [onUnreadChange]);
useEffect(() => {
if (isOpen) {
setMessages([]);
setTickets([]);
setInputValue('');
setSelectedTicket(null);
setShowTicketList(isAdmin);
setTranslatedText({});
setIsDeleting(false);
if (isAdmin) {
loadAdminTickets();
} else {
const loadUserTicket = async () => {
try {
const data = await getUserTickets();
const openTickets = data.tickets?.filter(t => t.status === 'open') || [];
if (openTickets.length > 0) {
setSelectedTicket(openTickets[0]);
}
} catch (e) {
console.error('Error loading user tickets:', e);
}
};
loadUserTicket();
}
}
}, [isOpen, isAdmin, loadAdminTickets]);
useEffect(() => {
if (selectedTicket) {
if (isAdmin) {
loadAdminMessages(selectedTicket.id);
} else {
loadUserMessages(selectedTicket.id);
}
}
}, [selectedTicket, isAdmin, loadAdminMessages, loadUserMessages]);
useEffect(() => {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
}, [messages]);
const handleSend = async () => {
const text = inputValue.trim();
if (!text || isLoading) return;
setIsLoading(true);
try {
if (isAdmin && selectedTicket) {
await adminReply(selectedTicket.id, text);
await loadAdminMessages(selectedTicket.id);
} else {
const result = await sendSupportMessage(text);
if (result.ticket_id) {
const ticketsData = await getUserTickets();
const ticket = ticketsData.tickets?.find(t => t.id === result.ticket_id);
if (ticket) {
setSelectedTicket(ticket);
}
}
if (selectedTicket) {
await loadUserMessages(selectedTicket.id);
}
}
setInputValue('');
if (inputRef.current) {
inputRef.current.style.height = 'auto';
}
// 🔧 Сообщаем родителю — счётчик мог измениться
if (onUnreadChange) onUnreadChange();
} catch (e) {
console.error('Error sending message:', e);
} finally {
setIsLoading(false);
}
};
const handleTranslate = async (msgId: number, text: string) => {
if (translatedText[msgId] || isTranslating === msgId) return;
setIsTranslating(msgId);
try {
const targetLang = isAdmin ? 'ru' : language;
const data = await translateMessage(text, targetLang);
setTranslatedText(prev => ({ ...prev, [msgId]: data.translation }));
} catch (e) {
console.error('Error translating:', e);
} finally {
setIsTranslating(null);
}
};
// Мгновенное удаление
const handleDeleteClick = async () => {
if (!selectedTicket || isDeleting) return;
setIsDeleting(true);
try {
await deleteTicket(selectedTicket.id);
setSelectedTicket(null);
setMessages([]);
setShowTicketList(isAdmin);
if (isAdmin) {
loadAdminTickets();
}
// 🔧 Сообщаем родителю — счётчик мог измениться
if (onUnreadChange) onUnreadChange();
} catch (e) {
console.error('Error deleting ticket:', e);
} finally {
setIsDeleting(false);
}
};
const handleTextareaChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
setInputValue(e.target.value);
e.target.style.height = 'auto';
e.target.style.height = Math.min(e.target.scrollHeight, 100) + 'px';
};
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleSend();
}
};
if (!isOpen) return null;
// 🔧 ИСПРАВЛЕНО: определяем "от кого" сообщение через isAdmin проп, а не через хардкод
// Если я админ: мои сообщения — те, где sender_id === userId. Остальные — от пользователя.
// Если я пользователь: мои сообщения — те, где sender_id === userId. Остальные — от админа.
// В обоих случаях "свои" = sender_id === userId. Меняется только логика цвета.
const isMessageFromMe = (senderId: number) => senderId === Number(userId);
return (
<div
style={{
background: cardBg,
backdropFilter: 'blur(24px) saturate(180%)',
WebkitBackdropFilter: 'blur(24px) saturate(180%)',
border: '1px solid rgba(255,255,255,0.7)',
boxShadow: '0 24px 60px rgba(31,38,73,0.20), inset 0 1px 0 rgba(255,255,255,0.85)',
borderRadius: radius.lg,
padding: '20px',
width: '100%',
maxWidth: '420px',
height: '80vh',
maxHeight: '600px',
display: 'flex',
flexDirection: 'column',
animation: 'modalSlideUp 0.3s ease',
}}
onClick={(e) => e.stopPropagation()}
>
<style>{`
@keyframes modalSlideUp {
0% { transform: translateY(20px); opacity: 0; }
100% { transform: translateY(0); opacity: 1; }
}
@keyframes messageIn {
0% { transform: translateY(10px); opacity: 0; }
100% { transform: translateY(0); opacity: 1; }
}
@keyframes fadeInUp {
0% { transform: translateY(10px); opacity: 0; }
100% { transform: translateY(0); opacity: 1; }
}
`}</style>
{/* Заголовок */}
<div style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
marginBottom: '16px',
paddingBottom: '12px',
borderBottom: '1px solid rgba(0,0,0,0.06)',
flexShrink: 0,
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
{isAdmin && showTicketList ? (
<span />
) : isAdmin ? (
<button
onClick={() => {
setShowTicketList(true);
setSelectedTicket(null);
}}
style={{
...glass({ padding: '8px 14px', borderRadius: radius.sm }),
color: textColor,
fontSize: '14px',
fontWeight: 600,
cursor: 'pointer',
}}
>
← {getBackLabel()}
</button>
) : null}
<h3 style={{ margin: 0, fontSize: '18px', fontWeight: 800, color: textColor }}>
📮 {getLabel('Wsparcie', 'Поддержка', 'Підтримка', 'Support')}
</h3>
</div>
<div style={{ display: 'flex', gap: '6px' }}>
{selectedTicket && (
<button
onClick={handleDeleteClick}
disabled={isDeleting}
style={{
...glass({ padding: '8px 12px', borderRadius: radius.sm }),
color: '#E74C3C',
fontSize: '14px',
cursor: 'pointer',
}}
>
{isDeleting ? '...' : '🗑️'}
</button>
)}
<button
onClick={onClose}
style={{
...glass({ padding: '8px 14px', borderRadius: radius.sm }),
color: textColor,
fontSize: '14px',
cursor: 'pointer',
}}
>
✕
</button>
</div>
</div>
{/* Список тикетов (для админа) */}
{isAdmin && showTicketList && (
<div style={{ flex: 1, overflow: 'auto', display: 'flex', flexDirection: 'column', gap: '8px' }}>
{isLoading ? (
<div style={{ textAlign: 'center', padding: '40px', color: subColor, fontSize: '14px' }}>
{getLoadingLabel()}
</div>
) : tickets.length === 0 ? (
<div style={{ textAlign: 'center', padding: '40px', color: subColor, fontSize: '14px' }}>
{getNoTicketsLabel()}
</div>
) : (
tickets.map((ticket, index) => (
<button
key={ticket.id}
onClick={() => {
setSelectedTicket(ticket);
setShowTicketList(false);
}}
style={{
...glass({
padding: '14px 16px',
borderRadius: radius.md,
textAlign: 'left',
}),
cursor: 'pointer',
animation: `fadeInUp 0.3s ease ${index * 0.03}s both`,
border: ticket.unread_count && ticket.unread_count > 0 ? `2px solid ${supportColor}50` : '1px solid rgba(255,255,255,0.7)',
}}
>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '6px' }}>
<span style={{ fontSize: '14px', fontWeight: 700, color: textColor }}>
{ticket.username || `ID: ${ticket.user_id}`}
</span>
{ticket.unread_count && ticket.unread_count > 0 ? (
<span style={{
minWidth: '22px',
height: '22px',
borderRadius: '11px',
background: '#E74C3C',
color: '#FFFFFF',
fontSize: '11px',
fontWeight: 800,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
padding: '0 6px',
}}>
{ticket.unread_count}
</span>
) : (
<span style={{ fontSize: '11px', color: subColor }}>
{ticket.app_language ? ticket.app_language.toUpperCase() : ''}
</span>
)}
</div>
{ticket.last_message && (
<div style={{ fontSize: '12px', color: subColor, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{ticket.last_message}
</div>
)}
</button>
))
)}
</div>
)}
{/* Чат с сообщениями */}
{(!isAdmin || (isAdmin && !showTicketList)) && (
<>
<div style={{
flex: 1,
overflow: 'auto',
display: 'flex',
flexDirection: 'column',
gap: '10px',
paddingBottom: '12px',
WebkitOverflowScrolling: 'touch',
}}>
{isLoading ? (
<div style={{ textAlign: 'center', padding: '40px', color: subColor, fontSize: '14px' }}>
{getLoadingLabel()}
</div>
) : messages.length === 0 ? (
<div style={{ textAlign: 'center', padding: '40px', color: subColor, fontSize: '14px' }}>
<div style={{ fontSize: '40px', marginBottom: '12px' }}>📮</div>
{getDescriptionLabel()}
</div>
) : (
messages.map((msg) => {
const isFromMe = isMessageFromMe(msg.sender_id);
const isTranslated = translatedText[msg.id];
return (
<div
key={msg.id}
style={{
alignSelf: isFromMe ? 'flex-end' : 'flex-start',
maxWidth: '85%',
animation: 'messageIn 0.3s ease',
}}
>
<div
style={{
padding: '10px 14px',
borderRadius: isFromMe ? '16px 16px 4px 16px' : '16px 16px 16px 4px',
background: isFromMe
? `linear-gradient(135deg, ${supportColor}, #E85D5D)`
: 'rgba(255,255,255,0.8)',
color: isFromMe ? '#FFFFFF' : textColor,
fontSize: '14px',
lineHeight: '1.5',
whiteSpace: 'pre-line',
border: isFromMe ? 'none' : '1px solid rgba(0,0,0,0.06)',
boxShadow: isFromMe
? '0 2px 10px rgba(255,107,107,0.3)'
: '0 2px 8px rgba(31,38,73,0.06)',
wordBreak: 'break-word',
cursor: 'pointer',
}}
onClick={() => handleTranslate(msg.id, msg.message)}
>
{isTranslated ? isTranslated : msg.message}
{isTranslating === msg.id && (
<span style={{ fontSize: '10px', opacity: 0.7 }}> ...</span>
)}
</div>
</div>
);
})
)}
<div ref={messagesEndRef} />
</div>
<div style={{
display: 'flex',
gap: '8px',
flexShrink: 0,
paddingTop: '12px',
borderTop: '1px solid rgba(0,0,0,0.06)',
}}>
<textarea
ref={inputRef}
value={inputValue}
onChange={handleTextareaChange}
onKeyDown={handleKeyDown}
placeholder={getPlaceholderLabel()}
disabled={isLoading}
rows={1}
style={{
flex: 1,
padding: '12px 16px',
borderRadius: radius.md,
border: `1px solid ${supportColor}30`,
background: 'rgba(255,255,255,0.8)',
color: textColor,
fontSize: '14px',
fontFamily: fonts.main,
outline: 'none',
resize: 'none',
maxHeight: '100px',
overflowY: 'auto',
minHeight: '44px',
}}
onFocus={(e) => {
e.currentTarget.style.borderColor = supportColor;
e.currentTarget.style.boxShadow = `0 0 0 3px ${supportColor}15`;
}}
onBlur={(e) => {
e.currentTarget.style.borderColor = `${supportColor}30`;
e.currentTarget.style.boxShadow = 'none';
}}
/>
<button
onClick={handleSend}
disabled={isLoading || !inputValue.trim()}
style={{
padding: '12px 18px',
borderRadius: radius.md,
border: 'none',
background: isLoading || !inputValue.trim()
? 'rgba(0,0,0,0.1)'
: `linear-gradient(135deg, ${supportColor}, #E85D5D)`,
color: '#FFFFFF',
fontSize: '14px',
fontWeight: 700,
cursor: isLoading || !inputValue.trim() ? 'default' : 'pointer',
flexShrink: 0,
}}
>
{getSendLabel()}
</button>
</div>
</>
)}
</div>
);
};
export default SupportChatModal;