Spaces:
Running

axeronis commited on
Commit
d54be21
·
1 Parent(s): 208781e

feat: optimized BookingModal with resource selection, dynamic working hours, existing booking warning

Browse files
backend/app/api/bookings.py CHANGED
@@ -48,6 +48,39 @@ async def list_appointments(
48
  result = await session.execute(query)
49
  return result.scalars().all()
50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  @router.post("/", response_model=Appointment)
52
  async def create_appointment(
53
  appointment: Appointment,
 
48
  result = await session.execute(query)
49
  return result.scalars().all()
50
 
51
+
52
+ @router.get("/lead/{lead_id}")
53
+ async def get_appointments_by_lead(
54
+ lead_id: UUID,
55
+ session: AsyncSession = Depends(get_session),
56
+ current_user: User = Depends(get_current_user)
57
+ ):
58
+ """Get all appointments for a specific lead."""
59
+ query = select(Appointment).where(
60
+ Appointment.tenant_id == current_user.tenant_id,
61
+ Appointment.lead_id == lead_id
62
+ ).options(
63
+ selectinload(Appointment.service),
64
+ selectinload(Appointment.resource)
65
+ ).order_by(col(Appointment.start_time).desc())
66
+
67
+ result = await session.execute(query)
68
+ appointments = result.scalars().all()
69
+
70
+ return [
71
+ {
72
+ "id": str(a.id),
73
+ "start_time": a.start_time.isoformat() if a.start_time else None,
74
+ "end_time": a.end_time.isoformat() if a.end_time else None,
75
+ "status": a.status.value if a.status else "scheduled",
76
+ "service_name": a.service.name if a.service else None,
77
+ "resource_name": a.resource.name if a.resource else None,
78
+ "notes": a.notes
79
+ }
80
+ for a in appointments
81
+ ]
82
+
83
+
84
  @router.post("/", response_model=Appointment)
85
  async def create_appointment(
86
  appointment: Appointment,
frontend/components/bookings/BookingModal.tsx CHANGED
@@ -1,8 +1,8 @@
1
  'use client'
2
 
3
- import { useState, useEffect } from 'react'
4
- import { X, Calendar as CalendarIcon, Clock, Loader2, Check } from 'lucide-react'
5
- import { format, addDays, startOfToday, isSameDay } from 'date-fns'
6
  import { ru } from 'date-fns/locale'
7
  import { motion, AnimatePresence } from 'framer-motion'
8
  import { bookingsApi } from '@/lib/api'
@@ -15,36 +15,130 @@ interface BookingModalProps {
15
  leadName?: string
16
  }
17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  export function BookingModal({ isOpen, onClose, leadId, leadName }: BookingModalProps) {
19
- const [step, setStep] = useState<'date' | 'time' | 'confirm'>('date')
20
  const [selectedDate, setSelectedDate] = useState<Date>(startOfToday())
21
  const [selectedTime, setSelectedTime] = useState<string | null>(null)
 
22
  const [bookingNote, setBookingNote] = useState('')
23
  const [isSubmitting, setIsSubmitting] = useState(false)
24
  const [isSuccess, setIsSuccess] = useState(false)
25
- const [services, setServices] = useState<any[]>([])
 
 
 
 
26
  const [selectedService, setSelectedService] = useState<string | null>(null)
 
27
 
28
- // Load available services (in real app)
29
  useEffect(() => {
30
- if (isOpen) {
31
- setIsSuccess(false) // Reset on open
32
- bookingsApi.getServices().then(data => {
33
- if (data && data.length > 0) {
34
- setServices(data)
35
- setSelectedService(data[0].id)
36
- } else {
37
- setServices([{ id: 'default', name: 'Консультация', duration_minutes: 30 }])
38
- setSelectedService('default')
39
- }
40
- }).catch(() => {
 
 
 
 
 
 
 
 
41
  setServices([{ id: 'default', name: 'Консультация', duration_minutes: 30 }])
42
  setSelectedService('default')
43
- })
 
 
44
  }
45
- }, [isOpen])
46
 
47
- const handleBook = async () => {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  if (!selectedDate || !selectedTime || !selectedService) return
49
 
50
  setIsSubmitting(true)
@@ -60,6 +154,7 @@ export function BookingModal({ isOpen, onClose, leadId, leadName }: BookingModal
60
  await bookingsApi.createAppointment({
61
  lead_id: leadId,
62
  service_id: selectedService === 'default' ? null : selectedService,
 
63
  start_time: startDateTime.toISOString(),
64
  end_time: endDateTime.toISOString(),
65
  notes: bookingNote,
@@ -69,27 +164,17 @@ export function BookingModal({ isOpen, onClose, leadId, leadName }: BookingModal
69
  setIsSuccess(true)
70
  } catch (error) {
71
  console.error('Booking error:', error)
72
- // Use toast if available, or just log
73
  } finally {
74
  setIsSubmitting(false)
75
  }
76
- }
77
-
78
- // Generate next 14 days
79
- const dates = Array.from({ length: 14 }).map((_, i) => addDays(startOfToday(), i))
80
-
81
- // Generate time slots (mock)
82
- const timeSlots = [
83
- '09:00', '09:30', '10:00', '10:30', '11:00', '11:30',
84
- '12:00', '13:00', '13:30', '14:00', '14:30', '15:00',
85
- '15:30', '16:00', '16:30', '17:00'
86
- ]
87
 
88
  if (!isOpen) return null
89
 
 
 
90
  return (
91
  <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
92
- {/* Backdrop */}
93
  <motion.div
94
  initial={{ opacity: 0 }}
95
  animate={{ opacity: 1 }}
@@ -99,176 +184,211 @@ export function BookingModal({ isOpen, onClose, leadId, leadName }: BookingModal
99
  />
100
 
101
  <motion.div
102
- initial={{ opacity: 0, scale: 0.95, y: 20 }}
103
- animate={{ opacity: 1, scale: 1, y: 0 }}
104
- exit={{ opacity: 0, scale: 0.95, y: 20 }}
105
- className="relative bg-[#0D0E18]/90 backdrop-blur-2xl border border-white/10 rounded-[32px] w-full max-w-md md:max-w-4xl overflow-hidden shadow-[0_0_50px_rgba(0,0,0,0.5)] flex flex-col max-h-[90vh]"
106
- style={{
107
- willChange: 'transform',
108
- transform: 'translateZ(0)'
109
- }}
110
  >
111
- {/* Aurora Background Atmosphere */}
112
- <div className="absolute inset-0 pointer-events-none overflow-hidden -z-10 opacity-30">
113
- <div className="absolute top-[-10%] right-[-10%] w-[60%] h-[60%] bg-indigo-500/20 blur-[80px] rounded-full" />
114
- <div className="absolute bottom-[-10%] left-[-10%] w-[60%] h-[60%] bg-purple-500/20 blur-[80px] rounded-full" />
115
- </div>
116
-
117
  <AnimatePresence mode="wait">
118
  {isSuccess ? (
119
  <motion.div
120
  key="success"
121
  initial={{ opacity: 0, y: 20 }}
122
  animate={{ opacity: 1, y: 0 }}
123
- className="p-10 flex flex-col items-center text-center max-w-lg mx-auto"
124
  >
125
- <div className="w-20 h-20 rounded-3xl bg-emerald-500/10 border border-emerald-500/30 flex items-center justify-center mb-6 relative">
126
- <Check className="w-10 h-10 text-emerald-400" />
127
- <motion.div
128
- initial={{ scale: 0.8, opacity: 0 }}
129
- animate={{ scale: 1.5, opacity: 0 }}
130
- transition={{ duration: 1, repeat: Infinity }}
131
- className="absolute inset-0 rounded-3xl border border-emerald-500/50"
132
- />
133
  </div>
134
-
135
- <h3 className="text-2xl font-bold text-white mb-2">Запись создана!</h3>
136
- <p className="text-slate-400 mb-8 leading-relaxed">
137
- Встреча с клиентом <span className="text-white font-medium">{leadName}</span> успешно запланирована на <span className="text-indigo-400 font-bold">{selectedTime}</span> {format(selectedDate, 'd MMMM', { locale: ru })}.
 
138
  </p>
139
-
140
  <button
141
  onClick={onClose}
142
- className="w-full py-4 bg-white/10 hover:bg-white/20 text-white font-bold rounded-2xl transition-all border border-white/10"
143
  >
144
- Отлично
145
  </button>
146
  </motion.div>
 
 
 
 
147
  ) : (
148
- <motion.div key="form" className="flex flex-col h-full overflow-hidden">
149
  {/* Header */}
150
- <div className="px-6 md:px-8 py-4 md:py-6 border-b border-white/5 flex items-center justify-between shrink-0 bg-white/[0.02]">
151
  <div>
152
- <h3 className="font-bold text-lg md:text-xl text-white flex items-center gap-2">
153
  <CalendarIcon className="w-5 h-5 text-indigo-400" />
154
  Запись: {leadName || 'Клиент'}
155
  </h3>
156
- <p className="text-[10px] md:text-xs text-slate-500 font-medium uppercase tracking-wider mt-0.5">Выберите параметры визита</p>
157
  </div>
158
- <button onClick={onClose} className="p-2 hover:bg-white/10 rounded-full transition-all text-slate-400 hover:text-white border border-transparent hover:border-white/10">
159
  <X className="w-5 h-5" />
160
  </button>
161
  </div>
162
 
163
- <div className="flex-1 overflow-y-auto overflow-x-hidden scrollbar-thin scrollbar-thumb-white/10 p-4 md:p-8" style={{ WebkitOverflowScrolling: 'touch' }}>
164
- <div className="grid grid-cols-1 md:grid-cols-[1fr_200px_200px] gap-8">
165
- {/* Col 1: Service & Notes */}
166
- <div className="space-y-6">
167
- <section>
168
- <label className="block text-[10px] font-bold text-slate-500 uppercase tracking-[0.2em] mb-4 ml-1">Тип встречи</label>
169
- <div className="grid grid-cols-1 gap-2">
170
- {services.map(s => (
171
- <button
172
- key={s.id}
173
- onClick={() => setSelectedService(s.id)}
174
- className={cn(
175
- "w-full p-4 rounded-2xl border text-left transition-all duration-300 group relative overflow-hidden",
176
- selectedService === s.id
177
- ? "bg-indigo-600/20 border-indigo-500/50 shadow-[0_0_20px_rgba(99,102,241,0.1)]"
178
- : "bg-white/5 border-white/10 hover:bg-white/10 hover:border-white/20"
179
- )}
180
- >
181
- <div className="relative z-10 flex items-center justify-between">
182
- <div>
183
- <h4 className={cn(
184
- "font-bold transition-colors",
185
- selectedService === s.id ? "text-white" : "text-slate-300 group-hover:text-white"
186
- )}>{s.name}</h4>
187
- <div className="flex items-center gap-2 mt-1">
188
- <Clock className="w-3 h-3 text-slate-500" />
189
- <span className="text-xs text-slate-500 font-medium">{s.duration_minutes} минут</span>
190
- </div>
191
- </div>
192
- {selectedService === s.id && (
193
- <div className="w-6 h-6 rounded-full bg-indigo-500 flex items-center justify-center">
194
- <Check className="w-4 h-4 text-white" />
195
- </div>
196
- )}
197
- </div>
198
- </button>
199
- ))}
200
- </div>
201
- </section>
202
-
203
- <section>
204
- <label className="block text-[10px] font-bold text-slate-500 uppercase tracking-[0.2em] mb-4 ml-1">Комментарий</label>
205
- <textarea
206
- value={bookingNote}
207
- onChange={(e) => setBookingNote(e.target.value)}
208
- placeholder="Детали встречи..."
209
- className="w-full p-4 bg-white/5 border border-white/10 rounded-2xl text-sm focus:ring-2 focus:ring-indigo-500/50 focus:border-indigo-500 outline-none resize-none h-32 text-white placeholder:text-slate-600 transition-all font-medium"
210
- />
211
- </section>
212
  </div>
 
213
 
214
- {/* Col 2: Date Selector */}
 
215
  <section>
216
- <label className="block text-[10px] font-bold text-slate-500 uppercase tracking-[0.2em] mb-4 ml-1 text-center md:text-left">Дата</label>
217
- <div className="flex md:flex-col gap-2 overflow-x-auto md:overflow-y-auto md:max-h-[400px] pb-2 md:pb-0 scrollbar-hide md:scrollbar-thin scrollbar-thumb-white/10 px-1">
218
- {dates.map((date) => (
 
 
 
 
 
 
 
 
 
 
 
 
 
 
219
  <button
220
- key={date.toString()}
221
- onClick={() => setSelectedDate(date)}
222
  className={cn(
223
- "flex flex-row md:flex-col items-center justify-center min-w-[5rem] px-3 py-2 md:py-3 rounded-xl border transition-all duration-300 shrink-0",
224
- isSameDay(date, selectedDate)
225
- ? "border-indigo-500 bg-indigo-500/20 text-indigo-300 shadow-[0_0_15px_rgba(99,102,241,0.15)]"
226
- : "border-white/5 bg-white/5 text-slate-400 hover:border-white/10 hover:bg-white/10"
227
  )}
228
  >
229
- <span className="text-[10px] md:text-xs font-bold uppercase tracking-tighter md:mb-1 mr-2 md:mr-0">{format(date, 'eee', { locale: ru })}</span>
230
- <span className="text-base md:text-xl font-black">{format(date, 'd')}</span>
231
  </button>
232
  ))}
233
  </div>
234
  </section>
 
235
 
236
- {/* Col 3: Time Grid */}
 
 
237
  <section>
238
- <label className="block text-[10px] font-bold text-slate-500 uppercase tracking-[0.2em] mb-4 ml-1 text-center md:text-left">Время</label>
239
- <div className="grid grid-cols-4 md:grid-cols-2 gap-2 max-h-[400px] overflow-y-auto scrollbar-thin scrollbar-thumb-white/10 px-1">
240
- {timeSlots.map(time => (
241
- <button
242
- key={time}
243
- onClick={() => setSelectedTime(time)}
244
- className={cn(
245
- "py-2.5 rounded-xl text-xs font-bold transition-all duration-300 text-center border",
246
- selectedTime === time
247
- ? "bg-indigo-600 border-indigo-500 text-white shadow-[0_0_15px_rgba(99,102,241,0.2)]"
248
- : "bg-white/5 text-slate-400 border-transparent hover:border-white/10 hover:bg-white/10"
249
- )}
250
- >
251
- {time}
252
- </button>
253
- ))}
 
 
 
 
 
 
 
254
  </div>
255
  </section>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
256
  </div>
 
 
 
 
 
 
 
 
 
 
 
257
  </div>
258
 
259
  {/* Footer */}
260
- <div className="px-6 md:px-8 py-4 md:py-6 border-t border-white/5 bg-white/[0.04] shrink-0">
261
  <button
262
  onClick={handleBook}
263
  disabled={!selectedDate || !selectedTime || !selectedService || isSubmitting}
264
- className="w-full py-4 bg-indigo-600 hover:bg-indigo-500 text-white font-black rounded-2xl shadow-xl shadow-indigo-900/40 transition-all flex items-center justify-center gap-3 disabled:opacity-30 disabled:cursor-not-allowed hover:scale-[1.01] active:scale-[0.98] tracking-wider uppercase text-sm"
265
  >
266
  {isSubmitting ? (
267
  <Loader2 className="w-5 h-5 animate-spin" />
268
  ) : (
269
  <Check className="w-5 h-5" />
270
  )}
271
- {isSubmitting ? 'Оформление записи...' : `Назначить на ${selectedTime || '--:--'}`}
272
  </button>
273
  </div>
274
  </motion.div>
 
1
  'use client'
2
 
3
+ import { useState, useEffect, useMemo, useCallback } from 'react'
4
+ import { X, Calendar as CalendarIcon, Clock, Loader2, Check, User, AlertCircle } from 'lucide-react'
5
+ import { format, addDays, startOfToday, isSameDay, getDay } from 'date-fns'
6
  import { ru } from 'date-fns/locale'
7
  import { motion, AnimatePresence } from 'framer-motion'
8
  import { bookingsApi } from '@/lib/api'
 
15
  leadName?: string
16
  }
17
 
18
+ interface Resource {
19
+ id: string
20
+ name: string
21
+ working_hours?: Record<string, { start: string; end: string }>
22
+ }
23
+
24
+ interface Service {
25
+ id: string
26
+ name: string
27
+ duration_minutes: number
28
+ }
29
+
30
+ interface ExistingAppointment {
31
+ id: string
32
+ start_time: string
33
+ status: string
34
+ service_name?: string
35
+ resource_name?: string
36
+ }
37
+
38
+ // Generate time slots from start to end with 30 min interval
39
+ function generateTimeSlots(startTime: string, endTime: string): string[] {
40
+ const slots: string[] = []
41
+ const [startH, startM] = startTime.split(':').map(Number)
42
+ const [endH, endM] = endTime.split(':').map(Number)
43
+
44
+ let current = startH * 60 + startM
45
+ const end = endH * 60 + endM
46
+
47
+ while (current < end) {
48
+ const h = Math.floor(current / 60)
49
+ const m = current % 60
50
+ slots.push(`${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}`)
51
+ current += 30
52
+ }
53
+ return slots
54
+ }
55
+
56
+ // Default working hours (9:00 - 18:00)
57
+ const DEFAULT_START = '09:00'
58
+ const DEFAULT_END = '18:00'
59
+
60
  export function BookingModal({ isOpen, onClose, leadId, leadName }: BookingModalProps) {
 
61
  const [selectedDate, setSelectedDate] = useState<Date>(startOfToday())
62
  const [selectedTime, setSelectedTime] = useState<string | null>(null)
63
+ const [selectedResource, setSelectedResource] = useState<string | null>(null)
64
  const [bookingNote, setBookingNote] = useState('')
65
  const [isSubmitting, setIsSubmitting] = useState(false)
66
  const [isSuccess, setIsSuccess] = useState(false)
67
+
68
+ // Data states
69
+ const [services, setServices] = useState<Service[]>([])
70
+ const [resources, setResources] = useState<Resource[]>([])
71
+ const [existingAppointments, setExistingAppointments] = useState<ExistingAppointment[]>([])
72
  const [selectedService, setSelectedService] = useState<string | null>(null)
73
+ const [isLoading, setIsLoading] = useState(true)
74
 
75
+ // Load data on open
76
  useEffect(() => {
77
+ if (!isOpen) return
78
+
79
+ setIsSuccess(false)
80
+ setIsLoading(true)
81
+
82
+ const loadData = async () => {
83
+ try {
84
+ const [servicesData, resourcesData, appointmentsData] = await Promise.all([
85
+ bookingsApi.getServices(),
86
+ bookingsApi.getResources(),
87
+ bookingsApi.getAppointmentsByLead(leadId)
88
+ ])
89
+
90
+ setServices(servicesData?.length ? servicesData : [{ id: 'default', name: 'Консультация', duration_minutes: 30 }])
91
+ setSelectedService(servicesData?.[0]?.id || 'default')
92
+ setResources(resourcesData || [])
93
+ setExistingAppointments(appointmentsData?.filter((a: ExistingAppointment) => a.status === 'scheduled') || [])
94
+ } catch (e) {
95
+ console.error('Failed to load booking data:', e)
96
  setServices([{ id: 'default', name: 'Консультация', duration_minutes: 30 }])
97
  setSelectedService('default')
98
+ } finally {
99
+ setIsLoading(false)
100
+ }
101
  }
 
102
 
103
+ loadData()
104
+ }, [isOpen, leadId])
105
+
106
+ // Memoized dates (next 14 days)
107
+ const dates = useMemo(() => {
108
+ return Array.from({ length: 14 }).map((_, i) => addDays(startOfToday(), i))
109
+ }, [])
110
+
111
+ // Get selected resource data
112
+ const selectedResourceData = useMemo(() => {
113
+ if (!selectedResource) return null
114
+ return resources.find(r => r.id === selectedResource)
115
+ }, [selectedResource, resources])
116
+
117
+ // Check if date is working day for selected resource
118
+ const isWorkingDay = useCallback((date: Date) => {
119
+ if (!selectedResourceData?.working_hours) return true
120
+ const dayOfWeek = getDay(date)
121
+ // Convert to 0=Monday format (JS uses 0=Sunday)
122
+ const dayKey = String(dayOfWeek === 0 ? 6 : dayOfWeek - 1)
123
+ return !!selectedResourceData.working_hours[dayKey]
124
+ }, [selectedResourceData])
125
+
126
+ // Memoized time slots based on selected date and resource
127
+ const timeSlots = useMemo(() => {
128
+ if (!selectedResourceData?.working_hours) {
129
+ return generateTimeSlots(DEFAULT_START, DEFAULT_END)
130
+ }
131
+
132
+ const dayOfWeek = getDay(selectedDate)
133
+ const dayKey = String(dayOfWeek === 0 ? 6 : dayOfWeek - 1)
134
+ const dayHours = selectedResourceData.working_hours[dayKey]
135
+
136
+ if (!dayHours) return [] // Day off
137
+
138
+ return generateTimeSlots(dayHours.start || DEFAULT_START, dayHours.end || DEFAULT_END)
139
+ }, [selectedDate, selectedResourceData])
140
+
141
+ const handleBook = useCallback(async () => {
142
  if (!selectedDate || !selectedTime || !selectedService) return
143
 
144
  setIsSubmitting(true)
 
154
  await bookingsApi.createAppointment({
155
  lead_id: leadId,
156
  service_id: selectedService === 'default' ? null : selectedService,
157
+ resource_id: selectedResource || null,
158
  start_time: startDateTime.toISOString(),
159
  end_time: endDateTime.toISOString(),
160
  notes: bookingNote,
 
164
  setIsSuccess(true)
165
  } catch (error) {
166
  console.error('Booking error:', error)
 
167
  } finally {
168
  setIsSubmitting(false)
169
  }
170
+ }, [selectedDate, selectedTime, selectedService, selectedResource, services, leadId, bookingNote])
 
 
 
 
 
 
 
 
 
 
171
 
172
  if (!isOpen) return null
173
 
174
+ const hasExistingBooking = existingAppointments.length > 0
175
+
176
  return (
177
  <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
 
178
  <motion.div
179
  initial={{ opacity: 0 }}
180
  animate={{ opacity: 1 }}
 
184
  />
185
 
186
  <motion.div
187
+ initial={{ opacity: 0, scale: 0.95 }}
188
+ animate={{ opacity: 1, scale: 1 }}
189
+ className="relative bg-[#0a0a12] border border-white/10 rounded-2xl w-full max-w-3xl overflow-hidden shadow-2xl flex flex-col max-h-[85vh]"
 
 
 
 
 
190
  >
 
 
 
 
 
 
191
  <AnimatePresence mode="wait">
192
  {isSuccess ? (
193
  <motion.div
194
  key="success"
195
  initial={{ opacity: 0, y: 20 }}
196
  animate={{ opacity: 1, y: 0 }}
197
+ className="p-10 flex flex-col items-center text-center"
198
  >
199
+ <div className="w-16 h-16 rounded-2xl bg-emerald-500/10 border border-emerald-500/30 flex items-center justify-center mb-6">
200
+ <Check className="w-8 h-8 text-emerald-400" />
 
 
 
 
 
 
201
  </div>
202
+ <h3 className="text-xl font-bold text-white mb-2">Запись создана!</h3>
203
+ <p className="text-slate-400 mb-6 text-sm">
204
+ Встреча с <span className="text-white font-medium">{leadName}</span> на{' '}
205
+ <span className="text-indigo-400 font-bold">{selectedTime}</span>{' '}
206
+ {format(selectedDate, 'd MMMM', { locale: ru })}
207
  </p>
 
208
  <button
209
  onClick={onClose}
210
+ className="px-8 py-3 bg-white/10 hover:bg-white/20 text-white font-semibold rounded-xl transition-all"
211
  >
212
+ Закрыть
213
  </button>
214
  </motion.div>
215
+ ) : isLoading ? (
216
+ <div className="p-20 flex items-center justify-center">
217
+ <Loader2 className="w-8 h-8 animate-spin text-indigo-500" />
218
+ </div>
219
  ) : (
220
+ <motion.div key="form" className="flex flex-col h-full">
221
  {/* Header */}
222
+ <div className="px-6 py-4 border-b border-white/5 flex items-center justify-between shrink-0">
223
  <div>
224
+ <h3 className="font-bold text-lg text-white flex items-center gap-2">
225
  <CalendarIcon className="w-5 h-5 text-indigo-400" />
226
  Запись: {leadName || 'Клиент'}
227
  </h3>
228
+ <p className="text-xs text-slate-500 mt-0.5">Выберите параметры визита</p>
229
  </div>
230
+ <button onClick={onClose} className="p-2 hover:bg-white/10 rounded-lg transition-colors text-slate-400 hover:text-white">
231
  <X className="w-5 h-5" />
232
  </button>
233
  </div>
234
 
235
+ {/* Existing booking warning */}
236
+ {hasExistingBooking && (
237
+ <div className="mx-6 mt-4 p-3 bg-amber-500/10 border border-amber-500/30 rounded-xl flex items-start gap-3">
238
+ <AlertCircle className="w-5 h-5 text-amber-400 shrink-0 mt-0.5" />
239
+ <div>
240
+ <p className="text-sm font-medium text-amber-300">Клиент уже записан</p>
241
+ <p className="text-xs text-amber-400/70 mt-0.5">
242
+ {existingAppointments[0].service_name || 'Встреча'} • {' '}
243
+ {format(new Date(existingAppointments[0].start_time), 'd MMM HH:mm', { locale: ru })}
244
+ {existingAppointments[0].resource_name && ` • ${existingAppointments[0].resource_name}`}
245
+ </p>
246
+ </div>
247
+ </div>
248
+ )}
249
+
250
+ {/* Content */}
251
+ <div className="flex-1 overflow-y-auto p-6 space-y-6">
252
+ {/* Services */}
253
+ <section>
254
+ <label className="block text-xs font-semibold text-slate-500 uppercase tracking-wider mb-3">Услуга</label>
255
+ <div className="flex flex-wrap gap-2">
256
+ {services.map(s => (
257
+ <button
258
+ key={s.id}
259
+ onClick={() => setSelectedService(s.id)}
260
+ className={cn(
261
+ "px-4 py-2.5 rounded-xl border text-sm font-medium transition-all",
262
+ selectedService === s.id
263
+ ? "bg-indigo-500/20 border-indigo-500/50 text-white"
264
+ : "bg-white/5 border-white/10 text-slate-400 hover:bg-white/10"
265
+ )}
266
+ >
267
+ {s.name}
268
+ <span className="text-xs text-slate-500 ml-2">{s.duration_minutes} мин</span>
269
+ </button>
270
+ ))}
 
 
 
 
 
 
 
 
 
 
 
 
 
271
  </div>
272
+ </section>
273
 
274
+ {/* Resources */}
275
+ {resources.length > 0 && (
276
  <section>
277
+ <label className="block text-xs font-semibold text-slate-500 uppercase tracking-wider mb-3">
278
+ <User className="w-3.5 h-3.5 inline mr-1" />
279
+ Мастер / Ресурс
280
+ </label>
281
+ <div className="flex flex-wrap gap-2">
282
+ <button
283
+ onClick={() => setSelectedResource(null)}
284
+ className={cn(
285
+ "px-4 py-2.5 rounded-xl border text-sm font-medium transition-all",
286
+ !selectedResource
287
+ ? "bg-indigo-500/20 border-indigo-500/50 text-white"
288
+ : "bg-white/5 border-white/10 text-slate-400 hover:bg-white/10"
289
+ )}
290
+ >
291
+ Любой
292
+ </button>
293
+ {resources.map(r => (
294
  <button
295
+ key={r.id}
296
+ onClick={() => setSelectedResource(r.id)}
297
  className={cn(
298
+ "px-4 py-2.5 rounded-xl border text-sm font-medium transition-all",
299
+ selectedResource === r.id
300
+ ? "bg-indigo-500/20 border-indigo-500/50 text-white"
301
+ : "bg-white/5 border-white/10 text-slate-400 hover:bg-white/10"
302
  )}
303
  >
304
+ {r.name}
 
305
  </button>
306
  ))}
307
  </div>
308
  </section>
309
+ )}
310
 
311
+ {/* Date and Time */}
312
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
313
+ {/* Dates */}
314
  <section>
315
+ <label className="block text-xs font-semibold text-slate-500 uppercase tracking-wider mb-3">Дата</label>
316
+ <div className="flex flex-wrap gap-2 max-h-[200px] overflow-y-auto">
317
+ {dates.map((date) => {
318
+ const isWorking = isWorkingDay(date)
319
+ return (
320
+ <button
321
+ key={date.toString()}
322
+ onClick={() => isWorking && setSelectedDate(date)}
323
+ disabled={!isWorking}
324
+ className={cn(
325
+ "flex flex-col items-center justify-center w-16 py-2 rounded-xl border transition-all",
326
+ isSameDay(date, selectedDate)
327
+ ? "border-indigo-500 bg-indigo-500/20 text-white"
328
+ : isWorking
329
+ ? "border-white/5 bg-white/5 text-slate-400 hover:bg-white/10"
330
+ : "border-white/5 bg-white/[0.02] text-slate-600 cursor-not-allowed opacity-50"
331
+ )}
332
+ >
333
+ <span className="text-[10px] font-semibold uppercase">{format(date, 'eee', { locale: ru })}</span>
334
+ <span className="text-lg font-bold">{format(date, 'd')}</span>
335
+ </button>
336
+ )
337
+ })}
338
  </div>
339
  </section>
340
+
341
+ {/* Times */}
342
+ <section>
343
+ <label className="block text-xs font-semibold text-slate-500 uppercase tracking-wider mb-3">Время</label>
344
+ {timeSlots.length === 0 ? (
345
+ <p className="text-sm text-slate-500">Выходной день</p>
346
+ ) : (
347
+ <div className="grid grid-cols-4 gap-2 max-h-[200px] overflow-y-auto">
348
+ {timeSlots.map(time => (
349
+ <button
350
+ key={time}
351
+ onClick={() => setSelectedTime(time)}
352
+ className={cn(
353
+ "py-2 rounded-xl text-sm font-semibold transition-all border",
354
+ selectedTime === time
355
+ ? "bg-indigo-600 border-indigo-500 text-white"
356
+ : "bg-white/5 text-slate-400 border-transparent hover:bg-white/10"
357
+ )}
358
+ >
359
+ {time}
360
+ </button>
361
+ ))}
362
+ </div>
363
+ )}
364
+ </section>
365
  </div>
366
+
367
+ {/* Notes */}
368
+ <section>
369
+ <label className="block text-xs font-semibold text-slate-500 uppercase tracking-wider mb-3">Комментарий</label>
370
+ <textarea
371
+ value={bookingNote}
372
+ onChange={(e) => setBookingNote(e.target.value)}
373
+ placeholder="Детали встречи..."
374
+ className="w-full p-4 bg-white/5 border border-white/10 rounded-xl text-sm text-white placeholder:text-slate-600 focus:outline-none focus:border-indigo-500/50 resize-none h-20"
375
+ />
376
+ </section>
377
  </div>
378
 
379
  {/* Footer */}
380
+ <div className="px-6 py-4 border-t border-white/5 shrink-0">
381
  <button
382
  onClick={handleBook}
383
  disabled={!selectedDate || !selectedTime || !selectedService || isSubmitting}
384
+ className="w-full py-3.5 bg-indigo-600 hover:bg-indigo-500 text-white font-bold rounded-xl transition-all flex items-center justify-center gap-2 disabled:opacity-30 disabled:cursor-not-allowed"
385
  >
386
  {isSubmitting ? (
387
  <Loader2 className="w-5 h-5 animate-spin" />
388
  ) : (
389
  <Check className="w-5 h-5" />
390
  )}
391
+ {isSubmitting ? 'Создание записи...' : `Записать на ${selectedTime || '--:--'}`}
392
  </button>
393
  </div>
394
  </motion.div>
frontend/lib/api.ts CHANGED
@@ -505,6 +505,11 @@ export const bookingsApi = {
505
  return response.data
506
  },
507
 
 
 
 
 
 
508
  getServices: async () => {
509
  const response = await api.get('/api/v1/bookings/services')
510
  return response.data
 
505
  return response.data
506
  },
507
 
508
+ getAppointmentsByLead: async (leadId: string) => {
509
+ const response = await api.get(`/api/v1/bookings/lead/${leadId}`)
510
+ return response.data
511
+ },
512
+
513
  getServices: async () => {
514
  const response = await api.get('/api/v1/bookings/services')
515
  return response.data