Spaces:
Running
Running
Download frontend/components/GoogleSheetsCard.tsx from axeronis/microfunnel-api: direct link, hf CLI and curl.
- Browser
- Download file 18.4 kB
-
https://huggingface.co/spaces/axeronis/microfunnel-api/resolve/main/frontend/components/GoogleSheetsCard.tsx
- Command line
-
hf download hf://spaces/axeronis/microfunnel-api/frontend/components/GoogleSheetsCard.tsx
-
curl -L -o GoogleSheetsCard.tsx https://huggingface.co/spaces/axeronis/microfunnel-api/resolve/main/frontend/components/GoogleSheetsCard.tsx
18.4 kB
| 'use client' | |
| import { useState, useEffect } from 'react' | |
| import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' | |
| import { useToast } from '@/contexts/ToastContext' | |
| import { googleSheetsApi } from '@/lib/api' | |
| import { motion, AnimatePresence } from 'framer-motion' | |
| import { cn } from '@/lib/utils' | |
| import { Loader2, RefreshCw, Link2, Unlink, CheckCircle, XCircle, Table, FileSpreadsheet, Settings } from 'lucide-react' | |
| interface GoogleSheetsCardProps { | |
| className?: string | |
| } | |
| export default function GoogleSheetsCard({ className }: GoogleSheetsCardProps) { | |
| const toast = useToast() | |
| const queryClient = useQueryClient() | |
| // State | |
| const [isModalOpen, setIsModalOpen] = useState(false) | |
| const [sheetUrl, setSheetUrl] = useState('') | |
| const [sheetName, setSheetName] = useState('Sheet1') | |
| const [mapping, setMapping] = useState({ name: 'A', price: 'B', quantity: 'C' }) | |
| const [previewData, setPreviewData] = useState<{ headers: string[], rows: string[][], total_rows: number } | null>(null) | |
| const [isPreviewLoading, setIsPreviewLoading] = useState(false) | |
| // Fetch status | |
| const { data: status, isLoading } = useQuery({ | |
| queryKey: ['google-sheets-status'], | |
| queryFn: googleSheetsApi.getStatus, | |
| retry: false | |
| }) | |
| // Connect mutation | |
| const connectMutation = useMutation({ | |
| mutationFn: (data: any) => googleSheetsApi.connect(data), | |
| onSuccess: () => { | |
| toast.success('Успех!', 'Google Sheet подключен') | |
| queryClient.invalidateQueries({ queryKey: ['google-sheets-status'] }) | |
| setIsModalOpen(false) | |
| }, | |
| onError: (e: any) => { | |
| toast.error('Ошибка', e.response?.data?.detail || 'Не удалось подключить') | |
| } | |
| }) | |
| // Sync mutation | |
| const syncMutation = useMutation({ | |
| mutationFn: googleSheetsApi.sync, | |
| onSuccess: (data) => { | |
| toast.success('Синхронизация', `Обновлено ${data.synced} товаров`) | |
| queryClient.invalidateQueries({ queryKey: ['google-sheets-status'] }) | |
| }, | |
| onError: (e: any) => { | |
| toast.error('Ошибка', e.response?.data?.detail || 'Синхронизация не удалась') | |
| } | |
| }) | |
| // Disconnect mutation | |
| const disconnectMutation = useMutation({ | |
| mutationFn: googleSheetsApi.disconnect, | |
| onSuccess: () => { | |
| toast.success('Отключено', 'Google Sheet отключен') | |
| queryClient.invalidateQueries({ queryKey: ['google-sheets-status'] }) | |
| } | |
| }) | |
| // Preview sheet | |
| const handlePreview = async () => { | |
| if (!sheetUrl) return | |
| setIsPreviewLoading(true) | |
| try { | |
| const data = await googleSheetsApi.preview(sheetUrl, sheetName) | |
| setPreviewData(data) | |
| } catch (e: any) { | |
| toast.error('Ошибка', e.response?.data?.detail || 'Не удалось загрузить таблицу') | |
| } finally { | |
| setIsPreviewLoading(false) | |
| } | |
| } | |
| // Connect sheet | |
| const handleConnect = () => { | |
| connectMutation.mutate({ | |
| sheet_url: sheetUrl, | |
| sheet_name: sheetName, | |
| mapping, | |
| sync_enabled: true | |
| }) | |
| } | |
| const isConnected = status?.connected | |
| if (isLoading) { | |
| return ( | |
| <div className={cn("bg-surface-elevated rounded-2xl p-6 border border-white/10", className)}> | |
| <div className="flex items-center justify-center py-8"> | |
| <Loader2 className="w-6 h-6 animate-spin text-slate-400" /> | |
| </div> | |
| </div> | |
| ) | |
| } | |
| return ( | |
| <> | |
| {/* Main Card */} | |
| <div className={cn("bg-surface-elevated rounded-2xl p-6 border border-white/10 relative overflow-hidden", className)}> | |
| {/* Gradient accent */} | |
| <div className="absolute top-0 left-0 right-0 h-1 bg-gradient-to-r from-green-500 to-emerald-400" /> | |
| <div className="flex items-start justify-between mb-4"> | |
| <div className="flex items-center gap-3"> | |
| <div className="p-3 bg-green-500/20 rounded-xl"> | |
| <FileSpreadsheet className="w-6 h-6 text-green-500" /> | |
| </div> | |
| <div> | |
| <h3 className="text-lg font-bold text-white">Google Sheets</h3> | |
| <p className="text-sm text-slate-400">Синхронизация наличия товаров</p> | |
| </div> | |
| </div> | |
| {isConnected ? ( | |
| <div className="flex items-center gap-2 px-3 py-1.5 bg-green-500/10 rounded-full"> | |
| <CheckCircle className="w-4 h-4 text-green-500" /> | |
| <span className="text-sm text-green-400 font-medium">Подключено</span> | |
| </div> | |
| ) : ( | |
| <div className="flex items-center gap-2 px-3 py-1.5 bg-slate-500/10 rounded-full"> | |
| <XCircle className="w-4 h-4 text-slate-400" /> | |
| <span className="text-sm text-slate-400 font-medium">Не подключено</span> | |
| </div> | |
| )} | |
| </div> | |
| {isConnected && ( | |
| <div className="mb-4 p-3 bg-surface rounded-lg border border-white/5"> | |
| <div className="flex items-center justify-between text-sm"> | |
| <span className="text-slate-400">Последняя синхронизация:</span> | |
| <span className="text-white">{status.last_sync ? new Date(status.last_sync).toLocaleString('ru') : 'Никогда'}</span> | |
| </div> | |
| </div> | |
| )} | |
| <div className="flex gap-2"> | |
| {isConnected ? ( | |
| <> | |
| <button | |
| onClick={() => syncMutation.mutate()} | |
| disabled={syncMutation.isPending} | |
| className="flex-1 py-2.5 px-4 bg-green-600 hover:bg-green-700 text-white rounded-lg font-medium transition-colors disabled:opacity-50 flex items-center justify-center gap-2" | |
| > | |
| {syncMutation.isPending ? <Loader2 className="w-4 h-4 animate-spin" /> : <RefreshCw className="w-4 h-4" />} | |
| Синхронизировать | |
| </button> | |
| <button | |
| onClick={() => disconnectMutation.mutate()} | |
| className="py-2.5 px-4 bg-red-500/10 hover:bg-red-500/20 text-red-400 rounded-lg font-medium transition-colors" | |
| > | |
| <Unlink className="w-4 h-4" /> | |
| </button> | |
| </> | |
| ) : ( | |
| <button | |
| onClick={() => setIsModalOpen(true)} | |
| className="w-full py-2.5 px-4 bg-green-600 hover:bg-green-700 text-white rounded-lg font-medium transition-colors flex items-center justify-center gap-2" | |
| > | |
| <Link2 className="w-4 h-4" /> | |
| Подключить таблицу | |
| </button> | |
| )} | |
| </div> | |
| </div> | |
| {/* Connect Modal */} | |
| <AnimatePresence> | |
| {isModalOpen && ( | |
| <motion.div | |
| initial={{ opacity: 0 }} | |
| animate={{ opacity: 1 }} | |
| exit={{ opacity: 0 }} | |
| className="fixed inset-0 bg-black/60 backdrop-blur-sm z-50 flex items-center justify-center p-4" | |
| onClick={() => setIsModalOpen(false)} | |
| > | |
| <motion.div | |
| initial={{ scale: 0.95, opacity: 0 }} | |
| animate={{ scale: 1, opacity: 1 }} | |
| exit={{ scale: 0.95, opacity: 0 }} | |
| className="bg-surface-elevated rounded-2xl p-6 w-full max-w-lg border border-white/10 shadow-2xl" | |
| onClick={(e) => e.stopPropagation()} | |
| > | |
| <h2 className="text-xl font-bold text-white mb-4 flex items-center gap-2"> | |
| <FileSpreadsheet className="w-6 h-6 text-green-500" /> | |
| Подключить Google Sheet | |
| </h2> | |
| <div className="space-y-4"> | |
| {/* Instructions */} | |
| <div className="p-3 bg-green-500/10 rounded-lg border border-green-500/20 text-sm text-green-300"> | |
| <p className="font-medium mb-1">Как подключить:</p> | |
| <ol className="list-decimal list-inside space-y-1 text-green-400"> | |
| <li>Откройте вашу Google таблицу</li> | |
| <li>Нажмите "Поделиться" → "Все у кого есть ссылка"</li> | |
| <li>Скопируйте ссылку и вставьте ниже</li> | |
| </ol> | |
| </div> | |
| {/* Sheet URL */} | |
| <div> | |
| <label className="block text-sm text-slate-300 mb-2">Ссылка на таблицу</label> | |
| <input | |
| type="text" | |
| value={sheetUrl} | |
| onChange={(e) => setSheetUrl(e.target.value)} | |
| placeholder="https://docs.google.com/spreadsheets/d/..." | |
| className="w-full px-4 py-3 bg-surface border border-white/10 rounded-lg text-white placeholder:text-slate-500 focus:border-green-500 focus:ring-1 focus:ring-green-500/30 outline-none" | |
| /> | |
| </div> | |
| {/* Sheet Name */} | |
| <div> | |
| <label className="block text-sm text-slate-300 mb-2">Имя листа (вкладки)</label> | |
| <input | |
| type="text" | |
| value={sheetName} | |
| onChange={(e) => setSheetName(e.target.value)} | |
| placeholder="Sheet1" | |
| className="w-full px-4 py-3 bg-surface border border-white/10 rounded-lg text-white placeholder:text-slate-500 focus:border-green-500 focus:ring-1 focus:ring-green-500/30 outline-none" | |
| /> | |
| </div> | |
| {/* Preview Button */} | |
| <button | |
| onClick={handlePreview} | |
| disabled={!sheetUrl || isPreviewLoading} | |
| className="w-full py-2.5 px-4 bg-slate-700 hover:bg-slate-600 text-white rounded-lg font-medium transition-colors disabled:opacity-50 flex items-center justify-center gap-2" | |
| > | |
| {isPreviewLoading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Table className="w-4 h-4" />} | |
| Предпросмотр данных | |
| </button> | |
| {/* Preview Data */} | |
| {previewData && ( | |
| <div className="p-3 bg-surface rounded-lg border border-white/10 overflow-x-auto"> | |
| <p className="text-xs text-slate-400 mb-2">Колонки: {previewData.headers.join(', ')}</p> | |
| <table className="w-full text-sm"> | |
| <thead> | |
| <tr className="border-b border-white/10"> | |
| {previewData.headers.map((h, i) => ( | |
| <th key={i} className="text-left py-1 px-2 text-slate-400 font-medium"> | |
| {String.fromCharCode(65 + i)}: {h} | |
| </th> | |
| ))} | |
| </tr> | |
| </thead> | |
| <tbody> | |
| {previewData.rows.slice(0, 3).map((row, i) => ( | |
| <tr key={i} className="border-b border-white/5"> | |
| {row.map((cell, j) => ( | |
| <td key={j} className="py-1 px-2 text-white truncate max-w-[100px]" title={cell}>{cell}</td> | |
| ))} | |
| </tr> | |
| ))} | |
| </tbody> | |
| </table> | |
| <p className="text-xs text-slate-500 mt-2">Всего строк: {previewData.total_rows}</p> | |
| </div> | |
| )} | |
| {/* Column Mapping */} | |
| {previewData && ( | |
| <div className="grid grid-cols-3 gap-3"> | |
| <div> | |
| <label className="block text-xs text-slate-400 mb-1">Название</label> | |
| <input | |
| type="text" | |
| value={mapping.name} | |
| onChange={(e) => setMapping({ ...mapping, name: e.target.value })} | |
| placeholder="A" | |
| className="w-full px-3 py-2 bg-surface border border-white/10 rounded-lg text-white text-center uppercase" | |
| /> | |
| </div> | |
| <div> | |
| <label className="block text-xs text-slate-400 mb-1">Цена</label> | |
| <input | |
| type="text" | |
| value={mapping.price} | |
| onChange={(e) => setMapping({ ...mapping, price: e.target.value })} | |
| placeholder="B" | |
| className="w-full px-3 py-2 bg-surface border border-white/10 rounded-lg text-white text-center uppercase" | |
| /> | |
| </div> | |
| <div> | |
| <label className="block text-xs text-slate-400 mb-1">Количество</label> | |
| <input | |
| type="text" | |
| value={mapping.quantity} | |
| onChange={(e) => setMapping({ ...mapping, quantity: e.target.value })} | |
| placeholder="C" | |
| className="w-full px-3 py-2 bg-surface border border-white/10 rounded-lg text-white text-center uppercase" | |
| /> | |
| </div> | |
| </div> | |
| )} | |
| {/* Actions */} | |
| <div className="flex gap-3 pt-2"> | |
| <button | |
| onClick={() => setIsModalOpen(false)} | |
| className="flex-1 py-2.5 px-4 bg-slate-700 hover:bg-slate-600 text-white rounded-lg font-medium transition-colors" | |
| > | |
| Отмена | |
| </button> | |
| <button | |
| onClick={handleConnect} | |
| disabled={!sheetUrl || !previewData || connectMutation.isPending} | |
| className="flex-1 py-2.5 px-4 bg-green-600 hover:bg-green-700 text-white rounded-lg font-medium transition-colors disabled:opacity-50 flex items-center justify-center gap-2" | |
| > | |
| {connectMutation.isPending && <Loader2 className="w-4 h-4 animate-spin" />} | |
| Подключить | |
| </button> | |
| </div> | |
| </div> | |
| </motion.div> | |
| </motion.div> | |
| )} | |
| </AnimatePresence> | |
| </> | |
| ) | |
| } | |