Spaces:
Sleeping

microfunnel-api / frontend /components /bookings /CreateAppointmentModal.tsx
axeronis
feat: improve appointments page with stats, working day highlighting, create modal; remove Google Sheets from channels
b34de88
Raw History Blame Contribute Delete
12.1 kB
'use client'
import { useState } from 'react'
import { motion } from 'framer-motion'
import { X, Loader2, Calendar, Clock, User, Phone, Mail, FileText } from 'lucide-react'
import { bookingsApi } from '@/lib/api'
import { useToast } from '@/contexts/ToastContext'
import { format, addDays, setHours, setMinutes, parse } from 'date-fns'
import { ru } from 'date-fns/locale'
interface CreateAppointmentModalProps {
onClose: () => void
onSuccess: () => void
services: any[]
bookingSettings: {
working_days: string[]
working_hours: { start: string; end: string }
slot_duration: number
timezone?: string
}
}
export function CreateAppointmentModal({
onClose,
onSuccess,
services,
bookingSettings
}: CreateAppointmentModalProps) {
const toast = useToast()
const [loading, setLoading] = useState(false)
const [formData, setFormData] = useState({
date: format(new Date(), 'yyyy-MM-dd'),
time: bookingSettings.working_hours?.start || '09:00',
serviceId: services[0]?.id || '',
clientName: '',
clientPhone: '',
clientEmail: '',
notes: ''
})
// Generate time slots based on working hours and slot duration
const generateTimeSlots = () => {
const slots: string[] = []
const startHour = parseInt(bookingSettings.working_hours?.start?.split(':')[0] || '9')
const endHour = parseInt(bookingSettings.working_hours?.end?.split(':')[0] || '18')
const duration = bookingSettings.slot_duration || 30
for (let hour = startHour; hour < endHour; hour++) {
for (let minute = 0; minute < 60; minute += duration) {
slots.push(`${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`)
}
}
return slots
}
const timeSlots = generateTimeSlots()
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
if (!formData.clientName.trim()) {
toast.error('Введите имя клиента')
return
}
setLoading(true)
try {
// Parse date and time
const [year, month, day] = formData.date.split('-').map(Number)
const [hour, minute] = formData.time.split(':').map(Number)
const startTime = new Date(year, month - 1, day, hour, minute)
const selectedService = services.find(s => s.id === formData.serviceId)
const durationMinutes = selectedService?.duration_minutes || bookingSettings.slot_duration || 30
const endTime = new Date(startTime.getTime() + durationMinutes * 60 * 1000)
await bookingsApi.createAppointment({
service_id: formData.serviceId || undefined,
start_time: startTime.toISOString(),
end_time: endTime.toISOString(),
notes: formData.notes || undefined,
customer_name: formData.clientName,
customer_phone: formData.clientPhone || undefined,
customer_email: formData.clientEmail || undefined
})
toast.success('Запись создана!')
onSuccess()
} catch (error: any) {
console.error('Create appointment error:', error)
toast.error(error.response?.data?.detail || 'Ошибка создания записи')
} finally {
setLoading(false)
}
}
return (
<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-center justify-center p-4"
onClick={onClose}
>
<motion.div
initial={{ scale: 0.95, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
exit={{ scale: 0.95, opacity: 0 }}
className="bg-[#1E1F2E] rounded-2xl w-full max-w-md border border-white/10 shadow-xl"
onClick={(e) => e.stopPropagation()}
>
{/* Header */}
<div className="flex items-center justify-between p-4 border-b border-white/10">
<h2 className="text-lg font-bold text-white">Новая запись</h2>
<button
onClick={onClose}
className="p-2 hover:bg-white/10 rounded-lg transition-colors"
>
<X className="w-5 h-5 text-slate-400" />
</button>
</div>
{/* Form */}
<form onSubmit={handleSubmit} className="p-4 space-y-4">
{/* Date & Time */}
<div className="grid grid-cols-2 gap-3">
<div>
<label className="text-xs font-medium text-slate-400 mb-1 block">
<Calendar className="w-3.5 h-3.5 inline mr-1" />
Дата
</label>
<input
type="date"
value={formData.date}
onChange={(e) => setFormData({ ...formData, date: e.target.value })}
className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
/>
</div>
<div>
<label className="text-xs font-medium text-slate-400 mb-1 block">
<Clock className="w-3.5 h-3.5 inline mr-1" />
Время
</label>
<select
value={formData.time}
onChange={(e) => setFormData({ ...formData, time: e.target.value })}
className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
>
{timeSlots.map(slot => (
<option key={slot} value={slot}>{slot}</option>
))}
</select>
</div>
</div>
{/* Service */}
{services.length > 0 && (
<div>
<label className="text-xs font-medium text-slate-400 mb-1 block">Услуга</label>
<select
value={formData.serviceId}
onChange={(e) => setFormData({ ...formData, serviceId: e.target.value })}
className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
>
<option value="">Без услуги</option>
{services.map((service: any) => (
<option key={service.id} value={service.id}>
{service.name} ({service.duration_minutes} мин)
</option>
))}
</select>
</div>
)}
{/* Client Name */}
<div>
<label className="text-xs font-medium text-slate-400 mb-1 block">
<User className="w-3.5 h-3.5 inline mr-1" />
Имя клиента *
</label>
<input
type="text"
value={formData.clientName}
onChange={(e) => setFormData({ ...formData, clientName: e.target.value })}
placeholder="Иван Иванов"
className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white text-sm placeholder:text-slate-500 focus:outline-none focus:ring-2 focus:ring-indigo-500"
/>
</div>
{/* Phone & Email */}
<div className="grid grid-cols-2 gap-3">
<div>
<label className="text-xs font-medium text-slate-400 mb-1 block">
<Phone className="w-3.5 h-3.5 inline mr-1" />
Телефон
</label>
<input
type="tel"
value={formData.clientPhone}
onChange={(e) => setFormData({ ...formData, clientPhone: e.target.value })}
placeholder="+7 999 123 45 67"
className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white text-sm placeholder:text-slate-500 focus:outline-none focus:ring-2 focus:ring-indigo-500"
/>
</div>
<div>
<label className="text-xs font-medium text-slate-400 mb-1 block">
<Mail className="w-3.5 h-3.5 inline mr-1" />
Email
</label>
<input
type="email"
value={formData.clientEmail}
onChange={(e) => setFormData({ ...formData, clientEmail: e.target.value })}
placeholder="email@example.com"
className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white text-sm placeholder:text-slate-500 focus:outline-none focus:ring-2 focus:ring-indigo-500"
/>
</div>
</div>
{/* Notes */}
<div>
<label className="text-xs font-medium text-slate-400 mb-1 block">
<FileText className="w-3.5 h-3.5 inline mr-1" />
Заметки
</label>
<textarea
value={formData.notes}
onChange={(e) => setFormData({ ...formData, notes: e.target.value })}
placeholder="Дополнительная информация..."
rows={2}
className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white text-sm placeholder:text-slate-500 focus:outline-none focus:ring-2 focus:ring-indigo-500 resize-none"
/>
</div>
{/* Submit */}
<button
type="submit"
disabled={loading}
className="w-full py-3 bg-indigo-600 text-white font-bold rounded-xl hover:bg-indigo-700 transition-colors disabled:opacity-50 flex items-center justify-center gap-2"
>
{loading ? (
<>
<Loader2 className="w-4 h-4 animate-spin" />
Создание...
</>
) : (
'Создать запись'
)}
</button>
</form>
</motion.div>
</motion.div>
)
}