Spaces:
Running

microfunnel-api / frontend /components /knowledge /PaymentMethodsManager.tsx
axeronis
fix: Phase 11 - toggle aspect-ratio, day abbreviations, calendar/modal mobile UX
b92f979
Raw History Blame Contribute Delete
20.8 kB
'use client'
import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { knowledgeApi, uploadApi } from '@/lib/api'
import { useToast } from '@/contexts/ToastContext'
import { Plus, Trash2, Edit2, CreditCard, Link as LinkIcon, Image as ImageIcon, Loader2, Save, X, Upload } from 'lucide-react'
import { motion, AnimatePresence } from 'framer-motion'
interface PaymentMethod {
id: string
name: string
payment_type: 'requisites' | 'link' | 'qr_code' | 'image'
requisites_text?: string
payment_link?: string
image_url?: string
send_condition: 'on_request' | 'after_agreement' | 'always'
ai_instruction?: string
sort_order: number
}
const PAYMENT_TYPES = [
{ value: 'requisites', label: 'Реквизиты', icon: CreditCard, desc: 'Номер карты, ФИО получателя' },
{ value: 'link', label: 'Ссылка на оплату', icon: LinkIcon, desc: 'Прямая ссылка на оплату' },
{ value: 'image', label: 'Изображение / QR', icon: ImageIcon, desc: 'QR-код или фото реквизитов' }
]
const SEND_CONDITIONS = [
{ value: 'on_request', label: 'По запросу клиента' },
{ value: 'after_agreement', label: 'После согласия на покупку' },
{ value: 'always', label: 'Всегда показывать' }
]
export function PaymentMethodsManager() {
const toast = useToast()
const queryClient = useQueryClient()
const [editingMethod, setEditingMethod] = useState<PaymentMethod | null>(null)
const [showForm, setShowForm] = useState(false)
const [uploading, setUploading] = useState(false)
const [formData, setFormData] = useState({
name: '',
payment_type: 'requisites',
requisites_text: '',
payment_link: '',
image_url: '',
send_condition: 'on_request',
ai_instruction: '',
sort_order: 0
})
const { data: methods = [], isLoading } = useQuery({
queryKey: ['payment-methods'],
queryFn: knowledgeApi.getPaymentMethods
})
const createMutation = useMutation({
mutationFn: knowledgeApi.createPaymentMethod,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['payment-methods'] })
toast.success('Способ оплаты добавлен')
resetForm()
},
onError: () => toast.error('Ошибка при добавлении')
})
const updateMutation = useMutation({
mutationFn: ({ id, data }: { id: string; data: any }) => knowledgeApi.updatePaymentMethod(id, data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['payment-methods'] })
toast.success('Способ оплаты обновлён')
resetForm()
},
onError: () => toast.error('Ошибка при обновлении')
})
const deleteMutation = useMutation({
mutationFn: knowledgeApi.deletePaymentMethod,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['payment-methods'] })
toast.success('Способ оплаты удалён')
},
onError: () => toast.error('Ошибка при удалении')
})
const resetForm = () => {
setFormData({
name: '',
payment_type: 'requisites',
requisites_text: '',
payment_link: '',
image_url: '',
send_condition: 'on_request',
ai_instruction: '',
sort_order: 0
})
setEditingMethod(null)
setShowForm(false)
}
const handleEdit = (method: PaymentMethod) => {
setFormData({
name: method.name,
payment_type: method.payment_type,
requisites_text: method.requisites_text || '',
payment_link: method.payment_link || '',
image_url: method.image_url || '',
send_condition: method.send_condition,
ai_instruction: method.ai_instruction || '',
sort_order: method.sort_order
})
setEditingMethod(method)
setShowForm(true)
}
const handleSubmit = () => {
if (!formData.name.trim()) {
toast.error('Введите название')
return
}
if (editingMethod) {
updateMutation.mutate({ id: editingMethod.id, data: formData })
} else {
createMutation.mutate(formData)
}
}
const getTypeIcon = (type: string) => {
const found = PAYMENT_TYPES.find(t => t.value === type)
return found?.icon || CreditCard
}
if (isLoading) {
return (
<div className="flex items-center justify-center py-8">
<Loader2 className="w-6 h-6 animate-spin text-indigo-500" />
</div>
)
}
return (
<div className="space-y-4">
<div className="flex items-center justify-between">
<h3 className="text-lg font-semibold text-white">Способы оплаты</h3>
<button
onClick={() => setShowForm(true)}
className="flex items-center gap-2 px-3 py-1.5 bg-indigo-600 text-white text-sm rounded-lg hover:bg-indigo-700"
>
<Plus className="w-4 h-4" />
Добавить
</button>
</div>
{/* List */}
<div className="space-y-2">
{methods.length === 0 ? (
<div className="text-center py-8 text-slate-400">
Нет способов оплаты. Добавьте первый!
</div>
) : (
methods.map((method: PaymentMethod) => {
const TypeIcon = getTypeIcon(method.payment_type)
return (
<div key={method.id} className="flex items-center justify-between p-3 bg-white/5 rounded-lg border border-white/10">
<div className="flex items-center gap-3">
<div className="w-8 h-8 rounded-lg bg-indigo-500/20 flex items-center justify-center">
<TypeIcon className="w-4 h-4 text-indigo-400" />
</div>
<div>
<div className="text-white font-medium">{method.name}</div>
<div className="text-xs text-slate-400">
{SEND_CONDITIONS.find(c => c.value === method.send_condition)?.label}
</div>
</div>
</div>
<div className="flex items-center gap-2">
<button onClick={() => handleEdit(method)} className="p-2 hover:bg-white/10 rounded-lg">
<Edit2 className="w-4 h-4 text-slate-400" />
</button>
<button onClick={() => deleteMutation.mutate(method.id)} className="p-2 hover:bg-red-500/20 rounded-lg">
<Trash2 className="w-4 h-4 text-red-400" />
</button>
</div>
</div>
)
})
)}
</div>
{/* Form Modal */}
<AnimatePresence>
{showForm && (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
className="fixed inset-0 z-50 bg-black/60 backdrop-blur-sm flex items-end sm:items-center justify-center p-0 sm:p-4"
onClick={() => resetForm()}
>
<motion.div
initial={{ scale: 0.95, y: 50 }}
animate={{ scale: 1, y: 0 }}
exit={{ scale: 0.95, y: 50 }}
className="bg-[#1E1F2E] rounded-t-2xl sm:rounded-2xl w-full sm:max-w-md border border-white/10 max-h-[85vh] flex flex-col"
style={{ marginBottom: 'max(70px, env(safe-area-inset-bottom, 70px))' }}
onClick={e => e.stopPropagation()}
>
<div className="flex-shrink-0 flex items-center justify-between p-4 border-b border-white/10">
<h3 className="text-lg font-bold text-white">
{editingMethod ? 'Редактировать' : 'Новый способ оплаты'}
</h3>
<button onClick={() => resetForm()} className="p-2 hover:bg-white/10 rounded-lg">
<X className="w-5 h-5 text-slate-400" />
</button>
</div>
<div className="flex-1 overflow-y-auto p-4 space-y-4">
<div>
<label className="text-sm font-medium text-slate-400 mb-1 block">Название</label>
<input
type="text"
value={formData.name}
onChange={e => setFormData({ ...formData, name: e.target.value })}
placeholder="Например: Kaspi перевод"
className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white"
/>
</div>
<div>
<label className="text-sm font-medium text-slate-400 mb-1 block">Тип</label>
<div className="grid grid-cols-2 gap-2">
{PAYMENT_TYPES.map(type => (
<button
key={type.value}
onClick={() => setFormData({ ...formData, payment_type: type.value })}
className={`flex items-center gap-2 p-2 rounded-lg border ${formData.payment_type === type.value
? 'bg-indigo-500/20 border-indigo-500 text-indigo-400'
: 'bg-white/5 border-white/10 text-slate-300'
}`}
>
<type.icon className="w-4 h-4" />
<span className="text-sm">{type.label}</span>
</button>
))}
</div>
</div>
{formData.payment_type === 'requisites' && (
<div>
<label className="text-sm font-medium text-slate-400 mb-1 block">Реквизиты</label>
<textarea
value={formData.requisites_text}
onChange={e => setFormData({ ...formData, requisites_text: e.target.value })}
placeholder="Номер карты, ФИО получателя..."
rows={3}
className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white resize-none"
/>
</div>
)}
{formData.payment_type === 'link' && (
<div>
<label className="text-sm font-medium text-slate-400 mb-1 block">Ссылка на оплату</label>
<input
type="url"
value={formData.payment_link}
onChange={e => setFormData({ ...formData, payment_link: e.target.value })}
placeholder="https://..."
className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white"
/>
</div>
)}
{formData.payment_type === 'image' && (
<div>
<label className="text-sm font-medium text-slate-400 mb-2 block">Изображение (QR-код или фото)</label>
{/* Upload button */}
<label className={`flex items-center justify-center gap-2 p-4 border-2 border-dashed rounded-xl cursor-pointer transition-all mb-3 ${uploading ? 'border-indigo-500 bg-indigo-500/10' : 'border-white/20 hover:border-indigo-500/50 hover:bg-indigo-500/5'}`}>
{uploading ? (
<Loader2 className="w-5 h-5 text-indigo-400 animate-spin" />
) : (
<Upload className="w-5 h-5 text-slate-400" />
)}
<span className="text-slate-400">{uploading ? 'Загрузка...' : 'Загрузить изображение'}</span>
<input
type="file"
accept="image/*"
className="hidden"
disabled={uploading}
onChange={async (e) => {
const file = e.target.files?.[0]
if (file) {
try {
setUploading(true)
const result = await uploadApi.uploadImage(file)
setFormData({ ...formData, image_url: result.url })
toast.success('Изображение загружено!')
} catch (err) {
toast.error('Ошибка загрузки')
} finally {
setUploading(false)
}
}
}}
/>
</label>
{/* URL fallback */}
<div className="relative">
<span className="absolute left-3 top-1/2 -translate-y-1/2 text-xs text-slate-500">или URL:</span>
<input
type="url"
value={formData.image_url}
onChange={e => setFormData({ ...formData, image_url: e.target.value })}
placeholder="https://..."
className="w-full pl-16 pr-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white text-sm"
/>
</div>
{/* Preview */}
{formData.image_url && (
<div className="mt-3 p-2 bg-white/5 rounded-lg">
<img
src={formData.image_url}
alt="Preview"
className="max-h-32 mx-auto rounded"
onError={(e) => (e.target as HTMLImageElement).style.display = 'none'}
/>
</div>
)}
</div>
)}
<div>
<label className="text-sm font-medium text-slate-400 mb-1 block">Когда отправлять</label>
<select
value={formData.send_condition}
onChange={e => setFormData({ ...formData, send_condition: e.target.value })}
className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white"
>
{SEND_CONDITIONS.map(c => (
<option key={c.value} value={c.value}>{c.label}</option>
))}
</select>
</div>
<div>
<label className="text-sm font-medium text-slate-400 mb-1 block">Инструкция для ИИ (опционально)</label>
<textarea
value={formData.ai_instruction}
onChange={e => setFormData({ ...formData, ai_instruction: e.target.value })}
placeholder="Когда и как отправлять эти реквизиты..."
rows={2}
className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white resize-none"
/>
</div>
</div>
{/* Sticky Footer */}
<div className="flex-shrink-0 p-4 border-t border-white/10 bg-[#1E1F2E]">
<button
onClick={handleSubmit}
disabled={createMutation.isPending || updateMutation.isPending}
className="w-full py-3 bg-indigo-600 text-white font-bold rounded-xl hover:bg-indigo-700 disabled:opacity-50 flex items-center justify-center gap-2"
>
{(createMutation.isPending || updateMutation.isPending) ? (
<Loader2 className="w-4 h-4 animate-spin" />
) : (
<Save className="w-4 h-4" />
)}
{editingMethod ? 'Сохранить' : 'Добавить'}
</button>
</div>
</motion.div>
</motion.div>
)}
</AnimatePresence>
</div>
)
}