Spaces:
Running

File size: 20,829 Bytes
263213f
 
 
 
3bafddd
263213f
6661747
263213f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6661747
 
 
263213f
 
 
 
 
 
 
 
 
 
 
 
 
3bafddd
263213f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b92f979
263213f
 
 
b92f979
 
 
 
 
263213f
 
b92f979
263213f
 
 
 
 
 
 
 
b92f979
263213f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6661747
 
263213f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6661747
263213f
6661747
 
 
3bafddd
 
 
 
 
 
 
6661747
 
 
 
3bafddd
6661747
 
 
3bafddd
 
 
 
 
 
 
 
 
 
6661747
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
263213f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b92f979
263213f
b92f979
 
263213f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
'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>
    )
}